1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
impl CudaExecutor {
/// Execute a tiled GEMM kernel: C = A @ B
///
/// # Arguments
///
/// * `a` - Input matrix A (m x k, row-major)
/// * `b` - Input matrix B (k x n, row-major)
/// * `c` - Output matrix C (m x n, row-major)
/// * `m` - Number of rows in A and C
/// * `n` - Number of columns in B and C
/// * `k` - Number of columns in A / rows in B
///
/// # Errors
///
/// Returns error if kernel execution fails.
pub fn gemm(
&mut self,
a: &[f32],
b: &[f32],
c: &mut [f32],
m: u32,
n: u32,
k: u32,
) -> Result<(), GpuError> {
// Validate sizes
let expected_a = (m * k) as usize;
let expected_b = (k * n) as usize;
let expected_c = (m * n) as usize;
if a.len() != expected_a || b.len() != expected_b || c.len() != expected_c {
return Err(GpuError::InvalidLaunchConfig(format!(
"GEMM size mismatch: A[{}] expected {}, B[{}] expected {}, C[{}] expected {}",
a.len(),
expected_a,
b.len(),
expected_b,
c.len(),
expected_c
)));
}
// Generate PTX for this configuration
// PARITY-003: Enable simpler Gemv (warp-reduce) for M=1 operations
let use_gemv = m == 1;
let (kernel_type, cache_key) = if use_gemv {
(KernelType::Gemv { k, n }, format!("gemv_{}_{}", k, n))
} else {
(
KernelType::GemmTiled {
m,
n,
k,
tile_size: 32,
},
format!("gemm_{}_{}_{}_{}", m, n, k, 32),
)
};
let kernel_name = self.kernels.kernel_name(&kernel_type);
// Load module if not cached
if !self.modules.contains_key(&cache_key) {
let ptx = self.kernels.generate_ptx(&kernel_type);
let module = self.compile_ptx(&ptx)?;
self.modules.insert(cache_key.clone(), module);
}
let module = self
.modules
.get_mut(&cache_key)
.expect("module just inserted");
// Allocate GPU buffers
let buf_a = GpuBuffer::from_host(&self.context, a)?;
let buf_b = GpuBuffer::from_host(&self.context, b)?;
// PARITY-114 FIX: Initialize output buffer with zeros to prevent state accumulation
let c_zeros = vec![0.0f32; expected_c];
let buf_c = GpuBuffer::from_host(&self.context, &c_zeros)?;
// Launch configuration differs for Gemv vs GEMM
// PARITY-003: Enable simpler Gemv with correct config
let config = if use_gemv {
// Simple Gemv: 32 threads (one warp) per block, N blocks
// Each block computes one output element y[block_id]
LaunchConfig::grid_2d(n, 1, 32, 1)
} else {
// GEMM: 2D grid of 32x32 tiles
// PARITY-114 FIX: Grid X is for columns (N), Grid Y is for rows (M)
LaunchConfig::grid_2d(
(n + 31) / 32, // Grid X - columns (N dimension)
(m + 31) / 32, // Grid Y - rows (M dimension)
32, // Block X
32, // Block Y
)
};
// Get raw pointers for kernel args
let mut ptr_a = buf_a.as_ptr();
let mut ptr_b = buf_b.as_ptr();
let mut ptr_c = buf_c.as_ptr();
let mut k_val = k;
let mut n_val = n;
// Launch kernel
// SAFETY: Buffers are valid, config matches kernel expectations
// PARITY-003: Enable GEMV for M=1 operations
// SAFETY: Memory safety ensured by bounds checking and alignment
unsafe {
if use_gemv {
// GEMV kernel: y = B * x where x is A (1×K row as K vector), B is K×N, y is C (1×N as N vector)
// Args: y_ptr, a_ptr (matrix), x_ptr, k_dim, n_dim
self.stream.launch_kernel(
module,
kernel_name,
&config,
&mut [
std::ptr::from_mut(&mut ptr_c) as *mut std::ffi::c_void, // y_ptr (output)
std::ptr::from_mut(&mut ptr_b) as *mut std::ffi::c_void, // a_ptr (K×N matrix)
std::ptr::from_mut(&mut ptr_a) as *mut std::ffi::c_void, // x_ptr (K input vector)
std::ptr::from_mut(&mut k_val) as *mut std::ffi::c_void, // k_dim
std::ptr::from_mut(&mut n_val) as *mut std::ffi::c_void, // n_dim
],
)?;
} else {
// GEMM kernel: C = A × B
// Args: a_ptr, b_ptr, c_ptr, m, n, k
// GH-282: Keep as u32 to match kernel .param .u32 declarations
let mut m_val = m;
let mut n_val_i32 = n;
let mut k_val_i32 = k;
self.stream.launch_kernel(
module,
kernel_name,
&config,
&mut [
std::ptr::from_mut(&mut ptr_a) as *mut std::ffi::c_void,
std::ptr::from_mut(&mut ptr_b) as *mut std::ffi::c_void,
std::ptr::from_mut(&mut ptr_c) as *mut std::ffi::c_void,
std::ptr::from_mut(&mut m_val) as *mut std::ffi::c_void,
std::ptr::from_mut(&mut n_val_i32) as *mut std::ffi::c_void,
std::ptr::from_mut(&mut k_val_i32) as *mut std::ffi::c_void,
],
)?;
}
}
// Synchronize and copy result back
self.stream.synchronize()?;
buf_c.copy_to_host(c)?;
Ok(())
}
/// Execute GEMV using cached weight matrix (PARITY-120: 10x speedup)
///
/// This is the fast path for single-token generation (M=1).
/// The weight matrix must be pre-loaded via `load_weights()`.
///
/// # Arguments
///
/// * `weight_name` - Name of cached weight matrix
/// * `x` - Input vector (K elements)
/// * `y` - Output vector (N elements)
/// * `k` - Input dimension
/// * `n` - Output dimension
///
/// # Errors
///
/// Returns error if weight not cached or kernel execution fails.
pub fn gemv_cached(
&mut self,
weight_name: &str,
x: &[f32],
y: &mut [f32],
k: u32,
n: u32,
) -> Result<(), GpuError> {
// Validate sizes
if x.len() != k as usize {
return Err(GpuError::InvalidLaunchConfig(format!(
"GEMV input size mismatch: got {}, expected {}",
x.len(),
k
)));
}
if y.len() != n as usize {
return Err(GpuError::InvalidLaunchConfig(format!(
"GEMV output size mismatch: got {}, expected {}",
y.len(),
n
)));
}
// Get cached weight buffer
let buf_w = self.weight_cache.get(weight_name).ok_or_else(|| {
GpuError::InvalidLaunchConfig(format!("Weight '{}' not cached on GPU", weight_name))
})?;
// PARITY-003: Use simpler Gemv kernel (32 threads warp-reduce) instead of CoalescedGemv
let kernel_type = KernelType::Gemv { k, n };
let cache_key = format!("gemv_simple_{}_{}", k, n);
let kernel_name = self.kernels.kernel_name(&kernel_type);
// Load module if not cached
if !self.modules.contains_key(&cache_key) {
let ptx = self.kernels.generate_ptx(&kernel_type);
let module = self.compile_ptx(&ptx)?;
self.modules.insert(cache_key.clone(), module);
}
let module = self
.modules
.get_mut(&cache_key)
.expect("module just inserted");
// Allocate only input/output buffers (weight stays on GPU!)
let buf_x = GpuBuffer::from_host(&self.context, x)?;
let y_zeros = vec![0.0f32; n as usize];
let buf_y = GpuBuffer::from_host(&self.context, &y_zeros)?;
// PARITY-003: Simple Gemv config - 32 threads (one warp) per block, N blocks
let config = LaunchConfig::grid_2d(n, 1, 32, 1);
// Get raw pointers
let mut ptr_y = buf_y.as_ptr();
let mut ptr_w = buf_w.as_ptr();
let mut ptr_x = buf_x.as_ptr();
let mut k_val = k;
let mut n_val = n;
// Launch kernel: y = W * x
// SAFETY: Buffers are valid, config matches kernel expectations
unsafe {
self.stream.launch_kernel(
module,
kernel_name,
&config,
&mut [
std::ptr::from_mut(&mut ptr_y) as *mut std::ffi::c_void, // y_ptr (output)
std::ptr::from_mut(&mut ptr_w) as *mut std::ffi::c_void, // w_ptr (K×N matrix, CACHED)
std::ptr::from_mut(&mut ptr_x) as *mut std::ffi::c_void, // x_ptr (K input vector)
std::ptr::from_mut(&mut k_val) as *mut std::ffi::c_void, // k_dim
std::ptr::from_mut(&mut n_val) as *mut std::ffi::c_void, // n_dim
],
)?;
}
// Synchronize and copy result back
self.stream.synchronize()?;
buf_y.copy_to_host(y)?;
Ok(())
}
/// Execute optimized GEMM kernel (IMP-900a)
///
/// Uses larger tile sizes and register blocking for better performance.
/// Provides ~2-3x improvement over naive tiled GEMM.
///
/// # Arguments
///
/// * `a` - Input matrix A (m × k)
/// * `b` - Input matrix B (k × n)
/// * `c` - Output matrix C (m × n)
/// * `m` - Number of rows in A and C
/// * `n` - Number of columns in B and C
/// * `k` - Number of columns in A / rows in B
/// * `tile_size` - Tile size for shared memory (32 or 64)
///
/// # Errors
///
/// Returns error if kernel execution fails.
#[allow(clippy::too_many_arguments)]
pub fn gemm_optimized(
&mut self,
a: &[f32],
b: &[f32],
c: &mut [f32],
m: u32,
n: u32,
k: u32,
tile_size: u32,
) -> Result<(), GpuError> {
// Validate sizes
let expected_a = (m * k) as usize;
let expected_b = (k * n) as usize;
let expected_c = (m * n) as usize;
if a.len() != expected_a || b.len() != expected_b || c.len() != expected_c {
return Err(GpuError::InvalidLaunchConfig(format!(
"GEMM size mismatch: A[{}] expected {}, B[{}] expected {}, C[{}] expected {}",
a.len(),
expected_a,
b.len(),
expected_b,
c.len(),
expected_c
)));
}
// IMP-900a: Use optimized kernel with larger tiles
let reg_block = if tile_size >= 64 { 8 } else { 4 };
let kernel_type = KernelType::GemmOptimized {
m,
n,
k,
tile_size,
reg_block,
};
let kernel_name = self.kernels.kernel_name(&kernel_type);
let cache_key = format!("gemm_opt_{}_{}_{}_{}", m, n, k, tile_size);
// Load module if not cached
if !self.modules.contains_key(&cache_key) {
let ptx = self.kernels.generate_ptx(&kernel_type);
let module = self.compile_ptx(&ptx)?;
self.modules.insert(cache_key.clone(), module);
}
let module = self
.modules
.get_mut(&cache_key)
.expect("module just inserted");
// Allocate GPU buffers
let buf_a = GpuBuffer::from_host(&self.context, a)?;
let buf_b = GpuBuffer::from_host(&self.context, b)?;
// PARITY-114 FIX: Initialize output buffer with zeros to prevent state accumulation
let c_zeros = vec![0.0f32; expected_c];
let buf_c = GpuBuffer::from_host(&self.context, &c_zeros)?;
// Launch configuration with optimized tile size
// PARITY-114 FIX: Grid X is for columns (N), Grid Y is for rows (M)
let config = LaunchConfig::grid_2d(
(n + tile_size - 1) / tile_size, // Grid X - columns (N dimension)
(m + tile_size - 1) / tile_size, // Grid Y - rows (M dimension)
tile_size, // Block X
tile_size, // Block Y
);
// Get raw pointers for kernel args
let mut ptr_a = buf_a.as_ptr();
let mut ptr_b = buf_b.as_ptr();
let mut ptr_c = buf_c.as_ptr();
// GH-282: Keep as u32 to match kernel .param .u32 declarations
let mut m_val = m;
let mut n_val = n;
let mut k_val = k;
// Launch kernel
// SAFETY: Buffers are valid, config matches kernel expectations
unsafe {
self.stream.launch_kernel(
module,
kernel_name,
&config,
&mut [
std::ptr::from_mut(&mut ptr_a) as *mut std::ffi::c_void,
std::ptr::from_mut(&mut ptr_b) as *mut std::ffi::c_void,
std::ptr::from_mut(&mut ptr_c) as *mut std::ffi::c_void,
std::ptr::from_mut(&mut m_val) as *mut std::ffi::c_void,
std::ptr::from_mut(&mut n_val) as *mut std::ffi::c_void,
std::ptr::from_mut(&mut k_val) as *mut std::ffi::c_void,
],
)?;
}
// Synchronize and copy result back
self.stream.synchronize()?;
buf_c.copy_to_host(c)?;
Ok(())
}
}