diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index b06179af..fc7f4254 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -60,6 +60,10 @@ mod original_mtp_actor; mod original_mtp_coupled; mod original_mtp_loader; mod original_session_state; +pub use original_session_state::{ + OriginalGeometryFacts, OriginalHostKv, OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, + OriginalRegion, OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts, +}; mod qwen_dispatch; pub use qwen_dispatch::gr_batch_read::{GrMicroValues, GrMicrobatchRead}; mod qsa_selected_kv; @@ -2088,6 +2092,13 @@ impl DeviceBuffer<'_> { /// Copy a nonempty checked subspan. Owned staging remains alive through /// synchronization, with the same poisoning/leak rule as whole-buffer copies. pub fn copy_from_range(&mut self, offset: usize, input: &[u8]) -> Result<()> { + self.copy_from_range_shared(offset, input) + } + /// The same transfer through a shared borrow, for arenas their single + /// owner thread shares between read-only views (`Rc`). + /// Ranges are checked and the copy is synchronised exactly like + /// `copy_from_range`; callers keep writes to disjoint spans. + pub(crate) fn copy_from_range_shared(&self, offset: usize, input: &[u8]) -> Result<()> { if self.context.poisoned.get() { return Err(Error::ContextPoisoned); } @@ -2111,6 +2122,35 @@ impl DeviceBuffer<'_> { } combine(copy, guard.finish()) } + /// Read back a nonempty checked subspan. Owned staging stays alive through + /// synchronization with the same poisoning/leak rule as whole-buffer reads; + /// a failed synchronization never returns its bytes. + pub fn copy_to_range(&self, offset: usize, output: &mut [u8]) -> Result<()> { + if self.context.poisoned.get() { + return Err(Error::ContextPoisoned); + } + let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan( + self.bytes, + offset, + output.len(), + )?; + let mut staging = Vec::new(); + staging + .try_reserve_exact(output.len()) + .map_err(|_| Error::HostAllocation)?; + staging.resize(output.len(), 0); + let guard = self.context.enter()?; + let copy = self.context.driver.api.copy_to(handle, &mut staging); + let sync = self.context.driver.api.synchronize(); + if sync.is_err() { + self.context.poisoned.set(true); + std::mem::forget(staging); + return combine(combine(copy, sync), guard.finish()); + } + combine(copy, guard.finish())?; + output.copy_from_slice(&staging); + Ok(()) + } pub fn copy_to(&self, output: &mut [u8]) -> Result<()> { let staging = self.staging(output.len())?; let staging = self.copy_staged(staging, true)?; diff --git a/crates/cuda-driver/src/original_conversation_state.rs b/crates/cuda-driver/src/original_conversation_state.rs new file mode 100644 index 00000000..85feca8d --- /dev/null +++ b/crates/cuda-driver/src/original_conversation_state.rs @@ -0,0 +1,424 @@ +//! Source-level binding of conversation snapshots (`core/conversation_*.cpp`) +//! to the Original session owners: the carved session arena of +//! `original_session_state.rs` (GDN recurrence, PLE history, QSA indexer state, +//! resident K/V pools), the authoritative mapped-host K/V of streamed layers +//! and the MTP drafter's ring. +//! +//! It owns no policy. The runtime's `conversation` module decides what to +//! park and restore; this module only answers "where are these bytes" and +//! moves them, in the same region vocabulary the runtime's `StateMemory` uses. +//! Everything that lives in the session arena is read and written here through +//! checked sub-spans; everything that lives in mapped host memory is delegated +//! to [`OriginalHostKv`], implemented by the owner of that memory (it holds the +//! `MappedHost` handles returned by `initialize_qsa`). +//! +//! No state is acknowledged from metadata: a region is only readable or +//! writable through the actual arena or the actual host owner. + +use super::{OriginalSessionLayout, OriginalSessionQsaLayout, OriginalSessionSpan, OriginalSessionState}; +use crate::{Context, Error, Result}; + +// ---- plain data and traits: no CUDA types below until `OriginalSessionLayout` (begin) + +/// A K/V payload of one layer, in `ConversationKv` order. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum OriginalKvPool { + K, + V, + KScale, + VScale, + Pooled, +} + +/// Per-owned-layer indexer running state. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum OriginalIdxKind { + Tail, + Dead, + BlockPos, +} + +/// A layer whose K/V a snapshot moves: the `n`-th QSA state this session +/// owns, or the MTP drafter's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum OriginalKvLayer { + Owned(usize), + Draft, +} + +/// A byte range of session state. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum OriginalRegion { + /// Every owned GDN layer's recurrence then convolution history. + Gdn, + /// The PLE history window. + PleHist, + Idx { owned: usize, kind: OriginalIdxKind }, + /// `resident` selects the VRAM slots over the authoritative copy. + Kv { layer: OriginalKvLayer, pool: OriginalKvPool, resident: bool }, +} + +/// The model geometry fields the session layout knows. `ssm_k_heads` is not +/// part of the layout; the pinned model has 16. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct OriginalGeometryFacts { + pub n_embd: usize, + pub n_layers: usize, + pub qsa_interval: usize, + pub state_size: usize, + pub value_heads: usize, + pub conv_width: usize, + pub conv_channels: usize, + pub value_dim: usize, + pub heads: usize, + pub kv_heads: usize, + pub head_dim: usize, + pub index_heads: usize, + pub index_dim: usize, + pub hc: usize, + pub hc_lr: usize, + pub experts: usize, + pub n_ff: usize, +} + +/// What snapshot validation needs to know about one QSA state. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OriginalQsaFacts { + pub ordinal: usize, + /// 0 resident, 1 streamed (authoritative copy in mapped host memory), + /// 2 ring. + pub mode: u8, + pub pages: usize, + pub slots: usize, + pub pooled_rows: usize, + pub kv_int8: bool, + pub kv_q4: bool, + pub kv_hybrid: bool, + pub kv_rotate: bool, + pub without_key: bool, + /// Names of the carved regions this state owns (`k_pool`, `idx_tail`, ...). + pub regions: Vec<&'static str>, + /// Bytes of the authoritative mapped host copy (0 when resident). + pub host_kv_bytes: usize, +} + +impl OriginalQsaFacts { + pub fn has(&self, name: &str) -> bool { + self.regions.contains(&name) + } +} + +/// The session fields conversation snapshots read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OriginalSessionFacts { + pub geometry: OriginalGeometryFacts, + pub max_cells: usize, + pub layer_lo: usize, + pub layer_hi: usize, + pub qsa_ord0: usize, + pub qsa_alloc: usize, + pub gdn_alloc: usize, + pub gdn_state_bytes: usize, + pub ple_hist_bytes: usize, + /// The owned QSA states, in ordinal order (`qsa_ord0 .. qsa_ord0 + qsa_alloc`). + pub qsa: Vec, +} + +/// Authoritative mapped-host K/V and the drafter ring: memory the session +/// arena does not contain. Implemented by the owner of those allocations. +pub trait OriginalHostKv { + fn read(&mut self, layer: OriginalKvLayer, pool: OriginalKvPool, resident: bool, offset: usize, dst: &mut [u8]) -> Result<()>; + fn write(&mut self, layer: OriginalKvLayer, pool: OriginalKvPool, resident: bool, offset: usize, src: &[u8]) -> Result<()>; + /// `kv_stream_reset` on a streamed layer's device map. + fn reset_stream_map(&mut self, owned: usize) -> Result<()>; + /// `kv_ring_restore` of host blocks `[begin, end)` into a ring's slots. + fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, begin: i64, end: i64, slots: i64) -> Result<()>; +} + +/// Byte access to one session's state, in the runtime's vocabulary. +pub trait OriginalSessionBytes { + fn read(&mut self, region: OriginalRegion, offset: usize, dst: &mut [u8]) -> Result<()>; + fn write(&mut self, region: OriginalRegion, offset: usize, src: &[u8]) -> Result<()>; + fn synchronize(&mut self) -> Result<()>; + fn set_ple_prev(&mut self, prev: [i32; 2]); + fn reset_stream_map(&mut self, owned: usize) -> Result<()>; + fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, begin: i64, end: i64, slots: i64) -> Result<()>; +} + +/// Session lifecycle operations beyond raw bytes, supplied by the serving owner. +pub trait OriginalSessionControl { + /// `session_zero` plus stream synchronisation. + fn zero_session(&mut self) -> Result<()>; + /// `mtp.kv_restore(resume)`. + fn restore_draft(&mut self, resume: usize) -> Result<()>; + /// `cvec_set_enabled`. + fn set_steering(&mut self, enabled: bool); +} + +// ---- plain data and traits (end) + +fn region_name(q: &OriginalSessionQsaLayout, pool: OriginalKvPool) -> Option<&'static str> { + use OriginalKvPool::*; + Some(match pool { + Pooled => "idx_pooled", + K if q.kv_hybrid || (q.kv_int8 && !q.kv_q4) => "k_q", + K if q.kv_q4 => "k_q4", + K => "k_pool", + V if q.kv_hybrid || q.kv_q4 => "v_q4", + V if q.kv_int8 => "v_q", + V => "v_pool", + KScale if q.kv_hybrid || q.kv_int8 => "k_scale", + VScale if q.kv_int8 && !q.kv_hybrid && !q.kv_q4 => "v_scale", + KScale | VScale => return None, + }) +} + +impl OriginalSessionLayout { + /// Facts for snapshot validation. Pure: reads the layout only. + pub(crate) fn conversation_facts(&self) -> OriginalSessionFacts { + let g = self.geometry; + let qsa = (0..self.qsa_alloc) + .filter_map(|j| self.qsa.get(self.qsa_ord0 + j).and_then(Option::as_ref)) + .map(|q| OriginalQsaFacts { + ordinal: q.ordinal, + mode: q.mode, + pages: q.pages, + slots: q.slots, + pooled_rows: q.pooled_rows, + kv_int8: q.kv_int8, + kv_q4: q.kv_q4, + kv_hybrid: q.kv_hybrid, + kv_rotate: q.kv_rotate, + without_key: self.policy.without_key && q.kv_int8, + regions: q.regions.iter().map(|(name, _)| *name).collect(), + host_kv_bytes: q.host_kv_bytes, + }) + .collect(); + OriginalSessionFacts { + geometry: OriginalGeometryFacts { + n_embd: g.n_embd, + n_layers: g.n_layers, + qsa_interval: g.qsa_interval, + state_size: g.state_size, + value_heads: g.value_heads, + conv_width: g.conv_width, + conv_channels: g.conv_channels, + value_dim: g.value_dim, + heads: g.heads, + kv_heads: g.kv_heads, + head_dim: g.head_dim, + index_heads: g.index_heads, + index_dim: g.index_dim, + hc: g.hc, + hc_lr: g.hc_lr, + experts: g.experts, + n_ff: g.n_ff, + }, + max_cells: self.max_cells, + layer_lo: self.layer_lo, + layer_hi: self.layer_hi, + qsa_ord0: self.qsa_ord0, + qsa_alloc: self.qsa_alloc, + gdn_alloc: self.gdn_alloc, + gdn_state_bytes: self.gdn_state.bytes, + ple_hist_bytes: self.ple_hist.bytes, + qsa, + } + } + + /// The arena span of a region, or `None` when the bytes live outside the + /// arena (the authoritative host copy of a streamed layer, the drafter). + pub(crate) fn conversation_span(&self, region: OriginalRegion) -> Result> { + match region { + OriginalRegion::Gdn => Ok(Some(self.gdn_state)), + OriginalRegion::PleHist => Ok(Some(self.ple_hist)), + OriginalRegion::Idx { owned, kind } => { + let q = self.owned_qsa(owned)?; + let name = match kind { + OriginalIdxKind::Tail => "idx_tail", + OriginalIdxKind::Dead => "idx_dead", + OriginalIdxKind::BlockPos => "idx_block_pos", + }; + q.span(name).map(Some) + } + OriginalRegion::Kv { layer: OriginalKvLayer::Draft, .. } => Ok(None), + OriginalRegion::Kv { layer: OriginalKvLayer::Owned(owned), pool, resident } => { + let q = self.owned_qsa(owned)?; + // A streamed layer's authoritative K/V lives in mapped host + // memory; its arena pools are the replaceable VRAM slots. + if q.mode != 0 && pool != OriginalKvPool::Pooled && !resident { + return Ok(None); + } + let name = region_name(q, pool).ok_or(Error::InvalidQwenShape)?; + q.span(name).map(Some) + } + } + } + + fn owned_qsa(&self, owned: usize) -> Result<&OriginalSessionQsaLayout> { + if owned >= self.qsa_alloc { + return Err(Error::InvalidQwenShape); + } + let ordinal = self.qsa_ord0.checked_add(owned).ok_or(Error::InvalidSize)?; + self.qsa.get(ordinal).and_then(Option::as_ref).ok_or(Error::InvalidQwenShape) + } +} + +/// Session arena plus host owner, as one [`OriginalSessionBytes`]. +pub(crate) struct OriginalConversationAccess<'a, 'ctx, H: OriginalHostKv> { + pub(crate) state: &'a mut OriginalSessionState<'ctx>, + pub(crate) context: &'a Context<'ctx>, + pub(crate) host: &'a mut H, +} + +fn checked_range(span: OriginalSessionSpan, offset: usize, len: usize) -> Result { + let end = offset.checked_add(len).ok_or(Error::InvalidSize)?; + if len == 0 || end > span.bytes { + return Err(Error::InvalidSize); + } + span.offset.checked_add(offset).ok_or(Error::InvalidSize) +} + +impl OriginalSessionBytes for OriginalConversationAccess<'_, '_, H> { + fn read(&mut self, region: OriginalRegion, offset: usize, dst: &mut [u8]) -> Result<()> { + if dst.is_empty() { + return Ok(()); + } + let span = self.state.with_carved_arena(self.context, |_, layout| layout.conversation_span(region))?; + match span { + Some(span) => { + let at = checked_range(span, offset, dst.len())?; + self.state.with_carved_arena(self.context, |arena, _| arena.copy_to_range(at, dst)) + } + None => match region { + OriginalRegion::Kv { layer, pool, resident } => self.host.read(layer, pool, resident, offset, dst), + _ => Err(Error::InvalidQwenShape), + }, + } + } + + fn write(&mut self, region: OriginalRegion, offset: usize, src: &[u8]) -> Result<()> { + if src.is_empty() { + return Ok(()); + } + let span = self.state.with_carved_arena(self.context, |_, layout| layout.conversation_span(region))?; + match span { + Some(span) => { + let at = checked_range(span, offset, src.len())?; + // `with_carved_arena` hands out a shared borrow of the arena; + // `copy_from_range` needs the exclusive one the owner keeps. + self.state.write_arena(self.context, at, src) + } + None => match region { + OriginalRegion::Kv { layer, pool, resident } => self.host.write(layer, pool, resident, offset, src), + _ => Err(Error::InvalidQwenShape), + }, + } + } + + fn synchronize(&mut self) -> Result<()> { + self.state.validate_context(self.context)?; + self.context.synchronize() + } + + fn set_ple_prev(&mut self, prev: [i32; 2]) { + self.state.ple_prev = prev; + } + + fn reset_stream_map(&mut self, owned: usize) -> Result<()> { + self.state.validate_context(self.context)?; + self.host.reset_stream_map(owned) + } + + fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, begin: i64, end: i64, slots: i64) -> Result<()> { + self.state.validate_context(self.context)?; + self.host.restore_ring(layer, format, begin, end, slots) + } +} + +impl<'ctx> OriginalSessionState<'ctx> { + /// Exclusive arena write at an absolute arena offset. The arena is an + /// `Rc` the owner shares only with itself for reads, so the + /// write goes through a fresh exclusive handle check. + pub(crate) fn write_arena(&self, c: &Context<'_>, offset: usize, src: &[u8]) -> Result<()> { + self.validate_context(c)?; + self.arena.as_ref().ok_or(Error::ContextPoisoned)?.copy_from_range_shared(offset, src) + } +} + +#[cfg(test)] +mod tests { + use super::super::{OriginalSessionGeometry, OriginalSessionKvPolicy, OriginalSessionLayout}; + use super::*; + + fn policy() -> OriginalSessionKvPolicy { + OriginalSessionKvPolicy { + resident_cells: 0, + main_off: false, + ring_off: false, + ring_cells: 0, + without_key: false, + int8: true, + int8_rotate: false, + q4: false, + hybrid: false, + } + } + + // The Original geometry's running-state sizes, pinned against the + // compiled C++ `conversation_state_sizes` (golden/state_golden.json: + // whole = [117669888, 368640, 1536, 512, 4]). + #[test] + fn running_state_regions_match_the_original_conversation_sizes() { + let layout = + OriginalSessionLayout::new(OriginalSessionGeometry::original(), 4096, 10, 0, -1, policy()).unwrap(); + let facts = layout.conversation_facts(); + assert_eq!((facts.qsa_alloc, facts.gdn_alloc), (12, 36)); + assert_eq!(facts.gdn_state_bytes, 117_669_888); + assert_eq!(facts.ple_hist_bytes, 368_640); + assert_eq!(facts.qsa.len(), 12); + for (j, q) in facts.qsa.iter().enumerate() { + let span = |kind| layout.conversation_span(OriginalRegion::Idx { owned: j, kind }).unwrap().unwrap(); + assert_eq!(span(OriginalIdxKind::Tail).bytes, 1536); + assert_eq!(span(OriginalIdxKind::Dead).bytes, 512); + assert_eq!(span(OriginalIdxKind::BlockPos).bytes, 4); + assert!(q.has("idx_pooled") && q.has("page_table")); + } + } + + #[test] + fn kv_regions_follow_the_state_format_and_streaming_mode() { + let layout = + OriginalSessionLayout::new(OriginalSessionGeometry::original(), 4096, 10, 0, -1, policy()).unwrap(); + let kv = |pool, resident| { + layout.conversation_span(OriginalRegion::Kv { layer: OriginalKvLayer::Owned(0), pool, resident }) + }; + // INT8, resident: K/V codes and both scale pools are arena spans. + for pool in [OriginalKvPool::K, OriginalKvPool::V, OriginalKvPool::KScale, OriginalKvPool::VScale, OriginalKvPool::Pooled] { + assert!(kv(pool, false).unwrap().is_some(), "{pool:?}"); + } + // The drafter's K/V is never in the session arena. + assert_eq!( + layout + .conversation_span(OriginalRegion::Kv { + layer: OriginalKvLayer::Draft, + pool: OriginalKvPool::K, + resident: false + }) + .unwrap(), + None + ); + // Out-of-range owned layer is refused. + assert!(layout.conversation_span(OriginalRegion::Idx { owned: 12, kind: OriginalIdxKind::Tail }).is_err()); + // Every span lies inside the session. + for j in 0..12 { + for pool in [OriginalKvPool::K, OriginalKvPool::V, OriginalKvPool::Pooled] { + let s = layout + .conversation_span(OriginalRegion::Kv { layer: OriginalKvLayer::Owned(j), pool, resident: false }) + .unwrap() + .unwrap(); + assert!(s.end().unwrap() <= layout.session_bytes); + } + } + } +} diff --git a/crates/cuda-driver/src/original_session_state.rs b/crates/cuda-driver/src/original_session_state.rs index 407e1eb4..4d1ca8a2 100644 --- a/crates/cuda-driver/src/original_session_state.rs +++ b/crates/cuda-driver/src/original_session_state.rs @@ -5,6 +5,12 @@ #[path="original_session_rope.rs"] mod rope; pub(crate) use rope::{OriginalRopeScaling, OriginalRopeScalingType, OriginalRopeTable, OriginalRopeUpload}; #[path="original_session_qsa_init.rs"] mod qsa_init; +#[allow(dead_code)] +#[path="original_conversation_state.rs"] mod conversation; +#[allow(unused_imports)] +pub use conversation::{OriginalGeometryFacts,OriginalHostKv,OriginalIdxKind,OriginalKvLayer,OriginalKvPool,OriginalQsaFacts,OriginalRegion,OriginalSessionBytes,OriginalSessionControl,OriginalSessionFacts}; +#[allow(unused_imports)] +pub(crate) use conversation::OriginalConversationAccess; use crate::{Context, DeviceBuffer, Error, Result, combine}; use std::rc::Rc; diff --git a/crates/leleka-runtime/src/conversation/mod.rs b/crates/leleka-runtime/src/conversation/mod.rs index 832ac13b..c0cb2913 100644 --- a/crates/leleka-runtime/src/conversation/mod.rs +++ b/crates/leleka-runtime/src/conversation/mod.rs @@ -18,6 +18,8 @@ pub mod manager; mod manager_tests; pub mod memory; pub mod model; +#[cfg(any(test, all(target_os = "linux", target_arch = "x86_64")))] +pub mod original; pub mod retention; pub mod snapshot; #[cfg(test)] diff --git a/crates/leleka-runtime/src/conversation/original.rs b/crates/leleka-runtime/src/conversation/original.rs new file mode 100644 index 00000000..45064bbb --- /dev/null +++ b/crates/leleka-runtime/src/conversation/original.rs @@ -0,0 +1,353 @@ +//! Adapter from the Original session owners (cuda-driver's +//! `OriginalSessionBytes`/`OriginalSessionControl`) to the conversation policy: +//! it translates the policy's region vocabulary, and turns the layout facts of +//! `OriginalSessionState` into the [`SessionSpec`] snapshot validation needs. +//! +//! Compiles only where the CUDA driver crate does; the policy it feeds is +//! device-independent and tested on every host. + +use super::binding::SessionDevice; +use super::model::{ + HostPools, IdxKind, KvLayer, KvPool, ModelGeometry, QsaDesc, SessionShape, SessionSpec, + StateMemory, StateRegion, StreamMap, +}; +use leleka_cuda_driver::{ + OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, OriginalRegion, + OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts, +}; + +fn layer(l: KvLayer) -> OriginalKvLayer { + match l { + KvLayer::Main(owned) => OriginalKvLayer::Owned(owned), + KvLayer::Draft => OriginalKvLayer::Draft, + } +} + +fn pool(p: KvPool) -> OriginalKvPool { + match p { + KvPool::K => OriginalKvPool::K, + KvPool::V => OriginalKvPool::V, + KvPool::KScale => OriginalKvPool::KScale, + KvPool::VScale => OriginalKvPool::VScale, + KvPool::Pooled => OriginalKvPool::Pooled, + } +} + +fn region(r: StateRegion) -> OriginalRegion { + match r { + StateRegion::Gdn => OriginalRegion::Gdn, + StateRegion::PleHist => OriginalRegion::PleHist, + StateRegion::Idx { layer, kind } => OriginalRegion::Idx { + owned: layer, + kind: match kind { + IdxKind::Tail => OriginalIdxKind::Tail, + IdxKind::Dead => OriginalIdxKind::Dead, + IdxKind::BlockPos => OriginalIdxKind::BlockPos, + }, + }, + StateRegion::Kv { + layer: l, + pool: p, + resident, + } => OriginalRegion::Kv { + layer: layer(l), + pool: pool(p), + resident, + }, + } +} + +/// The pinned model's `ssm_k_heads`: the session layout does not carry it. +const SSM_K_HEADS: i64 = 16; + +/// `ModelGeometry` of a session, for the compatibility key and the sizing. +pub fn model_geometry(facts: &OriginalSessionFacts) -> ModelGeometry { + let g = &facts.geometry; + ModelGeometry { + n_embd: g.n_embd as i64, + n_layers: g.n_layers as i64, + qsa_interval: g.qsa_interval as i64, + ssm_state_size: g.state_size as i64, + ssm_k_heads: SSM_K_HEADS, + ssm_v_heads: g.value_heads as i64, + ssm_d_conv: g.conv_width as i64, + ssm_conv_channels: g.conv_channels as i64, + ssm_value_dim: g.value_dim as i64, + n_head: g.heads as i64, + n_head_kv: g.kv_heads as i64, + head_dim: g.head_dim as i64, + idx_q_heads: g.index_heads as i64, + idx_key_dim: g.index_dim as i64, + hc: g.hc as i64, + hc_lr: g.hc_lr as i64, + n_expert: g.experts as i64, + n_ff: g.n_ff as i64, + } +} + +/// One owned QSA state as snapshot validation sees it. +pub fn qsa_desc(q: &OriginalQsaFacts, max_cells: usize) -> QsaDesc { + let streamed = q.mode != 0; + let (k_pool, v_pool) = (q.has("k_pool"), q.has("v_pool")); + let int8 = q.kv_int8 || q.kv_hybrid; + QsaDesc { + without_key: q.without_key, + kv_int8: q.kv_int8, + kv_q4: q.kv_q4, + kv_hybrid: q.kv_hybrid, + kv_rot: q.kv_rotate, + k_pool, + v_pool, + k_q: q.has("k_q"), + v_q: q.has("v_q"), + k_scale: q.has("k_scale"), + v_scale: q.has("v_scale"), + k_q4: q.has("k_q4"), + v_q4: q.has("v_q4"), + page_table: q.has("page_table"), + n_pages: q.pages as i64, + max_cells: max_cells as i64, + kv_mode: i32::from(q.mode), + n_slots: q.slots as i64, + // The authoritative host copy mirrors the pool set of the format. + host: HostPools { + k_pool: streamed && k_pool, + v_pool: streamed && v_pool, + k_q: streamed && int8 && !q.kv_q4 && q.has("k_q"), + v_q: streamed && q.kv_int8 && !q.kv_q4 && q.has("v_q"), + k_scale: streamed && q.kv_int8 && q.has("k_scale"), + v_scale: streamed && q.kv_int8 && q.has("v_scale"), + k_q4: streamed && q.kv_q4 && q.has("k_q4"), + v_q4: streamed && (q.kv_q4 || q.kv_hybrid) && q.has("v_q4"), + }, + map: StreamMap { + n_blocks: q.pages as i64, + n_slots: q.slots as i64, + complete: [ + "slot_block", + "slot_stamp", + "slot_ref", + "miss_block", + "miss_slot", + "ctl", + ] + .iter() + .all(|name| q.has(name)), + }, + idx_pooled_rows: q.pooled_rows as i64, + idx_tail: q.has("idx_tail"), + idx_dead: q.has("idx_dead"), + idx_pooled: q.has("idx_pooled"), + idx_block_pos: q.has("idx_block_pos"), + } +} + +/// The session carve and its QSA states (indexed by global ordinal). +pub fn session_spec(facts: &OriginalSessionFacts) -> SessionSpec { + let ord0 = facts.qsa_ord0; + let mut qsa = vec![QsaDesc::default(); ord0]; + qsa.extend(facts.qsa.iter().map(|q| qsa_desc(q, facts.max_cells))); + SessionSpec { + shape: SessionShape { + max_cells: facts.max_cells as i64, + layer_lo: facts.layer_lo as i64, + layer_hi: facts.layer_hi as i64, + qsa_ord0: ord0 as i64, + qsa_alloc: facts.qsa_alloc as i64, + gdn_alloc: facts.gdn_alloc as i64, + has_gdn_state: facts.gdn_state_bytes != 0, + has_ple_hist: facts.ple_hist_bytes != 0, + }, + qsa, + } +} + +/// A session whose bytes are reached through the CUDA-driver owners. +pub struct OriginalDevice { + pub session: T, +} + +fn text(e: leleka_cuda_driver::Error) -> String { + e.to_string() +} + +impl StateMemory for OriginalDevice { + fn synchronize(&mut self) -> Result<(), String> { + self.session.synchronize().map_err(text) + } + + fn read(&mut self, r: StateRegion, offset: usize, dst: &mut [u8]) -> Result<(), String> { + self.session.read(region(r), offset, dst).map_err(text) + } + + fn write(&mut self, r: StateRegion, offset: usize, src: &[u8]) -> Result<(), String> { + self.session.write(region(r), offset, src).map_err(text) + } + + fn set_ple_prev(&mut self, prev: [i32; 2]) { + self.session.set_ple_prev(prev); + } + + fn reset_streaming_residency(&mut self, l: KvLayer) -> Result<(), String> { + match l { + KvLayer::Main(owned) => self.session.reset_stream_map(owned).map_err(text), + KvLayer::Draft => Err("the drafter ring has no streaming map".into()), + } + } + + fn restore_ring( + &mut self, + l: KvLayer, + format: i32, + begin: i64, + end: i64, + slots: i64, + ) -> Result<(), String> { + self.session + .restore_ring(layer(l), format, begin, end, slots) + .map_err(text) + } +} + +impl SessionDevice for OriginalDevice { + fn zero_session(&mut self) -> Result<(), String> { + self.session.zero_session().map_err(text) + } + + fn restore_draft(&mut self, resume: usize) -> Result<(), String> { + self.session.restore_draft(resume).map_err(text) + } + + fn set_steering(&mut self, enabled: bool) { + self.session.set_steering(enabled); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::conversation::state::{checkpoint_targets, session_sizes, state_sizes}; + use leleka_cuda_driver::OriginalGeometryFacts; + + fn facts(streamed: bool) -> OriginalSessionFacts { + let qsa = (0..12) + .map(|j| OriginalQsaFacts { + ordinal: j, + mode: u8::from(streamed), + pages: 1024, + slots: if streamed { 80 } else { 1024 }, + pooled_rows: 1026, + kv_int8: true, + kv_q4: false, + kv_hybrid: false, + kv_rotate: false, + without_key: false, + regions: [ + "k_q", + "v_q", + "k_scale", + "v_scale", + "page_table", + "idx_tail", + "idx_dead", + "idx_pooled", + "idx_block_pos", + "step", + "attention_status", + "pos_dev", + ] + .into_iter() + .chain(streamed.then_some("slot_block")) + .collect(), + host_kv_bytes: if streamed { 1 << 20 } else { 0 }, + }) + .collect(); + OriginalSessionFacts { + geometry: OriginalGeometryFacts { + n_embd: 2560, + n_layers: 48, + qsa_interval: 4, + state_size: 128, + value_heads: 48, + conv_width: 4, + conv_channels: 10240, + value_dim: 6144, + heads: 24, + kv_heads: 2, + head_dim: 256, + index_heads: 4, + index_dim: 128, + hc: 4, + hc_lr: 320, + experts: 512, + n_ff: 640, + }, + max_cells: 4096, + layer_lo: 0, + layer_hi: 48, + qsa_ord0: 0, + qsa_alloc: 12, + gdn_alloc: 36, + gdn_state_bytes: 117_669_888, + ple_hist_bytes: 368_640, + qsa, + } + } + + #[test] + fn the_original_session_facts_are_a_valid_snapshot_target() { + let f = facts(false); + let g = model_geometry(&f); + assert_eq!( + g, + ModelGeometry::default(), + "the pinned geometry round-trips through the layout facts" + ); + let spec = session_spec(&f); + // The compiled C++ sizes (golden/state_golden.json, "original whole model"). + let z = session_sizes(&g, &spec).unwrap(); + assert_eq!( + (z.gdn, z.ple, z.tail, z.dead, z.block_pos), + (117_669_888, 368_640, 1536, 512, 4) + ); + assert_eq!(z, state_sizes(&g).unwrap()); + checkpoint_targets(&spec, &g, 100) + .expect("a session with every running-state buffer takes checkpoints"); + assert!( + checkpoint_targets(&spec, &g, 5000).is_err(), + "more tokens than cells" + ); + } + + #[test] + fn streamed_layers_expose_a_host_copy_and_a_complete_map_only_when_carved() { + let f = facts(true); + let d = qsa_desc(&f.qsa[0], f.max_cells); + assert_eq!(d.kv_mode, 1); + assert!(d.host.present() && d.host.k_q && d.host.v_q && d.host.k_scale && d.host.v_scale); + assert!(!d.map.complete, "a map missing its arrays is not usable"); + let resident = qsa_desc(&facts(false).qsa[0], 4096); + assert!(!resident.host.present()); + assert_eq!(resident.pools(false), [true, true, true, true, true]); + } + + #[test] + fn a_carved_stage_session_indexes_states_by_global_ordinal() { + let mut f = facts(false); + f.layer_lo = 4; + f.qsa_ord0 = 1; + f.qsa_alloc = 1; + f.gdn_alloc = 3; + f.qsa.truncate(1); + f.gdn_state_bytes = 117_669_888 / 12; + let spec = session_spec(&f); + assert_eq!( + spec.qsa.len(), + 2, + "one placeholder below the first owned ordinal" + ); + assert!(spec.owned(0).is_some() && spec.owned(1).is_none()); + let g = model_geometry(&f); + assert_eq!(session_sizes(&g, &spec).unwrap().gdn, 117_669_888 / 36 * 3); + } +}