aprender-serve 0.65.1

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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593

    fn create_executor() -> Option<CudaExecutor> {
        CudaExecutor::new(0).ok()
    }

    // ========================================================================
    // KV Cache Initialization Tests
    // ========================================================================

    #[test]
    fn test_init_kv_cache_gpu() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        let n_layers = 4usize;
        let n_kv_heads = 4usize;
        let head_dim = 64usize;
        let max_seq_len = 1024usize;

        let result =
            exec.init_kv_cache_gpu(n_layers, n_kv_heads, head_dim, max_seq_len, n_kv_heads * 4);
        assert!(result.is_ok());

        // Verify cache is initialized
        assert!(exec.has_kv_cache_gpu());
        assert!(exec.kv_cache_max_len > 0);
    }

    #[test]
    fn test_init_batched_kv_cache_gpu_requires_kv_cache() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        // Without init_kv_cache_gpu first, should fail
        let result = exec.init_batched_kv_cache_gpu(4, 8);
        assert!(result.is_err());
    }

    #[test]
    fn test_init_batched_kv_cache_gpu_after_kv_init() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        // First init regular KV cache
        exec.init_kv_cache_gpu(4, 4, 64, 1024, 16).unwrap();

        // Then init batched cache
        let result = exec.init_batched_kv_cache_gpu(4, 8);
        assert!(result.is_ok());

        // Verify batched cache is initialized
        assert_eq!(exec.batched_kv_allocated_batch, 8);
    }

    // ========================================================================
    // KV Cache State Tests
    // ========================================================================

    #[test]
    fn test_has_kv_cache_gpu_initial_false() {
        let Some(exec) = create_executor() else {
            return;
        };
        assert!(!exec.has_kv_cache_gpu());
    }

    #[test]
    fn test_kv_cache_len_uninitialized() {
        let Some(exec) = create_executor() else {
            return;
        };
        // Uninitialized layer should return 0
        assert_eq!(exec.kv_cache_len(0), 0);
        assert_eq!(exec.kv_cache_len(99), 0);
    }

    #[test]
    fn test_kv_cache_len_after_init() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        exec.init_kv_cache_gpu(4, 4, 64, 1024, 16).unwrap();

        // Initially should be 0 for each layer
        assert_eq!(exec.kv_cache_len(0), 0);
        assert_eq!(exec.kv_cache_len(1), 0);
    }

    // ========================================================================
    // KV Cache Reset Tests
    // ========================================================================

    #[test]
    fn test_reset_kv_cache_gpu() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        exec.init_kv_cache_gpu(4, 4, 64, 1024, 16).unwrap();

        // Reset should succeed
        exec.reset_kv_cache_gpu();

        // All lengths should be 0
        assert_eq!(exec.kv_cache_len(0), 0);
    }

    #[test]
    fn test_reset_batched_kv_cache_gpu() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        // Init regular cache first
        exec.init_kv_cache_gpu(4, 4, 64, 1024, 16).unwrap();
        exec.init_batched_kv_cache_gpu(4, 8).unwrap();

        exec.reset_batched_kv_cache_gpu();

        // Batched lengths should all be 0
        assert!(exec.batched_kv_lengths.iter().all(|&len| len == 0));
    }

    // ========================================================================
    // RoPE Configuration Tests
    // ========================================================================

    #[test]
    fn test_set_rope_theta() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        exec.set_rope_theta(10000.0);
        assert_eq!(exec.rope_theta, 10000.0);

        exec.set_rope_theta(500000.0); // Longer context
        assert_eq!(exec.rope_theta, 500000.0);
    }

    #[test]
    fn test_set_rope_type() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        exec.set_rope_type(0); // NORM
        assert_eq!(exec.rope_type, 0);

        exec.set_rope_type(2); // NEOX (GPT-NeoX style)
        assert_eq!(exec.rope_type, 2);
    }

    // ========================================================================
    // KV Cache Rollback Tests
    // ========================================================================

    #[test]
    fn test_rollback_kv_cache_gpu() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        exec.init_kv_cache_gpu(4, 4, 64, 1024, 16).unwrap();

        // Rollback to position 5
        exec.rollback_kv_cache_gpu(5);

        // All layers should be rolled back to 5
        for layer in 0..4 {
            assert!(exec.kv_cache_len(layer) <= 5);
        }
    }

    #[test]
    fn test_rollback_to_zero() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        exec.init_kv_cache_gpu(4, 4, 64, 1024, 16).unwrap();

        // Rollback to 0 should be equivalent to reset
        exec.rollback_kv_cache_gpu(0);

        assert_eq!(exec.kv_cache_len(0), 0);
    }

    // ========================================================================
    // Flash Attention Cached Tests
    // ========================================================================

    #[test]
    fn test_flash_attention_cached_requires_kv_cache() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        // Without KV cache initialization
        let q = vec![1.0f32; 256];
        let k = vec![1.0f32; 256];
        let v = vec![1.0f32; 256];
        let mut output = vec![0.0f32; 256];

        // flash_attention_cached takes (layer_idx, q, current_k, current_v, output)
        let result = exec.flash_attention_cached(0, &q, &k, &v, &mut output);
        assert!(result.is_err());
    }

    #[test]
    fn test_incremental_attention_gpu_requires_kv_cache() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        let q = vec![1.0f32; 256];
        let k = vec![1.0f32; 256];
        let v = vec![1.0f32; 256];
        let mut output = vec![0.0f32; 256];

        // incremental_attention_gpu takes (layer_idx, q, current_k, current_v, output)
        let result = exec.incremental_attention_gpu(0, &q, &k, &v, &mut output);
        assert!(result.is_err());
    }

    // ========================================================================
    // KV Cache Memory Calculation Tests
    // ========================================================================

    #[test]
    fn test_kv_cache_memory_calculation() {
        // Test memory calculation for KV cache
        let n_layers = 32usize;
        let n_kv_heads = 8usize;
        let head_dim = 128usize;
        let max_seq_len = 4096usize;

        let per_layer_bytes = 2 * max_seq_len * n_kv_heads * head_dim * 4; // K + V, f32
        let total_bytes = n_layers * per_layer_bytes;

        // Verify it's a reasonable size (1-10 GB range for large models)
        assert!(total_bytes > 1_000_000_000); // > 1GB
        assert!(total_bytes < 20_000_000_000); // < 20GB
    }

    #[test]
    fn test_gqa_kv_cache_savings() {
        // Test memory savings from GQA (fewer KV heads)
        let n_layers = 32usize;
        let head_dim = 128usize;
        let max_seq_len = 4096usize;

        // MHA: 32 KV heads
        let mha_per_layer = 2 * max_seq_len * 32 * head_dim * 4;
        let mha_total = n_layers * mha_per_layer;

        // GQA: 8 KV heads (4x savings)
        let gqa_per_layer = 2 * max_seq_len * 8 * head_dim * 4;
        let gqa_total = n_layers * gqa_per_layer;

        assert_eq!(mha_total / gqa_total, 4);
    }

    // ========================================================================
    // QWEN-007: Q8 KV Cache Tests
    // ========================================================================

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

        // Initialize Q8 KV cache
        let result = exec.init_kv_cache_q8_gpu(
            4,   // num_layers
            8,   // num_heads
            4,   // num_kv_heads (GQA)
            128, // head_dim (divisible by 32)
            512, // max_len
        );
        assert!(result.is_ok(), "Q8 KV cache init failed: {:?}", result);
        assert!(exec.is_kv_cache_q8_enabled());
    }

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

        // head_dim not divisible by 32 should fail
        let result = exec.init_kv_cache_q8_gpu(4, 8, 4, 100, 512);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("divisible by 32"));
        }
    }

    #[test]
    fn test_q8_kv_cache_memory_calculation() {
        // Test Q8 memory calculation vs FP32
        let n_layers = 32usize;
        let n_kv_heads = 8usize;
        let head_dim = 128usize;
        let max_seq_len = 4096usize;

        // FP32: 4 bytes per value
        let fp32_bytes = n_layers * 2 * n_kv_heads * max_seq_len * head_dim * 4;

        // Q8: 1 byte per value + 4 bytes per 32 values (scale)
        let q8_values = n_layers * 2 * n_kv_heads * max_seq_len * head_dim * 1;
        let q8_scales = n_layers * 2 * n_kv_heads * max_seq_len * (head_dim / 32) * 4;
        let q8_bytes = q8_values + q8_scales;

        // Q8 should be ~4x smaller (actually 4x / (1 + 1/8) ≈ 3.56x due to scales)
        let reduction = fp32_bytes as f64 / q8_bytes as f64;
        assert!(
            reduction > 3.5,
            "Expected >3.5x reduction, got {:.2}x",
            reduction
        );
        assert!(
            reduction < 4.0,
            "Expected <4x reduction, got {:.2}x",
            reduction
        );
    }

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

        // Initialize Q8 KV cache
        exec.init_kv_cache_q8_gpu(4, 8, 4, 128, 512).unwrap();

        let q8_mem = exec.kv_cache_q8_memory_bytes();
        let fp32_equiv = exec.kv_cache_fp32_equivalent_bytes();

        assert!(q8_mem > 0, "Q8 memory should be > 0");
        assert!(fp32_equiv > q8_mem, "FP32 equivalent should be > Q8 memory");

        let reduction = fp32_equiv as f64 / q8_mem as f64;
        assert!(
            reduction > 3.5,
            "Expected >3.5x reduction, got {:.2}x",
            reduction
        );
    }

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

        let num_kv_heads = 4;
        let head_dim = 64; // Divisible by 32
        let max_len = 16;

        // Initialize Q8 KV cache
        exec.init_kv_cache_q8_gpu(2, 8, num_kv_heads, head_dim, max_len)
            .unwrap();

        // Create test K/V vectors with known values
        let size = num_kv_heads * head_dim;
        let k: Vec<f32> = (0..size).map(|i| (i as f32) * 0.01).collect();
        let v: Vec<f32> = (0..size).map(|i| (i as f32) * -0.01).collect();

        // Write to position 0
        exec.write_kv_q8(0, 0, &k, &v).unwrap();

        // Read back
        let (k_out, v_out) = exec.read_kv_q8(0, 0, 1).unwrap();

        // Verify dimensions
        assert_eq!(k_out.len(), size, "K output size mismatch");
        assert_eq!(v_out.len(), size, "V output size mismatch");

        // Verify values are close (Q8 has ~1% quantization error max)
        for i in 0..size {
            let k_err = (k[i] - k_out[i]).abs();
            let v_err = (v[i] - v_out[i]).abs();
            // Allow 1% relative error or 0.01 absolute error
            let k_tol = (k[i].abs() * 0.02).max(0.02);
            let v_tol = (v[i].abs() * 0.02).max(0.02);
            assert!(
                k_err < k_tol,
                "K[{}]: expected {}, got {}, err {} > tol {}",
                i,
                k[i],
                k_out[i],
                k_err,
                k_tol
            );
            assert!(
                v_err < v_tol,
                "V[{}]: expected {}, got {}, err {} > tol {}",
                i,
                v[i],
                v_out[i],
                v_err,
                v_tol
            );
        }
    }

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

        let num_kv_heads = 2;
        let head_dim = 32; // Minimal divisible by 32
        let max_len = 8;

        exec.init_kv_cache_q8_gpu(1, 4, num_kv_heads, head_dim, max_len)
            .unwrap();

        let size = num_kv_heads * head_dim;

        // Write to multiple positions
        for pos in 0..4 {
            let k: Vec<f32> = (0..size).map(|i| (pos as f32 + i as f32) * 0.1).collect();
            let v: Vec<f32> = (0..size).map(|i| -(pos as f32 + i as f32) * 0.1).collect();
            exec.write_kv_q8(0, pos, &k, &v).unwrap();
        }

        // Read all positions at once
        let (k_all, v_all) = exec.read_kv_q8(0, 0, 4).unwrap();

        assert_eq!(k_all.len(), 4 * size, "K all size mismatch");
        assert_eq!(v_all.len(), 4 * size, "V all size mismatch");
    }

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

        // Don't initialize Q8 cache
        let k = vec![1.0f32; 128];
        let v = vec![1.0f32; 128];

        let result = exec.write_kv_q8(0, 0, &k, &v);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not enabled"));
    }

    // ========================================================================
    // X1-KVALLOC (#2774): batched KV allocation is sized from the batch, not 32
    // ========================================================================
    //
    // MEASURED on lambda-4090 (RTX 4090, 24564 MiB) with
    // qwen2.5-coder-7b-instruct-q4_k_m.gguf, num_layers=28, num_kv_heads=4,
    // head_dim=128, --context-length 4096:
    //
    //   VRAM after load ......... 14961 MiB (4.4 GB Q4_K + 6.7 GB FP8 cache + ctx)
    //   free at admission ....... 24564 - 14961 = 9603 MiB
    //   bytes per slot .......... 2*4*4096*128*4*28 = 469_762_048  (448 MiB)
    //   32 slots ................ 14336 MiB  -> CUDA_ERROR_OUT_OF_MEMORY
    //   admitted batch .......... 3
    //
    // Pre-fix the allocation was `max_kv_slots.max(m)` = 32 regardless of m,
    // and the server returned HTTP 500 for 3 of 4 concurrent requests:
    //
    //   [PMAT-072] Setup+prefill ERROR (m=3): Failed to init batched KV cache
    //   for M=32: CUDA driver error: CUDA_ERROR_OUT_OF_MEMORY (code: 2)

    /// Bytes-per-slot for the measured 7B/4096 configuration.
    const W1_7B_SLOT_BYTES: usize = 2 * 4 * 4096 * 128 * 4 * 28;
    /// Free VRAM measured at admission time on lambda-4090, in bytes.
    const W1_7B_FREE_BYTES: usize = 9603 * 1024 * 1024;

    /// RED without the fix. `requested` is the scheduler's ceiling; pre-fix it
    /// was passed through untouched, which is the OOM above.
    #[test]
    fn x1_kvalloc_2774_does_not_allocate_a_ceiling_that_cannot_fit() {
        let slots = CudaExecutor::batched_kv_slots_that_fit(
            W1_7B_FREE_BYTES,
            CudaExecutor::BATCHED_KV_VRAM_RESERVE_BYTES,
            W1_7B_SLOT_BYTES,
            32,
            3,
        );
        assert_ne!(
            slots, 32,
            "sized the allocation from the scheduler's ceiling, not the device \
             (#2774): 32 x 448 MiB = 14336 MiB into 9603 MiB free"
        );
        assert!(
            slots * W1_7B_SLOT_BYTES
                <= W1_7B_FREE_BYTES - CudaExecutor::BATCHED_KV_VRAM_RESERVE_BYTES,
            "sized {slots} slots ({} MiB) past the spendable budget",
            slots * W1_7B_SLOT_BYTES / (1024 * 1024)
        );
    }

    /// RED without the fix, and the acceptance case for #2774: the W1 model at
    /// the c=4 band must get exactly the four slots it admitted.
    #[test]
    fn x1_kvalloc_2774_c4_band_gets_four_slots_not_thirty_two() {
        let slots = CudaExecutor::batched_kv_slots_that_fit(
            W1_7B_FREE_BYTES,
            CudaExecutor::BATCHED_KV_VRAM_RESERVE_BYTES,
            W1_7B_SLOT_BYTES,
            32,
            4,
        );
        assert!(slots >= 4, "c=4 admitted 4 sequences, sized {slots} slots");
        assert!(
            slots < 32,
            "c=4 still took the whole ceiling ({slots}); that is the #2774 OOM"
        );
        assert!(
            slots * W1_7B_SLOT_BYTES + CudaExecutor::BATCHED_KV_VRAM_RESERVE_BYTES
                <= W1_7B_FREE_BYTES,
            "{slots} slots does not fit the measured budget"
        );
    }

    /// The floor is the ADMITTED batch. Sizing may not silently hand back fewer
    /// slots than there are sequences: slot i>=alloc would scatter its prefill
    /// past the end of the K/V buffers. Under-provisioning is admission's job,
    /// and it must be an error, not a quiet truncation.
    #[test]
    fn x1_kvalloc_2774_never_returns_fewer_slots_than_admitted() {
        // A budget that fits nothing at all.
        let slots = CudaExecutor::batched_kv_slots_that_fit(
            1024,
            CudaExecutor::BATCHED_KV_VRAM_RESERVE_BYTES,
            W1_7B_SLOT_BYTES,
            32,
            8,
        );
        assert_eq!(slots, 8, "sizing must never drop an admitted sequence");
    }

    /// DISCRIMINATION: stays GREEN before and after. When the ceiling genuinely
    /// fits, the fix must not shrink it — mid-batch joins (PMAT-073) depend on
    /// the spare slots, and a fix that always returned `m` would trade an OOM
    /// for a reallocation on every join.
    #[test]
    fn x1_kvalloc_2774_leaves_a_ceiling_that_fits_alone() {
        // 1.5B at ctx 2048: 2*2*2048*128*4*28 = 58_720_256 bytes/slot (56 MiB).
        let slot = 2 * 2 * 2048 * 128 * 4 * 28;
        let slots = CudaExecutor::batched_kv_slots_that_fit(
            20 * 1024 * 1024 * 1024,
            CudaExecutor::BATCHED_KV_VRAM_RESERVE_BYTES,
            slot,
            32,
            4,
        );
        assert_eq!(slots, 32, "32 x 56 MiB fits in 20 GiB; do not shrink it");
    }

    /// DISCRIMINATION: the reserve is load-bearing. Deleting it (a plausible
    /// simplification) lets the allocation consume the last byte, leaving the
    /// prefill workspace and captured graphs nothing.
    #[test]
    fn x1_kvalloc_2774_reserve_is_honoured() {
        // Exactly 4 slots' worth of VRAM, and a reserve of one slot.
        let with_reserve = CudaExecutor::batched_kv_slots_that_fit(
            4 * W1_7B_SLOT_BYTES,
            W1_7B_SLOT_BYTES,
            W1_7B_SLOT_BYTES,
            4,
            1,
        );
        assert_eq!(with_reserve, 3, "reserve must be subtracted before dividing");
    }

    /// #2762's shape, guarded inside #2774's fix: per-slot bytes are derived
    /// from `kv_cache_max_len` — the CONFIGURED context — so doubling the
    /// context doubles the slot. A hardcoded 2048 here would make the two
    /// contexts indistinguishable, which is exactly how #2762 stayed invisible.
    #[test]
    fn x1_kvalloc_bytes_per_slot_tracks_the_configured_context() {
        let Some(mut exec) = create_executor() else {
            return;
        };
        exec.init_kv_cache_gpu(2, 4, 4, 128, 2048).expect("kv cache");
        let at_2048 = exec.batched_kv_bytes_per_slot(2);
        assert_eq!(at_2048, 2 * 4 * 2048 * 128 * 4 * 2);

        let Some(mut exec4k) = create_executor() else {
            return;
        };
        exec4k
            .init_kv_cache_gpu(2, 4, 4, 128, 4096)
            .expect("kv cache");
        assert_eq!(
            exec4k.batched_kv_bytes_per_slot(2),
            2 * at_2048,
            "per-slot size did not follow the configured context (#2762)"
        );
    }