aprender-serve 0.50.0

Pure Rust ML inference engine built from scratch - model serving for GGUF and safetensors
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507

#[cfg(test)]
#[cfg(feature = "cuda")]
mod tests {
    use super::*;
    use crate::cuda::executor::test_fixtures::{
        generate_q4_0_weights, generate_q5_0_weights, generate_q8_0_weights,
    };

    /// Helper to create CudaExecutor for tests
    fn create_executor() -> Option<CudaExecutor> {
        CudaExecutor::new(0).ok()
    }

    // ========================================================================
    // Q8_0 GEMV Tests
    // ========================================================================

    #[test]
    fn test_q8_0_gemv_into_basic() {
        let Some(mut exec) = create_executor() else {
            return;
        };

        // K=256, N=64: 64 output rows, 8 blocks per row (32 elements/block)
        let k = 256u32;
        let n = 64u32;
        let blocks = (n as usize) * (k as usize / 32);
        let weights = generate_q8_0_weights(blocks);

        // Upload weights to GPU
        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        let weight_ptr = weight_buf.as_ptr();

        // Create input/output buffers
        let input: Vec<f32> = (0..k as usize).map(|i| (i as f32) * 0.01).collect();
        let output = vec![0.0f32; n as usize];
        let input_buf = GpuBuffer::from_host(&exec.context, &input).unwrap();
        let output_buf = GpuBuffer::from_host(&exec.context, &output).unwrap();

        // Execute (may fail on PTX generation but exercises path)
        let result = exec.q8_0_gemv_into(weight_ptr, &input_buf, &output_buf, n, k);
        let _ = result;
    }

    #[test]
    fn test_q8_0_gemv_into_large() {
        let Some(mut exec) = create_executor() else {
            return;
        };

        let k = 512u32;
        let n = 128u32;
        let blocks = (n as usize) * (k as usize / 32);
        let weights = generate_q8_0_weights(blocks);

        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        let input: Vec<f32> = vec![0.5f32; k as usize];
        let output = vec![0.0f32; n as usize];
        let input_buf = GpuBuffer::from_host(&exec.context, &input).unwrap();
        let output_buf = GpuBuffer::from_host(&exec.context, &output).unwrap();

        let result = exec.q8_0_gemv_into(weight_buf.as_ptr(), &input_buf, &output_buf, n, k);
        let _ = result;
    }

    // ========================================================================
    // Q5_0 GEMV Tests
    // ========================================================================

    #[test]
    fn test_q5_0_gemv_into_basic() {
        let Some(mut exec) = create_executor() else {
            return;
        };

        let k = 256u32;
        let n = 64u32;
        let blocks = (n as usize) * (k as usize / 32);
        let weights = generate_q5_0_weights(blocks);

        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        let input: Vec<f32> = (0..k as usize).map(|i| (i as f32) * 0.01).collect();
        let output = vec![0.0f32; n as usize];
        let input_buf = GpuBuffer::from_host(&exec.context, &input).unwrap();
        let output_buf = GpuBuffer::from_host(&exec.context, &output).unwrap();

        let result = exec.q5_0_gemv_into(weight_buf.as_ptr(), &input_buf, &output_buf, n, k);
        let _ = result;
    }

    #[test]
    fn test_q5_0_gemv_into_large() {
        let Some(mut exec) = create_executor() else {
            return;
        };

        let k = 512u32;
        let n = 128u32;
        let blocks = (n as usize) * (k as usize / 32);
        let weights = generate_q5_0_weights(blocks);

        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        let input: Vec<f32> = vec![0.5f32; k as usize];
        let output = vec![0.0f32; n as usize];
        let input_buf = GpuBuffer::from_host(&exec.context, &input).unwrap();
        let output_buf = GpuBuffer::from_host(&exec.context, &output).unwrap();

        let result = exec.q5_0_gemv_into(weight_buf.as_ptr(), &input_buf, &output_buf, n, k);
        let _ = result;
    }

    // ========================================================================
    // Q4_0 GEMV Tests
    // ========================================================================

    #[test]
    fn test_q4_0_gemv_into_basic() {
        let Some(mut exec) = create_executor() else {
            return;
        };

        let k = 256u32;
        let n = 64u32;
        let blocks = (n as usize) * (k as usize / 32);
        let weights = generate_q4_0_weights(blocks);

        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        let input: Vec<f32> = (0..k as usize).map(|i| (i as f32) * 0.01).collect();
        let output = vec![0.0f32; n as usize];
        let input_buf = GpuBuffer::from_host(&exec.context, &input).unwrap();
        let output_buf = GpuBuffer::from_host(&exec.context, &output).unwrap();

        let result = exec.q4_0_gemv_into(weight_buf.as_ptr(), &input_buf, &output_buf, n, k);
        let _ = result;
    }

    #[test]
    fn test_q4_0_gemv_into_single_row() {
        let Some(mut exec) = create_executor() else {
            return;
        };

        let k = 256u32;
        let n = 1u32;
        let blocks = k as usize / 32;
        let weights = generate_q4_0_weights(blocks);

        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        let input: Vec<f32> = vec![1.0f32; k as usize];
        let output = vec![0.0f32; n as usize];
        let input_buf = GpuBuffer::from_host(&exec.context, &input).unwrap();
        let output_buf = GpuBuffer::from_host(&exec.context, &output).unwrap();

        let result = exec.q4_0_gemv_into(weight_buf.as_ptr(), &input_buf, &output_buf, n, k);
        let _ = result;
    }

    // ========================================================================
    // Q4_1 GEMV Tests
    // ========================================================================

    #[test]
    fn test_q4_1_gemv_into_basic() {
        let Some(mut exec) = create_executor() else {
            return;
        };

        // Q4_1 has same block count as Q4_0 but 20 bytes per block instead of 18
        let k = 256u32;
        let n = 64u32;
        let blocks = (n as usize) * (k as usize / 32);
        // Use Q4_0 weights (18 bytes/block), Q4_1 expects 20 bytes/block
        // The kernel will interpret incorrectly, but we're testing the path
        let weights = generate_q4_0_weights(blocks);

        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        let input: Vec<f32> = (0..k as usize).map(|i| (i as f32) * 0.01).collect();
        let output = vec![0.0f32; n as usize];
        let input_buf = GpuBuffer::from_host(&exec.context, &input).unwrap();
        let output_buf = GpuBuffer::from_host(&exec.context, &output).unwrap();

        let result = exec.q4_1_gemv_into(weight_buf.as_ptr(), &input_buf, &output_buf, n, k);
        let _ = result;
    }

    // ========================================================================
    // Q5_K GEMV Tests
    // ========================================================================

    #[test]
    fn test_q5k_gemv_into_basic() {
        let Some(mut exec) = create_executor() else {
            return;
        };

        // Q5_K: 176 bytes per 256 elements (super-block format)
        let k = 256u32;
        let n = 64u32;
        // Q5_K needs k to be multiple of 256
        let superblocks = (n as usize) * (k as usize / 256);
        // Simulate Q5K weight data
        let weights = vec![0u8; superblocks * 176];

        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        let input: Vec<f32> = (0..k as usize).map(|i| (i as f32) * 0.01).collect();
        let output = vec![0.0f32; n as usize];
        let input_buf = GpuBuffer::from_host(&exec.context, &input).unwrap();
        let output_buf = GpuBuffer::from_host(&exec.context, &output).unwrap();

        let result = exec.q5k_gemv_into(weight_buf.as_ptr(), &input_buf, &output_buf, n, k);
        let _ = result;
    }

    // ========================================================================
    // Q6_K GEMV Tests
    // ========================================================================

    #[test]
    fn test_q6k_gemv_into_basic() {
        let Some(mut exec) = create_executor() else {
            return;
        };

        // Q6_K: 210 bytes per 256 elements
        let k = 256u32;
        let n = 64u32;

        // The HwDp4a Q6K variant (default on sm_75+) quantizes activations into
        // workspace.q8_activation_buf and would otherwise panic; size it for k.
        exec.init_workspace(k as usize, k as usize)
            .expect("init_workspace");

        let superblocks = (n as usize) * (k as usize / 256);
        let weights = vec![0u8; superblocks * 210];

        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        let input: Vec<f32> = (0..k as usize).map(|i| (i as f32) * 0.01).collect();
        let output = vec![0.0f32; n as usize];
        let input_buf = GpuBuffer::from_host(&exec.context, &input).unwrap();
        let output_buf = GpuBuffer::from_host(&exec.context, &output).unwrap();

        let result = exec.q6k_gemv_into(weight_buf.as_ptr(), &input_buf, &output_buf, n, k);
        let _ = result;
    }

    #[test]
    fn test_coalesced_q6k_gemv_into_basic() {
        let Some(mut exec) = create_executor() else {
            return;
        };

        let k = 256u32;
        let n = 64u32;
        let superblocks = (n as usize) * (k as usize / 256);
        let weights = vec![0u8; superblocks * 210];

        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        let input: Vec<f32> = (0..k as usize).map(|i| (i as f32) * 0.01).collect();
        let output = vec![0.0f32; n as usize];
        let input_buf = GpuBuffer::from_host(&exec.context, &input).unwrap();
        let output_buf = GpuBuffer::from_host(&exec.context, &output).unwrap();

        let result =
            exec.coalesced_q6k_gemv_into(weight_buf.as_ptr(), &input_buf, &output_buf, n, k);
        let _ = result;
    }

    // ========================================================================
    // Batched Q6K GEMV Tests
    // ========================================================================

    #[test]
    fn test_batched_q6k_gemv_into_basic() {
        let Some(mut exec) = create_executor() else {
            return;
        };

        let m = 4u32; // batch size
        let k = 256u32;
        let n = 64u32;
        let superblocks = (n as usize) * (k as usize / 256);
        let weights = vec![0u8; superblocks * 210];

        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        // Batched input: m * k elements
        let input: Vec<f32> = (0..(m * k) as usize).map(|i| (i as f32) * 0.001).collect();
        // Batched output: m * n elements
        let output = vec![0.0f32; (m * n) as usize];
        let input_buf = GpuBuffer::from_host(&exec.context, &input).unwrap();
        let output_buf = GpuBuffer::from_host(&exec.context, &output).unwrap();

        let result =
            exec.batched_q6k_gemv_into(weight_buf.as_ptr(), &input_buf, &output_buf, m, n, k);
        let _ = result;
    }

    #[test]
    fn test_batched_q6k_gemv_into_m8() {
        let Some(mut exec) = create_executor() else {
            return;
        };

        let m = 8u32;
        let k = 256u32;
        let n = 32u32;
        let superblocks = (n as usize) * (k as usize / 256);
        let weights = vec![0u8; superblocks * 210];

        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        let input: Vec<f32> = vec![0.5f32; (m * k) as usize];
        let output = vec![0.0f32; (m * n) as usize];
        let input_buf = GpuBuffer::from_host(&exec.context, &input).unwrap();
        let output_buf = GpuBuffer::from_host(&exec.context, &output).unwrap();

        let result =
            exec.batched_q6k_gemv_into(weight_buf.as_ptr(), &input_buf, &output_buf, m, n, k);
        let _ = result;
    }

    // ========================================================================
    // PMAT-782: Legacy-quant GPU↔CPU parity (GGML interleaved nibble layout)
    //
    // GGML packs Q4_0/Q4_1/Q5_0 nibbles INTERLEAVED: byte j (0..16) holds value
    // j in its LOW nibble and value j+16 in its HIGH nibble (see
    // dequantize_row_q5_0 in ggml-quants.c). The GPU kernels previously assumed
    // CONSECUTIVE packing (byte = tid/2, low/high = tid&1), so every value index
    // ≥1 mapped to the wrong nibble → garbage logits. These tests build real
    // GGML-layout blocks and assert the GPU GEMV matches the CPU dequant
    // reference that already produces coherent output.
    // ========================================================================

    /// Build a single-row GGML-spec Q4_0 weight: `n=1`, `k` elements.
    /// Returns (raw_bytes, dequantized_f32_row).
    fn ggml_q4_0_row(k: usize, seed: u32) -> (Vec<u8>, Vec<f32>) {
        use half::f16;
        let nb = k / 32;
        let mut data = Vec::with_capacity(nb * 18);
        for b in 0..nb {
            let d = 0.05 * (b as f32 + 1.0);
            data.extend_from_slice(&f16::from_f32(d).to_le_bytes());
            // qs[j] low nibble = value j, high nibble = value j+16
            for j in 0..16 {
                let v_lo = ((b as u32 * 7 + j as u32 * 3 + seed) % 16) as u8;
                let v_hi = ((b as u32 * 11 + j as u32 * 5 + seed + 1) % 16) as u8;
                data.push(v_lo | (v_hi << 4));
            }
        }
        let row = crate::quantize::dequantize_q4_0(&data).unwrap();
        (data, row)
    }

    /// Build a single-row GGML-spec Q4_1 weight: `n=1`, `k` elements.
    fn ggml_q4_1_row(k: usize, seed: u32) -> (Vec<u8>, Vec<f32>) {
        use half::f16;
        let nb = k / 32;
        let mut data = Vec::with_capacity(nb * 20);
        for b in 0..nb {
            let d = 0.05 * (b as f32 + 1.0);
            let m = -0.3 * (b as f32 + 1.0);
            data.extend_from_slice(&f16::from_f32(d).to_le_bytes());
            data.extend_from_slice(&f16::from_f32(m).to_le_bytes());
            // qs[j] low nibble = value j, high nibble = value j+16
            for j in 0..16 {
                let v_lo = ((b as u32 * 7 + j as u32 * 3 + seed) % 16) as u8;
                let v_hi = ((b as u32 * 11 + j as u32 * 5 + seed + 1) % 16) as u8;
                data.push(v_lo | (v_hi << 4));
            }
        }
        let row = crate::quantize::dequantize_q4_1(&data).unwrap();
        (data, row)
    }

    /// Build a single-row GGML-spec Q5_0 weight: `n=1`, `k` elements.
    fn ggml_q5_0_row(k: usize, seed: u32) -> (Vec<u8>, Vec<f32>) {
        use half::f16;
        let nb = k / 32;
        let mut data = Vec::with_capacity(nb * 22);
        for b in 0..nb {
            let d = 0.05 * (b as f32 + 1.0);
            data.extend_from_slice(&f16::from_f32(d).to_le_bytes());
            // qh: bit v = high (5th) bit of value v
            let qh: u32 = 0x1357_9BDF_u32.wrapping_mul(b as u32 + 1).wrapping_add(seed);
            data.extend_from_slice(&qh.to_le_bytes());
            for j in 0..16 {
                let v_lo = ((b as u32 * 7 + j as u32 * 3 + seed) % 16) as u8;
                let v_hi = ((b as u32 * 11 + j as u32 * 5 + seed + 1) % 16) as u8;
                data.push(v_lo | (v_hi << 4));
            }
        }
        let row = crate::quantize::dequantize_q5_0(&data).unwrap();
        (data, row)
    }

    fn cpu_dot(row: &[f32], x: &[f32]) -> f32 {
        row.iter().zip(x.iter()).map(|(w, v)| w * v).sum()
    }

    #[test]
    fn test_q4_0_gemv_matches_cpu_ggml_layout() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        let k = 256usize;
        let n = 4usize;
        let x: Vec<f32> = (0..k).map(|i| (i as f32) * 0.013 - 1.0).collect();
        // Build n independent rows, concatenate weights row-major.
        let mut weights = Vec::new();
        let mut expected = vec![0.0f32; n];
        for (r, exp) in expected.iter_mut().enumerate() {
            let (w, row) = ggml_q4_0_row(k, r as u32 + 1);
            weights.extend_from_slice(&w);
            *exp = cpu_dot(&row, &x);
        }
        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        let input_buf = GpuBuffer::from_host(&exec.context, &x).unwrap();
        let out = vec![0.0f32; n];
        let output_buf = GpuBuffer::from_host(&exec.context, &out).unwrap();
        exec.q4_0_gemv_into(weight_buf.as_ptr(), &input_buf, &output_buf, n as u32, k as u32)
            .expect("q4_0 gemv");
        exec.stream.synchronize().unwrap();
        let mut got = vec![0.0f32; n];
        output_buf.copy_to_host(&mut got).unwrap();
        for r in 0..n {
            let diff = (got[r] - expected[r]).abs();
            let tol = 1e-2 * expected[r].abs().max(1.0);
            assert!(
                diff <= tol,
                "Q4_0 row {r}: GPU {} vs CPU {} (diff {diff} > tol {tol})",
                got[r],
                expected[r]
            );
        }
    }

    #[test]
    fn test_q4_1_gemv_matches_cpu_ggml_layout() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        let k = 256usize;
        let n = 4usize;
        let x: Vec<f32> = (0..k).map(|i| (i as f32) * 0.009 - 0.5).collect();
        let mut weights = Vec::new();
        let mut expected = vec![0.0f32; n];
        for (r, exp) in expected.iter_mut().enumerate() {
            let (w, row) = ggml_q4_1_row(k, r as u32 + 2);
            weights.extend_from_slice(&w);
            *exp = cpu_dot(&row, &x);
        }
        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        let input_buf = GpuBuffer::from_host(&exec.context, &x).unwrap();
        let out = vec![0.0f32; n];
        let output_buf = GpuBuffer::from_host(&exec.context, &out).unwrap();
        exec.q4_1_gemv_into(weight_buf.as_ptr(), &input_buf, &output_buf, n as u32, k as u32)
            .expect("q4_1 gemv");
        exec.stream.synchronize().unwrap();
        let mut got = vec![0.0f32; n];
        output_buf.copy_to_host(&mut got).unwrap();
        for r in 0..n {
            let diff = (got[r] - expected[r]).abs();
            let tol = 1e-2 * expected[r].abs().max(1.0);
            assert!(
                diff <= tol,
                "Q4_1 row {r}: GPU {} vs CPU {} (diff {diff} > tol {tol})",
                got[r],
                expected[r]
            );
        }
    }

    #[test]
    fn test_q5_0_gemv_matches_cpu_ggml_layout() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        let k = 256usize;
        let n = 4usize;
        let x: Vec<f32> = (0..k).map(|i| (i as f32) * 0.011 - 0.7).collect();
        let mut weights = Vec::new();
        let mut expected = vec![0.0f32; n];
        for (r, exp) in expected.iter_mut().enumerate() {
            let (w, row) = ggml_q5_0_row(k, r as u32 + 3);
            weights.extend_from_slice(&w);
            *exp = cpu_dot(&row, &x);
        }
        let weight_buf = GpuBuffer::from_host(&exec.context, &weights).unwrap();
        let input_buf = GpuBuffer::from_host(&exec.context, &x).unwrap();
        let out = vec![0.0f32; n];
        let output_buf = GpuBuffer::from_host(&exec.context, &out).unwrap();
        exec.q5_0_gemv_into(weight_buf.as_ptr(), &input_buf, &output_buf, n as u32, k as u32)
            .expect("q5_0 gemv");
        exec.stream.synchronize().unwrap();
        let mut got = vec![0.0f32; n];
        output_buf.copy_to_host(&mut got).unwrap();
        for r in 0..n {
            let diff = (got[r] - expected[r]).abs();
            let tol = 1e-2 * expected[r].abs().max(1.0);
            assert!(
                diff <= tol,
                "Q5_0 row {r}: GPU {} vs CPU {} (diff {diff} > tol {tol})",
                got[r],
                expected[r]
            );
        }
    }
}