1use burn::tensor::backend::Backend;
2use burn::tensor::Tensor;
3use std::collections::HashMap;
4
5use crate::ops::flash_attention::{FlashAttentionConfig, HierarchicalFlashAttention};
6
7pub const BLOCK_SIZE: usize = 16;
9
10#[derive(Debug, Clone)]
12pub struct KVBlock<B: Backend> {
13 pub keys: Tensor<B, 3>,
15 pub values: Tensor<B, 3>,
17 pub num_tokens: usize,
19}
20
21impl<B: Backend> KVBlock<B> {
22 pub fn new(num_heads: usize, head_dim: usize, device: &B::Device) -> Self {
23 Self {
24 keys: Tensor::zeros([num_heads, BLOCK_SIZE, head_dim], device),
25 values: Tensor::zeros([num_heads, BLOCK_SIZE, head_dim], device),
26 num_tokens: 0,
27 }
28 }
29
30 pub fn is_full(&self) -> bool {
31 self.num_tokens >= BLOCK_SIZE
32 }
33
34 pub fn remaining_capacity(&self) -> usize {
35 BLOCK_SIZE - self.num_tokens
36 }
37}
38
39#[derive(Debug, Clone)]
41pub struct BlockManager<B: Backend> {
42 free_blocks: Vec<usize>,
43 blocks: Vec<Option<KVBlock<B>>>,
44 num_heads: usize,
45 head_dim: usize,
46 device: B::Device,
47}
48
49impl<B: Backend> BlockManager<B> {
50 pub fn new(max_blocks: usize, num_heads: usize, head_dim: usize, device: B::Device) -> Self {
51 let mut blocks = Vec::with_capacity(max_blocks);
52 let mut free_blocks = Vec::with_capacity(max_blocks);
53
54 for i in 0..max_blocks {
55 blocks.push(Some(KVBlock::new(num_heads, head_dim, &device)));
56 free_blocks.push(i);
57 }
58
59 Self {
60 free_blocks,
61 blocks,
62 num_heads,
63 head_dim,
64 device,
65 }
66 }
67
68 pub fn allocate(&mut self) -> Option<usize> {
70 self.free_blocks.pop()
71 }
72
73 pub fn free(&mut self, block_id: usize) {
75 if block_id < self.blocks.len() {
76 if let Some(block) = &mut self.blocks[block_id] {
77 block.num_tokens = 0;
78 }
79 self.free_blocks.push(block_id);
80 }
81 }
82
83 pub fn get(&self, block_id: usize) -> Option<&KVBlock<B>> {
84 self.blocks.get(block_id)?.as_ref()
85 }
86
87 pub fn get_mut(&mut self, block_id: usize) -> Option<&mut KVBlock<B>> {
88 self.blocks.get_mut(block_id)?.as_mut()
89 }
90
91 pub fn num_free_blocks(&self) -> usize {
92 self.free_blocks.len()
93 }
94
95 pub fn num_heads(&self) -> usize {
96 self.num_heads
97 }
98
99 pub fn head_dim(&self) -> usize {
100 self.head_dim
101 }
102
103 pub fn device(&self) -> &B::Device {
104 &self.device
105 }
106}
107
108#[derive(Debug, Clone)]
110pub struct BlockTable {
111 block_table: Vec<usize>,
113 seq_len: usize,
115}
116
117impl BlockTable {
118 pub fn new() -> Self {
119 Self {
120 block_table: Vec::new(),
121 seq_len: 0,
122 }
123 }
124
125 pub fn get_physical_location(&self, token_idx: usize) -> Option<(usize, usize)> {
127 if token_idx >= self.seq_len {
128 return None;
129 }
130 let logical_block = token_idx / BLOCK_SIZE;
131 let offset = token_idx % BLOCK_SIZE;
132 self.block_table
133 .get(logical_block)
134 .map(|&block_id| (block_id, offset))
135 }
136
137 pub fn add_block(&mut self, physical_block_id: usize) {
138 self.block_table.push(physical_block_id);
139 }
140
141 pub fn extend_seq_len(&mut self, new_tokens: usize) {
142 self.seq_len += new_tokens;
143 }
144
145 pub fn physical_blocks(&self) -> &[usize] {
146 &self.block_table
147 }
148
149 pub fn seq_len(&self) -> usize {
150 self.seq_len
151 }
152
153 pub fn needs_new_block(&self) -> bool {
154 let current_capacity = self.block_table.len() * BLOCK_SIZE;
155 self.seq_len >= current_capacity
156 }
157}
158
159pub struct KVBlockRef<'a, B: Backend> {
161 pub keys: &'a Tensor<B, 3>,
163 pub values: &'a Tensor<B, 3>,
165 pub num_tokens: usize,
167 pub block_idx: usize,
169}
170
171pub struct KVBlockIterator<'a, B: Backend> {
173 block_manager: &'a BlockManager<B>,
174 block_ids: &'a [usize],
175 current_idx: usize,
176 remaining_tokens: usize,
177}
178
179impl<'a, B: Backend> Iterator for KVBlockIterator<'a, B> {
180 type Item = KVBlockRef<'a, B>;
181
182 fn next(&mut self) -> Option<Self::Item> {
183 if self.remaining_tokens == 0 || self.current_idx >= self.block_ids.len() {
184 return None;
185 }
186
187 let block_id = self.block_ids[self.current_idx];
188 let block = self.block_manager.get(block_id)?;
189
190 let valid_tokens = block.num_tokens.min(self.remaining_tokens);
191 if valid_tokens == 0 {
192 return None;
193 }
194
195 let block_ref = KVBlockRef {
196 keys: &block.keys,
197 values: &block.values,
198 num_tokens: valid_tokens,
199 block_idx: self.current_idx,
200 };
201
202 self.remaining_tokens -= valid_tokens;
203 self.current_idx += 1;
204
205 Some(block_ref)
206 }
207
208 fn size_hint(&self) -> (usize, Option<usize>) {
209 let remaining = self.block_ids.len() - self.current_idx;
210 (remaining.min(1), Some(remaining))
211 }
212}
213
214#[derive(Debug, Clone)]
216pub struct PagedKVCache<B: Backend> {
217 block_manager: BlockManager<B>,
218 page_tables: Vec<HashMap<usize, BlockTable>>,
219 num_layers: usize,
220 next_seq_id: usize,
221}
222
223impl<B: Backend> PagedKVCache<B> {
224 pub fn new(
225 max_blocks: usize,
226 num_layers: usize,
227 num_heads: usize,
228 head_dim: usize,
229 device: &B::Device,
230 ) -> Self {
231 let block_manager = BlockManager::new(max_blocks, num_heads, head_dim, device.clone());
232 let page_tables = (0..num_layers).map(|_| HashMap::new()).collect();
233
234 Self {
235 block_manager,
236 page_tables,
237 num_layers,
238 next_seq_id: 0,
239 }
240 }
241
242 pub fn allocate_sequence(&mut self) -> usize {
244 let seq_id = self.next_seq_id;
245 self.next_seq_id += 1;
246
247 for layer in 0..self.num_layers {
248 self.page_tables[layer].insert(seq_id, BlockTable::new());
249 }
250
251 seq_id
252 }
253
254 pub fn append(
256 &mut self,
257 layer: usize,
258 seq_id: usize,
259 keys: Tensor<B, 3>,
260 values: Tensor<B, 3>,
261 ) -> Result<(), &'static str> {
262 let (block_manager, page_tables) = (&mut self.block_manager, &mut self.page_tables);
263 let layer_tables = page_tables.get_mut(layer).ok_or("invalid layer")?;
264 let page_table = layer_tables.get_mut(&seq_id).ok_or("unknown sequence")?;
265
266 let [num_heads, new_len, head_dim] = keys.dims();
267 let values_dims = values.dims();
268 if values_dims != [num_heads, new_len, head_dim] {
269 return Err("keys/values shape mismatch");
270 }
271 if num_heads != block_manager.num_heads() || head_dim != block_manager.head_dim() {
272 return Err("keys/values head dimensions mismatch");
273 }
274 if new_len == 0 {
275 return Ok(());
276 }
277
278 let mut offset = 0usize;
279 while offset < new_len {
280 let needs_block = match page_table.physical_blocks().last() {
281 Some(&block_id) => {
282 let block = block_manager.get(block_id).ok_or("block not found")?;
283 block.is_full()
284 }
285 None => true,
286 };
287
288 if needs_block {
289 let block_id = block_manager
290 .allocate()
291 .ok_or("no free blocks available")?;
292 page_table.add_block(block_id);
293 }
294
295 let block_id = *page_table
296 .physical_blocks()
297 .last()
298 .ok_or("no block allocated")?;
299 let block = block_manager.get_mut(block_id).ok_or("block not found")?;
300 let write_len = (new_len - offset).min(block.remaining_capacity());
301 if write_len == 0 {
302 return Err("block has no remaining capacity");
303 }
304
305 let keys_slice = keys.clone().slice([
306 0..num_heads,
307 offset..(offset + write_len),
308 0..head_dim,
309 ]);
310 let values_slice = values.clone().slice([
311 0..num_heads,
312 offset..(offset + write_len),
313 0..head_dim,
314 ]);
315
316 let block_offset = block.num_tokens;
317 block.keys = block.keys.clone().slice_assign(
318 [
319 0..num_heads,
320 block_offset..(block_offset + write_len),
321 0..head_dim,
322 ],
323 keys_slice,
324 );
325 block.values = block.values.clone().slice_assign(
326 [
327 0..num_heads,
328 block_offset..(block_offset + write_len),
329 0..head_dim,
330 ],
331 values_slice,
332 );
333 block.num_tokens += write_len;
334 page_table.extend_seq_len(write_len);
335
336 offset += write_len;
337 }
338
339 Ok(())
340 }
341
342 pub fn get_kv(
344 &self,
345 layer: usize,
346 seq_id: usize,
347 ) -> Result<(Tensor<B, 3>, Tensor<B, 3>), &'static str> {
348 let layer_tables = self.page_tables.get(layer).ok_or("invalid layer")?;
349 let page_table = layer_tables.get(&seq_id).ok_or("unknown sequence")?;
350 let seq_len = page_table.seq_len();
351 if seq_len == 0 {
352 return Err("sequence is empty");
353 }
354
355 let mut remaining = seq_len;
356 let mut keys = Vec::new();
357 let mut values = Vec::new();
358
359 for &block_id in page_table.physical_blocks() {
360 if remaining == 0 {
361 break;
362 }
363 let block = self
364 .block_manager
365 .get(block_id)
366 .ok_or("block not found")?;
367 let [num_heads, _block_size, head_dim] = block.keys.dims();
368 let take = block.num_tokens.min(remaining);
369 if take == 0 {
370 continue;
371 }
372
373 keys.push(
374 block
375 .keys
376 .clone()
377 .slice([0..num_heads, 0..take, 0..head_dim]),
378 );
379 values.push(
380 block
381 .values
382 .clone()
383 .slice([0..num_heads, 0..take, 0..head_dim]),
384 );
385 remaining -= take;
386 }
387
388 if keys.is_empty() || remaining != 0 {
389 return Err("incomplete kv data");
390 }
391
392 Ok((Tensor::cat(keys, 1), Tensor::cat(values, 1)))
393 }
394
395 pub fn seq_len(&self, layer: usize, seq_id: usize) -> Result<usize, &'static str> {
396 let layer_tables = self.page_tables.get(layer).ok_or("invalid layer")?;
397 let page_table = layer_tables.get(&seq_id).ok_or("unknown sequence")?;
398 Ok(page_table.seq_len())
399 }
400
401 pub fn num_free_blocks(&self) -> usize {
402 self.block_manager.num_free_blocks()
403 }
404
405 pub fn iter_kv_blocks(
407 &self,
408 layer: usize,
409 seq_id: usize,
410 ) -> Result<KVBlockIterator<'_, B>, &'static str> {
411 let layer_tables = self.page_tables.get(layer).ok_or("invalid layer")?;
412 let page_table = layer_tables.get(&seq_id).ok_or("unknown sequence")?;
413 let seq_len = page_table.seq_len();
414
415 Ok(KVBlockIterator {
416 block_manager: &self.block_manager,
417 block_ids: page_table.physical_blocks(),
418 current_idx: 0,
419 remaining_tokens: seq_len,
420 })
421 }
422
423 pub fn num_blocks(&self, layer: usize, seq_id: usize) -> Result<usize, &'static str> {
425 let layer_tables = self.page_tables.get(layer).ok_or("invalid layer")?;
426 let page_table = layer_tables.get(&seq_id).ok_or("unknown sequence")?;
427 Ok(page_table.physical_blocks().len())
428 }
429
430 pub fn num_heads(&self) -> usize {
432 self.block_manager.num_heads()
433 }
434
435 pub fn head_dim(&self) -> usize {
436 self.block_manager.head_dim()
437 }
438
439 pub fn device(&self) -> &B::Device {
440 self.block_manager.device()
441 }
442
443 pub fn free_sequence(&mut self, seq_id: usize) -> Result<(), &'static str> {
445 let mut found = false;
446 for layer_tables in &mut self.page_tables {
447 if let Some(table) = layer_tables.remove(&seq_id) {
448 for &block_id in table.physical_blocks() {
449 self.block_manager.free(block_id);
450 }
451 found = true;
452 }
453 }
454
455 if found {
456 Ok(())
457 } else {
458 Err("unknown sequence")
459 }
460 }
461}
462
463pub struct PagedAttention {
465 attention: HierarchicalFlashAttention,
466}
467
468impl PagedAttention {
469 pub fn new(config: FlashAttentionConfig) -> Self {
470 Self {
471 attention: HierarchicalFlashAttention::new(config),
472 }
473 }
474
475 pub fn config(&self) -> &FlashAttentionConfig {
476 self.attention.config()
477 }
478
479 pub fn forward<B: Backend>(
480 &self,
481 cache: &mut PagedKVCache<B>,
482 layer: usize,
483 seq_id: usize,
484 query: Tensor<B, 4>,
485 key: Tensor<B, 4>,
486 value: Tensor<B, 4>,
487 causal: bool,
488 ) -> Result<Tensor<B, 4>, &'static str> {
489 let [batch, num_heads, new_seq_len, head_dim] = key.dims();
490 if batch != 1 {
491 return Err("paged attention expects batch=1");
492 }
493 if value.dims() != [batch, num_heads, new_seq_len, head_dim] {
494 return Err("keys/values shape mismatch");
495 }
496
497 let k_reshaped = key.clone().reshape([num_heads, new_seq_len, head_dim]);
498 let v_reshaped = value.clone().reshape([num_heads, new_seq_len, head_dim]);
499 cache.append(layer, seq_id, k_reshaped, v_reshaped)?;
500
501 let total_seq_len = cache.seq_len(layer, seq_id)?;
502 let position_offset = total_seq_len.saturating_sub(new_seq_len);
503
504 let (cached_k, cached_v) = cache.get_kv(layer, seq_id)?;
505 let cached_seq_len = cached_k.dims()[1];
506 let cached_k = cached_k.reshape([1, num_heads, cached_seq_len, head_dim]);
507 let cached_v = cached_v.reshape([1, num_heads, cached_seq_len, head_dim]);
508
509 let output = self
510 .attention
511 .forward(query, cached_k, cached_v, causal, position_offset);
512 B::sync(&output.device());
513 Ok(output)
514 }
515
516 pub fn forward_fused<B: Backend>(
517 &self,
518 cache: &mut PagedKVCache<B>,
519 layer: usize,
520 seq_id: usize,
521 query: Tensor<B, 4>,
522 key: Tensor<B, 4>,
523 value: Tensor<B, 4>,
524 causal: bool,
525 ) -> Result<Tensor<B, 4>, &'static str> {
526 let [batch, num_heads, new_seq_len, head_dim] = key.dims();
527 if batch != 1 {
528 return Err("paged attention expects batch=1");
529 }
530 if value.dims() != [batch, num_heads, new_seq_len, head_dim] {
531 return Err("keys/values shape mismatch");
532 }
533
534 let k_reshaped = key.clone().reshape([num_heads, new_seq_len, head_dim]);
535 let v_reshaped = value.clone().reshape([num_heads, new_seq_len, head_dim]);
536 cache.append(layer, seq_id, k_reshaped, v_reshaped)?;
537
538 let total_seq_len = cache.seq_len(layer, seq_id)?;
539 let position_offset = total_seq_len.saturating_sub(new_seq_len);
540
541 let kv_iter = cache.iter_kv_blocks(layer, seq_id)?;
542 let kv_blocks: Vec<(Tensor<B, 3>, Tensor<B, 3>)> = kv_iter
543 .map(|block| {
544 let [num_heads, _, head_dim] = block.keys.dims();
545 let k = block
546 .keys
547 .clone()
548 .slice([0..num_heads, 0..block.num_tokens, 0..head_dim]);
549 let v = block
550 .values
551 .clone()
552 .slice([0..num_heads, 0..block.num_tokens, 0..head_dim]);
553 (k, v)
554 })
555 .collect();
556
557 let output = self.attention.forward_fused_iter(
558 query,
559 kv_blocks.into_iter(),
560 causal,
561 position_offset,
562 total_seq_len,
563 );
564 B::sync(&output.device());
565 Ok(output)
566 }
567}
568
569#[cfg(all(test, feature = "cpu"))]
570mod tests {
571 use super::*;
572 use burn_ndarray::NdArray;
573
574 #[test]
575 fn test_block_manager_allocate_free() {
576 let device = <NdArray<f32> as Backend>::Device::default();
577 let mut manager = BlockManager::<NdArray<f32>>::new(2, 2, 4, device);
578
579 let first = manager.allocate().expect("first allocate");
580 assert_eq!(manager.num_free_blocks(), 1);
581 let second = manager.allocate().expect("second allocate");
582 assert_eq!(manager.num_free_blocks(), 0);
583 assert!(manager.allocate().is_none());
584
585 if let Some(block) = manager.get_mut(first) {
586 block.num_tokens = BLOCK_SIZE;
587 }
588 manager.free(first);
589 assert_eq!(manager.num_free_blocks(), 1);
590
591 let reused = manager.allocate().expect("reuse allocate");
592 let reused_block = manager.get(reused).expect("reused block");
593 assert_eq!(reused_block.num_tokens, 0);
594
595 manager.free(second);
596 manager.free(reused);
597 assert_eq!(manager.num_free_blocks(), 2);
598 }
599
600 #[test]
601 fn test_block_table_mapping() {
602 let mut table = BlockTable::new();
603 table.add_block(3);
604 table.add_block(7);
605 table.extend_seq_len(BLOCK_SIZE + 1);
606
607 assert_eq!(table.get_physical_location(0), Some((3, 0)));
608 assert_eq!(
609 table.get_physical_location(BLOCK_SIZE - 1),
610 Some((3, BLOCK_SIZE - 1))
611 );
612 assert_eq!(table.get_physical_location(BLOCK_SIZE), Some((7, 0)));
613 assert_eq!(table.get_physical_location(BLOCK_SIZE + 1), None);
614 }
615
616 #[test]
617 fn test_paged_kv_cache_basic() {
618 let device = <NdArray<f32> as Backend>::Device::default();
619 let mut cache = PagedKVCache::<NdArray<f32>>::new(4, 2, 2, 4, &device);
620 let seq_id = cache.allocate_sequence();
621
622 let keys = Tensor::<NdArray<f32>, 3>::zeros([2, BLOCK_SIZE + 3, 4], &device);
623 let values = Tensor::<NdArray<f32>, 3>::zeros([2, BLOCK_SIZE + 3, 4], &device);
624 cache.append(1, seq_id, keys, values).expect("append");
625
626 assert_eq!(cache.seq_len(1, seq_id).expect("seq len"), BLOCK_SIZE + 3);
627 assert_eq!(cache.num_free_blocks(), 2);
628
629 let (k, v) = cache.get_kv(1, seq_id).expect("get kv");
630 assert_eq!(k.dims(), [2, BLOCK_SIZE + 3, 4]);
631 assert_eq!(v.dims(), [2, BLOCK_SIZE + 3, 4]);
632
633 cache.free_sequence(seq_id).expect("free");
634 assert_eq!(cache.num_free_blocks(), 4);
635 }
636
637 #[test]
638 fn test_iter_kv_blocks() {
639 let device = <NdArray<f32> as Backend>::Device::default();
640 let mut cache = PagedKVCache::<NdArray<f32>>::new(8, 1, 2, 4, &device);
641 let seq_id = cache.allocate_sequence();
642
643 let total_tokens = BLOCK_SIZE * 2 + 5;
644 let keys = Tensor::<NdArray<f32>, 3>::zeros([2, total_tokens, 4], &device);
645 let values = Tensor::<NdArray<f32>, 3>::zeros([2, total_tokens, 4], &device);
646 cache.append(0, seq_id, keys, values).expect("append");
647
648 let iter = cache.iter_kv_blocks(0, seq_id).expect("iter");
649 let blocks: Vec<_> = iter.collect();
650
651 assert_eq!(blocks.len(), 3);
652 assert_eq!(blocks[0].num_tokens, BLOCK_SIZE);
653 assert_eq!(blocks[0].block_idx, 0);
654 assert_eq!(blocks[1].num_tokens, BLOCK_SIZE);
655 assert_eq!(blocks[1].block_idx, 1);
656 assert_eq!(blocks[2].num_tokens, 5);
657 assert_eq!(blocks[2].block_idx, 2);
658
659 let total: usize = blocks.iter().map(|b| b.num_tokens).sum();
660 assert_eq!(total, total_tokens);
661 }
662
663 #[test]
664 fn test_kv_blocks_to_tensors() {
665 let device = <NdArray<f32> as Backend>::Device::default();
666 let mut cache = PagedKVCache::<NdArray<f32>>::new(4, 2, 2, 4, &device);
667 let seq_id = cache.allocate_sequence();
668
669 let keys = Tensor::<NdArray<f32>, 3>::zeros([2, BLOCK_SIZE + 3, 4], &device);
670 let values = Tensor::<NdArray<f32>, 3>::zeros([2, BLOCK_SIZE + 3, 4], &device);
671 cache.append(1, seq_id, keys, values).expect("append");
672
673 let iter = cache.iter_kv_blocks(1, seq_id).expect("iter");
674 let kv_blocks: Vec<_> = iter
675 .map(|block| {
676 let [num_heads, _, head_dim] = block.keys.dims();
677 let k = block
678 .keys
679 .clone()
680 .slice([0..num_heads, 0..block.num_tokens, 0..head_dim]);
681 let v = block
682 .values
683 .clone()
684 .slice([0..num_heads, 0..block.num_tokens, 0..head_dim]);
685 (k, v)
686 })
687 .collect();
688
689 assert_eq!(kv_blocks.len(), 2);
690 }
691
692 #[test]
693 fn test_paged_attention_forward() {
694 let device = <NdArray<f32> as Backend>::Device::default();
695 let mut cache = PagedKVCache::<NdArray<f32>>::new(4, 1, 2, 4, &device);
696 let seq_id = cache.allocate_sequence();
697 let attention = PagedAttention::new(FlashAttentionConfig::default());
698
699 let q = Tensor::<NdArray<f32>, 4>::random(
700 [1, 2, 4, 4],
701 burn::tensor::Distribution::Normal(0.0, 0.5),
702 &device,
703 );
704 let k = Tensor::<NdArray<f32>, 4>::random(
705 [1, 2, 4, 4],
706 burn::tensor::Distribution::Normal(0.0, 0.5),
707 &device,
708 );
709 let v = Tensor::<NdArray<f32>, 4>::random(
710 [1, 2, 4, 4],
711 burn::tensor::Distribution::Normal(0.0, 0.5),
712 &device,
713 );
714
715 let output = attention
716 .forward(&mut cache, 0, seq_id, q.clone(), k, v, true)
717 .expect("paged attention forward");
718 assert_eq!(output.dims(), [1, 2, 4, 4]);
719
720 let q2 = Tensor::<NdArray<f32>, 4>::random(
721 [1, 2, 2, 4],
722 burn::tensor::Distribution::Normal(0.0, 0.5),
723 &device,
724 );
725 let k2 = Tensor::<NdArray<f32>, 4>::random(
726 [1, 2, 2, 4],
727 burn::tensor::Distribution::Normal(0.0, 0.5),
728 &device,
729 );
730 let v2 = Tensor::<NdArray<f32>, 4>::random(
731 [1, 2, 2, 4],
732 burn::tensor::Distribution::Normal(0.0, 0.5),
733 &device,
734 );
735
736 let output2 = attention
737 .forward_fused(&mut cache, 0, seq_id, q2, k2, v2, true)
738 .expect("paged attention fused");
739 assert_eq!(output2.dims(), [1, 2, 2, 4]);
740 assert_eq!(cache.seq_len(0, seq_id).expect("seq_len"), 6);
741 }
742}