diff --git a/architecture.json b/architecture.json index d658bf1d..b9af636f 100644 --- a/architecture.json +++ b/architecture.json @@ -53,7 +53,7 @@ "exceptions": [ {"crate": "leleka-cuda-model", "file": "src/env_switch.rs", "ratchet": "env-read", "reason": "EnvSwitch is the one reader of the operator environment in this crate: it reads one named variable on the first get() and applies a typed rule"}, {"crate": "leleka-cuda-model", "file": "src/env_switch.rs", "ratchet": "process-global", "reason": "the OnceLock inside EnvSwitch caches the switch position for the process life (an immutable operator setting; a hot path pays one atomic load)"}, - {"crate": "leleka-cuda-model", "file": "src/serving_context.rs", "ratchet": "process-global", "reason": "the serving context is fixed once at engine start (configure_serving_context) and read by every kernel geometry; injecting it through every owner is the settings follow-up of S13. The resident KV window is not here any more: it belongs to the driver Context"}, + {"crate": "leleka-cuda-model", "file": "src/serving_context.rs", "ratchet": "process-global", "reason": "the serving context is fixed once at engine start (configure_serving_context); the driver copies it into each Context when the Context is created and every kernel geometry reads it from the Context, so this cell is read at one place (create_context). The engine composition still reads it for the bind-time cell count; handing the value down from the config is the follow-up of S13. The resident KV window is not here: it belongs to the driver Context"}, {"crate": "leleka-cpu-worker", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"}, {"crate": "leleka-tokenizer", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"}, {"crate": "leleka-gptoss-npu", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"}, diff --git a/crates/cuda-driver/src/bringup_trace_enabled.rs b/crates/cuda-driver/src/bringup_trace_enabled.rs index 14ed6d7d..881a122a 100644 --- a/crates/cuda-driver/src/bringup_trace_enabled.rs +++ b/crates/cuda-driver/src/bringup_trace_enabled.rs @@ -4,6 +4,7 @@ use super::{ Cell, Context, Device, Driver, Error, PoisonCell, PromptSyncTrace, Rc, Result, RoutedGateUpQ8, ffi, qwen_dispatch, }; +use leleka_cuda_model::serving_context::ServingContext; impl PromptSyncTrace { pub fn enter() -> Self { @@ -50,7 +51,12 @@ impl Driver { } } impl<'driver> Device<'driver> { + /// A context for the serving context the process configured (the trained default when none was). pub fn create_context(&self, byte_budget: usize) -> Result> { + self.create_context_serving(byte_budget, crate::serving_context::serving_context()) + } + /// A context whose buffers are sized and whose rotating kernels are parameterized for `serving`. + pub fn create_context_serving(&self, byte_budget: usize, serving: ServingContext) -> Result> { valid_size(byte_budget)?; let api = &self.driver.api; let handle = api.create(self.handle)?; @@ -64,7 +70,9 @@ impl<'driver> Device<'driver> { } return combine(Err(error), cleanup); } - Ok(Context::fresh(self.driver, handle, self.ordinal, byte_budget)) + let mut context = Context::fresh(self.driver, handle, self.ordinal, byte_budget); + context.retained.serving = serving; + Ok(context) } } impl<'driver> Context<'driver> { @@ -95,7 +103,7 @@ impl<'driver> Context<'driver> { qwen_kernels: qwen_dispatch::Cache::new(), kar_levels: Cell::new(None), experimental: std::array::from_fn(|_| Cell::new(None)), - retained: crate::prompt_sync_trace_types::Retained::default(), + retained: crate::prompt_sync_trace_types::Retained::new(ServingContext::trained()), } } } diff --git a/crates/cuda-driver/src/context_kv_resident.rs b/crates/cuda-driver/src/context_kv_resident.rs deleted file mode 100644 index 25999f3f..00000000 --- a/crates/cuda-driver/src/context_kv_resident.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! The resident KV window of a Context (`--kv-resident N`, the Original's `qsa_set_kv_resident`): the cell count its -//! streamed QSA owners keep in VRAM. It belongs to the Context, not to the process: every owner sizes its pool from -//! the value when it is created, so an owner created before the window is set keeps the default window consistently. - -use super::{Context, Error, Result}; -use crate::serving_context::{KV_RESIDENT_DEFAULT_CELLS, geometry}; - -impl Context<'_> { - /// Fix the resident KV window of this context. `0` keeps the whole context resident; a positive count is raised to - /// `qsa_kv_resident_min()` (20480) and rounded up to whole pages. The first call wins; a later call must request - /// the same count. - pub fn configure_kv_resident(&self, cells: usize) -> Result<()> { - geometry().resident_pages_for(cells).map_err(|_| Error::InvalidDriverValue("resident KV window"))?; - match self.retained.kv_resident.get() { - Some(set) if set != cells => { - Err(Error::InvalidDriverValue("resident KV window already configured differently")) - } - _ => { - self.retained.kv_resident.set(Some(cells)); - Ok(()) - } - } - } - - /// Resident pages (VRAM slots) a new streamed QSA owner of this context allocates. - pub(crate) fn kv_resident_pages(&self) -> Result { - geometry() - .resident_pages_for(self.retained.kv_resident.get().unwrap_or(KV_RESIDENT_DEFAULT_CELLS)) - .map_err(|_| Error::InvalidDriverValue("resident KV window")) - } -} diff --git a/crates/cuda-driver/src/context_serving.rs b/crates/cuda-driver/src/context_serving.rs new file mode 100644 index 00000000..000786b8 --- /dev/null +++ b/crates/cuda-driver/src/context_serving.rs @@ -0,0 +1,40 @@ +//! The serving context of a Context: the cell count its buffers are sized from and the RoPE constants of its rotating +//! kernels (fixed when the context is created), and the resident KV window its streamed QSA owners keep in VRAM +//! (`--kv-resident N`, the Original's `qsa_set_kv_resident`). Both belong to the Context, not to the process: every +//! owner sizes its pool from the value when it is created, so an owner created before the window is set keeps the +//! default window consistently. + +use super::{Context, Error, Result}; +use crate::serving_context::{KV_RESIDENT_DEFAULT_CELLS, ServingContext}; +use leleka_context::geometry::QsaGeometry; + +impl Context<'_> { + /// The serving context this context was created for. + pub fn serving(&self) -> &ServingContext { + &self.retained.serving + } + + /// The geometry every context-linear size of this context is derived from. + pub fn serving_geometry(&self) -> QsaGeometry { + self.retained.serving.geometry + } + + /// Fix the resident KV window of this context. The first call wins; a later call must request the same count. + pub fn configure_kv_resident(&self, cells: usize) -> Result<()> { + self.serving().resident_pages_for(cells)?; + match self.retained.kv_resident.get() { + Some(set) if set != cells => { + Err(Error::InvalidDriverValue("resident KV window already configured differently")) + } + _ => { + self.retained.kv_resident.set(Some(cells)); + Ok(()) + } + } + } + + /// Resident pages (VRAM slots) a new streamed QSA owner of this context allocates. + pub(crate) fn kv_resident_pages(&self) -> Result { + self.serving().resident_pages_for(self.retained.kv_resident.get().unwrap_or(KV_RESIDENT_DEFAULT_CELLS)) + } +} diff --git a/crates/cuda-driver/src/kv_stream_gpu/stream_proof.rs b/crates/cuda-driver/src/kv_stream_gpu/stream_proof.rs index 56b7237b..853cffcb 100644 --- a/crates/cuda-driver/src/kv_stream_gpu/stream_proof.rs +++ b/crates/cuda-driver/src/kv_stream_gpu/stream_proof.rs @@ -27,11 +27,11 @@ fn synthetic_image(rng: &mut Rng) -> [Vec; 4] { /// The real mapped host copy holding `image` and the device addresses of its four runs. fn map_host(c: &Context<'_>, image: &[Vec; 4]) -> (MappedAllocation, [u64; 4]) { - let geometry = crate::serving_context::geometry(); + let geometry = c.serving_geometry(); let offsets = geometry.stage_offsets().unwrap(); let mut mapped = { let g = c.enter().unwrap(); - let m = MappedAllocation::new(); + let m = MappedAllocation::new(geometry); g.finish().unwrap(); m.expect("pinned mapped host copy") }; @@ -61,7 +61,7 @@ impl<'c> Pools<'c> { let identity = upload(c, &i32s(&(0..N_BLOCKS as i32).collect::>())).unwrap(); let stage = PAGE.iter().map(|n| c.allocate(n * N_BLOCKS).unwrap()).collect(); let resident = PAGE.iter().map(|n| c.allocate(n * slots).unwrap()).collect(); - let table = c.allocate(crate::serving_context::geometry().page_table_bytes()).unwrap(); + let table = c.allocate(c.serving_geometry().page_table_bytes()).unwrap(); Self { reference, identity, stage, resident, table } } @@ -205,7 +205,7 @@ impl<'c> Stream<'c> { fn new(c: &'c Context<'c>) -> Self { let mut w = c.native_batch_workspace().expect("workspace"); let mut rng = Rng(0x2545_f491_4f6c_dd1d); - let slots = crate::serving_context::geometry().resident_pages_for(20_480).unwrap(); + let slots = c.serving_geometry().resident_pages_for(20_480).unwrap(); assert_eq!(slots, 5120); let image = synthetic_image(&mut rng); let (mapped, host) = map_host(c, &image); @@ -257,7 +257,7 @@ impl<'c> Stream<'c> { /// Every block the call named is resident and holds the host bytes; nothing overflowed. fn check_resident(&mut self, call: usize, named: &BTreeSet) { - let bytes = crate::serving_context::geometry().page_table_bytes(); + let bytes = self.pools.table.context.serving_geometry().page_table_bytes(); let map = self.pools.table.copy_to_owned(bytes).unwrap(); let map: Vec = map.chunks_exact(4).map(|b| i32::from_le_bytes(b.try_into().unwrap())).collect(); let slots = self.slots; diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index cf31551a..b36fb6a3 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -273,7 +273,7 @@ use q6_k_shape::q6_k_shape; use q6_k_shape::vector_shape; mod context; mod context_gate_up_projection_admission; -mod context_kv_resident; +mod context_serving; mod context_matvec_k_quant_projections; mod context_projection_kernel_slots; mod context_routed_gate_up_projection; diff --git a/crates/cuda-driver/src/prompt_sync_trace_types/retained.rs b/crates/cuda-driver/src/prompt_sync_trace_types/retained.rs index 1a7b5862..a908964d 100644 --- a/crates/cuda-driver/src/prompt_sync_trace_types/retained.rs +++ b/crates/cuda-driver/src/prompt_sync_trace_types/retained.rs @@ -1,13 +1,17 @@ //! What a `Context` keeps for itself: the verify-window modules, the deferred buffer frees and the resident KV window //! its streamed QSA owners are sized from. -use super::{Cell, Rc, RefCell, ffi}; #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] use super::original_verify; +use super::{Cell, Rc, RefCell, ffi}; +use leleka_cuda_model::serving_context::ServingContext; -/// State that lives and dies with the context: the lists start empty, the KV window unset. -#[derive(Default)] +/// State that lives and dies with the context: its serving context, the lists (empty at the start) and the KV window +/// (unset at the start). pub(crate) struct Retained { + /// The serving context this context was created for: the cell count every context-linear buffer is sized + /// from and the RoPE constants of the rotating kernels. Fixed for the life of the context. + pub(crate) serving: ServingContext, /// Sealed verify-window modules loaded under this context, shared by every verifier bank created later /// (the serve path assembles one per request) and unloaded with the context. pub(crate) window_modules: RefCell, Vec<&'static str>)>>, @@ -17,3 +21,13 @@ pub(crate) struct Retained { /// The resident KV window of this context's streamed QSA owners, in cells; `None` keeps the default window. pub(crate) kv_resident: Cell>, } +impl Retained { + pub(crate) fn new(serving: ServingContext) -> Self { + Self { + serving, + window_modules: RefCell::default(), + deferred_frees: RefCell::default(), + kv_resident: Cell::new(None), + } + } +} diff --git a/crates/cuda-driver/src/qsa_index_ffi.rs b/crates/cuda-driver/src/qsa_index_ffi.rs index b5643810..63883d21 100644 --- a/crates/cuda-driver/src/qsa_index_ffi.rs +++ b/crates/cuda-driver/src/qsa_index_ffi.rs @@ -1,5 +1,6 @@ //! Private fixed Original QSA entries. No stream/Blas ownership or public grid API. use crate::{Error, Result, combine, ffi::BufferHandle}; +use leleka_cuda_model::serving_context::ServingContext; use std::ffi::CStr; pub(crate) enum Arg { Address(BufferHandle), @@ -21,9 +22,9 @@ pub(crate) struct Arguments { } impl Arguments { /// The arguments of `shape` followed, where its kernel takes them, by the serving context's RoPE constants. - pub(crate) fn for_launch(shape: Launch, mut values: Vec) -> Result { + pub(crate) fn for_launch(serving: &ServingContext, shape: Launch, mut values: Vec) -> Result { + shape.check_reach(serving)?; if shape.carries_rope() { - let serving = crate::serving_context::serving_context(); values.extend(rope_tail(rope_abi()?, serving.rope_is_scaled(), serving.rope_args)?); } Self::new(values) @@ -186,14 +187,19 @@ impl Launch { fn carries_rope(self) -> bool { matches!(self, Self::First | Self::Blocks(_) | Self::Rope(_) | Self::DecodeAppend | Self::DecodeRope(_)) } + /// Refuses a ScoreTC reach past the score row of the serving context (checked where the arguments are built, which + /// is where the serving context is known). + fn check_reach(self, serving: &ServingContext) -> Result<()> { + match self { + Self::Tc { reach, .. } if reach as usize > serving.geometry.max_blocks() => Err(Error::InvalidQwenShape), + _ => Ok(()), + } + } /// Refuses the launches whose extents the Original fixes: the ScoreTC window and the decode norm/rope widths. fn check_extents(self) -> Result<()> { match self { Self::Tc { t, reach } => { - if !(1..=256).contains(&t) - || reach == 0 - || reach as usize > crate::serving_context::geometry().max_blocks() - { + if !(1..=256).contains(&t) || reach == 0 { return Err(Error::InvalidQwenShape); } } diff --git a/crates/cuda-driver/src/qsa_late/gpu_tests/rng.rs b/crates/cuda-driver/src/qsa_late/gpu_tests/rng.rs index f6e73761..580ce720 100644 --- a/crates/cuda-driver/src/qsa_late/gpu_tests/rng.rs +++ b/crates/cuda-driver/src/qsa_late/gpu_tests/rng.rs @@ -31,7 +31,7 @@ pub(super) fn with_gpu(body: impl FnOnce(&Context<'_>, usize, usize)) { let context = device.create_context(6usize << 30).expect("context"); let workspace = context.native_batch_workspace().expect("workspace"); let stream = workspace.blas().expect("blas").stream(); - let max_blocks = crate::serving_context::geometry().max_blocks(); + let max_blocks = context.serving_geometry().max_blocks(); body(&context, stream, max_blocks); } diff --git a/crates/cuda-driver/src/qsa_prompt_host_ffi.rs b/crates/cuda-driver/src/qsa_prompt_host_ffi.rs index ef090030..31bc67fb 100644 --- a/crates/cuda-driver/src/qsa_prompt_host_ffi.rs +++ b/crates/cuda-driver/src/qsa_prompt_host_ffi.rs @@ -1,9 +1,10 @@ //! Private fixed mapped-host allocation. Caller holds actual Context and drains before CPU access/free. use crate::{Error, Result}; -/// Original payload + four 256 B cursor alignment allowances, for the configured serving context +use leleka_context::geometry::QsaGeometry; +/// Original payload + four 256 B cursor alignment allowances, for the serving context of `geometry` /// (`276_825_088` at the trained 262144 cells). -fn configured_bytes() -> Result { - crate::serving_context::geometry().mapped_host_bytes().map_err(|_| Error::InvalidSize) +fn configured_bytes(geometry: QsaGeometry) -> Result { + geometry.mapped_host_bytes().map_err(|_| Error::InvalidSize) } #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod enabled { @@ -55,12 +56,12 @@ mod enabled { free: Free, } impl MappedAllocation { - pub(crate) fn new() -> Result { + pub(crate) fn new(geometry: QsaGeometry) -> Result { let library = open_library()?; let alloc = sym!(library, c"cuMemHostAlloc", Alloc); let address = sym!(library, c"cuMemHostGetDevicePointer_v2", Address); let free = sym!(library, c"cuMemFreeHost", Free); - let bytes = configured_bytes()?; + let bytes = configured_bytes(geometry)?; let mut ptr = std::ptr::null_mut(); // SAFETY: valid out pointer; flags 3 = PORTABLE|DEVICEMAP; a context is current (the caller holds the // Context). On success the allocation is `bytes` long, page-aligned, and owned by `MappedAllocation` @@ -173,11 +174,11 @@ pub(crate) struct MappedAllocation; target_pointer_width = "64" )))] impl MappedAllocation { - pub(crate) fn new() -> Result { + pub(crate) fn new(_: QsaGeometry) -> Result { Err(Error::UnsupportedPlatform) } pub(crate) fn bytes(&self) -> usize { - configured_bytes().unwrap_or(0) + 0 } pub(crate) fn address(&self, _: usize, _: usize) -> Result { Err(Error::UnsupportedPlatform) diff --git a/crates/cuda-driver/src/qsa_prompt_index/append_select.rs b/crates/cuda-driver/src/qsa_prompt_index/append_select.rs index 596e9360..9a504f60 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/append_select.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/append_select.rs @@ -37,9 +37,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { Ok(()) } fn select_bounds_ok(&self, p: usize, n: usize) -> bool { - n != 0 - && n <= self.capacity - && p.checked_add(n).is_some_and(|e| e <= crate::serving_context::geometry().cells()) + n != 0 && n <= self.capacity && p.checked_add(n).is_some_and(|e| e <= self.context.serving_geometry().cells()) } /// Budget check, exact-size allocation and alias admission of the five outputs; releases them on failure. fn admit_outputs( diff --git a/crates/cuda-driver/src/qsa_prompt_index/max_blocks.rs b/crates/cuda-driver/src/qsa_prompt_index/max_blocks.rs index 52a69af9..c9a0e742 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/max_blocks.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/max_blocks.rs @@ -2,14 +2,14 @@ //! buffer sizes), the f32 little-endian encoder for uploads and the Context constructors. use super::{Context, Error, QsaPromptIndexWorkspace, Result}; +use leleka_context::geometry::QsaGeometry; -/// Score row stride (blocks plus tail and spare) of the configured serving context: `65538` at 262144 cells. -pub(super) fn max_blocks() -> usize { - crate::serving_context::geometry().max_blocks() +/// Score row stride (blocks plus tail and spare) of the serving context `g`: `65538` at 262144 cells. +pub(super) fn max_blocks(g: QsaGeometry) -> usize { + g.max_blocks() } // pooled,tail,dead,block_position,raw,K,V,Qfull,IndexQ,scores,status. -pub(super) fn sizes() -> [usize; 11] { - let g = crate::serving_context::geometry(); +pub(super) fn sizes(g: QsaGeometry) -> [usize; 11] { [ g.pooled_rows() * 128 * 4, 384 * 4, diff --git a/crates/cuda-driver/src/qsa_prompt_index/prompt_device/device_phases.rs b/crates/cuda-driver/src/qsa_prompt_index/prompt_device/device_phases.rs index e7bdd0be..84bb67a4 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/prompt_device/device_phases.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/prompt_device/device_phases.rs @@ -7,6 +7,7 @@ use super::{ QsaPromptIndexWorkspace, RESERVE, Result, S, SCRATCH, SELECT, arena_span, combine, common, ffi, max_blocks, native_block, sizes, }; +use leleka_context::geometry::QsaGeometry; type Spans = Vec<(ffi::BufferHandle, usize)>; @@ -30,11 +31,12 @@ pub(super) fn index_for<'ctx>( context: &'ctx Context<'ctx>, capacity: usize, ) -> ([usize; 11], QsaPromptIndexWorkspace<'ctx>) { - let mut sizes = sizes(); + let geometry = context.serving_geometry(); + let mut sizes = sizes(geometry); for i in [4, 5, 6, 7, 8] { sizes[i] = 4 } - sizes[9] = capacity.min(256) * max_blocks() * 4; + sizes[9] = capacity.min(256) * max_blocks(geometry) * 4; let index = QsaPromptIndexWorkspace { capacity, sizes, @@ -250,9 +252,9 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { } /// The prior image must have the lengths of a prompt starting at `p` and be finite. - pub(super) fn check_prior(t: usize, p: usize, prior: [&[f32]; 3]) -> Result<()> { + pub(super) fn check_prior(geometry: QsaGeometry, t: usize, p: usize, prior: [&[f32]; 3]) -> Result<()> { let [pooled, tail, dead] = prior; - if p.checked_add(t).is_none_or(|end| end > crate::serving_context::geometry().cells()) + if p.checked_add(t).is_none_or(|end| end > geometry.cells()) || pooled.len() != p / 4 * 128 || tail.len() != 384 || dead.len() != 128 diff --git a/crates/cuda-driver/src/qsa_prompt_index/prompt_device/device_prepare.rs b/crates/cuda-driver/src/qsa_prompt_index/prompt_device/device_prepare.rs index f19a6140..aa0e7350 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/prompt_device/device_prepare.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/prompt_device/device_prepare.rs @@ -40,7 +40,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { let QsaChunkPrior { first_position: p0, image } = prior; let QsaIndexPrior { pooled, tail, dead } = image; let (t, p) = (read.rows(), p0 as usize); - Self::check_prior(t, p, [pooled, tail, dead])?; + Self::check_prior(self.context.serving_geometry(), t, p, [pooled, tail, dead])?; let (w, gamma) = self.admit(&read, &weights, ws)?; self.project_prior(&read, ws, &weights.kinds, w)?; let (out, [raw, qfull, iq]) = self.index_spans(&read, t)?; diff --git a/crates/cuda-driver/src/qsa_prompt_index/prompt_device/original_qsa_prompt_device.rs b/crates/cuda-driver/src/qsa_prompt_index/prompt_device/original_qsa_prompt_device.rs index 1eb1120c..c69b4823 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/prompt_device/original_qsa_prompt_device.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/prompt_device/original_qsa_prompt_device.rs @@ -7,9 +7,10 @@ use super::{ OriginalQsaPromptWeights, QsaNativePacking, QsaPromptIndexWorkspace, RESERVE, Result, SCRATCH, ffi, max_blocks, sizes, }; +use leleka_context::geometry::QsaGeometry; impl<'ctx> OriginalQsaPromptDevice<'ctx> { - pub fn device_bytes(capacity: usize) -> Result { + pub fn device_bytes(geometry: QsaGeometry, capacity: usize) -> Result { if !(1..=8192).contains(&capacity) { return Err(Error::InvalidQwenShape); } @@ -17,17 +18,19 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { // projection/normalized/IDs/attn/Out payloads are actual arena spans. (SCRATCH + { - let z = sizes(); + let z = sizes(geometry); z[0] + z[1] + z[2] + z[3] } + 5 * 4 + 64) - .checked_add(capacity.min(256) * max_blocks() * 4) + .checked_add(capacity.min(256) * max_blocks(geometry) * 4) .and_then(|x| x.checked_add(capacity * 16)) .ok_or(Error::BudgetExceeded) } pub(super) fn new(context: &'ctx Context<'ctx>, capacity: usize, packing: QsaNativePacking) -> Result { - let required = Self::device_bytes(capacity)?.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + let required = Self::device_bytes(context.serving_geometry(), capacity)? + .checked_add(RESERVE) + .ok_or(Error::BudgetExceeded)?; check_assets()?; if context.is_poisoned() { return Err(Error::ContextPoisoned); diff --git a/crates/cuda-driver/src/qsa_prompt_index/prompt_device/resident_device/original_qsa_prompt_device.rs b/crates/cuda-driver/src/qsa_prompt_index/prompt_device/resident_device/original_qsa_prompt_device.rs index e25dbe21..2e106d4b 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/prompt_device/resident_device/original_qsa_prompt_device.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/prompt_device/resident_device/original_qsa_prompt_device.rs @@ -7,6 +7,7 @@ use super::{ OriginalQsaResidentIndex, OriginalQsaResidentSelection, PrefillPhase, ProjectionSpans, ProjectionWeight, QsaPromptIndexWorkspace, RESERVE, ResidentContinuation, Result, S, arena_span, combine, common, ffi, }; +use leleka_context::geometry::QsaGeometry; /// The spans the resident index program reads and writes for one chunk. struct ResidentSpans { @@ -96,7 +97,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { if t == 0 || t > self.capacity { return Err(Error::InvalidQwenShape); } - if p.checked_add(t).is_none_or(|end| end > crate::serving_context::geometry().cells()) { + if p.checked_add(t).is_none_or(|end| end > self.context.serving_geometry().cells()) { return Err(Error::InvalidQwenShape); } self.admit_budget(t)?; @@ -253,19 +254,20 @@ impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> } pub(crate) fn kv_stage_spans(&self, c: &Context<'_>) -> Result<[ffi::BufferHandle; 4]> { self.validate(c)?; - kv_stage_spans_of(&self.read, self.rows()) + kv_stage_spans_of(c.serving_geometry(), &self.read, self.rows()) } } /// The four KV stage spans of a read lease for `rows` rows (the arena's `kv_k_q`, `kv_v_q`, `kv_k_scale`, /// `kv_v_scale`), each checked against the layer's working spans. The stage is the same four arena spans for every QSA /// layer of a chunk, so they are known before the layer's indexer runs. pub(crate) fn kv_stage_spans_of( + geometry: QsaGeometry, read: &OriginalDeviceGrRead<'_, '_, '_>, rows: usize, ) -> Result<[ffi::BufferHandle; 4]> { let mut spans = Vec::new(); spans.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; - let runs = crate::serving_context::geometry().stage_runs().map_err(|_| Error::InvalidSize)?; + let runs = geometry.stage_runs().map_err(|_| Error::InvalidSize)?; for (name, bytes) in [("kv_k_q", runs[0]), ("kv_v_q", runs[1]), ("kv_k_scale", runs[2]), ("kv_v_scale", runs[3])] { let (h, n) = read.lease().span(PrefillPhase::Common, name)?; if n != bytes { diff --git a/crates/cuda-driver/src/qsa_prompt_index/prompt_device/resident_device/qsa_prompt_device_resident_bring_up.rs b/crates/cuda-driver/src/qsa_prompt_index/prompt_device/resident_device/qsa_prompt_device_resident_bring_up.rs index 75fdebe0..a2bb5167 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/prompt_device/resident_device/qsa_prompt_device_resident_bring_up.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/prompt_device/resident_device/qsa_prompt_device_resident_bring_up.rs @@ -6,6 +6,7 @@ use super::{ OriginalQsaResidentPromptDevice, POSTOPS, QsaNativePacking, QsaPromptIndexWorkspace, RESERVE, Result, SCRATCH, SELECT, combine, max_blocks, sizes, }; +use leleka_context::geometry::QsaGeometry; /// The sealed kernels must be the pinned ones. fn check_sealed() -> Result<()> { @@ -22,15 +23,15 @@ fn check_sealed() -> Result<()> { Ok(()) } /// The index image holds four 4-byte placeholders instead of the canonical image. -fn resident_sizes(capacity: usize) -> [usize; 11] { - let mut sizes = sizes(); +fn resident_sizes(geometry: QsaGeometry, capacity: usize) -> [usize; 11] { + let mut sizes = sizes(geometry); for n in &mut sizes[..4] { *n = 4; } for i in [4, 5, 6, 7, 8] { sizes[i] = 4 } - sizes[9] = capacity.min(256) * max_blocks() * 4; + sizes[9] = capacity.min(256) * max_blocks(geometry) * 4; sizes } impl<'ctx> OriginalQsaPromptDevice<'ctx> { @@ -39,7 +40,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { capacity: usize, packing: QsaNativePacking, ) -> Result { - let required = OriginalQsaResidentPromptDevice::device_bytes(capacity)? + let required = OriginalQsaResidentPromptDevice::device_bytes(context.serving_geometry(), capacity)? .checked_add(RESERVE) .ok_or(Error::BudgetExceeded)?; check_sealed()?; @@ -51,7 +52,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { { return Err(Error::BudgetExceeded); } - let sizes = resident_sizes(capacity); + let sizes = resident_sizes(context.serving_geometry(), capacity); let mut owner = Self::unloaded(context, capacity, packing, sizes); if let Err(e) = owner.init_resident(sizes) { let _ = owner.close(); diff --git a/crates/cuda-driver/src/qsa_prompt_index/prompt_device/resident_device/qsa_resident_prompt_device_prepare.rs b/crates/cuda-driver/src/qsa_prompt_index/prompt_device/resident_device/qsa_resident_prompt_device_prepare.rs index b41e243b..25e73cd7 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/prompt_device/resident_device/qsa_resident_prompt_device_prepare.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/prompt_device/resident_device/qsa_resident_prompt_device_prepare.rs @@ -11,6 +11,7 @@ use super::{ }; use crate::ple_batch_ffi::LinearLaunch; use crate::qsa_prompt_attention::OriginalQsaAttendedKv; +use leleka_context::geometry::QsaGeometry; impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> OriginalQsaResidentSelection<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> @@ -172,10 +173,10 @@ impl<'ctx> Context<'ctx> { } } impl<'ctx> OriginalQsaResidentPromptDevice<'ctx> { - pub fn device_bytes(capacity: usize) -> Result { - OriginalQsaPromptDevice::device_bytes(capacity)? + pub fn device_bytes(geometry: QsaGeometry, capacity: usize) -> Result { + OriginalQsaPromptDevice::device_bytes(geometry, capacity)? .checked_sub({ - let z = sizes(); + let z = sizes(geometry); z[0] + z[1] + z[2] + z[3] }) .and_then(|n| n.checked_add(16)) diff --git a/crates/cuda-driver/src/qsa_prompt_index/qsa_prompt_index_workspace.rs b/crates/cuda-driver/src/qsa_prompt_index/qsa_prompt_index_workspace.rs index 5ad47d57..31c9cd3c 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/qsa_prompt_index_workspace.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/qsa_prompt_index_workspace.rs @@ -6,6 +6,7 @@ use super::{ QsaIndexPrior, QsaPromptIndexWorkspace, QsaPromptSelection, RESERVE, Result, SELECT, SelectRequest, encode, ffi, max_blocks, sizes, }; +use leleka_context::geometry::QsaGeometry; impl<'ctx> QsaPromptIndexWorkspace<'ctx> { pub(super) fn new(context: &'ctx Context<'ctx>) -> Result { @@ -15,7 +16,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { if !(1..=8192).contains(&capacity) { return Err(Error::InvalidQwenShape); } - let sizes = capacity_sizes(capacity)?; + let sizes = capacity_sizes(context.serving_geometry(), capacity)?; let output_bytes = capacity * (512 * 2 + 6144 + CAP + 4) * 4; check_assets_sealed()?; if context.is_poisoned() { @@ -55,11 +56,11 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { } Ok(()) } - pub fn prompt_device_bytes(capacity: usize) -> Result { + pub fn prompt_device_bytes(geometry: QsaGeometry, capacity: usize) -> Result { if !(1..=8192).contains(&capacity) { return Err(Error::InvalidQwenShape); } - let s = sizes(); + let s = sizes(geometry); Ok(s[0] + s[1] + s[2] @@ -67,7 +68,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { + 8 + 64 + capacity * (128 + 12288 + 512) * 4 - + capacity.min(256) * max_blocks() * 4) + + capacity.min(256) * max_blocks(geometry) * 4) } pub fn prompt_output_bytes(capacity: usize) -> Result { if !(1..=8192).contains(&capacity) { @@ -170,12 +171,12 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { } /// Buffer sizes for a workspace of `capacity` rows. -fn capacity_sizes(capacity: usize) -> Result<[usize; 11]> { - let mut sizes = sizes(); +fn capacity_sizes(geometry: QsaGeometry, capacity: usize) -> Result<[usize; 11]> { + let mut sizes = sizes(geometry); for i in [4, 7, 8] { sizes[i] = (sizes[i] / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?; } - sizes[9] = capacity.min(256) * max_blocks() * 4; + sizes[9] = capacity.min(256) * max_blocks(geometry) * 4; Ok(sizes) } diff --git a/crates/cuda-driver/src/qsa_prompt_index/resident_index/image_bytes.rs b/crates/cuda-driver/src/qsa_prompt_index/resident_index/image_bytes.rs index 288a94e0..8bb46612 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/resident_index/image_bytes.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/resident_index/image_bytes.rs @@ -5,9 +5,10 @@ use super::{ CHECKPOINT_BYTES, Context, DeviceBuffer, Error, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex, POOLED, Result, Saved, sizes, }; +use leleka_context::geometry::QsaGeometry; -pub(super) fn image_bytes() -> usize { - sizes()[0] + 1536 + 512 + 4 +pub(super) fn image_bytes(geometry: QsaGeometry) -> usize { + sizes(geometry)[0] + 1536 + 512 + 4 } impl Drop for Saved<'_> { fn drop(&mut self) { @@ -44,7 +45,7 @@ impl OriginalQsaIndexCheckpoint<'_> { if self.0.bytes.context.is_poisoned() { return Err(Error::ContextPoisoned); } - if self.0.end > crate::serving_context::geometry().cells() + if self.0.end > context.serving_geometry().cells() || self.0.end > self.0.coverage.end.get() || self.0.bytes.len() != CHECKPOINT_BYTES { diff --git a/crates/cuda-driver/src/qsa_prompt_index/resident_index/original_qsa_resident_index.rs b/crates/cuda-driver/src/qsa_prompt_index/resident_index/original_qsa_resident_index.rs index 5b60cb1e..10b18958 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/resident_index/original_qsa_resident_index.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/resident_index/original_qsa_resident_index.rs @@ -6,13 +6,14 @@ use super::{ OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex, RESERVE, Rc, RefCell, Result, Saved, Transfer, combine, ffi, image_bytes, sizes, }; +use leleka_context::geometry::QsaGeometry; impl<'ctx> OriginalQsaResidentIndex<'ctx> { - pub fn device_bytes() -> usize { - image_bytes() + pub fn device_bytes(geometry: QsaGeometry) -> usize { + image_bytes(geometry) } pub(super) fn new(context: &'ctx Context<'ctx>) -> Result { - let n = image_bytes().checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + let n = image_bytes(context.serving_geometry()).checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; if context.is_poisoned() { return Err(Error::ContextPoisoned); } @@ -48,7 +49,7 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> { // One-time bounded initialization, never a whole host index image. Each // upload owns its actual staging until completion; no 33MiB host allocation. let zero = [0u8; 65536]; - for (i, n) in [sizes()[0], 1536, 512, 4].into_iter().enumerate() { + for (i, n) in [sizes(context.serving_geometry())[0], 1536, 512, 4].into_iter().enumerate() { self.image[i] = Some(context.allocate(n)?); let b = self.image[i].as_mut().ok_or(Error::ContextPoisoned)?; for offset in (0..n).step_by(zero.len()) { @@ -80,7 +81,7 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> { if self.is_failed() || self.copy.is_none() { return Err(Error::ContextPoisoned); } - for (i, n) in [sizes()[0], 1536, 512, 4].into_iter().enumerate() { + for (i, n) in [sizes(self.context.serving_geometry())[0], 1536, 512, 4].into_iter().enumerate() { let b = self.image[i].as_ref().ok_or(Error::ContextPoisoned)?; if !std::ptr::eq(b.context, self.context) || b.len() != n { return Err(Error::InvalidQwenShape); @@ -94,7 +95,7 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> { if !Rc::ptr_eq(&self.origin, &s.0.origin) || self.epoch != s.0.epoch || s.0.end > s.0.coverage.end.get() - || s.0.end > crate::serving_context::geometry().cells() + || s.0.end > self.context.serving_geometry().cells() || !std::ptr::eq(self.context, s.0.bytes.context) || s.0.bytes.len() != CHECKPOINT_BYTES { diff --git a/crates/cuda-driver/src/qsa_prompt_index/resident_index/qsa_resident_index_checkpoint_restore.rs b/crates/cuda-driver/src/qsa_prompt_index/resident_index/qsa_resident_index_checkpoint_restore.rs index c355189f..69eabde4 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/resident_index/qsa_resident_index_checkpoint_restore.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/resident_index/qsa_resident_index_checkpoint_restore.rs @@ -62,7 +62,7 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> { if !std::ptr::eq(self.context, w.context) { return Err(Error::ContextMismatch); } - let image_sizes = [sizes()[0], 1536, 512, 4]; + let image_sizes = [sizes(self.context.serving_geometry())[0], 1536, 512, 4]; let sizes = std::array::from_fn(|i| w.sizes[i]); for i in 0..4 { std::mem::swap(&mut self.image[i], &mut w.buffers[i]); @@ -267,7 +267,7 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> { if self.in_flight { return Err(Error::InvalidQwenShape); } - if tail.len() != CHECKPOINT_BYTES || end > crate::serving_context::geometry().cells() { + if tail.len() != CHECKPOINT_BYTES || end > self.context.serving_geometry().cells() { return Err(Error::InvalidQwenShape); } for (first, bytes) in spans { diff --git a/crates/cuda-driver/src/qsa_prompt_index/resident_index/verification_commit/original_verify_qsa_journal.rs b/crates/cuda-driver/src/qsa_prompt_index/resident_index/verification_commit/original_verify_qsa_journal.rs index 6d8de783..7f3221e1 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/resident_index/verification_commit/original_verify_qsa_journal.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/resident_index/verification_commit/original_verify_qsa_journal.rs @@ -101,7 +101,7 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> { let end = indices[0].next_position(); check_aligned(context, &indices, &mapped, end)?; check_gamma(context, &gamma, &indices)?; - rope.validate(context, crate::serving_context::geometry().cells())?; + rope.validate(context, context.serving_geometry().cells())?; check_rope_clear(&rope, &indices)?; Ok(Rc::new(Self { context, diff --git a/crates/cuda-driver/src/qsa_prompt_index/resident_index/verification_commit/verify_qsa_journal_capture_commit.rs b/crates/cuda-driver/src/qsa_prompt_index/resident_index/verification_commit/verify_qsa_journal_capture_commit.rs index 0acfb90d..e9366951 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/resident_index/verification_commit/verify_qsa_journal_capture_commit.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/resident_index/verification_commit/verify_qsa_journal_capture_commit.rs @@ -109,7 +109,7 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> { .rope .positions .as_ref() - .map(|b| whole(self.context, b, crate::serving_context::geometry().cells() * 12)) + .map(|b| whole(self.context, b, self.context.serving_geometry().cells() * 12)) .transpose()? .unwrap_or(0)) } diff --git a/crates/cuda-driver/src/qsa_prompt_index/resident_index/verification_commit/verify_qsa_journal_index_image.rs b/crates/cuda-driver/src/qsa_prompt_index/resident_index/verification_commit/verify_qsa_journal_index_image.rs index 7be50103..1b52fca6 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/resident_index/verification_commit/verify_qsa_journal_index_image.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/resident_index/verification_commit/verify_qsa_journal_index_image.rs @@ -26,7 +26,7 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> { .rope .positions .as_ref() - .map(|b| whole(self.context, b, crate::serving_context::geometry().cells() * 12)) + .map(|b| whole(self.context, b, self.context.serving_geometry().cells() * 12)) .transpose()? .unwrap_or(0); Ok(Some(IndexImage { tail, dead, pooled, block_pos, gamma, positions, rope: index_rope(&self.rope) })) diff --git a/crates/cuda-driver/src/qsa_prompt_index/resident_program/arena_plan.rs b/crates/cuda-driver/src/qsa_prompt_index/resident_program/arena_plan.rs index 2947b04a..60deb723 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/resident_program/arena_plan.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/resident_program/arena_plan.rs @@ -2,6 +2,7 @@ //! function; the submission and the checks stay in `qsa_prompt_index_workspace.rs`. use super::{A, Arguments, CAP, Error, Launch, QsaPromptIndexWorkspace, Result, ffi, max_blocks}; +use leleka_cuda_model::serving_context::ServingContext; /// A launch of `qsa_late.cu`: (position in `commands` it runs before, grid, entry, block, arguments). pub(super) type LateLaunch = (usize, u32, usize, u32, crate::ple_batch_ffi::KernelArguments); @@ -56,6 +57,8 @@ pub(super) struct ArenaPlan { pub(super) commands: Vec<(Launch, Arguments)>, pub(super) late: Vec, pushed: usize, + /// The serving context of the Context the program is planned for (launch geometry and RoPE constants). + serving: ServingContext, } /// One 256-row tile of the score selection. @@ -70,13 +73,13 @@ struct Tile { } impl ArenaPlan { - pub(super) fn new(n: usize) -> Result { + pub(super) fn new(n: usize, serving: ServingContext) -> Result { let mut commands = Vec::new(); commands.try_reserve_exact(32 + 4 * n.div_ceil(256)).map_err(|_| Error::HostAllocation)?; - Ok(Self { commands, late: Vec::new(), pushed: 0 }) + Ok(Self { commands, late: Vec::new(), pushed: 0, serving }) } fn push(&mut self, shape: Launch, args: Vec) -> Result<()> { - self.commands.push((shape, Arguments::for_launch(shape, args)?)); + self.commands.push((shape, Arguments::for_launch(&self.serving, shape, args)?)); self.pushed += 1; Ok(()) } @@ -215,7 +218,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { A::Address(io.dead), A::Address(io.pooled), A::Address(self.handle(3, 4)?), - A::I32(crate::serving_context::geometry().cells() as i32), + A::I32(plan.serving.geometry.cells() as i32), A::F32(io.theta), ], ) @@ -262,7 +265,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { fn plan_tiles(&self, plan: &mut ArenaPlan, io: &ArenaIo, fast_select: bool) -> Result<()> { let n = io.t as usize; let tile_rows = if io.decode { 1 } else { n.min(256) }; - let scores = self.handle(9, tile_rows * max_blocks() * 4)?; + let scores = self.handle(9, tile_rows * max_blocks(plan.serving.geometry) * 4)?; for first_row in (0..n).step_by(256) { let tile = Tile::new(io, scores, first_row)?; self.plan_scores(plan, io, &tile)?; @@ -275,7 +278,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { Ok(()) } fn plan_scores(&self, plan: &mut ArenaPlan, io: &ArenaIo, tile: &Tile) -> Result<()> { - let mb = max_blocks() as i64; + let mb = max_blocks(plan.serving.geometry) as i64; let (pooled, dead, iq, steps, scores) = (io.pooled, io.dead, tile.iq, tile.steps, tile.scores); let (pooled, dead, iq, steps, scores) = (A::Address(pooled), A::Address(dead), A::Address(iq), A::Address(steps), A::Address(scores)); @@ -291,7 +294,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { /// qsa_late.cu: the same flag over the blocks the tile can hold, and the same ids from coalesced reads. fn plan_late_select(plan: &mut ArenaPlan, io: &ArenaIo, tile: &Tile) { use crate::ple_batch_ffi::{BatchArg as B, KernelArguments as Args}; - let mb = max_blocks() as i64; + let mb = max_blocks(plan.serving.geometry) as i64; let (scores, steps) = (B::Address(tile.scores), B::Address(tile.steps)); plan.defer( (tile.count * tile.reach).div_ceil(256) as u32, @@ -313,10 +316,10 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { plan.defer(tile.ct, topk_entry, topk_block, args); } fn plan_scan_select(plan: &mut ArenaPlan, io: &ArenaIo, tile: &Tile) -> Result<()> { - let mb = max_blocks() as i64; + let mb = max_blocks(plan.serving.geometry) as i64; let (scores, steps) = (A::Address(tile.scores), A::Address(tile.steps)); plan.push( - Launch::ScoreScan((tile.count * max_blocks()) as u32), + Launch::ScoreScan((tile.count * max_blocks(plan.serving.geometry)) as u32), vec![scores, steps, A::I32(tile.count as i32), A::I64(mb), A::Address(io.status), A::U32(4)], )?; let (scores, steps) = (A::Address(tile.scores), A::Address(tile.steps)); diff --git a/crates/cuda-driver/src/qsa_prompt_index/resident_program/prefix_replay.rs b/crates/cuda-driver/src/qsa_prompt_index/resident_program/prefix_replay.rs index d91ed4c2..de059308 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/resident_program/prefix_replay.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/resident_program/prefix_replay.rs @@ -4,6 +4,7 @@ use super::{ A, Arguments, CAP, DeviceBuffer, Error, Launch, NativeBatchWorkspace, QsaPromptIndexWorkspace, Result, combine, ffi, }; +use leleka_cuda_model::serving_context::ServingContext; /// The device spans one accepted-prefix replay reads and writes. struct ReplayIo { @@ -15,6 +16,7 @@ struct ReplayIo { tail: ffi::BufferHandle, dead: ffi::BufferHandle, bp: ffi::BufferHandle, + serving: ServingContext, } /// The launches of a replay and the step rows they read. type ReplayWork<'ctx> = (Vec<(Launch, Arguments)>, DeviceBuffer<'ctx>); @@ -54,6 +56,7 @@ fn replay_commands(p0: usize, t: usize, io: &ReplayIo) -> Result Result { Arguments::for_launch( + &io.serving, Launch::DecodeAppend, vec![ A::Address(key), @@ -65,7 +68,7 @@ fn replay_append(io: &ReplayIo, key: ffi::BufferHandle, pos: ffi::BufferHandle, A::Address(io.dead), A::Address(io.pooled), A::Address(io.bp), - A::I32(crate::serving_context::geometry().cells() as i32), + A::I32(io.serving.geometry.cells() as i32), A::F32(theta), ], ) @@ -90,7 +93,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { let [status, pooled, tail, dead, bp] = self.replay_handles()?; let step = self.upload_steps(p0, t)?; let sh = step.handle.ok_or(Error::ContextPoisoned)?; - let io = ReplayIo { raw, gamma, step: sh, status, pooled, tail, dead, bp }; + let io = ReplayIo { raw, gamma, step: sh, status, pooled, tail, dead, bp, serving: *self.context.serving() }; let commands = replay_commands(p0, t, &io)?; let mut flags = [0u8; 64]; self.run_replay(ws, status, (commands, step), &mut flags)?; @@ -118,8 +121,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { (raw, gamma): (ffi::BufferHandle, ffi::BufferHandle), ws: &NativeBatchWorkspace<'ctx>, ) -> Result<()> { - if !(1..=8192).contains(&t) || p0.checked_add(t).is_none_or(|x| x > crate::serving_context::geometry().cells()) - { + if !(1..=8192).contains(&t) || p0.checked_add(t).is_none_or(|x| x > self.context.serving_geometry().cells()) { return Err(Error::InvalidQwenShape); } ws.validate_context(self.context)?; diff --git a/crates/cuda-driver/src/qsa_prompt_index/resident_program/qsa_prompt_index_workspace.rs b/crates/cuda-driver/src/qsa_prompt_index/resident_program/qsa_prompt_index_workspace.rs index 50a0da82..0edd1424 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/resident_program/qsa_prompt_index_workspace.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/resident_program/qsa_prompt_index_workspace.rs @@ -32,7 +32,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { let n = call.t as usize; let steps = Self::arena_steps(call.p0 as usize, n)?; let status = self.handle(10, 64)?; - let mut plan = ArenaPlan::new(n)?; + let mut plan = ArenaPlan::new(n, *self.context.serving())?; let fast_select = !call.decode && crate::qsa_late::usable(self.context); let (io, decode_positions) = self.arena_io(call, status)?; self.plan_arena(&mut plan, &io, fast_select)?; diff --git a/crates/cuda-driver/src/qsa_prompt_index/resident_scalar_index.rs b/crates/cuda-driver/src/qsa_prompt_index/resident_scalar_index.rs index 01c0921b..383f67e7 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/resident_scalar_index.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/resident_scalar_index.rs @@ -5,20 +5,21 @@ use super::{ NativeBatchWorkspace, OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex, POSTOPS, QsaPromptIndexWorkspace, RESERVE, ResidentContinuation, Result, SELECT, combine, encode, ffi, max_blocks, sizes, }; +use leleka_context::geometry::QsaGeometry; type Outputs<'ctx> = [Option>; 5]; pub struct OriginalQsaResidentScalarIndex<'ctx> { workspace: QsaPromptIndexWorkspace<'ctx>, } /// The index buffers of a scalar index: the image is four 4-byte placeholders. -fn scalar_index_sizes() -> [usize; 11] { - let mut sizes = sizes(); +fn scalar_index_sizes(geometry: QsaGeometry) -> [usize; 11] { + let mut sizes = sizes(geometry); for n in &mut sizes[..4] { *n = 4; } sizes[4] = 608; sizes[7] = 49152; sizes[8] = 2048; - sizes[9] = max_blocks() * 4; + sizes[9] = max_blocks(geometry) * 4; sizes } /// The sizes of the five outputs: K, V, the query, the selected ids and the finite flags. @@ -33,7 +34,7 @@ impl<'ctx> Context<'ctx> { if [INDEX, SELECT, POSTOPS, DECODE_POSTOPS].iter().any(|x| x.starts_with(b"// UNSEALED")) { return Err(Error::UnsupportedQwenOperation); } - let sizes = scalar_index_sizes(); + let sizes = scalar_index_sizes(self.serving_geometry()); self.admit_scalar_index(&sizes)?; let mut workspace = QsaPromptIndexWorkspace { capacity: 1, @@ -209,7 +210,7 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> { if resident.in_flight || resident.unpublished || resident.next_position() != p - || p >= crate::serving_context::geometry().cells() + || p >= context.serving_geometry().cells() || !std::ptr::eq(resident.context, context) { return Err(Error::InvalidQwenShape); diff --git a/crates/cuda-driver/src/qsa_prompt_index/run_launches.rs b/crates/cuda-driver/src/qsa_prompt_index/run_launches.rs index 4cf2eadd..1580deec 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/run_launches.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/run_launches.rs @@ -20,6 +20,7 @@ pub(super) fn push_scan( ) -> Result<()> { push_launch( commands, + &plan.serving, Launch::Scan(count as u32), vec![A::Address(buf), A::I64(count as i64), A::Address(plan.status), A::U32(which)], ) @@ -45,7 +46,7 @@ fn push_decode_norm_rope( (heads, dim, _): (u32, i32, i64), ) -> Result<()> { let rms = vec![A::Address(buf), A::Address(gamma), A::Address(buf), A::I32(dim), A::F32(1e-6)]; - push_launch(commands, Launch::DecodeRms(heads), rms)?; + push_launch(commands, &plan.serving, Launch::DecodeRms(heads), rms)?; let rope = vec![ A::Address(buf), A::Address(buf), @@ -54,7 +55,7 @@ fn push_decode_norm_rope( A::F32(plan.theta), A::Address(positions), ]; - push_launch(commands, Launch::DecodeRope(heads), rope) + push_launch(commands, &plan.serving, Launch::DecodeRope(heads), rope) } fn push_prompt_norm_rope( @@ -64,7 +65,7 @@ fn push_prompt_norm_rope( (heads, dim, stride): (u32, i32, i64), ) -> Result<()> { let rms = vec![A::Address(buf), A::Address(gamma), A::I64(dim as i64), A::I64(dim as i64), A::F32(1e-6)]; - push_launch(commands, Launch::Rms(plan.t * heads), rms)?; + push_launch(commands, &plan.serving, Launch::Rms(plan.t * heads), rms)?; let rope = vec![ A::Address(buf), A::I64(heads as i64), @@ -73,7 +74,7 @@ fn push_prompt_norm_rope( A::I64(plan.p0 as i64), A::F32(plan.theta), ]; - push_launch(commands, Launch::Rope(plan.t * heads), rope) + push_launch(commands, &plan.serving, Launch::Rope(plan.t * heads), rope) } impl<'ctx> QsaPromptIndexWorkspace<'ctx> { @@ -113,10 +114,10 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { A::Address(plan.dead), A::Address(plan.pooled), A::Address(self.handle(3, 4)?), - A::I32(crate::serving_context::geometry().cells() as i32), + A::I32(plan.serving.geometry.cells() as i32), A::F32(plan.theta), ]; - push_launch(commands, Launch::DecodeAppend, args) + push_launch(commands, &plan.serving, Launch::DecodeAppend, args) } fn push_pool_prompt(&self, commands: &mut Commands, plan: &RunPlan, gamma: ffi::BufferHandle) -> Result<()> { @@ -132,7 +133,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { self.push_pool_blocks(commands, plan, gamma, (first, hi))?; } let tail = vec![A::Address(plan.raw), A::I64(t as i64), A::I64(p0 as i64), A::Address(plan.tail)]; - push_launch(commands, Launch::Tail, tail) + push_launch(commands, &plan.serving, Launch::Tail, tail) } fn push_pool_blocks( @@ -157,7 +158,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { A::I64(hi as i64), A::F32(plan.theta), ]; - push_launch(commands, Launch::Blocks((hi - first + 1) as u32), args) + push_launch(commands, &plan.serving, Launch::Blocks((hi - first + 1) as u32), args) } pub(super) fn push_scores( @@ -170,7 +171,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { // Original prompt selection reuses one 256-row score tile. Every // offset is checked against the actual whole producer allocation. let tile_rows = if plan.decode { 1 } else { n.min(256) }; - let scores = self.handle(9, tile_rows * max_blocks() * 4)?; + let scores = self.handle(9, tile_rows * max_blocks(plan.serving.geometry) * 4)?; for first_row in (0..n).step_by(256) { let count = (n - first_row).min(256); let tile = ScoreTile { @@ -195,7 +196,7 @@ fn push_pool_first(commands: &mut Commands, plan: &RunPlan, gamma: ffi::BufferHa A::Address(plan.pooled), A::F32(plan.theta), ]; - push_launch(commands, Launch::First, args) + push_launch(commands, &plan.serving, Launch::First, args) } fn push_tile_scores( @@ -211,20 +212,20 @@ fn push_tile_scores( A::Address(tile.iq), A::Address(tile.steps), A::I32(1), - A::I64(max_blocks() as i64), + A::I64(max_blocks(plan.serving.geometry) as i64), A::Address(scores), ]; - return push_launch(commands, Launch::DecodeScores, args); + return push_launch(commands, &plan.serving, Launch::DecodeScores, args); } push_tile_tc(commands, plan, scores, tile)?; let tail = vec![ A::Address(plan.dead), A::Address(tile.iq), A::Address(tile.steps), - A::I64(max_blocks() as i64), + A::I64(max_blocks(plan.serving.geometry) as i64), A::Address(scores), ]; - push_launch(commands, Launch::ScoreTail(tile.count as u32), tail) + push_launch(commands, &plan.serving, Launch::ScoreTail(tile.count as u32), tail) } fn push_tile_tc(commands: &mut Commands, plan: &RunPlan, scores: ffi::BufferHandle, tile: &ScoreTile) -> Result<()> { @@ -233,11 +234,11 @@ fn push_tile_tc(commands: &mut Commands, plan: &RunPlan, scores: ffi::BufferHand A::Address(tile.iq), A::Address(tile.steps), A::I64(tile.count as i64), - A::I64(max_blocks() as i64), + A::I64(max_blocks(plan.serving.geometry) as i64), A::I64(tile.reach as i64), A::Address(scores), ]; - push_launch(commands, Launch::Tc { t: tile.count as u32, reach: tile.reach as u32 }, tc) + push_launch(commands, &plan.serving, Launch::Tc { t: tile.count as u32, reach: tile.reach as u32 }, tc) } fn push_tile_select( @@ -250,17 +251,22 @@ fn push_tile_select( A::Address(scores), A::Address(tile.steps), A::I32(tile.count as i32), - A::I64(max_blocks() as i64), + A::I64(max_blocks(plan.serving.geometry) as i64), A::Address(plan.status), A::U32(4), ]; - push_launch(commands, Launch::ScoreScan((tile.count * max_blocks()) as u32), scan)?; + push_launch( + commands, + &plan.serving, + Launch::ScoreScan((tile.count * max_blocks(plan.serving.geometry)) as u32), + scan, + )?; let topk = vec![ A::Address(scores), A::Address(tile.steps), - A::I64(max_blocks() as i64), + A::I64(max_blocks(plan.serving.geometry) as i64), A::I64(CAP as i64), A::Address(tile.ids), ]; - push_launch(commands, Launch::Topk(tile.count as u32), topk) + push_launch(commands, &plan.serving, Launch::Topk(tile.count as u32), topk) } diff --git a/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs b/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs index 42cc86e4..0468f1da 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs @@ -6,6 +6,7 @@ use super::{ QsaPromptIndexWorkspace, Result, encode, ffi, }; use crate::ple_batch_ffi::Blas; +use leleka_cuda_model::serving_context::ServingContext; pub(super) type Commands = Vec<(Launch, Arguments)>; @@ -23,6 +24,8 @@ pub(super) struct RunPlan { pub(super) status: ffi::BufferHandle, pub(super) positions: Option, pub(super) theta: f32, + /// The serving context of the Context the run is built for (launch geometry and RoPE constants). + pub(super) serving: ServingContext, } #[derive(Default)] @@ -52,8 +55,13 @@ impl HostStaging { } } -pub(super) fn push_launch(commands: &mut Commands, shape: Launch, args: Vec) -> Result<()> { - commands.push((shape, Arguments::for_launch(shape, args)?)); +pub(super) fn push_launch( + commands: &mut Commands, + serving: &ServingContext, + shape: Launch, + args: Vec, +) -> Result<()> { + commands.push((shape, Arguments::for_launch(serving, shape, args)?)); Ok(()) } @@ -181,6 +189,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { status, positions, theta, + serving: *self.context.serving(), }) } @@ -200,7 +209,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { None => self.handle(7, n * 12288 * 4)?, }; let split = vec![A::Address(qfull), A::Address(out[2]), A::I64(plan.t as i64)]; - push_launch(commands, Launch::Split((n * 6144) as u32), split)?; + push_launch(commands, &plan.serving, Launch::Split((n * 6144) as u32), split)?; push_norm_rope(commands, plan, (out[2], gamma[0]), (24, 256, 6144))?; push_scan(commands, plan, out[2], n * 6144, 1)?; push_norm_rope(commands, plan, (plan.iq, gamma[2]), (4, 128, 512))?; @@ -218,7 +227,12 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { let n = plan.t as usize; self.push_pool(commands, plan, gamma, out[4])?; self.push_scores(commands, plan, out)?; - push_launch(commands, Launch::Round((n * 128) as u32), vec![A::Address(plan.raw), A::I64((n * 128) as i64)])?; + push_launch( + commands, + &plan.serving, + Launch::Round((n * 128) as u32), + vec![A::Address(plan.raw), A::I64((n * 128) as i64)], + )?; push_scan(commands, plan, plan.raw, n * 128, 5) } diff --git a/crates/cuda-driver/src/qsa_prompt_kv.rs b/crates/cuda-driver/src/qsa_prompt_kv.rs index d2109ef6..5ee39f29 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv.rs @@ -3,12 +3,11 @@ use crate::qsa_prompt_attention_ffi::{Arg, Arguments, LaunchGeometry, Module}; use crate::qsa_prompt_host_ffi::MappedAllocation; use crate::qsa_prompt_resolver::{PoolAddresses, Resolver, SelectedRows}; -use crate::serving_context::geometry; use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine}; use std::rc::Rc; // The `pub const` sizes below are the frozen TRAINED-context (262144 cells) values and are kept for the -// public API; every internal use derives the size of the configured serving context from -// `serving_context::geometry()`, which equals these at the default (asserted in `leleka-context`). +// public API; every internal use derives the size of the serving context of its Context from +// `Context::serving_geometry()`, which equals these at the default (asserted in `leleka-context`). pub const QSA_PROMPT_MAX_CELLS: usize = 262144; /// Device bytes of one layer at the DEFAULT resident window (32768 cells); a configured `--kv-resident` /// window changes it (`QsaPromptKv::allocated_bytes` reports the actual owner). diff --git a/crates/cuda-driver/src/qsa_prompt_kv/device_kv.rs b/crates/cuda-driver/src/qsa_prompt_kv/device_kv.rs index 7b1a6fe0..22929cd7 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/device_kv.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/device_kv.rs @@ -15,7 +15,7 @@ impl<'ctx> QsaPromptKv<'ctx> { self.validate_snapshot(prior)?; stage.validate(self.context)?; workspace.validate_context(self.context)?; - Self::check_rows(prior, t, 8192)?; + self.check_rows(prior, t, 8192)?; let (kh, vh) = inputs.kv_spans(self.context)?; self.reject_original_spans((workspace, stage), (kh, vh), t * 512 * 4)?; let addresses = (kh.qwen_address(), vh.qwen_address(), t); diff --git a/crates/cuda-driver/src/qsa_prompt_kv/mapped_journal/original_qsa_mapped_journal.rs b/crates/cuda-driver/src/qsa_prompt_kv/mapped_journal/original_qsa_mapped_journal.rs index 978968f1..3d71d2b7 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/mapped_journal/original_qsa_mapped_journal.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/mapped_journal/original_qsa_mapped_journal.rs @@ -6,6 +6,7 @@ use super::{ OriginalQsaMappedJournal, OriginalQsaMappedPrefix, OriginalQsaResidentTransport, QSA_PROMPT_HOST_PAGE_BYTES, Rc, Result, checked, }; +use leleka_context::geometry::QsaGeometry; impl<'ctx> OriginalQsaMappedJournal<'ctx> { pub fn append_resident_decode( @@ -58,7 +59,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { stage.validate(self.owner.context)?; workspace.validate_context(self.owner.context)?; if !(1..=8192).contains(&t) - || prior.end.checked_add(t).is_none_or(|n| n > crate::serving_context::geometry().cells()) + || prior.end.checked_add(t).is_none_or(|n| n > self.owner.context.serving_geometry().cells()) { return Err(Error::InvalidQwenShape); } @@ -208,7 +209,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { } let _p = crate::host_profile::span("export.copy"); let m = self.owner.mapped.as_ref().ok_or(Error::ContextPoisoned)?; - let offsets = super::super::offsets()?; + let offsets = super::super::offsets(self.owner.context.serving_geometry())?; let mut at = 0; for (i, &page) in super::super::PAGE.iter().enumerate() { let n = pages * page; @@ -233,7 +234,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { pub fn export_pages_fast(&self, first_page: usize, pages: usize, out: &mut Vec) -> Result<()> { self.check_export(first_page, pages)?; let m = self.owner.mapped.as_ref().ok_or(Error::ContextPoisoned)?; - let offsets = super::super::offsets()?; + let offsets = super::super::offsets(self.owner.context.serving_geometry())?; let _p = crate::host_profile::span("export.copy_fast"); crate::exact_fill::fill_exact(out, pages * Self::HOST_PAGE_BYTES, |dst| { let mut rest = dst; @@ -252,8 +253,8 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { /// (as `QsaPromptKv::restore` does); with no span nothing is written and nothing is reset. The epoch does not /// change: prefixes minted before are fenced by the new coverage, exactly as after `rollback`. /// Every span is whole pages inside the serving context and below the new end. - fn check_import_spans(spans: &[(usize, &[u8])], end: usize) -> Result<()> { - let page_limit = crate::serving_context::geometry().pages(); + fn check_import_spans(geometry: QsaGeometry, spans: &[(usize, &[u8])], end: usize) -> Result<()> { + let page_limit = geometry.pages(); for (first, bytes) in spans { if bytes.is_empty() || bytes.len() % Self::HOST_PAGE_BYTES != 0 @@ -267,7 +268,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { } /// Writes the spans into the host image and resets the resolver; any failure marks the journal failed. fn write_import_spans(&mut self, w: &mut NativeBatchWorkspace<'ctx>, spans: &[(usize, &[u8])]) -> Result<()> { - let offsets = super::super::offsets()?; + let offsets = super::super::offsets(self.owner.context.serving_geometry())?; let m = self.owner.mapped.as_mut().ok_or(Error::ContextPoisoned)?; for (first, bytes) in spans { let pages = bytes.len() / Self::HOST_PAGE_BYTES; @@ -297,10 +298,11 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { ) -> Result { self.validate_context(self.owner.context)?; w.validate_context(self.owner.context)?; - if end > crate::serving_context::geometry().cells() { + let geometry = self.owner.context.serving_geometry(); + if end > geometry.cells() { return Err(Error::InvalidQwenShape); } - Self::check_import_spans(spans, end)?; + Self::check_import_spans(geometry, spans, end)?; // no CPU host write may race a stream use of the old cells self.owner.context.synchronize().map_err(|e| { self.failed = true; diff --git a/crates/cuda-driver/src/qsa_prompt_kv/mapped_journal/original_qsa_mapped_prefix/qsa_mapped_journal_arena.rs b/crates/cuda-driver/src/qsa_prompt_kv/mapped_journal/original_qsa_mapped_prefix/qsa_mapped_journal_arena.rs index 364b45fd..6f6f6818 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/mapped_journal/original_qsa_mapped_prefix/qsa_mapped_journal_arena.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/mapped_journal/original_qsa_mapped_prefix/qsa_mapped_journal_arena.rs @@ -72,7 +72,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { prior_end: usize, ) -> Result<()> { for (i, h) in stage_spans.iter().enumerate() { - self.owner.reject_original_span(*h, stage_runs()?[i])?; + self.owner.reject_original_span(*h, stage_runs(self.owner.context.serving_geometry())?[i])?; } let timed = crate::command_profile::enabled(); let started = std::time::Instant::now(); diff --git a/crates/cuda-driver/src/qsa_prompt_kv/mapped_journal/original_qsa_mapped_prefix/qsa_mapped_journal_prefix_lineage.rs b/crates/cuda-driver/src/qsa_prompt_kv/mapped_journal/original_qsa_mapped_prefix/qsa_mapped_journal_prefix_lineage.rs index 9041c681..f21d9361 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/mapped_journal/original_qsa_mapped_prefix/qsa_mapped_journal_prefix_lineage.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/mapped_journal/original_qsa_mapped_prefix/qsa_mapped_journal_prefix_lineage.rs @@ -14,8 +14,8 @@ impl OriginalQsaMappedPrefix { pub fn owner_id(&self) -> QsaKvOwnerId { self.origin.clone() } - pub fn validate_retained(&self) -> Result<()> { - if self.end > crate::serving_context::geometry().cells() || self.end > self.coverage.end.get() { + pub fn validate_retained(&self, context: &Context<'_>) -> Result<()> { + if self.end > context.serving_geometry().cells() || self.end > self.coverage.end.get() { return Err(Error::InvalidQwenShape); } Ok(()) @@ -112,7 +112,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { || p.epoch != self.epoch || p.end > p.coverage.end.get() || p.end > self.end - || p.end > crate::serving_context::geometry().cells() + || p.end > self.owner.context.serving_geometry().cells() { return Err(Error::InvalidQwenShape); } @@ -170,7 +170,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { pub(crate) fn publish_window_rows(&mut self, position: usize, keep: usize) -> Result<()> { self.validate_context(self.owner.context)?; let end = position.checked_add(keep).ok_or(Error::InvalidSize)?; - if keep == 0 || self.end != position || end > crate::serving_context::geometry().cells() { + if keep == 0 || self.end != position || end > self.owner.context.serving_geometry().cells() { return Err(Error::InvalidQwenShape); } self.end = end; @@ -214,9 +214,10 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { return Ok(()); } self.check_prefetch(workspace, stage, prior, read)?; - let stage_spans = crate::qsa_prompt_index::kv_stage_spans_of(read, read.rows())?; + let geometry = self.owner.context.serving_geometry(); + let stage_spans = crate::qsa_prompt_index::kv_stage_spans_of(geometry, read, read.rows())?; for (i, h) in stage_spans.iter().enumerate() { - self.owner.reject_original_span(*h, stage_runs()?[i])?; + self.owner.reject_original_span(*h, stage_runs(geometry)?[i])?; } let hp = self.owner.host_addresses()?; stage.begin_prefix(workspace, hp, stage_spans, prior.end.div_ceil(4)) diff --git a/crates/cuda-driver/src/qsa_prompt_kv/offsets.rs b/crates/cuda-driver/src/qsa_prompt_kv/offsets.rs index 3f594c39..129e4423 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/offsets.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/offsets.rs @@ -3,16 +3,17 @@ use super::{ CompletedQsaKvAppend, Context, DeviceBuffer, Error, Origin, Page, Pools, QSA_PROMPT_HOST_PAGE_BYTES, QsaKvInputs, - QsaKvOwnerId, QsaKvSnapshot, QsaPromptKv, QsaPromptStage, RESERVE, Rc, Result, Snapshot, combine, geometry, + QsaKvOwnerId, QsaKvSnapshot, QsaPromptKv, QsaPromptStage, RESERVE, Rc, Result, Snapshot, combine, }; +use leleka_context::geometry::QsaGeometry; -/// Run offsets inside the mapped allocation for the configured context. -pub(super) fn offsets() -> Result<[usize; 4]> { - geometry().stage_offsets().map_err(|_| Error::InvalidSize) +/// Run offsets inside the mapped allocation for the serving context of `geometry`. +pub(super) fn offsets(geometry: QsaGeometry) -> Result<[usize; 4]> { + geometry.stage_offsets().map_err(|_| Error::InvalidSize) } -/// Run lengths of the full staging pool for the configured context. -pub(super) fn stage_runs() -> Result<[usize; 4]> { - geometry().stage_runs().map_err(|_| Error::InvalidSize) +/// Run lengths of the full staging pool for the serving context of `geometry`. +pub(super) fn stage_runs(geometry: QsaGeometry) -> Result<[usize; 4]> { + geometry.stage_runs().map_err(|_| Error::InvalidSize) } /// The four resident runs of `slots` resident pages (`[16777216, 16777216, 524288, 524288]` at 8192). pub(super) fn resident_runs(slots: usize) -> Result<[usize; 4]> { @@ -55,7 +56,7 @@ impl QsaKvSnapshot { /// Diagnostic comparison of actual encoded logical cells. Completed batch /// snapshots may retain future backing; it is excluded from causal equality. pub fn logical_payload_eq(&self, other: &Self) -> bool { - if self.0.end != other.0.end || self.0.end > geometry().cells() { + if self.0.end != other.0.end { return false; } let pages = self.0.end.div_ceil(4); @@ -109,7 +110,7 @@ impl<'ctx> Pools<'ctx> { for (i, n) in sizes.into_iter().enumerate() { self.buffers[i] = Some(c.allocate(n)?); } - self.table = Some(c.allocate(geometry().page_table_bytes())?); + self.table = Some(c.allocate(c.serving_geometry().page_table_bytes())?); Ok(()) } pub(super) fn addresses(&self) -> Result<[u64; 4]> { @@ -126,7 +127,7 @@ impl<'ctx> Pools<'ctx> { for (b, n) in self.buffers.iter().zip(sizes) { checked(c, b.as_ref().ok_or(Error::ContextPoisoned)?, n)?; } - checked(c, self.table.as_ref().ok_or(Error::ContextPoisoned)?, geometry().page_table_bytes())?; + checked(c, self.table.as_ref().ok_or(Error::ContextPoisoned)?, c.serving_geometry().page_table_bytes())?; Ok(()) } pub(super) fn close(&mut self) -> Result<()> { diff --git a/crates/cuda-driver/src/qsa_prompt_kv/qsa_prompt_kv_drop.rs b/crates/cuda-driver/src/qsa_prompt_kv/qsa_prompt_kv_drop.rs index 1b78aa19..184d4e32 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/qsa_prompt_kv_drop.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/qsa_prompt_kv_drop.rs @@ -3,8 +3,7 @@ use super::{ Arguments, Context, DeviceBuffer, Error, LaunchGeometry, NativeBatchWorkspace, PAGE, Pools, QsaKvSnapshot, - QsaPromptKv, QsaPromptStage, RESERVE, Rc, Result, Snapshot, admit, bytes_i32, checked, combine, geometry, - stage_runs, + QsaPromptKv, QsaPromptStage, RESERVE, Rc, Result, Snapshot, admit, bytes_i32, checked, combine, stage_runs, }; impl Drop for QsaPromptKv<'_> { @@ -14,7 +13,7 @@ impl Drop for QsaPromptKv<'_> { } impl<'ctx> QsaPromptStage<'ctx> { pub(super) fn new(c: &'ctx Context<'ctx>) -> Result { - admit(c, geometry().stage_bytes().map_err(|_| Error::BudgetExceeded)?)?; + admit(c, c.serving_geometry().stage_bytes().map_err(|_| Error::BudgetExceeded)?)?; let ptx = include_bytes!("../qsa_prompt_kv.ptx"); let entries = &[c"leleka_qsa_kv_guard", c"leleka_qsa_kv_append", c"leleka_qsa_kv_scale_guard"]; let module = crate::qsa_prompt_attention_ffi::load_in_context(c, ptx, entries)?; @@ -34,13 +33,13 @@ impl<'ctx> QsaPromptStage<'ctx> { /// The pools, the status word and the identity page table; the reserve of device memory must stay free. fn allocate_all(&mut self) -> Result<()> { let c = self.context; - self.pools.allocate(c, stage_runs()?)?; + self.pools.allocate(c, stage_runs(c.serving_geometry())?)?; self.status = Some(c.allocate(4)?); self.pools .table .as_mut() .ok_or(Error::ContextPoisoned)? - .copy_from(&bytes_i32((0..geometry().pages()).map(|x| x as i32))?)?; + .copy_from(&bytes_i32((0..c.serving_geometry().pages()).map(|x| x as i32))?)?; if c.memory_info()?.0 < RESERVE { return Err(Error::BudgetExceeded); } @@ -59,7 +58,7 @@ impl<'ctx> QsaPromptStage<'ctx> { if self.is_failed() || self.module.is_none() { return Err(Error::ContextPoisoned); } - self.pools.validate(c, stage_runs()?)?; + self.pools.validate(c, stage_runs(c.serving_geometry())?)?; checked(c, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; Ok(()) } @@ -78,8 +77,8 @@ impl<'ctx> QsaPromptStage<'ctx> { self.validate(self.context)?; owner.validate_context(self.context)?; owner.validate_snapshot(s)?; - if s.0.end > geometry().cells() || s.0.pages.len() < s.0.end.div_ceil(4) || s.0.pages.len() > geometry().pages() - { + let geometry = self.context.serving_geometry(); + if s.0.end > geometry.cells() || s.0.pages.len() < s.0.end.div_ceil(4) || s.0.pages.len() > geometry.pages() { return Err(Error::InvalidQwenShape); } Ok(()) diff --git a/crates/cuda-driver/src/qsa_prompt_kv/resident_transport.rs b/crates/cuda-driver/src/qsa_prompt_kv/resident_transport.rs index 6ee89edc..9115cd2b 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/resident_transport.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/resident_transport.rs @@ -4,6 +4,7 @@ use super::{ Arguments, Context, DeviceBuffer, Error, LaunchGeometry, Module, NativeBatchWorkspace, RESERVE, Result, admit, bytes_i32, checked, combine, }; +use leleka_context::geometry::QsaGeometry; pub struct OriginalQsaResidentTransport<'ctx> { context: &'ctx Context<'ctx>, table: Option>, @@ -19,11 +20,11 @@ impl<'ctx> Context<'ctx> { } } impl<'ctx> OriginalQsaResidentTransport<'ctx> { - pub fn device_bytes() -> usize { - crate::serving_context::geometry().page_table_bytes() + 4 + pub fn device_bytes(geometry: QsaGeometry) -> usize { + geometry.page_table_bytes() + 4 } fn new(context: &'ctx Context<'ctx>) -> Result { - admit(context, Self::device_bytes())?; + admit(context, Self::device_bytes(context.serving_geometry()))?; let mut s = Self { context, table: None, status: None, module: None, transfer: None, failed: false, prefix: None }; if let Err(e) = s.init() { @@ -57,8 +58,9 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> { Ok(()) } fn init_table(&mut self) -> Result<()> { - let mut table = self.context.allocate(crate::serving_context::geometry().page_table_bytes())?; - table.copy_from(&bytes_i32((0..crate::serving_context::geometry().pages()).map(|p| p as i32))?)?; + let geometry = self.context.serving_geometry(); + let mut table = self.context.allocate(geometry.page_table_bytes())?; + table.copy_from(&bytes_i32((0..geometry.pages()).map(|p| p as i32))?)?; self.table = Some(table); self.status = Some(self.context.allocate(4)?); Ok(()) @@ -76,11 +78,7 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> { if self.is_failed() || self.module.is_none() { return Err(Error::ContextPoisoned); } - checked( - c, - self.table.as_ref().ok_or(Error::ContextPoisoned)?, - crate::serving_context::geometry().page_table_bytes(), - )?; + checked(c, self.table.as_ref().ok_or(Error::ContextPoisoned)?, c.serving_geometry().page_table_bytes())?; checked(c, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; Ok(()) } @@ -88,7 +86,7 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> { checked( self.context, self.table.as_ref().ok_or(Error::ContextPoisoned)?, - crate::serving_context::geometry().page_table_bytes(), + self.context.serving_geometry().page_table_bytes(), ) } pub(crate) fn status(&mut self) -> Result<&mut DeviceBuffer<'ctx>> { @@ -186,7 +184,7 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> { pages: usize, ) -> Result<()> { self.validate(self.context)?; - if pages > crate::serving_context::geometry().pages() { + if pages > self.context.serving_geometry().pages() { return Err(Error::InvalidQwenShape); } self.cancel_pending()?; @@ -226,7 +224,7 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> { pages: usize, ) -> Result<()> { self.validate(self.context)?; - if pages > crate::serving_context::geometry().pages() { + if pages > self.context.serving_geometry().pages() { return Err(Error::InvalidQwenShape); } if pages == 0 { diff --git a/crates/cuda-driver/src/qsa_prompt_kv/staged_append.rs b/crates/cuda-driver/src/qsa_prompt_kv/staged_append.rs index b592f85f..80f8e793 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/staged_append.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/staged_append.rs @@ -5,7 +5,7 @@ use super::{ Arg, Arguments, CompletedQsaKvAppend, Context, DeviceBuffer, Error, LaunchGeometry, MappedAllocation, NativeBatchWorkspace, Origin, PAGE, Page, PoolAddresses, Pools, QsaKvInputs, QsaKvOwnerId, QsaKvSnapshot, QsaPromptKv, QsaPromptStage, RESERVE, Rc, Resolver, Result, SelectedRows, Snapshot, admit, checked, combine, - geometry, offsets, read_range, resident_runs, stage_runs, + offsets, read_range, resident_runs, stage_runs, }; /// The stage one bounded append runs on and the snapshot it extends. diff --git a/crates/cuda-driver/src/qsa_prompt_kv/staged_append/append_phases.rs b/crates/cuda-driver/src/qsa_prompt_kv/staged_append/append_phases.rs index 1e2ed821..b915e43b 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/staged_append/append_phases.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/staged_append/append_phases.rs @@ -2,7 +2,7 @@ use super::{ Arg, Arguments, CompletedQsaKvAppend, DeviceBuffer, Error, LaunchGeometry, NativeBatchWorkspace, PAGE, Page, - QsaKvSnapshot, QsaPromptKv, QsaPromptStage, Rc, Result, Snapshot, checked, geometry, read_range, + QsaKvSnapshot, QsaPromptKv, QsaPromptStage, Rc, Result, Snapshot, checked, read_range, }; type Completed = Vec>>; @@ -83,8 +83,9 @@ fn install_pages(pages: &mut Vec>, completed: Completed, first: usize, impl<'ctx> QsaPromptKv<'ctx> { /// 1..=limit rows, ending within the context's cell count. - pub(in crate::qsa_prompt_kv) fn check_rows(prior: &QsaKvSnapshot, t: usize, limit: usize) -> Result<()> { - if !(1..=limit).contains(&t) || prior.0.end.checked_add(t).is_none_or(|n| n > geometry().cells()) { + pub(in crate::qsa_prompt_kv) fn check_rows(&self, prior: &QsaKvSnapshot, t: usize, limit: usize) -> Result<()> { + let cells = self.context.serving_geometry().cells(); + if !(1..=limit).contains(&t) || prior.0.end.checked_add(t).is_none_or(|n| n > cells) { return Err(Error::InvalidQwenShape); } Ok(()) @@ -98,7 +99,7 @@ impl<'ctx> QsaPromptKv<'ctx> { (keys, values, t): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, usize), limit: usize, ) -> Result<(u64, u64)> { - Self::check_rows(prior, t, limit)?; + self.check_rows(prior, t, limit)?; let k = checked(self.context, keys, t * 512 * 4)?; let v = checked(self.context, values, t * 512 * 4)?; let (kh, vh) = (keys.handle.ok_or(Error::ContextPoisoned)?, values.handle.ok_or(Error::ContextPoisoned)?); diff --git a/crates/cuda-driver/src/qsa_prompt_kv/staged_append/qsa_prompt_kv_bring_up.rs b/crates/cuda-driver/src/qsa_prompt_kv/staged_append/qsa_prompt_kv_bring_up.rs index 0873a244..2385f61c 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/staged_append/qsa_prompt_kv_bring_up.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/staged_append/qsa_prompt_kv_bring_up.rs @@ -4,16 +4,18 @@ use super::{ CompletedQsaKvAppend, Context, DeviceBuffer, Error, MappedAllocation, NativeBatchWorkspace, Origin, PAGE, PoolAddresses, Pools, QsaKvInputs, QsaKvOwnerId, QsaKvSnapshot, QsaPromptKv, QsaPromptStage, RESERVE, Rc, Resolver, - Result, SelectedRows, Snapshot, StagedAppend, admit, checked, combine, geometry, offsets, resident_runs, - stage_runs, + Result, SelectedRows, Snapshot, StagedAppend, admit, checked, combine, offsets, resident_runs, stage_runs, }; +use leleka_context::geometry::QsaGeometry; impl<'ctx> QsaPromptKv<'ctx> { pub(in super::super) fn new(c: &'ctx Context<'ctx>) -> Result { let slots = c.kv_resident_pages()?; admit( c, - geometry().resident_bytes_with(slots, Resolver::map_bytes(slots)?).map_err(|_| Error::BudgetExceeded)?, + c.serving_geometry() + .resident_bytes_with(slots, Resolver::map_bytes(slots)?) + .map_err(|_| Error::BudgetExceeded)?, )?; let mut o = Self { context: c, @@ -36,7 +38,7 @@ impl<'ctx> QsaPromptKv<'ctx> { fn init_resources(&mut self, slots: usize) -> Result<()> { let c = self.context; self.resolver = Some(Resolver::new(c, slots)?); - check_host_memory()?; + check_host_memory(c.serving_geometry())?; self.map_host()?; self.pools.allocate(c, resident_runs(slots)?)?; if c.memory_info()?.0 < RESERVE { @@ -48,7 +50,7 @@ impl<'ctx> QsaPromptKv<'ctx> { fn map_host(&mut self) -> Result<()> { let c = self.context; let g = c.enter()?; - let mapped = MappedAllocation::new(); + let mapped = MappedAllocation::new(c.serving_geometry()); let pop = g.finish(); match mapped { Ok(m) => { @@ -106,10 +108,11 @@ impl<'ctx> QsaPromptKv<'ctx> { } pub fn validate_snapshot(&self, s: &QsaKvSnapshot) -> Result<()> { self.validate()?; + let geometry = self.context.serving_geometry(); if !Rc::ptr_eq(&s.0.origin, &self.origin) - || s.0.end > geometry().cells() + || s.0.end > geometry.cells() || s.0.pages.len() < s.0.end.div_ceil(4) - || s.0.pages.len() > geometry().pages() + || s.0.pages.len() > geometry.pages() { return Err(Error::InvalidQwenShape); } @@ -124,7 +127,8 @@ impl<'ctx> QsaPromptKv<'ctx> { } pub(in super::super) fn host_addresses(&self) -> Result<[u64; 4]> { let m = self.mapped.as_ref().ok_or(Error::ContextPoisoned)?; - let (offsets, runs) = (offsets()?, stage_runs()?); + let geometry = self.context.serving_geometry(); + let (offsets, runs) = (offsets(geometry)?, stage_runs(geometry)?); Ok([ m.address(offsets[0], runs[0])?, m.address(offsets[1], runs[1])?, @@ -135,7 +139,7 @@ impl<'ctx> QsaPromptKv<'ctx> { /// Writes the pages of `s` that `previous` (the snapshot last written) does not already hold into the mapped host. fn write_pages(&mut self, previous: Option<&Rc>, s: &QsaKvSnapshot) -> Result<()> { let m = self.mapped.as_mut().ok_or(Error::ContextPoisoned)?; - let offsets = offsets()?; + let offsets = offsets(self.context.serving_geometry())?; for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { if previous.is_some_and(|old| { Rc::ptr_eq(&old.origin, &s.0.origin) @@ -240,7 +244,7 @@ impl<'ctx> QsaPromptKv<'ctx> { } /// The mapped host area plus 8 GiB of headroom must fit the available system memory. -fn check_host_memory() -> Result<()> { +fn check_host_memory(geometry: QsaGeometry) -> Result<()> { #[cfg(windows)] let available = libc::physical_memory() .and_then(|(_, available)| usize::try_from(available).ok()) @@ -253,7 +257,7 @@ fn check_host_memory() -> Result<()> { .find_map(|line| line.strip_prefix("MemAvailable:")?.split_whitespace().next()?.parse::().ok()) .and_then(|n| n.checked_mul(1024)) .ok_or(Error::HostAllocation)?; - let mapped_host = geometry().mapped_host_bytes().map_err(|_| Error::HostAllocation)?; + let mapped_host = geometry.mapped_host_bytes().map_err(|_| Error::HostAllocation)?; if available < mapped_host + 8 * 1024 * 1024 * 1024 { return Err(Error::HostAllocation); } diff --git a/crates/cuda-driver/src/qsa_prompt_resolver.rs b/crates/cuda-driver/src/qsa_prompt_resolver.rs index 6e96b366..fa081673 100644 --- a/crates/cuda-driver/src/qsa_prompt_resolver.rs +++ b/crates/cuda-driver/src/qsa_prompt_resolver.rs @@ -188,7 +188,7 @@ impl<'ctx> Resolver<'ctx> { } pub(crate) fn reset(&mut self, w: &mut NativeBatchWorkspace<'ctx>, table: u64) -> Result<()> { let mut values = self.addresses(table)?; - let pages = crate::serving_context::geometry().pages(); + let pages = self.context.serving_geometry().pages(); values.push(Arg::I64(pages as i64)); values.push(Arg::I64(self.n_slots as i64)); let a = Arguments::new(values)?; diff --git a/crates/cuda-driver/src/qwen_dispatch/context/qsa_fixed_kernels.rs b/crates/cuda-driver/src/qwen_dispatch/context/qsa_fixed_kernels.rs index 64b2eb65..e8008c0a 100644 --- a/crates/cuda-driver/src/qwen_dispatch/context/qsa_fixed_kernels.rs +++ b/crates/cuda-driver/src/qwen_dispatch/context/qsa_fixed_kernels.rs @@ -58,7 +58,7 @@ impl Context<'_> { if matches!( operation, Operation::QsaRopeQ | Operation::QsaRopeK | Operation::QsaRopeIndexQ | Operation::QsaIndexAppend - ) && crate::serving_context::serving_context().rope_is_scaled() + ) && self.serving().rope_is_scaled() { return Err(Error::UnsupportedQwenOperation); } diff --git a/crates/cuda-model/src/serving_context.rs b/crates/cuda-model/src/serving_context.rs index 5b11f744..f043e18e 100644 --- a/crates/cuda-model/src/serving_context.rs +++ b/crates/cuda-model/src/serving_context.rs @@ -67,17 +67,20 @@ pub fn serving_context() -> ServingContext { SERVING.get().copied().unwrap_or_else(ServingContext::trained) } -/// The geometry every context-linear size is derived from. -#[inline] -pub fn geometry() -> QsaGeometry { - serving_context().geometry -} - /// The resident KV window (cells per QSA layer kept in VRAM, `--kv-resident`) of the default configuration. pub const KV_RESIDENT_DEFAULT_CELLS: usize = leleka_context::geometry::KV_RESIDENT_DEFAULT_CELLS; /// `qsa_kv_resident_min()`. pub const KV_RESIDENT_MIN_CELLS: usize = leleka_context::geometry::KV_RESIDENT_MIN_CELLS; +impl ServingContext { + /// Resident pages (VRAM slots) a streamed QSA owner allocates for a window of `cells` (`--kv-resident N`, the + /// Original's `qsa_set_kv_resident`). `0` keeps the whole context resident; a positive count is raised to + /// `qsa_kv_resident_min()` (20480) and rounded up to whole pages. + pub fn resident_pages_for(&self, cells: usize) -> Result { + self.geometry.resident_pages_for(cells).map_err(|_| Error::InvalidDriverValue("resident KV window")) + } +} + #[cfg(test)] mod tests { use super::*; @@ -93,8 +96,8 @@ mod tests { #[test] fn the_default_resident_window_is_the_frozen_8192_page_pool() { assert_eq!(KV_RESIDENT_DEFAULT_CELLS, 32_768); - assert!(geometry().resident_pages_for(KV_RESIDENT_DEFAULT_CELLS) == Ok(8192)); - assert!(geometry().resident_pages_for(MAX_CONTEXT_CELLS + 4).is_err()); + assert!(ServingContext::trained().geometry.resident_pages_for(KV_RESIDENT_DEFAULT_CELLS) == Ok(8192)); + assert!(ServingContext::trained().resident_pages_for(MAX_CONTEXT_CELLS + 4).is_err()); } /// Wherever the Original streams a layer (`kv_plan` mode 1, golden-tested in `leleka-experimental-ref`)