fuel_tensor/inference_context.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Persistent inference state for the pipelined executor (Phase 7.6
3//! step 9c, sub-phase E.3.0).
4//!
5//! ## What this module owns
6//!
7//! - **[`InferenceContext`]**: a host-side per-session struct holding
8//! long-lived `Arc<RwLock<Storage>>` references that survive across
9//! realize calls. Replaces the legacy executor's `const_pool`
10//! for the pipelined dispatch world. Today's backing is a simple
11//! in-memory `HashMap<NodeId, Arc<...>>`; future work may swap this
12//! for an mmap-backed coherent store per
13//! `project_unified_durable_tensor_store.md`.
14//!
15//! - **[`KvCache`]**, **[`KvLayer`]**, **[`KvLayerId`]**, **[`KvSlot`]**,
16//! **[`AuthorityState`]**: the backend-erased KV cache primitive that
17//! replaced `lazy::KVCache<B>` and `lazy::LlamaKVCache` (both
18//! retired — E.3.3.D and Unification Session 4 E.3.4). Single
19//! concrete type with no generic-over-B parameter; each layer holds
20//! `Arc<RwLock<Storage>>` for K and V plus side-table metadata
21//! (layout, monotonic version, coherence authority).
22//!
23//! ## What this module deliberately does NOT do (yet)
24//!
25//! - **Pre-allocated buffers** (added Phase E.3.3.A, 2026-05-20):
26//! [`KvCache::with_capacity`] eagerly allocates `[1, n_kv_heads,
27//! max_seq_len, head_dim]` zero-initialized K + V buffers on a
28//! target device. Subsequent forward steps write into these via
29//! `Op::WriteSlice` rather than growing-by-replacement. The legacy
30//! [`KvCache::with_dims`] constructor stays available for callers
31//! not yet on the pre-allocated path (grow-by-replace works without
32//! changes).
33//! - **Multi-device coherence protocol**: the `authority` and
34//! `version` fields exist as placeholders. No protocol consults
35//! them yet — every layer starts and stays `AuthorityState::Host`
36//! for the lifetime of the session in single-device usage.
37//! Phase J (multi-GPU) activates the protocol.
38//! - **Weight persistence**: weights stay in the graph's storage_map
39//! per the design discussion; the persistent map handles KV layers
40//! and transient cross-step state only.
41
42use std::collections::HashMap;
43use std::sync::atomic::{AtomicUsize, Ordering};
44use std::sync::{Arc, RwLock};
45
46use fuel_dispatch::{
47 optimize::OptimizedGraph,
48 pipelined::{PipelinedExecutor, StorageCache},
49};
50use fuel_graph::{Graph, Node, NodeId, Op};
51use fuel_ir::{DType, DeviceLocation, Error, Layout, Result, SType, Shape, SymEnv, SymId};
52use fuel_memory::{BackendStorage, Storage};
53
54use crate::Device;
55use crate::decode_shape::KvAllocId;
56
57// ===========================================================================
58// KV cache primitive types
59// ===========================================================================
60
61/// Identifies a single key-or-value tensor within a [`KvCache`].
62/// Stable across realize calls — the graph-level NodeId may churn
63/// per step (each `Op::WriteSlice` produces a fresh NodeId pointing
64/// at the same Storage Arc) but the logical KV slot identity stays.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66pub struct KvLayerId {
67 pub layer_idx: usize,
68 pub slot: KvSlot,
69}
70
71/// Which half of a KV pair a [`KvLayerId`] addresses.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub enum KvSlot {
74 K,
75 V,
76}
77
78/// Coherence authority for one KV slot's storage. Placeholder for the
79/// multi-device protocol; today every slot starts and stays
80/// [`AuthorityState::Host`] for the lifetime of the session unless
81/// future code explicitly transitions it.
82///
83/// The intended protocol (deferred until multi-GPU lands):
84/// - **Host**: the host has the most recent version. Devices may
85/// hold stale copies. The default at session start.
86/// - **Device(loc)**: a device owns the most recent version. The
87/// host's copy may be stale until an explicit flush.
88#[derive(Debug, Clone)]
89pub enum AuthorityState {
90 Host,
91 Device(DeviceLocation),
92}
93
94/// One layer's K + V slots in a backend-erased KV cache.
95///
96/// Storage Arcs are dispatch-erased: each Arc points at a
97/// [`fuel_memory::BackendStorage`] enum variant (`Cpu`, `Cuda`,
98/// `Vulkan`, `Metal`). The graph references these Arcs via the
99/// persistent map in [`InferenceContext`]; readers see the bytes
100/// through whichever Layout the graph carries for the consuming
101/// NodeId.
102pub struct KvLayer {
103 pub k: Arc<RwLock<Storage>>,
104 pub v: Arc<RwLock<Storage>>,
105 /// View layout into `k` describing the live extent. For the grow-
106 /// by-replacement pattern (today) the layout matches the storage's
107 /// full shape. For pre-allocated buffers (Phase E.3.2) the layout
108 /// describes the leading `[..., cached_len, ...]` slice.
109 pub k_layout: Layout,
110 pub v_layout: Layout,
111 /// Monotonic write version for K. Bumps on every successful
112 /// `Op::WriteSlice` targeting this slot. Used by the future
113 /// multi-device coherence protocol to detect staleness.
114 pub k_version: u64,
115 pub v_version: u64,
116 /// Coherence authority per slot. K and V can in principle diverge
117 /// (a future optimization that decouples their update cadence
118 /// could exploit this), though standard transformer decoding
119 /// updates both together every step.
120 pub k_authority: AuthorityState,
121 pub v_authority: AuthorityState,
122}
123
124/// Backend-erased KV cache. Replaces `lazy::KVCache<B>` and
125/// `lazy::LlamaKVCache`. Indexed by global layer index; `layers[i]`
126/// is `None` if layer `i` hasn't been populated yet.
127///
128/// Pipeline-parallel friendly: when a model is split across devices,
129/// each device's cache holds entries only for its layer range; other
130/// indices are `None`. The model code queries `cache.layer(global_i)`
131/// regardless of which device owns it; the storage Arc inside
132/// [`KvLayer`] carries the device identity via its
133/// [`fuel_memory::BackendStorage`] variant.
134pub struct KvCache {
135 pub layers: Vec<Option<KvLayer>>,
136 pub cached_len: usize,
137 pub n_kv_heads: usize,
138 pub head_dim: usize,
139 /// Identity of the *allocation* backing this cache — the thing a held
140 /// [`DecodeSession`] is welded to. Private with an [`Self::alloc_id`]
141 /// reader so it cannot be assigned by hand: every path that replaces
142 /// storage ([`Self::clear`], [`Self::set_layer`]) re-mints it, and
143 /// [`Self::truncate_to`] deliberately does not. See [`KvAllocId`].
144 alloc_id: KvAllocId,
145 /// Pre-allocated capacity along the sequence axis. `Some(n)` when
146 /// constructed via [`KvCache::with_capacity`] — every layer's K + V
147 /// storage holds `[1, n_kv_heads, n, head_dim]` of zeros and the
148 /// forward path writes into it via `Op::WriteSlice`. `None` for the
149 /// legacy [`KvCache::with_dims`] grow-by-replacement constructor.
150 pub max_seq_len: Option<usize>,
151 /// Dtype the pre-allocated buffers were allocated with. `Some(dt)`
152 /// in the [`KvCache::with_capacity`] path, `None` in the legacy
153 /// `with_dims` path (which leaves dtype to whatever the first
154 /// inserted layer specifies).
155 pub dtype: Option<DType>,
156 /// Where this cache's storage lives — `Some(loc)` only while every
157 /// buffer is one [`Self::with_capacity`] allocated on `loc`, `None`
158 /// the moment that stops being provable.
159 ///
160 /// Exists for [`DecodeSession::rebind_kv`], which splices these `Arc`s
161 /// into a graph whose placement stamps and residency `Op::Copy`s were
162 /// baked against the *previous* cache. Shape it can prove from the
163 /// storage itself; residency it cannot — `fuel_memory::Storage` exposes
164 /// a backend *variant*, and `VulkanStorage` records no device ordinal at
165 /// all, so a multi-GPU swap is invisible from the bytes. The cache is
166 /// therefore the honest carrier: it is handed a `&Device` at the one
167 /// moment residency is known for certain.
168 ///
169 /// `None` means "cannot prove", not "CPU" — and every consumer must
170 /// treat it as a refusal. [`Self::with_dims`] never had a device;
171 /// [`Self::set_layer`] installs caller-supplied storage from anywhere.
172 /// Both therefore forfeit re-bind and fall back to a plan rebuild,
173 /// which is what shipped in GAP-014 and is safe by construction.
174 device_location: Option<DeviceLocation>,
175}
176
177impl KvCache {
178 /// Legacy grow-by-replacement constructor. Layers start `None`; the
179 /// caller calls [`Self::set_layer`] each forward step with a freshly
180 /// allocated `KvLayer` whose storage is sized to the current cached
181 /// length. Subsequent steps replace the layer entirely with a
182 /// larger buffer.
183 ///
184 /// Replaced by [`Self::with_capacity`] when the caller knows the
185 /// generation's max sequence length up-front (the common case for
186 /// autoregressive decoding).
187 pub fn with_dims(n_layers: usize, n_kv_heads: usize, head_dim: usize) -> Self {
188 Self {
189 layers: (0..n_layers).map(|_| None).collect(),
190 cached_len: 0,
191 n_kv_heads,
192 head_dim,
193 max_seq_len: None,
194 dtype: None,
195 alloc_id: KvAllocId::next(),
196 // No device was named, and this constructor's whole shape is
197 // grow-by-replacement — the storage a plan baked is replaced
198 // every step anyway. Unprovable residency, and nothing lost.
199 device_location: None,
200 }
201 }
202
203 /// Pre-allocated KV cache. Every layer's K + V storage is allocated
204 /// up-front as a `[1, n_kv_heads, max_seq_len, head_dim]` zero
205 /// buffer on `device` with `dtype`. Subsequent forward steps write
206 /// fresh K/V slabs into these buffers via `Op::WriteSlice` rather
207 /// than growing-by-replacement.
208 ///
209 /// Memory footprint: `n_layers * 2 * n_kv_heads * max_seq_len *
210 /// head_dim * dtype_size` bytes. For Llama-7B at max_seq_len=4096,
211 /// bf16: 32 * 2 * 8 * 4096 * 128 * 2 ≈ 512 MiB.
212 ///
213 /// Returns `Err` if any per-layer allocation fails (e.g. CUDA OOM)
214 /// or the requested device hasn't been wired up in
215 /// [`crate::pipelined_bridge`] (Vulkan / Metal — D2H/H2D for those still
216 /// goes through the legacy executor).
217 pub fn with_capacity(
218 n_layers: usize,
219 n_kv_heads: usize,
220 head_dim: usize,
221 max_seq_len: usize,
222 dtype: DType,
223 device: &Device,
224 ) -> Result<Self> {
225 // Bridge-retirement Phase 3a (post-9c): allocate the 2N K/V
226 // buffers via `Op::Alloc` graph emission, not direct backend
227 // calls. The executor's `WorkItemKind::Alloc` arm dispatches
228 // per-backend; the per-`DeviceLocation` match that used to
229 // live in `alloc_zeroed_on` is now in the executor (the
230 // architectural dispatch layer).
231 let shape = Shape::from_dims(&[1, n_kv_heads, max_seq_len, head_dim]);
232 let layout = Layout::contiguous(shape.clone());
233 let target_loc = device.location();
234
235 // Build the transient graph. For non-CPU targets the first
236 // node is an `Op::Const` placeholder whose StorageCache entry
237 // carries a small "device anchor" storage — the executor's
238 // Alloc arm searches the cache for any storage on the target
239 // backend to derive the device handle, so this entry makes
240 // the first Op::Alloc's device lookup succeed. The anchor's
241 // NodeId must exist in the graph so `realize_many`'s
242 // `layout_cache` seeding (which calls `g.layout(id)` on every
243 // cache key) doesn't panic.
244 let graph = Arc::new(RwLock::new(Graph::new()));
245 let cache = StorageCache::new();
246 // Emit pairs of (Op::Alloc, Op::ZeroFill) per K/V slot. The
247 // ZeroFill consumes the Alloc destructively (in-place fill,
248 // output adopts the Alloc's Storage Arc). Realizing the
249 // ZeroFill IDs produces zero-initialized device storages.
250 //
251 // Phase 3a follow-up architecture: Op::Alloc gives uninit
252 // memory; Op::ZeroFill explicitly fills with zero. On Vulkan
253 // this replaces the host-staged-zeros path with device-side
254 // `vkCmdFillBuffer` (~2× the bandwidth saved). On CUDA the
255 // pair becomes uninit `cuMemAlloc` + async `cuMemsetD8Async`
256 // — same total cost as the old `alloc_zeros` but exposes the
257 // ZeroFill as a first-class graph node the optimizer can
258 // see (and skip if a downstream op covers the full buffer).
259 let zero_fill_ids: Vec<NodeId> = {
260 let mut g = graph
261 .write()
262 .map_err(|_| Error::Msg("graph lock poisoned during KvCache build".into()).bt())?;
263 (0..(2 * n_layers))
264 .map(|_| {
265 let alloc_id = g.push(Node {
266 op: Op::Alloc { target: target_loc },
267 inputs: vec![],
268 shape: shape.clone(),
269 dtype,
270 });
271 g.push(Node {
272 op: Op::ZeroFill,
273 inputs: vec![alloc_id],
274 shape: shape.clone(),
275 dtype,
276 })
277 })
278 .collect()
279 };
280
281 // Realize all 2*n_layers Op::ZeroFill targets in one pass —
282 // PipelinedExecutor::realize_many shares the compile/execute
283 // pipeline so device-handle reuse is automatic, and the
284 // executor's destructive_input cleanup evicts the Op::Alloc
285 // intermediate NodeIds while the ZeroFill targets adopt the
286 // same Arcs (post-fill bytes).
287 let realized = PipelinedExecutor::realize_many_with_devices(
288 Arc::clone(&graph),
289 &zero_fill_ids,
290 cache,
291 crate::pipelined_bridge::primary_device_registry(device)?,
292 )?;
293 if realized.len() != 2 * n_layers {
294 return Err(Error::Msg(format!(
295 "KvCache::with_capacity: realize_many returned {} storages \
296 for {} Op::ZeroFill targets — internal bug",
297 realized.len(),
298 2 * n_layers,
299 ))
300 .bt());
301 }
302
303 // Never-panic: the length is checked above, but the production path
304 // must not `.expect()` — surface a typed `Err` if the iterator runs
305 // short. (Same pattern as `alloc_batched_kv` below.)
306 let mut realized_iter = realized.into_iter();
307 let short = |what: &str, l: usize| {
308 Error::Msg(format!(
309 "alloc_kv: realize_many yielded fewer storages than expected \
310 (ran out at layer {l} fetching {what})"
311 ))
312 .bt()
313 };
314 let mut layers: Vec<Option<KvLayer>> = Vec::with_capacity(n_layers);
315 for l in 0..n_layers {
316 let (k_arc, _) = realized_iter.next().ok_or_else(|| short("K", l))?;
317 let (v_arc, _) = realized_iter.next().ok_or_else(|| short("V", l))?;
318 layers.push(Some(KvLayer {
319 k: k_arc,
320 v: v_arc,
321 k_layout: layout.clone(),
322 v_layout: layout.clone(),
323 k_version: 0,
324 v_version: 0,
325 k_authority: AuthorityState::Host,
326 v_authority: AuthorityState::Host,
327 }));
328 }
329
330 // Silence the unused-bind lint for elem_count when this
331 // path no longer needs the legacy alloc helper.
332 let _ = (n_kv_heads, max_seq_len, head_dim);
333
334 Ok(Self {
335 layers,
336 cached_len: 0,
337 n_kv_heads,
338 head_dim,
339 max_seq_len: Some(max_seq_len),
340 dtype: Some(dtype),
341 alloc_id: KvAllocId::next(),
342 // Every buffer above was `Op::Alloc { target: target_loc }`, so
343 // this is measured at the allocation, not inferred later.
344 device_location: Some(target_loc),
345 })
346 }
347
348 /// Borrow the K-or-V storage Arc for a given layer + slot. Used by
349 /// the forward path to bind cache storage to per-step Const nodes
350 /// via [`InferenceContext::insert`]. Returns `None` if the layer
351 /// isn't populated (with_dims path before first
352 /// [`Self::set_layer`]) or `layer_idx` is out of range.
353 pub fn slot_storage(&self, layer_idx: usize, slot: KvSlot) -> Option<Arc<RwLock<Storage>>> {
354 let layer = self.layer(layer_idx)?;
355 Some(match slot {
356 KvSlot::K => Arc::clone(&layer.k),
357 KvSlot::V => Arc::clone(&layer.v),
358 })
359 }
360
361 /// Bump a slot's monotonic version counter. Called after every
362 /// successful `Op::WriteSlice` targeting the slot — the forward
363 /// path invokes this once per (layer, slot) per step.
364 ///
365 /// The version is consumed by the future multi-device coherence
366 /// protocol (placeholder today — see [`AuthorityState`]).
367 pub fn bump_version(&mut self, layer_idx: usize, slot: KvSlot) {
368 if let Some(layer) = self.layer_mut(layer_idx) {
369 match slot {
370 KvSlot::K => layer.k_version += 1,
371 KvSlot::V => layer.v_version += 1,
372 }
373 }
374 }
375
376 pub fn n_layers(&self) -> usize {
377 self.layers.len()
378 }
379
380 pub fn layer(&self, li: usize) -> Option<&KvLayer> {
381 self.layers.get(li).and_then(|o| o.as_ref())
382 }
383
384 pub fn layer_mut(&mut self, li: usize) -> Option<&mut KvLayer> {
385 self.layers.get_mut(li).and_then(|o| o.as_mut())
386 }
387
388 /// Identity of the storage this cache currently owns — the value a held
389 /// [`DecodeSession`]'s validity key carries so a cache **swap** cannot be
390 /// mistaken for a continuation. See [`KvAllocId`] for why re-allocation
391 /// re-mints it and rewinding does not.
392 pub fn alloc_id(&self) -> KvAllocId {
393 self.alloc_id
394 }
395
396 /// Where this cache's storage lives, or `None` when that is not provable.
397 /// See the field's doc — `None` is a refusal, never a CPU default.
398 pub fn device_location(&self) -> Option<DeviceLocation> {
399 self.device_location
400 }
401
402 /// Install a layer's storage, replacing whatever was there.
403 ///
404 /// This **re-mints [`Self::alloc_id`]**: the storage `Arc` a held plan
405 /// baked into its `base_cache` for this layer is no longer the storage
406 /// this cache reads, so any plan welded to the old one must be rebuilt.
407 /// It also clears [`Self::device_location`]: the storage arrives from the
408 /// caller, so where it lives is no longer something this cache measured.
409 /// That forfeits [`DecodeSession::rebind_kv`] for the rest of this cache's
410 /// life — deliberately, because an unprovable residency spliced into a
411 /// baked plan is the GAP-014 failure one layer down.
412 pub fn set_layer(&mut self, li: usize, layer: KvLayer) {
413 self.layers[li] = Some(layer);
414 self.alloc_id = KvAllocId::next();
415 self.device_location = None;
416 }
417
418 /// Drop every layer; reset `cached_len` to zero. Use between
419 /// independent generations (the cache's K/V shapes are tied to
420 /// a specific prompt prefix).
421 ///
422 /// **Re-mints [`Self::alloc_id`]** — every storage `Arc` is released, so
423 /// this is an allocation change, not a rewind. Contrast
424 /// [`Self::truncate_to`], which moves only `cached_len` and therefore must
425 /// preserve the id.
426 pub fn clear(&mut self) {
427 for layer in &mut self.layers {
428 *layer = None;
429 }
430 self.cached_len = 0;
431 self.alloc_id = KvAllocId::next();
432 // There is no storage left to have a residency. Repopulating goes
433 // through `set_layer`, which cannot prove one either.
434 self.device_location = None;
435 }
436
437 /// Shrink the cache to `new_len` cached positions. Speculative-
438 /// decoding's reject path calls this after a draft batch is
439 /// rejected by the target model.
440 ///
441 /// **Phase E.3.0 limitation**: this only updates `cached_len`;
442 /// the underlying storages and their layouts are *not* shrunk.
443 /// The grow-by-replacement pattern (today) means the next forward
444 /// pass would still see the old layout's full extent. Phase E.3.2
445 /// pairs this with pre-allocated buffers + `Op::WriteSlice` so
446 /// truncate becomes a pure metadata update — the trailing rows
447 /// of the pre-allocated buffer simply stop being read.
448 ///
449 /// **Deliberately does NOT touch [`Self::alloc_id`].** Rewinding the
450 /// conversation is not re-allocating the buffers: a held plan is still
451 /// welded to exactly the right storage, so invalidating here would forfeit
452 /// plan reuse on every rejected draft batch and buy no correctness. The
453 /// id names the allocation, never the conversation — see [`KvAllocId`].
454 pub fn truncate_to(&mut self, new_len: usize) {
455 if new_len < self.cached_len {
456 self.cached_len = new_len;
457 }
458 }
459
460 /// Write host-supplied K/V bytes into layer `layer_idx`'s `slot` buffer at
461 /// position range `[start, start+n)` — the `KvCache`-side sibling of
462 /// [`DeviceKvPool::write_block_bytes`](crate::kv_block_pool_device::DeviceKvPool::write_block_bytes).
463 ///
464 /// Builds a throwaway `Op::Const`(bytes) → `Op::WriteSlice` graph and
465 /// realizes it ONCE into the SAME buffer `Arc` this cache already holds —
466 /// it does **not** replace the Arc, so unlike [`Self::set_layer`] this
467 /// does **not** touch [`Self::alloc_id`] or [`Self::device_location`]: a
468 /// [`DecodeSession`] already welded to this cache's buffers (via
469 /// `base_cache`) sees the write transparently on its next token, with no
470 /// rebind and no rebuild — the write lands in the exact buffer the held
471 /// plan's `Op::WriteSlice` nodes already target.
472 ///
473 /// `bytes` is `n * n_kv_heads * head_dim * dtype.size_in_bytes()` raw
474 /// little-endian element bytes, row-major `[1, n_kv_heads, n, head_dim]`
475 /// — **HEAD-MAJOR** (position is axis 2). This is NOT the same layout as
476 /// [`DeviceKvPool`](crate::kv_block_pool_device::DeviceKvPool)'s
477 /// **position-major** `[block_size, Hkv, D]` block layout: a caller
478 /// moving bytes from the paged pool into a `KvCache` must transpose, a
479 /// plain memcpy silently produces wrong attention.
480 ///
481 /// `Err` (never a panic): this cache has no fixed dtype/capacity (built
482 /// via [`Self::with_dims`] rather than [`Self::with_capacity`] — this
483 /// primitive is `with_capacity`-only, since the legacy grow-by-replacement
484 /// path has no stable buffer to write into); `layer_idx` is out of range
485 /// or unpopulated; `start + n` exceeds the allocated `max_seq_len`; or
486 /// `bytes.len()` doesn't match the expected size for `n` positions.
487 pub fn write_bytes(
488 &self,
489 layer_idx: usize,
490 slot: KvSlot,
491 start: usize,
492 n: usize,
493 bytes: &[u8],
494 device: &Device,
495 ) -> Result<()> {
496 let dtype = self.dtype.ok_or_else(|| {
497 Error::Msg(
498 "KvCache::write_bytes: cache has no fixed dtype — not built via with_capacity"
499 .into(),
500 )
501 .bt()
502 })?;
503 let max_seq_len = self.max_seq_len.ok_or_else(|| {
504 Error::Msg(
505 "KvCache::write_bytes: cache has no fixed capacity — not built via with_capacity"
506 .into(),
507 )
508 .bt()
509 })?;
510 if start + n > max_seq_len {
511 return Err(Error::Msg(format!(
512 "KvCache::write_bytes: range [{start}, {}) exceeds max_seq_len {max_seq_len}",
513 start + n,
514 ))
515 .bt());
516 }
517 let elem_bytes = kv_cache_dtype_elem_bytes(dtype)?;
518 let want = n * self.n_kv_heads * self.head_dim * elem_bytes;
519 if bytes.len() != want {
520 return Err(Error::Msg(format!(
521 "KvCache::write_bytes: {} bytes != expected {want} \
522 ([1, n_kv_heads {}, n {n}, head_dim {}] for {dtype:?})",
523 bytes.len(),
524 self.n_kv_heads,
525 self.head_dim,
526 ))
527 .bt());
528 }
529 let layer = self.layer(layer_idx).ok_or_else(|| {
530 Error::Msg(format!(
531 "KvCache::write_bytes: layer {layer_idx} out of range or unpopulated"
532 ))
533 .bt()
534 })?;
535 let buf = match slot {
536 KvSlot::K => Arc::clone(&layer.k),
537 KvSlot::V => Arc::clone(&layer.v),
538 };
539 let full_shape = Shape::from_dims(&[1, self.n_kv_heads, max_seq_len, self.head_dim]);
540 let src = kv_cache_const_from_bytes(
541 dtype,
542 bytes,
543 Shape::from_dims(&[1, self.n_kv_heads, n, self.head_dim]),
544 device,
545 )?;
546 let dest = src.const_placeholder_like(full_shape, dtype);
547 let ranges = vec![
548 (0, 1),
549 (0, self.n_kv_heads),
550 (start, start + n),
551 (0, self.head_dim),
552 ];
553 let post = dest.write_slice(&src, ranges)?;
554 let mut cache = StorageCache::new();
555 cache.insert(dest.node_id(), buf);
556 let _ = crate::pipelined_bridge::realize_one_bytes_with_initial(
557 post.graph_handle(),
558 post.node_id(),
559 device,
560 cache,
561 )?;
562 Ok(())
563 }
564}
565
566/// Byte width of one `KvCache` element for byte-level movement — the
567/// `KvCache`-side sibling of
568/// [`DeviceKvPool::dtype_elem_bytes`](crate::kv_block_pool_device::DeviceKvPool).
569/// F32/BF16 only, matching [`KvCache::write_bytes`]'s supported dtypes.
570fn kv_cache_dtype_elem_bytes(dtype: DType) -> Result<usize> {
571 match dtype {
572 DType::F32 => Ok(4),
573 DType::BF16 => Ok(2),
574 other => Err(Error::Msg(format!(
575 "KvCache: byte movement unsupported for dtype {other:?} (F32/BF16)",
576 ))
577 .bt()),
578 }
579}
580
581/// Build a fresh-graph `Op::Const` of `dtype` from raw little-endian element
582/// bytes — the `KvCache`-side sibling of
583/// [`DeviceKvPool::const_from_bytes`](crate::kv_block_pool_device::DeviceKvPool).
584/// Dispatches `dtype` to the matching typed graph constructor via
585/// alignment-safe `try_cast_slice` (never panics).
586fn kv_cache_const_from_bytes(
587 dtype: DType,
588 bytes: &[u8],
589 shape: Shape,
590 device: &Device,
591) -> Result<crate::lazy::Tensor> {
592 match dtype {
593 DType::F32 => {
594 let v: &[f32] = bytemuck::try_cast_slice(bytes).map_err(|e| {
595 Error::Msg(format!("kv_cache_const_from_bytes: f32 cast: {e:?}")).bt()
596 })?;
597 crate::lazy::Tensor::from_f32(v.to_vec(), shape, device)
598 }
599 DType::BF16 => {
600 let v: &[half::bf16] = bytemuck::try_cast_slice(bytes).map_err(|e| {
601 Error::Msg(format!("kv_cache_const_from_bytes: bf16 cast: {e:?}")).bt()
602 })?;
603 let anchor =
604 crate::lazy::Tensor::from_f32(vec![0.0f32], Shape::from_dims(&[1]), device)?;
605 crate::lazy::Tensor::from_bf16_on(anchor.graph(), v.to_vec(), shape, device)
606 }
607 other => Err(Error::Msg(format!(
608 "kv_cache_const_from_bytes: unsupported dtype {other:?} (F32/BF16)",
609 ))
610 .bt()),
611 }
612}
613
614/// One layer's `(K, V)` cache storages. A KV cache is a `Vec` of these, one
615/// per layer, and the two halves are always allocated and dropped together.
616type KvStoragePair = (Arc<RwLock<Storage>>, Arc<RwLock<Storage>>);
617
618/// Allocate `n_layers` pairs of zero-initialized `[k, n_kv_heads,
619/// max_seq_len, head_dim]` K/V buffers on `device` with `dtype` — the shared
620/// batch-slot KV buffer for the multi-session batched decode arm (serving
621/// Increment 1, C3). Same `Op::Alloc`→`Op::ZeroFill` emission +
622/// `PipelinedExecutor::realize_many` pattern as [`KvCache::with_capacity`],
623/// with the leading dim `k` (the batch slot) instead of `1`. Returns the
624/// per-layer `(K_arc, V_arc)` pairs; the caller binds them into a batched
625/// decode graph.
626///
627/// Returns `Err` if any allocation fails (fail-on-OOM, spec #6).
628pub fn alloc_batched_kv(
629 k: usize,
630 n_layers: usize,
631 n_kv_heads: usize,
632 head_dim: usize,
633 max_seq_len: usize,
634 dtype: DType,
635 device: &Device,
636) -> Result<Vec<KvStoragePair>> {
637 let shape = Shape::from_dims(&[k, n_kv_heads, max_seq_len, head_dim]);
638 let target_loc = device.location();
639
640 let graph = Arc::new(RwLock::new(Graph::new()));
641 let cache = StorageCache::new();
642
643 let zero_fill_ids: Vec<NodeId> = {
644 let mut g = graph
645 .write()
646 .map_err(|_| Error::Msg("graph lock poisoned during alloc_batched_kv".into()).bt())?;
647 (0..(2 * n_layers))
648 .map(|_| {
649 let alloc_id = g.push(Node {
650 op: Op::Alloc { target: target_loc },
651 inputs: vec![],
652 shape: shape.clone(),
653 dtype,
654 });
655 g.push(Node {
656 op: Op::ZeroFill,
657 inputs: vec![alloc_id],
658 shape: shape.clone(),
659 dtype,
660 })
661 })
662 .collect()
663 };
664
665 let realized = PipelinedExecutor::realize_many_with_devices(
666 Arc::clone(&graph),
667 &zero_fill_ids,
668 cache,
669 crate::pipelined_bridge::primary_device_registry(device)?,
670 )?;
671 if realized.len() != 2 * n_layers {
672 return Err(Error::Msg(format!(
673 "alloc_batched_kv: realize_many returned {} storages for {} Op::ZeroFill targets",
674 realized.len(),
675 2 * n_layers,
676 ))
677 .bt());
678 }
679
680 // Never-panic: the length is checked above, but the production path must
681 // not `.expect()` — surface a typed `Err` if the iterator is short.
682 let mut it = realized.into_iter();
683 let mut pairs = Vec::with_capacity(n_layers);
684 let short = || {
685 Error::Msg(
686 "alloc_batched_kv: realize_many yielded fewer storages than expected".to_string(),
687 )
688 .bt()
689 };
690 for _ in 0..n_layers {
691 let (k_arc, _) = it.next().ok_or_else(short)?;
692 let (v_arc, _) = it.next().ok_or_else(short)?;
693 pairs.push((k_arc, v_arc));
694 }
695 Ok(pairs)
696}
697
698// ===========================================================================
699// LatentKvCache — N-slot generalization of KvCache (MLA increment 4)
700// ===========================================================================
701
702/// One slot's persistent latent buffer within a [`LatentKvCache`] layer.
703/// The per-slot analogue of [`KvLayer`]'s `k`/`v` pair, generalized to an
704/// arbitrary slot count and independent per-slot trailing shape.
705pub struct LatentSlot {
706 pub storage: Arc<RwLock<Storage>>,
707 /// View layout into `storage`. For the pre-allocated (capacity)
708 /// buffers [`LatentKvCache::with_capacity`] allocates, the layout
709 /// matches the storage's full `[max_seq_len, ...trailing]` shape.
710 pub layout: Layout,
711 /// Monotonic write version. Bumps on every successful
712 /// `Op::WriteSlice` targeting this slot. Placeholder for the future
713 /// multi-device coherence protocol — mirrors [`KvLayer::k_version`] /
714 /// `v_version`.
715 pub version: u64,
716 /// Coherence authority. Placeholder — see [`AuthorityState`].
717 pub authority: AuthorityState,
718}
719
720/// Cross-graph, cross-forward-pass persistent **N-slot** decode cache —
721/// the [`KvCache`] generalization for latent-caching attention
722/// architectures.
723///
724/// [`KvCache`] hardwires a symmetric K/V pair (two buffers per layer,
725/// same shape). That's wrong for compression architectures:
726///
727/// - **Multi-head Latent Attention (DeepSeek-V2 MLA)**: per layer, a
728/// low-rank compressed latent `[kv_lora_rank]` (slot 0) **and** a
729/// single-head RoPE key `[qk_rope_head_dim]` (slot 1) — two slots of
730/// *different* trailing shape, neither a `[n_kv_heads, head_dim]` K/V.
731/// - **Two-projection attention / QKV pruning**: a single retained
732/// projection per layer — one slot.
733///
734/// `LatentKvCache` is this module's counterpart to
735/// [`crate::lazy_latent_cache::LatentCache`] — that type makes the
736/// exact same **per-layer, ordered list of latent buffers with
737/// independent trailing shapes** generalization for the **per-forward-
738/// pass** (single [`fuel_graph::Graph`]-anchored, functional
739/// append-and-thread) lifecycle. `LatentKvCache` is the **persistent**
740/// sibling: device-resident `Arc<RwLock<Storage>>` buffers that survive
741/// across graphs/forward calls and are mutated in place via
742/// `Op::WriteSlice`, exactly the relationship [`KvCache`] has to a plain
743/// per-pass K/V cache. Read both modules' docs together for the two
744/// lifecycles side by side.
745///
746/// # Shape contract
747///
748/// Slot `s` of every layer is a buffer `[max_seq_len, ...slot_trailing[s]]`
749/// — the capacity axis is dim **0**. This differs from [`KvCache`]'s `[1,
750/// n_kv_heads, max_seq_len, head_dim]` convention (capacity axis 2):
751/// a latent is a per-token *vector*, not a per-head *plane*, so there is
752/// no head axis to lead with. Matches [`crate::lazy_latent_cache::
753/// LatentCache`]'s dim-0 convention exactly — this type's per-slot
754/// buffer is byte-for-byte what that type's `slot_buffer_full` realizes,
755/// modulo device residency.
756pub struct LatentKvCache {
757 /// `layers[l]` is `None` until populated; `Some(slots)` holds one
758 /// [`LatentSlot`] per slot index (pipeline-parallel friendly — mirrors
759 /// [`KvCache::layers`]).
760 pub layers: Vec<Option<Vec<LatentSlot>>>,
761 pub cached_len: usize,
762 /// Per-slot trailing shape (past the leading capacity axis); its
763 /// length is the per-layer slot count.
764 pub slot_trailing: Vec<Vec<usize>>,
765 pub max_seq_len: usize,
766 pub dtype: DType,
767 /// Identity of the allocation backing this cache. Same role and same
768 /// re-mint rules as [`KvCache::alloc_id`] — MLA reuses [`DecodeSession`]
769 /// verbatim (its 2 latent slots ride `kv_nodes` as `(latent, kpe)` pairs),
770 /// so it inherits the same welding and needs the same guard.
771 alloc_id: KvAllocId,
772 /// Where the slot buffers live. Unconditional here, unlike
773 /// [`KvCache::device_location`]: this type has exactly one constructor
774 /// and it is handed a `&Device`, so residency is never unprovable.
775 device_location: DeviceLocation,
776}
777
778impl LatentKvCache {
779 /// Pre-allocated N-slot latent cache. Every layer's slot buffers are
780 /// allocated up-front as zero buffers on `device` with `dtype`,
781 /// shaped `[max_seq_len, ...slot_trailing[s]]`. Mirrors [`KvCache::
782 /// with_capacity`]'s `Op::Alloc` → `Op::ZeroFill` graph-emission
783 /// pattern exactly, generalized from a fixed 2-buffer (K, V) layer to
784 /// `slot_trailing.len()` buffers of independent shape.
785 ///
786 /// Returns `Err` for degenerate geometry (`n_layers == 0`,
787 /// `max_seq_len == 0`, or no slots) or if any per-layer allocation
788 /// fails (e.g. CUDA OOM / an unwired device).
789 pub fn with_capacity(
790 n_layers: usize,
791 max_seq_len: usize,
792 slot_trailing: Vec<Vec<usize>>,
793 dtype: DType,
794 device: &Device,
795 ) -> Result<Self> {
796 if n_layers == 0 {
797 return Err(
798 Error::Msg("LatentKvCache::with_capacity: n_layers must be >= 1".into()).bt(),
799 );
800 }
801 if max_seq_len == 0 {
802 return Err(Error::Msg(
803 "LatentKvCache::with_capacity: max_seq_len must be >= 1".into(),
804 )
805 .bt());
806 }
807 if slot_trailing.is_empty() {
808 return Err(Error::Msg(
809 "LatentKvCache::with_capacity: need at least one slot (slot_trailing empty)".into(),
810 )
811 .bt());
812 }
813 let n_slots = slot_trailing.len();
814 let shapes: Vec<Shape> = slot_trailing
815 .iter()
816 .map(|trailing| {
817 let mut dims = Vec::with_capacity(1 + trailing.len());
818 dims.push(max_seq_len);
819 dims.extend_from_slice(trailing);
820 Shape::from_dims(&dims)
821 })
822 .collect();
823 let layouts: Vec<Layout> = shapes
824 .iter()
825 .map(|s| Layout::contiguous(s.clone()))
826 .collect();
827 let target_loc = device.location();
828
829 // Transient graph, same device-anchor trick + Alloc/ZeroFill
830 // emission pattern as KvCache::with_capacity — see that
831 // constructor's doc for the full rationale.
832 let graph = Arc::new(RwLock::new(Graph::new()));
833 let cache = StorageCache::new();
834
835 // Emit (Op::Alloc, Op::ZeroFill) pairs for every (layer, slot),
836 // each shaped per its own slot's shape.
837 let mut zero_fill_ids: Vec<NodeId> = Vec::with_capacity(n_layers * n_slots);
838 {
839 let mut g = graph.write().map_err(|_| {
840 Error::Msg("graph lock poisoned during LatentKvCache build".into()).bt()
841 })?;
842 for _ in 0..n_layers {
843 for shape in &shapes {
844 let alloc_id = g.push(Node {
845 op: Op::Alloc { target: target_loc },
846 inputs: vec![],
847 shape: shape.clone(),
848 dtype,
849 });
850 let zf_id = g.push(Node {
851 op: Op::ZeroFill,
852 inputs: vec![alloc_id],
853 shape: shape.clone(),
854 dtype,
855 });
856 zero_fill_ids.push(zf_id);
857 }
858 }
859 }
860
861 // Realize all n_layers * n_slots Op::ZeroFill targets in one pass
862 // — see KvCache::with_capacity's doc for why a single realize_many
863 // call is used instead of one realize per buffer.
864 let realized = PipelinedExecutor::realize_many_with_devices(
865 Arc::clone(&graph),
866 &zero_fill_ids,
867 cache,
868 crate::pipelined_bridge::primary_device_registry(device)?,
869 )?;
870 if realized.len() != n_layers * n_slots {
871 return Err(Error::Msg(format!(
872 "LatentKvCache::with_capacity: realize_many returned {} storages \
873 for {} Op::ZeroFill targets — internal bug",
874 realized.len(),
875 n_layers * n_slots,
876 ))
877 .bt());
878 }
879
880 // Never-panic: length checked above; still surface a typed `Err`
881 // rather than `.expect()` on a production path.
882 let mut realized_iter = realized.into_iter();
883 let short = |l: usize| {
884 Error::Msg(format!(
885 "alloc_latent: realize_many yielded fewer storages than \
886 expected (ran out at layer {l})"
887 ))
888 .bt()
889 };
890 let mut layers: Vec<Option<Vec<LatentSlot>>> = Vec::with_capacity(n_layers);
891 for l in 0..n_layers {
892 let mut slots = Vec::with_capacity(n_slots);
893 for layout in &layouts {
894 let (arc, _) = realized_iter.next().ok_or_else(|| short(l))?;
895 slots.push(LatentSlot {
896 storage: arc,
897 layout: layout.clone(),
898 version: 0,
899 authority: AuthorityState::Host,
900 });
901 }
902 layers.push(Some(slots));
903 }
904
905 Ok(Self {
906 layers,
907 cached_len: 0,
908 slot_trailing,
909 max_seq_len,
910 dtype,
911 alloc_id: KvAllocId::next(),
912 device_location: target_loc,
913 })
914 }
915
916 /// Borrow the slot `s` storage Arc for layer `layer_idx`. `None` if
917 /// the layer is unpopulated or either index is out of range. Used by
918 /// the forward path to bind cache storage to per-step Const nodes via
919 /// [`InferenceContext::insert`]. Mirrors [`KvCache::slot_storage`].
920 pub fn slot_storage(&self, layer_idx: usize, slot: usize) -> Option<Arc<RwLock<Storage>>> {
921 let layer = self.layers.get(layer_idx)?.as_ref()?;
922 layer.get(slot).map(|s| Arc::clone(&s.storage))
923 }
924
925 /// Bump slot `s`'s monotonic version counter for `layer_idx`. No-op
926 /// (never panics) if either index is out of range. Mirrors
927 /// [`KvCache::bump_version`].
928 pub fn bump_version(&mut self, layer_idx: usize, slot: usize) {
929 if let Some(Some(layer)) = self.layers.get_mut(layer_idx)
930 && let Some(s) = layer.get_mut(slot)
931 {
932 s.version += 1;
933 }
934 }
935
936 pub fn n_layers(&self) -> usize {
937 self.layers.len()
938 }
939
940 /// Number of slots per layer.
941 pub fn n_slots(&self) -> usize {
942 self.slot_trailing.len()
943 }
944
945 /// Trailing shape of slot `s` (past the leading capacity axis).
946 pub fn slot_trailing(&self, s: usize) -> &[usize] {
947 &self.slot_trailing[s]
948 }
949
950 /// Identity of the storage this cache currently owns. Mirrors
951 /// [`KvCache::alloc_id`]; see [`KvAllocId`].
952 pub fn alloc_id(&self) -> KvAllocId {
953 self.alloc_id
954 }
955
956 /// Drop every layer; reset `cached_len` to zero. Mirrors [`KvCache::clear`],
957 /// including the [`Self::alloc_id`] re-mint — every storage `Arc` is
958 /// released, so a plan welded to them must be rebuilt.
959 pub fn clear(&mut self) {
960 for layer in &mut self.layers {
961 *layer = None;
962 }
963 self.cached_len = 0;
964 self.alloc_id = KvAllocId::next();
965 }
966
967 /// Shrink the cache to `new_len` cached positions — metadata-only,
968 /// same Phase E.3.0 limitation and rationale as [`KvCache::
969 /// truncate_to`]: the underlying storages are not shrunk; the
970 /// pre-allocated buffers' trailing rows simply stop being read until
971 /// overwritten by a later `Op::WriteSlice` at the same positions.
972 ///
973 /// Deliberately preserves [`Self::alloc_id`] — a rewind is not a
974 /// re-allocation. Same rule as [`KvCache::truncate_to`].
975 pub fn truncate_to(&mut self, new_len: usize) {
976 if new_len < self.cached_len {
977 self.cached_len = new_len;
978 }
979 }
980}
981
982// ===========================================================================
983// Guarded KV re-bind (GAP-028)
984// ===========================================================================
985
986/// A KV allocation a held [`DecodeSession`] can be re-bound onto — the one
987/// abstraction over [`KvCache`] (K/V pairs) and [`LatentKvCache`] (MLA's
988/// `(latent, kpe)` pairs), which already share `DecodeSession` verbatim and
989/// therefore share its welding.
990///
991/// Deliberately narrow: identity, residency, and the storage behind a baked
992/// `kv_nodes` slot. Geometry is **not** here, because the guard does not ask
993/// this trait for it — it compares the incoming storage against the storage
994/// already baked into the plan, which is ground truth and cannot drift from
995/// whatever a cache believes about itself.
996pub trait KvRebindSource {
997 /// Identity of this allocation. See [`KvAllocId`].
998 fn alloc_id(&self) -> KvAllocId;
999 /// Where the storage lives, or `None` when that is not provable — which
1000 /// [`DecodeSession::rebind_kv`] treats as a refusal, never as a default.
1001 fn rebind_location(&self) -> Option<DeviceLocation>;
1002 /// Storage for slot `which` (0 or 1) of `layer` — the two halves of the
1003 /// plan's `kv_nodes[layer]` pair, in the order the builder bound them.
1004 fn rebind_slot(&self, layer: usize, which: usize) -> Option<Arc<RwLock<Storage>>>;
1005}
1006
1007impl KvRebindSource for KvCache {
1008 fn alloc_id(&self) -> KvAllocId {
1009 KvCache::alloc_id(self)
1010 }
1011 fn rebind_location(&self) -> Option<DeviceLocation> {
1012 self.device_location
1013 }
1014 fn rebind_slot(&self, layer: usize, which: usize) -> Option<Arc<RwLock<Storage>>> {
1015 // The builder pushes `(k_id, v_id)` — this order is the contract.
1016 let slot = match which {
1017 0 => KvSlot::K,
1018 1 => KvSlot::V,
1019 _ => return None,
1020 };
1021 self.slot_storage(layer, slot)
1022 }
1023}
1024
1025impl KvRebindSource for LatentKvCache {
1026 fn alloc_id(&self) -> KvAllocId {
1027 LatentKvCache::alloc_id(self)
1028 }
1029 fn rebind_location(&self) -> Option<DeviceLocation> {
1030 Some(self.device_location)
1031 }
1032 fn rebind_slot(&self, layer: usize, which: usize) -> Option<Arc<RwLock<Storage>>> {
1033 // MLA binds `(latent, kpe)` as slots 0 and 1 — same positional
1034 // contract as K/V above, which is why one `DecodeSession` serves both.
1035 self.slot_storage(layer, which)
1036 }
1037}
1038
1039/// Why a held plan could not be re-bound onto a replacement KV allocation.
1040///
1041/// A refusal is a normal outcome, not an error: the caller falls back to the
1042/// GAP-014 rebuild, which is correct by construction. The variants exist so
1043/// the guard's reasons are *nameable in a test* — the point of GAP-028 is that
1044/// this guard is load-bearing for correctness, so "it refused" is not enough
1045/// to know it refused for the right reason.
1046#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1047pub enum RebindRefusal {
1048 /// The replacement cannot say where its storage lives, so residency
1049 /// cannot be proven equal to the plan's. See [`KvCache::device_location`].
1050 ResidencyUnknown,
1051 /// The plan's placement stamps and residency copies were baked for a
1052 /// different device.
1053 ResidencyDiffers {
1054 baked: DeviceLocation,
1055 incoming: DeviceLocation,
1056 },
1057 /// The replacement has no storage for a slot the plan writes.
1058 MissingSlot { layer: usize, which: usize },
1059 /// A baked KV `Const` has no `base_cache` entry — an internal
1060 /// inconsistency in the held plan, not a property of the replacement.
1061 UnbakedSlot { layer: usize, which: usize },
1062 /// The replacement storage is not byte-interchangeable with the baked
1063 /// storage: different dtype, encoding, backend variant, or extent.
1064 StorageDiffers { layer: usize, which: usize },
1065 /// A storage lock was poisoned while comparing. Refuse rather than guess.
1066 LockPoisoned,
1067}
1068
1069/// Whether a held plan may serve a step, and if not, why not — **one** set of
1070/// comparisons, so the "is it valid" and "is only the allocation different"
1071/// questions cannot drift apart. [`DecodeSession::is_valid_for`] is a thin
1072/// view over this.
1073#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1074pub enum PlanValidity {
1075 /// Reuse the plan as-is.
1076 Valid,
1077 /// Everything the plan bakes still matches **except which KV allocation
1078 /// it is welded to.** A guarded [`DecodeSession::rebind_kv`] may rescue
1079 /// it; without one, the plan MUST NOT be reused — that is GAP-014.
1080 AllocationChanged,
1081 /// Something structural differs (shape, layer count, dtype, or the model
1082 /// itself). Rebuild.
1083 Stale,
1084}
1085
1086/// Everything about a storage that a baked graph depends on and that is
1087/// readable from the storage itself. Deliberately excludes residency, which
1088/// is NOT readable — see [`DecodeSession::rebind_kv`].
1089#[derive(PartialEq, Eq)]
1090struct StorageFingerprint {
1091 dtype: DType,
1092 stype: SType,
1093 bundled: bool,
1094 backend: std::mem::Discriminant<BackendStorage>,
1095 len_bytes: usize,
1096}
1097
1098fn fingerprint(s: &Arc<RwLock<Storage>>) -> Option<StorageFingerprint> {
1099 let g = s.read().ok()?;
1100 Some(StorageFingerprint {
1101 dtype: g.dtype,
1102 stype: g.stype.clone(),
1103 bundled: g.bundle.is_some(),
1104 backend: std::mem::discriminant(&g.inner),
1105 len_bytes: g.inner.len_bytes(),
1106 })
1107}
1108
1109/// May `incoming` stand in for `baked` inside an already-optimized graph?
1110/// `None` means a lock was poisoned and the question could not be answered —
1111/// which callers must treat as "no", not as "probably fine".
1112///
1113/// The two locks are taken one at a time and released before the next, so this
1114/// cannot deadlock even if some future caller passes overlapping storage.
1115fn storage_is_interchangeable(
1116 baked: &Arc<RwLock<Storage>>,
1117 incoming: &Arc<RwLock<Storage>>,
1118) -> Option<bool> {
1119 if Arc::ptr_eq(baked, incoming) {
1120 return Some(true);
1121 }
1122 let a = fingerprint(baked)?;
1123 let b = fingerprint(incoming)?;
1124 Some(a == b)
1125}
1126
1127// ===========================================================================
1128// DecodeSession (Phase D · D2b — plan-once persistent decode)
1129// ===========================================================================
1130
1131/// Per-token re-bound data-Const Arcs for a persistent decode step
1132/// (Phase D · D2b). Each is a device-resident `fuel_memory::Storage`
1133/// built from freshly recomputed host bytes (token-ids = the new token,
1134/// RoPE cos+sin at `position = cached_len`, mask with the shifted `-inf`
1135/// boundary). [`DecodeSession::realize_token`] overwrites the held
1136/// `base_cache`'s stable data-Const entries with these for the token.
1137pub struct DecodeTokenData {
1138 pub token_ids: Arc<RwLock<Storage>>,
1139 pub rope_cos: Arc<RwLock<Storage>>,
1140 pub rope_sin: Arc<RwLock<Storage>>,
1141 pub mask: Arc<RwLock<Storage>>,
1142 /// The device-resident KV-write offset (`cached_len` as a rank-0
1143 /// `I64`), present ONLY on the device-offset decode path (CUDA/CPU
1144 /// targets, where `Op::WriteSliceDoff` reads the start from this
1145 /// buffer at kernel launch — capture-ready). `None` on the SymEnv
1146 /// path (Vulkan), where the KV write is `Op::WriteSlice` with a
1147 /// `DynScalar::Sym(cached_len)` offset resolved host-side per token.
1148 pub offset: Option<Arc<RwLock<Storage>>>,
1149}
1150
1151/// Plan-once persistent decode state for one `LlamaModel` + one
1152/// [`KvCache`] capacity/dtype. Built on the first `seq == 1` decode token;
1153/// reused (graph + optimize view HELD, only the per-token data Consts +
1154/// `SymEnv` re-bound) for every subsequent token.
1155///
1156/// The ~1.8×/token win lives here: the decode-step graph is built +
1157/// `prepare`d (D2H `Op::Copy` spliced at the root) + `optimize_graph`'d
1158/// (placement stamps + residency `Op::Copy` + layout `Op::Contiguize`
1159/// baked in place) ONCE, then re-realized via the D2a prebuilt seam
1160/// ([`InferenceContext::realize_prebuilt_as_with_env`]) which SKIPS both
1161/// `prepare` and `optimize_graph`.
1162///
1163/// Held by the generate-loop owner (the caller of
1164/// `forward_with_kv_context_persistent`), NOT by the immutable
1165/// `LlamaModel` (the model is read-only weights; a session is per-
1166/// generation state). Constructed lazily as `Option<DecodeSession>` and
1167/// dropped-then-rebuilt on any validity-key mismatch / `TopologyChanged`
1168/// / a non-`seq==1` step (see `forward_with_kv_context_persistent`).
1169///
1170/// ## Why the graph is HELD here
1171///
1172/// D1 rebuilds a fresh `Tensor` graph every token and drops it after
1173/// realize. D2 keeps the `Arc<RwLock<Graph>>` alive on the session so the
1174/// already-optimized structure (the stamps + inserted copies) survives.
1175/// The cached [`OptimizedGraph`] holds only `{roots, generation}` — it
1176/// bakes NO Const data / storage / `SymEnv`, so reusing it is sound
1177/// **iff the graph structure + topology generation are unchanged** (D1's
1178/// input-independent-graph guarantee).
1179pub struct DecodeSession {
1180 /// The held decode-step graph, ALREADY optimized in place (stamps +
1181 /// residency/layout copies + D2H root splice baked in). Structure is
1182 /// stable across tokens (D1 guarantee).
1183 graph: Arc<RwLock<Graph>>,
1184 /// The cached optimize view from the first realize. Holds only
1185 /// `{roots, generation}`; valid while `graph` structure + topology
1186 /// generation are unchanged.
1187 optimized: OptimizedGraph,
1188 /// The realize root the executor was asked for — the D2H `Op::Copy`
1189 /// NodeId `prepare` spliced (NOT the logits node itself). Stable
1190 /// across tokens.
1191 effective_target: NodeId,
1192 /// The logits node (pre-D2H-splice) — `effective_target`'s input.
1193 /// Retained for D3 attribution / debugging; the executor is asked
1194 /// for `effective_target`. Also the CapturedRun replay TARGET
1195 /// (`CapturedDecodeSession::capture` must be given the pre-splice
1196 /// node — see [`Self::logits_node`]'s doc for why).
1197 logits_node: NodeId,
1198 /// Stable re-bindable token-ids Const (`[seq]` U32).
1199 token_ids_node: NodeId,
1200 /// Stable re-bindable RoPE cos table Const (`[seq, head_dim]` F32).
1201 rope_cos_node: NodeId,
1202 /// Stable re-bindable RoPE sin table Const (`[seq, head_dim]` F32).
1203 rope_sin_node: NodeId,
1204 /// Stable re-bindable causal mask Const (`[1, 1, seq, max_seq_len]`
1205 /// F32) — hoisted to ONE shared Const (was per-layer in D1).
1206 mask_node: NodeId,
1207 /// Per-layer `(k_const, v_const)` stable KV placeholder NodeIds. The
1208 /// KV Arcs are re-bound once at build time and mutated in place by
1209 /// `Op::WriteSlice`/`Op::WriteSliceDoff` each token (never re-inserted
1210 /// per token).
1211 kv_nodes: Vec<(NodeId, NodeId)>,
1212 /// The stable rank-0 `I64` KV-write offset Const, present ONLY on the
1213 /// **device-offset** decode path (CUDA/CPU — `Op::WriteSliceDoff`
1214 /// reads `cached_len` from this buffer device-side at launch, making
1215 /// the decode step CUDA-graph-capturable). `None` on the SymEnv path
1216 /// (Vulkan — the offset is host-resolved via `cached_len_sym`). When
1217 /// `Some`, `realize_token` re-binds the per-token offset Arc into the
1218 /// base-cache clone alongside token-ids/RoPE/mask.
1219 offset_node: Option<NodeId>,
1220 /// The symbol the per-pass `SymEnv` binds to `cached_len` each token.
1221 cached_len_sym: SymId,
1222 /// The symbol the per-pass `SymEnv` binds to the live **attended
1223 /// prefix length** (`cached_len + seq`) each token. This is the
1224 /// `k_len` the optimizer-emitted CUDA flash-decode arm resolves
1225 /// against (`decode_flash::DecodeFlashSpec::k_len`); distinct from
1226 /// `cached_len_sym` because the flash kernel attends `[0, k_len)`
1227 /// (the whole prefix including this token), while the KV-write lands
1228 /// at `[cached_len, cached_len + seq)`. Unreferenced on today's f32
1229 /// decode graph (no flash arm offered) — a harmless extra binding.
1230 attended_len_sym: SymId,
1231 /// The full realized [`StorageCache`] from the first realize — every
1232 /// reachable `Op::Const` (weights + the KV Arcs + the initial data
1233 /// Consts) that `build_const_cache` uploaded. Held because the
1234 /// prebuilt-realize path SKIPS the const-cache walk: each token we
1235 /// clone this and overwrite ONLY the per-token data-Const entries
1236 /// (token-ids / RoPE / mask). The weight Arcs + KV Arcs are stable
1237 /// (KV mutates in place via `Op::WriteSlice`).
1238 base_cache: StorageCache,
1239 /// The `seq` the held graph is shape-keyed to (always 1 for D2 decode).
1240 seq: usize,
1241 // ---- validity keys — rebuild if any change vs. the live cache/model ----
1242 max_seq_len: usize,
1243 n_layers: usize,
1244 cache_dtype: DType,
1245 /// The [`crate::decode_shape`] key this plan was baked against — model
1246 /// structure + weight identity. See [`Self::is_valid_for`].
1247 shape_key: u64,
1248 /// The KV **allocation** whose storage `Arc`s are baked into `base_cache`.
1249 /// `rebind_and_realize_prebuilt` never re-binds `kv_nodes`, so this plan
1250 /// reads and writes THESE buffers regardless of which cache the caller
1251 /// hands in — unless [`Self::rebind_kv`] re-points them — making the id,
1252 /// not the geometry, the thing that decides reuse. See [`KvAllocId`] and
1253 /// [`Self::is_valid_for`].
1254 alloc_id: KvAllocId,
1255 /// Where the KV `Arc`s baked into `base_cache` lived when this graph was
1256 /// optimized. The placement stamps and residency `Op::Copy`s in `graph`
1257 /// were chosen against THIS location, so [`Self::rebind_kv`] must refuse a
1258 /// replacement that lives anywhere else. `None` when the source could not
1259 /// prove it, which is likewise a refusal.
1260 kv_location: Option<DeviceLocation>,
1261 /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
1262 /// §5): the memoized dispatch order for this session's
1263 /// `(graph, effective_target, optimized)` triple, computed once on the
1264 /// first `realize_token` call and reused on every later one — measured
1265 /// as the single largest named per-token sub-cost prior to this cache
1266 /// (`extract_runs_multi` + `non_chosen_arm_nodes`, ~56ms/step on an RTX
1267 /// 4070). Empty at construction; `realize_token` never resets it, since
1268 /// a `DecodeSession` holds one shape-keyed graph for its whole lifetime
1269 /// (see `is_valid_for` — any mismatch rebuilds a fresh session with a
1270 /// fresh, empty cache, never reuses this one against a different graph).
1271 order_cache: std::sync::OnceLock<Vec<NodeId>>,
1272}
1273
1274impl DecodeSession {
1275 /// Assemble a held session from the artifacts a first-realize
1276 /// prebuild produced. `graph` is the (already prepared + optimized)
1277 /// held decode graph; `effective_target` / `optimized` come from
1278 /// [`InferenceContext::prebuild_optimized_as_with_env`]; the node ids
1279 /// are the STABLE data-Const NodeIds the builder minted.
1280 pub fn new(
1281 graph: Arc<RwLock<Graph>>,
1282 optimized: OptimizedGraph,
1283 effective_target: NodeId,
1284 logits_node: NodeId,
1285 token_ids_node: NodeId,
1286 rope_cos_node: NodeId,
1287 rope_sin_node: NodeId,
1288 mask_node: NodeId,
1289 kv_nodes: Vec<(NodeId, NodeId)>,
1290 offset_node: Option<NodeId>,
1291 cached_len_sym: SymId,
1292 attended_len_sym: SymId,
1293 base_cache: StorageCache,
1294 seq: usize,
1295 max_seq_len: usize,
1296 n_layers: usize,
1297 cache_dtype: DType,
1298 shape_key: u64,
1299 kv: &dyn KvRebindSource,
1300 ) -> Self {
1301 Self {
1302 shape_key,
1303 // Identity and residency are read from the SAME source in the same
1304 // breath, so they cannot describe different allocations — which a
1305 // pair of separate `alloc_id` / `location` parameters could.
1306 alloc_id: kv.alloc_id(),
1307 kv_location: kv.rebind_location(),
1308 graph,
1309 optimized,
1310 effective_target,
1311 logits_node,
1312 token_ids_node,
1313 rope_cos_node,
1314 rope_sin_node,
1315 mask_node,
1316 kv_nodes,
1317 offset_node,
1318 cached_len_sym,
1319 attended_len_sym,
1320 base_cache,
1321 seq,
1322 max_seq_len,
1323 n_layers,
1324 cache_dtype,
1325 order_cache: std::sync::OnceLock::new(),
1326 }
1327 }
1328
1329 /// Realize the held graph for one decode token via the D2a prebuilt
1330 /// seam (SKIP `prepare` + `optimize_graph`). `data` supplies the
1331 /// per-token re-bound data-Const Arcs (token-ids / RoPE cos+sin /
1332 /// mask); they overwrite the held `base_cache`'s entries for this
1333 /// token (the weight + KV Arcs stay from `base_cache`). `sym_env`
1334 /// binds `cached_len`. `TopologyChanged` surfaces typed (caller
1335 /// invalidates the session).
1336 pub fn realize_token(
1337 &self,
1338 device: &Device,
1339 data: DecodeTokenData,
1340 sym_env: &SymEnv,
1341 ) -> Result<Vec<f32>> {
1342 let _t = fuel_dispatch::compiled::op_profile::PhaseTimer::start("decode.realize_token");
1343 let mut cache = self.base_cache.clone();
1344 cache.insert(self.token_ids_node, data.token_ids);
1345 cache.insert(self.rope_cos_node, data.rope_cos);
1346 cache.insert(self.rope_sin_node, data.rope_sin);
1347 cache.insert(self.mask_node, data.mask);
1348 // Device-offset path (CUDA/CPU): re-bind the per-token KV-write
1349 // offset (`cached_len` as I64) into the base-cache clone so the
1350 // held `Op::WriteSliceDoff` nodes read the live position from a
1351 // fixed device buffer. On the SymEnv path both are `None` (the
1352 // offset rides `cached_len_sym` in `sym_env` instead).
1353 if let (Some(offset_node), Some(offset)) = (self.offset_node, data.offset) {
1354 cache.insert(offset_node, offset);
1355 }
1356 crate::pipelined_bridge::realize_one_prebuilt_cached_env::<f32>(
1357 &self.graph,
1358 self.effective_target,
1359 &self.optimized,
1360 &self.order_cache,
1361 device,
1362 cache,
1363 sym_env,
1364 )
1365 }
1366
1367 /// Whether this held session is valid for the given decode step.
1368 /// Rebuild (drop + build fresh) on any mismatch. `seq` must be 1
1369 /// (the held graph is the seq==1 decode graph); a change in
1370 /// `max_seq_len` / `n_layers` / `cache_dtype` means a different
1371 /// model/cache → the held graph's shapes are stale.
1372 /// May this held plan be reused for a step with these parameters?
1373 ///
1374 /// `shape_key` is the caller's [`crate::decode_shape`] key. Geometry alone
1375 /// is NOT sufficient and was the whole reason that module exists: a held
1376 /// graph bakes its op structure and its weight `Const`s, so two models at
1377 /// identical dims — a different architecture, or the same architecture with
1378 /// different weights — would otherwise be judged interchangeable and one
1379 /// would silently execute the other's baked plan.
1380 ///
1381 /// `alloc_id` is the live cache's [`KvCache::alloc_id`]. It is a SEPARATE
1382 /// question from `shape_key` and neither subsumes the other: `shape_key`
1383 /// names the model whose weights are baked in, `alloc_id` names the KV
1384 /// buffers the plan writes into. One model serving many concurrent
1385 /// requests has one `shape_key` and one allocation per request, and it is
1386 /// exactly that case — the slot-pooled server — where geometry-only keying
1387 /// hands request B a plan welded to request A's KV. Nothing errors: B just
1388 /// decodes over A's context at full speed.
1389 ///
1390 /// Both directions matter. Returning `true` too readily is a wrong answer
1391 /// at full speed; returning `false` too readily forfeits plan reuse
1392 /// (measured 223× on CUDA) while every correctness test stays green. That
1393 /// second direction is why `alloc_id` tracks the ALLOCATION and not the
1394 /// conversation — see [`KvCache::truncate_to`], which must not invalidate.
1395 pub fn is_valid_for(
1396 &self,
1397 seq: usize,
1398 max_seq_len: usize,
1399 n_layers: usize,
1400 cache_dtype: DType,
1401 shape_key: u64,
1402 alloc_id: KvAllocId,
1403 ) -> bool {
1404 matches!(
1405 self.validity_for(seq, max_seq_len, n_layers, cache_dtype, shape_key, alloc_id),
1406 PlanValidity::Valid,
1407 )
1408 }
1409
1410 /// The same comparisons as [`Self::is_valid_for`], reporting *which kind*
1411 /// of mismatch occurred rather than collapsing to a bool.
1412 ///
1413 /// The split exists so GAP-028 does not introduce a second predicate. A
1414 /// caller that wants to try [`Self::rebind_kv`] needs to know "everything
1415 /// matches except the allocation", and answering that with an
1416 /// `is_valid_ignoring_alloc` twin would leave two comparison lists to keep
1417 /// in sync — the exact drift that made
1418 /// `lazy::invalidate_decode_pair_if_stale` a shared free function instead
1419 /// of a per-model copy. There is one list, here.
1420 ///
1421 /// Note the asymmetry between the two non-`Valid` answers.
1422 /// `AllocationChanged` is a *conditional* verdict: it says a re-bind is
1423 /// worth attempting, NOT that one is safe. Everything it reports on is a
1424 /// property of the held plan; whether the incoming storage is actually
1425 /// interchangeable is [`Self::rebind_kv`]'s question, and it is answered
1426 /// against the storage itself.
1427 pub fn validity_for(
1428 &self,
1429 seq: usize,
1430 max_seq_len: usize,
1431 n_layers: usize,
1432 cache_dtype: DType,
1433 shape_key: u64,
1434 alloc_id: KvAllocId,
1435 ) -> PlanValidity {
1436 let structural = self.seq == seq
1437 && self.max_seq_len == max_seq_len
1438 && self.n_layers == n_layers
1439 && self.cache_dtype == cache_dtype
1440 && self.shape_key == shape_key;
1441 if !structural {
1442 return PlanValidity::Stale;
1443 }
1444 if self.alloc_id == alloc_id {
1445 PlanValidity::Valid
1446 } else {
1447 PlanValidity::AllocationChanged
1448 }
1449 }
1450
1451 /// Re-point the held plan's baked KV `Const`s at a replacement allocation,
1452 /// or refuse — the GAP-028 alternative to throwing the plan away.
1453 ///
1454 /// ## What this trades
1455 ///
1456 /// GAP-014 shipped invalidate-and-rebuild, which is safe **by
1457 /// construction**: a plan welded to storage it no longer serves is simply
1458 /// destroyed, and no guard can be wrong because there is no guard. This
1459 /// method replaces that with a guarantee that holds **by proof**. If the
1460 /// checks below ever accept an incompatible allocation, the failure mode is
1461 /// GAP-014 verbatim — a plan executing one request's tokens over another's
1462 /// KV, at full speed, with a plausible distribution and nothing to report.
1463 /// Every check here is therefore load-bearing for correctness, not for
1464 /// performance, and the cost of refusing wrongly is only a rebuild.
1465 ///
1466 /// ## What is checked, and against what
1467 ///
1468 /// Not against the cache's own description of itself — against the storage
1469 /// **already baked into `base_cache`**, which is ground truth and cannot
1470 /// disagree with the graph the way a `KvCache` field can. Per slot: dtype,
1471 /// encoding, backend variant, bundling, and byte extent. Byte extent is the
1472 /// load-bearing one: it collapses `batch × n_kv_heads × max_seq_len ×
1473 /// head_dim` into a single comparison that needs no reconstruction of the
1474 /// baked shape.
1475 ///
1476 /// Residency is the exception and is why [`KvRebindSource::rebind_location`]
1477 /// exists. `fuel_memory::Storage` exposes a backend *variant* but no device
1478 /// ordinal — `VulkanStorage` records none at all — so a same-geometry cache
1479 /// on a *different GPU of the same backend* is invisible from the bytes. It
1480 /// would pass every check above and be spliced into a graph whose placement
1481 /// stamps and residency `Op::Copy`s were baked for the old device. An
1482 /// unprovable residency is therefore a refusal, never a default.
1483 ///
1484 /// ## What the caller still owes
1485 ///
1486 /// **A re-bind invalidates any capture.** A `CapturedDecodeSession` records
1487 /// a CUDA graph over FIXED device addresses drawn from `base_cache`; after
1488 /// this returns `Ok`, some of those addresses name the old allocation.
1489 /// Callers must clear the capture alongside, on the same
1490 /// reader-before-owner rule that governs
1491 /// `lazy::invalidate_decode_pair_if_stale`.
1492 ///
1493 /// Structural validity is NOT rechecked here — call this only when
1494 /// [`Self::validity_for`] answered [`PlanValidity::AllocationChanged`].
1495 pub fn rebind_kv(
1496 &mut self,
1497 kv: &dyn KvRebindSource,
1498 ) -> core::result::Result<(), RebindRefusal> {
1499 let incoming_loc = kv
1500 .rebind_location()
1501 .ok_or(RebindRefusal::ResidencyUnknown)?;
1502 let baked_loc = self.kv_location.ok_or(RebindRefusal::ResidencyUnknown)?;
1503 if baked_loc != incoming_loc {
1504 return Err(RebindRefusal::ResidencyDiffers {
1505 baked: baked_loc,
1506 incoming: incoming_loc,
1507 });
1508 }
1509
1510 // Collect first, mutate second. A partial re-bind — some slots on the
1511 // new allocation, the rest still on the old — is the one state strictly
1512 // worse than either endpoint, and the only way to avoid it is to refuse
1513 // before touching `base_cache`.
1514 let mut staged: Vec<(NodeId, Arc<RwLock<Storage>>)> =
1515 Vec::with_capacity(self.kv_nodes.len() * 2);
1516 for (layer, &(k_node, v_node)) in self.kv_nodes.iter().enumerate() {
1517 for (which, node) in [(0usize, k_node), (1usize, v_node)] {
1518 let incoming = kv
1519 .rebind_slot(layer, which)
1520 .ok_or(RebindRefusal::MissingSlot { layer, which })?;
1521 let baked = self
1522 .base_cache
1523 .get(&node)
1524 .ok_or(RebindRefusal::UnbakedSlot { layer, which })?;
1525 if !storage_is_interchangeable(baked, &incoming)
1526 .ok_or(RebindRefusal::LockPoisoned)?
1527 {
1528 return Err(RebindRefusal::StorageDiffers { layer, which });
1529 }
1530 staged.push((node, incoming));
1531 }
1532 }
1533
1534 for (node, arc) in staged {
1535 self.base_cache.insert(node, arc);
1536 }
1537 self.alloc_id = kv.alloc_id();
1538 Ok(())
1539 }
1540
1541 /// The held graph handle (the caller re-binds data Consts + realizes
1542 /// through it).
1543 pub fn graph(&self) -> &Arc<RwLock<Graph>> {
1544 &self.graph
1545 }
1546
1547 /// The cached optimize view (fed to the prebuilt-realize seam).
1548 pub fn optimized(&self) -> &OptimizedGraph {
1549 &self.optimized
1550 }
1551
1552 /// The D2H `Op::Copy` root the executor is asked for.
1553 pub fn effective_target(&self) -> NodeId {
1554 self.effective_target
1555 }
1556
1557 /// The logits node (pre-D2H-splice) — `capture_decode` hard-rejects
1558 /// any `Op::Copy`/`Move` in the captured graph (cross-device, not
1559 /// single-device-CUDA-capturable), so [`fuel_dispatch::pipelined::
1560 /// CapturedDecodeSession::capture`] must target THIS node, not
1561 /// [`Self::effective_target`] (the spliced D2H `Op::Copy` root).
1562 /// The D2H happens OUTSIDE the capture, after `replay_token` returns
1563 /// the device-resident output Arc.
1564 pub fn logits_node(&self) -> NodeId {
1565 self.logits_node
1566 }
1567 pub fn token_ids_node(&self) -> NodeId {
1568 self.token_ids_node
1569 }
1570 pub fn rope_cos_node(&self) -> NodeId {
1571 self.rope_cos_node
1572 }
1573 pub fn rope_sin_node(&self) -> NodeId {
1574 self.rope_sin_node
1575 }
1576 pub fn mask_node(&self) -> NodeId {
1577 self.mask_node
1578 }
1579 pub fn kv_nodes(&self) -> &[(NodeId, NodeId)] {
1580 &self.kv_nodes
1581 }
1582 /// The device-resident KV-write offset Const NodeId, `Some` only on
1583 /// the device-offset decode path (CUDA/CPU); `None` on Vulkan's
1584 /// SymEnv path. Used by the CapturedRun replay wiring (Phase 3) and
1585 /// the per-token offset re-bind.
1586 pub fn offset_node(&self) -> Option<NodeId> {
1587 self.offset_node
1588 }
1589 pub fn cached_len_sym(&self) -> SymId {
1590 self.cached_len_sym
1591 }
1592 pub fn attended_len_sym(&self) -> SymId {
1593 self.attended_len_sym
1594 }
1595 pub fn max_seq_len(&self) -> usize {
1596 self.max_seq_len
1597 }
1598
1599 /// Build the per-token [`SymEnv`] for one decode step: bind
1600 /// `cached_len_sym = cached_len` (the KV-write offset) AND
1601 /// `attended_len_sym = cached_len + seq` (the flash-arm `k_len` — the
1602 /// live attended prefix including this token). Both are bound each
1603 /// token; the attended-length binding is unreferenced on today's f32
1604 /// decode graph (no flash arm) and becomes load-bearing the moment a
1605 /// bf16/f16 CUDA decode offers the arm. Write-once per pass (a
1606 /// conflicting rebind surfaces a typed error, never a panic).
1607 /// # DO NOT DELETE THE `cached_len_sym` BINDING BECAUSE IT LOOKS DEAD
1608 ///
1609 /// **`LlamaModel` and `PhiModel` take DIFFERENT decode paths on CPU/F32,
1610 /// measured 2026-08-12 (GAP-029 2b):**
1611 ///
1612 /// ```text
1613 /// llama: offset_node.is_some() == true → device-offset path; SymEnv INERT
1614 /// phi: offset_node.is_some() == false → SymEnv path; SymEnv LIVE
1615 /// ```
1616 ///
1617 /// On the device-offset path the KV write offset rides a device-resident
1618 /// buffer (`Op::WriteSliceDoff` reads the start from
1619 /// [`DecodeTokenData::offset`] at launch), so **no symbol here drives
1620 /// Llama's write** and both bindings are inert for it. On the SymEnv path
1621 /// the offset rides `cached_len_sym`, and it is **load-bearing for Phi** —
1622 /// proved by negative control: binding it wrong moves Phi's logits
1623 /// (`phi_attended_len_sym_is_unreferenced_negative_control`).
1624 ///
1625 /// The trap this comment exists to prevent: someone profiling or tracing
1626 /// **the Llama path** sees a binding nothing consumes and removes it as dead
1627 /// code. **Their evidence would be about Llama; the requirement comes from
1628 /// Phi**, and the breakage would be silent — wrong KV write offsets, not a
1629 /// compile error. Whichever model you were looking at, you were looking at
1630 /// half the callers.
1631 ///
1632 /// `attended_len_sym` is separately inert on **both** paths today (F32, CPU,
1633 /// no flash arm) and is bound anyway: it becomes load-bearing the moment a
1634 /// bf16/f16 CUDA decode offers the flash arm, and binding it unconditionally
1635 /// is what makes that switch a no-op rather than a hunt. That claim is
1636 /// scoped — re-run the controls above before relying on it under any other
1637 /// dtype/graph.
1638 pub fn per_token_sym_env(&self, cached_len: usize) -> Result<SymEnv> {
1639 let mut env = SymEnv::new();
1640 env.bind(self.cached_len_sym, cached_len)?;
1641 env.bind(self.attended_len_sym, cached_len + self.seq)?;
1642 Ok(env)
1643 }
1644
1645 /// The held graph's node count. The D2b born-red test asserts this
1646 /// is stable from token 2 onward (no per-token node growth — the
1647 /// guard against an accidental re-splice / re-insert / a builder
1648 /// sneaking a `cached_len`-dependent shape back in).
1649 pub fn graph_node_count(&self) -> usize {
1650 self.graph.read().map(|g| g.len()).unwrap_or(0)
1651 }
1652
1653 /// The full realized [`StorageCache`] from the first realize (every
1654 /// weight Const + the KV Arcs + the initial per-token data Consts).
1655 /// The CapturedRun capture-building step clones this cheaply
1656 /// (Arc-clones only) and overwrites the per-token entries with fresh
1657 /// FIXED-address Arcs before handing the merged cache to
1658 /// [`fuel_dispatch::pipelined::CapturedDecodeSession::capture`] as
1659 /// `inputs`.
1660 pub fn base_cache(&self) -> &StorageCache {
1661 &self.base_cache
1662 }
1663}
1664
1665/// Runtime policy for the paged persistent decode path
1666/// (`LlamaModel::forward_paged_step_persistent`):
1667/// whether to build the plan
1668/// ONCE and reuse it across tokens, or re-plan every token (the pre-plan-once
1669/// behavior). The paged driver holds this per config and passes it each step;
1670/// **the driver default is [`PlanOnce`](Self::PlanOnce)** (set by
1671/// `PagedSessionScheduler::new`), with [`Replan`](Self::Replan) available as an
1672/// explicit opt-out.
1673///
1674/// The A/B rollout this flag was built for is DONE, and the default moved with
1675/// the result. Measured (nsys, Lightbulb, 2026-08-01; 16 tokens, same binary and
1676/// model, only the plan mode differing): `Replan` → `PlanOnce` is **29.7×** on
1677/// ms/token (8,192.0 → 275.8) and cuts host-ward DtoH 61% (101,691 → 40,088 MB)
1678/// at IDENTICAL kernel-launch count (17,802 in both arms — same compute, less
1679/// data movement). Shipping `Replan` as the default meant every consumer who did
1680/// not know to opt in paid that 29.7×.
1681///
1682/// It remains a real runtime flag — not a test hook — because toggling it in ONE
1683/// process is what lets the correctness gate run both arms off a single setup,
1684/// and because `Replan` is the parity reference the plan-once path is checked
1685/// against. On [`Replan`](Self::Replan) the persistent forward drops any held
1686/// session (so nothing stale lingers) and delegates to the re-planning
1687/// `LlamaModel::forward_paged_step`;
1688/// on [`PlanOnce`](Self::PlanOnce) it
1689/// builds-once / rebinds.
1690#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1691pub enum PagedDecodePlan {
1692 /// Re-plan (build + optimize the graph) every token — the pre-plan-once
1693 /// path. Drops any held [`PagedDecodeSession`] and routes to
1694 /// `LlamaModel::forward_paged_step`.
1695 Replan,
1696 /// Build + optimize the graph ONCE (into a [`PagedDecodeSession`]) and reuse
1697 /// it (rebinding only the per-token data) for every subsequent token.
1698 PlanOnce,
1699}
1700
1701/// Per-token re-bound data Consts for one PAGED decode step — the paged twin
1702/// of [`DecodeTokenData`]. The shapes are stable across tokens (that is the
1703/// whole point of the plan-once path); only the bytes change, so each is an
1704/// `Arc<RwLock<Storage>>` overwriting the held [`PagedDecodeSession`]'s
1705/// base-cache entry for its stable NodeId.
1706pub struct PagedDecodeTokenData {
1707 /// The single decode token id (`[1]` U32).
1708 pub token_ids: Arc<RwLock<Storage>>,
1709 /// RoPE cos table at THIS token's absolute position (`[1, head_dim]` F32).
1710 pub rope_cos: Arc<RwLock<Storage>>,
1711 /// RoPE sin table at THIS token's absolute position (`[1, head_dim]` F32).
1712 pub rope_sin: Arc<RwLock<Storage>>,
1713 /// Capacity-padded block table (`[1, max_blocks_cap]` U32) — the shape is
1714 /// FIXED by `max_blocks_cap`; the content grows a physical block whenever
1715 /// this token crosses a block boundary (padded tail stays 0, masked out).
1716 pub block_table: Arc<RwLock<Storage>>,
1717 /// Attended prefix length for this row (`[1]` U32) — the `Op::PagedAttn`
1718 /// mask cutoff (`Ge(pos, context_len) → −inf`) that neutralizes both the
1719 /// future positions AND the padded block_table tail.
1720 pub context_lens: Arc<RwLock<Storage>>,
1721 /// The flattened KV-write offset (`linear = phys·block_size + slot` as a
1722 /// rank-0 I64), present ONLY on the device-offset path (CPU/CUDA, where
1723 /// `Op::WriteSliceDoff` reads the start device-side). `None` on the SymEnv
1724 /// path (Vulkan), where the offset rides `write_sym` in the per-pass env.
1725 pub offset: Option<Arc<RwLock<Storage>>>,
1726}
1727
1728/// Plan-once persistent decode state for one PAGED (block-pool) decode
1729/// stream — the paged twin of [`DecodeSession`]. Built on the first
1730/// `seq == 1` paged decode token; reused (graph + optimize view HELD, only
1731/// the per-token data Consts + `SymEnv` re-bound) for every subsequent token.
1732///
1733/// Paged decode's structural variabilities that a re-plan would otherwise pay
1734/// EVERY token are removed here: (1) the fresh `Tensor` graph root becomes
1735/// a held graph with stable re-bindable Const placeholders; (2) the L-varying
1736/// `block_table` shape is pinned to `[1, max_blocks_cap]` (Task 1 padded
1737/// materialize); (3) the per-step KV-write range becomes ONE flattened
1738/// dynamic offset (Task 2 `build_decode_attn_off`). What remains per token is
1739/// shape-stable data re-bound into a clone of `base_cache` + one bound scalar.
1740///
1741/// The pool K/V buffer Arcs are bound ONCE into `base_cache` and mutate IN
1742/// PLACE via `Op::WriteSliceDoff`/`Op::WriteSliceDyn` each token (never
1743/// re-inserted) — exactly the contiguous KV relationship, so the write this
1744/// step lands in the pool and is visible next step.
1745///
1746/// Held by the paged generate-loop owner alongside the `DeviceKvPool` +
1747/// `SessionHandle`; the caller must NOT swap the pool/model out from under a
1748/// live session (the held `base_cache` references THIS pool's buffers). A
1749/// validity-key mismatch (`is_valid_for`) or `TopologyChanged` drops + rebuilds
1750/// it (see `LlamaModel::forward_paged_step_persistent`). Single-session (B = 1)
1751/// today; the ragged batched persistent path is a follow-on.
1752pub struct PagedDecodeSession {
1753 /// The held paged decode-step graph, ALREADY optimized in place. Structure
1754 /// is stable across tokens (variabilities #1–#3 removed).
1755 graph: Arc<RwLock<Graph>>,
1756 /// The cached optimize view from the first realize. Holds only
1757 /// `{roots, generation}`; valid while `graph` structure + topology
1758 /// generation are unchanged.
1759 optimized: OptimizedGraph,
1760 /// The realize root the executor is asked for (the D2H `Op::Copy` splice).
1761 effective_target: NodeId,
1762 /// The logits node (pre-D2H-splice) — retained for debugging/attribution.
1763 logits_node: NodeId,
1764 /// Stable re-bindable single-token-id Const (`[1]` U32).
1765 token_ids_node: NodeId,
1766 /// Stable re-bindable RoPE cos table Const (`[1, head_dim]` F32).
1767 rope_cos_node: NodeId,
1768 /// Stable re-bindable RoPE sin table Const (`[1, head_dim]` F32).
1769 rope_sin_node: NodeId,
1770 /// Stable re-bindable padded block_table Const (`[1, max_blocks_cap]` U32).
1771 block_table_node: NodeId,
1772 /// Stable re-bindable context_lens Const (`[1]` U32).
1773 context_lens_node: NodeId,
1774 /// Per-layer `(k_pool_ph, v_pool_ph)` stable KV placeholder NodeIds, bound
1775 /// ONCE to the pool buffers (viewed at `pool_shape_flat`) and mutated in
1776 /// place by the flattened-offset write each token.
1777 kv_nodes: Vec<(NodeId, NodeId)>,
1778 /// The stable rank-0 `I64` KV-write offset Const, present ONLY on the
1779 /// device-offset path (CPU/CUDA — `Op::WriteSliceDoff`). `None` on the
1780 /// SymEnv path (Vulkan — the offset rides `write_sym`).
1781 offset_node: Option<NodeId>,
1782 /// The symbol the per-pass `SymEnv` binds to the flattened write offset
1783 /// (`linear`) each token. Load-bearing on the SymEnv path; a harmless
1784 /// (unreferenced) extra binding on the device-offset path.
1785 write_sym: SymId,
1786 /// The full realized [`StorageCache`] from the first realize (weights +
1787 /// the pool KV Arcs + the initial per-token data Consts). Each token we
1788 /// clone this and overwrite ONLY the per-token data-Const entries; the
1789 /// weight + pool Arcs are stable (the pool mutates in place).
1790 base_cache: StorageCache,
1791 // ---- validity keys — rebuild if any change vs. the live pool ----
1792 max_blocks_cap: usize,
1793 n_layers: usize,
1794 block_size: usize,
1795 cache_dtype: DType,
1796 /// The model's `decode_shape_key()` at build time — family + structure-
1797 /// affecting config + WEIGHT IDENTITY (a never-recycled `ModelInstanceId`).
1798 ///
1799 /// Geometry alone cannot separate two models: `PagedDecodeSession` bakes the
1800 /// weight `Const`s, so two same-shaped models produce identical
1801 /// `(max_blocks_cap, n_layers, block_size, cache_dtype)` and a plan built for
1802 /// one would be judged valid for the other — silently computing the wrong
1803 /// architecture, or the right architecture with the wrong weights, at full
1804 /// speed. The contiguous twin closed this first; this is the paged half of
1805 /// the same hole.
1806 shape_key: u64,
1807 /// The [`DeviceKvPool`](crate::kv_block_pool_device::DeviceKvPool) whose
1808 /// per-layer block buffers are baked into `base_cache`. The paged half of
1809 /// the same welding: `rebind_and_realize_paged_prebuilt` re-binds the
1810 /// per-token data (token id, RoPE, block_table, context_lens, offset) and
1811 /// never the pool, so this plan reads THESE buffers whichever pool the
1812 /// caller passes. Two same-geometry pools are otherwise indistinguishable
1813 /// to the key. See [`KvAllocId`].
1814 alloc_id: KvAllocId,
1815 /// Count of REBIND realizes this session has served (one per
1816 /// [`Self::realize_token`]). The build itself realizes through the prebuild
1817 /// seam, NOT `realize_token`, so it stays 0 right after construction and
1818 /// increments only on each plan-reuse token. A DEVICE-INDEPENDENT plan-HIT
1819 /// signal (the `optimize_calls_thread_local` counter is CPU-scoped — GPU
1820 /// per-token uploads bump it), so the correctness gate can assert "this
1821 /// token reused the plan" on any backend. Interior-mutable (`realize_token`
1822 /// takes `&self`); `Relaxed` — it is telemetry, ordered by the caller.
1823 realize_count: AtomicUsize,
1824 /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
1825 /// §5) — see [`DecodeSession::order_cache`]'s doc for the full
1826 /// argument; identical role here for the paged path.
1827 order_cache: std::sync::OnceLock<Vec<NodeId>>,
1828}
1829
1830impl PagedDecodeSession {
1831 /// Assemble a held paged session from the artifacts a first-realize
1832 /// prebuild produced. The node ids are the STABLE data-Const NodeIds the
1833 /// paged builder minted.
1834 pub fn new(
1835 graph: Arc<RwLock<Graph>>,
1836 optimized: OptimizedGraph,
1837 effective_target: NodeId,
1838 logits_node: NodeId,
1839 token_ids_node: NodeId,
1840 rope_cos_node: NodeId,
1841 rope_sin_node: NodeId,
1842 block_table_node: NodeId,
1843 context_lens_node: NodeId,
1844 kv_nodes: Vec<(NodeId, NodeId)>,
1845 offset_node: Option<NodeId>,
1846 write_sym: SymId,
1847 base_cache: StorageCache,
1848 max_blocks_cap: usize,
1849 n_layers: usize,
1850 block_size: usize,
1851 cache_dtype: DType,
1852 shape_key: u64,
1853 alloc_id: KvAllocId,
1854 ) -> Self {
1855 Self {
1856 alloc_id,
1857 graph,
1858 optimized,
1859 effective_target,
1860 logits_node,
1861 token_ids_node,
1862 rope_cos_node,
1863 rope_sin_node,
1864 block_table_node,
1865 context_lens_node,
1866 kv_nodes,
1867 offset_node,
1868 write_sym,
1869 base_cache,
1870 max_blocks_cap,
1871 n_layers,
1872 block_size,
1873 cache_dtype,
1874 shape_key,
1875 realize_count: AtomicUsize::new(0),
1876 order_cache: std::sync::OnceLock::new(),
1877 }
1878 }
1879
1880 /// Realize the held paged graph for one decode token via the prebuilt seam
1881 /// (SKIP `prepare` + `optimize_graph`). `data` supplies the per-token
1882 /// re-bound data-Const Arcs; they overwrite the held `base_cache`'s entries
1883 /// for this token (the weight + pool KV Arcs stay from `base_cache`).
1884 /// `sym_env` binds `write_sym` (load-bearing on the SymEnv path, harmless
1885 /// on the device-offset path). `TopologyChanged` surfaces typed (caller
1886 /// invalidates the session).
1887 pub fn realize_token(
1888 &self,
1889 device: &Device,
1890 data: PagedDecodeTokenData,
1891 sym_env: &SymEnv,
1892 ) -> Result<Vec<f32>> {
1893 let mut cache = self.base_cache.clone();
1894 cache.insert(self.token_ids_node, data.token_ids);
1895 cache.insert(self.rope_cos_node, data.rope_cos);
1896 cache.insert(self.rope_sin_node, data.rope_sin);
1897 cache.insert(self.block_table_node, data.block_table);
1898 cache.insert(self.context_lens_node, data.context_lens);
1899 if let (Some(offset_node), Some(offset)) = (self.offset_node, data.offset) {
1900 cache.insert(offset_node, offset);
1901 }
1902 // Device-independent plan-HIT tick: this token reuses the held plan
1903 // (the prebuild seam below SKIPs optimize). Bumped BEFORE the realize
1904 // so a realize error still records the attempted rebind.
1905 self.realize_count.fetch_add(1, Ordering::Relaxed);
1906 crate::pipelined_bridge::realize_one_prebuilt_cached_env::<f32>(
1907 &self.graph,
1908 self.effective_target,
1909 &self.optimized,
1910 &self.order_cache,
1911 device,
1912 cache,
1913 sym_env,
1914 )
1915 }
1916
1917 /// Whether this held session is valid for the given paged decode step.
1918 /// Rebuild (drop + build fresh) on any mismatch: a change in
1919 /// `max_blocks_cap` (the block_table shape key), `n_layers`, `block_size`,
1920 /// or `cache_dtype` means the held graph's shapes / offsets are stale.
1921 ///
1922 /// `alloc_id` is the live pool's
1923 /// [`DeviceKvPool::alloc_id`](crate::kv_block_pool_device::DeviceKvPool::alloc_id)
1924 /// — which POOL's buffers, as distinct from `shape_key`'s which MODEL's
1925 /// weights. Note it is deliberately not sensitive to block allocation:
1926 /// which physical blocks a session owns rides the per-token `block_table`
1927 /// rebind, so a generation that grows into new blocks keeps its plan.
1928 pub fn is_valid_for(
1929 &self,
1930 max_blocks_cap: usize,
1931 n_layers: usize,
1932 block_size: usize,
1933 cache_dtype: DType,
1934 shape_key: u64,
1935 alloc_id: KvAllocId,
1936 ) -> bool {
1937 self.max_blocks_cap == max_blocks_cap
1938 && self.n_layers == n_layers
1939 && self.block_size == block_size
1940 && self.cache_dtype == cache_dtype
1941 && self.shape_key == shape_key
1942 && self.alloc_id == alloc_id
1943 }
1944
1945 /// Build the per-token [`SymEnv`] for one paged decode step: bind
1946 /// `write_sym = linear` (the flattened KV-write offset). Load-bearing on
1947 /// the SymEnv path; a harmless unreferenced binding on the device-offset
1948 /// path (a conflicting rebind surfaces a typed error, never a panic).
1949 pub fn per_token_sym_env(&self, linear: usize) -> Result<SymEnv> {
1950 let mut env = SymEnv::new();
1951 env.bind(self.write_sym, linear)?;
1952 Ok(env)
1953 }
1954
1955 /// The held graph handle.
1956 pub fn graph(&self) -> &Arc<RwLock<Graph>> {
1957 &self.graph
1958 }
1959 /// The cached optimize view (fed to the prebuilt-realize seam).
1960 pub fn optimized(&self) -> &OptimizedGraph {
1961 &self.optimized
1962 }
1963 pub fn effective_target(&self) -> NodeId {
1964 self.effective_target
1965 }
1966 pub fn logits_node(&self) -> NodeId {
1967 self.logits_node
1968 }
1969 pub fn token_ids_node(&self) -> NodeId {
1970 self.token_ids_node
1971 }
1972 pub fn rope_cos_node(&self) -> NodeId {
1973 self.rope_cos_node
1974 }
1975 pub fn rope_sin_node(&self) -> NodeId {
1976 self.rope_sin_node
1977 }
1978 pub fn block_table_node(&self) -> NodeId {
1979 self.block_table_node
1980 }
1981 pub fn context_lens_node(&self) -> NodeId {
1982 self.context_lens_node
1983 }
1984 pub fn kv_nodes(&self) -> &[(NodeId, NodeId)] {
1985 &self.kv_nodes
1986 }
1987 pub fn offset_node(&self) -> Option<NodeId> {
1988 self.offset_node
1989 }
1990 pub fn write_sym(&self) -> SymId {
1991 self.write_sym
1992 }
1993 pub fn max_blocks_cap(&self) -> usize {
1994 self.max_blocks_cap
1995 }
1996
1997 /// How many REBIND (plan-reuse) tokens this session has served — a
1998 /// device-independent plan-HIT signal (see [`Self::realize_count`]). Zero
1999 /// right after the build; `n` after `n` reuse tokens. The correctness gate
2000 /// asserts this advances by exactly one per plan-once decode step.
2001 pub fn realize_count(&self) -> usize {
2002 self.realize_count.load(Ordering::Relaxed)
2003 }
2004
2005 /// The held graph's node count. The Task 3 born-red test asserts this is
2006 /// stable from token 2 onward (no per-token node growth — the guard
2007 /// against an accidental re-splice / re-insert).
2008 pub fn graph_node_count(&self) -> usize {
2009 self.graph.read().map(|g| g.len()).unwrap_or(0)
2010 }
2011
2012 /// The full realized [`StorageCache`] from the first realize.
2013 pub fn base_cache(&self) -> &StorageCache {
2014 &self.base_cache
2015 }
2016}
2017
2018// `alloc_zeroed_on` retired 2026-05-22 (bridge-retirement Phase 3a).
2019// Zero-init device allocation now flows through `Op::Alloc` graph
2020// emission + the executor's `WorkItemKind::Alloc` arm. The per-
2021// `DeviceLocation` match this function used to carry lives in
2022// `fuel-storage::pipelined::execute_work_item`'s Alloc arm; the
2023// per-realize device handles come from a `DeviceRegistry` built from the
2024// `Device` (`crate::pipelined_bridge::primary_device_registry`).
2025
2026// ===========================================================================
2027// InferenceContext
2028// ===========================================================================
2029
2030/// Per-session host-side context holding long-lived storage Arcs
2031/// that survive across realize calls.
2032///
2033/// The persistent map is the seam the unified-storage / mmap-coherence
2034/// backplane work later replaces (see
2035/// `project_unified_durable_tensor_store.md`); today it's a simple
2036/// in-memory `HashMap`. Each realize call clones the Arcs into the
2037/// executor's input cache; persistent entries reuse those Arcs
2038/// across calls instead of re-uploading.
2039///
2040/// ## Lifecycle
2041///
2042/// 1. Construct with a target device: `InferenceContext::new(device)`.
2043/// 2. Insert long-lived storages (KV layer storages, anything else
2044/// that should survive across realize calls):
2045/// `ctx.insert(node_id, arc)`.
2046/// 3. Realize: `ctx.realize_one_as::<f32>(&graph, target_node)`. The
2047/// persistent map is seeded into the executor's input cache; new
2048/// `Op::Const` nodes the graph references that aren't in the
2049/// persistent map get uploaded fresh from the graph's storage map.
2050/// 4. Subsequent realize calls reuse the persistent Arcs — no
2051/// re-upload, no D2H/H2D round-trip.
2052pub struct InferenceContext {
2053 device: Device,
2054 persistent: HashMap<NodeId, Arc<RwLock<Storage>>>,
2055 /// Held plan-once decode plan for `LlamaModel::forward_decode_step`
2056 /// — the carrier that lets a caller-driven decode loop get plan reuse
2057 /// WITHOUT threading an `Option<DecodeSession>` of its own.
2058 ///
2059 /// This exists because the ergonomic call shape and the fast call shape had
2060 /// drifted apart. `forward_with_kv_context(tokens, cache, ctx)` is the raw
2061 /// rebuild primitive; its persistent sibling takes a fourth argument, so a
2062 /// consumer hand-rolling a decode loop reaches the slow one and never learns
2063 /// the fast one exists. Not hypothetical: that gap cost a measured consumer
2064 /// 5,901 → 26.47 ms/token before anyone noticed (nsys, 2026-08-01).
2065 ///
2066 /// **One context per model.** Already this codebase's invariant — speculative
2067 /// decoding builds a separate `InferenceContext` for the draft and the target
2068 /// — and the held plan self-heals regardless: `DecodeSession::is_valid_for`
2069 /// drops it on any cache-geometry or dtype change.
2070 decode_session: Option<DecodeSession>,
2071}
2072
2073impl InferenceContext {
2074 pub fn new(device: Device) -> Self {
2075 Self {
2076 device,
2077 persistent: HashMap::new(),
2078 decode_session: None,
2079 }
2080 }
2081
2082 pub fn device(&self) -> &Device {
2083 &self.device
2084 }
2085
2086 /// Take the held decode plan out of the context, leaving `None`.
2087 ///
2088 /// Paired with [`Self::put_decode_session`]. The take/put dance exists for
2089 /// the borrow checker: the persistent forward needs `&mut InferenceContext`
2090 /// AND `&mut Option<DecodeSession>` at once, which it cannot have if the
2091 /// session lives inside the context. Callers outside
2092 /// `forward_decode_step` should not need either method.
2093 pub fn take_decode_session(&mut self) -> Option<DecodeSession> {
2094 self.decode_session.take()
2095 }
2096
2097 /// Put a decode plan back into the context. See [`Self::take_decode_session`].
2098 pub fn put_decode_session(&mut self, session: Option<DecodeSession>) {
2099 self.decode_session = session;
2100 }
2101
2102 /// Whether a decode plan is currently held. Observability hook — a caller
2103 /// that has decoded at least one token through
2104 /// `LlamaModel::forward_decode_step` holds one.
2105 pub fn has_decode_session(&self) -> bool {
2106 self.decode_session.is_some()
2107 }
2108
2109 /// Insert a long-lived storage at `node_id`. The Arc survives
2110 /// across subsequent realize calls and is treated as pre-realized
2111 /// for any graph that references `node_id` as a Const-shaped leaf.
2112 ///
2113 /// Replaces any prior entry at `node_id`.
2114 pub fn insert(&mut self, node_id: NodeId, storage: Arc<RwLock<Storage>>) {
2115 self.persistent.insert(node_id, storage);
2116 }
2117
2118 /// Remove the persistent entry at `node_id`. Returns the Arc if
2119 /// one was present. After this, the next realize that touches
2120 /// `node_id` will re-fetch from the graph's storage_map (and fail
2121 /// if the slot isn't populated there either).
2122 pub fn remove(&mut self, node_id: NodeId) -> Option<Arc<RwLock<Storage>>> {
2123 self.persistent.remove(&node_id)
2124 }
2125
2126 /// Whether the persistent map has an entry at `node_id`.
2127 pub fn contains(&self, node_id: NodeId) -> bool {
2128 self.persistent.contains_key(&node_id)
2129 }
2130
2131 /// Borrow the persistent entry at `node_id` if present.
2132 pub fn get(&self, node_id: NodeId) -> Option<&Arc<RwLock<Storage>>> {
2133 self.persistent.get(&node_id)
2134 }
2135
2136 /// Number of persistent slots.
2137 pub fn len(&self) -> usize {
2138 self.persistent.len()
2139 }
2140
2141 pub fn is_empty(&self) -> bool {
2142 self.persistent.is_empty()
2143 }
2144
2145 /// Drop every persistent entry. The Arcs are released; storages
2146 /// whose only remaining reference was the context's are freed
2147 /// (host memory for CPU, deferred-on-stream for async backends).
2148 pub fn clear_persistent(&mut self) {
2149 self.persistent.clear();
2150 }
2151
2152 /// Realize a single target. The persistent map is seeded into
2153 /// the executor's input cache via `Arc::clone` (the persistent
2154 /// entries survive the call). Op::Const NodeIds in the graph
2155 /// that aren't already in the persistent map get uploaded fresh
2156 /// from `graph.storage_for(id)` per the existing pipelined-bridge
2157 /// pattern.
2158 pub fn realize_one_as<T: bytemuck::Pod + fuel_ir::WithDType>(
2159 &self,
2160 graph: &Arc<RwLock<Graph>>,
2161 target: NodeId,
2162 ) -> Result<Vec<T>> {
2163 self.realize_one_as_with_env::<T>(graph, target, &SymEnv::default())
2164 }
2165
2166 /// Env-carrying counterpart of [`Self::realize_one_as`]: supplies a
2167 /// per-pass [`SymEnv`] binding the runtime values of any `DynScalar`
2168 /// op params (Phase D symbolic extents — e.g. the decode KV-cache
2169 /// write offset `cached_len`). The env is **per-pass** (re-supplied
2170 /// every forward step) while the persistent map is **per-session**;
2171 /// an empty env is byte-identical to [`Self::realize_one_as`].
2172 pub fn realize_one_as_with_env<T: bytemuck::Pod + fuel_ir::WithDType>(
2173 &self,
2174 graph: &Arc<RwLock<Graph>>,
2175 target: NodeId,
2176 env: &SymEnv,
2177 ) -> Result<Vec<T>> {
2178 crate::pipelined_bridge::realize_one_as_with_initial_env::<T>(
2179 graph,
2180 target,
2181 &self.device,
2182 self.cloned_persistent(),
2183 env,
2184 )
2185 }
2186
2187 /// Phase D · D2a — first-realize that ALSO captures the reusable
2188 /// optimize artifacts for a later prebuilt (plan-once) re-realize.
2189 ///
2190 /// Runs the full `prepare` + `optimize_graph` + dispatch path ONCE (like
2191 /// [`Self::realize_one_as_with_env`]) and returns
2192 /// `(effective_target, OptimizedGraph, result)`. The caller (D2b's
2193 /// `DecodeSession`) holds the `effective_target` (the spliced D2H
2194 /// `Op::Copy` root) + the cached `OptimizedGraph` and feeds them to
2195 /// [`Self::realize_prebuilt_as_with_env`] on later tokens to SKIP the
2196 /// re-plan. See [`crate::pipelined_bridge::prebuild_optimized_env`].
2197 pub fn prebuild_optimized_as_with_env<T: bytemuck::Pod + fuel_ir::WithDType>(
2198 &self,
2199 graph: &Arc<RwLock<Graph>>,
2200 target: NodeId,
2201 env: &SymEnv,
2202 ) -> Result<(NodeId, fuel_dispatch::optimize::OptimizedGraph, Vec<T>)> {
2203 crate::pipelined_bridge::prebuild_optimized_env::<T>(
2204 graph,
2205 target,
2206 &self.device,
2207 self.cloned_persistent(),
2208 env,
2209 )
2210 }
2211
2212 /// Phase D · D2b — first-realize that captures the reusable optimize
2213 /// artifacts AND the full realized [`StorageCache`] (all weight
2214 /// Consts uploaded by `build_const_cache`, merged over this context's
2215 /// persistent Arcs). The [`DecodeSession`] holds the cache so later
2216 /// prebuilt realizes (which SKIP the const-cache walk) still resolve
2217 /// every weight Const. Returns
2218 /// `(effective_target, OptimizedGraph, full_cache, result)`.
2219 pub fn prebuild_optimized_capturing_as_with_env<T: bytemuck::Pod + fuel_ir::WithDType>(
2220 &self,
2221 graph: &Arc<RwLock<Graph>>,
2222 target: NodeId,
2223 env: &SymEnv,
2224 ) -> Result<(
2225 NodeId,
2226 fuel_dispatch::optimize::OptimizedGraph,
2227 StorageCache,
2228 Vec<T>,
2229 )> {
2230 crate::pipelined_bridge::prebuild_optimized_env_capturing_cache::<T>(
2231 graph,
2232 target,
2233 &self.device,
2234 self.cloned_persistent(),
2235 env,
2236 )
2237 }
2238
2239 /// Phase D · D2a — plan-once re-realize over a graph already prepared +
2240 /// optimized by a prior [`Self::prebuild_optimized_as_with_env`]. Skips
2241 /// BOTH `prepare` (no D2H re-splice / const-cache walk) AND
2242 /// `optimize_graph` (no re-plan / double-insert). Re-binds only the
2243 /// per-call `StorageCache` (this context's persistent Arcs, incl. the
2244 /// re-bound per-token data Consts) + `env`, then dispatches straight to
2245 /// the executor. `effective_target` + `optimized` come from the prebuild.
2246 ///
2247 /// A `TopologyChanged` error surfaces to the caller (typed, not
2248 /// retried) — the cached view is stale; invalidate + rebuild the session.
2249 pub fn realize_prebuilt_as_with_env<T: bytemuck::Pod + fuel_ir::WithDType>(
2250 &self,
2251 graph: &Arc<RwLock<Graph>>,
2252 effective_target: NodeId,
2253 optimized: &fuel_dispatch::optimize::OptimizedGraph,
2254 env: &SymEnv,
2255 ) -> Result<Vec<T>> {
2256 crate::pipelined_bridge::realize_one_prebuilt_env::<T>(
2257 graph,
2258 effective_target,
2259 optimized,
2260 &self.device,
2261 self.cloned_persistent(),
2262 env,
2263 )
2264 }
2265
2266 /// Multi-target counterpart of [`Self::realize_one_as`].
2267 pub fn realize_many_as<T: bytemuck::Pod + fuel_ir::WithDType>(
2268 &self,
2269 graph: &Arc<RwLock<Graph>>,
2270 targets: &[NodeId],
2271 ) -> Result<Vec<Vec<T>>> {
2272 self.realize_many_as_with_env::<T>(graph, targets, &SymEnv::default())
2273 }
2274
2275 /// Env-carrying counterpart of [`Self::realize_many_as`] (Phase D
2276 /// symbolic extents). An empty env is byte-identical to
2277 /// [`Self::realize_many_as`].
2278 pub fn realize_many_as_with_env<T: bytemuck::Pod + fuel_ir::WithDType>(
2279 &self,
2280 graph: &Arc<RwLock<Graph>>,
2281 targets: &[NodeId],
2282 env: &SymEnv,
2283 ) -> Result<Vec<Vec<T>>> {
2284 crate::pipelined_bridge::realize_many_as_with_initial_env::<T>(
2285 graph,
2286 targets,
2287 &self.device,
2288 self.cloned_persistent(),
2289 env,
2290 )
2291 }
2292
2293 /// Realize-split counterpart of [`Self::realize_many_as`]: the
2294 /// first `n_host` targets are downloaded to host `Vec<T>`s, the
2295 /// rest come back as device-resident `(storage, layout)` pairs —
2296 /// no D2H for results that feed the next step's graph. See
2297 /// [`crate::pipelined_bridge::realize_split_as_with_initial`].
2298 pub fn realize_split_as<T: bytemuck::Pod + fuel_ir::WithDType>(
2299 &self,
2300 graph: &Arc<RwLock<Graph>>,
2301 targets: &[NodeId],
2302 n_host: usize,
2303 ) -> Result<crate::pipelined_bridge::SplitRealizeOutput<T>> {
2304 crate::pipelined_bridge::realize_split_as_with_initial::<T>(
2305 graph,
2306 targets,
2307 n_host,
2308 &self.device,
2309 self.cloned_persistent(),
2310 )
2311 }
2312
2313 /// Build a [`StorageCache`] containing Arc-clones of every
2314 /// persistent entry. The clone is cheap (Arc refcount bumps); the
2315 /// returned `StorageCache` is consumed by the realize call but
2316 /// the original Arcs in `self.persistent` survive.
2317 fn cloned_persistent(&self) -> StorageCache {
2318 let mut out = StorageCache::with_capacity(self.persistent.len());
2319 for (id, arc) in &self.persistent {
2320 out.insert(*id, Arc::clone(arc));
2321 }
2322 out
2323 }
2324}
2325
2326// ===========================================================================
2327// Tests
2328// ===========================================================================
2329
2330#[cfg(test)]
2331mod tests {
2332 use super::*;
2333 use fuel_graph::{Node, Op};
2334 use fuel_ir::{DType, Shape};
2335
2336 /// `InferenceContext::insert` + immediate retrieval round-trips.
2337 #[test]
2338 fn context_insert_retrieve() {
2339 let mut ctx = InferenceContext::new(Device::cpu());
2340 let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
2341 let arc = Arc::new(RwLock::new(storage));
2342 let id = NodeId(42);
2343
2344 assert!(!ctx.contains(id));
2345 assert_eq!(ctx.len(), 0);
2346
2347 ctx.insert(id, Arc::clone(&arc));
2348
2349 assert!(ctx.contains(id));
2350 assert_eq!(ctx.len(), 1);
2351 // The returned Arc is the same as what we inserted.
2352 let retrieved = ctx.get(id).expect("just inserted");
2353 assert!(Arc::ptr_eq(retrieved, &arc));
2354 }
2355
2356 /// Inserted Arcs survive across realize calls. Build a minimal
2357 /// 3-node graph (Const + Const + Add). Both Const slots come
2358 /// from the context's persistent map (no graph.storage_map
2359 /// involvement). Realize twice; verify the persistent Arcs are
2360 /// still held by the context after each call.
2361 #[test]
2362 fn context_persistent_arc_survives_realize() {
2363 let lhs_arc = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
2364 1.0_f32, 2.0, 3.0,
2365 ])));
2366 let rhs_arc = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
2367 10.0_f32, 20.0, 30.0,
2368 ])));
2369
2370 let graph = Arc::new(RwLock::new(Graph::new()));
2371 let (lhs_id, rhs_id, add_id) = {
2372 let mut g = graph.write().unwrap();
2373 let lhs = g.push(Node {
2374 op: Op::Const,
2375 inputs: vec![],
2376 shape: Shape::from_dims(&[3]),
2377 dtype: DType::F32,
2378 });
2379 let rhs = g.push(Node {
2380 op: Op::Const,
2381 inputs: vec![],
2382 shape: Shape::from_dims(&[3]),
2383 dtype: DType::F32,
2384 });
2385 let add = g.push(Node {
2386 op: Op::Add,
2387 inputs: vec![lhs, rhs],
2388 shape: Shape::from_dims(&[3]),
2389 dtype: DType::F32,
2390 });
2391 (lhs, rhs, add)
2392 };
2393
2394 let mut ctx = InferenceContext::new(Device::cpu());
2395 ctx.insert(lhs_id, Arc::clone(&lhs_arc));
2396 ctx.insert(rhs_id, Arc::clone(&rhs_arc));
2397
2398 // Before realize: each Arc held by the test (1) + context (1) = 2.
2399 assert_eq!(Arc::strong_count(&lhs_arc), 2);
2400 assert_eq!(Arc::strong_count(&rhs_arc), 2);
2401
2402 let out1 = ctx
2403 .realize_one_as::<f32>(&graph, add_id)
2404 .expect("first realize");
2405 assert_eq!(out1, vec![11.0, 22.0, 33.0]);
2406
2407 // After first realize: same count. The realize call's
2408 // cloned_persistent() bumped the counts to 3 during the call
2409 // and dropped them back to 2 when the call returned.
2410 assert_eq!(Arc::strong_count(&lhs_arc), 2);
2411 assert_eq!(Arc::strong_count(&rhs_arc), 2);
2412
2413 // Realize again — same Arcs get reused without re-upload.
2414 // This is the autoregressive-decoding pattern: weights stay
2415 // resident across forward passes.
2416 let out2 = ctx
2417 .realize_one_as::<f32>(&graph, add_id)
2418 .expect("second realize");
2419 assert_eq!(out2, vec![11.0, 22.0, 33.0]);
2420 assert_eq!(Arc::strong_count(&lhs_arc), 2);
2421 assert_eq!(Arc::strong_count(&rhs_arc), 2);
2422 }
2423
2424 /// Read back layer `layer_idx`'s `slot` buffer in full, as a flat
2425 /// row-major `[n_kv_heads * max_seq_len * head_dim]` f32 vec — test-only
2426 /// readback counterpart to [`KvCache::write_bytes`], deliberately NOT
2427 /// sliced, so a wrong write RANGE shows up as corruption anywhere in the
2428 /// buffer rather than being hidden by only reading the written window.
2429 fn read_kv_layer_f32(
2430 cache: &KvCache,
2431 layer_idx: usize,
2432 slot: KvSlot,
2433 device: &Device,
2434 ) -> Vec<f32> {
2435 let max_seq_len = cache.max_seq_len.expect("with_capacity cache");
2436 let full_shape = Shape::from_dims(&[1, cache.n_kv_heads, max_seq_len, cache.head_dim]);
2437 let buf = match slot {
2438 KvSlot::K => Arc::clone(&cache.layer(layer_idx).unwrap().k),
2439 KvSlot::V => Arc::clone(&cache.layer(layer_idx).unwrap().v),
2440 };
2441 let anchor =
2442 crate::lazy::Tensor::from_f32(vec![0.0f32], Shape::from_dims(&[1]), device).unwrap();
2443 let dest = anchor.const_placeholder_like(full_shape, DType::F32);
2444 let mut sc = StorageCache::new();
2445 sc.insert(dest.node_id(), buf);
2446 let bytes = crate::pipelined_bridge::realize_one_bytes_with_initial(
2447 dest.graph_handle(),
2448 dest.node_id(),
2449 device,
2450 sc,
2451 )
2452 .expect("readback realize");
2453 bytemuck::try_cast_slice::<u8, f32>(&bytes)
2454 .expect("f32 cast")
2455 .to_vec()
2456 }
2457
2458 /// Board item 86 (OverMind self-fork / Lightbulb KV-cache handoff design):
2459 /// [`KvCache::write_bytes`] must write EXACTLY the `[start, start+n)`
2460 /// position range on the right axis (2, head-major) and leave every other
2461 /// position untouched — a wrong range (e.g. accidentally position-major,
2462 /// axis 0) would either corrupt unrelated positions or silently land on
2463 /// the wrong head/position entirely, and reading back the FULL buffer
2464 /// (not just the written window) is what catches either failure.
2465 #[test]
2466 fn write_bytes_lands_at_the_correct_position_and_nowhere_else() {
2467 let device = Device::cpu();
2468 let (n_layers, n_kv_heads, head_dim, max_seq_len) = (1, 2, 3, 5);
2469 let cache = KvCache::with_capacity(
2470 n_layers,
2471 n_kv_heads,
2472 head_dim,
2473 max_seq_len,
2474 DType::F32,
2475 &device,
2476 )
2477 .expect("with_capacity");
2478
2479 let alloc_before = cache.alloc_id();
2480 let loc_before = cache.device_location();
2481
2482 // Write positions [1, 3) (n=2) with a distinctive, non-zero pattern —
2483 // zero would be indistinguishable from the buffer's own zero-init.
2484 let (start, n) = (1usize, 2usize);
2485 let payload: Vec<f32> = (0..(n * n_kv_heads * head_dim))
2486 .map(|i| 1000.0 + i as f32)
2487 .collect();
2488 cache
2489 .write_bytes(
2490 0,
2491 KvSlot::K,
2492 start,
2493 n,
2494 bytemuck::cast_slice(&payload),
2495 &device,
2496 )
2497 .expect("write_bytes");
2498
2499 // THE CORE CLAIM: no Arc replacement happened, so neither identity
2500 // marker moved — this is what makes a held DecodeSession safe to
2501 // keep using without a rebind or rebuild.
2502 assert_eq!(
2503 cache.alloc_id(),
2504 alloc_before,
2505 "write_bytes must not re-mint alloc_id (that would mean the Arc was replaced)",
2506 );
2507 assert_eq!(
2508 cache.device_location(),
2509 loc_before,
2510 "write_bytes must not clear device_location (that would mean residency became unprovable)",
2511 );
2512
2513 let full = read_kv_layer_f32(&cache, 0, KvSlot::K, &device);
2514 for h in 0..n_kv_heads {
2515 for p in 0..max_seq_len {
2516 for d in 0..head_dim {
2517 let got = full[h * max_seq_len * head_dim + p * head_dim + d];
2518 if (start..start + n).contains(&p) {
2519 let local_p = p - start;
2520 let want = 1000.0 + (h * n * head_dim + local_p * head_dim + d) as f32;
2521 assert_eq!(
2522 got, want,
2523 "head {h} position {p} dim {d}: written value must land exactly here",
2524 );
2525 } else {
2526 assert_eq!(
2527 got,
2528 0.0,
2529 "head {h} position {p} dim {d}: outside [{start},{}) must stay \
2530 untouched (zero-init) — a wrong write range would corrupt this",
2531 start + n,
2532 );
2533 }
2534 }
2535 }
2536 }
2537 }
2538
2539 /// `write_bytes` is `with_capacity`-only (needs a fixed dtype + a stable
2540 /// buffer to write into) — a `with_dims` (grow-by-replacement) cache has
2541 /// neither, and must refuse with a typed error, never panic.
2542 #[test]
2543 fn write_bytes_refuses_a_with_dims_cache() {
2544 let device = Device::cpu();
2545 let cache = KvCache::with_dims(1, 2, 3);
2546 let err = cache
2547 .write_bytes(0, KvSlot::K, 0, 1, &[0u8; 24], &device)
2548 .expect_err("with_dims cache has no fixed dtype/capacity");
2549 assert!(
2550 err.to_string().contains("with_capacity"),
2551 "refusal must name the real constraint, got: {err}",
2552 );
2553 }
2554
2555 /// A range exceeding `max_seq_len` must refuse before touching anything —
2556 /// never silently clamp (which would write at the wrong position) and
2557 /// never panic.
2558 #[test]
2559 fn write_bytes_refuses_an_out_of_range_position() {
2560 let device = Device::cpu();
2561 let cache = KvCache::with_capacity(1, 2, 3, 5, DType::F32, &device).unwrap();
2562 let payload = vec![0.0f32; 2 * 2 * 3]; // n=2 positions, valid byte length
2563 let err = cache
2564 .write_bytes(
2565 0,
2566 KvSlot::K,
2567 4, // start=4, n=2 -> [4,6) exceeds max_seq_len=5
2568 2,
2569 bytemuck::cast_slice(&payload),
2570 &device,
2571 )
2572 .expect_err("range must be refused, not clamped");
2573 assert!(
2574 err.to_string().contains("max_seq_len"),
2575 "refusal must name the real constraint, got: {err}",
2576 );
2577 }
2578
2579 /// A `bytes` length that doesn't match `n * n_kv_heads * head_dim *
2580 /// dtype_size` must refuse — a mismatched length is the shape of exactly
2581 /// the bug this check exists to catch (a caller passing position-major
2582 /// pool bytes straight through without transposing to head-major).
2583 #[test]
2584 fn write_bytes_refuses_a_mismatched_byte_length() {
2585 let device = Device::cpu();
2586 let cache = KvCache::with_capacity(1, 2, 3, 5, DType::F32, &device).unwrap();
2587 let wrong_payload = vec![0.0f32; 5]; // not n_kv_heads*n*head_dim for any valid n
2588 let err = cache
2589 .write_bytes(
2590 0,
2591 KvSlot::K,
2592 0,
2593 1,
2594 bytemuck::cast_slice(&wrong_payload),
2595 &device,
2596 )
2597 .expect_err("mismatched byte length must be refused");
2598 assert!(
2599 err.to_string().contains("bytes"),
2600 "refusal must name the byte-length mismatch, got: {err}",
2601 );
2602 }
2603
2604 /// Phase D symbolic extents — the decode-shaped path: a persistent
2605 /// fixed-capacity buffer + an `Op::WriteSlice` whose start offset is
2606 /// a per-pass `SymEnv` binding (the KV-cache append at `cached_len`).
2607 /// `realize_one_as_with_env` threads the env from the session through
2608 /// the bridge to the executor; the width-2 slab lands at the bound
2609 /// offset (3), not the static placeholder (0). Re-realizing the SAME
2610 /// graph with a different binding lands the slab at the new offset —
2611 /// the input-independent-graph property persistent decode relies on.
2612 #[test]
2613 fn realize_one_as_with_env_resolves_write_slice_offset() {
2614 use fuel_ir::{DynScalar, SymId};
2615 let dest_arc = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[0.0_f32; 6])));
2616 let src_arc = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[7.0_f32, 8.0])));
2617 let graph = Arc::new(RwLock::new(Graph::new()));
2618 let sym = SymId(0);
2619 let (dest_id, src_id, ws_id) = {
2620 let mut g = graph.write().unwrap();
2621 let dest = g.push(Node {
2622 op: Op::Const,
2623 inputs: vec![],
2624 shape: Shape::from_dims(&[6]),
2625 dtype: DType::F32,
2626 });
2627 let src = g.push(Node {
2628 op: Op::Const,
2629 inputs: vec![],
2630 shape: Shape::from_dims(&[2]),
2631 dtype: DType::F32,
2632 });
2633 let ws = g.push(Node {
2634 op: Op::WriteSlice {
2635 ranges: vec![(0, 2)],
2636 dyn_offset: Some((0, DynScalar::Sym(sym))),
2637 },
2638 inputs: vec![dest, src],
2639 shape: Shape::from_dims(&[6]),
2640 dtype: DType::F32,
2641 });
2642 (dest, src, ws)
2643 };
2644 let mut ctx = InferenceContext::new(Device::cpu());
2645 ctx.insert(dest_id, Arc::clone(&dest_arc));
2646 ctx.insert(src_id, Arc::clone(&src_arc));
2647
2648 // Bind cached_len = 3: the slab must append at indices [3, 4].
2649 let mut env = SymEnv::new();
2650 env.bind(sym, 3).unwrap();
2651 let out = ctx
2652 .realize_one_as_with_env::<f32>(&graph, ws_id, &env)
2653 .expect("realize_one_as_with_env");
2654 assert_eq!(
2655 out,
2656 vec![0.0, 0.0, 0.0, 7.0, 8.0, 0.0],
2657 "KV slab must land at the SymEnv-bound cached_len=3, not the placeholder 0",
2658 );
2659
2660 // An empty env on a graph with an unbound dyn_offset surfaces a
2661 // typed error (never a panic) — the write-once contract's
2662 // "presence ⇒ produced" read at realize.
2663 let err = ctx.realize_one_as_with_env::<f32>(&graph, ws_id, &SymEnv::new());
2664 assert!(
2665 err.is_err(),
2666 "unbound cached_len must surface a typed error"
2667 );
2668 }
2669
2670 /// `KvCache::with_dims` produces a fresh cache of the right
2671 /// shape with all layers `None` and `cached_len = 0`.
2672 #[test]
2673 fn kv_cache_with_dims_constructs_fresh() {
2674 let cache = KvCache::with_dims(4, 8, 64);
2675 assert_eq!(cache.n_layers(), 4);
2676 assert_eq!(cache.cached_len, 0);
2677 assert_eq!(cache.n_kv_heads, 8);
2678 assert_eq!(cache.head_dim, 64);
2679 for li in 0..4 {
2680 assert!(cache.layer(li).is_none());
2681 }
2682 }
2683
2684 /// `KvCache::set_layer` + `layer` round-trip.
2685 #[test]
2686 fn kv_cache_set_and_get_layer() {
2687 let mut cache = KvCache::with_dims(2, 4, 8);
2688 let k_arc = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[0.0_f32; 32])));
2689 let v_arc = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[0.0_f32; 32])));
2690 let layout = Layout::contiguous(Shape::from_dims(&[1, 4, 1, 8]));
2691 cache.set_layer(
2692 0,
2693 KvLayer {
2694 k: Arc::clone(&k_arc),
2695 v: Arc::clone(&v_arc),
2696 k_layout: layout.clone(),
2697 v_layout: layout.clone(),
2698 k_version: 0,
2699 v_version: 0,
2700 k_authority: AuthorityState::Host,
2701 v_authority: AuthorityState::Host,
2702 },
2703 );
2704 let layer = cache.layer(0).expect("just set");
2705 assert!(Arc::ptr_eq(&layer.k, &k_arc));
2706 assert!(Arc::ptr_eq(&layer.v, &v_arc));
2707 assert_eq!(layer.k_version, 0);
2708 assert!(matches!(layer.k_authority, AuthorityState::Host));
2709 assert!(cache.layer(1).is_none());
2710 }
2711
2712 /// `KvCache::clear` drops all layers and resets `cached_len`.
2713 #[test]
2714 fn kv_cache_clear_drops_layers() {
2715 let mut cache = KvCache::with_dims(2, 4, 8);
2716 let k = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[0.0_f32; 32])));
2717 let v = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[0.0_f32; 32])));
2718 let layout = Layout::contiguous(Shape::from_dims(&[1, 4, 1, 8]));
2719 cache.set_layer(
2720 0,
2721 KvLayer {
2722 k: Arc::clone(&k),
2723 v: Arc::clone(&v),
2724 k_layout: layout.clone(),
2725 v_layout: layout,
2726 k_version: 1,
2727 v_version: 1,
2728 k_authority: AuthorityState::Host,
2729 v_authority: AuthorityState::Host,
2730 },
2731 );
2732 cache.cached_len = 7;
2733 // Before clear: cache holds an Arc to k → strong_count 2.
2734 assert_eq!(Arc::strong_count(&k), 2);
2735
2736 cache.clear();
2737
2738 assert!(cache.layer(0).is_none());
2739 assert_eq!(cache.cached_len, 0);
2740 // After clear: cache's Arc dropped → strong_count 1.
2741 assert_eq!(Arc::strong_count(&k), 1);
2742 }
2743
2744 /// `KvCache::truncate_to` updates `cached_len` only (Phase E.3.0
2745 /// limitation; pre-allocated buffer + WriteSlice handles the
2746 /// in-place truncate in Phase E.3.2).
2747 #[test]
2748 fn kv_cache_truncate_updates_cached_len() {
2749 let mut cache = KvCache::with_dims(2, 4, 8);
2750 cache.cached_len = 16;
2751 cache.truncate_to(10);
2752 assert_eq!(cache.cached_len, 10);
2753 // Truncating to a value >= current is a no-op.
2754 cache.truncate_to(15);
2755 assert_eq!(cache.cached_len, 10);
2756 // Truncating to zero clears the live extent.
2757 cache.truncate_to(0);
2758 assert_eq!(cache.cached_len, 0);
2759 }
2760
2761 /// Authority + version fields are placeholders today; just
2762 /// confirm they default sensibly via `KvLayer` construction.
2763 #[test]
2764 fn kv_layer_default_authority_is_host() {
2765 let arc = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[0.0_f32; 4])));
2766 let layout = Layout::contiguous(Shape::from_dims(&[4]));
2767 let layer = KvLayer {
2768 k: Arc::clone(&arc),
2769 v: Arc::clone(&arc),
2770 k_layout: layout.clone(),
2771 v_layout: layout,
2772 k_version: 0,
2773 v_version: 0,
2774 k_authority: AuthorityState::Host,
2775 v_authority: AuthorityState::Host,
2776 };
2777 assert!(matches!(layer.k_authority, AuthorityState::Host));
2778 assert!(matches!(layer.v_authority, AuthorityState::Host));
2779 assert_eq!(layer.k_version, 0);
2780 assert_eq!(layer.v_version, 0);
2781 }
2782
2783 // ---- KvCache::with_capacity + accessors (Phase E.3.3.A) -----------------
2784
2785 /// `with_capacity` allocates n_layers fresh K + V buffers on the
2786 /// CPU device. Each buffer is `n_kv_heads * max_seq_len * head_dim`
2787 /// elements of the requested dtype, zero-initialized, with the
2788 /// `[1, n_kv_heads, max_seq_len, head_dim]` layout pre-populated.
2789 #[test]
2790 // `BackendStorage::{Cuda,Vulkan,Metal}` are cfg-gated, so at default
2791 // features `Cpu` is the only variant and this `if let` is irrefutable;
2792 // under --features cuda/vulkan/metal the pattern is refutable, so a plain
2793 // `let` would be an E0005 there. Allow the default-features lint.
2794 #[allow(irrefutable_let_patterns)]
2795 fn kv_cache_with_capacity_allocates_all_layers_on_cpu() {
2796 let device = Device::cpu();
2797 let cache = KvCache::with_capacity(
2798 /* n_layers */ 3,
2799 /* n_kv_heads */ 4,
2800 /* head_dim */ 16,
2801 /* max_seq_len */ 32,
2802 DType::F32,
2803 &device,
2804 )
2805 .expect("with_capacity");
2806
2807 assert_eq!(cache.n_layers(), 3);
2808 assert_eq!(cache.cached_len, 0);
2809 assert_eq!(cache.n_kv_heads, 4);
2810 assert_eq!(cache.head_dim, 16);
2811 assert_eq!(cache.max_seq_len, Some(32));
2812 assert_eq!(cache.dtype, Some(DType::F32));
2813
2814 // Every layer is populated and has the expected layout.
2815 for li in 0..3 {
2816 let layer = cache.layer(li).expect("layer populated");
2817 assert_eq!(layer.k_layout.shape().dims(), &[1, 4, 32, 16]);
2818 assert_eq!(layer.v_layout.shape().dims(), &[1, 4, 32, 16]);
2819 // Bytes are zero-initialized: 4 (n_kv) * 32 (seq) * 16 (head)
2820 // * 4 (f32) = 8192 bytes per slot.
2821 let k_guard = layer.k.read().unwrap();
2822 assert_eq!(k_guard.inner.len_bytes(), 8192);
2823 assert_eq!(k_guard.dtype, DType::F32);
2824 // Spot-check zero init.
2825 if let BackendStorage::Cpu(c) = &k_guard.inner {
2826 let typed: &[f32] = c.as_slice().unwrap();
2827 assert!(typed.iter().all(|&x| x == 0.0));
2828 } else {
2829 panic!("expected CPU storage");
2830 }
2831 }
2832 }
2833
2834 /// `slot_storage(li, K)` returns the same Arc as `layer(li).k`.
2835 /// Used by the forward path to bind cache storage to per-step
2836 /// Const nodes.
2837 #[test]
2838 fn kv_cache_slot_storage_returns_layer_arc() {
2839 let device = Device::cpu();
2840 let cache =
2841 KvCache::with_capacity(2, 4, 8, 16, DType::F32, &device).expect("with_capacity");
2842
2843 let k_via_layer = Arc::clone(&cache.layer(0).unwrap().k);
2844 let k_via_slot = cache.slot_storage(0, KvSlot::K).expect("layer 0 K");
2845 assert!(
2846 Arc::ptr_eq(&k_via_layer, &k_via_slot),
2847 "slot_storage should return the same Arc as layer().k",
2848 );
2849
2850 let v_via_layer = Arc::clone(&cache.layer(1).unwrap().v);
2851 let v_via_slot = cache.slot_storage(1, KvSlot::V).expect("layer 1 V");
2852 assert!(Arc::ptr_eq(&v_via_layer, &v_via_slot));
2853 }
2854
2855 /// `slot_storage` returns `None` for an unpopulated layer (the
2856 /// with_dims path before the first set_layer) and for an out-of-
2857 /// range layer index.
2858 #[test]
2859 fn kv_cache_slot_storage_returns_none_for_unpopulated() {
2860 let cache = KvCache::with_dims(2, 4, 8);
2861 assert!(cache.slot_storage(0, KvSlot::K).is_none());
2862 assert!(cache.slot_storage(1, KvSlot::V).is_none());
2863 // Out of range.
2864 assert!(cache.slot_storage(5, KvSlot::K).is_none());
2865 }
2866
2867 /// `bump_version` advances the per-slot version counter
2868 /// independently for K and V.
2869 #[test]
2870 fn kv_cache_bump_version_advances_per_slot() {
2871 let device = Device::cpu();
2872 let mut cache =
2873 KvCache::with_capacity(1, 4, 8, 16, DType::F32, &device).expect("with_capacity");
2874 assert_eq!(cache.layer(0).unwrap().k_version, 0);
2875 assert_eq!(cache.layer(0).unwrap().v_version, 0);
2876
2877 cache.bump_version(0, KvSlot::K);
2878 cache.bump_version(0, KvSlot::K);
2879 cache.bump_version(0, KvSlot::V);
2880
2881 assert_eq!(cache.layer(0).unwrap().k_version, 2);
2882 assert_eq!(cache.layer(0).unwrap().v_version, 1);
2883 }
2884
2885 /// Bumping a version on an unpopulated layer is a no-op (not a
2886 /// panic). The `with_dims` path leaves layers `None`; the
2887 /// forward code shouldn't blow up if it calls bump_version
2888 /// before the layer is wired.
2889 #[test]
2890 fn kv_cache_bump_version_unpopulated_is_noop() {
2891 let mut cache = KvCache::with_dims(2, 4, 8);
2892 cache.bump_version(0, KvSlot::K);
2893 cache.bump_version(99, KvSlot::V); // out of range, also no-op
2894 assert!(cache.layer(0).is_none());
2895 }
2896
2897 /// Sanity: bf16 capacity allocation produces 2-byte elements.
2898 #[test]
2899 fn kv_cache_with_capacity_bf16_byte_count() {
2900 let device = Device::cpu();
2901 let cache =
2902 KvCache::with_capacity(1, 2, 4, 8, DType::BF16, &device).expect("with_capacity bf16");
2903 let layer = cache.layer(0).unwrap();
2904 // 2 (n_kv) * 8 (seq) * 4 (head) * 2 (bf16) = 128 bytes per slot.
2905 assert_eq!(layer.k.read().unwrap().inner.len_bytes(), 128);
2906 assert_eq!(cache.dtype, Some(DType::BF16));
2907 }
2908
2909 // ---- LatentKvCache (MLA increment 4 — persistent N-slot decode cache) --
2910
2911 /// `LatentKvCache::with_capacity` allocates `n_layers * n_slots` fresh
2912 /// zero-initialized buffers on the CPU device, one per (layer, slot),
2913 /// shaped `[max_seq_len, ...slot_trailing[s]]`.
2914 #[test]
2915 // Irrefutable only at default features: `BackendStorage::{Cuda,Vulkan,
2916 // Metal}` are cfg-gated, so under --features cuda/vulkan/metal this pattern
2917 // is refutable and a plain `let` would be an E0005. Allow the default lint.
2918 #[allow(irrefutable_let_patterns)]
2919 fn latent_kv_cache_with_capacity_allocates_all_layers_on_cpu() {
2920 let device = Device::cpu();
2921 let cache = LatentKvCache::with_capacity(
2922 /* n_layers */ 3,
2923 /* max_seq_len */ 8,
2924 // MLA-shaped: slot 0 latent trailing [5], slot 1 k_pe trailing [2].
2925 vec![vec![5], vec![2]],
2926 DType::F32,
2927 &device,
2928 )
2929 .expect("with_capacity");
2930
2931 assert_eq!(cache.n_layers(), 3);
2932 assert_eq!(cache.n_slots(), 2);
2933 assert_eq!(cache.cached_len, 0);
2934 assert_eq!(cache.max_seq_len, 8);
2935 assert_eq!(cache.dtype, DType::F32);
2936 assert_eq!(cache.slot_trailing(0), &[5]);
2937 assert_eq!(cache.slot_trailing(1), &[2]);
2938
2939 for li in 0..3 {
2940 let latent = cache.slot_storage(li, 0).expect("latent slot populated");
2941 let kpe = cache.slot_storage(li, 1).expect("k_pe slot populated");
2942 // 8 (max_seq) * 5 (trailing) * 4 (f32) = 160 bytes.
2943 assert_eq!(latent.read().unwrap().inner.len_bytes(), 160);
2944 // 8 (max_seq) * 2 (trailing) * 4 (f32) = 64 bytes.
2945 assert_eq!(kpe.read().unwrap().inner.len_bytes(), 64);
2946 let guard = latent.read().unwrap();
2947 if let BackendStorage::Cpu(c) = &guard.inner {
2948 let typed: &[f32] = c.as_slice().unwrap();
2949 assert!(typed.iter().all(|&x| x == 0.0));
2950 } else {
2951 panic!("expected CPU storage");
2952 }
2953 }
2954 }
2955
2956 /// `slot_storage` returns `None` for an out-of-range layer or slot
2957 /// index (never panics).
2958 #[test]
2959 fn latent_kv_cache_slot_storage_returns_none_for_oob() {
2960 let device = Device::cpu();
2961 let cache = LatentKvCache::with_capacity(2, 4, vec![vec![3]], DType::F32, &device)
2962 .expect("with_capacity");
2963 assert!(cache.slot_storage(5, 0).is_none()); // layer OOB
2964 assert!(cache.slot_storage(0, 5).is_none()); // slot OOB
2965 }
2966
2967 /// `bump_version` advances the per-slot version counter independently
2968 /// per slot; out-of-range (layer, slot) is a no-op, never a panic.
2969 #[test]
2970 fn latent_kv_cache_bump_version_advances_per_slot_and_oob_is_noop() {
2971 let device = Device::cpu();
2972 let mut cache =
2973 LatentKvCache::with_capacity(1, 4, vec![vec![2], vec![1]], DType::F32, &device)
2974 .expect("with_capacity");
2975
2976 cache.bump_version(0, 0);
2977 cache.bump_version(0, 0);
2978 cache.bump_version(0, 1);
2979 cache.bump_version(99, 0); // layer OOB, no-op
2980 cache.bump_version(0, 99); // slot OOB, no-op
2981
2982 let layer0 = cache.layers[0].as_ref().expect("layer 0 populated");
2983 assert_eq!(layer0[0].version, 2);
2984 assert_eq!(layer0[1].version, 1);
2985 }
2986
2987 /// Degenerate geometry (`n_layers == 0`, `max_seq_len == 0`, or no
2988 /// slots) surfaces as a typed `Err`, never a panic.
2989 #[test]
2990 fn latent_kv_cache_with_capacity_rejects_bad_geometry() {
2991 let device = Device::cpu();
2992 assert!(LatentKvCache::with_capacity(0, 4, vec![vec![2]], DType::F32, &device).is_err());
2993 assert!(LatentKvCache::with_capacity(1, 0, vec![vec![2]], DType::F32, &device).is_err());
2994 assert!(LatentKvCache::with_capacity(1, 4, vec![], DType::F32, &device).is_err());
2995 }
2996}