realizar 0.8.4

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

    #[test]
    fn test_quantized_kv_data_q8() {
        let data = QuantizedKvData::new(KvQuantType::Q8, 16, 8, 64);
        assert_eq!(data.quant_type(), KvQuantType::Q8);
        // Q8 uses less memory than FP32
        let fp32_data = QuantizedKvData::new(KvQuantType::FP32, 16, 8, 64);
        assert!(data.memory_bytes() < fp32_data.memory_bytes());
    }

    #[test]
    fn test_quantized_kv_data_q4() {
        let data = QuantizedKvData::new(KvQuantType::Q4, 16, 8, 64);
        assert_eq!(data.quant_type(), KvQuantType::Q4);
        // Q4 uses even less memory than Q8
        let q8_data = QuantizedKvData::new(KvQuantType::Q8, 16, 8, 64);
        assert!(data.memory_bytes() < q8_data.memory_bytes());
    }

    #[test]
    fn test_quantized_kv_data_write_read_fp32() {
        let mut data = QuantizedKvData::new(KvQuantType::FP32, 16, 8, 64);

        let test_keys: Vec<f32> = (0..64).map(|i| i as f32 * 0.1).collect();
        data.write_keys(0, &test_keys);
        let read_keys = data.read_keys(0, 64);

        assert_eq!(read_keys, test_keys);
    }

    #[test]
    fn test_quantized_kv_data_write_read_q8() {
        let mut data = QuantizedKvData::new(KvQuantType::Q8, 16, 8, 64);

        let test_values: Vec<f32> = (0..64).map(|i| (i as f32 - 32.0) * 0.1).collect();
        data.write_values(0, &test_values);
        let read_values = data.read_values(0, 64);

        // Q8 should preserve values with small error
        for (orig, read) in test_values.iter().zip(read_values.iter()) {
            assert!((orig - read).abs() < 0.05);
        }
    }

    #[test]
    fn test_quantized_kv_page_new() {
        let page = QuantizedKvPage::new(PageId::new(0), KvQuantType::Q8, 16, 8, 64);
        assert_eq!(page.quant_type(), KvQuantType::Q8);
        assert_eq!(page.num_tokens, 0);
        assert_eq!(page.ref_count, 0); // Pages start in free pool with ref_count 0
        assert!(!page.is_full());
        assert!(!page.is_shared());
    }

    #[test]
    fn test_quantized_kv_page_read_write() {
        let mut page = QuantizedKvPage::new(PageId::new(0), KvQuantType::FP32, 16, 8, 64);

        let keys: Vec<f32> = (0..512).map(|i| i as f32 * 0.01).collect();
        let values: Vec<f32> = (0..512).map(|i| -i as f32 * 0.01).collect();

        page.write_keys(0, &keys);
        page.write_values(0, &values);

        let read_keys = page.read_keys(0);
        let read_values = page.read_values(0);

        assert_eq!(read_keys.len(), 512);
        assert_eq!(read_values.len(), 512);
        assert_eq!(read_keys, keys);
        assert_eq!(read_values, values);
    }

    #[test]
    fn test_quantized_kv_page_is_full() {
        let mut page = QuantizedKvPage::new(PageId::new(0), KvQuantType::Q8, 16, 8, 64);
        assert!(!page.is_full());
        assert_eq!(page.remaining_capacity(), 16);

        page.num_tokens = 16;
        assert!(page.is_full());
        assert_eq!(page.remaining_capacity(), 0);
    }

    #[test]
    fn test_quantized_paged_kv_cache_new() {
        let cache = QuantizedPagedKvCache::new(100, 16, 8, 64, KvQuantType::Q8);
        assert_eq!(cache.quant_type(), KvQuantType::Q8);
        assert_eq!(cache.free_page_count(), 100);
        assert_eq!(cache.stats().active_sequences, 0);
    }

    #[test]
    fn test_quantized_paged_kv_cache_allocate() {
        let mut cache = QuantizedPagedKvCache::new(100, 16, 8, 64, KvQuantType::Q8);
        let seq_id = cache.allocate_sequence(32).expect("test");

        assert_eq!(cache.free_page_count(), 98); // 32 tokens = 2 pages
        assert_eq!(cache.stats().active_sequences, 1);
        assert!(seq_id.value() < u64::MAX);
    }

    #[test]
    fn test_quantized_paged_kv_cache_free() {
        let mut cache = QuantizedPagedKvCache::new(100, 16, 8, 64, KvQuantType::Q4);
        let seq_id = cache.allocate_sequence(16).expect("test");

        assert_eq!(cache.free_page_count(), 99);

        cache.free_sequence(seq_id);

        assert_eq!(cache.free_page_count(), 100);
        assert_eq!(cache.stats().active_sequences, 0);
    }

    #[test]
    fn test_quantized_paged_kv_cache_memory_savings() {
        let mut cache = QuantizedPagedKvCache::new(100, 16, 8, 64, KvQuantType::Q8);
        let _seq_id = cache.allocate_sequence(16).expect("test");

        let savings = cache.memory_savings();
        // Q8 uses (4 + 32) = 36 bytes per block of 32 values vs 128 bytes for FP32
        // Ratio: 36/128 = 0.28125, with some overhead ~0.35
        assert!(
            savings < 0.6,
            "Q8 should use less than 60% of FP32 memory, got {}",
            savings
        );
    }

    #[test]
    fn test_quantized_paged_kv_cache_q4_savings() {
        let mut cache = QuantizedPagedKvCache::new(100, 16, 8, 64, KvQuantType::Q4);
        let _seq_id = cache.allocate_sequence(16).expect("test");

        let savings = cache.memory_savings();
        // Q4 uses (4 + 16) = 20 bytes per block of 32 values vs 128 bytes for FP32
        // Ratio: 20/128 = 0.15625, with some overhead ~0.20
        assert!(
            savings < 0.4,
            "Q4 should use less than 40% of FP32 memory, got {}",
            savings
        );
    }

    #[test]
    fn test_quantized_paged_kv_cache_get_page() {
        let mut cache = QuantizedPagedKvCache::new(100, 16, 8, 64, KvQuantType::Q8);
        let seq_id = cache.allocate_sequence(32).expect("test");

        let page = cache.get_page(seq_id, 0).expect("test");
        assert_eq!(page.quant_type(), KvQuantType::Q8);

        let page2 = cache.get_page(seq_id, 16).expect("test");
        assert_eq!(page2.quant_type(), KvQuantType::Q8);
    }

    #[test]
    fn test_quantized_paged_kv_cache_get_page_mut() {
        let mut cache = QuantizedPagedKvCache::new(100, 16, 8, 64, KvQuantType::Q8);
        let seq_id = cache.allocate_sequence(16).expect("test");

        let page = cache.get_page_mut(seq_id, 0).expect("test");
        page.num_tokens = 8;

        let page2 = cache.get_page(seq_id, 0).expect("test");
        assert_eq!(page2.num_tokens, 8);
    }

    #[test]
    fn test_quantized_paged_kv_cache_oom() {
        let mut cache = QuantizedPagedKvCache::new(1, 16, 8, 64, KvQuantType::Q8);
        let _seq1 = cache.allocate_sequence(16).expect("test");

        let result = cache.allocate_sequence(16);
        assert!(matches!(result, Err(PagedCacheError::OutOfMemory { .. })));
    }

    #[test]
    fn test_q8_block_default() {
        let block = Q8KvBlock::default();
        assert_eq!(block.scale, 0.0);
    }

    #[test]
    fn test_q4_block_default() {
        let block = Q4KvBlock::default();
        assert_eq!(block.scale, 0.0);
    }

    // =========================================================================
    // Deep coverage tests (_deep_pkcov_ prefix)
    // =========================================================================

    // --- Error handling paths ---

    #[test]
    fn test_deep_pkcov_extend_sequence_not_found() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);
        let fake_seq = SeqId::new();

        let result = cache.extend(fake_seq, 32);
        assert!(matches!(result, Err(PagedCacheError::SequenceNotFound(_))));
    }

    #[test]
    fn test_deep_pkcov_extend_sequence_out_of_memory() {
        let mut cache = PagedKvCache::new(2, 16, 8, 64);
        let seq_id = cache.allocate_sequence(16).expect("alloc"); // Uses 1 page, 1 free

        // Extend to need more pages than available
        // extend(48) needs 48/16 = 3 pages total, have 1, need 2 more, only 1 free
        let result = cache.extend(seq_id, 48);
        assert!(matches!(result, Err(PagedCacheError::OutOfMemory { .. })));
    }

    #[test]
    fn test_deep_pkcov_extend_no_new_pages_needed() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);
        let seq_id = cache.allocate_sequence(16).expect("alloc"); // 1 page, 16 capacity
        cache.update_tokens(seq_id, 5).expect("update");

        // Extend by small amount that fits in existing page
        let result = cache.extend(seq_id, 5);
        assert!(result.is_ok());
        assert_eq!(cache.free_page_count(), 99); // No new pages allocated
    }

    #[test]
    fn test_deep_pkcov_update_tokens_not_found() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);
        let fake_seq = SeqId::new();

        let result = cache.update_tokens(fake_seq, 10);
        assert!(matches!(result, Err(PagedCacheError::SequenceNotFound(_))));
    }

    #[test]
    fn test_deep_pkcov_fork_sequence_not_found() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);
        let fake_seq = SeqId::new();

        let result = cache.fork_sequence(fake_seq);
        assert!(matches!(result, Err(PagedCacheError::SequenceNotFound(_))));
    }

    #[test]
    fn test_deep_pkcov_get_page_sequence_not_found() {
        let cache = PagedKvCache::new(100, 16, 8, 64);
        let fake_seq = SeqId::new();

        let result = cache.get_page(fake_seq, 0);
        assert!(matches!(result, Err(PagedCacheError::SequenceNotFound(_))));
    }

    #[test]
    fn test_deep_pkcov_get_page_mut_sequence_not_found() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);
        let fake_seq = SeqId::new();

        let result = cache.get_page_mut(fake_seq, 0);
        assert!(matches!(result, Err(PagedCacheError::SequenceNotFound(_))));
    }

    #[test]
    fn test_deep_pkcov_get_page_mut_invalid_page_access() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);
        let seq_id = cache.allocate_sequence(16).expect("alloc"); // 1 page

        let result = cache.get_page_mut(seq_id, 100); // Beyond allocated
        assert!(matches!(
            result,
            Err(PagedCacheError::InvalidPageAccess { .. })
        ));
    }

    // --- Edge cases in paged memory management ---

    #[test]
    fn test_deep_pkcov_utilization_zero_pages() {
        // Create cache with zero pages - edge case
        let cache = PagedKvCache::new(0, 16, 8, 64);
        assert_eq!(cache.utilization(), 0.0);
        assert_eq!(cache.free_page_count(), 0);
    }

    #[test]
    fn test_deep_pkcov_free_nonexistent_sequence() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);
        let fake_seq = SeqId::new();

        // Should not panic, just do nothing
        cache.free_sequence(fake_seq);
        assert_eq!(cache.stats().sequences_freed, 0);
    }

    #[test]
    fn test_deep_pkcov_allocate_zero_tokens() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);

        // Zero tokens should allocate at least 1 page (div_ceil behavior)
        // Actually 0.div_ceil(16) = 0, so 0 pages needed
        let seq_id = cache.allocate_sequence(0).expect("alloc");
        assert!(cache.page_tables.contains_key(&seq_id));
    }

    #[test]
    fn test_deep_pkcov_update_tokens_spans_multiple_pages() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);
        let seq_id = cache.allocate_sequence(48).expect("alloc"); // 3 pages

        // Update with tokens spanning all pages
        cache.update_tokens(seq_id, 48).expect("update");

        let tokens = cache.get_sequence_tokens(seq_id).expect("get");
        assert_eq!(tokens, 48);
    }

    #[test]
    fn test_deep_pkcov_update_tokens_partial_fill() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);
        let seq_id = cache.allocate_sequence(32).expect("alloc"); // 2 pages

        // Only fill part of first page
        cache.update_tokens(seq_id, 5).expect("update");

        let tokens = cache.get_sequence_tokens(seq_id).expect("get");
        assert_eq!(tokens, 5);
    }

    // --- Copy-on-write edge cases ---

    #[test]
    fn test_deep_pkcov_cow_out_of_memory() {
        let mut cache = PagedKvCache::new(2, 16, 8, 64);
        let parent_id = cache.allocate_sequence(16).expect("alloc"); // 1 page
        let child_id = cache.fork_sequence(parent_id).expect("fork"); // Shares page

        // Fill remaining page
        let _ = cache.allocate_sequence(16).expect("alloc2");

        // Now try to write to child - COW needs a free page but none available
        let result = cache.get_page_mut(child_id, 0);
        assert!(matches!(result, Err(PagedCacheError::OutOfMemory { .. })));
    }

    #[test]
    fn test_deep_pkcov_cow_multiple_forks() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);
        let parent_id = cache.allocate_sequence(16).expect("alloc");
        cache.update_tokens(parent_id, 16).expect("update");

        // Fork multiple times
        let child1 = cache.fork_sequence(parent_id).expect("fork1");
        let child2 = cache.fork_sequence(parent_id).expect("fork2");

        assert_eq!(cache.stats().cow_operations, 2);

        // Write to child1 triggers COW
        let _page = cache.get_page_mut(child1, 0).expect("get");
        assert_eq!(cache.stats().cow_operations, 3);

        // child2 still shares with parent
        let page = cache.get_page(child2, 0).expect("get2");
        assert!(page.ref_count >= 1);
    }

    #[test]
    fn test_deep_pkcov_free_shared_sequence() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);
        let parent_id = cache.allocate_sequence(16).expect("alloc");
        let child_id = cache.fork_sequence(parent_id).expect("fork");

        // Free parent - pages should not return to free list (still referenced by child)
        cache.free_sequence(parent_id);
        assert_eq!(cache.free_page_count(), 99); // Page still in use by child

        // Free child - now pages return
        cache.free_sequence(child_id);
        assert_eq!(cache.free_page_count(), 100);
    }

    // --- Defragmentation paths ---

    #[test]
    fn test_deep_pkcov_should_defragment_low_free_ratio() {
        let mut cache = PagedKvCache::new(10, 16, 8, 64);

        // Allocate to use most pages
        for _ in 0..9 {
            let _ = cache.allocate_sequence(16).expect("alloc");
        }

        // With >90% utilization and any fragmentation, should trigger
        // Need to create a hole first
        let seq_to_free = cache.allocate_sequence(16).ok();
        if let Some(seq) = seq_to_free {
            cache.free_sequence(seq);
        }

        // Low free ratio check is at 10% threshold
        // We have 1 free page out of 10 = 10%, right at threshold
    }

    #[test]
    fn test_deep_pkcov_should_defragment_high_waste() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);

        // Allocate several sequences with partial fill
        let seq1 = cache.allocate_sequence(32).expect("alloc1"); // 2 pages
        let seq2 = cache.allocate_sequence(32).expect("alloc2"); // 2 pages
        let seq3 = cache.allocate_sequence(32).expect("alloc3"); // 2 pages

        // Free middle sequence to create holes
        cache.free_sequence(seq2);

        // Update with very few tokens to create waste
        cache.update_tokens(seq1, 1).expect("update1");
        cache.update_tokens(seq3, 1).expect("update3");

        let stats = cache.fragmentation_stats();
        assert!(stats.holes > 0 || stats.wasted_capacity > 0);
    }

    #[test]
    fn test_deep_pkcov_compact_empty_page_list() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);
        let seq_id = cache.allocate_sequence(0).expect("alloc"); // 0 pages

        let moved = cache.compact_sequence(seq_id);
        assert_eq!(moved, 0);
    }

    #[test]
    fn test_deep_pkcov_fragmentation_stats_large_free_region() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);

        // Allocate just one sequence at the beginning
        let _ = cache.allocate_sequence(16).expect("alloc");

        let stats = cache.fragmentation_stats();
        // Large free region at the end
        assert!(stats.largest_free_region >= 99);
    }