interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-kv-cache / src / lib.rs

2430 lines · 86665 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Native Paged KV-Cache Manager with physical unified-memory tensors,
17//! reference-counted copy-on-write branching, and prefix caching.
18//!
19//! Who owns each KV buffer, who may write it when, what makes a write visible
20//! to the GPU, and which bounds, cancellation, reuse and restart rules exist
21//! (with the platform each claim was tested on): see `OWNERSHIP.md` next to
22//! this crate's `Cargo.toml`. The design authority is sovereign-core
23//! `docs/adr/0003-persistent-kv-identity-storage-contract-and-ownership.md`.
24
25use parking_lot::RwLock;
26use serde::{Deserialize, Serialize};
27use std::collections::HashMap;
28use std::sync::Arc;
29
30pub type BlockId = usize;
31
32/// Reserved arena slot for storage holders: the high 32 bits of a sequence id.
33/// The scheduler arena grows one slot at a time from 0, so it never reaches
34/// this slot in practice (ADR 0003 section 5.2).
35pub const HOLDER_SLOT: u32 = u32::MAX;
36
37/// Sequence id of the holder for storage job `job` (`HOLDER_SLOT << 32 | job`).
38/// Refused for job 0 (generation zero is invalid) and for jobs past `u32::MAX`
39/// (they would wrap onto another live holder).
40pub fn holder_id(job: u64) -> Result<u64, String> {
41 if job == 0 || job > u32::MAX as u64 {
42 return Err(format!("holder job id {job} outside 1..=u32::MAX"));
43 }
44 Ok(((HOLDER_SLOT as u64) << 32) | job)
45}
46
47/// True when `id` lies in the reserved holder slot.
48pub fn is_holder_id(id: u64) -> bool {
49 (id >> 32) as u32 == HOLDER_SLOT
50}
51
52/// What `assemble_table` does with a partial block at the end of the last
53/// holder. DOCS SILENT in ADR 0003: the ADR names the parameter only in
54/// CUTS.md; this is the narrowest rule that is well defined. Only the last
55/// holder may end in a partial block; earlier ones never may.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum SuffixPolicy {
58 /// Refuse an assembly whose last holder ends in a partial block.
59 FullBlocksOnly,
60 /// Accept a partial block at the end of the last holder (a parked tail).
61 AllowPartialTail,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
65pub enum KvDType {
66 Fp4,
67 Fp8,
68 Bf16,
69 Fp16,
70 Fp32,
71}
72
73impl Default for KvDType {
74 /// Full precision: no rounding anywhere (the pre-sc#464 behaviour).
75 fn default() -> Self {
76 KvDType::Fp32
77 }
78}
79
80/// Rounds `values` in place to what a pool of `dtype` would store, so a K/V vector
81/// has the same bits whether a reader takes it from the dense per-sequence cache or
82/// gathers it back from the pool (PREFILL-E2E-2: a prompt prefilled in chunks must
83/// be bit-identical to the same prompt prefilled in one shot). Called once, where
84/// the vector is produced; `write_token_kv` applies the same rounding on the pool
85/// side, so the pool write is a no-op re-rounding. `Fp32` leaves the values alone.
86/// Element types this crate cannot store on the host path are a loud error, as in
87/// `write_token_kv`.
88pub fn round_to_dtype_in_place(dtype: KvDType, values: &mut [f32]) {
89 match dtype {
90 KvDType::Fp32 => {}
91 KvDType::Bf16 => {
92 for x in values.iter_mut() {
93 *x = bf16_bits_to_f32(f32_to_bf16_bits(*x));
94 }
95 }
96 other => panic!(
97 "Unsupported KvDType for round_to_dtype_in_place: {:?}",
98 other
99 ),
100 }
101}
102
103impl KvDType {
104 pub fn bytes_per_element(&self) -> f32 {
105 match self {
106 KvDType::Fp4 => 0.5,
107 KvDType::Fp8 => 1.0,
108 KvDType::Bf16 | KvDType::Fp16 => 2.0,
109 KvDType::Fp32 => 4.0,
110 }
111 }
112}
113
114/// Exact IEEE-754 / bfloat16 round-to-nearest-even conversion.
115#[inline]
116pub fn f32_to_bf16_bits(val: f32) -> u16 {
117 let u = val.to_bits();
118 let lsb = (u >> 16) & 1;
119 let rounding_bias = 0x7fff + lsb;
120 ((u.wrapping_add(rounding_bias)) >> 16) as u16
121}
122
123#[inline]
124pub fn bf16_bits_to_f32(bits: u16) -> f32 {
125 f32::from_bits((bits as u32) << 16)
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct KvPoolConfig {
130 pub num_blocks: usize,
131 pub block_size: usize,
132 pub num_layers: usize,
133 pub num_kv_heads: usize,
134 pub head_dim: usize,
135 pub dtype: KvDType,
136}
137
138impl KvPoolConfig {
139 pub fn for_tinyllama(num_blocks: usize, block_size: usize, dtype: KvDType) -> Self {
140 Self {
141 num_blocks,
142 block_size,
143 num_layers: 22,
144 num_kv_heads: 4,
145 head_dim: 64,
146 dtype,
147 }
148 }
149
150 pub fn for_qwen2_5_7b(num_blocks: usize, block_size: usize, dtype: KvDType) -> Self {
151 Self {
152 num_blocks,
153 block_size,
154 num_layers: 28,
155 num_kv_heads: 4,
156 head_dim: 128,
157 dtype,
158 }
159 }
160
161 pub fn for_nemotron_30b(num_blocks: usize, block_size: usize, dtype: KvDType) -> Self {
162 Self {
163 num_blocks,
164 block_size,
165 num_layers: 48,
166 num_kv_heads: 8,
167 head_dim: 128,
168 dtype,
169 }
170 }
171
172 pub fn for_model(
173 num_blocks: usize,
174 block_size: usize,
175 num_layers: usize,
176 num_kv_heads: usize,
177 head_dim: usize,
178 dtype: KvDType,
179 ) -> Self {
180 Self {
181 num_blocks,
182 block_size,
183 num_layers,
184 num_kv_heads,
185 head_dim,
186 dtype,
187 }
188 }
189
190 pub fn bytes_per_block(&self) -> usize {
191 let elements = 2 * self.num_layers * self.block_size * self.num_kv_heads * self.head_dim;
192 (elements as f32 * self.dtype.bytes_per_element()).ceil() as usize
193 }
194
195 pub fn total_bytes(&self) -> usize {
196 self.num_blocks * self.bytes_per_block()
197 }
198
199 pub fn layout(&self) -> Result<KvLayout, String> {
200 KvLayout::from_config(self)
201 }
202
203 pub fn layout_desc(&self) -> Result<KvLayoutDesc, String> {
204 Ok(self.layout()?.to_desc())
205 }
206}
207
208/// Explicit C-ABI layout descriptor matching the GPU kernel parameterization.
209#[repr(C)]
210#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
211pub struct KvLayoutDesc {
212 pub block_stride_bytes: u64,
213 pub layer_stride_bytes: u64,
214 pub kv_plane_stride_bytes: u64,
215 pub token_stride_bytes: u64,
216 pub head_stride_bytes: u64,
217
218 pub pool_bytes: u64,
219 pub num_blocks: u32,
220 pub num_layers: u32,
221 pub block_size: u32,
222}
223
224/// Canonical physical layout definition owning authoritative stride mathematics.
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
226pub struct KvLayout {
227 pub block_stride_bytes: usize,
228 pub layer_stride_bytes: usize,
229 pub kv_plane_stride_bytes: usize,
230 pub token_stride_bytes: usize,
231 pub head_stride_bytes: usize,
232 pub element_bytes: usize,
233 pub total_bytes: usize,
234 pub num_blocks: usize,
235 pub num_layers: usize,
236 pub block_size: usize,
237 pub num_kv_heads: usize,
238 pub head_dim: usize,
239}
240
241impl KvLayout {
242 pub fn for_bf16(config: &KvPoolConfig) -> Result<Self, String> {
243 if config.dtype != KvDType::Bf16 {
244 return Err(format!(
245 "Canonical layout requires BF16, got {:?}",
246 config.dtype
247 ));
248 }
249 Self::from_config(config)
250 }
251
252 pub fn from_config(config: &KvPoolConfig) -> Result<Self, String> {
253 let element_bytes = match config.dtype {
254 KvDType::Bf16 | KvDType::Fp16 => 2usize,
255 KvDType::Fp32 => 4usize,
256 KvDType::Fp8 => 1usize,
257 KvDType::Fp4 => {
258 return Err("Fp4 sub-byte stride requires packed layout".to_string());
259 }
260 };
261
262 let overflow = |what: &str| format!("KV layout size overflow computing {what}");
263 let head_stride_bytes = config
264 .head_dim
265 .checked_mul(element_bytes)
266 .ok_or_else(|| overflow("head_stride_bytes"))?;
267 let token_stride_bytes = config
268 .num_kv_heads
269 .checked_mul(head_stride_bytes)
270 .ok_or_else(|| overflow("token_stride_bytes"))?;
271 let kv_plane_stride_bytes = config
272 .block_size
273 .checked_mul(token_stride_bytes)
274 .ok_or_else(|| overflow("kv_plane_stride_bytes"))?;
275 let layer_stride_bytes = kv_plane_stride_bytes
276 .checked_mul(2)
277 .ok_or_else(|| overflow("layer_stride_bytes"))?;
278 let block_stride_bytes = config
279 .num_layers
280 .checked_mul(layer_stride_bytes)
281 .ok_or_else(|| overflow("block_stride_bytes"))?;
282 let total_bytes = config
283 .num_blocks
284 .checked_mul(block_stride_bytes)
285 .ok_or_else(|| overflow("total_bytes"))?;
286
287 Ok(Self {
288 block_stride_bytes,
289 layer_stride_bytes,
290 kv_plane_stride_bytes,
291 token_stride_bytes,
292 head_stride_bytes,
293 element_bytes,
294 total_bytes,
295 num_blocks: config.num_blocks,
296 num_layers: config.num_layers,
297 block_size: config.block_size,
298 num_kv_heads: config.num_kv_heads,
299 head_dim: config.head_dim,
300 })
301 }
302
303 #[inline]
304 pub fn element_offset(
305 &self,
306 block: usize,
307 layer: usize,
308 is_value: bool,
309 token: usize,
310 head: usize,
311 dim: usize,
312 ) -> usize {
313 assert!(block < self.num_blocks, "Block {} out of range", block);
314 assert!(layer < self.num_layers, "Layer {} out of range", layer);
315 assert!(token < self.block_size, "Token {} out of range", token);
316 assert!(head < self.num_kv_heads, "Head {} out of range", head);
317 assert!(dim < self.head_dim, "Dim {} out of range", dim);
318
319 block * self.block_stride_bytes
320 + layer * self.layer_stride_bytes
321 + usize::from(is_value) * self.kv_plane_stride_bytes
322 + token * self.token_stride_bytes
323 + head * self.head_stride_bytes
324 + dim * self.element_bytes
325 }
326
327 #[inline]
328 pub fn token_plane_offset(
329 &self,
330 block: usize,
331 layer: usize,
332 is_value: bool,
333 token: usize,
334 ) -> usize {
335 assert!(block < self.num_blocks, "Block {} out of range", block);
336 assert!(layer < self.num_layers, "Layer {} out of range", layer);
337 assert!(token < self.block_size, "Token {} out of range", token);
338
339 block * self.block_stride_bytes
340 + layer * self.layer_stride_bytes
341 + usize::from(is_value) * self.kv_plane_stride_bytes
342 + token * self.token_stride_bytes
343 }
344
345 #[inline]
346 pub fn block_offset(&self, block: usize) -> usize {
347 assert!(block < self.num_blocks, "Block {} out of range", block);
348 block * self.block_stride_bytes
349 }
350
351 pub fn to_desc(&self) -> KvLayoutDesc {
352 KvLayoutDesc {
353 block_stride_bytes: self.block_stride_bytes as u64,
354 layer_stride_bytes: self.layer_stride_bytes as u64,
355 kv_plane_stride_bytes: self.kv_plane_stride_bytes as u64,
356 token_stride_bytes: self.token_stride_bytes as u64,
357 head_stride_bytes: self.head_stride_bytes as u64,
358 pool_bytes: self.total_bytes as u64,
359 num_blocks: self.num_blocks as u32,
360 num_layers: self.num_layers as u32,
361 block_size: self.block_size as u32,
362 }
363 }
364}
365
366pub use aien_platform::{BufferRegion, MemoryDevice};
367
368#[cfg(target_os = "linux")]
369pub type DefaultUnifiedBuffer = aien_platform_linux::LinuxUnifiedBuffer;
370#[cfg(not(target_os = "linux"))]
371pub type DefaultUnifiedBuffer = HeapUnifiedBuffer;
372
373/// Wraps memory another allocator owns (the omega GPU engine's resident KV pool: GPU-uncached,
374/// host-visible, chip address equal to the host address) as the default unified buffer, so the
375/// pooled KV manager can live in it and the paged attention can read it in place. `release` runs
376/// exactly once, when the buffer is dropped.
377///
378/// # Safety
379/// `ptr` must stay valid, readable and writable for `len` bytes until `release` runs, and nothing
380/// else may free it.
381#[cfg(target_os = "linux")]
382pub unsafe fn external_default_buffer(
383 ptr: *mut u8,
384 len: usize,
385 device_address: u64,
386 release: Box<dyn FnOnce() + Send + Sync>,
387) -> Result<DefaultUnifiedBuffer, String> {
388 aien_platform_linux::LinuxUnifiedBuffer::from_external(
389 ptr,
390 len,
391 aien_platform::DeviceAddress(device_address),
392 release,
393 )
394 .map_err(|e| format!("external KV buffer: {e:?}"))
395}
396
397/// Fallback standard host buffer implementing UnifiedBuffer for testing.
398pub struct HeapUnifiedBuffer {
399 ptr: *mut u8,
400 layout: std::alloc::Layout,
401 len: usize,
402}
403
404unsafe impl Send for HeapUnifiedBuffer {}
405unsafe impl Sync for HeapUnifiedBuffer {}
406
407impl HeapUnifiedBuffer {
408 pub fn allocate(size: usize, align: usize) -> Result<Self, String> {
409 let align = align.max(std::mem::align_of::<usize>());
410 let layout = std::alloc::Layout::from_size_align(size, align)
411 .map_err(|e| format!("Invalid layout: {}", e))?;
412 let ptr = unsafe { std::alloc::alloc_zeroed(layout) };
413 if ptr.is_null() {
414 return Err(format!("Failed to allocate {} bytes on heap", size));
415 }
416 Ok(Self {
417 ptr,
418 layout,
419 len: size,
420 })
421 }
422}
423
424impl aien_platform::UnifiedBuffer for HeapUnifiedBuffer {
425 fn len(&self) -> usize {
426 self.len
427 }
428 fn device_address(&self) -> aien_platform::DeviceAddress {
429 aien_platform::DeviceAddress(self.ptr as u64)
430 }
431 fn as_ptr(&self) -> *const u8 {
432 self.ptr
433 }
434 fn as_mut_ptr(&mut self) -> *mut u8 {
435 self.ptr
436 }
437}
438
439impl Drop for HeapUnifiedBuffer {
440 fn drop(&mut self) {
441 if !self.ptr.is_null() && self.layout.size() > 0 {
442 unsafe {
443 std::alloc::dealloc(self.ptr, self.layout);
444 }
445 }
446 }
447}
448
449/// Physical unified-memory KV tensor pool owning layout interpretation over an underlying UnifiedBuffer.
450pub struct UnifiedKvTensorPool<B: aien_platform::UnifiedBuffer = DefaultUnifiedBuffer> {
451 config: KvPoolConfig,
452 layout: KvLayout,
453 buffer: B,
454}
455
456unsafe impl<B: aien_platform::UnifiedBuffer + Send> Send for UnifiedKvTensorPool<B> {}
457unsafe impl<B: aien_platform::UnifiedBuffer + Sync> Sync for UnifiedKvTensorPool<B> {}
458
459impl<B: aien_platform::UnifiedBuffer> UnifiedKvTensorPool<B> {
460 pub fn new(config: KvPoolConfig, buffer: B) -> Result<Self, String> {
461 let layout = KvLayout::from_config(&config)?;
462 if buffer.len() < layout.total_bytes {
463 return Err(format!(
464 "Buffer size {} is smaller than required KV tensor pool size {}",
465 buffer.len(),
466 layout.total_bytes
467 ));
468 }
469
470 Ok(Self {
471 config,
472 layout,
473 buffer,
474 })
475 }
476
477 pub fn config(&self) -> &KvPoolConfig {
478 &self.config
479 }
480
481 pub fn layout(&self) -> &KvLayout {
482 &self.layout
483 }
484
485 pub fn layout_desc(&self) -> KvLayoutDesc {
486 self.layout.to_desc()
487 }
488
489 pub fn total_bytes(&self) -> usize {
490 self.layout.total_bytes
491 }
492
493 pub fn block_bytes(&self) -> usize {
494 self.layout.block_stride_bytes
495 }
496
497 pub fn base_ptr(&self) -> *const u8 {
498 self.buffer.as_ptr()
499 }
500
501 pub fn base_mut_ptr(&mut self) -> *mut u8 {
502 self.buffer.as_mut_ptr()
503 }
504
505 pub fn device_address(&self) -> aien_platform::DeviceAddress {
506 self.buffer.device_address()
507 }
508
509 pub fn block_device_address(&self, block_id: BlockId) -> aien_platform::DeviceAddress {
510 let offset = self.layout.block_offset(block_id);
511 aien_platform::DeviceAddress(self.buffer.device_address().0 + offset as u64)
512 }
513
514 pub fn element_offset(
515 &self,
516 block_id: BlockId,
517 layer_idx: usize,
518 is_value: bool,
519 token_in_block: usize,
520 ) -> usize {
521 self.layout
522 .token_plane_offset(block_id, layer_idx, is_value, token_in_block)
523 }
524
525 pub fn block_region(&self, block_id: BlockId) -> BufferRegion {
526 let offset = self.layout.block_offset(block_id);
527 BufferRegion {
528 address: aien_platform::DeviceAddress(self.buffer.device_address().0 + offset as u64),
529 offset,
530 len: self.layout.block_stride_bytes,
531 }
532 }
533
534 pub fn buffer(&self) -> &B {
535 &self.buffer
536 }
537
538 pub fn buffer_mut(&mut self) -> &mut B {
539 &mut self.buffer
540 }
541
542 pub fn copy_block(&mut self, src_block: BlockId, dst_block: BlockId) {
543 if src_block == dst_block {
544 return;
545 }
546 let src_offset = self.layout.block_offset(src_block);
547 let dst_offset = self.layout.block_offset(dst_block);
548 let len = self.layout.block_stride_bytes;
549 unsafe {
550 let base = self.buffer.as_mut_ptr();
551 let src = base.add(src_offset);
552 let dst = base.add(dst_offset);
553 std::ptr::copy(src, dst, len);
554 }
555 }
556
557 pub fn zero_block(&mut self, block_id: BlockId) {
558 let offset = self.layout.block_offset(block_id);
559 let len = self.layout.block_stride_bytes;
560 unsafe {
561 let ptr = self.buffer.as_mut_ptr().add(offset);
562 std::ptr::write_bytes(ptr, 0, len);
563 }
564 }
565
566 pub fn copy_block_device<M: MemoryDevice>(
567 &self,
568 device: &M,
569 src_block: BlockId,
570 dst_block: BlockId,
571 ) -> Result<aien_platform::Fence, aien_platform::PlatformError> {
572 let src_region = self.block_region(src_block);
573 let dst_region = self.block_region(dst_block);
574 device.copy(src_region, dst_region)
575 }
576
577 pub fn zero_block_device<M: MemoryDevice>(
578 &self,
579 device: &M,
580 block_id: BlockId,
581 ) -> Result<aien_platform::Fence, aien_platform::PlatformError> {
582 let region = self.block_region(block_id);
583 device.zero(region)
584 }
585
586 pub fn write_token_kv(
587 &mut self,
588 block_id: BlockId,
589 layer_idx: usize,
590 token_in_block: usize,
591 k: &[f32],
592 v: &[f32],
593 ) {
594 let kv_dim = self.config.num_kv_heads * self.config.head_dim;
595 assert_eq!(k.len(), kv_dim, "K vector length must equal kv_dim");
596 assert_eq!(v.len(), kv_dim, "V vector length must equal kv_dim");
597
598 let k_offset = self
599 .layout
600 .token_plane_offset(block_id, layer_idx, false, token_in_block);
601 let v_offset = self
602 .layout
603 .token_plane_offset(block_id, layer_idx, true, token_in_block);
604
605 match self.config.dtype {
606 KvDType::Fp32 => unsafe {
607 let k_ptr = self.buffer.as_mut_ptr().add(k_offset) as *mut f32;
608 let v_ptr = self.buffer.as_mut_ptr().add(v_offset) as *mut f32;
609 std::ptr::copy_nonoverlapping(k.as_ptr(), k_ptr, kv_dim);
610 std::ptr::copy_nonoverlapping(v.as_ptr(), v_ptr, kv_dim);
611 },
612 KvDType::Bf16 => unsafe {
613 let k_ptr = self.buffer.as_mut_ptr().add(k_offset) as *mut u16;
614 let v_ptr = self.buffer.as_mut_ptr().add(v_offset) as *mut u16;
615 for i in 0..kv_dim {
616 *k_ptr.add(i) = f32_to_bf16_bits(k[i]);
617 *v_ptr.add(i) = f32_to_bf16_bits(v[i]);
618 }
619 },
620 other => panic!("Unsupported KvDType for write_token_kv: {:?}", other),
621 }
622 }
623
624 pub fn read_token_kv(
625 &self,
626 block_id: BlockId,
627 layer_idx: usize,
628 token_in_block: usize,
629 k_out: &mut [f32],
630 v_out: &mut [f32],
631 ) {
632 let kv_dim = self.config.num_kv_heads * self.config.head_dim;
633 assert_eq!(k_out.len(), kv_dim, "K_out length must equal kv_dim");
634 assert_eq!(v_out.len(), kv_dim, "V_out length must equal kv_dim");
635
636 let k_offset = self
637 .layout
638 .token_plane_offset(block_id, layer_idx, false, token_in_block);
639 let v_offset = self
640 .layout
641 .token_plane_offset(block_id, layer_idx, true, token_in_block);
642
643 match self.config.dtype {
644 KvDType::Fp32 => unsafe {
645 let k_ptr = self.buffer.as_ptr().add(k_offset) as *const f32;
646 let v_ptr = self.buffer.as_ptr().add(v_offset) as *const f32;
647 std::ptr::copy_nonoverlapping(k_ptr, k_out.as_mut_ptr(), kv_dim);
648 std::ptr::copy_nonoverlapping(v_ptr, v_out.as_mut_ptr(), kv_dim);
649 },
650 KvDType::Bf16 => unsafe {
651 let k_ptr = self.buffer.as_ptr().add(k_offset) as *const u16;
652 let v_ptr = self.buffer.as_ptr().add(v_offset) as *const u16;
653 for i in 0..kv_dim {
654 k_out[i] = bf16_bits_to_f32(*k_ptr.add(i));
655 v_out[i] = bf16_bits_to_f32(*v_ptr.add(i));
656 }
657 },
658 other => panic!("Unsupported KvDType for read_token_kv: {:?}", other),
659 }
660 }
661
662 pub fn gather_layer_kv(
663 &self,
664 block_table: &[BlockId],
665 total_tokens: usize,
666 layer_idx: usize,
667 ) -> (Vec<f32>, Vec<f32>) {
668 let kv_dim = self.config.num_kv_heads * self.config.head_dim;
669 let mut k_gathered = Vec::with_capacity(total_tokens * kv_dim);
670 let mut v_gathered = Vec::with_capacity(total_tokens * kv_dim);
671
672 let mut token_k = vec![0.0f32; kv_dim];
673 let mut token_v = vec![0.0f32; kv_dim];
674
675 let mut tokens_read = 0;
676 for &blk in block_table {
677 let tokens_in_this_block = (total_tokens - tokens_read).min(self.config.block_size);
678 for tok_idx in 0..tokens_in_this_block {
679 self.read_token_kv(blk, layer_idx, tok_idx, &mut token_k, &mut token_v);
680 k_gathered.extend_from_slice(&token_k);
681 v_gathered.extend_from_slice(&token_v);
682 }
683 tokens_read += tokens_in_this_block;
684 if tokens_read >= total_tokens {
685 break;
686 }
687 }
688
689 (k_gathered, v_gathered)
690 }
691}
692
693impl UnifiedKvTensorPool<DefaultUnifiedBuffer> {
694 pub fn allocate(config: KvPoolConfig) -> Result<Self, String> {
695 let layout = KvLayout::from_config(&config)?;
696 #[cfg(target_os = "linux")]
697 {
698 let platform_layout = aien_platform::BufferLayout::new(layout.total_bytes, 256);
699 let dev = aien_platform_linux::LinuxComputeDevice::new();
700 let kind = dev.preferred_memory_kind();
701 let buf = aien_platform_linux::LinuxUnifiedBuffer::allocate(
702 platform_layout,
703 kind,
704 aien_platform_linux::ResidencyPolicy::FaultIn,
705 )
706 .map_err(|e| format!("LinuxUnifiedBuffer allocation failed: {:?}", e))?;
707 Self::new(config, buf)
708 }
709 #[cfg(not(target_os = "linux"))]
710 {
711 let buf = HeapUnifiedBuffer::allocate(layout.total_bytes, 256)?;
712 Self::new(config, buf)
713 }
714 }
715}
716
717impl UnifiedKvTensorPool<HeapUnifiedBuffer> {
718 pub fn allocate_heap(config: KvPoolConfig) -> Result<Self, String> {
719 let layout = KvLayout::from_config(&config)?;
720 let buf = HeapUnifiedBuffer::allocate(layout.total_bytes, 256)?;
721 Self::new(config, buf)
722 }
723}
724
725#[derive(Debug, Clone, Serialize, Deserialize)]
726pub struct KvBlock {
727 pub block_id: BlockId,
728 pub ref_count: usize,
729 pub num_tokens: usize,
730 pub is_shared: bool,
731}
732
733/// Readiness of the K/V content behind a block table.
734///
735/// Allocated is not computed: `allocate_sequence` only reserves and zeroes
736/// blocks. Only the prefill completion fence (the point where the model
737/// forward over the prompt span returned Ok, see `complete_prefill`) may move
738/// a table to `PrefillReady`. Decode and sharing require `PrefillReady` or
739/// `SharedFrozen`. Reclaimed is the absence of the table (`free_sequence`).
740#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
741pub enum PrefillState {
742 /// Blocks reserved and zeroed; no K/V computed.
743 #[default]
744 Allocated,
745 /// A model prefill over the prompt span has been issued but has not completed.
746 PrefillPending,
747 /// The completion fence fired: K/V for the prompt span is computed.
748 PrefillReady,
749 /// Ready and shared with at least one fork; the prefix is immutable.
750 SharedFrozen,
751}
752
753impl PrefillState {
754 /// True only when the prompt K/V has been computed by a completed prefill.
755 pub fn is_ready(self) -> bool {
756 matches!(
757 self,
758 PrefillState::PrefillReady | PrefillState::SharedFrozen
759 )
760 }
761}
762
763/// Typed refusal from the prefill readiness gate.
764#[derive(Debug, Clone, Copy, PartialEq, Eq)]
765pub enum PrefillGateError {
766 /// No block table exists for this sequence.
767 UnknownSequence { seq_id: u64 },
768 /// The blocks are allocated but their K/V is not computed yet.
769 NotReady { seq_id: u64, state: PrefillState },
770 /// The completion fence fired for a table that never had a prefill issued.
771 FenceWithoutPending { seq_id: u64, state: PrefillState },
772}
773
774impl std::fmt::Display for PrefillGateError {
775 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
776 match self {
777 PrefillGateError::UnknownSequence { seq_id } => {
778 write!(f, "prefill gate: sequence {} has no block table", seq_id)
779 }
780 PrefillGateError::NotReady { seq_id, state } => write!(
781 f,
782 "prefill gate: sequence {} blocks are {:?}, not PrefillReady; refusing to share or decode",
783 seq_id, state
784 ),
785 PrefillGateError::FenceWithoutPending { seq_id, state } => write!(
786 f,
787 "prefill gate: completion fence for sequence {} in state {:?} without a pending prefill",
788 seq_id, state
789 ),
790 }
791 }
792}
793
794impl std::error::Error for PrefillGateError {}
795
796#[derive(Debug, Clone, Default, Serialize, Deserialize)]
797pub struct BlockTable {
798 pub sequence_id: u64,
799 pub block_ids: Vec<BlockId>,
800 pub total_tokens: usize,
801 /// Whether the K/V behind `block_ids` has been computed. Defaults to
802 /// `Allocated` (also for tables serialized before this field existed).
803 #[serde(default)]
804 pub prefill_state: PrefillState,
805}
806
807impl BlockTable {
808 /// True only when a completed prefill computed this table's prompt K/V.
809 pub fn is_prefill_ready(&self) -> bool {
810 self.prefill_state.is_ready()
811 }
812}
813
814#[derive(Debug, Clone)]
815pub struct KvTransactionSnapshot {
816 pub free_blocks: Vec<BlockId>,
817 pub blocks: Vec<KvBlock>,
818 pub sequence_tables: HashMap<u64, BlockTable>,
819 pub prefix_cache: HashMap<Vec<u32>, BlockId>,
820 pub cow_faults: usize,
821}
822
823#[derive(Debug)]
824pub struct KvTransaction {
825 snapshot: Option<KvTransactionSnapshot>,
826 committed: bool,
827}
828
829impl KvTransaction {
830 pub fn new(snapshot: KvTransactionSnapshot) -> Self {
831 Self {
832 snapshot: Some(snapshot),
833 committed: false,
834 }
835 }
836
837 pub fn commit(&mut self) {
838 self.committed = true;
839 self.snapshot = None;
840 }
841
842 pub fn is_committed(&self) -> bool {
843 self.committed
844 }
845
846 pub fn rollback<B: aien_platform::UnifiedBuffer>(&mut self, manager: &mut AienKvManager<B>) {
847 if !self.committed {
848 if let Some(snapshot) = self.snapshot.take() {
849 manager.free_blocks = snapshot.free_blocks;
850 manager.blocks = snapshot.blocks;
851 manager.sequence_tables = snapshot.sequence_tables;
852 manager.prefix_cache = snapshot.prefix_cache;
853 manager.cow_faults = snapshot.cow_faults;
854 }
855 self.committed = true;
856 }
857 }
858}
859
860#[derive(Debug)]
861pub struct TokenReservation {
862 pub seq_id: u64,
863 pub block_id: BlockId,
864 pub slot: usize,
865 pub original_block_id: Option<BlockId>,
866 pub was_cow: bool,
867 pub tx: Option<KvTransaction>,
868}
869
870#[derive(Debug, Clone, Default, Serialize, Deserialize)]
871pub struct KvMetrics {
872 pub physical_pages: usize,
873 pub logical_pages: usize,
874 pub shared_pages: usize,
875 pub private_pages: usize,
876 pub cow_faults: usize,
877 pub bytes_saved_vs_full_copy: usize,
878 pub used_blocks: usize,
879}
880
881/// The block allocator, block tables, refcounts and prefix cache, plus the
882/// physical pool the K/V bytes live in.
883///
884/// It has no lock of its own: every caller shares one manager as
885/// [`SharedKvManager`] and takes its write guard for any change. Every new
886/// block is zeroed before use, a block shared by a fork is copied before an
887/// append writes into it, and a block returns to the free list only when its
888/// refcount reaches zero. Ownership, platforms and evidence: `OWNERSHIP.md`
889/// in this crate.
890pub struct AienKvManager<B: aien_platform::UnifiedBuffer = DefaultUnifiedBuffer> {
891 total_blocks: usize,
892 block_size: usize,
893 free_blocks: Vec<BlockId>,
894 blocks: Vec<KvBlock>,
895 sequence_tables: HashMap<u64, BlockTable>,
896 #[allow(dead_code)]
897 prefix_cache: HashMap<Vec<u32>, BlockId>,
898 tensor_pool: Option<UnifiedKvTensorPool<B>>,
899 pub cow_faults: usize,
900}
901
902impl AienKvManager<DefaultUnifiedBuffer> {
903 pub fn new(total_blocks: usize, block_size: usize) -> Self {
904 let mut free_blocks = Vec::with_capacity(total_blocks);
905 let mut blocks = Vec::with_capacity(total_blocks);
906
907 for id in (0..total_blocks).rev() {
908 free_blocks.push(id);
909 }
910
911 for id in 0..total_blocks {
912 blocks.push(KvBlock {
913 block_id: id,
914 ref_count: 0,
915 num_tokens: 0,
916 is_shared: false,
917 });
918 }
919
920 Self {
921 total_blocks,
922 block_size,
923 free_blocks,
924 blocks,
925 sequence_tables: HashMap::new(),
926 prefix_cache: HashMap::new(),
927 tensor_pool: None,
928 cow_faults: 0,
929 }
930 }
931
932 pub fn new_with_pool(
933 total_blocks: usize,
934 block_size: usize,
935 config: KvPoolConfig,
936 ) -> Result<Self, String> {
937 let mut mgr = Self::new(total_blocks, block_size);
938 mgr.attach_tensor_pool(config)?;
939 Ok(mgr)
940 }
941
942 pub fn with_tensor_pool(
943 total_blocks: usize,
944 block_size: usize,
945 config: KvPoolConfig,
946 ) -> Result<Self, String> {
947 Self::new_with_pool(total_blocks, block_size, config)
948 }
949
950 pub fn attach_tensor_pool(&mut self, config: KvPoolConfig) -> Result<(), String> {
951 let pool = UnifiedKvTensorPool::allocate(config)?;
952 self.tensor_pool = Some(pool);
953 Ok(())
954 }
955
956 /// `new_with_pool` over a buffer the caller already holds (the GPU engine's resident KV
957 /// pool, see `external_default_buffer`); `buffer.len()` must cover the layout.
958 pub fn new_with_pool_buffer(
959 total_blocks: usize,
960 block_size: usize,
961 config: KvPoolConfig,
962 buffer: DefaultUnifiedBuffer,
963 ) -> Result<Self, String> {
964 let mut mgr = Self::new(total_blocks, block_size);
965 mgr.tensor_pool = Some(UnifiedKvTensorPool::new(config, buffer)?);
966 Ok(mgr)
967 }
968}
969
970#[cfg(target_os = "linux")]
971impl AienKvManager<HeapUnifiedBuffer> {
972 pub fn new_heap(total_blocks: usize, block_size: usize) -> Self {
973 let mut free_blocks = Vec::with_capacity(total_blocks);
974 let mut blocks = Vec::with_capacity(total_blocks);
975
976 for id in (0..total_blocks).rev() {
977 free_blocks.push(id);
978 }
979
980 for id in 0..total_blocks {
981 blocks.push(KvBlock {
982 block_id: id,
983 ref_count: 0,
984 num_tokens: 0,
985 is_shared: false,
986 });
987 }
988
989 Self {
990 total_blocks,
991 block_size,
992 free_blocks,
993 blocks,
994 sequence_tables: HashMap::new(),
995 prefix_cache: HashMap::new(),
996 tensor_pool: None,
997 cow_faults: 0,
998 }
999 }
1000
1001 pub fn new_with_heap_pool(
1002 total_blocks: usize,
1003 block_size: usize,
1004 config: KvPoolConfig,
1005 ) -> Result<Self, String> {
1006 let mut mgr = Self::new_heap(total_blocks, block_size);
1007 let pool = UnifiedKvTensorPool::allocate_heap(config)?;
1008 mgr.tensor_pool = Some(pool);
1009 Ok(mgr)
1010 }
1011}
1012
1013impl<B: aien_platform::UnifiedBuffer> AienKvManager<B> {
1014 pub fn with_buffer(
1015 total_blocks: usize,
1016 block_size: usize,
1017 config: KvPoolConfig,
1018 buffer: B,
1019 ) -> Result<Self, String> {
1020 let mut free_blocks = Vec::with_capacity(total_blocks);
1021 let mut blocks = Vec::with_capacity(total_blocks);
1022
1023 for id in (0..total_blocks).rev() {
1024 free_blocks.push(id);
1025 }
1026
1027 for id in 0..total_blocks {
1028 blocks.push(KvBlock {
1029 block_id: id,
1030 ref_count: 0,
1031 num_tokens: 0,
1032 is_shared: false,
1033 });
1034 }
1035
1036 let pool = UnifiedKvTensorPool::new(config, buffer)?;
1037
1038 Ok(Self {
1039 total_blocks,
1040 block_size,
1041 free_blocks,
1042 blocks,
1043 sequence_tables: HashMap::new(),
1044 prefix_cache: HashMap::new(),
1045 tensor_pool: Some(pool),
1046 cow_faults: 0,
1047 })
1048 }
1049
1050 pub fn attach_buffer(&mut self, config: KvPoolConfig, buffer: B) -> Result<(), String> {
1051 let pool = UnifiedKvTensorPool::new(config, buffer)?;
1052 self.tensor_pool = Some(pool);
1053 Ok(())
1054 }
1055
1056 pub fn available_blocks(&self) -> usize {
1057 self.free_blocks.len()
1058 }
1059
1060 pub fn debug_active_blocks(&self) -> Vec<(usize, usize, bool)> {
1061 self.blocks
1062 .iter()
1063 .enumerate()
1064 .filter(|(_, b)| b.ref_count > 0)
1065 .map(|(i, b)| (i, b.ref_count, b.is_shared))
1066 .collect()
1067 }
1068
1069 pub fn active_sequence_count(&self) -> usize {
1070 self.sequence_tables.len()
1071 }
1072
1073 pub fn fork_context(&mut self, parent_id: u64, child_id: u64) -> Result<Vec<BlockId>, String> {
1074 self.fork_sequence(parent_id, child_id)
1075 }
1076
1077 pub fn release_branch(&mut self, seq_id: u64) -> Result<(), String> {
1078 self.free_sequence(seq_id)
1079 }
1080
1081 pub fn metrics(&self) -> KvMetrics {
1082 let physical_pages = self.blocks.iter().filter(|b| b.ref_count > 0).count();
1083 let logical_pages: usize = self
1084 .sequence_tables
1085 .values()
1086 .map(|t| t.block_ids.len())
1087 .sum();
1088 let shared_pages = self.blocks.iter().filter(|b| b.ref_count > 1).count();
1089 let private_pages = self.blocks.iter().filter(|b| b.ref_count == 1).count();
1090 let bytes_per_block = self
1091 .tensor_pool
1092 .as_ref()
1093 .map(|p| p.block_bytes())
1094 .unwrap_or(0);
1095 let bytes_saved_vs_full_copy =
1096 logical_pages.saturating_sub(physical_pages) * bytes_per_block;
1097
1098 KvMetrics {
1099 physical_pages,
1100 logical_pages,
1101 shared_pages,
1102 private_pages,
1103 cow_faults: self.cow_faults,
1104 bytes_saved_vs_full_copy,
1105 used_blocks: physical_pages,
1106 }
1107 }
1108
1109 pub fn pool(&self) -> Option<&UnifiedKvTensorPool<B>> {
1110 self.tensor_pool.as_ref()
1111 }
1112
1113 pub fn pool_mut(&mut self) -> Option<&mut UnifiedKvTensorPool<B>> {
1114 self.tensor_pool.as_mut()
1115 }
1116
1117 pub fn free_block_count(&self) -> usize {
1118 self.free_blocks.len()
1119 }
1120
1121 pub fn allocated_block_count(&self) -> usize {
1122 self.total_blocks - self.free_blocks.len()
1123 }
1124
1125 pub fn allocate_block(&mut self) -> Result<BlockId, String> {
1126 let blk_id = self
1127 .free_blocks
1128 .pop()
1129 .ok_or_else(|| "Out of physical KV blocks".to_string())?;
1130 self.blocks[blk_id].ref_count = 1;
1131 self.blocks[blk_id].num_tokens = 0;
1132 self.blocks[blk_id].is_shared = false;
1133
1134 if let Some(pool) = &mut self.tensor_pool {
1135 pool.zero_block(blk_id);
1136 }
1137
1138 Ok(blk_id)
1139 }
1140
1141 pub fn allocate_sequence(
1142 &mut self,
1143 seq_id: u64,
1144 prompt_tokens: &[u32],
1145 ) -> Result<Vec<BlockId>, String> {
1146 if let Some(table) = self.sequence_tables.get(&seq_id) {
1147 return Ok(table.block_ids.clone());
1148 }
1149
1150 let num_tokens = prompt_tokens.len();
1151 let blocks_needed = num_tokens.div_ceil(self.block_size);
1152
1153 if self.free_blocks.len() < blocks_needed {
1154 return Err(format!(
1155 "Insufficient blocks: need {}, have {}",
1156 blocks_needed,
1157 self.free_blocks.len()
1158 ));
1159 }
1160
1161 let mut assigned = Vec::with_capacity(blocks_needed);
1162 let mut tokens_remaining = num_tokens;
1163
1164 for _ in 0..blocks_needed {
1165 let blk = self.allocate_block()?;
1166 let tokens_in_blk = tokens_remaining.min(self.block_size);
1167 self.blocks[blk].num_tokens = tokens_in_blk;
1168 tokens_remaining -= tokens_in_blk;
1169 assigned.push(blk);
1170 }
1171
1172 // Allocation reserves and zeroes blocks only. No K/V is computed here,
1173 // so the table starts Allocated; only the prefill completion fence
1174 // (`complete_prefill`) may mark it PrefillReady.
1175 let prefill_state = if cfg!(feature = "prefill_mutant_ready_at_alloc") {
1176 PrefillState::PrefillReady
1177 } else {
1178 PrefillState::Allocated
1179 };
1180
1181 self.sequence_tables.insert(
1182 seq_id,
1183 BlockTable {
1184 sequence_id: seq_id,
1185 block_ids: assigned.clone(),
1186 total_tokens: num_tokens,
1187 prefill_state,
1188 },
1189 );
1190
1191 Ok(assigned)
1192 }
1193
1194 /// Readiness of a sequence's K/V, or None when it has no block table.
1195 pub fn prefill_state(&self, seq_id: u64) -> Option<PrefillState> {
1196 self.sequence_tables.get(&seq_id).map(|t| t.prefill_state)
1197 }
1198
1199 /// Records that a model prefill over the prompt span has been issued.
1200 /// A ready table stays ready (its prefix K/V is already computed).
1201 pub fn mark_prefill_pending(&mut self, seq_id: u64) -> Result<(), PrefillGateError> {
1202 let table = self
1203 .sequence_tables
1204 .get_mut(&seq_id)
1205 .ok_or(PrefillGateError::UnknownSequence { seq_id })?;
1206 if !table.prefill_state.is_ready() {
1207 table.prefill_state = PrefillState::PrefillPending;
1208 }
1209 Ok(())
1210 }
1211
1212 /// The prefill completion fence: the ONLY setter of `PrefillReady`.
1213 /// Call it only after the backend forward over the whole prompt span
1214 /// returned Ok (aien-scheduler `AienScheduler::step` after
1215 /// `execute_step`, and `AienScheduler::prefill_detached`). Refuses a table
1216 /// that never had a prefill issued, so allocation alone can never become
1217 /// ready through this path.
1218 pub fn complete_prefill(&mut self, seq_id: u64) -> Result<(), PrefillGateError> {
1219 let table = self
1220 .sequence_tables
1221 .get_mut(&seq_id)
1222 .ok_or(PrefillGateError::UnknownSequence { seq_id })?;
1223 match table.prefill_state {
1224 PrefillState::PrefillPending => {
1225 table.prefill_state = PrefillState::PrefillReady;
1226 Ok(())
1227 }
1228 PrefillState::PrefillReady | PrefillState::SharedFrozen => Ok(()),
1229 state @ PrefillState::Allocated => {
1230 Err(PrefillGateError::FenceWithoutPending { seq_id, state })
1231 }
1232 }
1233 }
1234
1235 /// Gated zero-copy fork: shares the parent's blocks only when the parent
1236 /// K/V is computed (PrefillReady or SharedFrozen). Refuses with a typed
1237 /// error otherwise, so a branch can never share allocated-but-uncomputed
1238 /// blocks. On success parent and child are both SharedFrozen.
1239 pub fn fork_prefilled(
1240 &mut self,
1241 parent_id: u64,
1242 child_id: u64,
1243 ) -> Result<Vec<BlockId>, PrefillGateError> {
1244 let state = self
1245 .prefill_state(parent_id)
1246 .ok_or(PrefillGateError::UnknownSequence { seq_id: parent_id })?;
1247 if !state.is_ready() {
1248 return Err(PrefillGateError::NotReady {
1249 seq_id: parent_id,
1250 state,
1251 });
1252 }
1253 self.fork_sequence(parent_id, child_id)
1254 .map_err(|_| PrefillGateError::UnknownSequence { seq_id: parent_id })
1255 }
1256
1257 pub fn fork_sequence(&mut self, parent_id: u64, child_id: u64) -> Result<Vec<BlockId>, String> {
1258 let parent_table = self
1259 .sequence_tables
1260 .get(&parent_id)
1261 .ok_or_else(|| format!("Parent sequence {} not found", parent_id))?
1262 .clone();
1263 if parent_id == child_id {
1264 return Err(format!("Cannot fork sequence {} onto itself", parent_id));
1265 }
1266
1267 for &blk_id in &parent_table.block_ids {
1268 self.blocks[blk_id].ref_count += 1;
1269 self.blocks[blk_id].is_shared = true;
1270 }
1271
1272 // A live child id is replaced: release its old blocks (after taking the
1273 // new references, so blocks shared with the parent stay counted).
1274 if self.sequence_tables.contains_key(&child_id) {
1275 self.free_sequence(child_id)?;
1276 }
1277
1278 // Readiness travels with the blocks: a fork of a ready parent freezes
1279 // the shared prefix; a fork of an unready parent stays unready, so the
1280 // scheduler will not decode the child (use `fork_prefilled` to refuse
1281 // such a fork outright).
1282 let child_state = if parent_table.prefill_state.is_ready() {
1283 if let Some(parent) = self.sequence_tables.get_mut(&parent_id) {
1284 parent.prefill_state = PrefillState::SharedFrozen;
1285 }
1286 PrefillState::SharedFrozen
1287 } else {
1288 parent_table.prefill_state
1289 };
1290
1291 self.sequence_tables.insert(
1292 child_id,
1293 BlockTable {
1294 sequence_id: child_id,
1295 block_ids: parent_table.block_ids.clone(),
1296 total_tokens: parent_table.total_tokens,
1297 prefill_state: child_state,
1298 },
1299 );
1300
1301 Ok(parent_table.block_ids)
1302 }
1303
1304 /// Like `fork_sequence`, but `holder` shares only `n_blocks` blocks of `src`
1305 /// starting at table index `first_block`, never the whole table. This is the
1306 /// per-chunk storage reference (ADR 0003 section 5.2): a park takes one
1307 /// holder per chunk, a restore job gets one over its destination blocks, so
1308 /// freeing a holder (or a failed sibling job) can never return blocks
1309 /// another job still targets. Refused, nothing changed, for an unknown
1310 /// `src`, `src == holder`, a live `holder` table (never replaced, unlike
1311 /// `fork_sequence`), or an empty or out-of-range block span. Readiness
1312 /// travels with the blocks (a ready source gives a `SharedFrozen` holder),
1313 /// but the source's own state is left alone. `total_tokens` counts only the
1314 /// tokens inside the span.
1315 pub fn fork_range(
1316 &mut self,
1317 parent_id: u64,
1318 first_block: usize,
1319 n_blocks: usize,
1320 child_id: u64,
1321 ) -> Result<Vec<BlockId>, String> {
1322 let blocks = first_block
1323 .checked_add(n_blocks)
1324 .map(|end| first_block..end)
1325 .ok_or_else(|| "Block range overflows".to_string())?;
1326 if parent_id == child_id {
1327 return Err(format!("Cannot fork sequence {} onto itself", parent_id));
1328 }
1329 if self.sequence_tables.contains_key(&child_id) {
1330 return Err(format!("Sequence {} already has a table", child_id));
1331 }
1332 let parent = self
1333 .sequence_tables
1334 .get(&parent_id)
1335 .ok_or_else(|| format!("Parent sequence {} not found", parent_id))?;
1336 if blocks.start >= blocks.end || blocks.end > parent.block_ids.len() {
1337 return Err(format!(
1338 "Block range {}..{} invalid for sequence {} with {} blocks",
1339 blocks.start,
1340 blocks.end,
1341 parent_id,
1342 parent.block_ids.len()
1343 ));
1344 }
1345 let shared: Vec<BlockId> = parent.block_ids[blocks.clone()].to_vec();
1346 let covered_end = (blocks.end * self.block_size).min(parent.total_tokens);
1347 let total_tokens = covered_end.saturating_sub(blocks.start * self.block_size);
1348 let state = parent.prefill_state;
1349 for &b in &shared {
1350 self.blocks[b].ref_count += 1;
1351 self.blocks[b].is_shared = true;
1352 }
1353 let child_state = if state.is_ready() {
1354 PrefillState::SharedFrozen
1355 } else {
1356 state
1357 };
1358 self.sequence_tables.insert(
1359 child_id,
1360 BlockTable {
1361 sequence_id: child_id,
1362 block_ids: shared.clone(),
1363 total_tokens,
1364 prefill_state: child_state,
1365 },
1366 );
1367 Ok(shared)
1368 }
1369
1370 /// Builds the request's own table `seq` from chunk holders, in the order
1371 /// given: block lists are concatenated, one reference is added per block,
1372 /// and the table is `PrefillPending` (the suffix prefill and its fence
1373 /// follow; ADR 0003 section 5.2 and S3). The holders are not modified; the
1374 /// caller frees them afterwards. Everything is checked before anything
1375 /// changes, so any refusal leaves every holder and the pool untouched.
1376 /// Refused when `seq` is a holder id or already has a table (never
1377 /// replaced), when the list is empty or repeats a holder or a block, when an
1378 /// entry is not a live holder or its prefill is not complete (not yet
1379 /// `PrefillReady`/`SharedFrozen`), when a holder before the last ends in a
1380 /// partial block (it would leave a gap in positions), or when the last one
1381 /// does and `suffix_policy` is `FullBlocksOnly`.
1382 pub fn assemble_table(
1383 &mut self,
1384 seq: u64,
1385 holders: &[u64],
1386 suffix_policy: SuffixPolicy,
1387 ) -> Result<Vec<BlockId>, String> {
1388 if is_holder_id(seq) {
1389 return Err(format!("{seq} is a holder id, not a sequence"));
1390 }
1391 if self.sequence_tables.contains_key(&seq) {
1392 return Err(format!("Sequence {seq} already has a table"));
1393 }
1394 if holders.is_empty() {
1395 return Err("assemble_table needs at least one holder".to_string());
1396 }
1397 let bs = self.block_size;
1398 let mut ids = Vec::new();
1399 let mut seen = std::collections::HashSet::new();
1400 let mut total_tokens = 0usize;
1401 for (i, &h) in holders.iter().enumerate() {
1402 if !is_holder_id(h) {
1403 return Err(format!("{h} is not a holder id"));
1404 }
1405 let t = self
1406 .sequence_tables
1407 .get(&h)
1408 .ok_or_else(|| format!("Holder {h} not found"))?;
1409 if !t.prefill_state.is_ready() || t.block_ids.is_empty() {
1410 return Err(format!("Holder {h} is not complete"));
1411 }
1412 let full = t.total_tokens == t.block_ids.len() * bs;
1413 let last = i + 1 == holders.len();
1414 if !full && (!last || suffix_policy == SuffixPolicy::FullBlocksOnly) {
1415 return Err(format!("Holder {h} ends in a partial block"));
1416 }
1417 for &b in &t.block_ids {
1418 if !seen.insert(b) {
1419 return Err(format!("Block {b} appears twice in the assembly"));
1420 }
1421 }
1422 ids.extend_from_slice(&t.block_ids);
1423 total_tokens += t.total_tokens;
1424 }
1425 for &b in &ids {
1426 self.blocks[b].ref_count += 1;
1427 self.blocks[b].is_shared = true;
1428 }
1429 self.sequence_tables.insert(
1430 seq,
1431 BlockTable {
1432 sequence_id: seq,
1433 block_ids: ids.clone(),
1434 total_tokens,
1435 prefill_state: PrefillState::PrefillPending,
1436 },
1437 );
1438 Ok(ids)
1439 }
1440
1441 /// Moves the table of `holder` to the real sequence id `seq`, keeping every
1442 /// reference count, the free list and the readiness state exactly as they
1443 /// are (restore commit, ADR 0003 S3). Refused, nothing changed, when
1444 /// `holder` is not a holder id or has no table, when `seq` is a holder id
1445 /// or is `holder`, or when `seq` already has a table (never replaced).
1446 pub fn adopt_table(&mut self, holder: u64, seq: u64) -> Result<(), String> {
1447 if !is_holder_id(holder) {
1448 return Err(format!("{holder} is not a holder id"));
1449 }
1450 if is_holder_id(seq) || seq == holder {
1451 return Err(format!("{seq} cannot adopt a holder table"));
1452 }
1453 if self.sequence_tables.contains_key(&seq) {
1454 return Err(format!("Sequence {seq} already has a table"));
1455 }
1456 let mut table = self
1457 .sequence_tables
1458 .remove(&holder)
1459 .ok_or_else(|| format!("Holder {holder} not found"))?;
1460 table.sequence_id = seq;
1461 self.sequence_tables.insert(seq, table);
1462 Ok(())
1463 }
1464
1465 /// Distinct pool blocks referenced by at least one holder table, for the
1466 /// `kv_pool_holder_blocks` metric. A block shared by two holders counts once.
1467 pub fn holder_block_count(&self) -> usize {
1468 let mut seen = std::collections::HashSet::new();
1469 for (id, table) in &self.sequence_tables {
1470 if is_holder_id(*id) {
1471 seen.extend(table.block_ids.iter().copied());
1472 }
1473 }
1474 seen.len()
1475 }
1476
1477 pub fn append_token(&mut self, seq_id: u64) -> Result<BlockId, String> {
1478 let (block_id, _) = self.append_token_with_slot(seq_id)?;
1479 Ok(block_id)
1480 }
1481
1482 /// Reserves the next token position of `seq_id` and returns its
1483 /// `(block, slot)`, the only slot a caller may then write with
1484 /// `write_explicit_token_kv`.
1485 ///
1486 /// When the tail block is shared with another table and still has room,
1487 /// this is the copy-on-write point: a new block is allocated, the shared
1488 /// tail is copied into it on the host, and the old block's refcount drops,
1489 /// so the returned slot is always in a block this sequence owns alone. A
1490 /// full tail gets a fresh zeroed block instead. Refused, nothing changed,
1491 /// when the sequence is unknown or the pool has no free block.
1492 pub fn append_token_with_slot(&mut self, seq_id: u64) -> Result<(BlockId, usize), String> {
1493 let table = self
1494 .sequence_tables
1495 .get_mut(&seq_id)
1496 .ok_or_else(|| format!("Sequence {} not found", seq_id))?;
1497
1498 if table.block_ids.is_empty() {
1499 let new_blk = self.allocate_block()?;
1500 let table = self.sequence_tables.get_mut(&seq_id).unwrap();
1501 table.block_ids.push(new_blk);
1502 table.total_tokens = 1;
1503 self.blocks[new_blk].num_tokens = 1;
1504 return Ok((new_blk, 0));
1505 }
1506
1507 let last_blk_idx = table.block_ids.len() - 1;
1508 let last_blk_id = table.block_ids[last_blk_idx];
1509 let blk = &self.blocks[last_blk_id];
1510
1511 if blk.is_shared {
1512 if blk.num_tokens < self.block_size {
1513 // Counted only once the copy has a block: a copy-on-write refused for
1514 // an empty pool is not a fault that happened (L6-KV).
1515 let new_blk = self.allocate_block()?;
1516 self.cow_faults += 1;
1517 if let Some(pool) = &mut self.tensor_pool {
1518 pool.copy_block(last_blk_id, new_blk);
1519 }
1520 let old_blk = &mut self.blocks[last_blk_id];
1521 old_blk.ref_count -= 1;
1522 if old_blk.ref_count == 1 {
1523 old_blk.is_shared = false;
1524 }
1525
1526 let num_tokens = old_blk.num_tokens;
1527 self.blocks[new_blk].num_tokens = num_tokens + 1;
1528 self.blocks[new_blk].is_shared = false;
1529
1530 let table = self.sequence_tables.get_mut(&seq_id).unwrap();
1531 table.block_ids[last_blk_idx] = new_blk;
1532 table.total_tokens += 1;
1533 Ok((new_blk, num_tokens))
1534 } else {
1535 let new_blk = self.allocate_block()?;
1536 let table = self.sequence_tables.get_mut(&seq_id).unwrap();
1537 table.block_ids.push(new_blk);
1538 table.total_tokens += 1;
1539 self.blocks[new_blk].num_tokens = 1;
1540 self.blocks[new_blk].is_shared = false;
1541 Ok((new_blk, 0))
1542 }
1543 } else if blk.num_tokens < self.block_size {
1544 let slot = blk.num_tokens;
1545 self.blocks[last_blk_id].num_tokens += 1;
1546 table.total_tokens += 1;
1547 Ok((last_blk_id, slot))
1548 } else {
1549 let new_blk = self.allocate_block()?;
1550 let table = self.sequence_tables.get_mut(&seq_id).unwrap();
1551 table.block_ids.push(new_blk);
1552 table.total_tokens += 1;
1553 self.blocks[new_blk].num_tokens = 1;
1554 Ok((new_blk, 0))
1555 }
1556 }
1557
1558 /// `append_token_with_slot` with the copy-on-write copy issued through
1559 /// `device` instead of the host. The returned `Fence` is not waited on
1560 /// here; the caller must wait on it before reading the new block.
1561 ///
1562 /// On Linux the `MemoryDevice` copy is a CPU `ptr::copy` and its
1563 /// `synchronize` is a no-op (`aien-platform-linux` `device.rs`), so this is
1564 /// not a DMA path today. No production code calls it; the qualification
1565 /// test `kv_lifecycle_qualification.rs` does. A failed copy gives the new
1566 /// block back.
1567 pub fn append_token_with_slot_device<M: MemoryDevice>(
1568 &mut self,
1569 device: &M,
1570 seq_id: u64,
1571 ) -> Result<(BlockId, usize, Option<aien_platform::Fence>), String> {
1572 let table = self
1573 .sequence_tables
1574 .get_mut(&seq_id)
1575 .ok_or_else(|| format!("Sequence {} not found", seq_id))?;
1576
1577 if table.block_ids.is_empty() {
1578 let new_blk = self.allocate_block()?;
1579 let table = self.sequence_tables.get_mut(&seq_id).unwrap();
1580 table.block_ids.push(new_blk);
1581 table.total_tokens = 1;
1582 self.blocks[new_blk].num_tokens = 1;
1583 return Ok((new_blk, 0, None));
1584 }
1585
1586 let last_blk_idx = table.block_ids.len() - 1;
1587 let last_blk_id = table.block_ids[last_blk_idx];
1588 let blk = &self.blocks[last_blk_id];
1589
1590 if blk.is_shared {
1591 if blk.num_tokens < self.block_size {
1592 let new_blk = self.allocate_block()?;
1593 let mut fence = None;
1594 if let Some(pool) = &mut self.tensor_pool {
1595 match pool.copy_block_device(device, last_blk_id, new_blk) {
1596 Ok(f) => fence = Some(f),
1597 Err(e) => {
1598 // Nothing references the new block yet: give it back so a
1599 // failed device copy neither leaks a block nor counts a
1600 // copy-on-write (L6-KV).
1601 self.blocks[new_blk].ref_count = 0;
1602 self.free_blocks.push(new_blk);
1603 return Err(format!("copy_block_device failed: {:?}", e));
1604 }
1605 }
1606 }
1607 self.cow_faults += 1;
1608 let old_blk = &mut self.blocks[last_blk_id];
1609 old_blk.ref_count -= 1;
1610 if old_blk.ref_count == 1 {
1611 old_blk.is_shared = false;
1612 }
1613
1614 let num_tokens = old_blk.num_tokens;
1615 self.blocks[new_blk].num_tokens = num_tokens + 1;
1616 self.blocks[new_blk].is_shared = false;
1617
1618 let table = self.sequence_tables.get_mut(&seq_id).unwrap();
1619 table.block_ids[last_blk_idx] = new_blk;
1620 table.total_tokens += 1;
1621 Ok((new_blk, num_tokens, fence))
1622 } else {
1623 let new_blk = self.allocate_block()?;
1624 let table = self.sequence_tables.get_mut(&seq_id).unwrap();
1625 table.block_ids.push(new_blk);
1626 table.total_tokens += 1;
1627 self.blocks[new_blk].num_tokens = 1;
1628 self.blocks[new_blk].is_shared = false;
1629 Ok((new_blk, 0, None))
1630 }
1631 } else if blk.num_tokens < self.block_size {
1632 let slot = blk.num_tokens;
1633 self.blocks[last_blk_id].num_tokens += 1;
1634 table.total_tokens += 1;
1635 Ok((last_blk_id, slot, None))
1636 } else {
1637 let new_blk = self.allocate_block()?;
1638 let table = self.sequence_tables.get_mut(&seq_id).unwrap();
1639 table.block_ids.push(new_blk);
1640 table.total_tokens += 1;
1641 self.blocks[new_blk].num_tokens = 1;
1642 Ok((new_blk, 0, None))
1643 }
1644 }
1645
1646 pub fn begin_transaction(&self) -> KvTransaction {
1647 KvTransaction::new(KvTransactionSnapshot {
1648 free_blocks: self.free_blocks.clone(),
1649 blocks: self.blocks.clone(),
1650 sequence_tables: self.sequence_tables.clone(),
1651 prefix_cache: self.prefix_cache.clone(),
1652 cow_faults: self.cow_faults,
1653 })
1654 }
1655
1656 pub fn rollback_transaction(&mut self, mut tx: KvTransaction) {
1657 tx.rollback(self);
1658 }
1659
1660 pub fn cow_faults(&self) -> usize {
1661 self.cow_faults
1662 }
1663
1664 pub fn reserve_token(&mut self, seq_id: u64) -> Result<TokenReservation, String> {
1665 let tx = self.begin_transaction();
1666 let (block_id, slot) = self.append_token_with_slot(seq_id)?;
1667 Ok(TokenReservation {
1668 seq_id,
1669 block_id,
1670 slot,
1671 original_block_id: None,
1672 was_cow: false,
1673 tx: Some(tx),
1674 })
1675 }
1676
1677 pub fn commit(&mut self, mut reservation: TokenReservation) -> Result<(), String> {
1678 if let Some(mut tx) = reservation.tx.take() {
1679 tx.commit();
1680 }
1681 Ok(())
1682 }
1683
1684 pub fn rollback(&mut self, mut reservation: TokenReservation) -> Result<(), String> {
1685 if let Some(mut tx) = reservation.tx.take() {
1686 tx.rollback(self);
1687 } else {
1688 let table = self
1689 .sequence_tables
1690 .get_mut(&reservation.seq_id)
1691 .ok_or_else(|| format!("Sequence {} not found", reservation.seq_id))?;
1692 table.total_tokens = table.total_tokens.saturating_sub(1);
1693 }
1694 Ok(())
1695 }
1696
1697 pub fn free_sequence(&mut self, seq_id: u64) -> Result<(), String> {
1698 let table = self
1699 .sequence_tables
1700 .remove(&seq_id)
1701 .ok_or_else(|| format!("Sequence {} not found", seq_id))?;
1702
1703 for blk_id in table.block_ids {
1704 let blk = &mut self.blocks[blk_id];
1705 blk.ref_count -= 1;
1706 if blk.ref_count == 0 {
1707 blk.is_shared = false;
1708 blk.num_tokens = 0;
1709 self.free_blocks.push(blk_id);
1710 } else if blk.ref_count == 1 {
1711 blk.is_shared = false;
1712 }
1713 }
1714
1715 Ok(())
1716 }
1717
1718 /// Drops the K/V of every position at or past `new_total` of `seq_id`: the
1719 /// cleanup after a speculative verification (sc draft-verify, 2026-10-12)
1720 /// that forwarded draft tokens the model then rejected. Trailing blocks that
1721 /// no longer hold a token go back to the free list (and leave the prefix
1722 /// cache), the tail block's token count and the table's `total_tokens` become
1723 /// `new_total`. Refused, nothing changed, when the sequence is unknown, when
1724 /// `new_total` is past the current length, or when a block to shrink or free
1725 /// is shared with another sequence (a fork still owns those tokens).
1726 pub fn truncate_sequence(&mut self, seq_id: u64, new_total: usize) -> Result<(), String> {
1727 let table = self
1728 .sequence_tables
1729 .get(&seq_id)
1730 .ok_or_else(|| format!("Sequence {} not found", seq_id))?;
1731 if new_total > table.total_tokens {
1732 return Err(format!(
1733 "truncate_sequence: {new_total} is past the {} tokens of sequence {seq_id}",
1734 table.total_tokens
1735 ));
1736 }
1737 if new_total == table.total_tokens {
1738 return Ok(());
1739 }
1740 let bs = self.block_size;
1741 let keep = new_total.div_ceil(bs);
1742 // Blocks touched: every freed block, plus the tail kept block when it loses tokens.
1743 let first_touched = if new_total.is_multiple_of(bs) {
1744 keep
1745 } else {
1746 keep - 1
1747 };
1748 for &b in &table.block_ids[first_touched.min(table.block_ids.len())..] {
1749 let blk = &self.blocks[b];
1750 if blk.is_shared || blk.ref_count > 1 {
1751 return Err(format!(
1752 "truncate_sequence: block {b} of sequence {seq_id} is shared (ref_count {})",
1753 blk.ref_count
1754 ));
1755 }
1756 }
1757 let table = self.sequence_tables.get_mut(&seq_id).unwrap();
1758 let freed: Vec<BlockId> = table
1759 .block_ids
1760 .drain(keep.min(table.block_ids.len())..)
1761 .collect();
1762 if keep > 0 {
1763 let tail = table.block_ids[keep - 1];
1764 self.blocks[tail].num_tokens = new_total - (keep - 1) * bs;
1765 }
1766 table.total_tokens = new_total;
1767 for b in &freed {
1768 let blk = &mut self.blocks[*b];
1769 blk.ref_count = 0;
1770 blk.is_shared = false;
1771 blk.num_tokens = 0;
1772 self.free_blocks.push(*b);
1773 }
1774 if !freed.is_empty() {
1775 self.prefix_cache.retain(|_, b| !freed.contains(b));
1776 }
1777 Ok(())
1778 }
1779
1780 pub fn get_block_table(&self, seq_id: u64) -> Option<&BlockTable> {
1781 self.sequence_tables.get(&seq_id)
1782 }
1783
1784 pub fn get_block(&self, block_id: BlockId) -> Option<&KvBlock> {
1785 self.blocks.get(block_id)
1786 }
1787
1788 pub fn tensor_pool(&self) -> Option<&UnifiedKvTensorPool<B>> {
1789 self.tensor_pool.as_ref()
1790 }
1791
1792 pub fn tensor_pool_mut(&mut self) -> Option<&mut UnifiedKvTensorPool<B>> {
1793 self.tensor_pool.as_mut()
1794 }
1795
1796 pub fn block_size(&self) -> usize {
1797 self.block_size
1798 }
1799
1800 /// Total physical blocks in the pool (free + allocated).
1801 pub fn total_block_count(&self) -> usize {
1802 self.total_blocks
1803 }
1804
1805 /// How many fresh physical blocks `appends` consecutive
1806 /// `append_token_with_slot` calls on `seq_id` would allocate, computed
1807 /// read-only from the table's tail block with the same rule as
1808 /// `append_token_with_slot`:
1809 /// - empty table: the first append allocates a block;
1810 /// - shared tail block, partly filled: copy-on-write, one fresh block;
1811 /// - shared tail block, full: one fresh block;
1812 /// - private tail block: its free slots take appends first;
1813 ///
1814 /// then every further `block_size` appends need one more fresh block.
1815 /// Returns 0 when the sequence has no block table (the append itself then
1816 /// reports the missing sequence).
1817 pub fn blocks_needed_for_appends(&self, seq_id: u64, appends: usize) -> usize {
1818 if appends == 0 {
1819 return 0;
1820 }
1821 let Some(table) = self.sequence_tables.get(&seq_id) else {
1822 return 0;
1823 };
1824 let block_size = self.block_size;
1825 let mut remaining = appends;
1826 let mut needed = 0usize;
1827 // Free slots left in the tail block once the first append has resolved.
1828 let tail_free = match table.block_ids.last().and_then(|&id| self.get_block(id)) {
1829 None => {
1830 // Empty table: the first append allocates a block holding 1 token.
1831 needed += 1;
1832 remaining -= 1;
1833 block_size - 1
1834 }
1835 Some(blk) if blk.is_shared => {
1836 // Copy-on-write of a partly filled tail, or a fresh block after a
1837 // full one: either way one fresh private block takes this append.
1838 needed += 1;
1839 remaining -= 1;
1840 if blk.num_tokens < block_size {
1841 block_size - (blk.num_tokens + 1)
1842 } else {
1843 block_size - 1
1844 }
1845 }
1846 Some(blk) => block_size.saturating_sub(blk.num_tokens),
1847 };
1848 remaining -= remaining.min(tail_free);
1849 needed + remaining.div_ceil(block_size)
1850 }
1851
1852 /// The sole authority for how many NEW physical blocks the scheduler must
1853 /// find free before it admits `seq_id` with a `prompt_len`-token prompt.
1854 /// Read-only; uses this pool's block size, never a literal.
1855 ///
1856 /// - No table: a fresh `allocate_sequence`, `ceil(prompt_len / block_size)`.
1857 /// - Table whose K/V is not computed (`!is_prefill_ready`): the scheduler
1858 /// drops that table and allocates again, so the need is a fresh
1859 /// allocation minus the blocks the drop gives back (those only this
1860 /// table references).
1861 /// - Computed table (a fork child or a resumed sequence): its blocks,
1862 /// shared or not, are already held, so only the tokens beyond the table
1863 /// plus the first decode token count. That first append is where a
1864 /// shared partial tail is copy-on-written, so a fork child of a
1865 /// mid-block prefix needs exactly one new block.
1866 pub fn incremental_blocks_needed(&self, seq_id: u64, prompt_len: usize) -> usize {
1867 let fresh = prompt_len.div_ceil(self.block_size);
1868 match self.sequence_tables.get(&seq_id) {
1869 None => fresh,
1870 Some(table) if !table.is_prefill_ready() => {
1871 let returned = table
1872 .block_ids
1873 .iter()
1874 .filter(|&&b| self.blocks.get(b).is_some_and(|blk| blk.ref_count == 1))
1875 .count();
1876 fresh.saturating_sub(returned)
1877 }
1878 Some(table) => self.blocks_needed_for_appends(
1879 seq_id,
1880 prompt_len.saturating_sub(table.total_tokens) + 1,
1881 ),
1882 }
1883 }
1884
1885 pub fn total_tokens(&self, seq_id: u64) -> Option<usize> {
1886 self.sequence_tables.get(&seq_id).map(|t| t.total_tokens)
1887 }
1888
1889 /// Writes one token's K and V for one layer at `token_pos` of `seq_id`'s
1890 /// table into the pool. A bf16 pool rounds each value to bf16
1891 /// (round-to-nearest-even) on write.
1892 ///
1893 /// Caller contract: this does not check whether the block is shared or
1894 /// its refcount, so a write into a shared block changes every table that
1895 /// holds it. Write only positions of a table nobody shares, or the slot
1896 /// `append_token_with_slot` just returned.
1897 pub fn write_token_kv(
1898 &mut self,
1899 seq_id: u64,
1900 token_pos: usize,
1901 layer_idx: usize,
1902 k: &[f32],
1903 v: &[f32],
1904 ) -> Result<(), String> {
1905 let table = self
1906 .sequence_tables
1907 .get(&seq_id)
1908 .ok_or_else(|| format!("Sequence {} not found", seq_id))?;
1909
1910 let block_idx = token_pos / self.block_size;
1911 let token_in_block = token_pos % self.block_size;
1912
1913 if block_idx >= table.block_ids.len() {
1914 return Err(format!(
1915 "Token pos {} out of bounds for sequence {}",
1916 token_pos, seq_id
1917 ));
1918 }
1919
1920 let physical_block = table.block_ids[block_idx];
1921
1922 if let Some(pool) = &mut self.tensor_pool {
1923 pool.write_token_kv(physical_block, layer_idx, token_in_block, k, v);
1924 Ok(())
1925 } else {
1926 Err("No physical tensor pool attached".to_string())
1927 }
1928 }
1929
1930 /// Writes one token's K and V for one layer into `block_id` at
1931 /// `token_in_block`, the slot a caller got from `append_token_with_slot`.
1932 /// A bf16 pool rounds each value to bf16 (round-to-nearest-even) on write.
1933 ///
1934 /// Caller contract: like `write_token_kv`, this does not check sharing or
1935 /// refcount; the append that produced the slot is what makes it private.
1936 pub fn write_explicit_token_kv(
1937 &mut self,
1938 block_id: BlockId,
1939 layer_idx: usize,
1940 token_in_block: usize,
1941 k: &[f32],
1942 v: &[f32],
1943 ) -> Result<(), String> {
1944 if let Some(pool) = &mut self.tensor_pool {
1945 pool.write_token_kv(block_id, layer_idx, token_in_block, k, v);
1946 Ok(())
1947 } else {
1948 Err("No physical tensor pool attached".to_string())
1949 }
1950 }
1951
1952 pub fn gather_sequence_layer_kv(
1953 &self,
1954 seq_id: u64,
1955 layer_idx: usize,
1956 k_out: &mut Vec<f32>,
1957 v_out: &mut Vec<f32>,
1958 ) -> Result<(), String> {
1959 let (k, v) = self.gather_layer_kv(seq_id, layer_idx)?;
1960 *k_out = k;
1961 *v_out = v;
1962 Ok(())
1963 }
1964
1965 pub fn gather_layer_kv(
1966 &self,
1967 seq_id: u64,
1968 layer_idx: usize,
1969 ) -> Result<(Vec<f32>, Vec<f32>), String> {
1970 let table = self
1971 .sequence_tables
1972 .get(&seq_id)
1973 .ok_or_else(|| format!("Sequence {} not found", seq_id))?;
1974
1975 if let Some(pool) = &self.tensor_pool {
1976 Ok(pool.gather_layer_kv(&table.block_ids, table.total_tokens, layer_idx))
1977 } else {
1978 Err("No physical tensor pool attached".to_string())
1979 }
1980 }
1981}
1982
1983pub type SharedKvManager<B = DefaultUnifiedBuffer> = Arc<RwLock<AienKvManager<B>>>;
1984
1985pub fn create_shared_kv_manager(
1986 total_blocks: usize,
1987 block_size: usize,
1988) -> SharedKvManager<DefaultUnifiedBuffer> {
1989 Arc::new(RwLock::new(AienKvManager::new(total_blocks, block_size)))
1990}
1991
1992pub fn create_shared_kv_manager_with_pool(
1993 total_blocks: usize,
1994 block_size: usize,
1995 config: KvPoolConfig,
1996) -> Result<SharedKvManager<DefaultUnifiedBuffer>, String> {
1997 let mgr = AienKvManager::new_with_pool(total_blocks, block_size, config)?;
1998 Ok(Arc::new(RwLock::new(mgr)))
1999}
2000
2001/// `create_shared_kv_manager_with_pool` over a buffer the caller already holds
2002/// (`AienKvManager::new_with_pool_buffer`).
2003pub fn create_shared_kv_manager_with_pool_buffer(
2004 total_blocks: usize,
2005 block_size: usize,
2006 config: KvPoolConfig,
2007 buffer: DefaultUnifiedBuffer,
2008) -> Result<SharedKvManager<DefaultUnifiedBuffer>, String> {
2009 let mgr = AienKvManager::new_with_pool_buffer(total_blocks, block_size, config, buffer)?;
2010 Ok(Arc::new(RwLock::new(mgr)))
2011}
2012
2013#[cfg(test)]
2014mod tests {
2015 use super::*;
2016
2017 fn oracle_offset(
2018 block: usize,
2019 layer: usize,
2020 is_value: bool,
2021 token: usize,
2022 head: usize,
2023 dim: usize,
2024 cfg: &KvPoolConfig,
2025 ) -> usize {
2026 let e = match cfg.dtype {
2027 KvDType::Bf16 | KvDType::Fp16 => 2usize,
2028 KvDType::Fp32 => 4usize,
2029 KvDType::Fp8 => 1usize,
2030 KvDType::Fp4 => 1usize,
2031 };
2032
2033 let head_stride = cfg.head_dim * e;
2034 let token_stride = cfg.num_kv_heads * head_stride;
2035 let plane_stride = cfg.block_size * token_stride;
2036 let layer_stride = 2 * plane_stride;
2037 let block_stride = cfg.num_layers * layer_stride;
2038
2039 block * block_stride
2040 + layer * layer_stride
2041 + usize::from(is_value) * plane_stride
2042 + token * token_stride
2043 + head * head_stride
2044 + dim * e
2045 }
2046
2047 #[test]
2048 fn test_kv_layout_stride_invariants() {
2049 let cfg = KvPoolConfig {
2050 num_blocks: 8,
2051 block_size: 16,
2052 num_layers: 3,
2053 num_kv_heads: 2,
2054 head_dim: 64,
2055 dtype: KvDType::Bf16,
2056 };
2057
2058 let layout = KvLayout::from_config(&cfg).unwrap();
2059
2060 assert_eq!(layout.element_bytes, 2);
2061 assert_eq!(layout.head_stride_bytes, 128);
2062 assert_eq!(layout.token_stride_bytes, 256);
2063 assert_eq!(layout.kv_plane_stride_bytes, 4096);
2064 assert_eq!(layout.layer_stride_bytes, 8192);
2065 assert_eq!(layout.block_stride_bytes, 24576);
2066 assert_eq!(layout.total_bytes, 8 * 24576);
2067
2068 let desc = layout.to_desc();
2069 assert_eq!(desc.head_stride_bytes, 128);
2070 assert_eq!(desc.token_stride_bytes, 256);
2071 assert_eq!(desc.kv_plane_stride_bytes, 4096);
2072 assert_eq!(desc.layer_stride_bytes, 8192);
2073 assert_eq!(desc.block_stride_bytes, 24576);
2074 assert_eq!(desc.pool_bytes, (8 * 24576) as u64);
2075 }
2076
2077 #[test]
2078 fn test_kv_layout_rejects_total_bytes_overflow() {
2079 // Formal finding (arch#112): 2^45 blocks wrapped total_bytes to
2080 // 6917529027641081856 instead of 25364273101350633472.
2081 let cfg = KvPoolConfig {
2082 num_blocks: 1usize << 45,
2083 block_size: 16,
2084 num_layers: 22,
2085 num_kv_heads: 4,
2086 head_dim: 64,
2087 dtype: KvDType::Fp32,
2088 };
2089 let err = KvLayout::from_config(&cfg).unwrap_err();
2090 assert!(err.contains("overflow"), "unexpected error: {err}");
2091 assert!(cfg.layout().is_err());
2092 assert!(cfg.layout_desc().is_err());
2093 }
2094
2095 #[test]
2096 fn test_kv_layout_independent_address_parity() {
2097 let cfg = KvPoolConfig::for_tinyllama(16, 16, KvDType::Bf16);
2098 let layout = KvLayout::from_config(&cfg).unwrap();
2099
2100 let test_cases = [
2101 (0, 0, false, 0, 0, 0),
2102 (0, 0, true, 0, 0, 0),
2103 (0, 1, false, 0, 0, 0),
2104 (1, 0, false, 0, 0, 0),
2105 (7, 13, true, 4, 2, 31),
2106 (15, 21, true, 15, 3, 63),
2107 ];
2108
2109 for &(blk, layer, is_val, tok, head, dim) in &test_cases {
2110 let expected = oracle_offset(blk, layer, is_val, tok, head, dim, &cfg);
2111 let actual = layout.element_offset(blk, layer, is_val, tok, head, dim);
2112 assert_eq!(
2113 expected, actual,
2114 "Offset mismatch at blk={} layer={} val={} tok={} head={} dim={}",
2115 blk, layer, is_val, tok, head, dim
2116 );
2117 }
2118 }
2119
2120 #[test]
2121 fn test_bf16_pool_roundtrip() {
2122 let cfg = KvPoolConfig {
2123 num_blocks: 4,
2124 block_size: 16,
2125 num_layers: 2,
2126 num_kv_heads: 2,
2127 head_dim: 8,
2128 dtype: KvDType::Bf16,
2129 };
2130
2131 let mut pool = UnifiedKvTensorPool::allocate(cfg.clone()).unwrap();
2132 let kv_dim = 2 * 8;
2133
2134 let k_in: Vec<f32> = (0..kv_dim).map(|i| i as f32 * 0.125).collect();
2135 let v_in: Vec<f32> = (0..kv_dim).map(|i| (i as f32 + 10.0) * 0.25).collect();
2136
2137 pool.write_token_kv(1, 0, 3, &k_in, &v_in);
2138
2139 let mut k_out = vec![0.0f32; kv_dim];
2140 let mut v_out = vec![0.0f32; kv_dim];
2141 pool.read_token_kv(1, 0, 3, &mut k_out, &mut v_out);
2142
2143 for i in 0..kv_dim {
2144 assert!(
2145 (k_in[i] - k_out[i]).abs() < 1e-2,
2146 "K mismatch at {}: expected {}, got {}",
2147 i,
2148 k_in[i],
2149 k_out[i]
2150 );
2151 assert!(
2152 (v_in[i] - v_out[i]).abs() < 1e-2,
2153 "V mismatch at {}: expected {}, got {}",
2154 i,
2155 v_in[i],
2156 v_out[i]
2157 );
2158 }
2159 }
2160
2161 #[test]
2162 fn test_physical_byte_pattern() {
2163 let cfg = KvPoolConfig {
2164 num_blocks: 4,
2165 block_size: 16,
2166 num_layers: 2,
2167 num_kv_heads: 2,
2168 head_dim: 4,
2169 dtype: KvDType::Bf16,
2170 };
2171
2172 let mut pool = UnifiedKvTensorPool::allocate(cfg.clone()).unwrap();
2173
2174 let coord_val = |b: usize, l: usize, is_v: bool, t: usize, h: usize, d: usize| -> f32 {
2175 b as f32 * 0.1
2176 + l as f32 * 0.01
2177 + if is_v { 0.005 } else { 0.0 }
2178 + t as f32 * 0.0001
2179 + h as f32 * 0.00001
2180 + d as f32 * 0.000001
2181 };
2182
2183 let kv_dim = cfg.num_kv_heads * cfg.head_dim;
2184 for b in 0..2 {
2185 for l in 0..2 {
2186 for t in 0..4 {
2187 let mut k = vec![0.0f32; kv_dim];
2188 let mut v = vec![0.0f32; kv_dim];
2189 for h in 0..cfg.num_kv_heads {
2190 for d in 0..cfg.head_dim {
2191 k[h * cfg.head_dim + d] = coord_val(b, l, false, t, h, d);
2192 v[h * cfg.head_dim + d] = coord_val(b, l, true, t, h, d);
2193 }
2194 }
2195 pool.write_token_kv(b, l, t, &k, &v);
2196 }
2197 }
2198 }
2199
2200 let mut k_read = vec![0.0f32; kv_dim];
2201 let mut v_read = vec![0.0f32; kv_dim];
2202 pool.read_token_kv(0, 0, 0, &mut k_read, &mut v_read);
2203 assert_ne!(k_read[0], v_read[0], "K and V should not match");
2204
2205 let mut k_l1 = vec![0.0f32; kv_dim];
2206 let mut v_l1 = vec![0.0f32; kv_dim];
2207 pool.read_token_kv(0, 1, 0, &mut k_l1, &mut v_l1);
2208 assert_ne!(k_read[0], k_l1[0], "Layer 0 and Layer 1 K should not match");
2209 }
2210
2211 #[test]
2212 fn test_cow_manager_fork_and_divergence() {
2213 let cfg = KvPoolConfig::for_tinyllama(32, 16, KvDType::Bf16);
2214 let mut mgr = AienKvManager::new_with_pool(32, 16, cfg).unwrap();
2215
2216 let prompt: Vec<u32> = (0..30).collect();
2217 let parent_blocks = mgr.allocate_sequence(100, &prompt).unwrap();
2218 assert_eq!(parent_blocks.len(), 2);
2219
2220 let child1_blocks = mgr.fork_sequence(100, 201).unwrap();
2221 let child2_blocks = mgr.fork_sequence(100, 202).unwrap();
2222
2223 assert_eq!(child1_blocks, parent_blocks);
2224 assert_eq!(child2_blocks, parent_blocks);
2225
2226 // Append to child 1 -> triggers COW on block 1
2227 let (new_blk, _) = mgr.append_token_with_slot(201).unwrap();
2228 let child1_now = mgr.get_block_table(201).unwrap();
2229
2230 assert_eq!(
2231 child1_now.block_ids[0], parent_blocks[0],
2232 "Prefix block 0 must remain shared"
2233 );
2234 assert_ne!(
2235 child1_now.block_ids[1], parent_blocks[1],
2236 "Tail block 1 must have diverged via COW"
2237 );
2238 assert_eq!(child1_now.block_ids[1], new_blk);
2239
2240 // Parent and child 2 still share original block 1
2241 let parent_now = mgr.get_block_table(100).unwrap();
2242 let child2_now = mgr.get_block_table(202).unwrap();
2243 assert_eq!(parent_now.block_ids[1], parent_blocks[1]);
2244 assert_eq!(child2_now.block_ids[1], parent_blocks[1]);
2245 }
2246
2247 #[test]
2248 #[cfg(target_os = "linux")]
2249 fn test_kv_pool_device_copy_and_zero() {
2250 use aien_platform::ComputeDevice;
2251
2252 let cfg = KvPoolConfig {
2253 num_blocks: 4,
2254 block_size: 16,
2255 num_layers: 2,
2256 num_kv_heads: 2,
2257 head_dim: 8,
2258 dtype: KvDType::Bf16,
2259 };
2260
2261 let mut pool = UnifiedKvTensorPool::allocate(cfg.clone()).unwrap();
2262 let kv_dim = 2 * 8;
2263 let k_in: Vec<f32> = (0..kv_dim).map(|i| (i + 1) as f32).collect();
2264 let v_in: Vec<f32> = (0..kv_dim).map(|i| (i + 10) as f32).collect();
2265
2266 pool.write_token_kv(0, 0, 0, &k_in, &v_in);
2267
2268 let device = aien_platform_linux::LinuxComputeDevice::new();
2269 let fence = pool
2270 .copy_block_device(&device, 0, 1)
2271 .expect("copy_block_device failed");
2272 device.synchronize(fence).expect("synchronize copy");
2273
2274 let mut k_out = vec![0.0f32; kv_dim];
2275 let mut v_out = vec![0.0f32; kv_dim];
2276 pool.read_token_kv(1, 0, 0, &mut k_out, &mut v_out);
2277 assert_eq!(k_in, k_out);
2278 assert_eq!(v_in, v_out);
2279
2280 let fence_zero = pool
2281 .zero_block_device(&device, 1)
2282 .expect("zero_block_device failed");
2283 device.synchronize(fence_zero).expect("synchronize zero");
2284
2285 pool.read_token_kv(1, 0, 0, &mut k_out, &mut v_out);
2286 assert_eq!(k_out, vec![0.0f32; kv_dim]);
2287 assert_eq!(v_out, vec![0.0f32; kv_dim]);
2288 }
2289
2290 #[test]
2291 fn test_kv_transaction_commit_and_rollback() {
2292 let cfg = KvPoolConfig::for_tinyllama(32, 16, KvDType::Bf16);
2293 let mut mgr = AienKvManager::new_with_pool(32, 16, cfg).unwrap();
2294
2295 let prompt: Vec<u32> = (0..20).collect();
2296 mgr.allocate_sequence(1, &prompt).unwrap();
2297 assert_eq!(mgr.available_blocks(), 30);
2298
2299 // Transaction 1: reserve token, then rollback
2300 let mut tx = mgr.begin_transaction();
2301 let (_blk, slot) = mgr.append_token_with_slot(1).unwrap();
2302 assert_eq!(slot, 4); // token 21 in block 1
2303 assert_eq!(mgr.get_block_table(1).unwrap().total_tokens, 21);
2304
2305 // Rollback
2306 tx.rollback(&mut mgr);
2307 assert_eq!(mgr.get_block_table(1).unwrap().total_tokens, 20);
2308 assert_eq!(mgr.available_blocks(), 30);
2309
2310 // Transaction 2: allocate new sequence and commit
2311 let mut tx2 = mgr.begin_transaction();
2312 mgr.allocate_sequence(2, &prompt).unwrap();
2313 assert_eq!(mgr.available_blocks(), 28);
2314 tx2.commit();
2315 assert_eq!(mgr.available_blocks(), 28);
2316 assert!(mgr.get_block_table(2).is_some());
2317
2318 // Transaction 3: fork and append with rollback
2319 let mut tx3 = mgr.begin_transaction();
2320 mgr.fork_sequence(1, 3).unwrap();
2321 mgr.append_token_with_slot(3).unwrap();
2322 assert_eq!(mgr.cow_faults(), 1);
2323 tx3.rollback(&mut mgr);
2324
2325 assert!(mgr.get_block_table(3).is_none());
2326 assert_eq!(mgr.cow_faults(), 0);
2327 let b1 = mgr.get_block_table(1).unwrap().block_ids[1];
2328 assert_eq!(mgr.get_block(b1).unwrap().ref_count, 1);
2329 assert!(!mgr.get_block(b1).unwrap().is_shared);
2330
2331 // TokenReservation commit & rollback
2332 let res = mgr.reserve_token(1).unwrap();
2333 assert_eq!(mgr.get_block_table(1).unwrap().total_tokens, 21);
2334 mgr.rollback(res).unwrap();
2335 assert_eq!(mgr.get_block_table(1).unwrap().total_tokens, 20);
2336
2337 let res2 = mgr.reserve_token(1).unwrap();
2338 assert_eq!(mgr.get_block_table(1).unwrap().total_tokens, 21);
2339 mgr.commit(res2).unwrap();
2340 assert_eq!(mgr.get_block_table(1).unwrap().total_tokens, 21);
2341 }
2342
2343 // PREFILL-GATE: allocated != computed.
2344
2345 #[test]
2346 fn test_prefill_gate_allocation_is_not_ready() {
2347 let mut mgr = AienKvManager::new(16, 16);
2348 mgr.allocate_sequence(7, &[1, 2, 3, 4]).unwrap();
2349 assert_eq!(mgr.prefill_state(7), Some(PrefillState::Allocated));
2350 assert!(
2351 !mgr.get_block_table(7).unwrap().is_prefill_ready(),
2352 "allocate_sequence zeroes blocks only; it must never yield a ready table"
2353 );
2354 }
2355
2356 #[test]
2357 fn test_prefill_gate_fork_refuses_unready_root() {
2358 let mut mgr = AienKvManager::new(16, 16);
2359 mgr.allocate_sequence(1, &[1, 2, 3]).unwrap();
2360 let free_before = mgr.free_block_count();
2361
2362 let err = mgr.fork_prefilled(1, 2).unwrap_err();
2363 assert_eq!(
2364 err,
2365 PrefillGateError::NotReady {
2366 seq_id: 1,
2367 state: PrefillState::Allocated
2368 }
2369 );
2370 assert!(
2371 mgr.get_block_table(2).is_none(),
2372 "refused fork must not create a child table"
2373 );
2374 assert_eq!(mgr.free_block_count(), free_before);
2375
2376 mgr.mark_prefill_pending(1).unwrap();
2377 let err = mgr.fork_prefilled(1, 2).unwrap_err();
2378 assert_eq!(
2379 err,
2380 PrefillGateError::NotReady {
2381 seq_id: 1,
2382 state: PrefillState::PrefillPending
2383 }
2384 );
2385 assert_eq!(
2386 mgr.fork_prefilled(99, 2).unwrap_err(),
2387 PrefillGateError::UnknownSequence { seq_id: 99 }
2388 );
2389 }
2390
2391 #[test]
2392 fn test_prefill_gate_fence_requires_pending_then_shares_frozen() {
2393 let mut mgr = AienKvManager::new(16, 16);
2394 mgr.allocate_sequence(1, &[1, 2, 3]).unwrap();
2395
2396 // The fence cannot be fired on a table that never had a prefill issued.
2397 assert_eq!(
2398 mgr.complete_prefill(1).unwrap_err(),
2399 PrefillGateError::FenceWithoutPending {
2400 seq_id: 1,
2401 state: PrefillState::Allocated
2402 }
2403 );
2404 assert_eq!(mgr.prefill_state(1), Some(PrefillState::Allocated));
2405
2406 mgr.mark_prefill_pending(1).unwrap();
2407 assert_eq!(mgr.prefill_state(1), Some(PrefillState::PrefillPending));
2408 mgr.complete_prefill(1).unwrap();
2409 assert_eq!(mgr.prefill_state(1), Some(PrefillState::PrefillReady));
2410
2411 let blocks = mgr.fork_prefilled(1, 2).unwrap();
2412 assert_eq!(blocks, mgr.get_block_table(1).unwrap().block_ids);
2413 assert_eq!(mgr.prefill_state(1), Some(PrefillState::SharedFrozen));
2414 assert_eq!(mgr.prefill_state(2), Some(PrefillState::SharedFrozen));
2415 assert!(mgr.get_block_table(2).unwrap().is_prefill_ready());
2416
2417 // Reclaimed = table gone.
2418 mgr.free_sequence(2).unwrap();
2419 assert_eq!(mgr.prefill_state(2), None);
2420 }
2421
2422 #[test]
2423 fn test_prefill_gate_plain_fork_of_unready_parent_stays_unready() {
2424 let mut mgr = AienKvManager::new(16, 16);
2425 mgr.allocate_sequence(1, &[1, 2, 3]).unwrap();
2426 mgr.fork_sequence(1, 2).unwrap();
2427 assert_eq!(mgr.prefill_state(2), Some(PrefillState::Allocated));
2428 assert!(!mgr.get_block_table(2).unwrap().is_prefill_ready());
2429 }
2430}