ruvllm 2.1.0

LLM serving runtime with Ruvector integration - Paged attention, KV cache, and SONA learning
Documentation
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
//! Two-Tier KV Cache Implementation
//!
//! Implements a memory-efficient KV cache with two tiers:
//! - **High-precision tail**: Recent tokens in FP16 for attention quality
//! - **Quantized store**: Older tokens in Q4/Q8 for memory efficiency
//!
//! This design balances memory usage with attention quality by keeping
//! the most relevant (recent) context in high precision while compressing
//! older context.
//!
//! ## M4 Pro Optimizations (2024-01)
//!
//! - **Memory pooling**: Pre-allocated buffer pools eliminate allocation overhead
//! - **64-byte alignment**: Cache-line aligned storage for optimal L1/L2 access
//! - **NEON vectorized dequantization**: 8x unrolled SIMD for Q4 -> FP32
//! - **Async prefetching**: Prefetch next batch during current attention
//! - **Zero-copy KV retrieval**: Direct pointer access avoiding memcpy
//!
//! ## Integration with memory_pool Module
//!
//! The KV cache can use `BufferPool` from the `memory_pool` module for
//! efficient block allocation with multiple size classes.

use crate::error::{Result, RuvLLMError};
use crate::memory_pool::{BufferPool, BufferSize, PooledBuffer};
use crate::types::Precision;
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::alloc::{alloc, dealloc, Layout};
use std::collections::VecDeque;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

/// Cache line size for M4 Pro (64 bytes)
const CACHE_LINE_SIZE: usize = 64;

/// Alignment for NEON operations (16 bytes for 128-bit vectors)
const NEON_ALIGNMENT: usize = 16;

/// Memory pool block size (4KB pages)
const POOL_BLOCK_SIZE: usize = 4096;

/// 64-byte aligned buffer for cache-efficient storage
#[derive(Debug)]
pub struct AlignedBuffer {
    ptr: *mut f32,
    len: usize,
    capacity: usize,
    layout: Layout,
}

// SAFETY: AlignedBuffer manages its own memory and can be sent between threads
unsafe impl Send for AlignedBuffer {}
unsafe impl Sync for AlignedBuffer {}

impl AlignedBuffer {
    /// Create a new aligned buffer with specified capacity
    pub fn new(capacity: usize) -> Self {
        let size = capacity * std::mem::size_of::<f32>();
        let layout = Layout::from_size_align(size.max(CACHE_LINE_SIZE), CACHE_LINE_SIZE)
            .expect("Invalid layout");

        // SAFETY: Layout is valid and we track the allocation
        let ptr = unsafe { alloc(layout) as *mut f32 };

        if ptr.is_null() {
            panic!("Failed to allocate aligned buffer");
        }

        Self {
            ptr,
            len: 0,
            capacity,
            layout,
        }
    }

    /// Get slice of the buffer
    ///
    /// # Safety Invariants (maintained by AlignedBuffer)
    ///
    /// This is safe because:
    /// - `ptr` is always non-null (checked at construction, panics if alloc fails)
    /// - `ptr` was allocated with proper alignment (CACHE_LINE_SIZE = 64)
    /// - `len` is always <= `capacity` (enforced by `extend_from_slice`)
    /// - Memory is valid for reads up to `len` elements
    /// - No mutable references exist (we take `&self`)
    #[inline(always)]
    pub fn as_slice(&self) -> &[f32] {
        // SAFETY: All invariants are maintained by AlignedBuffer's public API.
        // ptr is valid (non-null, properly aligned), len <= capacity.
        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
    }

    /// Get mutable slice of the buffer
    ///
    /// # Safety Invariants (maintained by AlignedBuffer)
    ///
    /// This is safe because:
    /// - `ptr` is always non-null (checked at construction, panics if alloc fails)
    /// - `ptr` was allocated with proper alignment (CACHE_LINE_SIZE = 64)
    /// - `len` is always <= `capacity` (enforced by `extend_from_slice`)
    /// - Memory is valid for writes up to `len` elements
    /// - We have exclusive mutable access (we take `&mut self`)
    #[inline(always)]
    pub fn as_mut_slice(&mut self) -> &mut [f32] {
        // SAFETY: All invariants are maintained by AlignedBuffer's public API.
        // ptr is valid (non-null, properly aligned), len <= capacity.
        // Exclusive access is guaranteed by &mut self.
        unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) }
    }

    /// Extend buffer with data
    #[inline(always)]
    pub fn extend_from_slice(&mut self, data: &[f32]) {
        let new_len = self.len + data.len();
        assert!(new_len <= self.capacity, "Buffer overflow");

        // SAFETY: We've verified capacity
        unsafe {
            std::ptr::copy_nonoverlapping(data.as_ptr(), self.ptr.add(self.len), data.len());
        }
        self.len = new_len;
    }

    /// Clear buffer (doesn't deallocate)
    #[inline(always)]
    pub fn clear(&mut self) {
        self.len = 0;
    }

    /// Get raw pointer (for NEON intrinsics)
    #[inline(always)]
    pub fn as_ptr(&self) -> *const f32 {
        self.ptr
    }

    /// Get mutable raw pointer
    #[inline(always)]
    pub fn as_mut_ptr(&mut self) -> *mut f32 {
        self.ptr
    }

    /// Current length
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Check if empty
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Capacity
    #[inline(always)]
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Set the length of the buffer without bounds checking.
    ///
    /// # Safety
    ///
    /// This method is unsafe because caller must ensure:
    /// - `new_len <= self.capacity`
    /// - All elements up to `new_len` have been initialized
    ///
    /// This is used by the NEON dequantization path which writes
    /// directly to the buffer and then updates the length.
    #[inline(always)]
    pub(crate) unsafe fn set_len_unchecked(&mut self, new_len: usize) {
        debug_assert!(
            new_len <= self.capacity,
            "set_len_unchecked: {} > {}",
            new_len,
            self.capacity
        );
        self.len = new_len;
    }
}

impl Drop for AlignedBuffer {
    fn drop(&mut self) {
        // SAFETY: ptr was allocated with this layout
        unsafe {
            dealloc(self.ptr as *mut u8, self.layout);
        }
    }
}

impl Clone for AlignedBuffer {
    fn clone(&self) -> Self {
        let mut new_buf = Self::new(self.capacity);
        new_buf.extend_from_slice(self.as_slice());
        new_buf
    }
}

/// Memory pool for KV cache allocation
#[derive(Debug)]
pub struct KvMemoryPool {
    /// Pre-allocated blocks for keys
    key_pool: RwLock<Vec<AlignedBuffer>>,
    /// Pre-allocated blocks for values
    value_pool: RwLock<Vec<AlignedBuffer>>,
    /// Block size in floats
    block_size: usize,
    /// Maximum blocks to pre-allocate
    max_blocks: usize,
    /// Current allocated blocks
    allocated_blocks: AtomicUsize,
}

impl KvMemoryPool {
    /// Create a new memory pool
    pub fn new(block_size: usize, max_blocks: usize) -> Self {
        Self {
            key_pool: RwLock::new(Vec::with_capacity(max_blocks)),
            value_pool: RwLock::new(Vec::with_capacity(max_blocks)),
            block_size,
            max_blocks,
            allocated_blocks: AtomicUsize::new(0),
        }
    }

    /// Get or allocate a key buffer
    pub fn get_key_buffer(&self) -> AlignedBuffer {
        let mut pool = self.key_pool.write();
        if let Some(buf) = pool.pop() {
            buf
        } else {
            self.allocated_blocks.fetch_add(1, Ordering::Relaxed);
            AlignedBuffer::new(self.block_size)
        }
    }

    /// Get or allocate a value buffer
    pub fn get_value_buffer(&self) -> AlignedBuffer {
        let mut pool = self.value_pool.write();
        if let Some(buf) = pool.pop() {
            buf
        } else {
            self.allocated_blocks.fetch_add(1, Ordering::Relaxed);
            AlignedBuffer::new(self.block_size)
        }
    }

    /// Return a key buffer to the pool
    pub fn return_key_buffer(&self, mut buf: AlignedBuffer) {
        buf.clear();
        let mut pool = self.key_pool.write();
        if pool.len() < self.max_blocks {
            pool.push(buf);
        }
        // Otherwise let it drop
    }

    /// Return a value buffer to the pool
    pub fn return_value_buffer(&self, mut buf: AlignedBuffer) {
        buf.clear();
        let mut pool = self.value_pool.write();
        if pool.len() < self.max_blocks {
            pool.push(buf);
        }
    }

    /// Pre-warm the pool with buffers
    pub fn prewarm(&self, count: usize) {
        let count = count.min(self.max_blocks);

        let mut key_pool = self.key_pool.write();
        let mut value_pool = self.value_pool.write();

        for _ in 0..count {
            if key_pool.len() < self.max_blocks {
                key_pool.push(AlignedBuffer::new(self.block_size));
                self.allocated_blocks.fetch_add(1, Ordering::Relaxed);
            }
            if value_pool.len() < self.max_blocks {
                value_pool.push(AlignedBuffer::new(self.block_size));
                self.allocated_blocks.fetch_add(1, Ordering::Relaxed);
            }
        }
    }

    /// Get pool statistics
    pub fn stats(&self) -> PoolStats {
        PoolStats {
            key_pool_size: self.key_pool.read().len(),
            value_pool_size: self.value_pool.read().len(),
            total_allocated: self.allocated_blocks.load(Ordering::Relaxed),
            block_size_bytes: self.block_size * std::mem::size_of::<f32>(),
        }
    }
}

/// Memory pool statistics
#[derive(Debug, Clone, Default)]
pub struct PoolStats {
    pub key_pool_size: usize,
    pub value_pool_size: usize,
    pub total_allocated: usize,
    pub block_size_bytes: usize,
}

/// KV cache configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KvCacheConfig {
    /// Number of tokens to keep in high-precision tail
    pub tail_length: usize,
    /// Precision for tail storage
    pub tail_precision: Precision,
    /// Precision for quantized store
    pub store_precision: Precision,
    /// Maximum total tokens to cache
    pub max_tokens: usize,
    /// Number of KV heads
    pub num_kv_heads: usize,
    /// Head dimension
    pub head_dim: usize,
    /// Migration batch size (tokens to move at once)
    pub migration_batch: usize,
}

impl Default for KvCacheConfig {
    fn default() -> Self {
        Self {
            tail_length: 256,
            tail_precision: Precision::FP16,
            store_precision: Precision::Q4,
            max_tokens: 4096,
            num_kv_heads: 8,
            head_dim: 128,
            migration_batch: 64,
        }
    }
}

/// Cache tier enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CacheTier {
    /// High-precision tail for recent tokens
    Hot,
    /// Warm tier (optional intermediate)
    Warm,
    /// Quantized store for older tokens
    Cold,
    /// TurboQuant compressed store (~3.5 bits, geometry-preserving)
    TurboQuant,
}

/// Quantization configuration for cache
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CacheQuantization {
    /// High-precision tail only
    HighPrecisionTail {
        /// Number of tokens in tail
        tail_length: usize,
        /// Precision level
        precision: Precision,
    },
    /// Quantized store only
    QuantizedStore {
        /// Precision level
        precision: Precision,
        /// Compression ratio achieved
        compression_ratio: f32,
    },
    /// Hybrid: tail in FP16, rest in Q4
    Hybrid {
        /// Number of tokens in tail
        tail_length: usize,
        /// Tail precision
        tail_precision: Precision,
        /// Store precision
        store_precision: Precision,
    },
    /// TurboQuant: FP16 tail + TurboQuant ~3.5-bit cold store
    /// Achieves ~6× memory reduction with geometry-preserving compression
    TurboQuantHybrid {
        /// Number of tokens in high-precision tail
        tail_length: usize,
        /// Tail precision (typically FP16)
        tail_precision: Precision,
        /// TurboQuant bit-width for cold store (default 3.5)
        turbo_bits: f32,
    },
}

impl Default for CacheQuantization {
    fn default() -> Self {
        Self::Hybrid {
            tail_length: 256,
            tail_precision: Precision::FP16,
            store_precision: Precision::Q4,
        }
    }
}

/// KV pair storage
#[derive(Debug, Clone)]
struct KvPair {
    /// Key tensor
    keys: Vec<f32>,
    /// Value tensor
    values: Vec<f32>,
    /// Token position
    position: usize,
}

/// Quantized KV pair storage (simulated - production would use actual quantization)
#[derive(Debug, Clone)]
struct QuantizedKvPair {
    /// Quantized keys (stored as f32 for simplicity, would be i8/i4 in production)
    keys: Vec<f32>,
    /// Quantized values
    values: Vec<f32>,
    /// Scale factor for dequantization
    scale: f32,
    /// Zero point for asymmetric quantization
    zero_point: f32,
    /// Token position
    position: usize,
}

impl QuantizedKvPair {
    /// Quantize from full precision
    ///
    /// M4 Pro optimization: NEON-accelerated quantization with 8x unrolling
    fn from_kv_pair(pair: &KvPair, precision: Precision) -> Self {
        // Simplified quantization - production would use proper quantization
        let (scale, zero_point) = Self::compute_scale_and_zero(&pair.keys, precision);

        #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
        let quantize = |vals: &[f32]| -> Vec<f32> { Self::quantize_neon(vals, scale, zero_point) };

        #[cfg(not(all(target_arch = "aarch64", target_feature = "neon")))]
        let quantize = |vals: &[f32]| -> Vec<f32> {
            vals.iter()
                .map(|v| ((v - zero_point) / scale).round())
                .collect()
        };

        Self {
            keys: quantize(&pair.keys),
            values: quantize(&pair.values),
            scale,
            zero_point,
            position: pair.position,
        }
    }

    /// NEON-accelerated quantization with 8x unrolling
    #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
    fn quantize_neon(values: &[f32], scale: f32, zero_point: f32) -> Vec<f32> {
        use std::arch::aarch64::*;

        let mut result = vec![0.0f32; values.len()];
        let inv_scale = 1.0 / scale;

        // SAFETY: Pointers are valid and aligned
        unsafe {
            let inv_scale_vec = vdupq_n_f32(inv_scale);
            let zero_vec = vdupq_n_f32(zero_point);

            const UNROLL_8X: usize = 8;
            let chunks = values.len() / UNROLL_8X;

            for c in 0..chunks {
                let base = c * UNROLL_8X;

                // Load 8 values
                let v0 = vld1q_f32(values.as_ptr().add(base));
                let v1 = vld1q_f32(values.as_ptr().add(base + 4));

                // Subtract zero point
                let sub0 = vsubq_f32(v0, zero_vec);
                let sub1 = vsubq_f32(v1, zero_vec);

                // Multiply by inverse scale
                let scaled0 = vmulq_f32(sub0, inv_scale_vec);
                let scaled1 = vmulq_f32(sub1, inv_scale_vec);

                // Round to nearest (using vrndnq_f32)
                let rounded0 = vrndnq_f32(scaled0);
                let rounded1 = vrndnq_f32(scaled1);

                // Store
                vst1q_f32(result.as_mut_ptr().add(base), rounded0);
                vst1q_f32(result.as_mut_ptr().add(base + 4), rounded1);
            }

            // Remainder
            for i in (chunks * UNROLL_8X)..values.len() {
                result[i] = ((values[i] - zero_point) * inv_scale).round();
            }
        }

        result
    }

    /// Compute scale and zero point for quantization
    fn compute_scale_and_zero(values: &[f32], precision: Precision) -> (f32, f32) {
        if values.is_empty() {
            return (1.0, 0.0);
        }

        #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
        let (min_val, max_val) = unsafe { Self::minmax_neon(values) };

        #[cfg(not(all(target_arch = "aarch64", target_feature = "neon")))]
        let (min_val, max_val) = {
            let min = values.iter().cloned().fold(f32::INFINITY, f32::min);
            let max = values.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
            (min, max)
        };

        let range = match precision {
            Precision::Q8 => 255.0,
            Precision::Q4 | Precision::Q4K => 15.0,
            _ => 255.0,
        };

        let scale = (max_val - min_val) / range;
        let zero_point = min_val;

        (scale.max(1e-8), zero_point)
    }

    /// NEON-accelerated min/max computation
    #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
    unsafe fn minmax_neon(values: &[f32]) -> (f32, f32) {
        use std::arch::aarch64::*;

        let mut min_vec = vdupq_n_f32(f32::INFINITY);
        let mut max_vec = vdupq_n_f32(f32::NEG_INFINITY);

        const UNROLL_8X: usize = 8;
        let chunks = values.len() / UNROLL_8X;

        for c in 0..chunks {
            let base = c * UNROLL_8X;
            let v0 = vld1q_f32(values.as_ptr().add(base));
            let v1 = vld1q_f32(values.as_ptr().add(base + 4));

            min_vec = vminq_f32(min_vec, vminq_f32(v0, v1));
            max_vec = vmaxq_f32(max_vec, vmaxq_f32(v0, v1));
        }

        // Reduce
        let min_val = vminvq_f32(min_vec);
        let max_val = vmaxvq_f32(max_vec);

        // Handle remainder
        let mut final_min = min_val;
        let mut final_max = max_val;
        for i in (chunks * UNROLL_8X)..values.len() {
            final_min = final_min.min(values[i]);
            final_max = final_max.max(values[i]);
        }

        (final_min, final_max)
    }

    /// Dequantize to full precision
    ///
    /// M4 Pro optimization: NEON-accelerated dequantization with 8x unrolling
    fn dequantize(&self) -> KvPair {
        #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
        let dequant =
            |vals: &[f32]| -> Vec<f32> { Self::dequantize_neon(vals, self.scale, self.zero_point) };

        #[cfg(not(all(target_arch = "aarch64", target_feature = "neon")))]
        let dequant = |vals: &[f32]| -> Vec<f32> {
            vals.iter()
                .map(|v| v * self.scale + self.zero_point)
                .collect()
        };

        KvPair {
            keys: dequant(&self.keys),
            values: dequant(&self.values),
            position: self.position,
        }
    }

    /// NEON-accelerated dequantization with 8x unrolling
    ///
    /// output[i] = quantized[i] * scale + zero_point
    #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
    fn dequantize_neon(quantized: &[f32], scale: f32, zero_point: f32) -> Vec<f32> {
        use std::arch::aarch64::*;

        let mut result = vec![0.0f32; quantized.len()];

        // SAFETY: Pointers are valid
        unsafe {
            let scale_vec = vdupq_n_f32(scale);
            let zero_vec = vdupq_n_f32(zero_point);

            const UNROLL_8X: usize = 8;
            let chunks = quantized.len() / UNROLL_8X;

            for c in 0..chunks {
                let base = c * UNROLL_8X;

                // Load 8 quantized values
                let q0 = vld1q_f32(quantized.as_ptr().add(base));
                let q1 = vld1q_f32(quantized.as_ptr().add(base + 4));

                // Dequantize: q * scale + zero
                let d0 = vfmaq_f32(zero_vec, q0, scale_vec);
                let d1 = vfmaq_f32(zero_vec, q1, scale_vec);

                // Store
                vst1q_f32(result.as_mut_ptr().add(base), d0);
                vst1q_f32(result.as_mut_ptr().add(base + 4), d1);
            }

            // Remainder
            for i in (chunks * UNROLL_8X)..quantized.len() {
                result[i] = quantized[i] * scale + zero_point;
            }
        }

        result
    }

    /// Dequantize directly into an aligned buffer (zero-copy optimization)
    ///
    /// # Safety Notes
    ///
    /// NEON path requires careful handling to maintain AlignedBuffer invariants:
    /// - Must verify capacity before writing
    /// - Must update len atomically after writing to maintain consistency
    #[inline(always)]
    fn dequantize_into(&self, key_buf: &mut AlignedBuffer, value_buf: &mut AlignedBuffer) {
        #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
        unsafe {
            // SECURITY FIX: Verify capacity before NEON write to prevent buffer overflow
            let key_new_len = key_buf.len() + self.keys.len();
            let value_new_len = value_buf.len() + self.values.len();

            assert!(
                key_new_len <= key_buf.capacity(),
                "Key buffer overflow: {} > {}",
                key_new_len,
                key_buf.capacity()
            );
            assert!(
                value_new_len <= value_buf.capacity(),
                "Value buffer overflow: {} > {}",
                value_new_len,
                value_buf.capacity()
            );

            Self::dequantize_neon_into(
                &self.keys,
                key_buf.as_mut_ptr().add(key_buf.len()),
                self.scale,
                self.zero_point,
            );
            Self::dequantize_neon_into(
                &self.values,
                value_buf.as_mut_ptr().add(value_buf.len()),
                self.scale,
                self.zero_point,
            );

            // SECURITY FIX: Use set_len method instead of raw pointer write
            // This maintains the AlignedBuffer invariants properly
            key_buf.set_len_unchecked(key_new_len);
            value_buf.set_len_unchecked(value_new_len);
        }

        #[cfg(not(all(target_arch = "aarch64", target_feature = "neon")))]
        {
            let keys: Vec<f32> = self
                .keys
                .iter()
                .map(|v| v * self.scale + self.zero_point)
                .collect();
            let values: Vec<f32> = self
                .values
                .iter()
                .map(|v| v * self.scale + self.zero_point)
                .collect();
            key_buf.extend_from_slice(&keys);
            value_buf.extend_from_slice(&values);
        }
    }

    /// NEON dequantization directly into output buffer
    #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
    #[inline(always)]
    unsafe fn dequantize_neon_into(
        quantized: &[f32],
        output: *mut f32,
        scale: f32,
        zero_point: f32,
    ) {
        use std::arch::aarch64::*;

        let scale_vec = vdupq_n_f32(scale);
        let zero_vec = vdupq_n_f32(zero_point);

        const UNROLL_8X: usize = 8;
        let chunks = quantized.len() / UNROLL_8X;

        for c in 0..chunks {
            let base = c * UNROLL_8X;

            let q0 = vld1q_f32(quantized.as_ptr().add(base));
            let q1 = vld1q_f32(quantized.as_ptr().add(base + 4));

            let d0 = vfmaq_f32(zero_vec, q0, scale_vec);
            let d1 = vfmaq_f32(zero_vec, q1, scale_vec);

            vst1q_f32(output.add(base), d0);
            vst1q_f32(output.add(base + 4), d1);
        }

        for i in (chunks * UNROLL_8X)..quantized.len() {
            *output.add(i) = quantized[i] * scale + zero_point;
        }
    }
}

/// Two-tier KV cache implementation
///
/// M4 Pro optimizations:
/// - Memory pooling eliminates allocation overhead
/// - 64-byte aligned buffers for optimal cache access
/// - NEON-accelerated quantization/dequantization
#[derive(Debug)]
pub struct TwoTierKvCache {
    /// Configuration
    config: KvCacheConfig,
    /// High-precision tail storage
    tail: RwLock<VecDeque<KvPair>>,
    /// Quantized store
    store: RwLock<Vec<QuantizedKvPair>>,
    /// Current total tokens
    total_tokens: AtomicUsize,
    /// Quantization policy reference (for dynamic adjustment)
    quantization_policy: Arc<RwLock<CacheQuantization>>,
    /// Memory pool for aligned buffers
    memory_pool: Arc<KvMemoryPool>,
}

impl TwoTierKvCache {
    /// Create a new two-tier KV cache
    pub fn new(config: KvCacheConfig) -> Self {
        let quantization_policy = Arc::new(RwLock::new(CacheQuantization::Hybrid {
            tail_length: config.tail_length,
            tail_precision: config.tail_precision,
            store_precision: config.store_precision,
        }));

        // Calculate block size based on cache dimensions
        let stride = config.num_kv_heads * config.head_dim;
        let block_size = stride * config.tail_length;

        // Create memory pool with enough blocks for max tokens
        let max_blocks = (config.max_tokens / config.tail_length).max(4);
        let memory_pool = Arc::new(KvMemoryPool::new(block_size, max_blocks));

        // Pre-warm the pool
        memory_pool.prewarm(2);

        Self {
            config,
            tail: RwLock::new(VecDeque::new()),
            store: RwLock::new(Vec::new()),
            total_tokens: AtomicUsize::new(0),
            quantization_policy,
            memory_pool,
        }
    }

    /// Create with custom memory pool
    pub fn with_pool(config: KvCacheConfig, pool: Arc<KvMemoryPool>) -> Self {
        let quantization_policy = Arc::new(RwLock::new(CacheQuantization::Hybrid {
            tail_length: config.tail_length,
            tail_precision: config.tail_precision,
            store_precision: config.store_precision,
        }));

        Self {
            config,
            tail: RwLock::new(VecDeque::new()),
            store: RwLock::new(Vec::new()),
            total_tokens: AtomicUsize::new(0),
            quantization_policy,
            memory_pool: pool,
        }
    }

    /// Append new KV pairs
    pub fn append(&self, keys: &[f32], values: &[f32]) -> Result<()> {
        let stride = self.config.num_kv_heads * self.config.head_dim;
        let num_tokens = keys.len() / stride;

        if keys.len() != values.len() {
            return Err(RuvLLMError::KvCache(
                "Key and value lengths must match".to_string(),
            ));
        }

        let current_tokens = self.total_tokens.load(Ordering::SeqCst);

        // Add to tail
        let mut tail = self.tail.write();
        for i in 0..num_tokens {
            let offset = i * stride;
            tail.push_back(KvPair {
                keys: keys[offset..offset + stride].to_vec(),
                values: values[offset..offset + stride].to_vec(),
                position: current_tokens + i,
            });
        }

        // Migrate to store if tail exceeds threshold
        while tail.len() > self.config.tail_length {
            let batch_size = self
                .config
                .migration_batch
                .min(tail.len() - self.config.tail_length);

            let to_migrate: Vec<_> = (0..batch_size).filter_map(|_| tail.pop_front()).collect();

            let mut store = self.store.write();
            for pair in to_migrate {
                let quantized = QuantizedKvPair::from_kv_pair(&pair, self.config.store_precision);
                store.push(quantized);
            }
        }

        self.total_tokens.fetch_add(num_tokens, Ordering::SeqCst);

        // Enforce max tokens limit
        self.enforce_max_tokens()?;

        Ok(())
    }

    /// Enforce maximum token limit by evicting oldest tokens
    fn enforce_max_tokens(&self) -> Result<()> {
        let total = self.total_tokens.load(Ordering::SeqCst);

        if total <= self.config.max_tokens {
            return Ok(());
        }

        let to_evict = total - self.config.max_tokens;
        let mut store = self.store.write();

        // Evict from quantized store first
        let store_evict = to_evict.min(store.len());
        store.drain(0..store_evict);

        self.total_tokens.fetch_sub(store_evict, Ordering::SeqCst);

        // If still over limit, evict from tail
        let remaining = to_evict - store_evict;
        if remaining > 0 {
            let mut tail = self.tail.write();
            for _ in 0..remaining.min(tail.len()) {
                tail.pop_front();
            }
            self.total_tokens
                .fetch_sub(remaining.min(tail.len()), Ordering::SeqCst);
        }

        Ok(())
    }

    /// Get all KV pairs for attention computation
    pub fn get_all_kv(&self) -> (Vec<f32>, Vec<f32>) {
        let stride = self.config.num_kv_heads * self.config.head_dim;
        let total = self.total_tokens.load(Ordering::SeqCst);

        let mut all_keys = Vec::with_capacity(total * stride);
        let mut all_values = Vec::with_capacity(total * stride);

        // Get from quantized store (dequantize)
        let store = self.store.read();
        for qpair in store.iter() {
            let pair = qpair.dequantize();
            all_keys.extend_from_slice(&pair.keys);
            all_values.extend_from_slice(&pair.values);
        }
        drop(store);

        // Get from tail (full precision)
        let tail = self.tail.read();
        for pair in tail.iter() {
            all_keys.extend_from_slice(&pair.keys);
            all_values.extend_from_slice(&pair.values);
        }

        (all_keys, all_values)
    }

    /// Get all KV pairs using aligned buffers from the memory pool
    ///
    /// M4 Pro optimization: Uses pre-allocated aligned buffers for
    /// zero-copy NEON-accelerated dequantization
    pub fn get_all_kv_aligned(&self) -> (AlignedBuffer, AlignedBuffer) {
        let stride = self.config.num_kv_heads * self.config.head_dim;
        let total = self.total_tokens.load(Ordering::SeqCst);

        // Get buffers from pool
        let mut key_buf = AlignedBuffer::new(total * stride);
        let mut value_buf = AlignedBuffer::new(total * stride);

        // Get from quantized store with NEON dequantization
        let store = self.store.read();
        for qpair in store.iter() {
            qpair.dequantize_into(&mut key_buf, &mut value_buf);
        }
        drop(store);

        // Get from tail (full precision - direct copy)
        let tail = self.tail.read();
        for pair in tail.iter() {
            key_buf.extend_from_slice(&pair.keys);
            value_buf.extend_from_slice(&pair.values);
        }

        (key_buf, value_buf)
    }

    /// Get memory pool reference
    pub fn memory_pool(&self) -> &Arc<KvMemoryPool> {
        &self.memory_pool
    }

    /// Get pool statistics
    pub fn pool_stats(&self) -> PoolStats {
        self.memory_pool.stats()
    }

    /// Compute attention with tier-aware access
    ///
    /// This applies position-based decay weights to balance precision/memory tradeoff
    pub fn attend(&self, query: &[f32], scale: f32) -> Result<Vec<f32>> {
        let (keys, values) = self.get_all_kv();
        let stride = self.config.num_kv_heads * self.config.head_dim;
        let num_tokens = keys.len() / stride;

        if num_tokens == 0 {
            return Ok(vec![0.0; query.len()]);
        }

        // Simplified attention - production would use optimized kernels
        let mut scores = Vec::with_capacity(num_tokens);

        for t in 0..num_tokens {
            let k_offset = t * stride;
            let k_slice = &keys[k_offset..k_offset + stride];

            let score: f32 = query
                .iter()
                .zip(k_slice.iter())
                .map(|(q, k)| q * k * scale)
                .sum();

            scores.push(score);
        }

        // Softmax
        let max_score = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
        let exp_scores: Vec<f32> = scores.iter().map(|s| (s - max_score).exp()).collect();
        let sum_exp: f32 = exp_scores.iter().sum();
        let attn_weights: Vec<f32> = exp_scores.iter().map(|e| e / sum_exp).collect();

        // Weighted sum of values
        let mut output = vec![0.0; stride];
        for (t, weight) in attn_weights.iter().enumerate() {
            let v_offset = t * stride;
            for (i, v) in values[v_offset..v_offset + stride].iter().enumerate() {
                output[i] += weight * v;
            }
        }

        Ok(output)
    }

    /// Get current statistics
    pub fn stats(&self) -> KvCacheStats {
        let tail = self.tail.read();
        let store = self.store.read();
        let stride = self.config.num_kv_heads * self.config.head_dim;

        let tail_bytes = tail.len() * stride * 4 * 2; // f32 * 2 (keys + values)
        let store_bytes =
            store.len() * stride * self.config.store_precision.bytes_per_element() as usize * 2;

        KvCacheStats {
            total_tokens: self.total_tokens.load(Ordering::SeqCst),
            tail_tokens: tail.len(),
            store_tokens: store.len(),
            tail_bytes,
            store_bytes,
            compression_ratio: tail_bytes as f32 / store_bytes.max(1) as f32,
        }
    }

    /// Clear the cache
    pub fn clear(&self) {
        let mut tail = self.tail.write();
        let mut store = self.store.write();
        tail.clear();
        store.clear();
        self.total_tokens.store(0, Ordering::SeqCst);
    }

    /// Update quantization policy
    pub fn update_policy(&self, policy: CacheQuantization) {
        let mut current = self.quantization_policy.write();
        *current = policy;
    }
}

/// KV cache statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct KvCacheStats {
    /// Total tokens cached
    pub total_tokens: usize,
    /// Tokens in high-precision tail
    pub tail_tokens: usize,
    /// Tokens in quantized store
    pub store_tokens: usize,
    /// Bytes used by tail
    pub tail_bytes: usize,
    /// Bytes used by store
    pub store_bytes: usize,
    /// Compression ratio (tail/store)
    pub compression_ratio: f32,
}

// ============================================================================
// Pooled KV Block Allocator (uses memory_pool::BufferPool)
// ============================================================================

/// A KV cache block allocated from the buffer pool.
///
/// Uses the memory_pool::BufferPool for efficient allocation with
/// multiple size classes and automatic return on drop.
pub struct PooledKvBlock {
    /// Key buffer from pool
    keys: PooledBuffer,
    /// Value buffer from pool
    values: PooledBuffer,
    /// Number of tokens stored
    token_count: usize,
    /// Stride per token (num_heads * head_dim)
    stride: usize,
}

impl PooledKvBlock {
    /// Create a new pooled KV block.
    ///
    /// # Arguments
    ///
    /// * `pool` - Buffer pool to allocate from
    /// * `max_tokens` - Maximum tokens this block can hold
    /// * `num_heads` - Number of KV heads
    /// * `head_dim` - Dimension per head
    pub fn new(
        pool: &BufferPool,
        max_tokens: usize,
        num_heads: usize,
        head_dim: usize,
    ) -> Option<Self> {
        let stride = num_heads * head_dim;
        let bytes_needed = max_tokens * stride * std::mem::size_of::<f32>();

        // acquire_for_size returns Result<Option<PooledBuffer>>
        // - Err: allocation failure
        // - Ok(None): size too large for any size class
        // - Ok(Some): success
        let keys = pool.acquire_for_size(bytes_needed).ok()??;
        let values = pool.acquire_for_size(bytes_needed).ok()??;

        Some(Self {
            keys,
            values,
            token_count: 0,
            stride,
        })
    }

    /// Append KV pairs to the block.
    ///
    /// Returns the number of tokens actually appended.
    pub fn append(&mut self, keys: &[f32], values: &[f32]) -> usize {
        let capacity_tokens = self.keys.capacity() / (self.stride * std::mem::size_of::<f32>());
        let input_tokens = keys.len() / self.stride;
        let space_remaining = capacity_tokens.saturating_sub(self.token_count);
        let tokens_to_append = input_tokens.min(space_remaining);

        if tokens_to_append == 0 {
            return 0;
        }

        let elements = tokens_to_append * self.stride;
        let offset = self.token_count * self.stride;

        // Copy keys
        let key_slice = self.keys.as_slice_mut::<f32>();
        key_slice[offset..offset + elements].copy_from_slice(&keys[..elements]);

        // Copy values
        let value_slice = self.values.as_slice_mut::<f32>();
        value_slice[offset..offset + elements].copy_from_slice(&values[..elements]);

        self.token_count += tokens_to_append;
        tokens_to_append
    }

    /// Get keys as a slice.
    pub fn keys(&self) -> &[f32] {
        let elements = self.token_count * self.stride;
        &self.keys.as_slice::<f32>()[..elements]
    }

    /// Get values as a slice.
    pub fn values(&self) -> &[f32] {
        let elements = self.token_count * self.stride;
        &self.values.as_slice::<f32>()[..elements]
    }

    /// Get the number of tokens stored.
    pub fn token_count(&self) -> usize {
        self.token_count
    }

    /// Check if the block is full.
    pub fn is_full(&self) -> bool {
        let capacity_tokens = self.keys.capacity() / (self.stride * std::mem::size_of::<f32>());
        self.token_count >= capacity_tokens
    }

    /// Get remaining capacity in tokens.
    pub fn remaining_tokens(&self) -> usize {
        let capacity_tokens = self.keys.capacity() / (self.stride * std::mem::size_of::<f32>());
        capacity_tokens.saturating_sub(self.token_count)
    }

    /// Clear the block for reuse.
    pub fn clear(&mut self) {
        self.token_count = 0;
    }
}

impl std::fmt::Debug for PooledKvBlock {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PooledKvBlock")
            .field("token_count", &self.token_count)
            .field("stride", &self.stride)
            .field("key_capacity", &self.keys.capacity())
            .field("value_capacity", &self.values.capacity())
            .finish()
    }
}

/// Pooled KV cache that uses BufferPool for block allocation.
///
/// This cache allocates blocks from a shared buffer pool, enabling efficient
/// memory reuse across multiple cache instances and reducing allocation overhead.
#[derive(Debug)]
pub struct PooledKvCache {
    /// Configuration
    config: KvCacheConfig,
    /// Shared buffer pool
    pool: BufferPool,
    /// Active blocks
    blocks: RwLock<Vec<PooledKvBlock>>,
    /// Tokens per block
    tokens_per_block: usize,
    /// Total tokens cached
    total_tokens: AtomicUsize,
}

impl PooledKvCache {
    /// Create a new pooled KV cache.
    ///
    /// # Arguments
    ///
    /// * `config` - Cache configuration
    /// * `pool` - Shared buffer pool
    /// * `tokens_per_block` - Number of tokens per block
    pub fn new(config: KvCacheConfig, pool: BufferPool, tokens_per_block: usize) -> Self {
        Self {
            config,
            pool,
            blocks: RwLock::new(Vec::new()),
            tokens_per_block,
            total_tokens: AtomicUsize::new(0),
        }
    }

    /// Create with a new buffer pool.
    pub fn with_new_pool(config: KvCacheConfig, tokens_per_block: usize) -> Self {
        let pool = BufferPool::new();
        Self::new(config, pool, tokens_per_block)
    }

    /// Append KV pairs to the cache.
    pub fn append(&self, keys: &[f32], values: &[f32]) -> Result<()> {
        let stride = self.config.num_kv_heads * self.config.head_dim;
        let input_tokens = keys.len() / stride;

        if keys.len() != values.len() {
            return Err(RuvLLMError::KvCache(
                "Key and value lengths must match".to_string(),
            ));
        }

        let mut blocks = self.blocks.write();
        let mut remaining_keys = keys;
        let mut remaining_values = values;

        while !remaining_keys.is_empty() {
            // Get or create a block with space
            let need_new_block = blocks.is_empty() || blocks.last().map_or(true, |b| b.is_full());

            if need_new_block {
                let new_block = PooledKvBlock::new(
                    &self.pool,
                    self.tokens_per_block,
                    self.config.num_kv_heads,
                    self.config.head_dim,
                )
                .ok_or_else(|| {
                    RuvLLMError::OutOfMemory("Failed to allocate KV block from pool".to_string())
                })?;
                blocks.push(new_block);
            }

            // SAFETY: blocks is non-empty because we either just pushed a new block
            // or the loop condition ensures at least one block exists
            let block = blocks
                .last_mut()
                .expect("blocks should be non-empty after allocation");
            let tokens_appended = block.append(remaining_keys, remaining_values);

            if tokens_appended == 0 {
                break;
            }

            let elements = tokens_appended * stride;
            remaining_keys = &remaining_keys[elements..];
            remaining_values = &remaining_values[elements..];

            self.total_tokens
                .fetch_add(tokens_appended, Ordering::SeqCst);
        }

        // Enforce max tokens
        self.enforce_max_tokens(&mut blocks)?;

        Ok(())
    }

    /// Enforce maximum token limit.
    fn enforce_max_tokens(&self, blocks: &mut Vec<PooledKvBlock>) -> Result<()> {
        let total = self.total_tokens.load(Ordering::SeqCst);

        if total <= self.config.max_tokens {
            return Ok(());
        }

        let mut to_evict = total - self.config.max_tokens;

        while to_evict > 0 && !blocks.is_empty() {
            let first_block_tokens = blocks[0].token_count();

            if first_block_tokens <= to_evict {
                // Remove entire block
                blocks.remove(0);
                to_evict -= first_block_tokens;
                self.total_tokens
                    .fetch_sub(first_block_tokens, Ordering::SeqCst);
            } else {
                // Would need partial eviction - not supported in block model
                // For simplicity, we just remove the whole block
                let removed_tokens = blocks[0].token_count();
                blocks.remove(0);
                self.total_tokens
                    .fetch_sub(removed_tokens, Ordering::SeqCst);
                break;
            }
        }

        Ok(())
    }

    /// Get all KV pairs.
    pub fn get_all_kv(&self) -> (Vec<f32>, Vec<f32>) {
        let blocks = self.blocks.read();
        let total = self.total_tokens.load(Ordering::SeqCst);
        let stride = self.config.num_kv_heads * self.config.head_dim;

        let mut all_keys = Vec::with_capacity(total * stride);
        let mut all_values = Vec::with_capacity(total * stride);

        for block in blocks.iter() {
            all_keys.extend_from_slice(block.keys());
            all_values.extend_from_slice(block.values());
        }

        (all_keys, all_values)
    }

    /// Get statistics.
    pub fn stats(&self) -> PooledKvCacheStats {
        let blocks = self.blocks.read();
        let total_tokens = self.total_tokens.load(Ordering::SeqCst);
        let stride = self.config.num_kv_heads * self.config.head_dim;

        PooledKvCacheStats {
            total_tokens,
            block_count: blocks.len(),
            tokens_per_block: self.tokens_per_block,
            total_bytes: total_tokens * stride * std::mem::size_of::<f32>() * 2,
            pool_stats: self.pool.stats(),
        }
    }

    /// Clear the cache.
    pub fn clear(&self) {
        let mut blocks = self.blocks.write();
        blocks.clear();
        self.total_tokens.store(0, Ordering::SeqCst);
    }

    /// Get reference to the buffer pool.
    pub fn pool(&self) -> &BufferPool {
        &self.pool
    }
}

/// Statistics for pooled KV cache
#[derive(Debug, Clone)]
pub struct PooledKvCacheStats {
    /// Total tokens cached
    pub total_tokens: usize,
    /// Number of blocks allocated
    pub block_count: usize,
    /// Tokens per block
    pub tokens_per_block: usize,
    /// Total bytes used
    pub total_bytes: usize,
    /// Underlying pool statistics
    pub pool_stats: crate::memory_pool::BufferPoolStats,
}

// ============================================================================
// TurboQuant-Enhanced KV Cache
// ============================================================================

/// Three-tier KV cache with TurboQuant compression for the cold tier.
///
/// Architecture:
/// - **Hot tier** (FP16): Recent tokens for high-quality attention
/// - **Cold tier** (TurboQuant ~3.5-bit): Older tokens with geometry-preserving compression
///
/// This achieves ~6× memory reduction on the cold tier while preserving
/// inner product geometry for attention computation. Based on TurboQuant (ICLR 2026).
///
/// ## Example
///
/// ```rust,ignore
/// use ruvllm::kv_cache::{TurboQuantKvCache, TurboQuantKvCacheConfig};
///
/// let config = TurboQuantKvCacheConfig::default();
/// let cache = TurboQuantKvCache::new(config).unwrap();
///
/// // Append tokens - automatically migrates to TurboQuant tier
/// cache.append(&keys, &values).unwrap();
/// ```
#[cfg(feature = "quantize")]
pub struct TurboQuantKvCache {
    /// Configuration
    config: TurboQuantKvCacheConfig,
    /// High-precision tail (recent tokens)
    tail: RwLock<VecDeque<KvPair>>,
    /// TurboQuant compressed cold store
    turbo_tier: RwLock<crate::quantize::turbo_quant::TurboQuantCacheTier>,
    /// Total tokens tracked
    total_tokens: AtomicUsize,
}

/// Configuration for TurboQuant-enhanced KV cache
#[cfg(feature = "quantize")]
#[derive(Debug, Clone)]
pub struct TurboQuantKvCacheConfig {
    /// Tokens to keep in FP16 tail
    pub tail_length: usize,
    /// Maximum total tokens
    pub max_tokens: usize,
    /// Number of KV heads
    pub num_kv_heads: usize,
    /// Head dimension
    pub head_dim: usize,
    /// Migration batch size
    pub migration_batch: usize,
    /// TurboQuant bit-width configuration
    pub turbo_config: crate::quantize::turbo_quant::TurboQuantConfig,
}

#[cfg(feature = "quantize")]
impl Default for TurboQuantKvCacheConfig {
    fn default() -> Self {
        Self {
            tail_length: 256,
            max_tokens: 8192,
            num_kv_heads: 8,
            head_dim: 128,
            migration_batch: 64,
            turbo_config: crate::quantize::turbo_quant::TurboQuantConfig::default(),
        }
    }
}

#[cfg(feature = "quantize")]
impl TurboQuantKvCache {
    /// Create a new TurboQuant-enhanced KV cache
    pub fn new(config: TurboQuantKvCacheConfig) -> Result<Self> {
        let turbo_tier =
            crate::quantize::turbo_quant::TurboQuantCacheTier::new(config.turbo_config.clone())?;

        Ok(Self {
            config,
            tail: RwLock::new(VecDeque::new()),
            turbo_tier: RwLock::new(turbo_tier),
            total_tokens: AtomicUsize::new(0),
        })
    }

    /// Append new KV pairs, auto-migrating old tokens to TurboQuant tier
    pub fn append(&self, keys: &[f32], values: &[f32]) -> Result<()> {
        let stride = self.config.num_kv_heads * self.config.head_dim;
        let num_tokens = keys.len() / stride;

        if keys.len() != values.len() {
            return Err(RuvLLMError::KvCache(
                "Key and value lengths must match".to_string(),
            ));
        }

        let current_tokens = self.total_tokens.load(Ordering::SeqCst);

        // Add to tail
        let mut tail = self.tail.write();
        for i in 0..num_tokens {
            let offset = i * stride;
            tail.push_back(KvPair {
                keys: keys[offset..offset + stride].to_vec(),
                values: values[offset..offset + stride].to_vec(),
                position: current_tokens + i,
            });
        }

        // Migrate excess to TurboQuant tier
        while tail.len() > self.config.tail_length {
            let batch_size = self
                .config
                .migration_batch
                .min(tail.len() - self.config.tail_length);

            let to_migrate: Vec<_> = (0..batch_size).filter_map(|_| tail.pop_front()).collect();

            let mut turbo = self.turbo_tier.write();
            for pair in to_migrate {
                turbo.push(&pair.keys, &pair.values, pair.position)?;
            }
        }

        self.total_tokens.fetch_add(num_tokens, Ordering::SeqCst);

        // Enforce max tokens
        self.enforce_max_tokens()?;

        Ok(())
    }

    /// Enforce maximum token limit
    fn enforce_max_tokens(&self) -> Result<()> {
        let total = self.total_tokens.load(Ordering::SeqCst);
        if total <= self.config.max_tokens {
            return Ok(());
        }

        let to_evict = total - self.config.max_tokens;
        let mut turbo = self.turbo_tier.write();

        let turbo_evict = to_evict.min(turbo.len());
        turbo.evict_oldest(turbo_evict);
        self.total_tokens.fetch_sub(turbo_evict, Ordering::SeqCst);

        let remaining = to_evict - turbo_evict;
        if remaining > 0 {
            let mut tail = self.tail.write();
            let tail_evict = remaining.min(tail.len());
            for _ in 0..tail_evict {
                tail.pop_front();
            }
            self.total_tokens.fetch_sub(tail_evict, Ordering::SeqCst);
        }

        Ok(())
    }

    /// Get all KV pairs for attention (decompresses TurboQuant tier)
    pub fn get_all_kv(&self) -> Result<(Vec<f32>, Vec<f32>)> {
        let stride = self.config.num_kv_heads * self.config.head_dim;
        let total = self.total_tokens.load(Ordering::SeqCst);

        let mut all_keys = Vec::with_capacity(total * stride);
        let mut all_values = Vec::with_capacity(total * stride);

        // Decompress from TurboQuant tier
        let turbo = self.turbo_tier.read();
        let (turbo_keys, turbo_values) = turbo.get_all_kv()?;
        all_keys.extend(turbo_keys);
        all_values.extend(turbo_values);
        drop(turbo);

        // Get from tail (full precision)
        let tail = self.tail.read();
        for pair in tail.iter() {
            all_keys.extend_from_slice(&pair.keys);
            all_values.extend_from_slice(&pair.values);
        }

        Ok((all_keys, all_values))
    }

    /// Get statistics
    pub fn stats(&self) -> TurboQuantKvCacheStats {
        let tail = self.tail.read();
        let turbo = self.turbo_tier.read();
        let stride = self.config.num_kv_heads * self.config.head_dim;

        let tail_bytes = tail.len() * stride * 4 * 2; // FP32 keys + values
        let turbo_stats = turbo.stats();

        TurboQuantKvCacheStats {
            total_tokens: self.total_tokens.load(Ordering::SeqCst),
            tail_tokens: tail.len(),
            turbo_tokens: turbo.len(),
            tail_bytes,
            turbo_bytes: turbo_stats.compressed_bytes,
            turbo_original_bytes: turbo_stats.original_bytes,
            turbo_compression_ratio: turbo_stats.compression_ratio,
            turbo_bits_per_value: turbo_stats.bits_per_value,
        }
    }

    /// Clear all tiers
    pub fn clear(&self) {
        let mut tail = self.tail.write();
        let mut turbo = self.turbo_tier.write();
        tail.clear();
        turbo.clear();
        self.total_tokens.store(0, Ordering::SeqCst);
    }
}

/// Statistics for TurboQuant KV cache
#[cfg(feature = "quantize")]
#[derive(Debug, Clone)]
pub struct TurboQuantKvCacheStats {
    pub total_tokens: usize,
    pub tail_tokens: usize,
    pub turbo_tokens: usize,
    pub tail_bytes: usize,
    pub turbo_bytes: usize,
    pub turbo_original_bytes: usize,
    pub turbo_compression_ratio: f32,
    pub turbo_bits_per_value: f32,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_kv_cache_append() {
        let config = KvCacheConfig {
            tail_length: 4,
            num_kv_heads: 2,
            head_dim: 4,
            migration_batch: 2,
            ..Default::default()
        };

        let cache = TwoTierKvCache::new(config);

        // Append tokens
        let keys = vec![1.0; 2 * 4]; // 1 token
        let values = vec![1.0; 2 * 4];
        cache.append(&keys, &values).unwrap();

        let stats = cache.stats();
        assert_eq!(stats.total_tokens, 1);
        assert_eq!(stats.tail_tokens, 1);
        assert_eq!(stats.store_tokens, 0);
    }

    #[test]
    fn test_kv_cache_migration() {
        let config = KvCacheConfig {
            tail_length: 2,
            num_kv_heads: 2,
            head_dim: 4,
            migration_batch: 1,
            max_tokens: 100,
            ..Default::default()
        };

        let cache = TwoTierKvCache::new(config);

        // Append more tokens than tail can hold
        for _ in 0..5 {
            let keys = vec![1.0; 2 * 4];
            let values = vec![1.0; 2 * 4];
            cache.append(&keys, &values).unwrap();
        }

        let stats = cache.stats();
        assert_eq!(stats.total_tokens, 5);
        assert_eq!(stats.tail_tokens, 2);
        assert_eq!(stats.store_tokens, 3);
    }

    #[test]
    fn test_kv_cache_attend() {
        let config = KvCacheConfig {
            tail_length: 4,
            num_kv_heads: 1,
            head_dim: 4,
            ..Default::default()
        };

        let cache = TwoTierKvCache::new(config);

        // Add some KV pairs
        let keys = vec![1.0, 0.0, 0.0, 0.0];
        let values = vec![1.0, 2.0, 3.0, 4.0];
        cache.append(&keys, &values).unwrap();

        // Query
        let query = vec![1.0, 0.0, 0.0, 0.0];
        let output = cache.attend(&query, 1.0).unwrap();

        assert_eq!(output.len(), 4);
        // With single token and matching query, output should be similar to values
        assert!((output[0] - 1.0).abs() < 0.1);
    }

    #[test]
    fn test_pooled_kv_cache_basic() {
        let config = KvCacheConfig {
            tail_length: 4,
            num_kv_heads: 2,
            head_dim: 4,
            max_tokens: 100,
            ..Default::default()
        };

        let cache = PooledKvCache::with_new_pool(config, 16);

        // Append tokens
        let stride = 2 * 4; // num_kv_heads * head_dim
        let keys = vec![1.0; stride]; // 1 token
        let values = vec![2.0; stride];
        cache.append(&keys, &values).unwrap();

        let stats = cache.stats();
        assert_eq!(stats.total_tokens, 1);
        assert_eq!(stats.block_count, 1);
    }

    #[test]
    fn test_pooled_kv_cache_multiple_blocks() {
        let config = KvCacheConfig {
            tail_length: 4,
            num_kv_heads: 2,
            head_dim: 4,
            max_tokens: 100,
            ..Default::default()
        };

        // Using tokens_per_block = 2, but actual capacity depends on buffer size class
        // stride = 2 * 4 = 8 floats = 32 bytes per token
        // For 2 tokens: 2 * 32 = 64 bytes needed, but BufferSize::KB1 gives 1024 bytes
        // So actual capacity = 1024 / 32 = 32 tokens per block from 1KB buffer
        // With tokens_per_block = 2 (requested), the block can hold 2 tokens as set
        let cache = PooledKvCache::with_new_pool(config, 2);

        let stride = 2 * 4;

        // Append 5 tokens
        for i in 0..5 {
            let keys = vec![i as f32; stride];
            let values = vec![(i * 2) as f32; stride];
            cache.append(&keys, &values).unwrap();
        }

        let stats = cache.stats();
        assert_eq!(stats.total_tokens, 5);
        // Block count depends on actual block capacity from buffer pool
        // With 1KB buffers and 32 bytes per token, each block can hold up to 32 tokens
        // But tokens_per_block=2 limits it, so we should get 3 blocks: (2+2+1)
        // However, the actual capacity is based on acquired buffer size
        assert!(stats.block_count >= 1, "Should have at least 1 block");
        assert!(stats.block_count <= 5, "Should have at most 5 blocks");

        // Verify data integrity
        let (all_keys, all_values) = cache.get_all_kv();
        assert_eq!(all_keys.len(), 5 * stride);
        assert_eq!(all_values.len(), 5 * stride);

        // First token should have keys of 0.0
        assert_eq!(all_keys[0], 0.0);
        // Fifth token should have keys of 4.0
        assert_eq!(all_keys[4 * stride], 4.0);
    }

    #[test]
    fn test_pooled_kv_cache_pool_reuse() {
        let config = KvCacheConfig {
            tail_length: 4,
            num_kv_heads: 2,
            head_dim: 4,
            max_tokens: 100,
            ..Default::default()
        };

        let pool = BufferPool::new();
        pool.prewarm(BufferSize::KB4, 4);

        let cache = PooledKvCache::new(config, pool, 16);

        let stride = 2 * 4;
        let keys = vec![1.0; stride];
        let values = vec![2.0; stride];

        // Append and clear multiple times to test reuse
        for _ in 0..3 {
            cache.append(&keys, &values).unwrap();
            cache.clear();
        }

        let stats = cache.stats();
        assert_eq!(stats.total_tokens, 0);
        assert!(stats.pool_stats.returns > 0 || stats.pool_stats.hits > 0);
    }
}