diff --git a/crates/cuda-driver/src/mtp_original_int8.rs b/crates/cuda-driver/src/mtp_original_int8.rs index 61c92877..f4c624ed 100644 --- a/crates/cuda-driver/src/mtp_original_int8.rs +++ b/crates/cuda-driver/src/mtp_original_int8.rs @@ -1,1639 +1,1639 @@ -//! Literal Original MTP INT8 ring and record_forward(full=false) attention tail. -//! Input/GR and runtime causal authority are separate genuine producer obligations. -//! No F16 ring, whole warm_step, prompt-attention, or host-float readiness substitute. -#[path = "mtp_original_int8_ffi.rs"] -#[allow(unsafe_code)] -mod abi; -#[path = "mtp_original_ring_state.rs"] -mod ring_state; -use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine}; -use abi::{Arg, Arguments, MappedOwner, Module}; -use std::{ - cell::{Cell, Ref, RefCell, RefMut}, - rc::Rc, -}; - -pub const MTP_ORIGINAL_WINDOW: usize = 32768; -/// The MTP drafter bank is FROZEN at the trained 262144-cell geometry (its mapped host image, page table and -/// ring layouts are literal). It is deliberately NOT derived from the serving context: -/// `validate_existing_int8_bank` refuses any other session geometry, and the runtime refuses the MTP modes for a -/// context past the trained one. Re-deriving and qualifying it is a separate piece of work. -pub const MTP_ORIGINAL_MAX_CELLS: usize = 262144; -pub const MTP_ORIGINAL_PINNED_HOST_BYTES: usize = 276825088; -pub const MTP_ORIGINAL_SNAPSHOT_PAYLOAD_BYTES: usize = 276824064; -const RESERVE: usize = 128 * 1024 * 1024; -const PAGE_BYTES: [usize; 4] = [2048, 2048, 64, 64]; -const HOST_RUNS: [usize; 4] = [134217728, 134217728, 4194304, 4194304]; -const HOST_OFFSETS: [usize; 4] = [0, 134217728, 268435456, 272629760]; -const CHUNKS: usize = 512; -const SCRATCH_FLOATS: usize = CHUNKS * 24 * (256 + 2); -const STATUS_WORDS: usize = 21; // four leading stages, two per real row, final scale scan -const TAIL_ENTRIES: &[&std::ffi::CStr] = &[ - c"mtp_original_quantize", - c"mtp_original_q80_1", - c"mtp_original_q80_2", - c"mtp_original_q80_3", - c"mtp_original_q80_4", - c"mtp_original_q80_5", - c"mtp_original_q80_6", - c"mtp_original_q80_7", - c"mtp_original_q80_8", - c"mtp_original_knorm", - c"mtp_original_krope", - c"mtp_original_finite", - c"mtp_original_q8_guard", -]; -const KV_ENTRIES: &[&std::ffi::CStr] = &[ - c"mtp_original_append", - c"mtp_original_ring_table", - c"mtp_original_window_ids", - c"mtp_original_encoded_guard", -]; -const ATTN_ENTRIES: &[&std::ffi::CStr] = &[ - c"leleka_qsa_prompt_guard", - c"leleka_qsa_decode_chunk", - c"leleka_qsa_decode_merge", - c"leleka_qsa_prompt_output_guard", -]; -struct Origin; -#[derive(Clone)] -pub struct MtpInt8OwnerId(Rc); -impl MtpInt8OwnerId { - pub fn same_owner(&self, other: &Self) -> bool { - Rc::ptr_eq(&self.0, &other.0) - } -} - -#[path = "mtp_original_logical_prefix.rs"] -mod logical_prefix; -pub use logical_prefix::OriginalMtpSkippedPrefix; -// The literal prefill producer is an MTP child because it borrows this -// owner's private ring/state types. Its public contracts are re-exported by -// the crate integration point below. -#[path = "mtp_original_prefill.rs"] -mod prefill; -pub(crate) use prefill::session_assets_sealed; -pub use prefill::{ - CompletedDraftKv, CompletedOriginalMtpDraft, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, - OriginalMtpDraftProgram, OriginalMtpDrafter, OriginalMtpEmbedding, OriginalMtpForwardProgram, - OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpPrefill, - OriginalMtpPrefillWeights, OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, - OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, - OriginalMtpStepOutput, -}; -/// `LELEKA_MTP_SNAPSHOT_MEMO=off`: scan every page of a snapshot on each `validate_snapshot` (the earlier behaviour; the A/B control). -fn snapshot_memo() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| !std::env::var("LELEKA_MTP_SNAPSHOT_MEMO").is_ok_and(|v| v == "off" || v == "0")) -} -struct Page { - runs: [Box<[u8]>; 4], -} -/// The immutable page list of a snapshot, in chunks of `PAGES_PER_CHUNK` so that the next snapshot of a speculation round shares every -/// chunk the round did not touch: the page list is O(context / 4) long (65,536 pages at 256k) and the round changes its last few entries only. -#[derive(Clone)] -struct Pages { - chunks: Rc>>>>, - len: usize, -} -const PAGES_PER_CHUNK: usize = 256; -impl Pages { - fn empty() -> Self { - Self { chunks: Rc::new(Vec::new()), len: 0 } - } - fn from_vec(pages: Vec>) -> Self { - let len = pages.len(); - let chunks = pages.chunks(PAGES_PER_CHUNK).map(|c| Rc::new(c.to_vec())).collect(); - Self { chunks: Rc::new(chunks), len } - } - /// The first `keep` pages of `self` (`keep <= len`), then `tail`. Whole chunks inside `keep` are shared, not copied. - fn with_tail(&self, keep: usize, tail: Vec>) -> Self { - let keep = keep.min(self.len); - let whole = keep / PAGES_PER_CHUNK; - let mut chunks: Vec>>> = Vec::with_capacity(whole + 1 + tail.len() / PAGES_PER_CHUNK); - chunks.extend(self.chunks[..whole].iter().cloned()); - let mut open: Vec> = Vec::with_capacity(PAGES_PER_CHUNK); - if keep % PAGES_PER_CHUNK != 0 { - open.extend(self.chunks[whole][..keep % PAGES_PER_CHUNK].iter().cloned()); - } - let len = keep + tail.len(); - for page in tail { - open.push(page); - if open.len() == PAGES_PER_CHUNK { - chunks.push(Rc::new(std::mem::replace(&mut open, Vec::with_capacity(PAGES_PER_CHUNK)))); - } - } - if !open.is_empty() { - chunks.push(Rc::new(open)); - } - Self { chunks: Rc::new(chunks), len } - } - fn len(&self) -> usize { - self.len - } - fn get(&self, p: usize) -> Option<&Rc> { - if p >= self.len { - return None; - } - self.chunks.get(p / PAGES_PER_CHUNK)?.get(p % PAGES_PER_CHUNK) - } - fn iter(&self) -> impl Iterator> { - self.chunks.iter().flat_map(|c| c.iter()) - } -} -struct Snapshot { - origin: Rc, - pages: Pages, - end: usize, - /// The pages up to `end` were checked to have the exact run sizes (`validate_snapshot`). The snapshot is immutable, so the - /// answer cannot change; the scan is O(context / 4) and ran several times per speculation round. - checked: Cell, -} -/// Immutable actual encoded bytes; runtime binds these to its genuine MTP epoch. -#[derive(Clone)] -pub struct MtpInt8Snapshot(Rc); -impl MtpInt8Snapshot { - pub fn owner_id(&self) -> MtpInt8OwnerId { - MtpInt8OwnerId(self.0.origin.clone()) - } - pub fn next_position(&self) -> usize { - self.0.end - } - pub fn encoded_bytes(&self) -> usize { - self.0.pages.len() * 4224 - } - pub fn metadata_bytes(&self) -> usize { - std::mem::size_of::() - + std::mem::size_of::() - + 8 * std::mem::size_of::() - + self.0.pages.len() - * (std::mem::size_of::>() - + std::mem::size_of::() - + 2 * std::mem::size_of::()) - } -} -/// Created only inside the actual driver input+fused-GR producer integration. -/// Public constructors accepting arbitrary floats or a caller readiness bit do not exist. -pub struct MtpOriginalMixed<'loan, 'buffers> { - mixed: &'loan DeviceBuffer<'buffers>, - first: usize, - rows: usize, -} -impl<'loan, 'buffers> MtpOriginalMixed<'loan, 'buffers> { - pub(crate) fn from_completed_gr( - c: &Context<'_>, - mixed: &'loan DeviceBuffer<'buffers>, - first: usize, - rows: usize, - ) -> Result { - rows_range(first, rows, 8)?; - checked(c, mixed, rows * 2560 * 4)?; - Ok(Self { mixed, first, rows }) - } - pub fn rows(&self) -> usize { - self.rows - } - pub fn first_position(&self) -> usize { - self.first - } -} -/// Real native normalized/RoPE query, minted by the actual scalar full-draft producer. -pub struct MtpOriginalQuery<'loan, 'buffers> { - query: &'loan DeviceBuffer<'buffers>, -} -impl<'loan, 'buffers> MtpOriginalQuery<'loan, 'buffers> { - pub(crate) fn from_completed_native( - c: &Context<'_>, - query: &'loan DeviceBuffer<'buffers>, - ) -> Result { - checked(c, query, 6144 * 4)?; - Ok(Self { query }) - } -} -/// Replay completion retains actual ring and immutable whole-weight/input loans. -pub struct CompletedMtpKvReplay<'loan, 'ctx, 'buffers, 'weights> { - owner: &'loan mut MtpOriginalInt8<'ctx>, - snapshot: MtpInt8Snapshot, - _mixed: &'loan MtpOriginalMixed<'loan, 'buffers>, - _weights: [&'loan DeviceBuffer<'weights>; 3], - first: usize, - rows: usize, -} -impl CompletedMtpKvReplay<'_, '_, '_, '_> { - pub fn rows(&self) -> usize { - self.rows - } - pub fn final_snapshot(&self) -> &MtpInt8Snapshot { - &self.snapshot - } - /// End can only be derived from a real row of this completed append. - pub fn snapshot_after(&self, row: usize) -> Result { - self.owner.validate()?; - if row >= self.rows { - return Err(Error::InvalidQwenShape); - } - Ok(MtpInt8Snapshot(Rc::new(Snapshot { - origin: self.snapshot.0.origin.clone(), - pages: self.snapshot.0.pages.clone(), - end: self.first + row + 1, - checked: std::cell::Cell::new(self.snapshot.0.checked.get()), - }))) - } - pub fn into_final_snapshot(self) -> MtpInt8Snapshot { - self.snapshot - } -} -pub struct CompletedMtpAttention<'loan, 'ctx, 'buffers> { - owner: &'loan mut MtpOriginalInt8<'ctx>, - _snapshot: &'loan MtpInt8Snapshot, - _query: &'loan MtpOriginalQuery<'loan, 'buffers>, -} -impl CompletedMtpAttention<'_, '_, '_> { - pub fn with_output(&self, f: impl FnOnce(&DeviceBuffer<'_>) -> Result) -> Result { - self.owner.validate()?; - f(self.owner.buffer(11)?) - } - pub fn into_values(self) -> Result> { - self.owner.validate()?; - let bytes = self.owner.buffer(11)?.copy_to_owned(6144 * 4)?; - let mut out = Vec::new(); - out.try_reserve_exact(6144) - .map_err(|_| Error::HostAllocation)?; - for x in bytes.chunks_exact(4) { - out.push(f32::from_le_bytes( - x.try_into().map_err(|_| Error::InvalidSize)?, - )); - } - Ok(out.into_boxed_slice()) - } -} -enum Command { - Kernel { - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - args: Arguments, - }, - Copy { - dst: u64, - src: u64, - bytes: usize, - }, -} -/// Actual model-lifetime physical allocations. Causal current/generation lives -/// only on MtpOriginalInt8. Graph resources retain this Rc without a RefCell loan. -/// Only bounded CPU mapped-page accesses take short exclusive mapped borrows. -struct PhysicalRing<'ctx> { - context: &'ctx Context<'ctx>, - origin: Rc, - sizes: [usize; 15], - buffers: [Option>; 15], - modules: [Option; 3], - mapped: RefCell>, - selected: Option>, - failed: Cell, - active: Cell, -} -/// Opaque genuine physical retention minted only by this ring. No caller pointer, -/// bytes or ready marker can construct a token. It is not a causal state proof. -pub struct MtpOriginalRingResources<'ctx> { - physical: Rc>, -} -impl Clone for MtpOriginalRingResources<'_> { - fn clone(&self) -> Self { - Self { - physical: Rc::clone(&self.physical), - } - } -} -impl MtpOriginalRingResources<'_> { - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - self.physical.validate_context(c) - } - pub fn owner_id(&self) -> MtpInt8OwnerId { - MtpInt8OwnerId(self.physical.origin.clone()) - } - pub fn allocated_bytes(&self) -> usize { - self.physical - .buffers - .iter() - .flatten() - .map(|b| b.bytes) - .sum::() - + self - .physical - .selected - .as_ref() - .map_or(0, |s| s.unique_bytes()) - } - pub fn metadata_bytes(&self) -> usize { - std::mem::size_of::>() - + 2 * std::mem::size_of::() - + std::mem::size_of::() - } -} -impl PhysicalRing<'_> { - fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - if !self.active.get() - || self.failed.get() - || c.is_poisoned() - || c.handle.is_none() - || self.modules.iter().any(Option::is_none) - || (self.selected.is_none() - && self - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .is_none()) - { - return Err(Error::ContextPoisoned); - } - for (i, b) in self.buffers.iter().enumerate() { - if let Some(b) = b { - checked(c, b, self.sizes[i])?; - } else if !self.selected.as_ref().is_some_and(|s| s.provides(i)) { - return Err(Error::ContextPoisoned); - } - } - if let Some(s) = &self.selected { - s.validate(c)?; - } - Ok(()) - } - fn close_inner(&mut self) -> Result<()> { - self.active.set(false); - self.failed.set(true); - let mut result = Ok(()); - // Same original module -> mapped -> device order and primary arbitration. - // A poisoned Context retains every actual physical owner and its charge. - for m in &mut self.modules { - if let Some(module) = m.take() { - let close = if self.context.is_poisoned() { - std::mem::forget(module); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(module.close(), g.finish()), - Err(e) => { - self.context.poison(); - std::mem::forget(module); - Err(e) - } - } - }; - if close.is_err() { - self.context.poison(); - } - result = combine(result, close); - } - } - if let Some(mut mapped) = self.mapped.get_mut().take() { - let close = if self.context.is_poisoned() { - std::mem::forget(mapped); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => { - let op = mapped.close(); - let pop = g.finish(); - combine(op, pop) - } - Err(e) => { - self.context.poison(); - std::mem::forget(mapped); - Err(e) - } - } - }; - if close.is_err() { - self.context.poison(); - } - result = combine(result, close); - } - if let Some(mut s) = self.selected.take() { - result = combine(result, s.close()); - } - for b in &mut self.buffers { - if let Some(buffer) = b.take() { - let close = if self.context.is_poisoned() { - std::mem::forget(buffer); - Err(Error::ContextPoisoned) - } else { - buffer.release() - }; - if close.is_err() { - self.context.poison(); - } - result = combine(result, close); - } - } - if self.context.is_poisoned() { - self.context.retain_driver(); - } - result - } -} -impl Drop for PhysicalRing<'_> { - fn drop(&mut self) { - let _ = self.close_inner(); - } -} -/// One Context-affine model owner. The literal selected plain INT8, unrotated -/// 32K-window profile is explicit. Other Original formats/options remain separate. -pub struct MtpOriginalInt8<'ctx> { - context: &'ctx Context<'ctx>, - origin: Rc, - max_t: usize, - slots: usize, - sizes: [usize; 15], - physical: Option>>, - current: Option, - failed: bool, - generation: u64, -} -fn zero_bytes(n: usize) -> Result> { - let mut v = Vec::new(); - v.try_reserve_exact(n).map_err(|_| Error::HostAllocation)?; - v.resize(n, 0); - Ok(v) -} -fn checked(c: &Context<'_>, b: &DeviceBuffer<'_>, n: usize) -> Result { - if !std::ptr::eq(c, b.context) { - return Err(Error::ContextMismatch); - } - if b.bytes != n { - return Err(Error::InvalidQwenShape); - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(n, 4)?; - Ok(h.qwen_address()) -} -fn rows_range(first: usize, rows: usize, max_t: usize) -> Result<()> { - if !(1..=max_t).contains(&rows) - || first - .checked_add(rows) - .is_none_or(|e| e > MTP_ORIGINAL_MAX_CELLS) - { - return Err(Error::InvalidQwenShape); - } - Ok(()) -} -fn layout(t: usize) -> Result<(usize, [usize; 15])> { - if !(1..=8).contains(&t) { - return Err(Error::InvalidQwenShape); - } - let slots = (MTP_ORIGINAL_WINDOW + 4 * t + 64).div_ceil(4); - Ok(( - slots, - [ - slots * 2048, - slots * 2048, - slots * 64, - slots * 64, - 65536 * 4, - t * 2880, - t * 2048, - t * 2048, - t * 24 * 4, - t * 4 * 4, - STATUS_WORDS * 4, - 6144 * 4, - SCRATCH_FLOATS * 4, - MTP_ORIGINAL_WINDOW * 4, - 16, - ], - )) -} -impl Context<'_> { - pub fn mtp_original_int8(&self, max_t: usize) -> Result> { - MtpOriginalInt8::new(self, max_t) - } -} -impl<'ctx> MtpOriginalInt8<'ctx> { - pub fn planned_device_bytes(max_t: usize) -> Result { - Ok(layout(max_t)?.1.into_iter().sum()) - } - pub fn pinned_host_bytes() -> usize { - MTP_ORIGINAL_PINNED_HOST_BYTES - } - pub fn max_snapshot_payload_bytes() -> usize { - MTP_ORIGINAL_SNAPSHOT_PAYLOAD_BYTES - } - pub fn max_snapshot_metadata_bytes() -> usize { - std::mem::size_of::() - + std::mem::size_of::() - + 8 * std::mem::size_of::() - + 65536 - * (std::mem::size_of::>() - + std::mem::size_of::() - + 2 * std::mem::size_of::()) - } - fn new(c: &'ctx Context<'ctx>, max_t: usize) -> Result { - let (slots, sizes) = layout(max_t)?; - if c.is_poisoned() || c.handle.is_none() { - return Err(Error::ContextPoisoned); - } - // Refuse placeholders before any host or device owner allocation. - for ptx in [ - include_bytes!("mtp_original_tail.ptx").as_slice(), - include_bytes!("mtp_original_kv.ptx").as_slice(), - ] { - if ptx.windows(8).any(|w| w == b"UNSEALED") { - return Err(Error::UnsupportedQwenOperation); - } - } - let needed = sizes - .into_iter() - .sum::() - .checked_add(RESERVE) - .ok_or(Error::BudgetExceeded)?; - if c.allocated_bytes() - .checked_add(needed) - .is_none_or(|n| n > c.budget) - || c.memory_info()?.0 < needed - { - return Err(Error::BudgetExceeded); - } - let origin = Rc::new(Origin); - let physical = Rc::new(PhysicalRing { - context: c, - origin: origin.clone(), - sizes, - buffers: std::array::from_fn(|_| None), - modules: std::array::from_fn(|_| None), - mapped: RefCell::new(None), - selected: None, - failed: Cell::new(false), - active: Cell::new(true), - }); - let mut o = Self { - context: c, - origin, - max_t, - slots, - sizes, - physical: Some(physical), - current: None, - failed: false, - generation: 0, - }; - let operation = (|| { - let guard = c.enter().inspect_err(|_| { - c.poison(); - c.retain_driver(); - })?; - let load = (|| { - o.physical_mut()?.modules[0] = Some(Module::load( - include_bytes!("mtp_original_tail.ptx"), - TAIL_ENTRIES, - )?); - o.physical_mut()?.modules[1] = Some(Module::load( - include_bytes!("mtp_original_kv.ptx"), - KV_ENTRIES, - )?); - o.physical_mut()?.modules[2] = Some(Module::load( - include_bytes!("qsa_native_decode.ptx"), - ATTN_ENTRIES, - )?); - *o.physical_mut()?.mapped.get_mut() = Some(MappedOwner::new()?); - if o.physical()? - .mapped - .borrow() - .as_ref() - .is_none_or(|m| m.bytes() != MTP_ORIGINAL_PINNED_HOST_BYTES) - { - return Err(Error::InvalidSize); - } - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - o.poison(); - } - combine(load, pop)?; - for (i, n) in sizes.into_iter().enumerate() { - o.physical_mut()?.buffers[i] = Some(c.allocate(n)?); - } - // Real initialized pools; no reader ever names an unwritten logical cell. - for i in 0..4 { - o.copy_from_physical(i, &zero_bytes(sizes[i])?)?; - } - let mut table = zero_bytes(65536 * 4)?; - for (p, b) in table.chunks_exact_mut(4).enumerate() { - b.copy_from_slice(&((p % slots) as i32).to_le_bytes()); - } - o.copy_from_physical(4, &table)?; - if c.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = operation { - return combine(Err(e), o.close()); - } - Ok(o) - } - fn physical(&self) -> Result<&PhysicalRing<'ctx>> { - self.physical.as_deref().ok_or(Error::ContextPoisoned) - } - fn physical_mut(&mut self) -> Result<&mut PhysicalRing<'ctx>> { - Rc::get_mut(self.physical.as_mut().ok_or(Error::ContextPoisoned)?) - .ok_or(Error::InvalidQwenShape) - } - fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { - self.physical()? - .buffers - .get(i) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) - } - fn buffers(&self) -> Result<&[Option>; 15]> { - Ok(&self.physical()?.buffers) - } - fn mapped(&self) -> Result> { - Ref::filter_map( - self.physical()? - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)?, - Option::as_ref, - ) - .map_err(|_| Error::ContextPoisoned) - } - fn mapped_mut(&self) -> Result> { - RefMut::filter_map( - self.physical()? - .mapped - .try_borrow_mut() - .map_err(|_| Error::InvalidQwenShape)?, - Option::as_mut, - ) - .map_err(|_| Error::ContextPoisoned) - } - fn copy_from_physical(&self, i: usize, input: &[u8]) -> Result<()> { - if let Some(s) = &self.physical()?.selected { - if s.provides(i) { - return s.copy_from(i, 0, input); - } - } - let b = self.buffer(i)?; - let mut staging = b.staging(input.len())?; - staging.copy_from_slice(input); - b.copy_staged(staging, false).map(|_| ()) - } - pub(crate) fn retain_physical_resources(&self) -> Result> { - self.validate()?; - Ok(MtpOriginalRingResources { - physical: Rc::clone(self.physical.as_ref().ok_or(Error::ContextPoisoned)?), - }) - } - pub fn physical_metadata_bytes() -> usize { - std::mem::size_of::>() + 2 * std::mem::size_of::() - } - - fn address(&self, i: usize) -> Result { - if let Some(s) = &self.physical()?.selected { - if s.provides(i) { - return Ok(s.span(i, 0, self.sizes[i])?.qwen_address()); - } - } - checked(self.context, self.buffer(i)?, self.sizes[i]) - } - fn sub(&self, i: usize, o: usize, n: usize) -> Result { - if let Some(s) = &self.physical()?.selected { - if s.provides(i) { - return Ok(s.span(i, o, n)?.qwen_address()); - } - } - Ok(self - .buffer(i)? - .handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(self.sizes[i], o, n)? - .qwen_address()) - } - pub fn allocated_bytes(&self) -> usize { - self.physical.as_ref().map_or(0, |p| { - p.buffers.iter().flatten().map(|b| b.bytes).sum::() - + p.selected.as_ref().map_or(0, |s| s.unique_bytes()) - }) - } - pub fn is_failed(&self) -> bool { - self.failed - || self.context.is_poisoned() - || self.context.handle.is_none() - || self - .physical - .as_ref() - .is_none_or(|p| p.failed.get() || !p.active.get()) - } - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - self.validate() - } - fn validate(&self) -> Result<()> { - if self.is_failed() { - return Err(Error::ContextPoisoned); - } - self.physical()?.validate_context(self.context)?; - for i in 0..15 { - if self - .physical()? - .selected - .as_ref() - .is_some_and(|s| s.provides(i)) - { - continue; - } - let b = self.buffer(i)?; - checked(self.context, b, self.sizes[i])?; - if let Some(s) = &self.physical()?.selected { - s.reject_state_alias(b)?; - s.reject_main_alias(b)?; - } - for j in 0..i { - if self - .physical()? - .selected - .as_ref() - .is_some_and(|s| s.provides(j)) - { - continue; - } - let other = self.buffer(j)?; - if b.handle.ok_or(Error::ContextPoisoned)?.overlaps( - b.bytes, - other.handle.ok_or(Error::ContextPoisoned)?, - other.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - if self.context.allocated_bytes() > self.context.budget { - return Err(Error::BudgetExceeded); - } - Ok(()) - } - fn external( - &self, - w: &NativeBatchWorkspace<'ctx>, - b: &DeviceBuffer<'_>, - n: usize, - ) -> Result { - let addr = checked(self.context, b, n)?; - self.reject_state_alias(b)?; - if self - .physical()? - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .is_some() - { - let mapped = self.mapped()?; - let ma = mapped.address(0, MTP_ORIGINAL_PINNED_HOST_BYTES)?; - if addr < ma + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 && ma < addr + n as u64 { - return Err(Error::OutputAliasesInput); - } - } - if let Some(s) = &self.physical()?.selected { - s.reject_main_alias(b)?; - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - w.reject_alias(h, n)?; - for own in self.buffers()?.iter().flatten() { - if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { - return Err(Error::OutputAliasesInput); - } - } - Ok(addr) - } - pub fn empty_snapshot(&self) -> Result { - self.validate()?; - Ok(MtpInt8Snapshot(Rc::new(Snapshot { - origin: self.origin.clone(), - pages: Pages::empty(), - end: 0, - checked: std::cell::Cell::new(true), - }))) - } - pub fn validate_snapshot(&self, s: &MtpInt8Snapshot) -> Result<()> { - self.validate()?; - if !Rc::ptr_eq(&self.origin, &s.0.origin) - || s.0.end > MTP_ORIGINAL_MAX_CELLS - || s.0.pages.len() < s.0.end.div_ceil(4) - { - return Err(Error::InvalidQwenShape); - } - if s.0.checked.get() && snapshot_memo() { - return Ok(()); - } - for p in s.0.pages.iter().take(s.0.end.div_ceil(4)) { - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - if p.runs[i].len() != n { - return Err(Error::InvalidSize); - } - } - } - s.0.checked.set(true); - Ok(()) - } - fn poison(&mut self) { - self.failed = true; - self.current = None; - if let Some(p) = &self.physical { - p.failed.set(true); - } - self.context.poison(); - self.context.retain_driver(); - } - fn execute( - &mut self, - w: &mut NativeBatchWorkspace<'ctx>, - mut commands: Vec, - ) -> Result<()> { - self.validate()?; - w.validate_context(self.context)?; - let blas = w.blas()?; - let stream = blas.stream(); - let modules = &self.physical()?.modules; - let g = match self.context.enter() { - Ok(g) => g, - Err(e) => { - self.poison(); - w.mark_failed(); - return Err(e); - } - }; - // Inputs may be produced on Original default stream. This confirmed dependency - // precedes the model-owned nonblocking stream, never a guessed ready flag. - let mut op = self.context.driver.api.synchronize(); - if op.is_ok() { - for command in &mut commands { - let result = match command { - Command::Kernel { - asset, - index, - grid, - block, - args, - } => modules[*asset] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.launch(*index, *grid, *block, 0, stream, args) - }), - Command::Copy { dst, src, bytes } => modules[1] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.copy(*dst, *src, *bytes, stream) - }), - }; - if let Err(e) = result { - op = Err(e); - break; - } - } - } - let sync = blas.synchronize(); - let pop = g.finish(); - let uncertain = sync.is_err() || pop.is_err(); - if uncertain { - std::mem::forget(commands); - } - if op.is_err() || uncertain { - self.poison(); - w.mark_failed(); - } - combine(combine(op, sync), pop) - } - fn push( - commands: &mut Vec, - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - values: Vec, - ) -> Result<()> { - commands.try_reserve(1).map_err(|_| Error::HostAllocation)?; - commands.push(Command::Kernel { - asset, - index, - grid, - block, - args: Arguments::new(values)?, - }); - Ok(()) - } - fn finite(&self, commands: &mut Vec, a: u64, n: usize, status: usize) -> Result<()> { - Self::push( - commands, - 0, - 11, - [64, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(a), - Arg::I32(n as i32), - Arg::U64(self.sub(10, status * 4, 4)?), - ], - ) - } - fn flags(&mut self) -> Result<[u32; STATUS_WORDS]> { - let b = self.buffer(10)?.copy_to_owned(STATUS_WORDS * 4)?; - let mut s = [0; STATUS_WORDS]; - for (i, v) in b.chunks_exact(4).enumerate() { - s[i] = u32::from_le_bytes(v.try_into().map_err(|_| Error::InvalidSize)?); - if s[i] > 1 { - self.poison(); - return Err(Error::InvalidDriverValue("MTP finite flags")); - } - } - Ok(s) - } - /// Restore real immutable host pages, then exact Original modulo ring blocks. - /// The current witness is invalidated BEFORE any write; valid-end guards prevent - /// O(1) future-backing pages from incorrectly skipping rematerialization. - pub fn restore( - &mut self, - w: &mut NativeBatchWorkspace<'ctx>, - s: &MtpInt8Snapshot, - ) -> Result<()> { - self.validate_snapshot(s)?; - w.validate_context(self.context)?; - self.generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - if self - .current - .as_ref() - .is_some_and(|old| Rc::ptr_eq(&old.0, &s.0)) - { - return Ok(()); - } - let previous = self.current.take(); - if self.fully_resident()? { - // Canonical snapshots remain genuine; restore overwritten accepted pages - // to the same identity cells before publishing the restored witness. - for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { - if previous.as_ref().is_some_and(|old| { - p < old.0.end.div_ceil(4) - && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) - }) { - continue; - } - let state = self - .physical()? - .selected - .as_ref() - .ok_or(Error::ContextPoisoned)?; - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - state.copy_from(i, p * n, &page.runs[i])?; - } - } - self.current = Some(s.clone()); - return Ok(()); - } - let mut mapped = self.mapped_mut()?; - for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { - if previous.as_ref().is_some_and(|old| { - p < old.0.end.div_ceil(4) && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) - }) { - continue; - } - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - mapped.write(HOST_OFFSETS[i] + p * n, &page.runs[i])?; - } - } - drop(mapped); - let b1 = s.0.end.div_ceil(4); - let b0 = b1.saturating_sub(self.slots); - let mut commands = Vec::new(); - commands - .try_reserve_exact(8) - .map_err(|_| Error::HostAllocation)?; - let mut b = b0; - while b < b1 { - let slot = b % self.slots; - let run = (b1 - b).min(self.slots - slot); - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - commands.push(Command::Copy { - dst: self.sub(i, slot * n, run * n)?, - src: self.mapped()?.address(HOST_OFFSETS[i] + b * n, run * n)?, - bytes: run * n, - }); - } - b += run; - } - if !commands.is_empty() { - self.execute(w, commands)?; - } - self.current = Some(s.clone()); - Ok(()) - } - /// Exact attention tail of record_forward(false). Real input+GR has already - /// produced this opaque mixed owner; no full MLP/head work is performed here. - pub fn record_kv_only<'loan, 'buffers, 'weights>( - &'loan mut self, - w: &mut NativeBatchWorkspace<'ctx>, - prior: &MtpInt8Snapshot, - input: &'loan MtpOriginalMixed<'loan, 'buffers>, - weights: [&'loan DeviceBuffer<'weights>; 3], - ) -> Result> { - self.validate_snapshot(prior)?; - w.validate_context(self.context)?; - rows_range(input.first, input.rows, self.max_t)?; - if input.first > prior.0.end { - return Err(Error::InvalidQwenShape); - } - let mixed = self.external(w, input.mixed, input.rows * 10240)?; - let wk = self.external(w, weights[0], 512 * 80 * 34)?; - let wv = self.external(w, weights[1], 512 * 80 * 34)?; - let gamma = self.external(w, weights[2], 256 * 4)?; - let spans = [ - ( - input.mixed.handle.ok_or(Error::ContextPoisoned)?, - input.mixed.bytes, - ), - ( - weights[0].handle.ok_or(Error::ContextPoisoned)?, - weights[0].bytes, - ), - ( - weights[1].handle.ok_or(Error::ContextPoisoned)?, - weights[1].bytes, - ), - ( - weights[2].handle.ok_or(Error::ContextPoisoned)?, - weights[2].bytes, - ), - ]; - for (i, (a, an)) in spans.iter().enumerate() { - for (b, bn) in spans.iter().take(i) { - let exact = a.qwen_address() == b.qwen_address() && an == bn; - if !exact && a.overlaps(*an, *b, *bn) { - return Err(Error::OutputAliasesInput); - } - } - } - let generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - let end = input.first + input.rows; - let n_pages = end.div_ceil(4); - let first_page = input.first / 4; - // All new host ownership is fallibly allocated before the first command. - let mut pages = Vec::new(); - pages - .try_reserve_exact(n_pages) - .map_err(|_| Error::HostAllocation)?; - for page in prior.0.pages.iter().take(first_page) { - pages.push(page.clone()); - } - let mut changed = Vec::new(); - changed - .try_reserve_exact(n_pages - first_page) - .map_err(|_| Error::HostAllocation)?; - for p in first_page..n_pages { - let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - runs[i] = zero_bytes(n)?; - if let Some(old) = prior.0.pages.get(p) { - runs[i].copy_from_slice(&old.runs[i]); - } - } - changed.push(runs); - } - let mut pos = zero_bytes(self.sizes[8])?; - let mut steps = zero_bytes(self.sizes[9])?; - for t in 0..input.rows { - let p = input.first + t; - for h in 0..24 { - pos[(t * 24 + h) * 4..(t * 24 + h + 1) * 4] - .copy_from_slice(&(p as i32).to_le_bytes()); - } - for (i, v) in [p, p + 1, (p + 1) / 4, p + 1].into_iter().enumerate() { - steps[(t * 4 + i) * 4..(t * 4 + i + 1) * 4] - .copy_from_slice(&(v as i32).to_le_bytes()); - } - } - // The real mixed producer supplies the rewind position. Restoring the - // longer prior's ring would keep future blocks after a shorter replay. - // This private prefix is bounded by that genuine prior, never caller-minted. - let replay_prior = if input.first == prior.0.end { - prior.clone() - } else { - MtpInt8Snapshot(Rc::new(Snapshot { - origin: prior.0.origin.clone(), - pages: prior.0.pages.clone(), - end: input.first, - checked: std::cell::Cell::new(prior.0.checked.get()), - })) - }; - self.restore(w, &replay_prior)?; - self.copy_from_physical(8, &pos)?; - self.copy_from_physical(9, &steps)?; - self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?; - let mut commands = Vec::new(); - commands - .try_reserve_exact(32 + input.rows * 5) - .map_err(|_| Error::HostAllocation)?; - self.finite(&mut commands, mixed, input.rows * 2560, 0)?; - Self::push( - &mut commands, - 0, - 0, - [(input.rows * 2560).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(mixed), - Arg::U64(self.address(5)?), - Arg::I32((input.rows * 2560) as i32), - ], - )?; - Self::push( - &mut commands, - 0, - 12, - [64, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(self.address(5)?), - Arg::I32((input.rows * 80) as i32), - Arg::U64(self.sub(10, 4, 4)?), - ], - )?; - for (weight, out, status) in [(wk, 6, 2), (wv, 7, 3)] { - Self::push( - &mut commands, - 0, - input.rows, - [512, 1, 1], - [32, 4, 1], - vec![ - Arg::U64(weight), - Arg::U64(self.address(5)?), - Arg::U64(self.address(out)?), - Arg::I32(2560), - Arg::I32(512), - ], - )?; - self.finite(&mut commands, self.address(out)?, input.rows * 512, status)?; - } - for t in 0..input.rows { - let k = self.sub(6, t * 2048, 2048)?; - Self::push( - &mut commands, - 0, - 9, - [2, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(k), - Arg::U64(gamma), - Arg::U64(k), - Arg::I32(256), - Arg::F32(1.0e-6), - ], - )?; - self.finite(&mut commands, k, 512, 4 + 2 * t)?; - Self::push( - &mut commands, - 0, - 10, - [1, 2, 1], - [128, 1, 1], - vec![ - Arg::U64(k), - Arg::U64(k), - Arg::I32(2), - Arg::I32(256), - Arg::F32(crate::qsa_index_ffi::theta()), - Arg::U64(self.sub(8, t * 96, 8)?), - ], - )?; - self.finite(&mut commands, k, 512, 5 + 2 * t)?; - } - // First failed upstream full scan/quant wins. No host/ring write before - // successful numeric admission of all real K/V rows. - self.execute(w, commands)?; - let flags = self.flags()?; - for (i, v) in flags.iter().enumerate().take(4 + 2 * input.rows) { - if *v != 0 { - return Err(if i == 1 { - Error::InvalidQ8Activation - } else { - Error::NonFiniteMmqOutput("mtp-kv-only") - }); - } - } - let mut append = Vec::new(); - append - .try_reserve_exact(input.rows * 2) - .map_err(|_| Error::HostAllocation)?; - let host = self.host_addresses()?; - for t in 0..input.rows { - Self::push( - &mut append, - 1, - 0, - [2, 4, 2], - [64, 1, 1], - vec![ - Arg::U64(self.address(0)?), - Arg::U64(self.address(1)?), - Arg::U64(self.address(2)?), - Arg::U64(self.address(3)?), - Arg::U64(self.address(4)?), - Arg::U64(self.sub(9, t * 16, 16)?), - Arg::U64(self.sub(6, t * 2048, 2048)?), - Arg::U64(self.sub(7, t * 2048, 2048)?), - Arg::I32(2), - Arg::I32(256), - Arg::I32(4), - Arg::U64(host[0]), - Arg::U64(host[1]), - Arg::U64(host[2]), - Arg::U64(host[3]), - ], - )?; - } - Self::push( - &mut append, - 1, - 3, - [64, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(self.address(2)?), - Arg::U64(self.address(3)?), - Arg::I32((self.slots * 32) as i32), - Arg::U64(self.sub(10, (4 + 2 * self.max_t) * 4, 4)?), - ], - )?; - self.current = None; // source pages and resident ring mutate only after invalidation - self.execute(w, append)?; - if self.flags()?[4 + 2 * self.max_t] != 0 { - return Err(Error::NonFiniteMmqOutput("mtp-int8-scale")); - } - for (p, runs) in changed.iter_mut().enumerate() { - self.read_encoded_page(p + first_page, runs)?; - } - for runs in changed { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); - } - let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { - origin: self.origin.clone(), - pages: Pages::from_vec(pages), - end, - checked: std::cell::Cell::new(false), - })); - self.current = Some(snapshot.clone()); - self.generation = generation; - Ok(CompletedMtpKvReplay { - owner: self, - snapshot, - _mixed: input, - _weights: weights, - first: input.first, - rows: input.rows, - }) - } - /// Literal Original dense-window INT8 split-K attention. No selected index, - /// clock resolver, prompt MMA or F16 intermediate pool stands in for the ring. - pub fn attend<'loan, 'buffers>( - &'loan mut self, - w: &mut NativeBatchWorkspace<'ctx>, - snapshot: &'loan MtpInt8Snapshot, - position: usize, - query: &'loan MtpOriginalQuery<'loan, 'buffers>, - ) -> Result> { - self.validate_snapshot(snapshot)?; - w.validate_context(self.context)?; - if position >= snapshot.0.end { - return Err(Error::InvalidQwenShape); - } - // Snapshot may contain the whole verified suffix. Its ring's extra4*S+64 - // cells cover every legal earlier query in that same completed replay. - let b1 = snapshot.0.end.div_ceil(4); - let oldest = (position + 1).saturating_sub(MTP_ORIGINAL_WINDOW); - if oldest / 4 < b1.saturating_sub(self.slots) { - return Err(Error::InvalidQwenShape); - } - let q = self.external(w, query.query, 24576)?; - self.restore(w, snapshot)?; - self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?; - let mut steps = [0u8; 16]; - for (i, v) in [position, position + 1, (position + 1) / 4, position + 1] - .into_iter() - .enumerate() - { - steps[i * 4..i * 4 + 4].copy_from_slice(&(v as i32).to_le_bytes()); - } - self.copy_from_physical(14, &steps)?; - let mut admission = Vec::new(); - self.finite(&mut admission, q, 6144, 0)?; - self.execute(w, admission)?; - if self.flags()?[0] != 0 { - return Err(Error::NonFiniteMmqOutput("mtp-query")); - } - let mut commands = Vec::new(); - commands - .try_reserve_exact(4) - .map_err(|_| Error::HostAllocation)?; - Self::push( - &mut commands, - 1, - 2, - [8, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(self.address(14)?), - Arg::I32(32768), - Arg::U64(self.address(13)?), - Arg::I64(32768), - ], - )?; - let pa = self.address(12)?; - let pm = self.sub(12, CHUNKS * 24 * 256 * 4, CHUNKS * 24 * 4)?; - let pl = self.sub(12, CHUNKS * 24 * 257 * 4, CHUNKS * 24 * 4)?; - Self::push( - &mut commands, - 2, - 1, - [CHUNKS as u32, 2, 1], - [256, 1, 1], - vec![ - Arg::U64(q), - Arg::U64(self.address(0)?), - Arg::U64(self.address(1)?), - Arg::U64(self.address(2)?), - Arg::U64(self.address(3)?), - Arg::U64(self.address(4)?), - Arg::U64(self.address(13)?), - Arg::U64(self.address(14)?), - Arg::I32(2), - Arg::I32(4), - Arg::F32(1.0 / 16.0), - Arg::U64(pa), - Arg::U64(pm), - Arg::U64(pl), - Arg::I32(CHUNKS as i32), - Arg::I32(32768), - Arg::I64(SCRATCH_FLOATS as i64), - ], - )?; - Self::push( - &mut commands, - 2, - 2, - [24, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(pa), - Arg::U64(pm), - Arg::U64(pl), - Arg::I32(CHUNKS as i32), - Arg::U64(self.address(11)?), - Arg::I64(SCRATCH_FLOATS as i64), - ], - )?; - self.finite(&mut commands, self.address(11)?, 6144, 1)?; - self.execute(w, commands)?; - if self.flags()?[1] != 0 { - return Err(Error::NonFiniteMmqOutput("mtp-int8-attention")); - } - Ok(CompletedMtpAttention { - owner: self, - _snapshot: snapshot, - _query: query, - }) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - fn close_inner(&mut self) -> Result<()> { - self.failed = true; - self.current = None; - let Some(mut physical) = self.physical.take() else { - return Ok(()); - }; - physical.active.set(false); - // Explicit close requires graph retirement first. Dropping this logical - // ring never frees allocations retained by a real graph resource token. - if Rc::strong_count(&physical) != 1 { - return Err(Error::InvalidQwenShape); - } - Rc::get_mut(&mut physical) - .ok_or(Error::InvalidQwenShape)? - .close_inner() - } -} -impl Drop for MtpOriginalInt8<'_> { - fn drop(&mut self) { - let _ = self.close_inner(); - } -} - -impl<'ctx> MtpOriginalInt8<'ctx> { - fn new_original_state( - c: &'ctx Context<'ctx>, - max_t: usize, - main: Rc>, - spans: [(usize, usize); 7], - prepared: ring_state::PreparedState<'ctx>, - ) -> Result { - let (slots, sizes) = layout(max_t)?; - if c.is_poisoned() { - return Err(Error::ContextPoisoned); - } - for ptx in [ - include_bytes!("mtp_original_tail.ptx").as_slice(), - include_bytes!("mtp_original_kv.ptx").as_slice(), - include_bytes!("qsa_native_decode.ptx").as_slice(), - ] { - if ptx.windows(8).any(|w| w == b"UNSEALED") { - return Err(Error::UnsupportedQwenOperation); - } - } - let origin = Rc::new(Origin); - let physical = Rc::new(PhysicalRing { - context: c, - origin: origin.clone(), - sizes, - buffers: std::array::from_fn(|_| None), - modules: std::array::from_fn(|_| None), - mapped: RefCell::new(None), - selected: None, - failed: Cell::new(false), - active: Cell::new(true), - }); - let mut o = Self { - context: c, - origin, - max_t, - slots, - sizes, - physical: Some(physical), - current: None, - failed: false, - generation: 0, - }; - let op = (|| { - let g = c.enter().inspect_err(|_| { - c.poison(); - c.retain_driver(); - })?; - let load = (|| { - for (i, (ptx, entries)) in [ - ( - include_bytes!("mtp_original_tail.ptx").as_slice(), - TAIL_ENTRIES, - ), - (include_bytes!("mtp_original_kv.ptx").as_slice(), KV_ENTRIES), - ( - include_bytes!("qsa_native_decode.ptx").as_slice(), - ATTN_ENTRIES, - ), - ] - .into_iter() - .enumerate() - { - o.physical_mut()?.modules[i] = Some(Module::load(ptx, entries)?); - } - Ok(()) - })(); - let pop = g.finish(); - if pop.is_err() { - o.poison(); - } - combine(load, pop)?; - let (selected, mapped) = ring_state::Selected::from_prepared(prepared, main, spans)?; - if selected.layout.resident { - o.slots = 65536; - for (i, n) in [134217728, 134217728, 4194304, 4194304, 262144] - .into_iter() - .enumerate() - { - o.sizes[i] = n; - o.physical_mut()?.sizes[i] = n; - } - } - o.physical_mut()?.selected = Some(selected); - *o.physical_mut()?.mapped.get_mut() = mapped; - let extras = o - .sizes - .into_iter() - .enumerate() - .filter(|(i, _)| !matches!(i,0..=9|12..=14)) - .try_fold(0usize, |a, (_, n)| { - a.checked_add(n).ok_or(Error::BudgetExceeded) - })?; - let need = extras.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if c.allocated_bytes() - .checked_add(need) - .is_none_or(|n| n > c.budget) - || c.memory_info()?.0 < need - { - return Err(Error::BudgetExceeded); - } - for (i, n) in o.sizes.into_iter().enumerate() { - if !matches!(i,0..=9|12..=14) { - o.physical_mut()?.buffers[i] = Some(c.allocate(n)?); - } - } - o.validate()?; - if c.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = op { - return combine(Err(e), o.close()); - } - Ok(o) - } - pub fn fully_resident(&self) -> Result { - self.validate()?; - Ok(self - .physical()? - .selected - .as_ref() - .is_some_and(|s| s.layout.resident)) - } - pub fn actual_pinned_host_bytes(&self) -> Result { - let p = self.physical()?; - let m = p.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?; - Ok((if p.selected.is_some() { 116 } else { 0 }) + m.as_ref().map_or(0, MappedOwner::bytes)) - } - fn host_addresses(&self) -> Result<[u64; 4]> { - if self.fully_resident()? { - return Ok([0; 4]); - } - let mapped = self.mapped()?; - let mut a = [0; 4]; - for (i, n) in HOST_RUNS.into_iter().enumerate() { - a[i] = mapped.address(HOST_OFFSETS[i], n)?; - } - Ok(a) - } - fn read_encoded_page(&self, page: usize, runs: &mut [Vec; 4]) -> Result<()> { - if self.fully_resident()? { - return self - .physical()? - .selected - .as_ref() - .ok_or(Error::ContextPoisoned)? - .read_page(page, runs); - } - let mapped = self.mapped()?; - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - if runs[i].len() != n { - return Err(Error::InvalidSize); - } - mapped.read_into(HOST_OFFSETS[i] + page * n, &mut runs[i])?; - } - Ok(()) - } - fn validate_original_main(&self, main: &Rc>) -> Result<()> { - if let Some(s) = &self.physical()?.selected { - if !s.same_main(main) { - return Err(Error::InvalidQwenShape); - } - } - Ok(()) - } - fn reject_state_alias(&self, b: &DeviceBuffer<'_>) -> Result<()> { - if let Some(s) = &self.physical()?.selected { - s.reject_state_alias(b)?; - } - Ok(()) - } - /// State+retained diagnostic owners only; main bank is counted by paired layout. - pub fn planned_original_state_device_bytes( - max_t: usize, - fully_resident: bool, - ) -> Result { - let (_, sizes) = layout(max_t)?; - sizes - .into_iter() - .enumerate() - .filter(|(i, _)| !matches!(i,0..=9|12..=14)) - .try_fold( - ring_state::StateLayout::new(max_t, fully_resident)?.bytes, - |a, (_, n)| a.checked_add(n).ok_or(Error::InvalidSize), - ) - } -} +//! Literal Original MTP INT8 ring and record_forward(full=false) attention tail. +//! Input/GR and runtime causal authority are separate genuine producer obligations. +//! No F16 ring, whole warm_step, prompt-attention, or host-float readiness substitute. +#[path = "mtp_original_int8_ffi.rs"] +#[allow(unsafe_code)] +mod abi; +#[path = "mtp_original_ring_state.rs"] +mod ring_state; +use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine}; +use abi::{Arg, Arguments, MappedOwner, Module}; +use std::{ + cell::{Cell, Ref, RefCell, RefMut}, + rc::Rc, +}; + +pub const MTP_ORIGINAL_WINDOW: usize = 32768; +/// The MTP drafter bank is FROZEN at the trained 262144-cell geometry (its mapped host image, page table and +/// ring layouts are literal). It is deliberately NOT derived from the serving context: +/// `validate_existing_int8_bank` refuses any other session geometry, and the runtime refuses the MTP modes for a +/// context past the trained one. Re-deriving and qualifying it is a separate piece of work. +pub const MTP_ORIGINAL_MAX_CELLS: usize = 262144; +pub const MTP_ORIGINAL_PINNED_HOST_BYTES: usize = 276825088; +pub const MTP_ORIGINAL_SNAPSHOT_PAYLOAD_BYTES: usize = 276824064; +const RESERVE: usize = 128 * 1024 * 1024; +const PAGE_BYTES: [usize; 4] = [2048, 2048, 64, 64]; +const HOST_RUNS: [usize; 4] = [134217728, 134217728, 4194304, 4194304]; +const HOST_OFFSETS: [usize; 4] = [0, 134217728, 268435456, 272629760]; +const CHUNKS: usize = 512; +const SCRATCH_FLOATS: usize = CHUNKS * 24 * (256 + 2); +const STATUS_WORDS: usize = 21; // four leading stages, two per real row, final scale scan +const TAIL_ENTRIES: &[&std::ffi::CStr] = &[ + c"mtp_original_quantize", + c"mtp_original_q80_1", + c"mtp_original_q80_2", + c"mtp_original_q80_3", + c"mtp_original_q80_4", + c"mtp_original_q80_5", + c"mtp_original_q80_6", + c"mtp_original_q80_7", + c"mtp_original_q80_8", + c"mtp_original_knorm", + c"mtp_original_krope", + c"mtp_original_finite", + c"mtp_original_q8_guard", +]; +const KV_ENTRIES: &[&std::ffi::CStr] = &[ + c"mtp_original_append", + c"mtp_original_ring_table", + c"mtp_original_window_ids", + c"mtp_original_encoded_guard", +]; +const ATTN_ENTRIES: &[&std::ffi::CStr] = &[ + c"leleka_qsa_prompt_guard", + c"leleka_qsa_decode_chunk", + c"leleka_qsa_decode_merge", + c"leleka_qsa_prompt_output_guard", +]; +struct Origin; +#[derive(Clone)] +pub struct MtpInt8OwnerId(Rc); +impl MtpInt8OwnerId { + pub fn same_owner(&self, other: &Self) -> bool { + Rc::ptr_eq(&self.0, &other.0) + } +} + +#[path = "mtp_original_logical_prefix.rs"] +mod logical_prefix; +pub use logical_prefix::OriginalMtpSkippedPrefix; +// The literal prefill producer is an MTP child because it borrows this +// owner's private ring/state types. Its public contracts are re-exported by +// the crate integration point below. +#[path = "mtp_original_prefill.rs"] +mod prefill; +pub(crate) use prefill::session_assets_sealed; +pub use prefill::{ + CompletedDraftKv, CompletedOriginalMtpDraft, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, + OriginalMtpDraftProgram, OriginalMtpDrafter, OriginalMtpEmbedding, OriginalMtpForwardProgram, + OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpPrefill, + OriginalMtpPrefillWeights, OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, + OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, + OriginalMtpStepOutput, +}; +/// `LELEKA_MTP_SNAPSHOT_MEMO=off`: scan every page of a snapshot on each `validate_snapshot` (the earlier behaviour; the A/B control). +fn snapshot_memo() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("LELEKA_MTP_SNAPSHOT_MEMO").is_ok_and(|v| v == "off" || v == "0")) +} +struct Page { + runs: [Box<[u8]>; 4], +} +/// The immutable page list of a snapshot, in chunks of `PAGES_PER_CHUNK` so that the next snapshot of a speculation round shares every +/// chunk the round did not touch: the page list is O(context / 4) long (65,536 pages at 256k) and the round changes its last few entries only. +#[derive(Clone)] +struct Pages { + chunks: Rc>>>>, + len: usize, +} +const PAGES_PER_CHUNK: usize = 256; +impl Pages { + fn empty() -> Self { + Self { chunks: Rc::new(Vec::new()), len: 0 } + } + fn from_vec(pages: Vec>) -> Self { + let len = pages.len(); + let chunks = pages.chunks(PAGES_PER_CHUNK).map(|c| Rc::new(c.to_vec())).collect(); + Self { chunks: Rc::new(chunks), len } + } + /// The first `keep` pages of `self` (`keep <= len`), then `tail`. Whole chunks inside `keep` are shared, not copied. + fn with_tail(&self, keep: usize, tail: Vec>) -> Self { + let keep = keep.min(self.len); + let whole = keep / PAGES_PER_CHUNK; + let mut chunks: Vec>>> = Vec::with_capacity(whole + 1 + tail.len() / PAGES_PER_CHUNK); + chunks.extend(self.chunks[..whole].iter().cloned()); + let mut open: Vec> = Vec::with_capacity(PAGES_PER_CHUNK); + if keep % PAGES_PER_CHUNK != 0 { + open.extend(self.chunks[whole][..keep % PAGES_PER_CHUNK].iter().cloned()); + } + let len = keep + tail.len(); + for page in tail { + open.push(page); + if open.len() == PAGES_PER_CHUNK { + chunks.push(Rc::new(std::mem::replace(&mut open, Vec::with_capacity(PAGES_PER_CHUNK)))); + } + } + if !open.is_empty() { + chunks.push(Rc::new(open)); + } + Self { chunks: Rc::new(chunks), len } + } + fn len(&self) -> usize { + self.len + } + fn get(&self, p: usize) -> Option<&Rc> { + if p >= self.len { + return None; + } + self.chunks.get(p / PAGES_PER_CHUNK)?.get(p % PAGES_PER_CHUNK) + } + fn iter(&self) -> impl Iterator> { + self.chunks.iter().flat_map(|c| c.iter()) + } +} +struct Snapshot { + origin: Rc, + pages: Pages, + end: usize, + /// The pages up to `end` were checked to have the exact run sizes (`validate_snapshot`). The snapshot is immutable, so the + /// answer cannot change; the scan is O(context / 4) and ran several times per speculation round. + checked: Cell, +} +/// Immutable actual encoded bytes; runtime binds these to its genuine MTP epoch. +#[derive(Clone)] +pub struct MtpInt8Snapshot(Rc); +impl MtpInt8Snapshot { + pub fn owner_id(&self) -> MtpInt8OwnerId { + MtpInt8OwnerId(self.0.origin.clone()) + } + pub fn next_position(&self) -> usize { + self.0.end + } + pub fn encoded_bytes(&self) -> usize { + self.0.pages.len() * 4224 + } + pub fn metadata_bytes(&self) -> usize { + std::mem::size_of::() + + std::mem::size_of::() + + 8 * std::mem::size_of::() + + self.0.pages.len() + * (std::mem::size_of::>() + + std::mem::size_of::() + + 2 * std::mem::size_of::()) + } +} +/// Created only inside the actual driver input+fused-GR producer integration. +/// Public constructors accepting arbitrary floats or a caller readiness bit do not exist. +pub struct MtpOriginalMixed<'loan, 'buffers> { + mixed: &'loan DeviceBuffer<'buffers>, + first: usize, + rows: usize, +} +impl<'loan, 'buffers> MtpOriginalMixed<'loan, 'buffers> { + pub(crate) fn from_completed_gr( + c: &Context<'_>, + mixed: &'loan DeviceBuffer<'buffers>, + first: usize, + rows: usize, + ) -> Result { + rows_range(first, rows, 8)?; + checked(c, mixed, rows * 2560 * 4)?; + Ok(Self { mixed, first, rows }) + } + pub fn rows(&self) -> usize { + self.rows + } + pub fn first_position(&self) -> usize { + self.first + } +} +/// Real native normalized/RoPE query, minted by the actual scalar full-draft producer. +pub struct MtpOriginalQuery<'loan, 'buffers> { + query: &'loan DeviceBuffer<'buffers>, +} +impl<'loan, 'buffers> MtpOriginalQuery<'loan, 'buffers> { + pub(crate) fn from_completed_native( + c: &Context<'_>, + query: &'loan DeviceBuffer<'buffers>, + ) -> Result { + checked(c, query, 6144 * 4)?; + Ok(Self { query }) + } +} +/// Replay completion retains actual ring and immutable whole-weight/input loans. +pub struct CompletedMtpKvReplay<'loan, 'ctx, 'buffers, 'weights> { + owner: &'loan mut MtpOriginalInt8<'ctx>, + snapshot: MtpInt8Snapshot, + _mixed: &'loan MtpOriginalMixed<'loan, 'buffers>, + _weights: [&'loan DeviceBuffer<'weights>; 3], + first: usize, + rows: usize, +} +impl CompletedMtpKvReplay<'_, '_, '_, '_> { + pub fn rows(&self) -> usize { + self.rows + } + pub fn final_snapshot(&self) -> &MtpInt8Snapshot { + &self.snapshot + } + /// End can only be derived from a real row of this completed append. + pub fn snapshot_after(&self, row: usize) -> Result { + self.owner.validate()?; + if row >= self.rows { + return Err(Error::InvalidQwenShape); + } + Ok(MtpInt8Snapshot(Rc::new(Snapshot { + origin: self.snapshot.0.origin.clone(), + pages: self.snapshot.0.pages.clone(), + end: self.first + row + 1, + checked: std::cell::Cell::new(self.snapshot.0.checked.get()), + }))) + } + pub fn into_final_snapshot(self) -> MtpInt8Snapshot { + self.snapshot + } +} +pub struct CompletedMtpAttention<'loan, 'ctx, 'buffers> { + owner: &'loan mut MtpOriginalInt8<'ctx>, + _snapshot: &'loan MtpInt8Snapshot, + _query: &'loan MtpOriginalQuery<'loan, 'buffers>, +} +impl CompletedMtpAttention<'_, '_, '_> { + pub fn with_output(&self, f: impl FnOnce(&DeviceBuffer<'_>) -> Result) -> Result { + self.owner.validate()?; + f(self.owner.buffer(11)?) + } + pub fn into_values(self) -> Result> { + self.owner.validate()?; + let bytes = self.owner.buffer(11)?.copy_to_owned(6144 * 4)?; + let mut out = Vec::new(); + out.try_reserve_exact(6144) + .map_err(|_| Error::HostAllocation)?; + for x in bytes.chunks_exact(4) { + out.push(f32::from_le_bytes( + x.try_into().map_err(|_| Error::InvalidSize)?, + )); + } + Ok(out.into_boxed_slice()) + } +} +enum Command { + Kernel { + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + args: Arguments, + }, + Copy { + dst: u64, + src: u64, + bytes: usize, + }, +} +/// Actual model-lifetime physical allocations. Causal current/generation lives +/// only on MtpOriginalInt8. Graph resources retain this Rc without a RefCell loan. +/// Only bounded CPU mapped-page accesses take short exclusive mapped borrows. +struct PhysicalRing<'ctx> { + context: &'ctx Context<'ctx>, + origin: Rc, + sizes: [usize; 15], + buffers: [Option>; 15], + modules: [Option; 3], + mapped: RefCell>, + selected: Option>, + failed: Cell, + active: Cell, +} +/// Opaque genuine physical retention minted only by this ring. No caller pointer, +/// bytes or ready marker can construct a token. It is not a causal state proof. +pub struct MtpOriginalRingResources<'ctx> { + physical: Rc>, +} +impl Clone for MtpOriginalRingResources<'_> { + fn clone(&self) -> Self { + Self { + physical: Rc::clone(&self.physical), + } + } +} +impl MtpOriginalRingResources<'_> { + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + self.physical.validate_context(c) + } + pub fn owner_id(&self) -> MtpInt8OwnerId { + MtpInt8OwnerId(self.physical.origin.clone()) + } + pub fn allocated_bytes(&self) -> usize { + self.physical + .buffers + .iter() + .flatten() + .map(|b| b.bytes) + .sum::() + + self + .physical + .selected + .as_ref() + .map_or(0, |s| s.unique_bytes()) + } + pub fn metadata_bytes(&self) -> usize { + std::mem::size_of::>() + + 2 * std::mem::size_of::() + + std::mem::size_of::() + } +} +impl PhysicalRing<'_> { + fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + if !self.active.get() + || self.failed.get() + || c.is_poisoned() + || c.handle.is_none() + || self.modules.iter().any(Option::is_none) + || (self.selected.is_none() + && self + .mapped + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .is_none()) + { + return Err(Error::ContextPoisoned); + } + for (i, b) in self.buffers.iter().enumerate() { + if let Some(b) = b { + checked(c, b, self.sizes[i])?; + } else if !self.selected.as_ref().is_some_and(|s| s.provides(i)) { + return Err(Error::ContextPoisoned); + } + } + if let Some(s) = &self.selected { + s.validate(c)?; + } + Ok(()) + } + fn close_inner(&mut self) -> Result<()> { + self.active.set(false); + self.failed.set(true); + let mut result = Ok(()); + // Same original module -> mapped -> device order and primary arbitration. + // A poisoned Context retains every actual physical owner and its charge. + for m in &mut self.modules { + if let Some(module) = m.take() { + let close = if self.context.is_poisoned() { + std::mem::forget(module); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine(module.close(), g.finish()), + Err(e) => { + self.context.poison(); + std::mem::forget(module); + Err(e) + } + } + }; + if close.is_err() { + self.context.poison(); + } + result = combine(result, close); + } + } + if let Some(mut mapped) = self.mapped.get_mut().take() { + let close = if self.context.is_poisoned() { + std::mem::forget(mapped); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => { + let op = mapped.close(); + let pop = g.finish(); + combine(op, pop) + } + Err(e) => { + self.context.poison(); + std::mem::forget(mapped); + Err(e) + } + } + }; + if close.is_err() { + self.context.poison(); + } + result = combine(result, close); + } + if let Some(mut s) = self.selected.take() { + result = combine(result, s.close()); + } + for b in &mut self.buffers { + if let Some(buffer) = b.take() { + let close = if self.context.is_poisoned() { + std::mem::forget(buffer); + Err(Error::ContextPoisoned) + } else { + buffer.release() + }; + if close.is_err() { + self.context.poison(); + } + result = combine(result, close); + } + } + if self.context.is_poisoned() { + self.context.retain_driver(); + } + result + } +} +impl Drop for PhysicalRing<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} +/// One Context-affine model owner. The literal selected plain INT8, unrotated +/// 32K-window profile is explicit. Other Original formats/options remain separate. +pub struct MtpOriginalInt8<'ctx> { + context: &'ctx Context<'ctx>, + origin: Rc, + max_t: usize, + slots: usize, + sizes: [usize; 15], + physical: Option>>, + current: Option, + failed: bool, + generation: u64, +} +fn zero_bytes(n: usize) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| Error::HostAllocation)?; + v.resize(n, 0); + Ok(v) +} +fn checked(c: &Context<'_>, b: &DeviceBuffer<'_>, n: usize) -> Result { + if !std::ptr::eq(c, b.context) { + return Err(Error::ContextMismatch); + } + if b.bytes != n { + return Err(Error::InvalidQwenShape); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(n, 4)?; + Ok(h.qwen_address()) +} +fn rows_range(first: usize, rows: usize, max_t: usize) -> Result<()> { + if !(1..=max_t).contains(&rows) + || first + .checked_add(rows) + .is_none_or(|e| e > MTP_ORIGINAL_MAX_CELLS) + { + return Err(Error::InvalidQwenShape); + } + Ok(()) +} +fn layout(t: usize) -> Result<(usize, [usize; 15])> { + if !(1..=8).contains(&t) { + return Err(Error::InvalidQwenShape); + } + let slots = (MTP_ORIGINAL_WINDOW + 4 * t + 64).div_ceil(4); + Ok(( + slots, + [ + slots * 2048, + slots * 2048, + slots * 64, + slots * 64, + 65536 * 4, + t * 2880, + t * 2048, + t * 2048, + t * 24 * 4, + t * 4 * 4, + STATUS_WORDS * 4, + 6144 * 4, + SCRATCH_FLOATS * 4, + MTP_ORIGINAL_WINDOW * 4, + 16, + ], + )) +} +impl Context<'_> { + pub fn mtp_original_int8(&self, max_t: usize) -> Result> { + MtpOriginalInt8::new(self, max_t) + } +} +impl<'ctx> MtpOriginalInt8<'ctx> { + pub fn planned_device_bytes(max_t: usize) -> Result { + Ok(layout(max_t)?.1.into_iter().sum()) + } + pub fn pinned_host_bytes() -> usize { + MTP_ORIGINAL_PINNED_HOST_BYTES + } + pub fn max_snapshot_payload_bytes() -> usize { + MTP_ORIGINAL_SNAPSHOT_PAYLOAD_BYTES + } + pub fn max_snapshot_metadata_bytes() -> usize { + std::mem::size_of::() + + std::mem::size_of::() + + 8 * std::mem::size_of::() + + 65536 + * (std::mem::size_of::>() + + std::mem::size_of::() + + 2 * std::mem::size_of::()) + } + fn new(c: &'ctx Context<'ctx>, max_t: usize) -> Result { + let (slots, sizes) = layout(max_t)?; + if c.is_poisoned() || c.handle.is_none() { + return Err(Error::ContextPoisoned); + } + // Refuse placeholders before any host or device owner allocation. + for ptx in [ + include_bytes!("mtp_original_tail.ptx").as_slice(), + include_bytes!("mtp_original_kv.ptx").as_slice(), + ] { + if ptx.windows(8).any(|w| w == b"UNSEALED") { + return Err(Error::UnsupportedQwenOperation); + } + } + let needed = sizes + .into_iter() + .sum::() + .checked_add(RESERVE) + .ok_or(Error::BudgetExceeded)?; + if c.allocated_bytes() + .checked_add(needed) + .is_none_or(|n| n > c.budget) + || c.memory_info()?.0 < needed + { + return Err(Error::BudgetExceeded); + } + let origin = Rc::new(Origin); + let physical = Rc::new(PhysicalRing { + context: c, + origin: origin.clone(), + sizes, + buffers: std::array::from_fn(|_| None), + modules: std::array::from_fn(|_| None), + mapped: RefCell::new(None), + selected: None, + failed: Cell::new(false), + active: Cell::new(true), + }); + let mut o = Self { + context: c, + origin, + max_t, + slots, + sizes, + physical: Some(physical), + current: None, + failed: false, + generation: 0, + }; + let operation = (|| { + let guard = c.enter().inspect_err(|_| { + c.poison(); + c.retain_driver(); + })?; + let load = (|| { + o.physical_mut()?.modules[0] = Some(Module::load( + include_bytes!("mtp_original_tail.ptx"), + TAIL_ENTRIES, + )?); + o.physical_mut()?.modules[1] = Some(Module::load( + include_bytes!("mtp_original_kv.ptx"), + KV_ENTRIES, + )?); + o.physical_mut()?.modules[2] = Some(Module::load( + include_bytes!("qsa_native_decode.ptx"), + ATTN_ENTRIES, + )?); + *o.physical_mut()?.mapped.get_mut() = Some(MappedOwner::new()?); + if o.physical()? + .mapped + .borrow() + .as_ref() + .is_none_or(|m| m.bytes() != MTP_ORIGINAL_PINNED_HOST_BYTES) + { + return Err(Error::InvalidSize); + } + Ok(()) + })(); + let pop = guard.finish(); + if pop.is_err() { + o.poison(); + } + combine(load, pop)?; + for (i, n) in sizes.into_iter().enumerate() { + o.physical_mut()?.buffers[i] = Some(c.allocate(n)?); + } + // Real initialized pools; no reader ever names an unwritten logical cell. + for i in 0..4 { + o.copy_from_physical(i, &zero_bytes(sizes[i])?)?; + } + let mut table = zero_bytes(65536 * 4)?; + for (p, b) in table.chunks_exact_mut(4).enumerate() { + b.copy_from_slice(&((p % slots) as i32).to_le_bytes()); + } + o.copy_from_physical(4, &table)?; + if c.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = operation { + return combine(Err(e), o.close()); + } + Ok(o) + } + fn physical(&self) -> Result<&PhysicalRing<'ctx>> { + self.physical.as_deref().ok_or(Error::ContextPoisoned) + } + fn physical_mut(&mut self) -> Result<&mut PhysicalRing<'ctx>> { + Rc::get_mut(self.physical.as_mut().ok_or(Error::ContextPoisoned)?) + .ok_or(Error::InvalidQwenShape) + } + fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { + self.physical()? + .buffers + .get(i) + .and_then(Option::as_ref) + .ok_or(Error::ContextPoisoned) + } + fn buffers(&self) -> Result<&[Option>; 15]> { + Ok(&self.physical()?.buffers) + } + fn mapped(&self) -> Result> { + Ref::filter_map( + self.physical()? + .mapped + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)?, + Option::as_ref, + ) + .map_err(|_| Error::ContextPoisoned) + } + fn mapped_mut(&self) -> Result> { + RefMut::filter_map( + self.physical()? + .mapped + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)?, + Option::as_mut, + ) + .map_err(|_| Error::ContextPoisoned) + } + fn copy_from_physical(&self, i: usize, input: &[u8]) -> Result<()> { + if let Some(s) = &self.physical()?.selected { + if s.provides(i) { + return s.copy_from(i, 0, input); + } + } + let b = self.buffer(i)?; + let mut staging = b.staging(input.len())?; + staging.copy_from_slice(input); + b.copy_staged(staging, false).map(|_| ()) + } + pub(crate) fn retain_physical_resources(&self) -> Result> { + self.validate()?; + Ok(MtpOriginalRingResources { + physical: Rc::clone(self.physical.as_ref().ok_or(Error::ContextPoisoned)?), + }) + } + pub fn physical_metadata_bytes() -> usize { + std::mem::size_of::>() + 2 * std::mem::size_of::() + } + + fn address(&self, i: usize) -> Result { + if let Some(s) = &self.physical()?.selected { + if s.provides(i) { + return Ok(s.span(i, 0, self.sizes[i])?.qwen_address()); + } + } + checked(self.context, self.buffer(i)?, self.sizes[i]) + } + fn sub(&self, i: usize, o: usize, n: usize) -> Result { + if let Some(s) = &self.physical()?.selected { + if s.provides(i) { + return Ok(s.span(i, o, n)?.qwen_address()); + } + } + Ok(self + .buffer(i)? + .handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(self.sizes[i], o, n)? + .qwen_address()) + } + pub fn allocated_bytes(&self) -> usize { + self.physical.as_ref().map_or(0, |p| { + p.buffers.iter().flatten().map(|b| b.bytes).sum::() + + p.selected.as_ref().map_or(0, |s| s.unique_bytes()) + }) + } + pub fn is_failed(&self) -> bool { + self.failed + || self.context.is_poisoned() + || self.context.handle.is_none() + || self + .physical + .as_ref() + .is_none_or(|p| p.failed.get() || !p.active.get()) + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + self.validate() + } + fn validate(&self) -> Result<()> { + if self.is_failed() { + return Err(Error::ContextPoisoned); + } + self.physical()?.validate_context(self.context)?; + for i in 0..15 { + if self + .physical()? + .selected + .as_ref() + .is_some_and(|s| s.provides(i)) + { + continue; + } + let b = self.buffer(i)?; + checked(self.context, b, self.sizes[i])?; + if let Some(s) = &self.physical()?.selected { + s.reject_state_alias(b)?; + s.reject_main_alias(b)?; + } + for j in 0..i { + if self + .physical()? + .selected + .as_ref() + .is_some_and(|s| s.provides(j)) + { + continue; + } + let other = self.buffer(j)?; + if b.handle.ok_or(Error::ContextPoisoned)?.overlaps( + b.bytes, + other.handle.ok_or(Error::ContextPoisoned)?, + other.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + } + if self.context.allocated_bytes() > self.context.budget { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + fn external( + &self, + w: &NativeBatchWorkspace<'ctx>, + b: &DeviceBuffer<'_>, + n: usize, + ) -> Result { + let addr = checked(self.context, b, n)?; + self.reject_state_alias(b)?; + if self + .physical()? + .mapped + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .is_some() + { + let mapped = self.mapped()?; + let ma = mapped.address(0, MTP_ORIGINAL_PINNED_HOST_BYTES)?; + if addr < ma + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 && ma < addr + n as u64 { + return Err(Error::OutputAliasesInput); + } + } + if let Some(s) = &self.physical()?.selected { + s.reject_main_alias(b)?; + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + w.reject_alias(h, n)?; + for own in self.buffers()?.iter().flatten() { + if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { + return Err(Error::OutputAliasesInput); + } + } + Ok(addr) + } + pub fn empty_snapshot(&self) -> Result { + self.validate()?; + Ok(MtpInt8Snapshot(Rc::new(Snapshot { + origin: self.origin.clone(), + pages: Pages::empty(), + end: 0, + checked: std::cell::Cell::new(true), + }))) + } + pub fn validate_snapshot(&self, s: &MtpInt8Snapshot) -> Result<()> { + self.validate()?; + if !Rc::ptr_eq(&self.origin, &s.0.origin) + || s.0.end > MTP_ORIGINAL_MAX_CELLS + || s.0.pages.len() < s.0.end.div_ceil(4) + { + return Err(Error::InvalidQwenShape); + } + if s.0.checked.get() && snapshot_memo() { + return Ok(()); + } + for p in s.0.pages.iter().take(s.0.end.div_ceil(4)) { + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + if p.runs[i].len() != n { + return Err(Error::InvalidSize); + } + } + } + s.0.checked.set(true); + Ok(()) + } + fn poison(&mut self) { + self.failed = true; + self.current = None; + if let Some(p) = &self.physical { + p.failed.set(true); + } + self.context.poison(); + self.context.retain_driver(); + } + fn execute( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + mut commands: Vec, + ) -> Result<()> { + self.validate()?; + w.validate_context(self.context)?; + let blas = w.blas()?; + let stream = blas.stream(); + let modules = &self.physical()?.modules; + let g = match self.context.enter() { + Ok(g) => g, + Err(e) => { + self.poison(); + w.mark_failed(); + return Err(e); + } + }; + // Inputs may be produced on Original default stream. This confirmed dependency + // precedes the model-owned nonblocking stream, never a guessed ready flag. + let mut op = self.context.driver.api.synchronize(); + if op.is_ok() { + for command in &mut commands { + let result = match command { + Command::Kernel { + asset, + index, + grid, + block, + args, + } => modules[*asset] + .as_ref() + .map_or(Err(Error::ContextPoisoned), |m| { + m.launch(*index, *grid, *block, 0, stream, args) + }), + Command::Copy { dst, src, bytes } => modules[1] + .as_ref() + .map_or(Err(Error::ContextPoisoned), |m| { + m.copy(*dst, *src, *bytes, stream) + }), + }; + if let Err(e) = result { + op = Err(e); + break; + } + } + } + let sync = blas.synchronize(); + let pop = g.finish(); + let uncertain = sync.is_err() || pop.is_err(); + if uncertain { + std::mem::forget(commands); + } + if op.is_err() || uncertain { + self.poison(); + w.mark_failed(); + } + combine(combine(op, sync), pop) + } + fn push( + commands: &mut Vec, + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + values: Vec, + ) -> Result<()> { + commands.try_reserve(1).map_err(|_| Error::HostAllocation)?; + commands.push(Command::Kernel { + asset, + index, + grid, + block, + args: Arguments::new(values)?, + }); + Ok(()) + } + fn finite(&self, commands: &mut Vec, a: u64, n: usize, status: usize) -> Result<()> { + Self::push( + commands, + 0, + 11, + [64, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(a), + Arg::I32(n as i32), + Arg::U64(self.sub(10, status * 4, 4)?), + ], + ) + } + fn flags(&mut self) -> Result<[u32; STATUS_WORDS]> { + let b = self.buffer(10)?.copy_to_owned(STATUS_WORDS * 4)?; + let mut s = [0; STATUS_WORDS]; + for (i, v) in b.chunks_exact(4).enumerate() { + s[i] = u32::from_le_bytes(v.try_into().map_err(|_| Error::InvalidSize)?); + if s[i] > 1 { + self.poison(); + return Err(Error::InvalidDriverValue("MTP finite flags")); + } + } + Ok(s) + } + /// Restore real immutable host pages, then exact Original modulo ring blocks. + /// The current witness is invalidated BEFORE any write; valid-end guards prevent + /// O(1) future-backing pages from incorrectly skipping rematerialization. + pub fn restore( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + s: &MtpInt8Snapshot, + ) -> Result<()> { + self.validate_snapshot(s)?; + w.validate_context(self.context)?; + self.generation = self + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + if self + .current + .as_ref() + .is_some_and(|old| Rc::ptr_eq(&old.0, &s.0)) + { + return Ok(()); + } + let previous = self.current.take(); + if self.fully_resident()? { + // Canonical snapshots remain genuine; restore overwritten accepted pages + // to the same identity cells before publishing the restored witness. + for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { + if previous.as_ref().is_some_and(|old| { + p < old.0.end.div_ceil(4) + && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) + }) { + continue; + } + let state = self + .physical()? + .selected + .as_ref() + .ok_or(Error::ContextPoisoned)?; + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + state.copy_from(i, p * n, &page.runs[i])?; + } + } + self.current = Some(s.clone()); + return Ok(()); + } + let mut mapped = self.mapped_mut()?; + for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { + if previous.as_ref().is_some_and(|old| { + p < old.0.end.div_ceil(4) && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) + }) { + continue; + } + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + mapped.write(HOST_OFFSETS[i] + p * n, &page.runs[i])?; + } + } + drop(mapped); + let b1 = s.0.end.div_ceil(4); + let b0 = b1.saturating_sub(self.slots); + let mut commands = Vec::new(); + commands + .try_reserve_exact(8) + .map_err(|_| Error::HostAllocation)?; + let mut b = b0; + while b < b1 { + let slot = b % self.slots; + let run = (b1 - b).min(self.slots - slot); + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + commands.push(Command::Copy { + dst: self.sub(i, slot * n, run * n)?, + src: self.mapped()?.address(HOST_OFFSETS[i] + b * n, run * n)?, + bytes: run * n, + }); + } + b += run; + } + if !commands.is_empty() { + self.execute(w, commands)?; + } + self.current = Some(s.clone()); + Ok(()) + } + /// Exact attention tail of record_forward(false). Real input+GR has already + /// produced this opaque mixed owner; no full MLP/head work is performed here. + pub fn record_kv_only<'loan, 'buffers, 'weights>( + &'loan mut self, + w: &mut NativeBatchWorkspace<'ctx>, + prior: &MtpInt8Snapshot, + input: &'loan MtpOriginalMixed<'loan, 'buffers>, + weights: [&'loan DeviceBuffer<'weights>; 3], + ) -> Result> { + self.validate_snapshot(prior)?; + w.validate_context(self.context)?; + rows_range(input.first, input.rows, self.max_t)?; + if input.first > prior.0.end { + return Err(Error::InvalidQwenShape); + } + let mixed = self.external(w, input.mixed, input.rows * 10240)?; + let wk = self.external(w, weights[0], 512 * 80 * 34)?; + let wv = self.external(w, weights[1], 512 * 80 * 34)?; + let gamma = self.external(w, weights[2], 256 * 4)?; + let spans = [ + ( + input.mixed.handle.ok_or(Error::ContextPoisoned)?, + input.mixed.bytes, + ), + ( + weights[0].handle.ok_or(Error::ContextPoisoned)?, + weights[0].bytes, + ), + ( + weights[1].handle.ok_or(Error::ContextPoisoned)?, + weights[1].bytes, + ), + ( + weights[2].handle.ok_or(Error::ContextPoisoned)?, + weights[2].bytes, + ), + ]; + for (i, (a, an)) in spans.iter().enumerate() { + for (b, bn) in spans.iter().take(i) { + let exact = a.qwen_address() == b.qwen_address() && an == bn; + if !exact && a.overlaps(*an, *b, *bn) { + return Err(Error::OutputAliasesInput); + } + } + } + let generation = self + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + let end = input.first + input.rows; + let n_pages = end.div_ceil(4); + let first_page = input.first / 4; + // All new host ownership is fallibly allocated before the first command. + let mut pages = Vec::new(); + pages + .try_reserve_exact(n_pages) + .map_err(|_| Error::HostAllocation)?; + for page in prior.0.pages.iter().take(first_page) { + pages.push(page.clone()); + } + let mut changed = Vec::new(); + changed + .try_reserve_exact(n_pages - first_page) + .map_err(|_| Error::HostAllocation)?; + for p in first_page..n_pages { + let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + runs[i] = zero_bytes(n)?; + if let Some(old) = prior.0.pages.get(p) { + runs[i].copy_from_slice(&old.runs[i]); + } + } + changed.push(runs); + } + let mut pos = zero_bytes(self.sizes[8])?; + let mut steps = zero_bytes(self.sizes[9])?; + for t in 0..input.rows { + let p = input.first + t; + for h in 0..24 { + pos[(t * 24 + h) * 4..(t * 24 + h + 1) * 4] + .copy_from_slice(&(p as i32).to_le_bytes()); + } + for (i, v) in [p, p + 1, (p + 1) / 4, p + 1].into_iter().enumerate() { + steps[(t * 4 + i) * 4..(t * 4 + i + 1) * 4] + .copy_from_slice(&(v as i32).to_le_bytes()); + } + } + // The real mixed producer supplies the rewind position. Restoring the + // longer prior's ring would keep future blocks after a shorter replay. + // This private prefix is bounded by that genuine prior, never caller-minted. + let replay_prior = if input.first == prior.0.end { + prior.clone() + } else { + MtpInt8Snapshot(Rc::new(Snapshot { + origin: prior.0.origin.clone(), + pages: prior.0.pages.clone(), + end: input.first, + checked: std::cell::Cell::new(prior.0.checked.get()), + })) + }; + self.restore(w, &replay_prior)?; + self.copy_from_physical(8, &pos)?; + self.copy_from_physical(9, &steps)?; + self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?; + let mut commands = Vec::new(); + commands + .try_reserve_exact(32 + input.rows * 5) + .map_err(|_| Error::HostAllocation)?; + self.finite(&mut commands, mixed, input.rows * 2560, 0)?; + Self::push( + &mut commands, + 0, + 0, + [(input.rows * 2560).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(mixed), + Arg::U64(self.address(5)?), + Arg::I32((input.rows * 2560) as i32), + ], + )?; + Self::push( + &mut commands, + 0, + 12, + [64, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(self.address(5)?), + Arg::I32((input.rows * 80) as i32), + Arg::U64(self.sub(10, 4, 4)?), + ], + )?; + for (weight, out, status) in [(wk, 6, 2), (wv, 7, 3)] { + Self::push( + &mut commands, + 0, + input.rows, + [512, 1, 1], + [32, 4, 1], + vec![ + Arg::U64(weight), + Arg::U64(self.address(5)?), + Arg::U64(self.address(out)?), + Arg::I32(2560), + Arg::I32(512), + ], + )?; + self.finite(&mut commands, self.address(out)?, input.rows * 512, status)?; + } + for t in 0..input.rows { + let k = self.sub(6, t * 2048, 2048)?; + Self::push( + &mut commands, + 0, + 9, + [2, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(k), + Arg::U64(gamma), + Arg::U64(k), + Arg::I32(256), + Arg::F32(1.0e-6), + ], + )?; + self.finite(&mut commands, k, 512, 4 + 2 * t)?; + Self::push( + &mut commands, + 0, + 10, + [1, 2, 1], + [128, 1, 1], + vec![ + Arg::U64(k), + Arg::U64(k), + Arg::I32(2), + Arg::I32(256), + Arg::F32(crate::qsa_index_ffi::theta()), + Arg::U64(self.sub(8, t * 96, 8)?), + ], + )?; + self.finite(&mut commands, k, 512, 5 + 2 * t)?; + } + // First failed upstream full scan/quant wins. No host/ring write before + // successful numeric admission of all real K/V rows. + self.execute(w, commands)?; + let flags = self.flags()?; + for (i, v) in flags.iter().enumerate().take(4 + 2 * input.rows) { + if *v != 0 { + return Err(if i == 1 { + Error::InvalidQ8Activation + } else { + Error::NonFiniteMmqOutput("mtp-kv-only") + }); + } + } + let mut append = Vec::new(); + append + .try_reserve_exact(input.rows * 2) + .map_err(|_| Error::HostAllocation)?; + let host = self.host_addresses()?; + for t in 0..input.rows { + Self::push( + &mut append, + 1, + 0, + [2, 4, 2], + [64, 1, 1], + vec![ + Arg::U64(self.address(0)?), + Arg::U64(self.address(1)?), + Arg::U64(self.address(2)?), + Arg::U64(self.address(3)?), + Arg::U64(self.address(4)?), + Arg::U64(self.sub(9, t * 16, 16)?), + Arg::U64(self.sub(6, t * 2048, 2048)?), + Arg::U64(self.sub(7, t * 2048, 2048)?), + Arg::I32(2), + Arg::I32(256), + Arg::I32(4), + Arg::U64(host[0]), + Arg::U64(host[1]), + Arg::U64(host[2]), + Arg::U64(host[3]), + ], + )?; + } + Self::push( + &mut append, + 1, + 3, + [64, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(self.address(2)?), + Arg::U64(self.address(3)?), + Arg::I32((self.slots * 32) as i32), + Arg::U64(self.sub(10, (4 + 2 * self.max_t) * 4, 4)?), + ], + )?; + self.current = None; // source pages and resident ring mutate only after invalidation + self.execute(w, append)?; + if self.flags()?[4 + 2 * self.max_t] != 0 { + return Err(Error::NonFiniteMmqOutput("mtp-int8-scale")); + } + for (p, runs) in changed.iter_mut().enumerate() { + self.read_encoded_page(p + first_page, runs)?; + } + for runs in changed { + pages.push(Rc::new(Page { + runs: runs.map(Vec::into_boxed_slice), + })); + } + let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { + origin: self.origin.clone(), + pages: Pages::from_vec(pages), + end, + checked: std::cell::Cell::new(false), + })); + self.current = Some(snapshot.clone()); + self.generation = generation; + Ok(CompletedMtpKvReplay { + owner: self, + snapshot, + _mixed: input, + _weights: weights, + first: input.first, + rows: input.rows, + }) + } + /// Literal Original dense-window INT8 split-K attention. No selected index, + /// clock resolver, prompt MMA or F16 intermediate pool stands in for the ring. + pub fn attend<'loan, 'buffers>( + &'loan mut self, + w: &mut NativeBatchWorkspace<'ctx>, + snapshot: &'loan MtpInt8Snapshot, + position: usize, + query: &'loan MtpOriginalQuery<'loan, 'buffers>, + ) -> Result> { + self.validate_snapshot(snapshot)?; + w.validate_context(self.context)?; + if position >= snapshot.0.end { + return Err(Error::InvalidQwenShape); + } + // Snapshot may contain the whole verified suffix. Its ring's extra4*S+64 + // cells cover every legal earlier query in that same completed replay. + let b1 = snapshot.0.end.div_ceil(4); + let oldest = (position + 1).saturating_sub(MTP_ORIGINAL_WINDOW); + if oldest / 4 < b1.saturating_sub(self.slots) { + return Err(Error::InvalidQwenShape); + } + let q = self.external(w, query.query, 24576)?; + self.restore(w, snapshot)?; + self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?; + let mut steps = [0u8; 16]; + for (i, v) in [position, position + 1, (position + 1) / 4, position + 1] + .into_iter() + .enumerate() + { + steps[i * 4..i * 4 + 4].copy_from_slice(&(v as i32).to_le_bytes()); + } + self.copy_from_physical(14, &steps)?; + let mut admission = Vec::new(); + self.finite(&mut admission, q, 6144, 0)?; + self.execute(w, admission)?; + if self.flags()?[0] != 0 { + return Err(Error::NonFiniteMmqOutput("mtp-query")); + } + let mut commands = Vec::new(); + commands + .try_reserve_exact(4) + .map_err(|_| Error::HostAllocation)?; + Self::push( + &mut commands, + 1, + 2, + [8, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(self.address(14)?), + Arg::I32(32768), + Arg::U64(self.address(13)?), + Arg::I64(32768), + ], + )?; + let pa = self.address(12)?; + let pm = self.sub(12, CHUNKS * 24 * 256 * 4, CHUNKS * 24 * 4)?; + let pl = self.sub(12, CHUNKS * 24 * 257 * 4, CHUNKS * 24 * 4)?; + Self::push( + &mut commands, + 2, + 1, + [CHUNKS as u32, 2, 1], + [256, 1, 1], + vec![ + Arg::U64(q), + Arg::U64(self.address(0)?), + Arg::U64(self.address(1)?), + Arg::U64(self.address(2)?), + Arg::U64(self.address(3)?), + Arg::U64(self.address(4)?), + Arg::U64(self.address(13)?), + Arg::U64(self.address(14)?), + Arg::I32(2), + Arg::I32(4), + Arg::F32(1.0 / 16.0), + Arg::U64(pa), + Arg::U64(pm), + Arg::U64(pl), + Arg::I32(CHUNKS as i32), + Arg::I32(32768), + Arg::I64(SCRATCH_FLOATS as i64), + ], + )?; + Self::push( + &mut commands, + 2, + 2, + [24, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(pa), + Arg::U64(pm), + Arg::U64(pl), + Arg::I32(CHUNKS as i32), + Arg::U64(self.address(11)?), + Arg::I64(SCRATCH_FLOATS as i64), + ], + )?; + self.finite(&mut commands, self.address(11)?, 6144, 1)?; + self.execute(w, commands)?; + if self.flags()?[1] != 0 { + return Err(Error::NonFiniteMmqOutput("mtp-int8-attention")); + } + Ok(CompletedMtpAttention { + owner: self, + _snapshot: snapshot, + _query: query, + }) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + self.failed = true; + self.current = None; + let Some(mut physical) = self.physical.take() else { + return Ok(()); + }; + physical.active.set(false); + // Explicit close requires graph retirement first. Dropping this logical + // ring never frees allocations retained by a real graph resource token. + if Rc::strong_count(&physical) != 1 { + return Err(Error::InvalidQwenShape); + } + Rc::get_mut(&mut physical) + .ok_or(Error::InvalidQwenShape)? + .close_inner() + } +} +impl Drop for MtpOriginalInt8<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} + +impl<'ctx> MtpOriginalInt8<'ctx> { + fn new_original_state( + c: &'ctx Context<'ctx>, + max_t: usize, + main: Rc>, + spans: [(usize, usize); 7], + prepared: ring_state::PreparedState<'ctx>, + ) -> Result { + let (slots, sizes) = layout(max_t)?; + if c.is_poisoned() { + return Err(Error::ContextPoisoned); + } + for ptx in [ + include_bytes!("mtp_original_tail.ptx").as_slice(), + include_bytes!("mtp_original_kv.ptx").as_slice(), + include_bytes!("qsa_native_decode.ptx").as_slice(), + ] { + if ptx.windows(8).any(|w| w == b"UNSEALED") { + return Err(Error::UnsupportedQwenOperation); + } + } + let origin = Rc::new(Origin); + let physical = Rc::new(PhysicalRing { + context: c, + origin: origin.clone(), + sizes, + buffers: std::array::from_fn(|_| None), + modules: std::array::from_fn(|_| None), + mapped: RefCell::new(None), + selected: None, + failed: Cell::new(false), + active: Cell::new(true), + }); + let mut o = Self { + context: c, + origin, + max_t, + slots, + sizes, + physical: Some(physical), + current: None, + failed: false, + generation: 0, + }; + let op = (|| { + let g = c.enter().inspect_err(|_| { + c.poison(); + c.retain_driver(); + })?; + let load = (|| { + for (i, (ptx, entries)) in [ + ( + include_bytes!("mtp_original_tail.ptx").as_slice(), + TAIL_ENTRIES, + ), + (include_bytes!("mtp_original_kv.ptx").as_slice(), KV_ENTRIES), + ( + include_bytes!("qsa_native_decode.ptx").as_slice(), + ATTN_ENTRIES, + ), + ] + .into_iter() + .enumerate() + { + o.physical_mut()?.modules[i] = Some(Module::load(ptx, entries)?); + } + Ok(()) + })(); + let pop = g.finish(); + if pop.is_err() { + o.poison(); + } + combine(load, pop)?; + let (selected, mapped) = ring_state::Selected::from_prepared(prepared, main, spans)?; + if selected.layout.resident { + o.slots = 65536; + for (i, n) in [134217728, 134217728, 4194304, 4194304, 262144] + .into_iter() + .enumerate() + { + o.sizes[i] = n; + o.physical_mut()?.sizes[i] = n; + } + } + o.physical_mut()?.selected = Some(selected); + *o.physical_mut()?.mapped.get_mut() = mapped; + let extras = o + .sizes + .into_iter() + .enumerate() + .filter(|(i, _)| !matches!(i,0..=9|12..=14)) + .try_fold(0usize, |a, (_, n)| { + a.checked_add(n).ok_or(Error::BudgetExceeded) + })?; + let need = extras.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + if c.allocated_bytes() + .checked_add(need) + .is_none_or(|n| n > c.budget) + || c.memory_info()?.0 < need + { + return Err(Error::BudgetExceeded); + } + for (i, n) in o.sizes.into_iter().enumerate() { + if !matches!(i,0..=9|12..=14) { + o.physical_mut()?.buffers[i] = Some(c.allocate(n)?); + } + } + o.validate()?; + if c.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = op { + return combine(Err(e), o.close()); + } + Ok(o) + } + pub fn fully_resident(&self) -> Result { + self.validate()?; + Ok(self + .physical()? + .selected + .as_ref() + .is_some_and(|s| s.layout.resident)) + } + pub fn actual_pinned_host_bytes(&self) -> Result { + let p = self.physical()?; + let m = p.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + Ok((if p.selected.is_some() { 116 } else { 0 }) + m.as_ref().map_or(0, MappedOwner::bytes)) + } + fn host_addresses(&self) -> Result<[u64; 4]> { + if self.fully_resident()? { + return Ok([0; 4]); + } + let mapped = self.mapped()?; + let mut a = [0; 4]; + for (i, n) in HOST_RUNS.into_iter().enumerate() { + a[i] = mapped.address(HOST_OFFSETS[i], n)?; + } + Ok(a) + } + fn read_encoded_page(&self, page: usize, runs: &mut [Vec; 4]) -> Result<()> { + if self.fully_resident()? { + return self + .physical()? + .selected + .as_ref() + .ok_or(Error::ContextPoisoned)? + .read_page(page, runs); + } + let mapped = self.mapped()?; + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + if runs[i].len() != n { + return Err(Error::InvalidSize); + } + mapped.read_into(HOST_OFFSETS[i] + page * n, &mut runs[i])?; + } + Ok(()) + } + fn validate_original_main(&self, main: &Rc>) -> Result<()> { + if let Some(s) = &self.physical()?.selected { + if !s.same_main(main) { + return Err(Error::InvalidQwenShape); + } + } + Ok(()) + } + fn reject_state_alias(&self, b: &DeviceBuffer<'_>) -> Result<()> { + if let Some(s) = &self.physical()?.selected { + s.reject_state_alias(b)?; + } + Ok(()) + } + /// State+retained diagnostic owners only; main bank is counted by paired layout. + pub fn planned_original_state_device_bytes( + max_t: usize, + fully_resident: bool, + ) -> Result { + let (_, sizes) = layout(max_t)?; + sizes + .into_iter() + .enumerate() + .filter(|(i, _)| !matches!(i,0..=9|12..=14)) + .try_fold( + ring_state::StateLayout::new(max_t, fully_resident)?.bytes, + |a, (_, n)| a.checked_add(n).ok_or(Error::InvalidSize), + ) + } +} #[cfg(test)] mod pages_tests { diff --git a/crates/cuda-driver/src/mtp_original_logical_prefix.rs b/crates/cuda-driver/src/mtp_original_logical_prefix.rs index b1ff9967..f628de05 100644 --- a/crates/cuda-driver/src/mtp_original_logical_prefix.rs +++ b/crates/cuda-driver/src/mtp_original_logical_prefix.rs @@ -1,202 +1,202 @@ -//! Child of mtp_original_int8. A skipped Original prompt group advances only -//! the logical conditioning cursor; it NEVER manufactures materialized KV pages. -use super::*; -use crate::{OriginalDeviceResidual, OriginalPromptLeaseIdentity}; -/// Genuine ring- and prompt-lease-bound no-work result. The retained physical -/// snapshot remains unchanged and may be empty even when `logical_end` is large. -pub struct OriginalMtpSkippedPrefix { - physical: MtpInt8Snapshot, - generation: u64, - start: usize, - logical_end: usize, - full_prompt_length: usize, - first_needed: usize, - lease: OriginalPromptLeaseIdentity, -} -impl OriginalMtpSkippedPrefix { - pub fn logical_end(&self) -> usize { - self.logical_end - } - pub fn first_needed(&self) -> usize { - self.first_needed - } - pub fn physical_snapshot(&self) -> &MtpInt8Snapshot { - &self.physical - } - pub fn materialized_end(&self) -> usize { - self.physical.0.end - } - pub fn validate_current(&self, ring: &MtpOriginalInt8<'_>) -> Result<()> { - ring.validate_snapshot(&self.physical)?; - if ring.generation != self.generation - || !ring - .current - .as_ref() - .is_some_and(|s| Rc::ptr_eq(&s.0, &self.physical.0)) - { - return Err(Error::InvalidQwenShape); - } - Ok(()) - } - pub fn validate_source( - &self, - residual: &OriginalDeviceResidual<'_, '_, '_>, - cell0: usize, - full_prompt_length: usize, - ) -> Result<()> { - if self.start != cell0 - || self.logical_end.checked_sub(cell0) != Some(residual.rows()) - || full_prompt_length != self.full_prompt_length - || !self.lease.same_lease(&residual.lease_identity()) - { - return Err(Error::InvalidQwenShape); - } - Ok(()) - } - pub fn metadata_bytes(&self) -> usize { - std::mem::size_of::() - } -} -impl MtpOriginalInt8<'_> { - /// Literal mtp.cpp690 cutoff, checked against actual whole prompt rows. Root - /// supplies full_prompt_length from retained OriginalPromptTxn source, not - /// from this chunk's end. No stream, kernel, page allocation or numerical - /// completion occurs in this outcome. - pub fn skip_original_prompt_prefix( - &mut self, - residual: &OriginalDeviceResidual<'_, '_, '_>, - physical_prior: &MtpInt8Snapshot, - logical_prior: Option<&OriginalMtpSkippedPrefix>, - cell0: usize, - full_prompt_length: usize, - ) -> Result> { - self.validate_snapshot(physical_prior)?; - if !residual.context_matches(self.context) - || residual.rows() == 0 - || full_prompt_length > MTP_ORIGINAL_MAX_CELLS - { - return Err(Error::InvalidProjectionShape); - } - let end = cell0 - .checked_add(residual.rows()) - .ok_or(Error::InvalidSize)?; - if end > full_prompt_length || end > MTP_ORIGINAL_MAX_CELLS { - return Err(Error::InvalidProjectionShape); - } - let first_needed = full_prompt_length.saturating_sub(MTP_ORIGINAL_WINDOW + 64); - let logical_start = if let Some(old) = logical_prior { - old.validate_current(self)?; - if old.full_prompt_length != full_prompt_length - || old.first_needed != first_needed - || !Rc::ptr_eq(&old.physical.0, &physical_prior.0) - { - return Err(Error::InvalidQwenShape); - } - old.logical_end - } else { - if self - .current - .as_ref() - .is_some_and(|s| !Rc::ptr_eq(&s.0, &physical_prior.0)) - { - return Err(Error::InvalidQwenShape); - } - if self.current.is_none() && physical_prior.0.end != 0 { - return Err(Error::InvalidQwenShape); - } - physical_prior.0.end - }; - if logical_start != cell0 { - return Err(Error::InvalidQwenShape); - } - // All complete groups are skipped iff the last group's end<=cutoff. This - // includes Original short remainder group; no individual-cell rounding. - if end > first_needed { - return Ok(None); - } - let generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - let result = OriginalMtpSkippedPrefix { - physical: physical_prior.clone(), - generation, - start: cell0, - logical_end: end, - full_prompt_length, - first_needed, - lease: residual.lease_identity(), - }; - self.current = Some(physical_prior.clone()); - self.generation = generation; - Ok(Some(result)) - } -} - -impl MtpOriginalInt8<'_> { - /// Private affine transition used only by the literal captured drafter. Actual - /// graph/window guards and successful drain, not these integers, authorize it. - pub(crate) fn begin_original_graph_mutation(&mut self, prior: &MtpInt8Snapshot) -> Result { - self.validate_snapshot(prior)?; - if self - .current - .as_ref() - .is_some_and(|s| !Rc::ptr_eq(&s.0, &prior.0)) - || self.current.is_none() && prior.0.end != 0 - { - return Err(Error::InvalidQwenShape); - } - let generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - self.current = None; - self.generation = generation; - Ok(generation) - } - pub(crate) fn finish_original_graph_mutation( - &mut self, - prior: &MtpInt8Snapshot, - first: usize, - end: usize, - generation: u64, - ) -> Result { - self.validate_snapshot(prior)?; - if self.current.is_some() - || self.generation != generation - || first > prior.0.end - || end <= first - || end > MTP_ORIGINAL_MAX_CELLS - { - return Err(Error::InvalidQwenShape); - } - let page0 = first / 4; - let page1 = end.div_ceil(4); - if page0 > prior.0.pages.len() { - return Err(Error::InvalidQwenShape); - } - // The leading pages are shared with the prior (whole chunks, no per-page work); only the pages from `page0` on are read back. - let mut tail = Vec::new(); - tail.try_reserve_exact(page1.saturating_sub(page0)) - .map_err(|_| Error::HostAllocation)?; - for p in page0..page1 { - let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - runs[i] = zero_bytes(n)?; - } - self.read_encoded_page(p, &mut runs)?; - tail.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); - } - let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { - origin: self.origin.clone(), - pages: prior.0.pages.with_tail(page0, tail), - end, - // the leading pages are the checked prior's (`validate_snapshot` above), the others were just sized by `zero_bytes` - checked: std::cell::Cell::new(true), - })); - self.current = Some(snapshot.clone()); - Ok(snapshot) - } -} +//! Child of mtp_original_int8. A skipped Original prompt group advances only +//! the logical conditioning cursor; it NEVER manufactures materialized KV pages. +use super::*; +use crate::{OriginalDeviceResidual, OriginalPromptLeaseIdentity}; +/// Genuine ring- and prompt-lease-bound no-work result. The retained physical +/// snapshot remains unchanged and may be empty even when `logical_end` is large. +pub struct OriginalMtpSkippedPrefix { + physical: MtpInt8Snapshot, + generation: u64, + start: usize, + logical_end: usize, + full_prompt_length: usize, + first_needed: usize, + lease: OriginalPromptLeaseIdentity, +} +impl OriginalMtpSkippedPrefix { + pub fn logical_end(&self) -> usize { + self.logical_end + } + pub fn first_needed(&self) -> usize { + self.first_needed + } + pub fn physical_snapshot(&self) -> &MtpInt8Snapshot { + &self.physical + } + pub fn materialized_end(&self) -> usize { + self.physical.0.end + } + pub fn validate_current(&self, ring: &MtpOriginalInt8<'_>) -> Result<()> { + ring.validate_snapshot(&self.physical)?; + if ring.generation != self.generation + || !ring + .current + .as_ref() + .is_some_and(|s| Rc::ptr_eq(&s.0, &self.physical.0)) + { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + pub fn validate_source( + &self, + residual: &OriginalDeviceResidual<'_, '_, '_>, + cell0: usize, + full_prompt_length: usize, + ) -> Result<()> { + if self.start != cell0 + || self.logical_end.checked_sub(cell0) != Some(residual.rows()) + || full_prompt_length != self.full_prompt_length + || !self.lease.same_lease(&residual.lease_identity()) + { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + pub fn metadata_bytes(&self) -> usize { + std::mem::size_of::() + } +} +impl MtpOriginalInt8<'_> { + /// Literal mtp.cpp690 cutoff, checked against actual whole prompt rows. Root + /// supplies full_prompt_length from retained OriginalPromptTxn source, not + /// from this chunk's end. No stream, kernel, page allocation or numerical + /// completion occurs in this outcome. + pub fn skip_original_prompt_prefix( + &mut self, + residual: &OriginalDeviceResidual<'_, '_, '_>, + physical_prior: &MtpInt8Snapshot, + logical_prior: Option<&OriginalMtpSkippedPrefix>, + cell0: usize, + full_prompt_length: usize, + ) -> Result> { + self.validate_snapshot(physical_prior)?; + if !residual.context_matches(self.context) + || residual.rows() == 0 + || full_prompt_length > MTP_ORIGINAL_MAX_CELLS + { + return Err(Error::InvalidProjectionShape); + } + let end = cell0 + .checked_add(residual.rows()) + .ok_or(Error::InvalidSize)?; + if end > full_prompt_length || end > MTP_ORIGINAL_MAX_CELLS { + return Err(Error::InvalidProjectionShape); + } + let first_needed = full_prompt_length.saturating_sub(MTP_ORIGINAL_WINDOW + 64); + let logical_start = if let Some(old) = logical_prior { + old.validate_current(self)?; + if old.full_prompt_length != full_prompt_length + || old.first_needed != first_needed + || !Rc::ptr_eq(&old.physical.0, &physical_prior.0) + { + return Err(Error::InvalidQwenShape); + } + old.logical_end + } else { + if self + .current + .as_ref() + .is_some_and(|s| !Rc::ptr_eq(&s.0, &physical_prior.0)) + { + return Err(Error::InvalidQwenShape); + } + if self.current.is_none() && physical_prior.0.end != 0 { + return Err(Error::InvalidQwenShape); + } + physical_prior.0.end + }; + if logical_start != cell0 { + return Err(Error::InvalidQwenShape); + } + // All complete groups are skipped iff the last group's end<=cutoff. This + // includes Original short remainder group; no individual-cell rounding. + if end > first_needed { + return Ok(None); + } + let generation = self + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + let result = OriginalMtpSkippedPrefix { + physical: physical_prior.clone(), + generation, + start: cell0, + logical_end: end, + full_prompt_length, + first_needed, + lease: residual.lease_identity(), + }; + self.current = Some(physical_prior.clone()); + self.generation = generation; + Ok(Some(result)) + } +} + +impl MtpOriginalInt8<'_> { + /// Private affine transition used only by the literal captured drafter. Actual + /// graph/window guards and successful drain, not these integers, authorize it. + pub(crate) fn begin_original_graph_mutation(&mut self, prior: &MtpInt8Snapshot) -> Result { + self.validate_snapshot(prior)?; + if self + .current + .as_ref() + .is_some_and(|s| !Rc::ptr_eq(&s.0, &prior.0)) + || self.current.is_none() && prior.0.end != 0 + { + return Err(Error::InvalidQwenShape); + } + let generation = self + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + self.current = None; + self.generation = generation; + Ok(generation) + } + pub(crate) fn finish_original_graph_mutation( + &mut self, + prior: &MtpInt8Snapshot, + first: usize, + end: usize, + generation: u64, + ) -> Result { + self.validate_snapshot(prior)?; + if self.current.is_some() + || self.generation != generation + || first > prior.0.end + || end <= first + || end > MTP_ORIGINAL_MAX_CELLS + { + return Err(Error::InvalidQwenShape); + } + let page0 = first / 4; + let page1 = end.div_ceil(4); + if page0 > prior.0.pages.len() { + return Err(Error::InvalidQwenShape); + } + // The leading pages are shared with the prior (whole chunks, no per-page work); only the pages from `page0` on are read back. + let mut tail = Vec::new(); + tail.try_reserve_exact(page1.saturating_sub(page0)) + .map_err(|_| Error::HostAllocation)?; + for p in page0..page1 { + let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + runs[i] = zero_bytes(n)?; + } + self.read_encoded_page(p, &mut runs)?; + tail.push(Rc::new(Page { + runs: runs.map(Vec::into_boxed_slice), + })); + } + let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { + origin: self.origin.clone(), + pages: prior.0.pages.with_tail(page0, tail), + end, + // the leading pages are the checked prior's (`validate_snapshot` above), the others were just sized by `zero_bytes` + checked: std::cell::Cell::new(true), + })); + self.current = Some(snapshot.clone()); + Ok(snapshot) + } +} diff --git a/crates/cuda-driver/src/mtp_original_prefill.rs b/crates/cuda-driver/src/mtp_original_prefill.rs index 4b663cf7..8f9e1b9c 100644 --- a/crates/cuda-driver/src/mtp_original_prefill.rs +++ b/crates/cuda-driver/src/mtp_original_prefill.rs @@ -1,1602 +1,1602 @@ -//! Literal prefill.cpp741..886, Q8_0 branch, on the actual borrowed prompt -//! region. Register as a PRIVATE child of mtp_original_int8: ring/host backing -//! never becomes a public address or a fabricated owning DeviceBuffer. -use super::*; -use crate::ffi::BufferHandle; -use crate::original_prefill_arena::OriginalPromptSpan; -use crate::{OriginalDeviceResidual, OriginalPromptRows}; -#[allow(unsafe_code)] -#[path = "mtp_original_prefill_ffi.rs"] -mod prefill_abi; -use prefill_abi::{Arg as A, Arguments as Args, Module as Mod}; -use std::ffi::CStr; -const RESERVE_BYTES: usize = 128 << 20; -const FLAG_WORDS: usize = 24; -const WIDTHS: [usize; 11] = [8, 16, 24, 32, 40, 48, 64, 80, 96, 112, 128]; -const ENTRIES: &[&CStr] = &[ - c"mtp_prefill_rms", - c"mtp_prefill_gr_norm", - c"mtp_prefill_gr_silu", - c"mtp_prefill_gr_mix", - c"mtp_prefill_broadcast", - c"mtp_prefill_embedding", - c"mtp_prefill_rope", - c"mtp_prefill_append", - c"mtp_prefill_finite", - c"mtp_prefill_iota", - c"mtp_prefill_encoded", - c"mtp_prefill_zero", - c"mtp_prefill_gr_norm_scan", - c"mtp_prefill_gr_silu_scan", - c"mtp_prefill_bf16_scan", - c"mtp_prefill_gr_product_scan", - c"mtp_prefill_q8_scan", -]; -#[path = "mtp_original_prefill_symbols.rs"] -mod symbols; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum DraftKvFallback { - Disabled, - Empty, - UnsupportedStorage, - MissingWeights, - UnsupportedEmbedding, - AlternateF16, - RegionTooSmall, - NoQ8Tile, - UnsupportedRopeTable, -} -pub enum DraftKvOutcome { - Fallback(DraftKvFallback), - Skipped, - Cancelled, - Completed(CompletedDraftKv), -} -/// Actual completed range, not a readiness bit or a scalar committed product. -/// Root retains the lower materialized bound with its real draft window state. -pub struct CompletedDraftKv { - snapshot: MtpInt8Snapshot, - first_materialized: usize, - end: usize, - generation: u64, -} -impl CompletedDraftKv { - pub fn validate_current(&self, ring: &MtpOriginalInt8<'_>) -> Result<()> { - ring.validate_snapshot(&self.snapshot)?; - if ring.is_failed() - || ring.generation != self.generation - || self.snapshot.0.end != self.end - || self.first_materialized >= self.end - || ring - .current - .as_ref() - .is_none_or(|current| !Rc::ptr_eq(¤t.0, &self.snapshot.0)) - { - return Err(Error::InvalidQwenShape); - } - Ok(()) - } - pub fn first_materialized(&self) -> usize { - self.first_materialized - } - pub fn next_position(&self) -> usize { - self.end - } - pub fn owner_id(&self) -> MtpInt8OwnerId { - self.snapshot.owner_id() - } - pub fn generation(&self) -> u64 { - self.generation - } - pub fn snapshot_after(&self, position: usize) -> Result { - if position < self.first_materialized || position >= self.end { - return Err(Error::InvalidQwenShape); - } - if position + 1 == self.end { - return Ok(self.snapshot.clone()); - } - Ok(MtpInt8Snapshot(Rc::new(Snapshot { - origin: self.snapshot.0.origin.clone(), - pages: self.snapshot.0.pages.clone(), - end: position + 1, - checked: std::cell::Cell::new(self.snapshot.0.checked.get()), - }))) - } - /// Use only after checking the true requested window excludes pruned cells. - pub fn snapshot_for_window(&self, position: usize, window: usize) -> Result { - if window == 0 - || position >= self.end - || position - .checked_add(1) - .ok_or(Error::InvalidSize)? - .saturating_sub(window) - < self.first_materialized - { - return Err(Error::InvalidQwenShape); - } - self.snapshot_after(position) - } -} -/// These are actual whole matrix loans acquired by Root's binding owner. The -/// private runtime adapter independently checks descriptor/role identity. -pub struct OriginalMtpPrefillWeights<'a, 'ctx> { - pub embedding_norm: &'a DeviceBuffer<'ctx>, - pub embedding_fc: &'a DeviceBuffer<'ctx>, - pub hidden_norm: &'a DeviceBuffer<'ctx>, - pub hidden_fc: &'a DeviceBuffer<'ctx>, - pub gr_norm: &'a DeviceBuffer<'ctx>, - pub gr_down: &'a DeviceBuffer<'ctx>, - pub gr_up: &'a DeviceBuffer<'ctx>, - pub key: &'a DeviceBuffer<'ctx>, - pub value: &'a DeviceBuffer<'ctx>, - pub key_norm: &'a DeviceBuffer<'ctx>, -} -/// Entire real embedding source, never a borrowed raw pointer supplied by the -/// public protocol. Construction is private to authenticated source adapters. -pub struct OriginalMtpEmbedding<'a, 'ctx> { - table: &'a DeviceBuffer<'ctx>, - kind: EmbeddingKind, -} -enum EmbeddingKind { - Native { - kind: i32, - row_bytes: usize, - vocab: usize, - }, - Compressed { - bits: i32, - bias: i32, - group: usize, - vocab: usize, - codes: usize, - scales: usize, - offsets: bool, - }, -} -impl<'a, 'ctx> OriginalMtpEmbedding<'a, 'ctx> { - pub fn native( - table: &'a DeviceBuffer<'ctx>, - kind: i32, - row_bytes: usize, - vocab: usize, - ) -> Result { - let per = match kind { - 16 => 66, - 17 => 74, - 18 => 98, - 20 => 144, - 21 => 110, - 22 => 82, - 23 => 136, - 29 => 56, - 11 => 110, - 12 => 144, - 13 => 176, - 7 => 192, - 8 => 272, - 42 => 72, - 30 => 512, - _ => return Err(Error::UnsupportedProjection), - }; - if row_bytes != 10 * per - || vocab == 0 - || vocab > 262144 - || table.bytes != row_bytes.checked_mul(vocab).ok_or(Error::InvalidSize)? - { - return Err(Error::InvalidProjectionShape); - } - Ok(Self { - table, - kind: EmbeddingKind::Native { - kind, - row_bytes, - vocab, - }, - }) - } - pub fn compressed( - table: &'a DeviceBuffer<'ctx>, - bits: i32, - bias: i32, - group: usize, - vocab: usize, - offsets: bool, - ) -> Result { - if !matches!(bits, 2 | 4 | 8) - || group == 0 - || !2560usize.is_multiple_of(group) - || vocab == 0 - || vocab > 262144 - { - return Err(Error::InvalidProjectionShape); - } - let codes = vocab - .checked_mul(2560 / (8 / bits as usize)) - .ok_or(Error::InvalidSize)?; - let scales = vocab - .checked_mul(2560 / group) - .and_then(|n| n.checked_mul(4)) - .ok_or(Error::InvalidSize)?; - let total = codes - .checked_add( - scales - .checked_mul(if offsets { 2 } else { 1 }) - .ok_or(Error::InvalidSize)?, - ) - .ok_or(Error::InvalidSize)?; - if table.bytes != total { - return Err(Error::InvalidProjectionShape); - } - Ok(Self { - table, - kind: EmbeddingKind::Compressed { - bits, - bias, - group, - vocab, - codes, - scales, - offsets, - }, - }) - } - fn vocab(&self) -> usize { - match self.kind { - EmbeddingKind::Native { vocab, .. } | EmbeddingKind::Compressed { vocab, .. } => vocab, - } - } -} -/// Explicit Original optional policy. It cannot assert finite tensors, source -/// provenance, or readiness. Unsupported options produce fallback, never success. -pub struct DraftKvPolicy { - pub disabled: bool, - pub alternate_f16: bool, - pub rotated: bool, - pub q4: bool, - pub hybrid: bool, - pub mode: i32, - pub theta_scale: f32, - pub freq_scale: f32, - pub corr_low: f32, - pub corr_high: f32, - pub ext_factor: f32, - pub mscale: f32, - pub rope_table_enabled: bool, - pub multimodal_positions: bool, -} -impl DraftKvPolicy { - pub fn original_int8(theta_scale: f32) -> Self { - Self { - disabled: false, - alternate_f16: false, - rotated: false, - q4: false, - hybrid: false, - mode: 0, - theta_scale, - freq_scale: 1.0, - corr_low: 0.0, - corr_high: 0.0, - ext_factor: 0.0, - mscale: 1.0, - rope_table_enabled: false, - multimodal_positions: false, - } - } -} -enum Cmd { - Kernel { - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - args: Args, - }, - Copy { - dst: u64, - src: u64, - bytes: usize, - }, - Gemm { - x: BufferHandle, - w: BufferHandle, - y: BufferHandle, - rows: i32, - n: i32, - k: i32, - alpha: f32, - beta: f32, - }, -} -struct Region { - base: BufferHandle, - bytes: usize, - b: usize, - roles: [(usize, usize); 20], -} -fn fastdiv(d: u32) -> [u32; 3] { - let l = 32 - (d - 1).leading_zeros(); - [ - (((1u64 << 32) * ((1u64 << l) - u64::from(d)) / u64::from(d)) + 1) as u32, - l, - d, - ] -} -fn aligned(n: usize) -> Result { - n.checked_add(255) - .map(|n| n & !255) - .ok_or(Error::InvalidSize) -} -fn q8_bytes(rows: usize) -> Result { - rows.checked_mul(20 * 144) - .and_then(|n| n.checked_add(128 * 144)) - .ok_or(Error::InvalidSize) -} -impl Region { - fn new(base: BufferHandle, bytes: usize, n: usize, r0: usize) -> Result> { - // Literal Original per_row (including fixed128-block tail in q8_bytes(4,N)). - let per = 4 * (2 * 2560 + 4 * 10240 + 320 + 4 + 2560 + 2 * 512 + 1) - + 2 * (2560 + 2 * 10240 + 320 + 2560) - + 64 - + q8_bytes(4)? - + 4 * 4; - let b = (n - r0).min((bytes / per) & !63); - if b < 64 { - return Ok(None); - } - let widths = [ - b * 10240, - b * 10240, - b * 5120, - b * 40960, - b * 40960, - b * 40960, - b * 40960, - b * 20480, - b * 20480, - b * 1280, - b * 640, - b * 16, - b * 10240, - b * 5120, - b * 2048, - b * 2048, - b * 4, - q8_bytes(b * 4)?, - b * 16, - 16, - ]; - let mut end: usize = 0; - let mut roles = [(0, 0); 20]; - for (i, len) in widths.into_iter().enumerate() { - roles[i] = (end, len); - end = end.checked_add(aligned(len)?).ok_or(Error::InvalidSize)?; - } - if end > bytes { - return Ok(None); - } - base.validate_projection_extent(bytes, 256)?; - Ok(Some(Self { - base, - bytes, - b, - roles, - })) - } - fn handle(&self, i: usize, len: usize) -> Result { - let (offset, extent) = self.roles.get(i).copied().ok_or(Error::InvalidSize)?; - if len == 0 || len > extent { - return Err(Error::InvalidSize); - } - self.base.checked_subspan(self.bytes, offset, len) - } - fn address(&self, i: usize, len: usize) -> Result { - Ok(self.handle(i, len)?.qwen_address()) - } -} -pub struct OriginalMtpPrefill<'ctx> { - context: &'ctx Context<'ctx>, - modules: [Option; 5], - status: Option>, - tmp: Option>, - sms: usize, - shared_limit: u32, - failed: bool, -} -impl<'ctx> Context<'ctx> { - pub fn original_mtp_prefill(&'ctx self) -> Result> { - OriginalMtpPrefill::new(self) - } -} -impl<'ctx> OriginalMtpPrefill<'ctx> { - fn new(context: &'ctx Context<'ctx>) -> Result { - let assets = [ - include_bytes!("mtp_original_prefill.ptx").as_slice(), - include_bytes!("mtp_original_prefill_embedding.ptx").as_slice(), - include_bytes!("mtp_original_prefill_quant.ptx").as_slice(), - include_bytes!("mtp_original_prefill_mmq.ptx").as_slice(), - include_bytes!("mtp_original_prefill_fixup.ptx").as_slice(), - ]; - if assets - .iter() - .any(|a| a.windows(8).any(|w| w == b"UNSEALED")) - { - return Err(Error::UnsupportedQwenOperation); - } - let mut owner = Self { - context, - modules: std::array::from_fn(|_| None), - status: None, - tmp: None, - sms: 0, - shared_limit: 0, - failed: false, - }; - let result = (|| { - let g = context.enter()?; - let load = (|| { - owner.modules[0] = Some(Mod::load(assets[0], ENTRIES)?); - owner.modules[1] = Some(Mod::load(assets[1], &[c"mtp_prefill_native_embedding"])?); - owner.modules[2] = Some(Mod::load(assets[2], &[c"mtp_prefill_q8"])?); - owner.modules[3] = Some(Mod::load(assets[3], symbols::PROJECT)?); - owner.modules[4] = Some(Mod::load(assets[4], symbols::FIXUP)?); - let (sms, limit) = owner.module(0)?.info()?; - crate::arch_ptx::latch_stream_k_policy(); - owner.sms = sms; - owner.shared_limit = limit; - Ok(()) - })(); - let pop = g.finish(); - if pop.is_err() - || load.as_ref().is_err_and(|e| { - matches!(e, Error::Driver { .. } | Error::InvalidDriverValue(_)) - }) - { - owner.poison(); - } - combine(load, pop)?; - let charge = owner - .sms - .checked_mul(128 * 128 * 4) - .and_then(|n| n.checked_add(FLAG_WORDS * 4)) - .ok_or(Error::BudgetExceeded)?; - let required = charge - .checked_add(RESERVE_BYTES) - .ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget_bytes()) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - owner.status = Some(context.allocate(FLAG_WORDS * 4)?); - owner.tmp = Some(context.allocate(charge - FLAG_WORDS * 4)?); - Ok(()) - })(); - if let Err(e) = result { - return combine(Err(e), owner.close()); - } - Ok(owner) - } - pub fn allocated_bytes(&self) -> usize { - self.status.as_ref().map_or(0, DeviceBuffer::len) - + self.tmp.as_ref().map_or(0, DeviceBuffer::len) - } - pub fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() - } - fn poison(&mut self) { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - } - fn module(&self, i: usize) -> Result<&Mod> { - self.modules - .get(i) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) - } - fn status(&self, i: usize) -> Result { - let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, i * 4, 4) - } - fn kernel( - cmds: &mut Vec, - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - args: Vec, - ) -> Result<()> { - cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; - cmds.push(Cmd::Kernel { - asset, - index, - grid, - block, - shared, - args: Args::new(args)?, - }); - Ok(()) - } - fn finite(&self, cmds: &mut Vec, data: u64, words: usize, stage: usize) -> Result<()> { - Self::kernel( - cmds, - 0, - 8, - [(words.div_ceil(256)) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(data), - A::I32(words as i32), - A::U64(self.status(stage)?.qwen_address()), - ], - ) - } - fn weight( - &self, - rows: &OriginalPromptRows<'_, '_, '_>, - w: &NativeBatchWorkspace<'_>, - b: &DeviceBuffer<'_>, - bytes: usize, - ) -> Result { - if b.bytes != bytes || !std::ptr::eq(b.context, self.context) { - return Err(Error::InvalidProjectionShape); - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(bytes, 2)?; - w.reject_alias(h, bytes)?; - let (region, n) = rows.draft_kv_region()?; - let (r, rn) = rows.common_span(OriginalPromptSpan::R)?; - for (a, len) in [ - (region, n), - (r, rn), - ( - self.status - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?, - FLAG_WORDS * 4, - ), - ( - self.tmp - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?, - self.sms * 128 * 128 * 4, - ), - ] { - if h.overlaps(bytes, a, len) { - return Err(Error::OutputAliasesInput); - } - } - Ok(h) - } - #[allow(clippy::too_many_arguments)] - fn project( - &self, - cmds: &mut Vec, - r: &Region, - x: u64, - w: u64, - y: u64, - rows: usize, - out: usize, - bound_slot: usize, - stage: usize, - ) -> Result<()> { - if rows == 0 || rows > r.b * 4 || !matches!(out, 512 | 2560) { - return Err(Error::InvalidProjectionShape); - } - let mut best = None; - let mut ntx = usize::MAX; - for (i, j) in WIDTHS.into_iter().enumerate() { - if ntx <= 1 { - break; - } - let shared = 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024; - if shared > self.shared_limit as usize { - continue; - } - if rows.div_ceil(j) < ntx { - best = Some((i, j, shared)); - ntx = rows.div_ceil(j); - } - } - let (index, j, shared) = best.ok_or(Error::UnsupportedProjection)?; - let tiles = (out / 128) * ntx; - let efficiency = 100 * tiles / (self.sms * tiles.div_ceil(self.sms)); - let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { self.sms }; - let fix = !tiles.is_multiple_of(grid); - if tiles.checked_mul(80).is_none_or(|n| n >= 1 << 30) { - return Err(Error::InvalidProjectionShape); - } - let xq = r.address(17, q8_bytes(rows)?)?; - let ids = r.address(18, rows * 4)?; - let bound = r - .handle(19, 16)? - .checked_subspan(16, bound_slot * 8, 8)? - .qwen_address(); - Self::kernel( - cmds, - 2, - 0, - [rows as u32, 5, 1], - [128, 1, 1], - 0, - vec![ - A::U64(x), - A::U64(0), - A::U64(xq), - A::I64(2560), - A::I64(2560), - A::I64((rows * 2560) as i64), - A::I64((rows * 2560) as i64), - A::I64(2560), - A::I32(rows as i32), - A::I32(1), - A::I32(1), - ], - )?; - // Original D4 data includes a fixed128-block tail. Initialize that exact - // tail before a literal vendor kernel can speculatively load it. - Self::kernel( - cmds, - 0, - 11, - [72, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(xq + (rows * 20 * 144) as u64), - A::I32((128 * 144) as i32), - ], - )?; - Self::kernel( - cmds, - 0, - 16, - [(rows * 20).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(xq), - A::I32((rows * 20) as i32), - A::U64(self.status(stage)?.qwen_address()), - ], - )?; - let tmp = if fix { - self.tmp - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address() - } else { - 0 - }; - let fd = fastdiv; - Self::kernel( - cmds, - 3, - index, - [grid as u32, 1, 1], - [32, 8, 1], - shared as u32, - vec![ - A::U64(w), - A::U64(xq), - A::U64(ids), - A::U64(bound), - A::U64(y), - A::U64(tmp), - A::U64(0), - A::U3(fd(80)), - A::I32(out as i32), - A::I32(rows as i32), - A::I32(80), - A::I32(rows as i32), - A::I32(out as i32), - A::U3(fd(1)), - A::U3(fd(1)), - A::I32((out * 80) as i32), - A::I32(0), - A::I32(0), - A::U3(fd(1)), - A::U3(fd(1)), - A::I32(0), - A::I32(0), - A::I32(0), - A::U3(fd(ntx as u32)), - ], - )?; - if fix { - Self::kernel( - cmds, - 4, - index, - [grid as u32, 4, 1], - [32, 4, 1], - 0, - vec![ - A::U64(ids), - A::U64(bound), - A::U64(y), - A::U64(tmp), - A::U3(fd(80)), - A::I32(out as i32), - A::I32(rows as i32), - A::I32(out as i32), - A::U3(fd(1)), - A::I32(0), - A::U3(fd(1)), - A::I32(0), - A::U3(fd(ntx as u32)), - ], - )?; - } - Ok(()) - } - fn run( - &mut self, - rows: &mut OriginalPromptRows<'_, '_, '_>, - w: &mut NativeBatchWorkspace<'ctx>, - mut cmds: Vec, - staging: Vec<(BufferHandle, Vec)>, - ) -> Result<()> { - let mut readback = zero_bytes(FLAG_WORDS * 4)?; - let zero = zero_bytes(FLAG_WORDS * 4)?; - let status = self - .status - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?; - status.validate_projection_extent(FLAG_WORDS * 4, 4)?; - for i in 0..5 { - self.module(i)?; - } - let blas = w.blas()?; - let g = match self.context.enter() { - Ok(g) => g, - Err(e) => { - self.poison(); - rows.mark_failed(); - w.mark_failed(); - return Err(e); - } - }; - let mut operation = self.context.driver.api.copy_from(status, &zero); - if operation.is_ok() { - for (dst, bytes) in &staging { - if let Err(e) = self.context.driver.api.copy_from(*dst, bytes) { - operation = Err(e); - break; - } - } - } - if operation.is_ok() { - operation = self.context.driver.api.synchronize(); - } - if operation.is_ok() { - for c in &mut cmds { - let r = match c { - Cmd::Kernel { - asset, - index, - grid, - block, - shared, - args, - } => self.modules[*asset] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.launch(*index, *grid, *block, *shared, blas.stream(), args) - }), - Cmd::Copy { dst, src, bytes } => self.modules[0] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.copy(*dst, *src, *bytes, blas.stream()) - }), - Cmd::Gemm { - x, - w, - y, - rows, - n, - k, - alpha, - beta, - } => blas.gemm_bf16(*x, *w, *y, *rows, *n, *k, alpha, beta), - }; - if let Err(e) = r { - operation = Err(e); - break; - } - } - } - let stream = blas.synchronize(); - if operation.is_ok() && stream.is_ok() { - operation = self.context.driver.api.copy_to(status, &mut readback); - } - let device = self.context.driver.api.synchronize(); - let pop = g.finish(); - if operation.is_err() || stream.is_err() || device.is_err() || pop.is_err() { - self.poison(); - rows.mark_failed(); - w.mark_failed(); - } - if stream.is_err() || device.is_err() || pop.is_err() { - std::mem::forget((cmds, staging, zero, readback)); - self.context.retain_driver(); - return combine(combine(combine(operation, stream), device), pop); - } - combine(combine(combine(operation, stream), device), pop)?; - for word in readback.chunks_exact(4) { - if u32::from_le_bytes(word.try_into().map_err(|_| Error::InvalidSize)?) > 1 { - self.poison(); - return Err(Error::InvalidDriverValue("draft prefill status")); - } - } - for (stage, word) in readback.chunks_exact(4).enumerate() { - if u32::from_le_bytes(word.try_into().map_err(|_| Error::InvalidSize)?) != 0 { - return Err(Error::NonFiniteMmqOutput(match stage { - 0 => "MTP embedding", - 1 => "MTP embedding norm", - 2 => "MTP FC embedding", - 3 => "MTP hidden norm", - 4 => "MTP FC hidden", - 5 => "MTP broadcast", - 6 => "MTP GR normalized", - 7 => "MTP GR down", - 8 => "MTP GR SiLU", - 9 => "MTP GR up", - 10 => "MTP GR mixed", - 11 => "MTP K", - 12 => "MTP V", - 13 => "MTP K norm", - 14 => "MTP K Rope", - _ => "MTP INT8 encoded", - })); - } - } - Ok(()) - } - #[allow(clippy::too_many_arguments)] - pub fn record<'arena, 'loan>( - &mut self, - residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - weights: OriginalMtpPrefillWeights<'_, '_>, - embedding: OriginalMtpEmbedding<'_, '_>, - policy: &DraftKvPolicy, - mut cancelled: impl FnMut() -> bool, - ) -> Result { - if policy.disabled { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Disabled)); - } - if tokens.is_empty() { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Empty)); - } - if policy.mode != 0 || policy.hybrid || policy.rotated || policy.q4 { - return Ok(DraftKvOutcome::Fallback( - DraftKvFallback::UnsupportedStorage, - )); - } - if policy.alternate_f16 { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::AlternateF16)); - } - if policy.rope_table_enabled || policy.multimodal_positions { - return Ok(DraftKvOutcome::Fallback( - DraftKvFallback::UnsupportedRopeTable, - )); - } - if [ - policy.theta_scale, - policy.freq_scale, - policy.corr_low, - policy.corr_high, - policy.ext_factor, - policy.mscale, - ] - .iter() - .any(|x| !x.is_finite()) - || policy.theta_scale <= 0.0 - || policy.freq_scale <= 0.0 - || policy.mscale <= 0.0 - { - return Err(Error::InvalidProjectionShape); - } - ring.validate_snapshot(prior)?; - workspace.validate_context(self.context)?; - ring.validate_context(self.context)?; - if self.is_failed() - || !residual.context_matches(self.context) - || tokens.len() != residual.rows() - || tokens.len() > 8192 - || cell0 - .checked_add(tokens.len()) - .is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) - { - return Err(Error::InvalidProjectionShape); - } - if tokens - .iter() - .any(|t| *t < 0 || *t as usize >= embedding.vocab()) - { - return Err(Error::InvalidProjectionShape); - } - let r0 = first_needed.saturating_sub(cell0); - if r0 >= tokens.len() { - return Ok(DraftKvOutcome::Skipped); - } - let rows = residual.lease_mut(); - let (region, region_bytes) = rows.draft_kv_region()?; - let Some(r) = Region::new(region, region_bytes, tokens.len(), r0)? else { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::RegionTooSmall)); - }; - crate::bringup_trace!("DBG prefill.record: region ok b={} tokens={} r0={r0}", r.b, tokens.len()); - if !WIDTHS.into_iter().any(|j| { - 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024 <= self.shared_limit as usize - }) { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::NoQ8Tile)); - } - let weight_refs = [ - weights.embedding_norm, - weights.embedding_fc, - weights.hidden_norm, - weights.hidden_fc, - weights.gr_norm, - weights.gr_down, - weights.gr_up, - weights.key, - weights.value, - weights.key_norm, - ]; - let extents = [ - 10240, - 2560 * 80 * 34, - 40960, - 2560 * 80 * 34, - 40960, - 320 * 10240 * 2, - 10240 * 320 * 2, - 512 * 80 * 34, - 512 * 80 * 34, - 1024, - ]; - let mut wh = [region; 10]; - for i in 0..10 { - wh[i] = self.weight(rows, workspace, weight_refs[i], extents[i]).map_err(|e| { crate::bringup_trace!("DBG prefill.record: weight {i} err {e:?}"); e })?; - } - crate::bringup_trace!("DBG prefill.record: 10 weights staged"); - let eh = self.weight(rows, workspace, embedding.table, embedding.table.bytes).map_err(|e| { crate::bringup_trace!("DBG prefill.record: embedding table err {e:?}"); e })?; - crate::bringup_trace!("DBG prefill.record: embedding table staged"); - for (i, a) in weight_refs.iter().enumerate() { - for b in weight_refs.iter().take(i) { - let ah = a.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref a.handle is None (i={i})"); Error::ContextPoisoned })?; - let bh = b.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref b.handle is None (i={i})"); Error::ContextPoisoned })?; - if ah.overlaps(a.bytes, bh, b.bytes) - && !(ah.qwen_address() == bh.qwen_address() && a.bytes == b.bytes) - { - return Err(Error::OutputAliasesInput); - } - } - } - for b in weight_refs { - let h = b.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight b.handle is None (embedding overlap)"); Error::ContextPoisoned })?; - if eh.overlaps(embedding.table.bytes, h, b.bytes) - && !(eh.qwen_address() == h.qwen_address() && embedding.table.bytes == b.bytes) - { - return Err(Error::OutputAliasesInput); - } - } - // Actual input residual lies outside the region being overwritten. - let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R).map_err(|e| { crate::bringup_trace!("DBG prefill.record: common_span(R) err {e:?}"); e })?; - crate::bringup_trace!("DBG prefill.record: weights vs embedding overlap ok, R span ok"); - if rh.overlaps(rbytes, region, region_bytes) { - return Err(Error::OutputAliasesInput); - } - // The serve ring is built from prepared spans of the drafter's shared region, so buffers 0..5 are not - // separately owned DeviceBuffers; compare by address (ring.address works for both layouts). - for i in 0..5 { - let hv = ring.address(i)?; - let n = ring.sizes[i]; - let ov = |o: u64, on: usize| hv < o.saturating_add(on as u64) && o < hv.saturating_add(n as u64); - if ov(region.qwen_address(), region_bytes) - || ov(rh.qwen_address(), rbytes) - || wh.iter().zip(extents).any(|(w, n2)| ov(w.qwen_address(), n2)) - || ov(eh.qwen_address(), embedding.table.bytes) - { - return Err(Error::OutputAliasesInput); - } - } - crate::bringup_trace!("DBG prefill.record: overlap checks ok"); - let generation = ring - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - let end = cell0 + tokens.len(); - let first = cell0 + r0; - let first_page = first / 4; - let page_count = end.div_ceil(4); - let mut pages = Vec::new(); - pages - .try_reserve_exact(page_count) - .map_err(|_| Error::HostAllocation)?; - let mut changed = Vec::new(); - changed - .try_reserve_exact(page_count - first_page) - .map_err(|_| Error::HostAllocation)?; - for p in 0..page_count { - if p < first_page { - if let Some(page) = prior.0.pages.get(p) { - pages.push(page.clone()); - continue; - } - } - let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - runs[i] = zero_bytes(n)?; - } - if p < first_page { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); - } else { - changed.push(runs); - } - } - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - // Genuine idle dependency before this stream can mutate the real drafter KV. - crate::bringup_trace!("DBG prefill.record: pages ready, ring.execute(idle)"); - ring.execute(workspace, Vec::new()).map_err(|e| { crate::bringup_trace!("DBG prefill.record: ring.execute err {e:?}"); e })?; // genuine global + shared drafter stream idle, even identical snapshot - ring.restore(workspace, prior).map_err(|e| { crate::bringup_trace!("DBG prefill.record: ring.restore err {e:?}"); e })?; - crate::bringup_trace!("DBG prefill.record: ring restored"); - ring.current = None; - for b0 in (r0..tokens.len()).step_by(r.b) { - let nb = r.b.min(tokens.len() - b0); - let c0 = cell0 + b0; - crate::bringup_trace!("DBG prefill.record: block b0={b0} nb={nb} c0={c0}"); - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - let mut commands = Vec::new(); - commands - .try_reserve_exact(80) - .map_err(|_| Error::HostAllocation)?; - let mut tk = zero_bytes(nb * 4)?; - for (dst, t) in tk.chunks_exact_mut(4).zip(&tokens[b0..b0 + nb]) { - dst.copy_from_slice(&t.to_le_bytes()); - } - let mut bounds = zero_bytes(16)?; - for (dst, v) in bounds - .chunks_exact_mut(4) - .zip([0, nb as i32, 0, (nb * 4) as i32]) - { - dst.copy_from_slice(&v.to_le_bytes()); - } - Self::kernel( - &mut commands, - 0, - 9, - [(nb * 4).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![A::U64(r.address(18, nb * 16)?), A::I32((nb * 4) as i32)], - )?; - let emb = r.address(0, nb * 10240)?; - let tok = r.address(16, nb * 4)?; - match embedding.kind { - EmbeddingKind::Native { - kind, row_bytes, .. - } => Self::kernel( - &mut commands, - 1, - 0, - [10, nb as u32, 1], - [32, 1, 1], - 0, - vec![ - A::I32(kind), - A::U64(eh.qwen_address()), - A::U64(row_bytes as u64), - A::U64(tok), - A::I64(2560), - A::U64(emb), - ], - )?, - EmbeddingKind::Compressed { - bits, - bias, - group, - codes, - scales, - offsets, - .. - } => Self::kernel( - &mut commands, - 0, - 5, - [10, nb as u32, 1], - [256, 1, 1], - 0, - vec![ - A::U64(eh.qwen_address()), - A::U64(eh.qwen_address() + codes as u64), - A::U64(if offsets { - eh.qwen_address() + (codes + scales) as u64 - } else { - 0 - }), - A::U64(tok), - A::I64(2560), - A::I32(bits), - A::I32(bias), - A::I32(group as i32), - A::U64((2560 / (8 / bits)) as u64), - A::U64((2560 / group) as u64), - A::U64(emb), - ], - )?, - } - self.finite(&mut commands, emb, nb * 2560, 0)?; - Self::kernel( - &mut commands, - 0, - 0, - [nb as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(emb), - A::U64(wh[0].qwen_address()), - A::I64(2560), - A::I64(2560), - A::F32(1e-6), - ], - )?; - self.finite(&mut commands, emb, nb * 2560, 1)?; - let e2 = r.address(1, nb * 10240)?; - self.project( - &mut commands, - &r, - emb, - wh[1].qwen_address(), - e2, - nb, - 2560, - 0, - 2, - )?; - self.finite(&mut commands, e2, nb * 2560, 2)?; - let hn = r.address(3, nb * 40960)?; - let h2 = r.address(4, nb * 40960)?; - commands.push(Cmd::Copy { - dst: hn, - src: rh - .checked_subspan(rbytes, b0 * 40960, nb * 40960)? - .qwen_address(), - bytes: nb * 40960, - }); - Self::kernel( - &mut commands, - 0, - 0, - [nb as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(hn), - A::U64(wh[2].qwen_address()), - A::I64(10240), - A::I64(10240), - A::F32(1e-6), - ], - )?; - self.finite(&mut commands, hn, nb * 10240, 3)?; - self.project( - &mut commands, - &r, - hn, - wh[3].qwen_address(), - h2, - nb * 4, - 2560, - 1, - 4, - )?; - self.finite(&mut commands, h2, nb * 10240, 4)?; - let rm = r.address(5, nb * 40960)?; - let gated = r.address(6, nb * 40960)?; - let xn = r.address(8, nb * 20480)?; - let lo = r.address(9, nb * 1280)?; - let lo16 = r.address(10, nb * 640)?; - let grs = r.address(11, nb * 16)?; - let mixed = r.address(12, nb * 10240)?; - let mixedh = r.address(13, nb * 5120)?; - Self::kernel( - &mut commands, - 0, - 4, - [40, nb as u32, 1], - [256, 1, 1], - 0, - vec![A::U64(h2), A::U64(e2), A::U64(rm), A::I64(2560), A::I32(4)], - )?; - self.finite(&mut commands, rm, nb * 10240, 5)?; - Self::kernel( - &mut commands, - 0, - 1, - [(nb * 4) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(rm), - A::U64(wh[4].qwen_address()), - A::F32(1e-6), - A::U64(grs), - A::U64(xn), - A::U64(0), - ], - )?; - self.finite(&mut commands, grs, nb * 4, 6)?; - Self::kernel( - &mut commands, - 0, - 12, - [(nb * 10240).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(rm), - A::U64(grs), - A::U64(wh[4].qwen_address()), - A::U64(self.status(6)?.qwen_address()), - A::I64(nb as i64), - ], - )?; - Self::kernel( - &mut commands, - 0, - 14, - [(nb * 10240).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(xn), - A::I32((nb * 10240) as i32), - A::U64(self.status(6)?.qwen_address()), - ], - )?; - commands.push(Cmd::Gemm { - x: r.handle(8, nb * 20480)?, - w: wh[5], - y: r.handle(9, nb * 1280)?, - rows: nb as i32, - n: 320, - k: 10240, - alpha: 1.0, - beta: 0.0, - }); - self.finite(&mut commands, lo, nb * 320, 7)?; - Self::kernel( - &mut commands, - 0, - 2, - [(nb * 320).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(lo), - A::U64(lo16), - A::U64(0), - A::I64((nb * 320) as i64), - ], - )?; - Self::kernel( - &mut commands, - 0, - 13, - [(nb * 320).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(lo), - A::U64(self.status(8)?.qwen_address()), - A::I64(nb as i64), - ], - )?; - Self::kernel( - &mut commands, - 0, - 14, - [(nb * 320).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(lo16), - A::I32((nb * 320) as i32), - A::U64(self.status(8)?.qwen_address()), - ], - )?; - commands.push(Cmd::Gemm { - x: r.handle(10, nb * 640)?, - w: wh[6], - y: r.handle(6, nb * 40960)?, - rows: nb as i32, - n: 10240, - k: 320, - alpha: 1.0, - beta: 0.0, - }); - self.finite(&mut commands, gated, nb * 10240, 9)?; - Self::kernel( - &mut commands, - 0, - 3, - [(nb * 2560).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(rm), - A::U64(grs), - A::U64(wh[4].qwen_address()), - A::U64(gated), - A::U64(mixed), - A::U64(0), - A::I64(nb as i64), - A::U64(mixedh), - A::U64(0), - ], - )?; - Self::kernel( - &mut commands, - 0, - 15, - [(nb * 10240).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(rm), - A::U64(grs), - A::U64(wh[4].qwen_address()), - A::U64(gated), - A::U64(self.status(10)?.qwen_address()), - A::I64(nb as i64), - ], - )?; - self.finite(&mut commands, mixed, nb * 2560, 10)?; - let kc = r.address(14, nb * 2048)?; - let vc = r.address(15, nb * 2048)?; - self.project( - &mut commands, - &r, - mixed, - wh[7].qwen_address(), - kc, - nb, - 512, - 0, - 11, - )?; - self.finite(&mut commands, kc, nb * 512, 11)?; - self.project( - &mut commands, - &r, - mixed, - wh[8].qwen_address(), - vc, - nb, - 512, - 0, - 12, - )?; - self.finite(&mut commands, vc, nb * 512, 12)?; - Self::kernel( - &mut commands, - 0, - 0, - [(nb * 2) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(kc), - A::U64(wh[9].qwen_address()), - A::I64(256), - A::I64(256), - A::F32(1e-6), - ], - )?; - self.finite(&mut commands, kc, nb * 512, 13)?; - Self::kernel( - &mut commands, - 0, - 6, - [(nb * 2) as u32, 1, 1], - [32, 1, 1], - 0, - vec![ - A::U64(kc), - A::I64(2), - A::I64(256), - A::I64(512), - A::I64(c0 as i64), - A::F32(policy.theta_scale), - A::F32(policy.freq_scale), - A::F32(policy.corr_low), - A::F32(policy.corr_high), - A::F32(policy.ext_factor), - A::F32(policy.mscale), - A::U64(0), - A::Words3([0; 3]), - ], - )?; - self.finite(&mut commands, kc, nb * 512, 14)?; - self.run( - rows, - workspace, - commands, - vec![(r.handle(16, nb * 4)?, tk), (r.handle(19, 16)?, bounds)], - )?; - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - let mapped = ring.mapped()?; - let mut host = [0u64; 8]; - for (i, n) in HOST_RUNS.into_iter().enumerate() { - host[i + 2] = mapped.address(HOST_OFFSETS[i], n)?; - } - let mut append = Vec::new(); - append - .try_reserve_exact(2) - .map_err(|_| Error::HostAllocation)?; - Self::kernel( - &mut append, - 0, - 7, - [nb as u32, 2, 8], - [64, 1, 1], - 0, - vec![ - A::U64(kc), - A::U64(vc), - A::I64(c0 as i64), - A::U64(ring.address(4)?), - A::I64(4), - A::U64(0), - A::U64(0), - A::U64(ring.address(0)?), - A::U64(ring.address(1)?), - A::U64(ring.address(2)?), - A::U64(ring.address(3)?), - A::Words8(host), - A::Words8([0; 8]), - ], - )?; - Self::kernel( - &mut append, - 0, - 10, - [64, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(ring.address(2)?), - A::U64(ring.address(3)?), - A::U64(ring.address(4)?), - A::I64(c0 as i64), - A::I32(nb as i32), - A::U64(self.status(15)?.qwen_address()), - ], - )?; - self.run(rows, workspace, append, Vec::new())?; - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - } - let mapped = ring.mapped()?; - for (p, runs) in changed.iter_mut().enumerate() { - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - mapped.read_into(HOST_OFFSETS[i] + (first_page + p) * n, &mut runs[i])?; - } - } - drop(mapped); - for runs in changed { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); - } - let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { - origin: ring.origin.clone(), - pages: Pages::from_vec(pages), - end, - checked: std::cell::Cell::new(false), - })); - ring.current = Some(snapshot.clone()); - ring.generation = generation; - Ok(DraftKvOutcome::Completed(CompletedDraftKv { - snapshot, - first_materialized: first, - end, - generation, - })) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - fn close_inner(&mut self) -> Result<()> { - self.failed = true; - let mut first = Ok(()); - for module in &mut self.modules { - if let Some(m) = module.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - self.context.poison(); - std::mem::forget(m); - Err(e) - } - } - }; - if r.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - first = combine(first, r); - } - } - for b in [&mut self.status, &mut self.tmp] { - if let Some(b) = b.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - b.release() - }; - first = combine(first, r); - } - } - if self.context.is_poisoned() { - self.context.retain_driver(); - } - first - } -} -impl Drop for OriginalMtpPrefill<'_> { - fn drop(&mut self) { - let _ = self.close_inner(); - } -} - -#[path = "mtp_original_scalar_prefill.rs"] -mod scalar; -pub use scalar::{ - CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, - OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, - OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, - OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, OriginalMtpStepOutput, -}; -pub(crate) use scalar::session_assets_sealed; +//! Literal prefill.cpp741..886, Q8_0 branch, on the actual borrowed prompt +//! region. Register as a PRIVATE child of mtp_original_int8: ring/host backing +//! never becomes a public address or a fabricated owning DeviceBuffer. +use super::*; +use crate::ffi::BufferHandle; +use crate::original_prefill_arena::OriginalPromptSpan; +use crate::{OriginalDeviceResidual, OriginalPromptRows}; +#[allow(unsafe_code)] +#[path = "mtp_original_prefill_ffi.rs"] +mod prefill_abi; +use prefill_abi::{Arg as A, Arguments as Args, Module as Mod}; +use std::ffi::CStr; +const RESERVE_BYTES: usize = 128 << 20; +const FLAG_WORDS: usize = 24; +const WIDTHS: [usize; 11] = [8, 16, 24, 32, 40, 48, 64, 80, 96, 112, 128]; +const ENTRIES: &[&CStr] = &[ + c"mtp_prefill_rms", + c"mtp_prefill_gr_norm", + c"mtp_prefill_gr_silu", + c"mtp_prefill_gr_mix", + c"mtp_prefill_broadcast", + c"mtp_prefill_embedding", + c"mtp_prefill_rope", + c"mtp_prefill_append", + c"mtp_prefill_finite", + c"mtp_prefill_iota", + c"mtp_prefill_encoded", + c"mtp_prefill_zero", + c"mtp_prefill_gr_norm_scan", + c"mtp_prefill_gr_silu_scan", + c"mtp_prefill_bf16_scan", + c"mtp_prefill_gr_product_scan", + c"mtp_prefill_q8_scan", +]; +#[path = "mtp_original_prefill_symbols.rs"] +mod symbols; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DraftKvFallback { + Disabled, + Empty, + UnsupportedStorage, + MissingWeights, + UnsupportedEmbedding, + AlternateF16, + RegionTooSmall, + NoQ8Tile, + UnsupportedRopeTable, +} +pub enum DraftKvOutcome { + Fallback(DraftKvFallback), + Skipped, + Cancelled, + Completed(CompletedDraftKv), +} +/// Actual completed range, not a readiness bit or a scalar committed product. +/// Root retains the lower materialized bound with its real draft window state. +pub struct CompletedDraftKv { + snapshot: MtpInt8Snapshot, + first_materialized: usize, + end: usize, + generation: u64, +} +impl CompletedDraftKv { + pub fn validate_current(&self, ring: &MtpOriginalInt8<'_>) -> Result<()> { + ring.validate_snapshot(&self.snapshot)?; + if ring.is_failed() + || ring.generation != self.generation + || self.snapshot.0.end != self.end + || self.first_materialized >= self.end + || ring + .current + .as_ref() + .is_none_or(|current| !Rc::ptr_eq(¤t.0, &self.snapshot.0)) + { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + pub fn first_materialized(&self) -> usize { + self.first_materialized + } + pub fn next_position(&self) -> usize { + self.end + } + pub fn owner_id(&self) -> MtpInt8OwnerId { + self.snapshot.owner_id() + } + pub fn generation(&self) -> u64 { + self.generation + } + pub fn snapshot_after(&self, position: usize) -> Result { + if position < self.first_materialized || position >= self.end { + return Err(Error::InvalidQwenShape); + } + if position + 1 == self.end { + return Ok(self.snapshot.clone()); + } + Ok(MtpInt8Snapshot(Rc::new(Snapshot { + origin: self.snapshot.0.origin.clone(), + pages: self.snapshot.0.pages.clone(), + end: position + 1, + checked: std::cell::Cell::new(self.snapshot.0.checked.get()), + }))) + } + /// Use only after checking the true requested window excludes pruned cells. + pub fn snapshot_for_window(&self, position: usize, window: usize) -> Result { + if window == 0 + || position >= self.end + || position + .checked_add(1) + .ok_or(Error::InvalidSize)? + .saturating_sub(window) + < self.first_materialized + { + return Err(Error::InvalidQwenShape); + } + self.snapshot_after(position) + } +} +/// These are actual whole matrix loans acquired by Root's binding owner. The +/// private runtime adapter independently checks descriptor/role identity. +pub struct OriginalMtpPrefillWeights<'a, 'ctx> { + pub embedding_norm: &'a DeviceBuffer<'ctx>, + pub embedding_fc: &'a DeviceBuffer<'ctx>, + pub hidden_norm: &'a DeviceBuffer<'ctx>, + pub hidden_fc: &'a DeviceBuffer<'ctx>, + pub gr_norm: &'a DeviceBuffer<'ctx>, + pub gr_down: &'a DeviceBuffer<'ctx>, + pub gr_up: &'a DeviceBuffer<'ctx>, + pub key: &'a DeviceBuffer<'ctx>, + pub value: &'a DeviceBuffer<'ctx>, + pub key_norm: &'a DeviceBuffer<'ctx>, +} +/// Entire real embedding source, never a borrowed raw pointer supplied by the +/// public protocol. Construction is private to authenticated source adapters. +pub struct OriginalMtpEmbedding<'a, 'ctx> { + table: &'a DeviceBuffer<'ctx>, + kind: EmbeddingKind, +} +enum EmbeddingKind { + Native { + kind: i32, + row_bytes: usize, + vocab: usize, + }, + Compressed { + bits: i32, + bias: i32, + group: usize, + vocab: usize, + codes: usize, + scales: usize, + offsets: bool, + }, +} +impl<'a, 'ctx> OriginalMtpEmbedding<'a, 'ctx> { + pub fn native( + table: &'a DeviceBuffer<'ctx>, + kind: i32, + row_bytes: usize, + vocab: usize, + ) -> Result { + let per = match kind { + 16 => 66, + 17 => 74, + 18 => 98, + 20 => 144, + 21 => 110, + 22 => 82, + 23 => 136, + 29 => 56, + 11 => 110, + 12 => 144, + 13 => 176, + 7 => 192, + 8 => 272, + 42 => 72, + 30 => 512, + _ => return Err(Error::UnsupportedProjection), + }; + if row_bytes != 10 * per + || vocab == 0 + || vocab > 262144 + || table.bytes != row_bytes.checked_mul(vocab).ok_or(Error::InvalidSize)? + { + return Err(Error::InvalidProjectionShape); + } + Ok(Self { + table, + kind: EmbeddingKind::Native { + kind, + row_bytes, + vocab, + }, + }) + } + pub fn compressed( + table: &'a DeviceBuffer<'ctx>, + bits: i32, + bias: i32, + group: usize, + vocab: usize, + offsets: bool, + ) -> Result { + if !matches!(bits, 2 | 4 | 8) + || group == 0 + || !2560usize.is_multiple_of(group) + || vocab == 0 + || vocab > 262144 + { + return Err(Error::InvalidProjectionShape); + } + let codes = vocab + .checked_mul(2560 / (8 / bits as usize)) + .ok_or(Error::InvalidSize)?; + let scales = vocab + .checked_mul(2560 / group) + .and_then(|n| n.checked_mul(4)) + .ok_or(Error::InvalidSize)?; + let total = codes + .checked_add( + scales + .checked_mul(if offsets { 2 } else { 1 }) + .ok_or(Error::InvalidSize)?, + ) + .ok_or(Error::InvalidSize)?; + if table.bytes != total { + return Err(Error::InvalidProjectionShape); + } + Ok(Self { + table, + kind: EmbeddingKind::Compressed { + bits, + bias, + group, + vocab, + codes, + scales, + offsets, + }, + }) + } + fn vocab(&self) -> usize { + match self.kind { + EmbeddingKind::Native { vocab, .. } | EmbeddingKind::Compressed { vocab, .. } => vocab, + } + } +} +/// Explicit Original optional policy. It cannot assert finite tensors, source +/// provenance, or readiness. Unsupported options produce fallback, never success. +pub struct DraftKvPolicy { + pub disabled: bool, + pub alternate_f16: bool, + pub rotated: bool, + pub q4: bool, + pub hybrid: bool, + pub mode: i32, + pub theta_scale: f32, + pub freq_scale: f32, + pub corr_low: f32, + pub corr_high: f32, + pub ext_factor: f32, + pub mscale: f32, + pub rope_table_enabled: bool, + pub multimodal_positions: bool, +} +impl DraftKvPolicy { + pub fn original_int8(theta_scale: f32) -> Self { + Self { + disabled: false, + alternate_f16: false, + rotated: false, + q4: false, + hybrid: false, + mode: 0, + theta_scale, + freq_scale: 1.0, + corr_low: 0.0, + corr_high: 0.0, + ext_factor: 0.0, + mscale: 1.0, + rope_table_enabled: false, + multimodal_positions: false, + } + } +} +enum Cmd { + Kernel { + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + args: Args, + }, + Copy { + dst: u64, + src: u64, + bytes: usize, + }, + Gemm { + x: BufferHandle, + w: BufferHandle, + y: BufferHandle, + rows: i32, + n: i32, + k: i32, + alpha: f32, + beta: f32, + }, +} +struct Region { + base: BufferHandle, + bytes: usize, + b: usize, + roles: [(usize, usize); 20], +} +fn fastdiv(d: u32) -> [u32; 3] { + let l = 32 - (d - 1).leading_zeros(); + [ + (((1u64 << 32) * ((1u64 << l) - u64::from(d)) / u64::from(d)) + 1) as u32, + l, + d, + ] +} +fn aligned(n: usize) -> Result { + n.checked_add(255) + .map(|n| n & !255) + .ok_or(Error::InvalidSize) +} +fn q8_bytes(rows: usize) -> Result { + rows.checked_mul(20 * 144) + .and_then(|n| n.checked_add(128 * 144)) + .ok_or(Error::InvalidSize) +} +impl Region { + fn new(base: BufferHandle, bytes: usize, n: usize, r0: usize) -> Result> { + // Literal Original per_row (including fixed128-block tail in q8_bytes(4,N)). + let per = 4 * (2 * 2560 + 4 * 10240 + 320 + 4 + 2560 + 2 * 512 + 1) + + 2 * (2560 + 2 * 10240 + 320 + 2560) + + 64 + + q8_bytes(4)? + + 4 * 4; + let b = (n - r0).min((bytes / per) & !63); + if b < 64 { + return Ok(None); + } + let widths = [ + b * 10240, + b * 10240, + b * 5120, + b * 40960, + b * 40960, + b * 40960, + b * 40960, + b * 20480, + b * 20480, + b * 1280, + b * 640, + b * 16, + b * 10240, + b * 5120, + b * 2048, + b * 2048, + b * 4, + q8_bytes(b * 4)?, + b * 16, + 16, + ]; + let mut end: usize = 0; + let mut roles = [(0, 0); 20]; + for (i, len) in widths.into_iter().enumerate() { + roles[i] = (end, len); + end = end.checked_add(aligned(len)?).ok_or(Error::InvalidSize)?; + } + if end > bytes { + return Ok(None); + } + base.validate_projection_extent(bytes, 256)?; + Ok(Some(Self { + base, + bytes, + b, + roles, + })) + } + fn handle(&self, i: usize, len: usize) -> Result { + let (offset, extent) = self.roles.get(i).copied().ok_or(Error::InvalidSize)?; + if len == 0 || len > extent { + return Err(Error::InvalidSize); + } + self.base.checked_subspan(self.bytes, offset, len) + } + fn address(&self, i: usize, len: usize) -> Result { + Ok(self.handle(i, len)?.qwen_address()) + } +} +pub struct OriginalMtpPrefill<'ctx> { + context: &'ctx Context<'ctx>, + modules: [Option; 5], + status: Option>, + tmp: Option>, + sms: usize, + shared_limit: u32, + failed: bool, +} +impl<'ctx> Context<'ctx> { + pub fn original_mtp_prefill(&'ctx self) -> Result> { + OriginalMtpPrefill::new(self) + } +} +impl<'ctx> OriginalMtpPrefill<'ctx> { + fn new(context: &'ctx Context<'ctx>) -> Result { + let assets = [ + include_bytes!("mtp_original_prefill.ptx").as_slice(), + include_bytes!("mtp_original_prefill_embedding.ptx").as_slice(), + include_bytes!("mtp_original_prefill_quant.ptx").as_slice(), + include_bytes!("mtp_original_prefill_mmq.ptx").as_slice(), + include_bytes!("mtp_original_prefill_fixup.ptx").as_slice(), + ]; + if assets + .iter() + .any(|a| a.windows(8).any(|w| w == b"UNSEALED")) + { + return Err(Error::UnsupportedQwenOperation); + } + let mut owner = Self { + context, + modules: std::array::from_fn(|_| None), + status: None, + tmp: None, + sms: 0, + shared_limit: 0, + failed: false, + }; + let result = (|| { + let g = context.enter()?; + let load = (|| { + owner.modules[0] = Some(Mod::load(assets[0], ENTRIES)?); + owner.modules[1] = Some(Mod::load(assets[1], &[c"mtp_prefill_native_embedding"])?); + owner.modules[2] = Some(Mod::load(assets[2], &[c"mtp_prefill_q8"])?); + owner.modules[3] = Some(Mod::load(assets[3], symbols::PROJECT)?); + owner.modules[4] = Some(Mod::load(assets[4], symbols::FIXUP)?); + let (sms, limit) = owner.module(0)?.info()?; + crate::arch_ptx::latch_stream_k_policy(); + owner.sms = sms; + owner.shared_limit = limit; + Ok(()) + })(); + let pop = g.finish(); + if pop.is_err() + || load.as_ref().is_err_and(|e| { + matches!(e, Error::Driver { .. } | Error::InvalidDriverValue(_)) + }) + { + owner.poison(); + } + combine(load, pop)?; + let charge = owner + .sms + .checked_mul(128 * 128 * 4) + .and_then(|n| n.checked_add(FLAG_WORDS * 4)) + .ok_or(Error::BudgetExceeded)?; + let required = charge + .checked_add(RESERVE_BYTES) + .ok_or(Error::BudgetExceeded)?; + if context + .allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > context.budget_bytes()) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + owner.status = Some(context.allocate(FLAG_WORDS * 4)?); + owner.tmp = Some(context.allocate(charge - FLAG_WORDS * 4)?); + Ok(()) + })(); + if let Err(e) = result { + return combine(Err(e), owner.close()); + } + Ok(owner) + } + pub fn allocated_bytes(&self) -> usize { + self.status.as_ref().map_or(0, DeviceBuffer::len) + + self.tmp.as_ref().map_or(0, DeviceBuffer::len) + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + fn poison(&mut self) { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + } + fn module(&self, i: usize) -> Result<&Mod> { + self.modules + .get(i) + .and_then(Option::as_ref) + .ok_or(Error::ContextPoisoned) + } + fn status(&self, i: usize) -> Result { + let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; + b.handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(b.bytes, i * 4, 4) + } + fn kernel( + cmds: &mut Vec, + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + args: Vec, + ) -> Result<()> { + cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; + cmds.push(Cmd::Kernel { + asset, + index, + grid, + block, + shared, + args: Args::new(args)?, + }); + Ok(()) + } + fn finite(&self, cmds: &mut Vec, data: u64, words: usize, stage: usize) -> Result<()> { + Self::kernel( + cmds, + 0, + 8, + [(words.div_ceil(256)) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(data), + A::I32(words as i32), + A::U64(self.status(stage)?.qwen_address()), + ], + ) + } + fn weight( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + w: &NativeBatchWorkspace<'_>, + b: &DeviceBuffer<'_>, + bytes: usize, + ) -> Result { + if b.bytes != bytes || !std::ptr::eq(b.context, self.context) { + return Err(Error::InvalidProjectionShape); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(bytes, 2)?; + w.reject_alias(h, bytes)?; + let (region, n) = rows.draft_kv_region()?; + let (r, rn) = rows.common_span(OriginalPromptSpan::R)?; + for (a, len) in [ + (region, n), + (r, rn), + ( + self.status + .as_ref() + .ok_or(Error::ContextPoisoned)? + .handle + .ok_or(Error::ContextPoisoned)?, + FLAG_WORDS * 4, + ), + ( + self.tmp + .as_ref() + .ok_or(Error::ContextPoisoned)? + .handle + .ok_or(Error::ContextPoisoned)?, + self.sms * 128 * 128 * 4, + ), + ] { + if h.overlaps(bytes, a, len) { + return Err(Error::OutputAliasesInput); + } + } + Ok(h) + } + #[allow(clippy::too_many_arguments)] + fn project( + &self, + cmds: &mut Vec, + r: &Region, + x: u64, + w: u64, + y: u64, + rows: usize, + out: usize, + bound_slot: usize, + stage: usize, + ) -> Result<()> { + if rows == 0 || rows > r.b * 4 || !matches!(out, 512 | 2560) { + return Err(Error::InvalidProjectionShape); + } + let mut best = None; + let mut ntx = usize::MAX; + for (i, j) in WIDTHS.into_iter().enumerate() { + if ntx <= 1 { + break; + } + let shared = 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024; + if shared > self.shared_limit as usize { + continue; + } + if rows.div_ceil(j) < ntx { + best = Some((i, j, shared)); + ntx = rows.div_ceil(j); + } + } + let (index, j, shared) = best.ok_or(Error::UnsupportedProjection)?; + let tiles = (out / 128) * ntx; + let efficiency = 100 * tiles / (self.sms * tiles.div_ceil(self.sms)); + let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { self.sms }; + let fix = !tiles.is_multiple_of(grid); + if tiles.checked_mul(80).is_none_or(|n| n >= 1 << 30) { + return Err(Error::InvalidProjectionShape); + } + let xq = r.address(17, q8_bytes(rows)?)?; + let ids = r.address(18, rows * 4)?; + let bound = r + .handle(19, 16)? + .checked_subspan(16, bound_slot * 8, 8)? + .qwen_address(); + Self::kernel( + cmds, + 2, + 0, + [rows as u32, 5, 1], + [128, 1, 1], + 0, + vec![ + A::U64(x), + A::U64(0), + A::U64(xq), + A::I64(2560), + A::I64(2560), + A::I64((rows * 2560) as i64), + A::I64((rows * 2560) as i64), + A::I64(2560), + A::I32(rows as i32), + A::I32(1), + A::I32(1), + ], + )?; + // Original D4 data includes a fixed128-block tail. Initialize that exact + // tail before a literal vendor kernel can speculatively load it. + Self::kernel( + cmds, + 0, + 11, + [72, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(xq + (rows * 20 * 144) as u64), + A::I32((128 * 144) as i32), + ], + )?; + Self::kernel( + cmds, + 0, + 16, + [(rows * 20).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(xq), + A::I32((rows * 20) as i32), + A::U64(self.status(stage)?.qwen_address()), + ], + )?; + let tmp = if fix { + self.tmp + .as_ref() + .ok_or(Error::ContextPoisoned)? + .handle + .ok_or(Error::ContextPoisoned)? + .qwen_address() + } else { + 0 + }; + let fd = fastdiv; + Self::kernel( + cmds, + 3, + index, + [grid as u32, 1, 1], + [32, 8, 1], + shared as u32, + vec![ + A::U64(w), + A::U64(xq), + A::U64(ids), + A::U64(bound), + A::U64(y), + A::U64(tmp), + A::U64(0), + A::U3(fd(80)), + A::I32(out as i32), + A::I32(rows as i32), + A::I32(80), + A::I32(rows as i32), + A::I32(out as i32), + A::U3(fd(1)), + A::U3(fd(1)), + A::I32((out * 80) as i32), + A::I32(0), + A::I32(0), + A::U3(fd(1)), + A::U3(fd(1)), + A::I32(0), + A::I32(0), + A::I32(0), + A::U3(fd(ntx as u32)), + ], + )?; + if fix { + Self::kernel( + cmds, + 4, + index, + [grid as u32, 4, 1], + [32, 4, 1], + 0, + vec![ + A::U64(ids), + A::U64(bound), + A::U64(y), + A::U64(tmp), + A::U3(fd(80)), + A::I32(out as i32), + A::I32(rows as i32), + A::I32(out as i32), + A::U3(fd(1)), + A::I32(0), + A::U3(fd(1)), + A::I32(0), + A::U3(fd(ntx as u32)), + ], + )?; + } + Ok(()) + } + fn run( + &mut self, + rows: &mut OriginalPromptRows<'_, '_, '_>, + w: &mut NativeBatchWorkspace<'ctx>, + mut cmds: Vec, + staging: Vec<(BufferHandle, Vec)>, + ) -> Result<()> { + let mut readback = zero_bytes(FLAG_WORDS * 4)?; + let zero = zero_bytes(FLAG_WORDS * 4)?; + let status = self + .status + .as_ref() + .ok_or(Error::ContextPoisoned)? + .handle + .ok_or(Error::ContextPoisoned)?; + status.validate_projection_extent(FLAG_WORDS * 4, 4)?; + for i in 0..5 { + self.module(i)?; + } + let blas = w.blas()?; + let g = match self.context.enter() { + Ok(g) => g, + Err(e) => { + self.poison(); + rows.mark_failed(); + w.mark_failed(); + return Err(e); + } + }; + let mut operation = self.context.driver.api.copy_from(status, &zero); + if operation.is_ok() { + for (dst, bytes) in &staging { + if let Err(e) = self.context.driver.api.copy_from(*dst, bytes) { + operation = Err(e); + break; + } + } + } + if operation.is_ok() { + operation = self.context.driver.api.synchronize(); + } + if operation.is_ok() { + for c in &mut cmds { + let r = match c { + Cmd::Kernel { + asset, + index, + grid, + block, + shared, + args, + } => self.modules[*asset] + .as_ref() + .map_or(Err(Error::ContextPoisoned), |m| { + m.launch(*index, *grid, *block, *shared, blas.stream(), args) + }), + Cmd::Copy { dst, src, bytes } => self.modules[0] + .as_ref() + .map_or(Err(Error::ContextPoisoned), |m| { + m.copy(*dst, *src, *bytes, blas.stream()) + }), + Cmd::Gemm { + x, + w, + y, + rows, + n, + k, + alpha, + beta, + } => blas.gemm_bf16(*x, *w, *y, *rows, *n, *k, alpha, beta), + }; + if let Err(e) = r { + operation = Err(e); + break; + } + } + } + let stream = blas.synchronize(); + if operation.is_ok() && stream.is_ok() { + operation = self.context.driver.api.copy_to(status, &mut readback); + } + let device = self.context.driver.api.synchronize(); + let pop = g.finish(); + if operation.is_err() || stream.is_err() || device.is_err() || pop.is_err() { + self.poison(); + rows.mark_failed(); + w.mark_failed(); + } + if stream.is_err() || device.is_err() || pop.is_err() { + std::mem::forget((cmds, staging, zero, readback)); + self.context.retain_driver(); + return combine(combine(combine(operation, stream), device), pop); + } + combine(combine(combine(operation, stream), device), pop)?; + for word in readback.chunks_exact(4) { + if u32::from_le_bytes(word.try_into().map_err(|_| Error::InvalidSize)?) > 1 { + self.poison(); + return Err(Error::InvalidDriverValue("draft prefill status")); + } + } + for (stage, word) in readback.chunks_exact(4).enumerate() { + if u32::from_le_bytes(word.try_into().map_err(|_| Error::InvalidSize)?) != 0 { + return Err(Error::NonFiniteMmqOutput(match stage { + 0 => "MTP embedding", + 1 => "MTP embedding norm", + 2 => "MTP FC embedding", + 3 => "MTP hidden norm", + 4 => "MTP FC hidden", + 5 => "MTP broadcast", + 6 => "MTP GR normalized", + 7 => "MTP GR down", + 8 => "MTP GR SiLU", + 9 => "MTP GR up", + 10 => "MTP GR mixed", + 11 => "MTP K", + 12 => "MTP V", + 13 => "MTP K norm", + 14 => "MTP K Rope", + _ => "MTP INT8 encoded", + })); + } + } + Ok(()) + } + #[allow(clippy::too_many_arguments)] + pub fn record<'arena, 'loan>( + &mut self, + residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + tokens: &[i32], + cell0: usize, + first_needed: usize, + weights: OriginalMtpPrefillWeights<'_, '_>, + embedding: OriginalMtpEmbedding<'_, '_>, + policy: &DraftKvPolicy, + mut cancelled: impl FnMut() -> bool, + ) -> Result { + if policy.disabled { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Disabled)); + } + if tokens.is_empty() { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Empty)); + } + if policy.mode != 0 || policy.hybrid || policy.rotated || policy.q4 { + return Ok(DraftKvOutcome::Fallback( + DraftKvFallback::UnsupportedStorage, + )); + } + if policy.alternate_f16 { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::AlternateF16)); + } + if policy.rope_table_enabled || policy.multimodal_positions { + return Ok(DraftKvOutcome::Fallback( + DraftKvFallback::UnsupportedRopeTable, + )); + } + if [ + policy.theta_scale, + policy.freq_scale, + policy.corr_low, + policy.corr_high, + policy.ext_factor, + policy.mscale, + ] + .iter() + .any(|x| !x.is_finite()) + || policy.theta_scale <= 0.0 + || policy.freq_scale <= 0.0 + || policy.mscale <= 0.0 + { + return Err(Error::InvalidProjectionShape); + } + ring.validate_snapshot(prior)?; + workspace.validate_context(self.context)?; + ring.validate_context(self.context)?; + if self.is_failed() + || !residual.context_matches(self.context) + || tokens.len() != residual.rows() + || tokens.len() > 8192 + || cell0 + .checked_add(tokens.len()) + .is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) + { + return Err(Error::InvalidProjectionShape); + } + if tokens + .iter() + .any(|t| *t < 0 || *t as usize >= embedding.vocab()) + { + return Err(Error::InvalidProjectionShape); + } + let r0 = first_needed.saturating_sub(cell0); + if r0 >= tokens.len() { + return Ok(DraftKvOutcome::Skipped); + } + let rows = residual.lease_mut(); + let (region, region_bytes) = rows.draft_kv_region()?; + let Some(r) = Region::new(region, region_bytes, tokens.len(), r0)? else { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::RegionTooSmall)); + }; + crate::bringup_trace!("DBG prefill.record: region ok b={} tokens={} r0={r0}", r.b, tokens.len()); + if !WIDTHS.into_iter().any(|j| { + 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024 <= self.shared_limit as usize + }) { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::NoQ8Tile)); + } + let weight_refs = [ + weights.embedding_norm, + weights.embedding_fc, + weights.hidden_norm, + weights.hidden_fc, + weights.gr_norm, + weights.gr_down, + weights.gr_up, + weights.key, + weights.value, + weights.key_norm, + ]; + let extents = [ + 10240, + 2560 * 80 * 34, + 40960, + 2560 * 80 * 34, + 40960, + 320 * 10240 * 2, + 10240 * 320 * 2, + 512 * 80 * 34, + 512 * 80 * 34, + 1024, + ]; + let mut wh = [region; 10]; + for i in 0..10 { + wh[i] = self.weight(rows, workspace, weight_refs[i], extents[i]).map_err(|e| { crate::bringup_trace!("DBG prefill.record: weight {i} err {e:?}"); e })?; + } + crate::bringup_trace!("DBG prefill.record: 10 weights staged"); + let eh = self.weight(rows, workspace, embedding.table, embedding.table.bytes).map_err(|e| { crate::bringup_trace!("DBG prefill.record: embedding table err {e:?}"); e })?; + crate::bringup_trace!("DBG prefill.record: embedding table staged"); + for (i, a) in weight_refs.iter().enumerate() { + for b in weight_refs.iter().take(i) { + let ah = a.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref a.handle is None (i={i})"); Error::ContextPoisoned })?; + let bh = b.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref b.handle is None (i={i})"); Error::ContextPoisoned })?; + if ah.overlaps(a.bytes, bh, b.bytes) + && !(ah.qwen_address() == bh.qwen_address() && a.bytes == b.bytes) + { + return Err(Error::OutputAliasesInput); + } + } + } + for b in weight_refs { + let h = b.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight b.handle is None (embedding overlap)"); Error::ContextPoisoned })?; + if eh.overlaps(embedding.table.bytes, h, b.bytes) + && !(eh.qwen_address() == h.qwen_address() && embedding.table.bytes == b.bytes) + { + return Err(Error::OutputAliasesInput); + } + } + // Actual input residual lies outside the region being overwritten. + let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R).map_err(|e| { crate::bringup_trace!("DBG prefill.record: common_span(R) err {e:?}"); e })?; + crate::bringup_trace!("DBG prefill.record: weights vs embedding overlap ok, R span ok"); + if rh.overlaps(rbytes, region, region_bytes) { + return Err(Error::OutputAliasesInput); + } + // The serve ring is built from prepared spans of the drafter's shared region, so buffers 0..5 are not + // separately owned DeviceBuffers; compare by address (ring.address works for both layouts). + for i in 0..5 { + let hv = ring.address(i)?; + let n = ring.sizes[i]; + let ov = |o: u64, on: usize| hv < o.saturating_add(on as u64) && o < hv.saturating_add(n as u64); + if ov(region.qwen_address(), region_bytes) + || ov(rh.qwen_address(), rbytes) + || wh.iter().zip(extents).any(|(w, n2)| ov(w.qwen_address(), n2)) + || ov(eh.qwen_address(), embedding.table.bytes) + { + return Err(Error::OutputAliasesInput); + } + } + crate::bringup_trace!("DBG prefill.record: overlap checks ok"); + let generation = ring + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + let end = cell0 + tokens.len(); + let first = cell0 + r0; + let first_page = first / 4; + let page_count = end.div_ceil(4); + let mut pages = Vec::new(); + pages + .try_reserve_exact(page_count) + .map_err(|_| Error::HostAllocation)?; + let mut changed = Vec::new(); + changed + .try_reserve_exact(page_count - first_page) + .map_err(|_| Error::HostAllocation)?; + for p in 0..page_count { + if p < first_page { + if let Some(page) = prior.0.pages.get(p) { + pages.push(page.clone()); + continue; + } + } + let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + runs[i] = zero_bytes(n)?; + } + if p < first_page { + pages.push(Rc::new(Page { + runs: runs.map(Vec::into_boxed_slice), + })); + } else { + changed.push(runs); + } + } + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + // Genuine idle dependency before this stream can mutate the real drafter KV. + crate::bringup_trace!("DBG prefill.record: pages ready, ring.execute(idle)"); + ring.execute(workspace, Vec::new()).map_err(|e| { crate::bringup_trace!("DBG prefill.record: ring.execute err {e:?}"); e })?; // genuine global + shared drafter stream idle, even identical snapshot + ring.restore(workspace, prior).map_err(|e| { crate::bringup_trace!("DBG prefill.record: ring.restore err {e:?}"); e })?; + crate::bringup_trace!("DBG prefill.record: ring restored"); + ring.current = None; + for b0 in (r0..tokens.len()).step_by(r.b) { + let nb = r.b.min(tokens.len() - b0); + let c0 = cell0 + b0; + crate::bringup_trace!("DBG prefill.record: block b0={b0} nb={nb} c0={c0}"); + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + let mut commands = Vec::new(); + commands + .try_reserve_exact(80) + .map_err(|_| Error::HostAllocation)?; + let mut tk = zero_bytes(nb * 4)?; + for (dst, t) in tk.chunks_exact_mut(4).zip(&tokens[b0..b0 + nb]) { + dst.copy_from_slice(&t.to_le_bytes()); + } + let mut bounds = zero_bytes(16)?; + for (dst, v) in bounds + .chunks_exact_mut(4) + .zip([0, nb as i32, 0, (nb * 4) as i32]) + { + dst.copy_from_slice(&v.to_le_bytes()); + } + Self::kernel( + &mut commands, + 0, + 9, + [(nb * 4).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![A::U64(r.address(18, nb * 16)?), A::I32((nb * 4) as i32)], + )?; + let emb = r.address(0, nb * 10240)?; + let tok = r.address(16, nb * 4)?; + match embedding.kind { + EmbeddingKind::Native { + kind, row_bytes, .. + } => Self::kernel( + &mut commands, + 1, + 0, + [10, nb as u32, 1], + [32, 1, 1], + 0, + vec![ + A::I32(kind), + A::U64(eh.qwen_address()), + A::U64(row_bytes as u64), + A::U64(tok), + A::I64(2560), + A::U64(emb), + ], + )?, + EmbeddingKind::Compressed { + bits, + bias, + group, + codes, + scales, + offsets, + .. + } => Self::kernel( + &mut commands, + 0, + 5, + [10, nb as u32, 1], + [256, 1, 1], + 0, + vec![ + A::U64(eh.qwen_address()), + A::U64(eh.qwen_address() + codes as u64), + A::U64(if offsets { + eh.qwen_address() + (codes + scales) as u64 + } else { + 0 + }), + A::U64(tok), + A::I64(2560), + A::I32(bits), + A::I32(bias), + A::I32(group as i32), + A::U64((2560 / (8 / bits)) as u64), + A::U64((2560 / group) as u64), + A::U64(emb), + ], + )?, + } + self.finite(&mut commands, emb, nb * 2560, 0)?; + Self::kernel( + &mut commands, + 0, + 0, + [nb as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(emb), + A::U64(wh[0].qwen_address()), + A::I64(2560), + A::I64(2560), + A::F32(1e-6), + ], + )?; + self.finite(&mut commands, emb, nb * 2560, 1)?; + let e2 = r.address(1, nb * 10240)?; + self.project( + &mut commands, + &r, + emb, + wh[1].qwen_address(), + e2, + nb, + 2560, + 0, + 2, + )?; + self.finite(&mut commands, e2, nb * 2560, 2)?; + let hn = r.address(3, nb * 40960)?; + let h2 = r.address(4, nb * 40960)?; + commands.push(Cmd::Copy { + dst: hn, + src: rh + .checked_subspan(rbytes, b0 * 40960, nb * 40960)? + .qwen_address(), + bytes: nb * 40960, + }); + Self::kernel( + &mut commands, + 0, + 0, + [nb as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(hn), + A::U64(wh[2].qwen_address()), + A::I64(10240), + A::I64(10240), + A::F32(1e-6), + ], + )?; + self.finite(&mut commands, hn, nb * 10240, 3)?; + self.project( + &mut commands, + &r, + hn, + wh[3].qwen_address(), + h2, + nb * 4, + 2560, + 1, + 4, + )?; + self.finite(&mut commands, h2, nb * 10240, 4)?; + let rm = r.address(5, nb * 40960)?; + let gated = r.address(6, nb * 40960)?; + let xn = r.address(8, nb * 20480)?; + let lo = r.address(9, nb * 1280)?; + let lo16 = r.address(10, nb * 640)?; + let grs = r.address(11, nb * 16)?; + let mixed = r.address(12, nb * 10240)?; + let mixedh = r.address(13, nb * 5120)?; + Self::kernel( + &mut commands, + 0, + 4, + [40, nb as u32, 1], + [256, 1, 1], + 0, + vec![A::U64(h2), A::U64(e2), A::U64(rm), A::I64(2560), A::I32(4)], + )?; + self.finite(&mut commands, rm, nb * 10240, 5)?; + Self::kernel( + &mut commands, + 0, + 1, + [(nb * 4) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(rm), + A::U64(wh[4].qwen_address()), + A::F32(1e-6), + A::U64(grs), + A::U64(xn), + A::U64(0), + ], + )?; + self.finite(&mut commands, grs, nb * 4, 6)?; + Self::kernel( + &mut commands, + 0, + 12, + [(nb * 10240).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(rm), + A::U64(grs), + A::U64(wh[4].qwen_address()), + A::U64(self.status(6)?.qwen_address()), + A::I64(nb as i64), + ], + )?; + Self::kernel( + &mut commands, + 0, + 14, + [(nb * 10240).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(xn), + A::I32((nb * 10240) as i32), + A::U64(self.status(6)?.qwen_address()), + ], + )?; + commands.push(Cmd::Gemm { + x: r.handle(8, nb * 20480)?, + w: wh[5], + y: r.handle(9, nb * 1280)?, + rows: nb as i32, + n: 320, + k: 10240, + alpha: 1.0, + beta: 0.0, + }); + self.finite(&mut commands, lo, nb * 320, 7)?; + Self::kernel( + &mut commands, + 0, + 2, + [(nb * 320).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(lo), + A::U64(lo16), + A::U64(0), + A::I64((nb * 320) as i64), + ], + )?; + Self::kernel( + &mut commands, + 0, + 13, + [(nb * 320).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(lo), + A::U64(self.status(8)?.qwen_address()), + A::I64(nb as i64), + ], + )?; + Self::kernel( + &mut commands, + 0, + 14, + [(nb * 320).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(lo16), + A::I32((nb * 320) as i32), + A::U64(self.status(8)?.qwen_address()), + ], + )?; + commands.push(Cmd::Gemm { + x: r.handle(10, nb * 640)?, + w: wh[6], + y: r.handle(6, nb * 40960)?, + rows: nb as i32, + n: 10240, + k: 320, + alpha: 1.0, + beta: 0.0, + }); + self.finite(&mut commands, gated, nb * 10240, 9)?; + Self::kernel( + &mut commands, + 0, + 3, + [(nb * 2560).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(rm), + A::U64(grs), + A::U64(wh[4].qwen_address()), + A::U64(gated), + A::U64(mixed), + A::U64(0), + A::I64(nb as i64), + A::U64(mixedh), + A::U64(0), + ], + )?; + Self::kernel( + &mut commands, + 0, + 15, + [(nb * 10240).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(rm), + A::U64(grs), + A::U64(wh[4].qwen_address()), + A::U64(gated), + A::U64(self.status(10)?.qwen_address()), + A::I64(nb as i64), + ], + )?; + self.finite(&mut commands, mixed, nb * 2560, 10)?; + let kc = r.address(14, nb * 2048)?; + let vc = r.address(15, nb * 2048)?; + self.project( + &mut commands, + &r, + mixed, + wh[7].qwen_address(), + kc, + nb, + 512, + 0, + 11, + )?; + self.finite(&mut commands, kc, nb * 512, 11)?; + self.project( + &mut commands, + &r, + mixed, + wh[8].qwen_address(), + vc, + nb, + 512, + 0, + 12, + )?; + self.finite(&mut commands, vc, nb * 512, 12)?; + Self::kernel( + &mut commands, + 0, + 0, + [(nb * 2) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(kc), + A::U64(wh[9].qwen_address()), + A::I64(256), + A::I64(256), + A::F32(1e-6), + ], + )?; + self.finite(&mut commands, kc, nb * 512, 13)?; + Self::kernel( + &mut commands, + 0, + 6, + [(nb * 2) as u32, 1, 1], + [32, 1, 1], + 0, + vec![ + A::U64(kc), + A::I64(2), + A::I64(256), + A::I64(512), + A::I64(c0 as i64), + A::F32(policy.theta_scale), + A::F32(policy.freq_scale), + A::F32(policy.corr_low), + A::F32(policy.corr_high), + A::F32(policy.ext_factor), + A::F32(policy.mscale), + A::U64(0), + A::Words3([0; 3]), + ], + )?; + self.finite(&mut commands, kc, nb * 512, 14)?; + self.run( + rows, + workspace, + commands, + vec![(r.handle(16, nb * 4)?, tk), (r.handle(19, 16)?, bounds)], + )?; + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + let mapped = ring.mapped()?; + let mut host = [0u64; 8]; + for (i, n) in HOST_RUNS.into_iter().enumerate() { + host[i + 2] = mapped.address(HOST_OFFSETS[i], n)?; + } + let mut append = Vec::new(); + append + .try_reserve_exact(2) + .map_err(|_| Error::HostAllocation)?; + Self::kernel( + &mut append, + 0, + 7, + [nb as u32, 2, 8], + [64, 1, 1], + 0, + vec![ + A::U64(kc), + A::U64(vc), + A::I64(c0 as i64), + A::U64(ring.address(4)?), + A::I64(4), + A::U64(0), + A::U64(0), + A::U64(ring.address(0)?), + A::U64(ring.address(1)?), + A::U64(ring.address(2)?), + A::U64(ring.address(3)?), + A::Words8(host), + A::Words8([0; 8]), + ], + )?; + Self::kernel( + &mut append, + 0, + 10, + [64, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(ring.address(2)?), + A::U64(ring.address(3)?), + A::U64(ring.address(4)?), + A::I64(c0 as i64), + A::I32(nb as i32), + A::U64(self.status(15)?.qwen_address()), + ], + )?; + self.run(rows, workspace, append, Vec::new())?; + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + } + let mapped = ring.mapped()?; + for (p, runs) in changed.iter_mut().enumerate() { + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + mapped.read_into(HOST_OFFSETS[i] + (first_page + p) * n, &mut runs[i])?; + } + } + drop(mapped); + for runs in changed { + pages.push(Rc::new(Page { + runs: runs.map(Vec::into_boxed_slice), + })); + } + let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { + origin: ring.origin.clone(), + pages: Pages::from_vec(pages), + end, + checked: std::cell::Cell::new(false), + })); + ring.current = Some(snapshot.clone()); + ring.generation = generation; + Ok(DraftKvOutcome::Completed(CompletedDraftKv { + snapshot, + first_materialized: first, + end, + generation, + })) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let mut first = Ok(()); + for module in &mut self.modules { + if let Some(m) = module.take() { + let r = if self.context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine(m.close(), g.finish()), + Err(e) => { + self.context.poison(); + std::mem::forget(m); + Err(e) + } + } + }; + if r.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + first = combine(first, r); + } + } + for b in [&mut self.status, &mut self.tmp] { + if let Some(b) = b.take() { + let r = if self.context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + b.release() + }; + first = combine(first, r); + } + } + if self.context.is_poisoned() { + self.context.retain_driver(); + } + first + } +} +impl Drop for OriginalMtpPrefill<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} + +#[path = "mtp_original_scalar_prefill.rs"] +mod scalar; +pub use scalar::{ + CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, + OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, + OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, + OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, OriginalMtpStepOutput, +}; +pub(crate) use scalar::session_assets_sealed; diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill.rs index 168cf98c..2756e5b4 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill.rs @@ -1,1481 +1,1481 @@ -//! Literal MtpDrafter::record_forward(full=false), groups <= actual max_t. -//! Private child of Original prefill. K/V, Q8 scratch and mapped host are the -//! actual MtpOriginalInt8 owner; no half-cache or batch-GEMM substitution. -use super::*; -#[allow(unsafe_code)] -#[path = "mtp_original_scalar_ffi.rs"] -mod scalar_abi; -use crate::{ - OriginalGpuStream, OriginalGraphKey, OriginalGraphRegistry, OriginalGraphResources, - OriginalStreamKind, -}; -use scalar_abi::{Arg, Arguments, Module}; -#[path = "mtp_original_scalar_weights.rs"] -mod retained_weights; -pub use retained_weights::OriginalMtpRetainedScalarWeights; -#[allow(unsafe_code)] -#[path = "mtp_original_scalar_mapped.rs"] -mod mapped_records; -use std::cell::RefCell; -#[allow(unsafe_code)] -#[path = "mtp_original_physical_layout.rs"] -mod physical_layout; -struct OriginalLayoutSetup<'ctx> { - layout: physical_layout::Layout, - bank: Rc>, - mapped: Rc>, -} -struct GraphResources<'ctx> { - context: &'ctx Context<'ctx>, - modules: [Rc; 6], - scratch: Rc>, - records: Rc>, - status: Rc>, - mapped: Rc>>, - ring: MtpOriginalRingResources<'ctx>, - weights: Rc>, - commands: Vec, -} -impl crate::original_gpu_schedule::resources::Sealed for GraphResources<'_> {} -impl OriginalGraphResources for GraphResources<'_> { - fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - self.ring.validate_context(c)?; - self.weights.validate_context(c)?; - for b in [&self.scratch, &self.records, &self.status] { - checked(c, b, b.bytes)?; - } - if self - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .is_none() - { - return Err(Error::ContextPoisoned); - } - Ok(()) - } -} - -const MAX_PROMPT: usize = 8192; -const SCALAR_FLAGS: usize = 16; -const GR_ENTRIES: &[&CStr] = &[ - c"mtp_scalar_gr_norm", - c"mtp_scalar_gr_split", - c"mtp_scalar_gr_staged", - c"mtp_scalar_gr_up", - c"mtp_scalar_gr_down1280", - c"mtp_scalar_gr_down2560", -]; -#[derive(Clone, Copy, PartialEq, Eq)] -pub enum OriginalMtpGrVariant { - Plain, - Split, - Staged, -} -/// Actual Original policy result, not an attestation about inputs/weights. -/// GR_V3 is deliberately a separate producer, not substituted here. -pub struct OriginalMtpScalarPolicy { - pub gr: OriginalMtpGrVariant, - pub per_group_sync: bool, - pub kv: DraftKvPolicy, -} -pub struct OriginalMtpScalarWeights<'a, 'ctx> { - pub input: OriginalMtpPrefillWeights<'a, 'ctx>, - pub gr_inject: &'a DeviceBuffer<'ctx>, -} -// Actual first twelve Original input/read roles plus token,step,position. One -// whole physical owner, each closed range derives from this exact carve. -struct Scratch { - sizes: [usize; 16], - offsets: [usize; 16], - bytes: usize, -} -impl Scratch { - fn new(t: usize) -> Result { - if !(1..=8).contains(&t) { - return Err(Error::InvalidQwenShape); - } - let sizes = [ - t * 40960, - t * 40960, - t * 10240, - t * 10240, - t * 10240, - t * 40960, - t * 40960, - t * 40960, - t * 1280, - t * 16, - t * 16, - t * 10240, - t * 4, - t * 16, - t * 96, - 8 * 80 * 36, - ]; - let mut offsets = [0; 16]; - let mut bytes = 0usize; - for (i, n) in sizes.into_iter().enumerate() { - offsets[i] = bytes; - bytes = bytes.checked_add(aligned(n)?).ok_or(Error::InvalidSize)?; - } - Ok(Self { - sizes, - offsets, - bytes, - }) - } -} - -#[path = "mtp_original_full_forward.rs"] -mod full_forward; -pub use full_forward::{ - CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, - OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, - OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpStepOutput, -}; -pub(crate) use full_forward::session_assets_sealed; -enum ScalarCommand { - Kernel { - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - args: Arguments, - }, - Copy { - dst: u64, - src: u64, - bytes: usize, - }, -} -/// Real affine scalar producer. Cached Original capture must retain this owner -/// AND genuine model-lifetime whole weights (see the explicit graph handoff). -pub struct OriginalMtpScalarPrefill<'ctx> { - context: &'ctx Context<'ctx>, - max_t: usize, - prompt_cap: usize, - modules: [Option>; 6], - scratch: Option>>, - records: Option>>, - status: Option>>, - layout: Scratch, - original_layout: Option, - shared_limit: usize, - plain_tile: usize, - stream: Option>, - failed: bool, - graphs: Option>>, - mapped: Rc>>, - retained: Option>>, - ring_id: Option, - policy_key: Option<[u32; 9]>, - pending_host: Vec>, - graph_metadata_bytes: usize, - has_pending: bool, -} -impl<'ctx> Context<'ctx> { - pub fn original_mtp_scalar_prefill( - &'ctx self, - max_t: usize, - prompt_cap: usize, - ) -> Result> { - OriginalMtpScalarPrefill::new(self, max_t, prompt_cap) - } -} -impl<'ctx> OriginalMtpScalarPrefill<'ctx> { - fn assets_ready() -> Result<()> { - let assets = [ - include_bytes!("mtp_original_prefill.ptx").as_slice(), - include_bytes!("mtp_original_prefill_embedding.ptx").as_slice(), - include_bytes!("mtp_original_tail.ptx").as_slice(), - include_bytes!("mtp_original_scalar_norm.ptx").as_slice(), - include_bytes!("mtp_original_scalar_gr.ptx").as_slice(), - include_bytes!("mtp_original_kv.ptx").as_slice(), - ]; - if assets - .iter() - .any(|p| p.windows(8).any(|w| w == b"UNSEALED")) - { - Err(Error::UnsupportedQwenOperation) - } else { - Ok(()) - } - } - pub fn planned_device_bytes(max_t: usize, prompt_cap: usize) -> Result { - if !(1..=MAX_PROMPT).contains(&prompt_cap) { - return Err(Error::InvalidQwenShape); - } - Scratch::new(max_t)? - .bytes - .checked_add(prompt_cap.checked_mul(29 * 4).ok_or(Error::InvalidSize)?) - .and_then(|n| n.checked_add((prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4)) - .ok_or(Error::InvalidSize) - } - pub fn planned_host_bytes(max_t: usize, prompt_cap: usize) -> Result { - Self::planned_device_bytes(max_t, prompt_cap)?; - let timeline = (prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4; - // New per-call immutable host snapshot may include absent pruned-prefix pages; - // charge its real worst-case payload+catalog separately from the existing - // physical mapped ring. Cached graph metadata is bounded per actual T/key. - let snapshot = MTP_ORIGINAL_MAX_CELLS - .div_ceil(4) - .checked_mul(4224 + 128) - .ok_or(Error::BudgetExceeded)?; - (2 * max_t) - .checked_mul(512 * 1024) - .and_then(|n| { - n.checked_add(prompt_cap * 29 * 4 + max_t * 29 * 4 + 2 * timeline + 64 * 1024) - }) - .and_then(|n| n.checked_add(snapshot)) - .ok_or(Error::BudgetExceeded) - } - pub fn host_metadata_bytes(&self) -> usize { - self.graphs - .as_ref() - .map_or(0, OriginalGraphRegistry::metadata_bytes) - + self.graph_metadata_bytes - + std::mem::size_of::() - + self.pending_host.capacity() * std::mem::size_of::>() - } - pub fn pinned_host_bytes(&self) -> usize { - if self.original_layout.is_some() { - self.max_t * 236 + 384 - } else { - self.max_t * 29 * 4 - } - } - fn new(c: &'ctx Context<'ctx>, max_t: usize, prompt_cap: usize) -> Result { - Self::new_internal(c, max_t, prompt_cap, None) - } - fn new_internal( - c: &'ctx Context<'ctx>, - max_t: usize, - prompt_cap: usize, - exact: Option>, - ) -> Result { - let legacy_charge = Self::planned_device_bytes(max_t, prompt_cap)?; - let charge = if exact.is_some() { - legacy_charge - .checked_sub(Scratch::new(max_t)?.bytes) - .ok_or(Error::InvalidSize)? - } else { - legacy_charge - }; - if let Some(e) = &exact { - if e.layout.t != max_t { - return Err(Error::InvalidQwenShape); - } - checked(c, &e.bank, e.layout.bytes)?; - } - let assets = [ - include_bytes!("mtp_original_prefill.ptx").as_slice(), - include_bytes!("mtp_original_prefill_embedding.ptx").as_slice(), - include_bytes!("mtp_original_tail.ptx").as_slice(), - include_bytes!("mtp_original_scalar_norm.ptx").as_slice(), - include_bytes!("mtp_original_scalar_gr.ptx").as_slice(), - include_bytes!("mtp_original_kv.ptx").as_slice(), - ]; - if assets - .iter() - .any(|p| p.windows(8).any(|w| w == b"UNSEALED")) - { - return Err(Error::UnsupportedQwenOperation); - } - let required = charge - .checked_add(RESERVE_BYTES) - .ok_or(Error::BudgetExceeded)?; - if c.is_poisoned() || c.handle.is_none() { - return Err(Error::ContextPoisoned); - } - if c.allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > c.budget_bytes()) - || c.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - let mut o = Self { - context: c, - max_t, - prompt_cap, - modules: std::array::from_fn(|_| None), - scratch: None, - records: None, - status: None, - layout: match &exact { - Some(e) => e.layout.scalar(), - None => Scratch::new(max_t)?, - }, - original_layout: exact.as_ref().map(|e| e.layout.clone()), - shared_limit: 0, - plain_tile: 0, - stream: None, - failed: false, - graphs: None, - mapped: Rc::new(RefCell::new(None)), - retained: None, - ring_id: None, - policy_key: None, - pending_host: Vec::new(), - graph_metadata_bytes: 0, - has_pending: false, - }; - let operation = (|| { - let g = c.enter().inspect_err(|_| { - c.poison(); - c.retain_driver(); - })?; - let load = (|| { - o.modules[0] = Some(Rc::new(Module::load(assets[0], ENTRIES)?)); - o.modules[1] = Some(Rc::new(Module::load( - assets[1], - &[c"mtp_prefill_native_embedding"], - )?)); - o.modules[2] = Some(Rc::new(Module::load(assets[2], TAIL_ENTRIES)?)); - o.modules[3] = Some(Rc::new(Module::load( - assets[3], - &[ - c"mtp_scalar_norm1024", - c"mtp_scalar_rope", - c"mtp_scalar_copy_i32", - c"mtp_scalar_encoded", - ], - )?)); - o.modules[4] = Some(Rc::new(Module::load(assets[4], GR_ENTRIES)?)); - o.modules[5] = Some(Rc::new(Module::load(assets[5], KV_ENTRIES)?)); - let (shared, tile) = o.module(4)?.configure_gr()?; - o.shared_limit = shared; - o.plain_tile = tile; - Ok(()) - })(); - let pop = g.finish(); - if load.is_err() || pop.is_err() { - o.poison(); - } - combine(load, pop)?; - o.scratch = Some(match &exact { - Some(e) => Rc::clone(&e.bank), - None => Rc::new(c.allocate(o.layout.bytes)?), - }); - o.records = Some(Rc::new(c.allocate(prompt_cap * 29 * 4)?)); - o.status = Some(Rc::new( - c.allocate((prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4)?, - )); - o.stream = Some(c.original_gpu_stream(OriginalStreamKind::NonBlocking)?); - let g = c.enter().inspect_err(|_| { - c.poison(); - c.retain_driver(); - })?; - let allocation = match &exact { - Some(e) => Ok(mapped_records::MappedOwner::original( - max_t, - Rc::clone(&e.mapped), - )), - None => mapped_records::MappedOwner::new(max_t), - }; - let pop = g.finish(); - if pop.is_err() { - o.poison(); - let original = match allocation { - Ok(owner) => { - std::mem::forget(owner); - Ok(()) - } - Err(e) => Err(e), - }; - return combine(original, pop); - } - if allocation.is_err() { - o.poison(); - } - *o.mapped.borrow_mut() = Some(allocation?); - o.graphs = Some(OriginalGraphRegistry::new(c, 2 * max_t)?); - o.pending_host - .try_reserve_exact(2) - .map_err(|_| Error::HostAllocation)?; - if c.memory_info()?.0 < RESERVE_BYTES { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = operation { - return combine(Err(e), o.close()); - } - Ok(o) - } - pub fn allocated_bytes(&self) -> usize { - [&self.scratch, &self.records, &self.status] - .into_iter() - .map(|s| s.as_ref().map_or(0, |b| b.len())) - .sum() - } - pub fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() - } - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - self.validate() - } - fn validate(&self) -> Result<()> { - if self.is_failed() - || self.modules.iter().any(Option::is_none) - || self - .stream - .as_ref() - .is_none_or(OriginalGpuStream::is_failed) - { - return Err(Error::ContextPoisoned); - } - for (b, n) in [ - (&self.scratch, self.layout.bytes), - (&self.records, self.prompt_cap * 29 * 4), - ( - &self.status, - (self.prompt_cap.div_ceil(self.max_t) + 1) * SCALAR_FLAGS * 4, - ), - ] { - let b = b.as_ref().ok_or(Error::ContextPoisoned)?; - checked(self.context, b, n)?; - } - Ok(()) - } - fn poison(&mut self) { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - } - fn module(&self, i: usize) -> Result<&Module> { - self.modules - .get(i) - .and_then(Option::as_ref) - .map(Rc::as_ref) - .ok_or(Error::ContextPoisoned) - } - fn scratch(&self, i: usize, n: usize) -> Result { - let b = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; - if n == 0 || n > self.layout.sizes[i] { - return Err(Error::InvalidSize); - } - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, self.layout.offsets[i], n) - } - fn address(&self, i: usize, n: usize) -> Result { - Ok(self.scratch(i, n)?.qwen_address()) - } - fn current_kv(&self, ring: &MtpOriginalInt8<'ctx>) -> Result<(u64, u64)> { - match &self.original_layout { - Some(l) => { - let b = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; - Ok(( - l.span(b, 22, 0, self.max_t * 2048)?.qwen_address(), - l.span(b, 23, 0, self.max_t * 2048)?.qwen_address(), - )) - } - None => Ok((ring.address(6)?, ring.address(7)?)), - } - } - fn flag(&self, group: usize, stage: usize) -> Result { - let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; - if stage >= SCALAR_FLAGS { - return Err(Error::InvalidSize); - } - Ok(b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, (group * SCALAR_FLAGS + stage) * 4, 4)? - .qwen_address()) - } - #[allow(clippy::too_many_arguments)] - fn kernel( - cmds: &mut Vec, - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - args: Vec, - ) -> Result<()> { - cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; - cmds.push(ScalarCommand::Kernel { - asset, - index, - grid, - block, - shared, - args: Arguments::new(args)?, - }); - Ok(()) - } - fn finite( - &self, - cmds: &mut Vec, - data: u64, - n: usize, - _g: usize, - s: usize, - ) -> Result<()> { - Self::kernel( - cmds, - 2, - 11, - [n.div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(data), - Arg::I32(n as i32), - Arg::U64(self.flag(0, s)?), - ], - ) - } - fn q8_guard( - &self, - cmds: &mut Vec, - q: u64, - rows: usize, - _g: usize, - s: usize, - ) -> Result<()> { - Self::kernel( - cmds, - 2, - 12, - [(rows * 80).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(q), - Arg::I32((rows * 80) as i32), - Arg::U64(self.flag(0, s)?), - ], - ) - } - fn quant(cmds: &mut Vec, x: u64, q: u64, rows: usize) -> Result<()> { - Self::kernel( - cmds, - 2, - 0, - [(rows * 2560).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![Arg::U64(x), Arg::U64(q), Arg::I32((rows * 2560) as i32)], - ) - } - fn project( - cmds: &mut Vec, - w: u64, - q: u64, - y: u64, - rows: usize, - out: usize, - ) -> Result<()> { - if !(1..=8).contains(&rows) || !matches!(out, 512 | 2560) { - return Err(Error::InvalidProjectionShape); - } - Self::kernel( - cmds, - 2, - rows, - [out as u32, 1, 1], - [32, 4, 1], - 0, - vec![ - Arg::U64(w), - Arg::U64(q), - Arg::U64(y), - Arg::I32(2560), - Arg::I32(out as i32), - ], - ) - } - fn external( - &self, - rows: &OriginalPromptRows<'_, '_, '_>, - w: &NativeBatchWorkspace<'_>, - ring: &MtpOriginalInt8<'_>, - b: &DeviceBuffer<'_>, - n: usize, - ) -> Result { - checked(self.context, b, n)?; - let h = b.handle.ok_or(Error::ContextPoisoned)?; - w.reject_alias(h, n)?; - let (r, rn) = rows.common_span(OriginalPromptSpan::R)?; - if h.overlaps(n, r, rn) { - return Err(Error::OutputAliasesInput); - } - for own in [&self.scratch, &self.records, &self.status] - .into_iter() - .flatten() - { - if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { - return Err(Error::OutputAliasesInput); - } - } - for own in ring.buffers()?.iter().flatten() { - if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { - return Err(Error::OutputAliasesInput); - } - } - ring.reject_state_alias(b)?; - if !ring.fully_resident()? { - let mapped = ring.mapped()?; - let host = mapped.address(0, MTP_ORIGINAL_PINNED_HOST_BYTES)?; - if h.qwen_address() < host + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 - && host < h.qwen_address() + n as u64 - { - return Err(Error::OutputAliasesInput); - } - } - Ok(h) - } - // Exact FusedGrArgs/GrMulti by-value ABI (static assertions in source asset). - #[allow(clippy::too_many_arguments)] - fn gr_args(&self, start: usize, t: usize, wh: &[BufferHandle; 11], xn: u64) -> Result { - let mut words = Box::new([0u64; 114]); - for i in 0..t { - let row = start + i; - let a = &mut words[i * 14..i * 14 + 14]; - a[0] = self.address(1, self.max_t * 40960)? + (row * 40960) as u64; - a[1] = a[0]; - a[2] = 0; // apply=false, exact null previous writers - a[5] = wh[4].qwen_address(); - a[6] = wh[5].qwen_address(); - a[7] = wh[6].qwen_address(); - a[8] = wh[10].qwen_address(); - a[9] = u64::from(1e-6f32.to_bits()); - a[10] = self.address(8, self.max_t * 1280)? + (row * 1280) as u64; - a[11] = self.address(9, self.max_t * 16)? + (row * 16) as u64; - a[12] = self.address(10, self.max_t * 16)? + (row * 16) as u64; - a[13] = self.address(11, self.max_t * 10240)? + (row * 10240) as u64; - } - words[112] = xn; - words[113] = t as u64; - Ok(Arg::GrMulti(words)) - } - fn gr( - &self, - cmds: &mut Vec, - t: usize, - wh: &[BufferHandle; 11], - policy: &OriginalMtpScalarPolicy, - ) -> Result<()> { - let xn = self.address(7, t * 40960)?; - Self::kernel( - cmds, - 4, - if policy.gr == OriginalMtpGrVariant::Plain { - 0 - } else { - 1 - }, - [ - t as u32, - if policy.gr == OriginalMtpGrVariant::Plain { - 1 - } else { - 4 - }, - 1, - ], - [256, 1, 1], - 0, - vec![self.gr_args(0, t, wh, xn)?], - )?; - let per_token = if policy.gr == OriginalMtpGrVariant::Staged { - 2 * 1280 * 4 - } else { - self.plain_tile * 4 - }; - let capacity = (self.shared_limit / per_token).clamp(1, 8); - for c in (0..t).step_by(capacity) { - let ct = capacity.min(t - c); - Self::kernel( - cmds, - 4, - if policy.gr == OriginalMtpGrVariant::Staged { - 2 - } else if self.plain_tile == 1280 { - 4 - } else { - 5 - }, - [41, 1, 1], - [256, 1, 1], - (ct * per_token) as u32, - vec![self.gr_args(c, ct, wh, xn + (c * 40960) as u64)?], - )?; - } - Self::kernel( - cmds, - 4, - 3, - [160, 1, 1], - [256, 1, 1], - 0, - vec![self.gr_args(0, t, wh, xn)?], - ) - } - #[allow(clippy::too_many_arguments)] - pub fn record<'arena, 'loan>( - &mut self, - residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - retained: Rc>, - policy: &OriginalMtpScalarPolicy, - cancelled: impl FnMut() -> bool, - ) -> Result { - let result = self.record_impl( - residual, - workspace, - ring, - prior, - tokens, - cell0, - first_needed, - retained, - policy, - cancelled, - ); - if self.has_pending { - let drained = self.drain_graphs(residual.lease_mut(), workspace); - return combine(result, drained); - } - result - } - /// Literal cached device-input or mapped-input per-T graph scheduling. - /// Unsupported storage/math branches return explicit fallback, never completion. - #[allow(clippy::too_many_arguments)] - fn record_impl<'arena, 'loan>( - &mut self, - residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - retained: Rc>, - policy: &OriginalMtpScalarPolicy, - mut cancelled: impl FnMut() -> bool, - ) -> Result { - let kv = &policy.kv; - if kv.disabled { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Disabled)); - } - if tokens.is_empty() { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Empty)); - } - if kv.mode != 0 || kv.hybrid || kv.rotated || kv.q4 { - return Ok(DraftKvOutcome::Fallback( - DraftKvFallback::UnsupportedStorage, - )); - } - if kv.alternate_f16 { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::AlternateF16)); - } - if kv.rope_table_enabled || kv.multimodal_positions { - return Ok(DraftKvOutcome::Fallback( - DraftKvFallback::UnsupportedRopeTable, - )); - } - if [ - kv.theta_scale, - kv.freq_scale, - kv.corr_low, - kv.corr_high, - kv.ext_factor, - kv.mscale, - ] - .iter() - .any(|x| !x.is_finite()) - || kv.theta_scale <= 0.0 - || kv.freq_scale <= 0.0 - || kv.mscale <= 0.0 - { - return Err(Error::InvalidProjectionShape); - } - let (weights, embedding) = retained.loans(self.context)?; - self.validate()?; - ring.validate_original_main(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?)?; - ring.validate_snapshot(prior)?; - workspace.validate_context(self.context)?; - ring.validate_context(self.context)?; - if !residual.context_matches(self.context) - || tokens.len() != residual.rows() - || tokens.len() > self.prompt_cap - || cell0 - .checked_add(tokens.len()) - .is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) - || ring.max_t < self.max_t - { - return Err(Error::InvalidProjectionShape); - } - if tokens - .iter() - .any(|t| *t < 0 || *t as usize >= embedding.vocab()) - { - return Err(Error::InvalidProjectionShape); - } - // Original skips WHOLE groups whose end<=first_needed, not individual rows. - let first_group = (0..tokens.len()) - .step_by(self.max_t) - .find(|c| cell0 + *c + self.max_t.min(tokens.len() - *c) > first_needed); - let Some(first_group) = first_group else { - return Ok(DraftKvOutcome::Skipped); - }; - let first = cell0 + first_group; - let end = cell0 + tokens.len(); - let rows = residual.lease_mut(); - let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R)?; - for own in [&self.scratch, &self.records, &self.status] - .into_iter() - .flatten() - { - if rh.overlaps(rbytes, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { - return Err(Error::OutputAliasesInput); - } - } - for own in [&self.scratch, &self.records, &self.status] - .into_iter() - .flatten() - { - ring.reject_state_alias(own)?; - let h = own.handle.ok_or(Error::ContextPoisoned)?; - workspace.reject_alias(h, own.bytes)?; - for other in ring.buffers()?.iter().flatten() { - if h.overlaps( - own.bytes, - other.handle.ok_or(Error::ContextPoisoned)?, - other.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - let wr = [ - weights.input.embedding_norm, - weights.input.embedding_fc, - weights.input.hidden_norm, - weights.input.hidden_fc, - weights.input.gr_norm, - weights.input.gr_down, - weights.input.gr_up, - weights.input.key, - weights.input.value, - weights.input.key_norm, - weights.gr_inject, - ]; - let extents = [ - 10240, - 2560 * 80 * 34, - 40960, - 2560 * 80 * 34, - 40960, - 320 * 10240 * 2, - 10240 * 320 * 2, - 512 * 80 * 34, - 512 * 80 * 34, - 1024, - 4 * 10240 * 2, - ]; - let mut wh = [rh; 11]; - for i in 0..11 { - wh[i] = self.external(rows, workspace, ring, wr[i], extents[i])?; - } - let eh = self.external( - rows, - workspace, - ring, - embedding.table, - embedding.table.bytes, - )?; - for i in 0..wr.len() { - for j in 0..i { - if wh[i].overlaps(extents[i], wh[j], extents[j]) - && !(wh[i].qwen_address() == wh[j].qwen_address() && extents[i] == extents[j]) - { - return Err(Error::OutputAliasesInput); - } - } - } - let key = [ - policy.gr as u32, - policy.per_group_sync as u32, - kv.theta_scale.to_bits(), - kv.freq_scale.to_bits(), - kv.corr_low.to_bits(), - kv.corr_high.to_bits(), - kv.ext_factor.to_bits(), - kv.mscale.to_bits(), - 0, - ]; - if self - .retained - .as_ref() - .is_some_and(|old| !Rc::ptr_eq(old, &retained)) - || self - .ring_id - .as_ref() - .is_some_and(|id| !id.same_owner(&prior.owner_id())) - || self.policy_key.is_some_and(|old| old != key) - { - return Err(Error::InvalidProjectionShape); - } - self.retained = Some(retained.clone()); - self.ring_id = Some(prior.owner_id()); - self.policy_key = Some(key); - let generation = ring - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - let first_page = first / 4; - let count = end.div_ceil(4); - let mut pages = Vec::new(); - pages - .try_reserve_exact(count) - .map_err(|_| Error::HostAllocation)?; - let mut changed = Vec::new(); - changed - .try_reserve_exact(count - first_page) - .map_err(|_| Error::HostAllocation)?; - for p in 0..count { - if p < first_page { - if let Some(old) = prior.0.pages.get(p) { - pages.push(old.clone()); - continue; - } - } - let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - runs[i] = zero_bytes(n)?; - } - if p < first_page { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); - } else { - changed.push(runs); - } - } - // Literal prefill records [tokens n][steps4*n][positions24*n], one upload. - let mut rec = zero_bytes(tokens.len() * 29 * 4)?; - let n = tokens.len(); - for (i, token) in tokens.iter().enumerate() { - let cell = cell0 + i; - rec[i * 4..i * 4 + 4].copy_from_slice(&token.to_le_bytes()); - for (j, v) in [cell, cell + 1, (cell + 1) / 4, cell + 1] - .into_iter() - .enumerate() - { - let off = (n + i * 4 + j) * 4; - rec[off..off + 4].copy_from_slice(&(v as i32).to_le_bytes()); - } - for h in 0..24 { - let off = (n * 5 + i * 24 + h) * 4; - rec[off..off + 4].copy_from_slice(&(cell as i32).to_le_bytes()); - } - } - let rb = self.records.as_ref().ok_or(Error::ContextPoisoned)?; - let rec_h = - rb.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(rb.bytes, 0, rec.len())?; - let mut staging = vec![(rec_h, rec)]; - let mut cmds = Vec::new(); - cmds.try_reserve(128).map_err(|_| Error::HostAllocation)?; - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - ring.execute(workspace, Vec::new())?; - ring.restore(workspace, prior)?; - ring.current = None; - if !policy.per_group_sync { - self.upload_records(&mut staging)?; - } else { - self.upload_records(&mut Vec::new())?; - } - staging.clear(); - for (group, c) in (0..n).step_by(self.max_t).enumerate() { - let t = self.max_t.min(n - c); - if cell0 + c + t <= first_needed { - continue; - } - let rin = self.address(0, t * 40960)?; - let emb = self.address(2, t * 10240)?; - let en = self.address(3, t * 10240)?; - let e2 = self.address(4, t * 10240)?; - let hn = self.address(5, t * 40960)?; - let h2 = self.address(6, t * 40960)?; - let r = self.address(1, t * 40960)?; - let mixed = self.address(11, t * 10240)?; - let tok = self.address(12, t * 4)?; - let step = self.address(13, t * 16)?; - let pos = self.address(14, t * 96)?; - let mut copies = [ - (tok, rec_h.qwen_address() + (c * 4) as u64, t * 4), - ( - step, - rec_h.qwen_address() + ((n + c * 4) * 4) as u64, - t * 16, - ), - ( - pos, - rec_h.qwen_address() + ((n * 5 + c * 24) * 4) as u64, - t * 96, - ), - ( - rin, - rh.checked_subspan(rbytes, c * 40960, t * 40960)? - .qwen_address(), - t * 40960, - ), - ] - .map(|(dst, src, bytes)| ScalarCommand::Copy { dst, src, bytes }); - let needs_capture = self - .graphs - .as_mut() - .ok_or(Error::ContextPoisoned)? - .find_mut(OriginalGraphKey::MtpPrefill { - rows: t as u8, - device_inputs: !policy.per_group_sync, - })? - .is_none(); - if needs_capture { - // Captured per-T forward owns fixed whole scratch/status and stable arguments. - Self::kernel( - &mut cmds, - 0, - 11, - [1, 1, 1], - [256, 1, 1], - 0, - vec![Arg::U64(self.flag(0, 0)?), Arg::I32(64)], - )?; - if policy.per_group_sync { - let mapped = self - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)?; - let m = mapped.as_ref().ok_or(Error::ContextPoisoned)?; - for (dst, offset, count) in [ - (tok, 0, t), - (step, self.max_t * 4, t * 4), - (pos, self.max_t * 20, t * 24), - ] { - Self::kernel( - &mut cmds, - 3, - 2, - [1, 1, 1], - [128, 1, 1], - 0, - vec![ - Arg::U64(dst), - Arg::U64(m.address(offset, count * 4)?), - Arg::I32(count as i32), - ], - )?; - } - } - match embedding.kind { - EmbeddingKind::Native { - kind, row_bytes, .. - } => Self::kernel( - &mut cmds, - 1, - 0, - [10, t as u32, 1], - [32, 1, 1], - 0, - vec![ - Arg::I32(kind), - Arg::U64(eh.qwen_address()), - Arg::U64(row_bytes as u64), - Arg::U64(tok), - Arg::I64(2560), - Arg::U64(emb), - ], - )?, - EmbeddingKind::Compressed { - bits, - bias, - group, - codes, - scales, - offsets, - .. - } => Self::kernel( - &mut cmds, - 0, - 5, - [10, t as u32, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(eh.qwen_address()), - Arg::U64(eh.qwen_address() + codes as u64), - Arg::U64(if offsets { - eh.qwen_address() + (codes + scales) as u64 - } else { - 0 - }), - Arg::U64(tok), - Arg::I64(2560), - Arg::I32(bits), - Arg::I32(bias), - Arg::I32(group as i32), - Arg::U64((2560 / (8 / bits)) as u64), - Arg::U64((2560 / group) as u64), - Arg::U64(emb), - ], - )?, - } - self.finite(&mut cmds, emb, t * 2560, group, 0)?; - Self::kernel( - &mut cmds, - 3, - 0, - [t as u32, 1, 1], - [1024, 1, 1], - 0, - vec![ - Arg::U64(emb), - Arg::U64(wh[0].qwen_address()), - Arg::U64(en), - Arg::I32(2560), - Arg::F32(1e-6), - ], - )?; - self.finite(&mut cmds, en, t * 2560, group, 1)?; - let q = self.address(15, 8 * 80 * 36)?; - Self::quant(&mut cmds, en, q, t)?; - self.q8_guard(&mut cmds, q, t, group, 2)?; - Self::project(&mut cmds, wh[1].qwen_address(), q, e2, t, 2560)?; - self.finite(&mut cmds, e2, t * 2560, group, 2)?; - Self::kernel( - &mut cmds, - 3, - 0, - [t as u32, 1, 1], - [1024, 1, 1], - 0, - vec![ - Arg::U64(rin), - Arg::U64(wh[2].qwen_address()), - Arg::U64(hn), - Arg::I32(10240), - Arg::F32(1e-6), - ], - )?; - self.finite(&mut cmds, hn, t * 10240, group, 3)?; - for hc in (0..t * 4).step_by(8) { - let cols = 8.min(t * 4 - hc); - Self::quant(&mut cmds, hn + (hc * 10240) as u64, q, cols)?; - self.q8_guard(&mut cmds, q, cols, group, 4)?; - Self::project( - &mut cmds, - wh[3].qwen_address(), - q, - h2 + (hc * 10240) as u64, - cols, - 2560, - )?; - } - self.finite(&mut cmds, h2, t * 10240, group, 4)?; - Self::kernel( - &mut cmds, - 0, - 4, - [40, t as u32, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(h2), - Arg::U64(e2), - Arg::U64(r), - Arg::I64(2560), - Arg::I32(4), - ], - )?; - self.finite(&mut cmds, r, t * 10240, group, 5)?; - self.gr(&mut cmds, t, &wh, policy)?; - self.finite(&mut cmds, self.address(9, t * 16)?, t * 4, group, 6)?; - self.finite(&mut cmds, self.address(7, t * 40960)?, t * 10240, group, 6)?; - self.finite(&mut cmds, self.address(8, t * 1280)?, t * 320, group, 7)?; - self.finite(&mut cmds, self.address(10, t * 16)?, t * 4, group, 7)?; - self.finite(&mut cmds, mixed, t * 2560, group, 8)?; - Self::quant(&mut cmds, mixed, q, t)?; - self.q8_guard(&mut cmds, q, t, group, 9)?; - let (kc, vc) = self.current_kv(ring)?; - Self::project(&mut cmds, wh[7].qwen_address(), q, kc, t, 512)?; - self.finite(&mut cmds, kc, t * 512, group, 10)?; - Self::project(&mut cmds, wh[8].qwen_address(), q, vc, t, 512)?; - self.finite(&mut cmds, vc, t * 512, group, 11)?; - for row in 0..t { - let k = kc + (row * 2048) as u64; - Self::kernel( - &mut cmds, - 2, - 9, - [2, 1, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(k), - Arg::U64(wh[9].qwen_address()), - Arg::U64(k), - Arg::I32(256), - Arg::F32(1e-6), - ], - )?; - self.finite(&mut cmds, k, 512, group, 12)?; - Self::kernel( - &mut cmds, - 3, - 1, - [4, 2, 1], - [32, 1, 1], - 0, - vec![ - Arg::U64(k), - Arg::U64(k), - Arg::I32(2), - Arg::I32(256), - Arg::I32(64), - Arg::F32(kv.theta_scale), - Arg::F32(kv.freq_scale), - Arg::F32(kv.corr_low), - Arg::F32(kv.corr_high), - Arg::F32(kv.ext_factor), - Arg::F32(kv.mscale), - Arg::U64(pos + (row * 96) as u64), - Arg::U64(0), - Arg::Words3([0; 3]), - ], - )?; - self.finite(&mut cmds, k, 512, group, 13)?; - let mut host = [0u64; 8]; - host[2..6].copy_from_slice(&ring.host_addresses()?); - // Literal step append kernel and actual private step record, not batched prompt arithmetic. - Self::kernel( - &mut cmds, - 5, - 0, - [2, 4, 2], - [64, 1, 1], - 0, - vec![ - Arg::U64(ring.address(0)?), - Arg::U64(ring.address(1)?), - Arg::U64(ring.address(2)?), - Arg::U64(ring.address(3)?), - Arg::U64(ring.address(4)?), - Arg::U64(step + (row * 16) as u64), - Arg::U64(k), - Arg::U64(vc + (row * 2048) as u64), - Arg::I32(2), - Arg::I32(256), - Arg::I32(4), - Arg::U64(host[2]), - Arg::U64(host[3]), - Arg::U64(host[4]), - Arg::U64(host[5]), - ], - )?; - } - Self::kernel( - &mut cmds, - 3, - 3, - [64, 1, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(ring.address(2)?), - Arg::U64(ring.address(3)?), - Arg::U64(ring.address(4)?), - Arg::U64(step), - Arg::I32(t as i32), - Arg::U64(self.flag(0, 14)?), - ], - )?; - } - if cancelled() { - self.drain_graphs(rows, workspace)?; - return Ok(DraftKvOutcome::Cancelled); - } - if let Err(primary) = self.enqueue_group( - t, - group, - policy.per_group_sync, - &retained, - ring, - &mut cmds, - if policy.per_group_sync { - &mut copies[3..] - } else { - &mut copies[..] - }, - &tokens[c..c + t], - cell0 + c, - ) { - let drained = self.drain_graphs(rows, workspace); - return combine(Err(primary), drained); - } - cmds.clear(); - if policy.per_group_sync { - self.drain_graphs(rows, workspace)?; - } - } - if !policy.per_group_sync { - self.drain_graphs(rows, workspace)?; - } - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - for (p, runs) in changed.iter_mut().enumerate() { - ring.read_encoded_page(first_page + p, runs)?; - } - for runs in changed { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); - } - let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { - origin: ring.origin.clone(), - pages: Pages::from_vec(pages), - end, - checked: std::cell::Cell::new(false), - })); - ring.current = Some(snapshot.clone()); - ring.generation = generation; - Ok(DraftKvOutcome::Completed(CompletedDraftKv { - snapshot, - first_materialized: first, - end, - generation, - })) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - fn close_inner(&mut self) -> Result<()> { - self.failed = true; - let mut primary = Ok(()); - if let Some(graphs) = self.graphs.take() { - primary = combine(primary, graphs.close()); - } - if let Some(stream) = self.stream.take() { - let r = stream.close(); - if r.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - primary = combine(primary, r); - } - for module in &mut self.modules { - if let Some(m) = module.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine( - Rc::try_unwrap(m) - .map_err(|_| Error::InvalidQwenShape) - .and_then(Module::close), - g.finish(), - ), - Err(e) => { - self.context.poison(); - std::mem::forget(m); - Err(e) - } - } - }; - if r.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - primary = combine(primary, r); - } - } - for b in [&mut self.scratch, &mut self.records, &mut self.status] { - if let Some(b) = b.take() { - primary = combine( - primary, - if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - match Rc::try_unwrap(b) { - Ok(b) => b.release(), - Err(b) => { - if self.original_layout.is_some() { - drop(b); - Ok(()) - } else { - Err(Error::InvalidQwenShape) - } - } - } - }, - ); - } - } - if let Some(mut m) = self.mapped.borrow_mut().take() { - let result = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - self.context.poison(); - std::mem::forget(m); - Err(e) - } - } - }; - if result.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - primary = combine(primary, result); - } - self.retained = None; - if self.context.is_poisoned() { - std::mem::forget(std::mem::take(&mut self.pending_host)); - } else { - self.pending_host.clear(); - } - if self.context.is_poisoned() { - self.context.retain_driver(); - } - primary - } -} -impl Drop for OriginalMtpScalarPrefill<'_> { - fn drop(&mut self) { - let _ = self.close_inner(); - } -} - -#[path = "mtp_original_scalar_graph.rs"] -mod graph; - -#[cfg(test)] -#[path = "mtp_original_scalar_short_gpu.rs"] -mod short_prompt_gpu; +//! Literal MtpDrafter::record_forward(full=false), groups <= actual max_t. +//! Private child of Original prefill. K/V, Q8 scratch and mapped host are the +//! actual MtpOriginalInt8 owner; no half-cache or batch-GEMM substitution. +use super::*; +#[allow(unsafe_code)] +#[path = "mtp_original_scalar_ffi.rs"] +mod scalar_abi; +use crate::{ + OriginalGpuStream, OriginalGraphKey, OriginalGraphRegistry, OriginalGraphResources, + OriginalStreamKind, +}; +use scalar_abi::{Arg, Arguments, Module}; +#[path = "mtp_original_scalar_weights.rs"] +mod retained_weights; +pub use retained_weights::OriginalMtpRetainedScalarWeights; +#[allow(unsafe_code)] +#[path = "mtp_original_scalar_mapped.rs"] +mod mapped_records; +use std::cell::RefCell; +#[allow(unsafe_code)] +#[path = "mtp_original_physical_layout.rs"] +mod physical_layout; +struct OriginalLayoutSetup<'ctx> { + layout: physical_layout::Layout, + bank: Rc>, + mapped: Rc>, +} +struct GraphResources<'ctx> { + context: &'ctx Context<'ctx>, + modules: [Rc; 6], + scratch: Rc>, + records: Rc>, + status: Rc>, + mapped: Rc>>, + ring: MtpOriginalRingResources<'ctx>, + weights: Rc>, + commands: Vec, +} +impl crate::original_gpu_schedule::resources::Sealed for GraphResources<'_> {} +impl OriginalGraphResources for GraphResources<'_> { + fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + self.ring.validate_context(c)?; + self.weights.validate_context(c)?; + for b in [&self.scratch, &self.records, &self.status] { + checked(c, b, b.bytes)?; + } + if self + .mapped + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .is_none() + { + return Err(Error::ContextPoisoned); + } + Ok(()) + } +} + +const MAX_PROMPT: usize = 8192; +const SCALAR_FLAGS: usize = 16; +const GR_ENTRIES: &[&CStr] = &[ + c"mtp_scalar_gr_norm", + c"mtp_scalar_gr_split", + c"mtp_scalar_gr_staged", + c"mtp_scalar_gr_up", + c"mtp_scalar_gr_down1280", + c"mtp_scalar_gr_down2560", +]; +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum OriginalMtpGrVariant { + Plain, + Split, + Staged, +} +/// Actual Original policy result, not an attestation about inputs/weights. +/// GR_V3 is deliberately a separate producer, not substituted here. +pub struct OriginalMtpScalarPolicy { + pub gr: OriginalMtpGrVariant, + pub per_group_sync: bool, + pub kv: DraftKvPolicy, +} +pub struct OriginalMtpScalarWeights<'a, 'ctx> { + pub input: OriginalMtpPrefillWeights<'a, 'ctx>, + pub gr_inject: &'a DeviceBuffer<'ctx>, +} +// Actual first twelve Original input/read roles plus token,step,position. One +// whole physical owner, each closed range derives from this exact carve. +struct Scratch { + sizes: [usize; 16], + offsets: [usize; 16], + bytes: usize, +} +impl Scratch { + fn new(t: usize) -> Result { + if !(1..=8).contains(&t) { + return Err(Error::InvalidQwenShape); + } + let sizes = [ + t * 40960, + t * 40960, + t * 10240, + t * 10240, + t * 10240, + t * 40960, + t * 40960, + t * 40960, + t * 1280, + t * 16, + t * 16, + t * 10240, + t * 4, + t * 16, + t * 96, + 8 * 80 * 36, + ]; + let mut offsets = [0; 16]; + let mut bytes = 0usize; + for (i, n) in sizes.into_iter().enumerate() { + offsets[i] = bytes; + bytes = bytes.checked_add(aligned(n)?).ok_or(Error::InvalidSize)?; + } + Ok(Self { + sizes, + offsets, + bytes, + }) + } +} + +#[path = "mtp_original_full_forward.rs"] +mod full_forward; +pub use full_forward::{ + CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, + OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, + OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpStepOutput, +}; +pub(crate) use full_forward::session_assets_sealed; +enum ScalarCommand { + Kernel { + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + args: Arguments, + }, + Copy { + dst: u64, + src: u64, + bytes: usize, + }, +} +/// Real affine scalar producer. Cached Original capture must retain this owner +/// AND genuine model-lifetime whole weights (see the explicit graph handoff). +pub struct OriginalMtpScalarPrefill<'ctx> { + context: &'ctx Context<'ctx>, + max_t: usize, + prompt_cap: usize, + modules: [Option>; 6], + scratch: Option>>, + records: Option>>, + status: Option>>, + layout: Scratch, + original_layout: Option, + shared_limit: usize, + plain_tile: usize, + stream: Option>, + failed: bool, + graphs: Option>>, + mapped: Rc>>, + retained: Option>>, + ring_id: Option, + policy_key: Option<[u32; 9]>, + pending_host: Vec>, + graph_metadata_bytes: usize, + has_pending: bool, +} +impl<'ctx> Context<'ctx> { + pub fn original_mtp_scalar_prefill( + &'ctx self, + max_t: usize, + prompt_cap: usize, + ) -> Result> { + OriginalMtpScalarPrefill::new(self, max_t, prompt_cap) + } +} +impl<'ctx> OriginalMtpScalarPrefill<'ctx> { + fn assets_ready() -> Result<()> { + let assets = [ + include_bytes!("mtp_original_prefill.ptx").as_slice(), + include_bytes!("mtp_original_prefill_embedding.ptx").as_slice(), + include_bytes!("mtp_original_tail.ptx").as_slice(), + include_bytes!("mtp_original_scalar_norm.ptx").as_slice(), + include_bytes!("mtp_original_scalar_gr.ptx").as_slice(), + include_bytes!("mtp_original_kv.ptx").as_slice(), + ]; + if assets + .iter() + .any(|p| p.windows(8).any(|w| w == b"UNSEALED")) + { + Err(Error::UnsupportedQwenOperation) + } else { + Ok(()) + } + } + pub fn planned_device_bytes(max_t: usize, prompt_cap: usize) -> Result { + if !(1..=MAX_PROMPT).contains(&prompt_cap) { + return Err(Error::InvalidQwenShape); + } + Scratch::new(max_t)? + .bytes + .checked_add(prompt_cap.checked_mul(29 * 4).ok_or(Error::InvalidSize)?) + .and_then(|n| n.checked_add((prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4)) + .ok_or(Error::InvalidSize) + } + pub fn planned_host_bytes(max_t: usize, prompt_cap: usize) -> Result { + Self::planned_device_bytes(max_t, prompt_cap)?; + let timeline = (prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4; + // New per-call immutable host snapshot may include absent pruned-prefix pages; + // charge its real worst-case payload+catalog separately from the existing + // physical mapped ring. Cached graph metadata is bounded per actual T/key. + let snapshot = MTP_ORIGINAL_MAX_CELLS + .div_ceil(4) + .checked_mul(4224 + 128) + .ok_or(Error::BudgetExceeded)?; + (2 * max_t) + .checked_mul(512 * 1024) + .and_then(|n| { + n.checked_add(prompt_cap * 29 * 4 + max_t * 29 * 4 + 2 * timeline + 64 * 1024) + }) + .and_then(|n| n.checked_add(snapshot)) + .ok_or(Error::BudgetExceeded) + } + pub fn host_metadata_bytes(&self) -> usize { + self.graphs + .as_ref() + .map_or(0, OriginalGraphRegistry::metadata_bytes) + + self.graph_metadata_bytes + + std::mem::size_of::() + + self.pending_host.capacity() * std::mem::size_of::>() + } + pub fn pinned_host_bytes(&self) -> usize { + if self.original_layout.is_some() { + self.max_t * 236 + 384 + } else { + self.max_t * 29 * 4 + } + } + fn new(c: &'ctx Context<'ctx>, max_t: usize, prompt_cap: usize) -> Result { + Self::new_internal(c, max_t, prompt_cap, None) + } + fn new_internal( + c: &'ctx Context<'ctx>, + max_t: usize, + prompt_cap: usize, + exact: Option>, + ) -> Result { + let legacy_charge = Self::planned_device_bytes(max_t, prompt_cap)?; + let charge = if exact.is_some() { + legacy_charge + .checked_sub(Scratch::new(max_t)?.bytes) + .ok_or(Error::InvalidSize)? + } else { + legacy_charge + }; + if let Some(e) = &exact { + if e.layout.t != max_t { + return Err(Error::InvalidQwenShape); + } + checked(c, &e.bank, e.layout.bytes)?; + } + let assets = [ + include_bytes!("mtp_original_prefill.ptx").as_slice(), + include_bytes!("mtp_original_prefill_embedding.ptx").as_slice(), + include_bytes!("mtp_original_tail.ptx").as_slice(), + include_bytes!("mtp_original_scalar_norm.ptx").as_slice(), + include_bytes!("mtp_original_scalar_gr.ptx").as_slice(), + include_bytes!("mtp_original_kv.ptx").as_slice(), + ]; + if assets + .iter() + .any(|p| p.windows(8).any(|w| w == b"UNSEALED")) + { + return Err(Error::UnsupportedQwenOperation); + } + let required = charge + .checked_add(RESERVE_BYTES) + .ok_or(Error::BudgetExceeded)?; + if c.is_poisoned() || c.handle.is_none() { + return Err(Error::ContextPoisoned); + } + if c.allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > c.budget_bytes()) + || c.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + let mut o = Self { + context: c, + max_t, + prompt_cap, + modules: std::array::from_fn(|_| None), + scratch: None, + records: None, + status: None, + layout: match &exact { + Some(e) => e.layout.scalar(), + None => Scratch::new(max_t)?, + }, + original_layout: exact.as_ref().map(|e| e.layout.clone()), + shared_limit: 0, + plain_tile: 0, + stream: None, + failed: false, + graphs: None, + mapped: Rc::new(RefCell::new(None)), + retained: None, + ring_id: None, + policy_key: None, + pending_host: Vec::new(), + graph_metadata_bytes: 0, + has_pending: false, + }; + let operation = (|| { + let g = c.enter().inspect_err(|_| { + c.poison(); + c.retain_driver(); + })?; + let load = (|| { + o.modules[0] = Some(Rc::new(Module::load(assets[0], ENTRIES)?)); + o.modules[1] = Some(Rc::new(Module::load( + assets[1], + &[c"mtp_prefill_native_embedding"], + )?)); + o.modules[2] = Some(Rc::new(Module::load(assets[2], TAIL_ENTRIES)?)); + o.modules[3] = Some(Rc::new(Module::load( + assets[3], + &[ + c"mtp_scalar_norm1024", + c"mtp_scalar_rope", + c"mtp_scalar_copy_i32", + c"mtp_scalar_encoded", + ], + )?)); + o.modules[4] = Some(Rc::new(Module::load(assets[4], GR_ENTRIES)?)); + o.modules[5] = Some(Rc::new(Module::load(assets[5], KV_ENTRIES)?)); + let (shared, tile) = o.module(4)?.configure_gr()?; + o.shared_limit = shared; + o.plain_tile = tile; + Ok(()) + })(); + let pop = g.finish(); + if load.is_err() || pop.is_err() { + o.poison(); + } + combine(load, pop)?; + o.scratch = Some(match &exact { + Some(e) => Rc::clone(&e.bank), + None => Rc::new(c.allocate(o.layout.bytes)?), + }); + o.records = Some(Rc::new(c.allocate(prompt_cap * 29 * 4)?)); + o.status = Some(Rc::new( + c.allocate((prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4)?, + )); + o.stream = Some(c.original_gpu_stream(OriginalStreamKind::NonBlocking)?); + let g = c.enter().inspect_err(|_| { + c.poison(); + c.retain_driver(); + })?; + let allocation = match &exact { + Some(e) => Ok(mapped_records::MappedOwner::original( + max_t, + Rc::clone(&e.mapped), + )), + None => mapped_records::MappedOwner::new(max_t), + }; + let pop = g.finish(); + if pop.is_err() { + o.poison(); + let original = match allocation { + Ok(owner) => { + std::mem::forget(owner); + Ok(()) + } + Err(e) => Err(e), + }; + return combine(original, pop); + } + if allocation.is_err() { + o.poison(); + } + *o.mapped.borrow_mut() = Some(allocation?); + o.graphs = Some(OriginalGraphRegistry::new(c, 2 * max_t)?); + o.pending_host + .try_reserve_exact(2) + .map_err(|_| Error::HostAllocation)?; + if c.memory_info()?.0 < RESERVE_BYTES { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = operation { + return combine(Err(e), o.close()); + } + Ok(o) + } + pub fn allocated_bytes(&self) -> usize { + [&self.scratch, &self.records, &self.status] + .into_iter() + .map(|s| s.as_ref().map_or(0, |b| b.len())) + .sum() + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + self.validate() + } + fn validate(&self) -> Result<()> { + if self.is_failed() + || self.modules.iter().any(Option::is_none) + || self + .stream + .as_ref() + .is_none_or(OriginalGpuStream::is_failed) + { + return Err(Error::ContextPoisoned); + } + for (b, n) in [ + (&self.scratch, self.layout.bytes), + (&self.records, self.prompt_cap * 29 * 4), + ( + &self.status, + (self.prompt_cap.div_ceil(self.max_t) + 1) * SCALAR_FLAGS * 4, + ), + ] { + let b = b.as_ref().ok_or(Error::ContextPoisoned)?; + checked(self.context, b, n)?; + } + Ok(()) + } + fn poison(&mut self) { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + } + fn module(&self, i: usize) -> Result<&Module> { + self.modules + .get(i) + .and_then(Option::as_ref) + .map(Rc::as_ref) + .ok_or(Error::ContextPoisoned) + } + fn scratch(&self, i: usize, n: usize) -> Result { + let b = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; + if n == 0 || n > self.layout.sizes[i] { + return Err(Error::InvalidSize); + } + b.handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(b.bytes, self.layout.offsets[i], n) + } + fn address(&self, i: usize, n: usize) -> Result { + Ok(self.scratch(i, n)?.qwen_address()) + } + fn current_kv(&self, ring: &MtpOriginalInt8<'ctx>) -> Result<(u64, u64)> { + match &self.original_layout { + Some(l) => { + let b = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; + Ok(( + l.span(b, 22, 0, self.max_t * 2048)?.qwen_address(), + l.span(b, 23, 0, self.max_t * 2048)?.qwen_address(), + )) + } + None => Ok((ring.address(6)?, ring.address(7)?)), + } + } + fn flag(&self, group: usize, stage: usize) -> Result { + let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; + if stage >= SCALAR_FLAGS { + return Err(Error::InvalidSize); + } + Ok(b.handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(b.bytes, (group * SCALAR_FLAGS + stage) * 4, 4)? + .qwen_address()) + } + #[allow(clippy::too_many_arguments)] + fn kernel( + cmds: &mut Vec, + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + args: Vec, + ) -> Result<()> { + cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; + cmds.push(ScalarCommand::Kernel { + asset, + index, + grid, + block, + shared, + args: Arguments::new(args)?, + }); + Ok(()) + } + fn finite( + &self, + cmds: &mut Vec, + data: u64, + n: usize, + _g: usize, + s: usize, + ) -> Result<()> { + Self::kernel( + cmds, + 2, + 11, + [n.div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(data), + Arg::I32(n as i32), + Arg::U64(self.flag(0, s)?), + ], + ) + } + fn q8_guard( + &self, + cmds: &mut Vec, + q: u64, + rows: usize, + _g: usize, + s: usize, + ) -> Result<()> { + Self::kernel( + cmds, + 2, + 12, + [(rows * 80).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(q), + Arg::I32((rows * 80) as i32), + Arg::U64(self.flag(0, s)?), + ], + ) + } + fn quant(cmds: &mut Vec, x: u64, q: u64, rows: usize) -> Result<()> { + Self::kernel( + cmds, + 2, + 0, + [(rows * 2560).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![Arg::U64(x), Arg::U64(q), Arg::I32((rows * 2560) as i32)], + ) + } + fn project( + cmds: &mut Vec, + w: u64, + q: u64, + y: u64, + rows: usize, + out: usize, + ) -> Result<()> { + if !(1..=8).contains(&rows) || !matches!(out, 512 | 2560) { + return Err(Error::InvalidProjectionShape); + } + Self::kernel( + cmds, + 2, + rows, + [out as u32, 1, 1], + [32, 4, 1], + 0, + vec![ + Arg::U64(w), + Arg::U64(q), + Arg::U64(y), + Arg::I32(2560), + Arg::I32(out as i32), + ], + ) + } + fn external( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + w: &NativeBatchWorkspace<'_>, + ring: &MtpOriginalInt8<'_>, + b: &DeviceBuffer<'_>, + n: usize, + ) -> Result { + checked(self.context, b, n)?; + let h = b.handle.ok_or(Error::ContextPoisoned)?; + w.reject_alias(h, n)?; + let (r, rn) = rows.common_span(OriginalPromptSpan::R)?; + if h.overlaps(n, r, rn) { + return Err(Error::OutputAliasesInput); + } + for own in [&self.scratch, &self.records, &self.status] + .into_iter() + .flatten() + { + if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { + return Err(Error::OutputAliasesInput); + } + } + for own in ring.buffers()?.iter().flatten() { + if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { + return Err(Error::OutputAliasesInput); + } + } + ring.reject_state_alias(b)?; + if !ring.fully_resident()? { + let mapped = ring.mapped()?; + let host = mapped.address(0, MTP_ORIGINAL_PINNED_HOST_BYTES)?; + if h.qwen_address() < host + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 + && host < h.qwen_address() + n as u64 + { + return Err(Error::OutputAliasesInput); + } + } + Ok(h) + } + // Exact FusedGrArgs/GrMulti by-value ABI (static assertions in source asset). + #[allow(clippy::too_many_arguments)] + fn gr_args(&self, start: usize, t: usize, wh: &[BufferHandle; 11], xn: u64) -> Result { + let mut words = Box::new([0u64; 114]); + for i in 0..t { + let row = start + i; + let a = &mut words[i * 14..i * 14 + 14]; + a[0] = self.address(1, self.max_t * 40960)? + (row * 40960) as u64; + a[1] = a[0]; + a[2] = 0; // apply=false, exact null previous writers + a[5] = wh[4].qwen_address(); + a[6] = wh[5].qwen_address(); + a[7] = wh[6].qwen_address(); + a[8] = wh[10].qwen_address(); + a[9] = u64::from(1e-6f32.to_bits()); + a[10] = self.address(8, self.max_t * 1280)? + (row * 1280) as u64; + a[11] = self.address(9, self.max_t * 16)? + (row * 16) as u64; + a[12] = self.address(10, self.max_t * 16)? + (row * 16) as u64; + a[13] = self.address(11, self.max_t * 10240)? + (row * 10240) as u64; + } + words[112] = xn; + words[113] = t as u64; + Ok(Arg::GrMulti(words)) + } + fn gr( + &self, + cmds: &mut Vec, + t: usize, + wh: &[BufferHandle; 11], + policy: &OriginalMtpScalarPolicy, + ) -> Result<()> { + let xn = self.address(7, t * 40960)?; + Self::kernel( + cmds, + 4, + if policy.gr == OriginalMtpGrVariant::Plain { + 0 + } else { + 1 + }, + [ + t as u32, + if policy.gr == OriginalMtpGrVariant::Plain { + 1 + } else { + 4 + }, + 1, + ], + [256, 1, 1], + 0, + vec![self.gr_args(0, t, wh, xn)?], + )?; + let per_token = if policy.gr == OriginalMtpGrVariant::Staged { + 2 * 1280 * 4 + } else { + self.plain_tile * 4 + }; + let capacity = (self.shared_limit / per_token).clamp(1, 8); + for c in (0..t).step_by(capacity) { + let ct = capacity.min(t - c); + Self::kernel( + cmds, + 4, + if policy.gr == OriginalMtpGrVariant::Staged { + 2 + } else if self.plain_tile == 1280 { + 4 + } else { + 5 + }, + [41, 1, 1], + [256, 1, 1], + (ct * per_token) as u32, + vec![self.gr_args(c, ct, wh, xn + (c * 40960) as u64)?], + )?; + } + Self::kernel( + cmds, + 4, + 3, + [160, 1, 1], + [256, 1, 1], + 0, + vec![self.gr_args(0, t, wh, xn)?], + ) + } + #[allow(clippy::too_many_arguments)] + pub fn record<'arena, 'loan>( + &mut self, + residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + tokens: &[i32], + cell0: usize, + first_needed: usize, + retained: Rc>, + policy: &OriginalMtpScalarPolicy, + cancelled: impl FnMut() -> bool, + ) -> Result { + let result = self.record_impl( + residual, + workspace, + ring, + prior, + tokens, + cell0, + first_needed, + retained, + policy, + cancelled, + ); + if self.has_pending { + let drained = self.drain_graphs(residual.lease_mut(), workspace); + return combine(result, drained); + } + result + } + /// Literal cached device-input or mapped-input per-T graph scheduling. + /// Unsupported storage/math branches return explicit fallback, never completion. + #[allow(clippy::too_many_arguments)] + fn record_impl<'arena, 'loan>( + &mut self, + residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + tokens: &[i32], + cell0: usize, + first_needed: usize, + retained: Rc>, + policy: &OriginalMtpScalarPolicy, + mut cancelled: impl FnMut() -> bool, + ) -> Result { + let kv = &policy.kv; + if kv.disabled { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Disabled)); + } + if tokens.is_empty() { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Empty)); + } + if kv.mode != 0 || kv.hybrid || kv.rotated || kv.q4 { + return Ok(DraftKvOutcome::Fallback( + DraftKvFallback::UnsupportedStorage, + )); + } + if kv.alternate_f16 { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::AlternateF16)); + } + if kv.rope_table_enabled || kv.multimodal_positions { + return Ok(DraftKvOutcome::Fallback( + DraftKvFallback::UnsupportedRopeTable, + )); + } + if [ + kv.theta_scale, + kv.freq_scale, + kv.corr_low, + kv.corr_high, + kv.ext_factor, + kv.mscale, + ] + .iter() + .any(|x| !x.is_finite()) + || kv.theta_scale <= 0.0 + || kv.freq_scale <= 0.0 + || kv.mscale <= 0.0 + { + return Err(Error::InvalidProjectionShape); + } + let (weights, embedding) = retained.loans(self.context)?; + self.validate()?; + ring.validate_original_main(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?)?; + ring.validate_snapshot(prior)?; + workspace.validate_context(self.context)?; + ring.validate_context(self.context)?; + if !residual.context_matches(self.context) + || tokens.len() != residual.rows() + || tokens.len() > self.prompt_cap + || cell0 + .checked_add(tokens.len()) + .is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) + || ring.max_t < self.max_t + { + return Err(Error::InvalidProjectionShape); + } + if tokens + .iter() + .any(|t| *t < 0 || *t as usize >= embedding.vocab()) + { + return Err(Error::InvalidProjectionShape); + } + // Original skips WHOLE groups whose end<=first_needed, not individual rows. + let first_group = (0..tokens.len()) + .step_by(self.max_t) + .find(|c| cell0 + *c + self.max_t.min(tokens.len() - *c) > first_needed); + let Some(first_group) = first_group else { + return Ok(DraftKvOutcome::Skipped); + }; + let first = cell0 + first_group; + let end = cell0 + tokens.len(); + let rows = residual.lease_mut(); + let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R)?; + for own in [&self.scratch, &self.records, &self.status] + .into_iter() + .flatten() + { + if rh.overlaps(rbytes, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { + return Err(Error::OutputAliasesInput); + } + } + for own in [&self.scratch, &self.records, &self.status] + .into_iter() + .flatten() + { + ring.reject_state_alias(own)?; + let h = own.handle.ok_or(Error::ContextPoisoned)?; + workspace.reject_alias(h, own.bytes)?; + for other in ring.buffers()?.iter().flatten() { + if h.overlaps( + own.bytes, + other.handle.ok_or(Error::ContextPoisoned)?, + other.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + } + let wr = [ + weights.input.embedding_norm, + weights.input.embedding_fc, + weights.input.hidden_norm, + weights.input.hidden_fc, + weights.input.gr_norm, + weights.input.gr_down, + weights.input.gr_up, + weights.input.key, + weights.input.value, + weights.input.key_norm, + weights.gr_inject, + ]; + let extents = [ + 10240, + 2560 * 80 * 34, + 40960, + 2560 * 80 * 34, + 40960, + 320 * 10240 * 2, + 10240 * 320 * 2, + 512 * 80 * 34, + 512 * 80 * 34, + 1024, + 4 * 10240 * 2, + ]; + let mut wh = [rh; 11]; + for i in 0..11 { + wh[i] = self.external(rows, workspace, ring, wr[i], extents[i])?; + } + let eh = self.external( + rows, + workspace, + ring, + embedding.table, + embedding.table.bytes, + )?; + for i in 0..wr.len() { + for j in 0..i { + if wh[i].overlaps(extents[i], wh[j], extents[j]) + && !(wh[i].qwen_address() == wh[j].qwen_address() && extents[i] == extents[j]) + { + return Err(Error::OutputAliasesInput); + } + } + } + let key = [ + policy.gr as u32, + policy.per_group_sync as u32, + kv.theta_scale.to_bits(), + kv.freq_scale.to_bits(), + kv.corr_low.to_bits(), + kv.corr_high.to_bits(), + kv.ext_factor.to_bits(), + kv.mscale.to_bits(), + 0, + ]; + if self + .retained + .as_ref() + .is_some_and(|old| !Rc::ptr_eq(old, &retained)) + || self + .ring_id + .as_ref() + .is_some_and(|id| !id.same_owner(&prior.owner_id())) + || self.policy_key.is_some_and(|old| old != key) + { + return Err(Error::InvalidProjectionShape); + } + self.retained = Some(retained.clone()); + self.ring_id = Some(prior.owner_id()); + self.policy_key = Some(key); + let generation = ring + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + let first_page = first / 4; + let count = end.div_ceil(4); + let mut pages = Vec::new(); + pages + .try_reserve_exact(count) + .map_err(|_| Error::HostAllocation)?; + let mut changed = Vec::new(); + changed + .try_reserve_exact(count - first_page) + .map_err(|_| Error::HostAllocation)?; + for p in 0..count { + if p < first_page { + if let Some(old) = prior.0.pages.get(p) { + pages.push(old.clone()); + continue; + } + } + let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + runs[i] = zero_bytes(n)?; + } + if p < first_page { + pages.push(Rc::new(Page { + runs: runs.map(Vec::into_boxed_slice), + })); + } else { + changed.push(runs); + } + } + // Literal prefill records [tokens n][steps4*n][positions24*n], one upload. + let mut rec = zero_bytes(tokens.len() * 29 * 4)?; + let n = tokens.len(); + for (i, token) in tokens.iter().enumerate() { + let cell = cell0 + i; + rec[i * 4..i * 4 + 4].copy_from_slice(&token.to_le_bytes()); + for (j, v) in [cell, cell + 1, (cell + 1) / 4, cell + 1] + .into_iter() + .enumerate() + { + let off = (n + i * 4 + j) * 4; + rec[off..off + 4].copy_from_slice(&(v as i32).to_le_bytes()); + } + for h in 0..24 { + let off = (n * 5 + i * 24 + h) * 4; + rec[off..off + 4].copy_from_slice(&(cell as i32).to_le_bytes()); + } + } + let rb = self.records.as_ref().ok_or(Error::ContextPoisoned)?; + let rec_h = + rb.handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(rb.bytes, 0, rec.len())?; + let mut staging = vec![(rec_h, rec)]; + let mut cmds = Vec::new(); + cmds.try_reserve(128).map_err(|_| Error::HostAllocation)?; + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + ring.execute(workspace, Vec::new())?; + ring.restore(workspace, prior)?; + ring.current = None; + if !policy.per_group_sync { + self.upload_records(&mut staging)?; + } else { + self.upload_records(&mut Vec::new())?; + } + staging.clear(); + for (group, c) in (0..n).step_by(self.max_t).enumerate() { + let t = self.max_t.min(n - c); + if cell0 + c + t <= first_needed { + continue; + } + let rin = self.address(0, t * 40960)?; + let emb = self.address(2, t * 10240)?; + let en = self.address(3, t * 10240)?; + let e2 = self.address(4, t * 10240)?; + let hn = self.address(5, t * 40960)?; + let h2 = self.address(6, t * 40960)?; + let r = self.address(1, t * 40960)?; + let mixed = self.address(11, t * 10240)?; + let tok = self.address(12, t * 4)?; + let step = self.address(13, t * 16)?; + let pos = self.address(14, t * 96)?; + let mut copies = [ + (tok, rec_h.qwen_address() + (c * 4) as u64, t * 4), + ( + step, + rec_h.qwen_address() + ((n + c * 4) * 4) as u64, + t * 16, + ), + ( + pos, + rec_h.qwen_address() + ((n * 5 + c * 24) * 4) as u64, + t * 96, + ), + ( + rin, + rh.checked_subspan(rbytes, c * 40960, t * 40960)? + .qwen_address(), + t * 40960, + ), + ] + .map(|(dst, src, bytes)| ScalarCommand::Copy { dst, src, bytes }); + let needs_capture = self + .graphs + .as_mut() + .ok_or(Error::ContextPoisoned)? + .find_mut(OriginalGraphKey::MtpPrefill { + rows: t as u8, + device_inputs: !policy.per_group_sync, + })? + .is_none(); + if needs_capture { + // Captured per-T forward owns fixed whole scratch/status and stable arguments. + Self::kernel( + &mut cmds, + 0, + 11, + [1, 1, 1], + [256, 1, 1], + 0, + vec![Arg::U64(self.flag(0, 0)?), Arg::I32(64)], + )?; + if policy.per_group_sync { + let mapped = self + .mapped + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)?; + let m = mapped.as_ref().ok_or(Error::ContextPoisoned)?; + for (dst, offset, count) in [ + (tok, 0, t), + (step, self.max_t * 4, t * 4), + (pos, self.max_t * 20, t * 24), + ] { + Self::kernel( + &mut cmds, + 3, + 2, + [1, 1, 1], + [128, 1, 1], + 0, + vec![ + Arg::U64(dst), + Arg::U64(m.address(offset, count * 4)?), + Arg::I32(count as i32), + ], + )?; + } + } + match embedding.kind { + EmbeddingKind::Native { + kind, row_bytes, .. + } => Self::kernel( + &mut cmds, + 1, + 0, + [10, t as u32, 1], + [32, 1, 1], + 0, + vec![ + Arg::I32(kind), + Arg::U64(eh.qwen_address()), + Arg::U64(row_bytes as u64), + Arg::U64(tok), + Arg::I64(2560), + Arg::U64(emb), + ], + )?, + EmbeddingKind::Compressed { + bits, + bias, + group, + codes, + scales, + offsets, + .. + } => Self::kernel( + &mut cmds, + 0, + 5, + [10, t as u32, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(eh.qwen_address()), + Arg::U64(eh.qwen_address() + codes as u64), + Arg::U64(if offsets { + eh.qwen_address() + (codes + scales) as u64 + } else { + 0 + }), + Arg::U64(tok), + Arg::I64(2560), + Arg::I32(bits), + Arg::I32(bias), + Arg::I32(group as i32), + Arg::U64((2560 / (8 / bits)) as u64), + Arg::U64((2560 / group) as u64), + Arg::U64(emb), + ], + )?, + } + self.finite(&mut cmds, emb, t * 2560, group, 0)?; + Self::kernel( + &mut cmds, + 3, + 0, + [t as u32, 1, 1], + [1024, 1, 1], + 0, + vec![ + Arg::U64(emb), + Arg::U64(wh[0].qwen_address()), + Arg::U64(en), + Arg::I32(2560), + Arg::F32(1e-6), + ], + )?; + self.finite(&mut cmds, en, t * 2560, group, 1)?; + let q = self.address(15, 8 * 80 * 36)?; + Self::quant(&mut cmds, en, q, t)?; + self.q8_guard(&mut cmds, q, t, group, 2)?; + Self::project(&mut cmds, wh[1].qwen_address(), q, e2, t, 2560)?; + self.finite(&mut cmds, e2, t * 2560, group, 2)?; + Self::kernel( + &mut cmds, + 3, + 0, + [t as u32, 1, 1], + [1024, 1, 1], + 0, + vec![ + Arg::U64(rin), + Arg::U64(wh[2].qwen_address()), + Arg::U64(hn), + Arg::I32(10240), + Arg::F32(1e-6), + ], + )?; + self.finite(&mut cmds, hn, t * 10240, group, 3)?; + for hc in (0..t * 4).step_by(8) { + let cols = 8.min(t * 4 - hc); + Self::quant(&mut cmds, hn + (hc * 10240) as u64, q, cols)?; + self.q8_guard(&mut cmds, q, cols, group, 4)?; + Self::project( + &mut cmds, + wh[3].qwen_address(), + q, + h2 + (hc * 10240) as u64, + cols, + 2560, + )?; + } + self.finite(&mut cmds, h2, t * 10240, group, 4)?; + Self::kernel( + &mut cmds, + 0, + 4, + [40, t as u32, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(h2), + Arg::U64(e2), + Arg::U64(r), + Arg::I64(2560), + Arg::I32(4), + ], + )?; + self.finite(&mut cmds, r, t * 10240, group, 5)?; + self.gr(&mut cmds, t, &wh, policy)?; + self.finite(&mut cmds, self.address(9, t * 16)?, t * 4, group, 6)?; + self.finite(&mut cmds, self.address(7, t * 40960)?, t * 10240, group, 6)?; + self.finite(&mut cmds, self.address(8, t * 1280)?, t * 320, group, 7)?; + self.finite(&mut cmds, self.address(10, t * 16)?, t * 4, group, 7)?; + self.finite(&mut cmds, mixed, t * 2560, group, 8)?; + Self::quant(&mut cmds, mixed, q, t)?; + self.q8_guard(&mut cmds, q, t, group, 9)?; + let (kc, vc) = self.current_kv(ring)?; + Self::project(&mut cmds, wh[7].qwen_address(), q, kc, t, 512)?; + self.finite(&mut cmds, kc, t * 512, group, 10)?; + Self::project(&mut cmds, wh[8].qwen_address(), q, vc, t, 512)?; + self.finite(&mut cmds, vc, t * 512, group, 11)?; + for row in 0..t { + let k = kc + (row * 2048) as u64; + Self::kernel( + &mut cmds, + 2, + 9, + [2, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(k), + Arg::U64(wh[9].qwen_address()), + Arg::U64(k), + Arg::I32(256), + Arg::F32(1e-6), + ], + )?; + self.finite(&mut cmds, k, 512, group, 12)?; + Self::kernel( + &mut cmds, + 3, + 1, + [4, 2, 1], + [32, 1, 1], + 0, + vec![ + Arg::U64(k), + Arg::U64(k), + Arg::I32(2), + Arg::I32(256), + Arg::I32(64), + Arg::F32(kv.theta_scale), + Arg::F32(kv.freq_scale), + Arg::F32(kv.corr_low), + Arg::F32(kv.corr_high), + Arg::F32(kv.ext_factor), + Arg::F32(kv.mscale), + Arg::U64(pos + (row * 96) as u64), + Arg::U64(0), + Arg::Words3([0; 3]), + ], + )?; + self.finite(&mut cmds, k, 512, group, 13)?; + let mut host = [0u64; 8]; + host[2..6].copy_from_slice(&ring.host_addresses()?); + // Literal step append kernel and actual private step record, not batched prompt arithmetic. + Self::kernel( + &mut cmds, + 5, + 0, + [2, 4, 2], + [64, 1, 1], + 0, + vec![ + Arg::U64(ring.address(0)?), + Arg::U64(ring.address(1)?), + Arg::U64(ring.address(2)?), + Arg::U64(ring.address(3)?), + Arg::U64(ring.address(4)?), + Arg::U64(step + (row * 16) as u64), + Arg::U64(k), + Arg::U64(vc + (row * 2048) as u64), + Arg::I32(2), + Arg::I32(256), + Arg::I32(4), + Arg::U64(host[2]), + Arg::U64(host[3]), + Arg::U64(host[4]), + Arg::U64(host[5]), + ], + )?; + } + Self::kernel( + &mut cmds, + 3, + 3, + [64, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(ring.address(2)?), + Arg::U64(ring.address(3)?), + Arg::U64(ring.address(4)?), + Arg::U64(step), + Arg::I32(t as i32), + Arg::U64(self.flag(0, 14)?), + ], + )?; + } + if cancelled() { + self.drain_graphs(rows, workspace)?; + return Ok(DraftKvOutcome::Cancelled); + } + if let Err(primary) = self.enqueue_group( + t, + group, + policy.per_group_sync, + &retained, + ring, + &mut cmds, + if policy.per_group_sync { + &mut copies[3..] + } else { + &mut copies[..] + }, + &tokens[c..c + t], + cell0 + c, + ) { + let drained = self.drain_graphs(rows, workspace); + return combine(Err(primary), drained); + } + cmds.clear(); + if policy.per_group_sync { + self.drain_graphs(rows, workspace)?; + } + } + if !policy.per_group_sync { + self.drain_graphs(rows, workspace)?; + } + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + for (p, runs) in changed.iter_mut().enumerate() { + ring.read_encoded_page(first_page + p, runs)?; + } + for runs in changed { + pages.push(Rc::new(Page { + runs: runs.map(Vec::into_boxed_slice), + })); + } + let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { + origin: ring.origin.clone(), + pages: Pages::from_vec(pages), + end, + checked: std::cell::Cell::new(false), + })); + ring.current = Some(snapshot.clone()); + ring.generation = generation; + Ok(DraftKvOutcome::Completed(CompletedDraftKv { + snapshot, + first_materialized: first, + end, + generation, + })) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let mut primary = Ok(()); + if let Some(graphs) = self.graphs.take() { + primary = combine(primary, graphs.close()); + } + if let Some(stream) = self.stream.take() { + let r = stream.close(); + if r.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + primary = combine(primary, r); + } + for module in &mut self.modules { + if let Some(m) = module.take() { + let r = if self.context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine( + Rc::try_unwrap(m) + .map_err(|_| Error::InvalidQwenShape) + .and_then(Module::close), + g.finish(), + ), + Err(e) => { + self.context.poison(); + std::mem::forget(m); + Err(e) + } + } + }; + if r.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + primary = combine(primary, r); + } + } + for b in [&mut self.scratch, &mut self.records, &mut self.status] { + if let Some(b) = b.take() { + primary = combine( + primary, + if self.context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + match Rc::try_unwrap(b) { + Ok(b) => b.release(), + Err(b) => { + if self.original_layout.is_some() { + drop(b); + Ok(()) + } else { + Err(Error::InvalidQwenShape) + } + } + } + }, + ); + } + } + if let Some(mut m) = self.mapped.borrow_mut().take() { + let result = if self.context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine(m.close(), g.finish()), + Err(e) => { + self.context.poison(); + std::mem::forget(m); + Err(e) + } + } + }; + if result.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + primary = combine(primary, result); + } + self.retained = None; + if self.context.is_poisoned() { + std::mem::forget(std::mem::take(&mut self.pending_host)); + } else { + self.pending_host.clear(); + } + if self.context.is_poisoned() { + self.context.retain_driver(); + } + primary + } +} +impl Drop for OriginalMtpScalarPrefill<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} + +#[path = "mtp_original_scalar_graph.rs"] +mod graph; + +#[cfg(test)] +#[path = "mtp_original_scalar_short_gpu.rs"] +mod short_prompt_gpu; diff --git a/crates/leleka-runtime/src/qwen_forward/kar_ple_cache.rs b/crates/leleka-runtime/src/qwen_forward/kar_ple_cache.rs index 84da781b..5a0e13a6 100644 --- a/crates/leleka-runtime/src/qwen_forward/kar_ple_cache.rs +++ b/crates/leleka-runtime/src/qwen_forward/kar_ple_cache.rs @@ -1,1301 +1,1301 @@ -//! One explicit experimental loaded provider, on its CUDA owner thread. -//! Cache mappings publish only after synchronized scatter + decode + finite readback. -#![allow(dead_code)] -use super::contract::{Error, Result}; -use crate::model_binding::qwen4exp_input::{BindingIdentity, PLE_ROWS}; -use crate::model_binding::qwen4exp_kar_ple::{KarPleBinding, KarRowPacket, KarRowReader}; -use leleka_cuda_driver::{Context, DeviceBuffer}; -use std::collections::{HashMap, VecDeque}; -use std::hash::{BuildHasherDefault, Hasher}; -use std::sync::Arc; -use std::thread::JoinHandle; -const CACHE_BYTES: usize = 64 * 1024 * 1024; -const SLOTS: u32 = (CACHE_BYTES / 64) as u32; -const OUTPUT_BYTES: usize = 16 * 160 * 4; -#[derive(Clone, Copy)] -struct Entry { - slot: u32, - age: u64, -} -/// Row numbers are dense small integers: SipHash costs more than the rest of a chunk's lookups together. -#[derive(Default)] -struct RowHasher(u64); -impl Hasher for RowHasher { - fn finish(&self) -> u64 { - self.0 - } - fn write(&mut self, bytes: &[u8]) { - for b in bytes { - self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100000001b3); - } - } - fn write_u64(&mut self, value: u64) { - let mut x = value.wrapping_add(0x9e3779b97f4a7c15); - x = (x ^ (x >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); - x = (x ^ (x >> 27)).wrapping_mul(0x94d049bb133111eb); - self.0 = x ^ (x >> 31); - } -} -type RowMap = HashMap>; -/// The rows the device cache holds, with a recency queue so the least recently used rows are found without scanning the map. -/// `order` holds `(age, row)` items in non-decreasing age (every age change pushes the new item at the back; ages only grow). -/// An item is live when the map still holds the row at exactly that age; an older item of a row that was touched since, or of an -/// evicted row, is stale and skipped (stale items at the front are dropped, the rest by `compact_if_loose`). A row has exactly one -/// live item. Finding the oldest `n` rows therefore reads the front of the queue, not the ~1M entries of a full cache. -#[derive(Default)] -struct Residents { - map: RowMap, - order: VecDeque<(u64, u64)>, - /// Items `oldest` examined, summed over calls (tests bound it). - #[cfg(test)] - examined: std::sync::atomic::AtomicUsize, -} -impl Residents { - fn len(&self) -> usize { - self.map.len() - } - fn get(&self, row: &u64) -> Option<&Entry> { - self.map.get(row) - } - fn contains_key(&self, row: &u64) -> bool { - self.map.contains_key(row) - } - fn try_reserve(&mut self, additional: usize) -> std::result::Result<(), std::collections::TryReserveError> { - self.map.try_reserve(additional)?; - self.order.try_reserve(additional) - } - /// Set the age of a held row (a no-op when it already has that age); returns its slot. - fn touch(&mut self, row: &u64, age: u64) -> Option { - let entry = self.map.get_mut(row)?; - let slot = entry.slot; - if entry.age != age { - entry.age = age; - self.order.push_back((age, *row)); - self.compact_if_loose(); - } - Some(slot) - } - fn insert(&mut self, row: u64, slot: u32, age: u64) { - self.map.insert(row, Entry { slot, age }); - self.order.push_back((age, row)); - self.compact_if_loose(); - } - fn remove(&mut self, row: &u64) { - self.map.remove(row); - while let Some(&(age, front)) = self.order.front() { - if self.map.get(&front).is_some_and(|e| e.age == age) { - break; - } - self.order.pop_front(); - } - } - fn compact_if_loose(&mut self) { - if self.order.len() > 2 * self.map.len() + 4096 { - let map = &self.map; - self.order.retain(|(age, row)| map.get(row).is_some_and(|e| e.age == *age)); - } - } - /// The `need` least recently used rows with age below `below` that `skip` does not name, oldest first, as `(row, slot)` - /// (rows of equal age in queue order); fewer when the cache holds fewer. Also returns how many items were examined: the cost, - /// which a test bounds. The queue answers; the full scan runs only when the queue gave fewer rows than asked. - fn oldest(&self, need: usize, below: u64, skip: impl Fn(u64) -> bool) -> Result<(Vec<(u64, u32)>, usize)> { - let mut out = Vec::<(u64, u32)>::new(); - out.try_reserve_exact(need.min(self.map.len())) - .map_err(|_| Error::InputAllocation)?; - let mut examined = 0usize; - for &(age, row) in &self.order { - if out.len() == need || age >= below { - break; - } - examined += 1; - if let Some(e) = self.map.get(&row) { - if e.age == age && !skip(row) { - out.push((row, e.slot)); - } - } - } - if out.len() < need { - let mut all: Vec<(u64, u64, u32)> = Vec::new(); - all.try_reserve_exact(self.map.len()) - .map_err(|_| Error::InputAllocation)?; - all.extend( - self.map - .iter() - .filter(|(r, e)| e.age < below && !skip(**r)) - .map(|(r, e)| (e.age, *r, e.slot)), - ); - examined += self.map.len(); - if all.len() > out.len() { - let take = need.min(all.len()); - if take < all.len() { - all.select_nth_unstable_by_key(take - 1, |c| (c.0, c.1)); - all.truncate(take); - } - all.sort_unstable_by_key(|c| (c.0, c.1)); - out.clear(); - out.extend(all.into_iter().map(|(_, r, s)| (r, s))); - } - } - #[cfg(test)] - self.examined.fetch_add(examined, std::sync::atomic::Ordering::Relaxed); - Ok((out, examined)) - } -} -/// A chunk's PLE rows resolved to cache slots (`KarPleCache::stage_batch`): the update records the device must -/// scatter and the slot of every row, plus the mapping changes `commit` publishes once the device has accepted them. -pub(super) struct KarPleStaged { - updates: Vec, - slots: Vec, - inserts: Vec<(u64, u32, Option)>, - next_slot: u32, - stamp: u64, -} -impl KarPleStaged { - pub(super) fn updates(&self) -> &[u8] { - &self.updates - } - pub(super) fn slots(&self) -> &[u32] { - &self.slots - } -} -/// Rows of a chunk against the cache map: the slot of every row the cache holds (its age refreshed to `stamp`), and -/// the distinct rows it lacks with, per position, which of them the position names (`u32::MAX` placeholder in `slots`). -struct Lookup { - slots: Vec, - miss_rows: Vec, - pending: Vec<(u32, u32)>, -} -fn lookup_rows(entries: &mut Residents, rows: &[[u64; 16]], stamp: u64) -> Result { - let total = rows.len().checked_mul(16).ok_or(Error::Overflow)?; - let mut slots = Vec::new(); - slots - .try_reserve_exact(total) - .map_err(|_| Error::InputAllocation)?; - let mut miss_rows = Vec::::new(); - let mut miss_of = RowMap::::default(); - let mut pending = Vec::<(u32, u32)>::new(); - for (at, row) in rows.iter().flatten().enumerate() { - if let Some(slot) = entries.touch(row, stamp) { - slots.push(slot); - continue; - } - let miss = match miss_of.get(row) { - Some(&m) => m, - None => { - let m = u32::try_from(miss_rows.len()).map_err(|_| Error::Overflow)?; - miss_rows.push(*row); - miss_of.insert(*row, m); - m - } - }; - slots.push(u32::MAX); - pending.push((at as u32, miss)); - } - Ok(Lookup { - slots, - miss_rows, - pending, - }) -} -/// A slot for each missing row: free slots first (`next_slot..capacity`), then the least recently used rows the chunk -/// did not touch (age below `stamp`). Returns the slot and the evicted row (if any) per miss, and the new `next_slot`. -#[allow(clippy::type_complexity)] -fn assign_slots( - entries: &Residents, - next_slot: u32, - capacity: u32, - stamp: u64, - misses: usize, -) -> Result<(Vec, Vec>, u32)> { - let free = (capacity - next_slot) as usize; - let from_free = free.min(misses); - let mut miss_slot = Vec::::new(); - miss_slot - .try_reserve_exact(misses) - .map_err(|_| Error::InputAllocation)?; - let mut victims = Vec::>::new(); - victims - .try_reserve_exact(misses) - .map_err(|_| Error::InputAllocation)?; - for i in 0..from_free { - miss_slot.push(next_slot + i as u32); - victims.push(None); - } - let need = misses - from_free; - if need > 0 { - let (oldest, _) = entries.oldest(need, stamp, |_| false)?; - if oldest.len() < need { - return Err(Error::InvalidDimension); - } - for (row, slot) in oldest { - miss_slot.push(slot); - victims.push(Some(row)); - } - } - Ok((miss_slot, victims, next_slot + from_free as u32)) -} -/// One row of a gather the cache lacks: its position in the 16 rows, the slot it gets and the row evicted from that slot. -struct PlannedMiss { - at: usize, - row: u64, - slot: u32, - victim: Option, -} -struct GatherPlan { - misses: Vec, - selected: [u32; 16], - next_slot: u32, -} -/// The slot of each of the sixteen rows of one token: held rows keep theirs, each distinct missing row gets a free slot -/// (`next_slot..capacity`) or the slot of the least recently used row that is neither one of the sixteen nor already a victim. -/// Nothing is mutated. -fn plan_gather(entries: &Residents, mut next_slot: u32, capacity: u32, rows: &[u64; 16]) -> Result { - let mut misses = Vec::::new(); - misses.try_reserve_exact(16).map_err(|_| Error::InputAllocation)?; - let mut selected = [0u32; 16]; - for (i, row) in rows.iter().enumerate() { - if let Some(entry) = entries.get(row) { - selected[i] = entry.slot; - continue; - } - if let Some(miss) = misses.iter().find(|m| m.row == *row) { - selected[i] = miss.slot; - continue; - } - let (slot, victim) = if next_slot < capacity { - let slot = next_slot; - next_slot += 1; - (slot, None) - } else { - let (oldest, _) = entries.oldest(1, u64::MAX, |r| { - rows.contains(&r) || misses.iter().any(|m| m.victim == Some(r)) - })?; - let &(victim, slot) = oldest.first().ok_or(Error::InvalidDimension)?; - (slot, Some(victim)) - }; - selected[i] = slot; - misses.push(PlannedMiss { - at: i, - row: *row, - slot, - victim, - }); - } - Ok(GatherPlan { - misses, - selected, - next_slot, - }) -} -/// Publish a gather the device accepted: evict the victims, map the new rows, and age the sixteen rows `age_base + 1..=16` -/// in order (a row named twice keeps the later age), as the scan-based code did. -fn publish_gather(entries: &mut Residents, misses: &[PlannedMiss], rows: &[u64; 16], age_base: u64) { - for m in misses { - if let Some(victim) = m.victim { - entries.remove(&victim); - } - entries.insert(m.row, m.slot, age_base + 1); - } - for (i, row) in rows.iter().enumerate() { - entries - .touch(row, age_base + i as u64 + 1) - .expect("completed batch mapping"); - } -} -struct Miss { - row: u64, - slot: u32, - victim: Option, - payload: [u8; 50], - part: u16, -} -/// `LELEKA_PLE_AHEAD=on|off` (read once) turns the read-ahead of the next chunk's PLE packets on or off. Unset: on for Windows, where the -/// archive is a file the rows are read from at 20-45 k random reads a second (5 to 12 s of every 6144-token chunk); off elsewhere, where -/// the server profile keeps the archive in a memfd and its rows are a memory read (not measured, so not changed). -fn ahead_enabled() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| match std::env::var("LELEKA_PLE_AHEAD").ok().as_deref() { - Some("on" | "1" | "yes") => true, - Some("off" | "0" | "no") => false, - _ => cfg!(windows), - }) -} -/// Threads of the read-ahead: the positional reads are latency-bound (three random pages per row), not CPU-bound. -const AHEAD_THREADS: usize = 24; -/// Packets read ahead and not used yet are dropped past this many (a chunk of 8192 tokens is 131,072 rows). -const AHEAD_KEEP: usize = 1 << 20; -/// The packets of the rows a chunk about to be read will miss, fetched on a thread of their own while the chunk -/// before it computes. A packet is a function of the archive's bytes only, so reading it early changes nothing the -/// device sees; a failed read-ahead is dropped and the rows are read at their use, which reports the error as before. -#[derive(Default)] -struct Ahead { - reader: Option>, - reader_failed: bool, - pending: Option>>, - ready: RowMap, -} -impl Ahead { - /// Wait for the outstanding read-ahead and keep what it read. - fn collect(&mut self) { - if let Some(handle) = self.pending.take() { - if let Ok(rows) = handle.join() { - self.ready.extend(rows); - } - } - } -} -pub(crate) struct KarPleCache<'ctx> { - ahead: Ahead, - context: &'ctx Context<'ctx>, - cache: DeviceBuffer<'ctx>, - books: DeviceBuffer<'ctx>, - slots: DeviceBuffer<'ctx>, - output: DeviceBuffer<'ctx>, - binding: BindingIdentity, - archive: [u8; 32], - profile: [u8; 32], - entries: Residents, - next_slot: u32, - age: u64, - failed: bool, -} -impl<'ctx> KarPleCache<'ctx> { - pub(crate) fn new(context: &'ctx Context<'ctx>, binding: &KarPleBinding) -> Result { - let book_bytes = binding - .books() - .len() - .checked_mul(8) - .ok_or(Error::Overflow)?; - let needed = CACHE_BYTES - .checked_add(book_bytes) - .and_then(|n| n.checked_add(64 + OUTPUT_BYTES + 16 * 56)) - .ok_or(Error::Overflow)?; - if context - .allocated_bytes() - .checked_add(needed) - .is_none_or(|n| n > context.budget_bytes()) - { - return Err(Error::InputAllocation); - } - let mut data = Vec::new(); - data.try_reserve_exact(book_bytes) - .map_err(|_| Error::InputAllocation)?; - for book in binding.books() { - for value in book { - data.extend_from_slice(&value.to_le_bytes()); - } - } - let cache = context - .allocate(CACHE_BYTES) - .map_err(|_| Error::CudaExecution)?; - let mut books = context - .allocate(book_bytes) - .map_err(|_| Error::CudaExecution)?; - books.copy_from(&data).map_err(|_| Error::CudaExecution)?; - let slots = context.allocate(64).map_err(|_| Error::CudaExecution)?; - let output = context - .allocate(OUTPUT_BYTES) - .map_err(|_| Error::CudaExecution)?; - Ok(Self { - ahead: Ahead::default(), - context, - cache, - books, - slots, - output, - binding: binding.identity(), - archive: *binding.archive_digest(), - profile: *binding.profile_digest(), - entries: Residents::default(), - next_slot: 0, - age: 0, - failed: false, - }) - } - pub(super) fn context_matches(&self, context: &Context<'_>) -> bool { - std::ptr::eq(self.context, context) - } - /// The device cache and the partition books, for `OriginalPromptDevice::initialize_staged`. - pub(super) fn device_parts(&mut self) -> (&mut DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>) { - (&mut self.cache, &self.books) - } - /// A device failure after `stage_batch` may have scattered into the cache: no mapping is trusted again. - pub(super) fn invalidate(&mut self) { - self.failed = true; - } - /// `gather` for every PLE row of a chunk at once, on the device. Nothing is gathered here: this resolves each of - /// the `rows.len() * 16` rows to a cache slot (reading the archive packets of the rows the cache lacks, in - /// parallel), assigns slots to the misses (free slots first, then the least recently used rows the chunk does - /// not use) and returns the update records and slot table the driver scatters and decodes with. The decoded - /// value of a row depends only on its packet, so the placement never changes a value. The mapping changes - /// (`commit`) happen only after the device accepted the chunk. - pub(super) fn stage_batch( - &mut self, - binding: &KarPleBinding, - rows: &[[u64; 16]], - ) -> Result { - if self.failed { - return Err(Error::CudaExecution); - } - if !binding.matches(&self.binding) - || &self.archive != binding.archive_digest() - || &self.profile != binding.profile_digest() - { - return Err(Error::IdentityMismatch); - } - if rows.is_empty() || rows.iter().flatten().any(|r| *r >= PLE_ROWS) { - return Err(Error::InvalidDimension); - } - let stamp = self.age.checked_add(1).ok_or(Error::Overflow)?; - let Lookup { - mut slots, - miss_rows, - pending, - } = lookup_rows(&mut self.entries, rows, stamp)?; - let packets = if miss_rows.is_empty() { - Vec::new() - } else { - self.ahead.collect(); - // the rows the read-ahead already holds come from it; the others are read now, as before - let mut packets = Vec::>::new(); - packets - .try_reserve_exact(miss_rows.len()) - .map_err(|_| Error::InputAllocation)?; - let mut rest_at = Vec::::new(); - let mut rest_rows = Vec::::new(); - let mut from_ahead = Vec::<(usize, u64)>::new(); - for (at, row) in miss_rows.iter().enumerate() { - match self.ahead.ready.remove(row) { - Some(packet) => { - from_ahead.push((at, *row)); - packets.push(Some(packet)); - } - None => { - packets.push(None); - rest_at.push(at); - rest_rows.push(*row); - } - } - } - if !rest_rows.is_empty() { - let read = binding - .read_rows_batch(&rest_rows) - .map_err(super::input::binding_error)?; - if read.len() != rest_rows.len() { - return Err(Error::InvalidDimension); - } - for (at, packet) in rest_at.into_iter().zip(read) { - packets[at] = Some(packet); - } - } - // LELEKA_PLE_AHEAD_VERIFY=1: every packet taken from the read-ahead is compared with a direct read of its row - if !from_ahead.is_empty() && std::env::var("LELEKA_PLE_AHEAD_VERIFY").is_ok_and(|v| v == "1") { - let rows: Vec = from_ahead.iter().map(|(_, row)| *row).collect(); - let direct = binding - .read_rows_batch(&rows) - .map_err(super::input::binding_error)?; - for ((at, row), direct) in from_ahead.iter().zip(&direct) { - let held = packets[*at].as_ref().ok_or(Error::InvalidDimension)?; - if held.payload() != direct.payload() || held.partition() != direct.partition() { - eprintln!("leleka-ple-ahead: MISMATCH row {row}"); - return Err(Error::IdentityMismatch); - } - } - eprintln!("leleka-ple-ahead: {} of {} missed rows came from the read-ahead, all equal to a direct read", from_ahead.len(), miss_rows.len()); - } - packets - .into_iter() - .collect::>>() - .ok_or(Error::InvalidDimension)? - }; - let misses = miss_rows.len(); - let (miss_slot, victims, next_slot) = - assign_slots(&self.entries, self.next_slot, SLOTS, stamp, misses)?; - for (at, miss) in pending { - slots[at as usize] = miss_slot[miss as usize]; - } - let mut updates = Vec::new(); - updates - .try_reserve_exact(misses * 56) - .map_err(|_| Error::InputAllocation)?; - let mut inserts = Vec::new(); - inserts - .try_reserve_exact(misses) - .map_err(|_| Error::InputAllocation)?; - for (i, packet) in packets.iter().enumerate() { - updates.extend_from_slice(&miss_slot[i].to_le_bytes()); - updates.extend_from_slice(packet.payload()); - updates.extend_from_slice(&packet.partition().to_le_bytes()); - inserts.push((miss_rows[i], miss_slot[i], victims[i])); - } - Ok(KarPleStaged { - updates, - slots, - inserts, - next_slot, - stamp, - }) - } - /// Start reading, on a thread of its own, the packets of the PLE `rows` (the sixteen rows of each token of the - /// chunk after the one being computed) that neither the device cache nor an earlier read-ahead holds. Call it - /// after `commit` of the current chunk. The result is used by the next `stage_batch`; nothing here can fail a request. - pub(super) fn read_ahead(&mut self, binding: &KarPleBinding, rows: &[u64]) { - if self.failed || rows.is_empty() || !ahead_enabled() { - return; - } - self.ahead.collect(); - if self.ahead.ready.len() > AHEAD_KEEP { - self.ahead.ready.clear(); - } - if self.ahead.reader.is_none() && !self.ahead.reader_failed { - match binding.row_reader() { - Ok(reader) => self.ahead.reader = Some(Arc::new(reader)), - Err(_) => self.ahead.reader_failed = true, - } - } - let Some(reader) = self.ahead.reader.clone() else { return }; - let mut seen = RowMap::<()>::default(); - let mut wanted = Vec::::new(); - for &row in rows { - if row >= PLE_ROWS || self.entries.contains_key(&row) || self.ahead.ready.contains_key(&row) { - continue; - } - if seen.insert(row, ()).is_none() { - wanted.push(row); - } - } - if wanted.is_empty() { - return; - } - let spawned = std::thread::Builder::new().name("ple-ahead".into()).spawn(move || { - match reader.read_rows(&wanted, AHEAD_THREADS) { - Ok(packets) if packets.len() == wanted.len() => wanted.into_iter().zip(packets).collect(), - _ => Vec::new(), - } - }); - if let Ok(handle) = spawned { - self.ahead.pending = Some(handle); - } - } - /// Publish the mapping of a chunk the device decoded and found finite. - pub(super) fn commit(&mut self, staged: KarPleStaged) { - for (_, _, victim) in &staged.inserts { - if let Some(victim) = victim { - self.entries.remove(victim); - } - } - for (row, slot, _) in staged.inserts { - self.entries.insert(row, slot, staged.stamp); - } - self.next_slot = staged.next_slot; - self.age = staged.stamp; - } - pub(super) fn gather( - &mut self, - binding: &KarPleBinding, - rows: &[u64; 16], - ) -> Result> { - if self.failed { - return Err(Error::CudaExecution); - } - if !binding.matches(&self.binding) - || &self.archive != binding.archive_digest() - || &self.profile != binding.profile_digest() - { - return Err(Error::IdentityMismatch); - } - let final_age = self.age.checked_add(16).ok_or(Error::Overflow)?; - // Read/validate every packet before any cache/device mutation. The FD stays in model_binding. - if rows.iter().any(|r| *r >= PLE_ROWS) { - return Err(Error::InvalidDimension); - } - let packets = if rows.iter().any(|r| !self.entries.contains_key(r)) { - let _p = super::original_serve_profile::span("ple.read_rows"); - Some( - binding - .read_rows(rows) - .map_err(super::input::binding_error)?, - ) - } else { - None - }; - let GatherPlan { - misses: planned, - selected, - next_slot, - } = plan_gather(&self.entries, self.next_slot, SLOTS, rows)?; - let mut misses = Vec::::new(); - misses - .try_reserve_exact(planned.len()) - .map_err(|_| Error::InputAllocation)?; - for p in &planned { - let packet = &packets.as_ref().expect("missing rows require packets")[p.at]; - misses.push(Miss { - row: p.row, - slot: p.slot, - victim: p.victim, - payload: *packet.payload(), - part: packet.partition(), - }); - } - let growth = misses.iter().filter(|m| m.victim.is_none()).count(); - self.entries - .try_reserve(growth) - .map_err(|_| Error::InputAllocation)?; - let mut updates = Vec::new(); - updates - .try_reserve_exact(misses.len() * 56) - .map_err(|_| Error::InputAllocation)?; - for m in &misses { - updates.extend_from_slice(&m.slot.to_le_bytes()); - updates.extend_from_slice(&m.payload); - updates.extend_from_slice(&m.part.to_le_bytes()); - } - let mut slot_bytes = [0u8; 64]; - for (i, slot) in selected.iter().enumerate() { - slot_bytes[i * 4..i * 4 + 4].copy_from_slice(&slot.to_le_bytes()); - } - let mut output = Vec::new(); - output - .try_reserve_exact(OUTPUT_BYTES) - .map_err(|_| Error::InputAllocation)?; - output.resize(OUTPUT_BYTES, 0); - let mut values = Vec::new(); - values - .try_reserve_exact(2560) - .map_err(|_| Error::InputAllocation)?; - // From the first mutating operation onward, any failure permanently invalidates - // this cache, including a partial scatter; no stale success mapping is reusable. - let _device_span = super::original_serve_profile::span("ple.device"); - let completed = (|| { - if !updates.is_empty() { - let mut device = self - .context - .allocate(updates.len()) - .map_err(|_| Error::CudaExecution)?; - device - .copy_from(&updates) - .map_err(|_| Error::CudaExecution)?; - self.context - .kar_ple_scatter(&mut self.cache, &device, misses.len() as u32) - .map_err(|_| Error::CudaExecution)?; - device.release().map_err(|_| Error::CudaExecution)?; - } - self.slots - .copy_from(&slot_bytes) - .map_err(|_| Error::CudaExecution)?; - self.context - .kar_ple_decode(&self.cache, &self.slots, &self.books, &mut self.output) - .map_err(|_| Error::CudaExecution)?; - self.output - .copy_to(&mut output) - .map_err(|_| Error::CudaExecution)?; - for word in output.as_chunks::<4>().0 { - let v = f32::from_le_bytes(*word); - if !v.is_finite() { - return Err(Error::NonFinite); - } - values.push(v); - } - Ok(()) - })(); - if let Err(error) = completed { - self.failed = true; - return Err(error); - } - publish_gather(&mut self.entries, &planned, rows, self.age); - self.next_slot = next_slot; - self.age = final_age; - Ok(values.into_boxed_slice()) - } -} - -/// Row-level parity probe against the Original's `strata_next_kar_ple_probe` -/// (gpu/kar/src/kar_ple_cpu_probe.cpp). Test-only: it admits a plain file path -/// through the same `VerifiedKarPleArtifact::verify` + pinned profile as -/// production, but does not touch the sealed-fd admission. -#[cfg(all(test, any(target_os = "linux", target_os = "windows")))] -mod row_parity_probe { - use super::*; - use crate::model_binding::qwen4exp_kar_ple::pinned_profile; - use leleka_cuda_driver::Driver; - use leleka_model_format::kar::{KarInspection, VerifiedKarPleArtifact}; - use std::io::Write; - - fn fnv(values: &[f32]) -> u64 { - let mut hash = 0xcbf29ce484222325u64; - for v in values { - for b in v.to_le_bytes() { - hash ^= u64::from(b); - hash = hash.wrapping_mul(0x100000001b3); - } - } - hash - } - - #[test] - #[ignore = "reads the real 55 GB KAR archive and uses the GPU; set LELEKA_PLE_PROBE_ARCHIVE and LELEKA_PLE_PROBE_ROWS"] - fn dump_decoded_rows_for_original_comparison() { - let archive = std::env::var("LELEKA_PLE_PROBE_ARCHIVE").expect("archive path"); - let rows_path = std::env::var("LELEKA_PLE_PROBE_ROWS").expect("rows file"); - let mut rows: Vec = std::fs::read_to_string(rows_path) - .expect("rows file readable") - .split_whitespace() - .map(|t| t.parse().expect("row number")) - .collect(); - let wanted = rows.len(); - while rows.len() % 16 != 0 { - rows.push(*rows.last().unwrap()); - } - let file = std::fs::File::open(archive).expect("archive opens"); - let inspection = KarInspection::inspect(file).expect("inspect"); - let artifact = - VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) - .expect("pinned verify"); - let identity = BindingIdentity::test_identity(); - let binding = KarPleBinding::new(&identity, artifact).expect("binding"); - let driver = Driver::load().expect("driver"); - let device = driver.device(0).expect("device0"); - let context = device.create_context(2usize << 30).expect("context"); - let mut cache = KarPleCache::new(&context, &binding).expect("cache"); - let mut dump = std::env::var("LELEKA_PLE_PROBE_DUMP") - .ok() - .map(|p| std::fs::File::create(p).expect("dump file")); - let mut done = 0; - for chunk in rows.chunks_exact(16) { - let batch: [u64; 16] = chunk.try_into().unwrap(); - let values = cache.gather(&binding, &batch).expect("gather"); - for (i, row) in batch.iter().enumerate() { - if done + i < wanted { - println!("row={} fnv1a64={:016x}", row, fnv(&values[i * 160..(i + 1) * 160])); - } - } - if let Some(dump) = dump.as_mut() { - for v in values.iter() { - dump.write_all(&v.to_le_bytes()).unwrap(); - } - } - done += 16; - } - } - - #[test] - #[ignore = "reads the real 55 GB KAR archive (full payload verification); set LELEKA_PLE_PROBE_ARCHIVE"] - fn batch_read_equals_the_sixteen_row_reads() { - let archive = std::env::var("LELEKA_PLE_PROBE_ARCHIVE").expect("archive path"); - let file = std::fs::File::open(archive).expect("archive opens"); - let inspection = KarInspection::inspect(file).expect("inspect"); - let artifact = - VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) - .expect("pinned verify"); - let identity = BindingIdentity::test_identity(); - let binding = KarPleBinding::new(&identity, artifact).expect("binding"); - // a deterministic spread over the whole table plus the first and last rows, more than one reader thread's share - let mut state = 0x9e3779b97f4a7c15u64; - let mut rows: Vec = (0..40_000) - .map(|_| { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - state % PLE_ROWS - }) - .collect(); - rows[0] = 0; - rows[1] = PLE_ROWS - 1; - while rows.len() % 16 != 0 { - rows.push(7); - } - let batch = binding.read_rows_batch(&rows).expect("batch read"); - assert_eq!(batch.len(), rows.len()); - for (i, chunk) in rows.chunks_exact(16).enumerate() { - let sixteen = binding.read_rows(chunk.try_into().unwrap()).expect("16-row read"); - for (j, packet) in sixteen.iter().enumerate() { - assert_eq!(packet.payload(), batch[i * 16 + j].payload(), "row {}", chunk[j]); - assert_eq!(packet.partition(), batch[i * 16 + j].partition(), "row {}", chunk[j]); - } - } - println!("batch read equals the 16-row reads for {} rows", rows.len()); - } -} - - -#[cfg(test)] -mod slot_tests { - use super::*; - - /// What `KarPleCache::commit` does to the map, over the pure parts. - fn apply( - entries: &mut Residents, - lookup: &Lookup, - miss_slot: &[u32], - victims: &[Option], - stamp: u64, - ) { - for victim in victims.iter().flatten() { - entries.remove(victim); - } - for (i, row) in lookup.miss_rows.iter().enumerate() { - entries.insert(*row, miss_slot[i], stamp); - } - } - fn chunk(rows: &[u64]) -> Vec<[u64; 16]> { - rows.chunks(16) - .map(|c| std::array::from_fn(|i| c[i % c.len()])) - .collect() - } - /// Every row maps to one slot and no slot serves two rows. - fn consistent(entries: &Residents) { - let mut seen = std::collections::HashSet::new(); - for entry in entries.map.values() { - assert!(seen.insert(entry.slot), "slot {} serves two rows", entry.slot); - } - } - - #[test] - fn a_fresh_chunk_gets_distinct_free_slots_and_duplicates_share_one() { - let mut entries = Residents::default(); - let rows = chunk(&[10, 20, 10, 30, 20, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140]); - let lookup = lookup_rows(&mut entries, &rows, 1).unwrap(); - assert_eq!(lookup.miss_rows.len(), 14); - let (miss_slot, victims, next) = assign_slots(&entries, 0, 100, 1, lookup.miss_rows.len()).unwrap(); - assert_eq!(next, 14); - assert!(victims.iter().all(Option::is_none)); - let mut slots = lookup.slots.clone(); - for (at, miss) in &lookup.pending { - slots[*at as usize] = miss_slot[*miss as usize]; - } - assert!(slots.iter().all(|s| *s < 14)); - assert_eq!(slots[0], slots[2]); - assert_eq!(slots[1], slots[4]); - apply(&mut entries, &lookup, &miss_slot, &victims, 1); - consistent(&entries); - assert_eq!(entries.len(), 14); - } - - #[test] - fn hits_keep_their_slots_and_refresh_their_age() { - let mut entries = Residents::default(); - let first = chunk(&[1, 2, 3, 4]); - let lookup = lookup_rows(&mut entries, &first, 1).unwrap(); - let (slot, victims, _) = assign_slots(&entries, 0, 8, 1, lookup.miss_rows.len()).unwrap(); - apply(&mut entries, &lookup, &slot, &victims, 1); - let before: Vec<(u64, u32)> = [1u64, 2, 3, 4].iter().map(|r| (*r, entries.map[r].slot)).collect(); - let second = chunk(&[3, 4, 5, 6]); - let lookup = lookup_rows(&mut entries, &second, 2).unwrap(); - assert_eq!(lookup.miss_rows, vec![5, 6]); - assert_eq!(entries.map[&3].age, 2); - assert_eq!(entries.map[&1].age, 1); - for (row, slot) in before { - assert_eq!(entries.map[&row].slot, slot); - } - } - - #[test] - fn a_full_cache_evicts_the_oldest_rows_the_chunk_does_not_touch() { - let mut entries = Residents::default(); - let capacity = 12u32; - let mut next = 0u32; - // chunk 1 fills 12 slots with rows 100..112 (stamp 1), chunk 2 refreshes 100..104 (stamp 2) - let rows1: Vec = (100..112).collect(); - let lookup = lookup_rows(&mut entries, &chunk(&rows1), 1).unwrap(); - let (slot, victims, n) = assign_slots(&entries, next, capacity, 1, lookup.miss_rows.len()).unwrap(); - apply(&mut entries, &lookup, &slot, &victims, 1); - next = n; - assert_eq!(next, capacity); - let lookup = lookup_rows(&mut entries, &chunk(&[100, 101, 102, 103]), 2).unwrap(); - assert!(lookup.miss_rows.is_empty()); - // chunk 3 touches 100, 101 and needs four new rows: the victims are the four oldest of 104..112 (age 1) - let rows3 = [100u64, 101, 500, 501, 502, 503]; - let lookup = lookup_rows(&mut entries, &chunk(&rows3), 3).unwrap(); - assert_eq!(lookup.miss_rows, vec![500, 501, 502, 503]); - let (slot, victims, n) = assign_slots(&entries, next, capacity, 3, lookup.miss_rows.len()).unwrap(); - assert_eq!(n, capacity); - let evicted: Vec = victims.iter().map(|v| v.expect("eviction")).collect(); - assert!(evicted.iter().all(|r| (104..112).contains(r)), "{evicted:?}"); - let distinct: std::collections::HashSet<_> = slot.iter().collect(); - assert_eq!(distinct.len(), 4); - // the evicted rows' slots are the ones handed out - for (i, v) in evicted.iter().enumerate() { - assert_eq!(entries.map[v].slot, slot[i]); - } - apply(&mut entries, &lookup, &slot, &victims, 3); - consistent(&entries); - assert_eq!(entries.len(), capacity as usize); - for r in [100u64, 101, 102, 103, 500, 501, 502, 503] { - assert!(entries.contains_key(&r), "row {r}"); - } - } - - /// Upstream 41cf05a0 `36381540` (`gather_batch` matched the prefetched rows by position): here rows are looked up by row - /// id, so a reordered, shifted, repeated or partly new chunk finds each row in the slot it was given, and a hit never moves. - #[test] - fn rows_are_matched_by_row_id_never_by_position_in_the_chunk() { - let mut entries = Residents::default(); - let first: Vec = (1..=32).map(|r| r * 1000).collect(); - let lookup = lookup_rows(&mut entries, &chunk(&first), 1).unwrap(); - let (slot, victims, _) = assign_slots(&entries, 0, 64, 1, lookup.miss_rows.len()).unwrap(); - apply(&mut entries, &lookup, &slot, &victims, 1); - let given: std::collections::HashMap = entries.map.iter().map(|(r, e)| (*r, e.slot)).collect(); - let slot_of = |row: u64| given[&row]; - let expect = |rows: &[u64]| -> Vec { rows.iter().map(|&r| slot_of(r)).collect() }; - let flat = |lookup: &Lookup| lookup.slots.clone(); - // a permutation (halves swapped), a reversal, a shift by one position, a repeat of one row and a subset - let mut swapped = first.clone(); - swapped.rotate_left(16); - let mut reversed = first.clone(); - reversed.reverse(); - let mut shifted = first.clone(); - shifted.rotate_left(1); - for (name, rows) in [ - ("swapped", swapped), - ("reversed", reversed), - ("shifted", shifted), - ("one row repeated", vec![first[5]; 16]), - ("subset", (0..16).map(|i| first[(i * 7) % 32]).collect()), - ] { - let lookup = lookup_rows(&mut entries, &chunk(&rows), 2).unwrap(); - assert!(lookup.miss_rows.is_empty() && lookup.pending.is_empty(), "{name}: a cached row is a miss"); - assert_eq!(flat(&lookup), expect(&rows), "{name}: a position got another row's slot"); - } - // a chunk of known and new rows: the known keep their slots wherever they stand, each new row is one miss however often it repeats - let mixed: Vec = vec![first[3], 77_001, first[0], 77_001, 77_002, first[3], first[31], 77_002]; - let lookup = lookup_rows(&mut entries, &chunk(&mixed), 3).unwrap(); - assert_eq!(lookup.miss_rows, vec![77_001, 77_002]); - for (at, &row) in mixed.iter().enumerate() { - let want = if row >= 77_000 { u32::MAX } else { slot_of(row) }; - // `chunk` pads a short chunk by repeating its rows: the first `mixed.len()` positions are the rows themselves - assert_eq!(lookup.slots[at], want, "mixed position {at}"); - } - // 77_001 stands at 2 of the 8 rows and 77_002 at 2: with the padding of the chunk, 4 positions name each - let named = |m: u32| lookup.pending.iter().filter(|(_, miss)| *miss == m).count(); - assert_eq!((named(0), named(1)), (4, 4)); - } - - #[test] - fn a_chunk_that_needs_more_slots_than_the_untouched_rows_hold_is_refused() { - let mut entries = Residents::default(); - let lookup = lookup_rows(&mut entries, &chunk(&(0..8).collect::>()), 1).unwrap(); - let (slot, victims, next) = assign_slots(&entries, 0, 8, 1, lookup.miss_rows.len()).unwrap(); - apply(&mut entries, &lookup, &slot, &victims, 1); - // touches 6 of the 8 rows and needs 4 new ones: only 2 rows are evictable - let lookup = lookup_rows(&mut entries, &chunk(&[0, 1, 2, 3, 4, 5, 90, 91, 92, 93]), 2).unwrap(); - assert_eq!(lookup.miss_rows.len(), 4); - assert_eq!( - assign_slots(&entries, next, 8, 2, 4).err(), - Some(Error::InvalidDimension) - ); - } -} - -#[cfg(test)] -mod lru_tests { - use super::*; - use std::collections::HashMap; - - struct Rng(u64); - impl Rng { - fn next(&mut self) -> u64 { - self.0 ^= self.0 << 13; - self.0 ^= self.0 >> 7; - self.0 ^= self.0 << 17; - self.0 - } - /// Half the draws from a hot set, the rest from the whole universe. - fn row(&mut self, hot: u64, universe: u64) -> u64 { - if self.next() % 2 == 0 { - self.next() % hot - } else { - self.next() % universe - } - } - } - - /// The previous implementation, kept as the reference: a plain map scanned in full for every victim. - struct Scan { - map: HashMap, - next_slot: u32, - age: u64, - capacity: u32, - } - impl Scan { - fn new(capacity: u32) -> Self { - Self { - map: HashMap::new(), - next_slot: 0, - age: 0, - capacity, - } - } - /// (selected slots, misses as (row, slot, victim)) exactly as `KarPleCache::gather` chose them before the recency queue. - fn gather(&mut self, rows: &[u64; 16]) -> ([u32; 16], Vec<(u64, u32, Option)>) { - let mut misses = Vec::<(u64, u32, Option)>::new(); - let mut selected = [0u32; 16]; - let mut next_slot = self.next_slot; - for (i, row) in rows.iter().enumerate() { - if let Some(&(slot, _)) = self.map.get(row) { - selected[i] = slot; - continue; - } - if let Some(m) = misses.iter().find(|m| m.0 == *row) { - selected[i] = m.1; - continue; - } - let (slot, victim) = if next_slot < self.capacity { - next_slot += 1; - (next_slot - 1, None) - } else { - let (victim, (slot, _)) = self - .map - .iter() - .filter(|(r, _)| !rows.contains(r) && !misses.iter().any(|m| m.2 == Some(**r))) - .min_by_key(|(_, e)| e.1) - .unwrap(); - (*slot, Some(*victim)) - }; - selected[i] = slot; - misses.push((*row, slot, victim)); - } - for m in &misses { - if let Some(v) = m.2 { - self.map.remove(&v); - } - self.map.insert(m.0, (m.1, 0)); - } - for (i, row) in rows.iter().enumerate() { - self.map.get_mut(row).unwrap().1 = self.age + i as u64 + 1; - } - self.next_slot = next_slot; - self.age += 16; - (selected, misses) - } - } - - /// The device side: what a scatter writes into a slot is the row's own packet (here the row number), so a gathered row is right - /// exactly when its slot holds its own number. - struct Device(Vec); - - fn token(rng: &mut Rng, hot: u64, universe: u64) -> [u64; 16] { - std::array::from_fn(|_| rng.row(hot, universe)) - } - - /// Gathers (the decode path) on a cache much smaller than the row universe: the queue picks the same slots, the same victims - /// and ends in the same state as the full scan, and every gathered row is its own row. - #[test] - fn gather_equals_the_full_scan_on_random_sequences() { - for (capacity, hot, universe, seed) in [(64u32, 40u64, 500u64, 1u64), (257, 200, 3000, 2), (1000, 300, 1200, 3), (32, 20, 40, 4)] { - let mut rng = Rng(0x9e3779b97f4a7c15 ^ seed); - let mut old = Scan::new(capacity); - let mut new = Residents::default(); - let (mut next_slot, mut age) = (0u32, 0u64); - let mut device = Device(vec![u64::MAX; capacity as usize]); - let mut evictions = 0usize; - for step in 0..6000 { - let rows = token(&mut rng, hot, universe); - let (old_selected, old_misses) = old.gather(&rows); - let plan = plan_gather(&new, next_slot, capacity, &rows).unwrap(); - assert_eq!(plan.selected, old_selected, "step {step}"); - let planned: Vec<_> = plan.misses.iter().map(|m| (m.row, m.slot, m.victim)).collect(); - assert_eq!(planned, old_misses, "step {step}"); - evictions += planned.iter().filter(|m| m.2.is_some()).count(); - for m in &plan.misses { - device.0[m.slot as usize] = m.row; - } - publish_gather(&mut new, &plan.misses, &rows, age); - next_slot = plan.next_slot; - age += 16; - for (i, row) in rows.iter().enumerate() { - assert_eq!(device.0[plan.selected[i] as usize], *row, "step {step} position {i}: wrong row in the slot"); - } - } - assert!(evictions > 1000, "capacity {capacity}: the cache never filled ({evictions} evictions)"); - let mut a: Vec<_> = old.map.iter().map(|(r, (s, g))| (*r, *s, *g)).collect(); - let mut b: Vec<_> = new.map.iter().map(|(r, e)| (*r, e.slot, e.age)).collect(); - a.sort(); - b.sort(); - assert_eq!(a, b, "capacity {capacity}: final state"); - assert!(new.order.len() <= 2 * new.len() + 4096 + 16, "queue grew to {} for {} rows", new.order.len(), new.len()); - } - } - - /// Prompt chunks (`lookup_rows` + `assign_slots` + commit) mixed with decode gathers: every row always reads its own slot, no slot - /// serves two rows, and each victim is among the oldest untouched rows (no kept row is older than a victim). - #[test] - fn chunks_and_gathers_interleaved_keep_every_row_in_its_own_slot() { - let capacity = 300u32; - let mut rng = Rng(0x2545f4914f6cdd1d); - let mut entries = Residents::default(); - let (mut next_slot, mut age) = (0u32, 0u64); - let mut device = Device(vec![u64::MAX; capacity as usize]); - let mut chunk_evictions = 0usize; - for step in 0..1500 { - if step % 3 == 0 { - let n = 1 + (rng.next() % 6) as usize; - let rows: Vec<[u64; 16]> = (0..n).map(|_| token(&mut rng, 150, 2500)).collect(); - let stamp = age + 1; - let lookup = lookup_rows(&mut entries, &rows, stamp).unwrap(); - let (miss_slot, victims, next) = assign_slots(&entries, next_slot, capacity, stamp, lookup.miss_rows.len()).unwrap(); - // a victim is no younger than any row left in the cache that the chunk did not touch - let youngest_victim = victims.iter().flatten().map(|v| entries.map[v].age).max(); - if let Some(limit) = youngest_victim { - let victims_set: std::collections::HashSet = victims.iter().flatten().copied().collect(); - for (r, e) in &entries.map { - if e.age < stamp && !victims_set.contains(r) { - assert!(e.age >= limit, "step {step}: row {r} (age {}) outlived a victim of age {limit}", e.age); - } - } - } - chunk_evictions += victims.iter().flatten().count(); - let mut slots = lookup.slots.clone(); - for (at, miss) in &lookup.pending { - slots[*at as usize] = miss_slot[*miss as usize]; - } - for (i, row) in lookup.miss_rows.iter().enumerate() { - device.0[miss_slot[i] as usize] = *row; - } - for v in victims.iter().flatten() { - entries.remove(v); - } - for (i, row) in lookup.miss_rows.iter().enumerate() { - entries.insert(*row, miss_slot[i], stamp); - } - next_slot = next; - age = stamp; - for (at, row) in rows.iter().flatten().enumerate() { - assert_eq!(device.0[slots[at] as usize], *row, "step {step}: chunk position {at}"); - } - } else { - let rows = token(&mut rng, 150, 2500); - let plan = plan_gather(&entries, next_slot, capacity, &rows).unwrap(); - for m in &plan.misses { - device.0[m.slot as usize] = m.row; - } - publish_gather(&mut entries, &plan.misses, &rows, age); - next_slot = plan.next_slot; - age += 16; - for (i, row) in rows.iter().enumerate() { - assert_eq!(device.0[plan.selected[i] as usize], *row, "step {step}: gather position {i}"); - } - } - let mut seen = std::collections::HashSet::new(); - for e in entries.map.values() { - assert!(seen.insert(e.slot), "step {step}: slot {} serves two rows", e.slot); - } - assert!(entries.len() <= capacity as usize); - // one live queue item per row - let live = entries - .order - .iter() - .filter(|(a, r)| entries.map.get(r).is_some_and(|e| e.age == *a)) - .count(); - assert_eq!(live, entries.len(), "step {step}"); - } - assert!(chunk_evictions > 500, "the chunks never evicted ({chunk_evictions})"); - } - - /// A full cache of 200,000 rows: each missed row costs a handful of queue items, never the 200,000 entries the scan read. - #[test] - fn eviction_in_a_full_cache_examines_a_handful_of_items_not_the_cache() { - let capacity = 200_000u32; - let mut entries = Residents::default(); - let (mut next_slot, mut age) = (0u32, 0u64); - let mut row = 0u64; - let mut batches = 0; - let mut examined_after_full = 0usize; - let mut misses_after_full = 0usize; - while batches < capacity as usize / 16 + 2000 { - let rows: [u64; 16] = std::array::from_fn(|i| row + i as u64); - row += 16; - let before = entries.examined.load(std::sync::atomic::Ordering::Relaxed); - let plan = plan_gather(&entries, next_slot, capacity, &rows).unwrap(); - publish_gather(&mut entries, &plan.misses, &rows, age); - next_slot = plan.next_slot; - age += 16; - if next_slot == capacity { - examined_after_full += entries.examined.load(std::sync::atomic::Ordering::Relaxed) - before; - misses_after_full += plan.misses.len(); - } - batches += 1; - } - assert!(misses_after_full >= 16 * 1900, "{misses_after_full}"); - // each miss examines its victim plus the sixteen protected rows at most; the old scan examined `capacity` entries per miss - assert!( - examined_after_full <= misses_after_full * 40, - "{examined_after_full} items examined for {misses_after_full} misses (a scan would be {})", - misses_after_full * capacity as usize - ); - // and a hot row touched over and over leaves the queue bounded - for i in 0..50_000u64 { - entries.touch(&(row - 1 - (i % 4)), age + i + 1); - } - assert!(entries.order.len() <= 2 * entries.len() + 4096 + 1, "queue {}", entries.order.len()); - } - - /// A prompt chunk of 50,000 misses in a full cache reads the front of the queue, not the cache once per chunk. - #[test] - fn a_chunk_eviction_examines_about_as_many_items_as_it_needs() { - let capacity = 100_000u32; - let mut entries = Residents::default(); - for r in 0..capacity as u64 { - entries.insert(r, r as u32, 1 + r / 10); - } - let before = entries.examined.load(std::sync::atomic::Ordering::Relaxed); - let (victims, _) = entries.oldest(50_000, 1_000_000, |_| false).unwrap(); - assert_eq!(victims.len(), 50_000); - assert!(victims.iter().enumerate().all(|(i, (r, _))| *r == i as u64)); - let examined = entries.examined.load(std::sync::atomic::Ordering::Relaxed) - before; - assert_eq!(examined, 50_000); - } - - /// Fewer evictable rows than asked is refused by the caller; `oldest` itself returns what exists, found by the full scan. - #[test] - fn oldest_returns_what_exists_when_the_queue_runs_short() { - let mut entries = Residents::default(); - for r in 0..10u64 { - entries.insert(r, r as u32, r + 1); - } - let (victims, _) = entries.oldest(8, 6, |r| r == 2).unwrap(); - let rows: Vec = victims.iter().map(|v| v.0).collect(); - assert_eq!(rows, vec![0, 1, 3, 4]); - // a queue out of order (cannot happen by construction) is settled by the full scan, still oldest first - let mut entries = Residents::default(); - entries.insert(100, 0, 50); - entries.insert(101, 1, 10); - entries.insert(102, 2, 12); - let (victims, examined) = entries.oldest(2, 20, |_| false).unwrap(); - assert_eq!(victims, vec![(101, 1), (102, 2)]); - assert!(examined >= entries.len()); - } - - /// Cost of the old scan against the queue on a full cache of 1,048,576 rows (the production size): - /// `cargo test --release -p leleka-runtime scan_against_queue -- --ignored --nocapture`. - #[test] - #[ignore = "timing probe; prints the per-miss cost of the old scan and of the queue"] - fn scan_against_queue_on_a_full_cache() { - let capacity = SLOTS; - let mut entries = Residents::default(); - let mut old = Scan::new(capacity); - for r in 0..capacity as u64 { - entries.insert(r * 7 + 3, r as u32, 1 + r); - old.map.insert(r * 7 + 3, (r as u32, 1 + r)); - } - let rows: [u64; 16] = std::array::from_fn(|i| 1_000_000_007 + i as u64 * 2); - let t = std::time::Instant::now(); - let n = 20; - for _ in 0..n { - std::hint::black_box( - old.map - .iter() - .filter(|(r, _)| !rows.contains(r)) - .min_by_key(|(_, e)| e.1) - .map(|(r, _)| *r), - ); - } - let scan = t.elapsed() / n; - let t = std::time::Instant::now(); - for _ in 0..1000 { - std::hint::black_box(entries.oldest(1, u64::MAX, |r| rows.contains(&r)).unwrap()); - } - let queue = t.elapsed() / 1000; - println!("per missed row: old scan {scan:?}, recency queue {queue:?} (full cache of {capacity} rows)"); - } -} +//! One explicit experimental loaded provider, on its CUDA owner thread. +//! Cache mappings publish only after synchronized scatter + decode + finite readback. +#![allow(dead_code)] +use super::contract::{Error, Result}; +use crate::model_binding::qwen4exp_input::{BindingIdentity, PLE_ROWS}; +use crate::model_binding::qwen4exp_kar_ple::{KarPleBinding, KarRowPacket, KarRowReader}; +use leleka_cuda_driver::{Context, DeviceBuffer}; +use std::collections::{HashMap, VecDeque}; +use std::hash::{BuildHasherDefault, Hasher}; +use std::sync::Arc; +use std::thread::JoinHandle; +const CACHE_BYTES: usize = 64 * 1024 * 1024; +const SLOTS: u32 = (CACHE_BYTES / 64) as u32; +const OUTPUT_BYTES: usize = 16 * 160 * 4; +#[derive(Clone, Copy)] +struct Entry { + slot: u32, + age: u64, +} +/// Row numbers are dense small integers: SipHash costs more than the rest of a chunk's lookups together. +#[derive(Default)] +struct RowHasher(u64); +impl Hasher for RowHasher { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100000001b3); + } + } + fn write_u64(&mut self, value: u64) { + let mut x = value.wrapping_add(0x9e3779b97f4a7c15); + x = (x ^ (x >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + x = (x ^ (x >> 27)).wrapping_mul(0x94d049bb133111eb); + self.0 = x ^ (x >> 31); + } +} +type RowMap = HashMap>; +/// The rows the device cache holds, with a recency queue so the least recently used rows are found without scanning the map. +/// `order` holds `(age, row)` items in non-decreasing age (every age change pushes the new item at the back; ages only grow). +/// An item is live when the map still holds the row at exactly that age; an older item of a row that was touched since, or of an +/// evicted row, is stale and skipped (stale items at the front are dropped, the rest by `compact_if_loose`). A row has exactly one +/// live item. Finding the oldest `n` rows therefore reads the front of the queue, not the ~1M entries of a full cache. +#[derive(Default)] +struct Residents { + map: RowMap, + order: VecDeque<(u64, u64)>, + /// Items `oldest` examined, summed over calls (tests bound it). + #[cfg(test)] + examined: std::sync::atomic::AtomicUsize, +} +impl Residents { + fn len(&self) -> usize { + self.map.len() + } + fn get(&self, row: &u64) -> Option<&Entry> { + self.map.get(row) + } + fn contains_key(&self, row: &u64) -> bool { + self.map.contains_key(row) + } + fn try_reserve(&mut self, additional: usize) -> std::result::Result<(), std::collections::TryReserveError> { + self.map.try_reserve(additional)?; + self.order.try_reserve(additional) + } + /// Set the age of a held row (a no-op when it already has that age); returns its slot. + fn touch(&mut self, row: &u64, age: u64) -> Option { + let entry = self.map.get_mut(row)?; + let slot = entry.slot; + if entry.age != age { + entry.age = age; + self.order.push_back((age, *row)); + self.compact_if_loose(); + } + Some(slot) + } + fn insert(&mut self, row: u64, slot: u32, age: u64) { + self.map.insert(row, Entry { slot, age }); + self.order.push_back((age, row)); + self.compact_if_loose(); + } + fn remove(&mut self, row: &u64) { + self.map.remove(row); + while let Some(&(age, front)) = self.order.front() { + if self.map.get(&front).is_some_and(|e| e.age == age) { + break; + } + self.order.pop_front(); + } + } + fn compact_if_loose(&mut self) { + if self.order.len() > 2 * self.map.len() + 4096 { + let map = &self.map; + self.order.retain(|(age, row)| map.get(row).is_some_and(|e| e.age == *age)); + } + } + /// The `need` least recently used rows with age below `below` that `skip` does not name, oldest first, as `(row, slot)` + /// (rows of equal age in queue order); fewer when the cache holds fewer. Also returns how many items were examined: the cost, + /// which a test bounds. The queue answers; the full scan runs only when the queue gave fewer rows than asked. + fn oldest(&self, need: usize, below: u64, skip: impl Fn(u64) -> bool) -> Result<(Vec<(u64, u32)>, usize)> { + let mut out = Vec::<(u64, u32)>::new(); + out.try_reserve_exact(need.min(self.map.len())) + .map_err(|_| Error::InputAllocation)?; + let mut examined = 0usize; + for &(age, row) in &self.order { + if out.len() == need || age >= below { + break; + } + examined += 1; + if let Some(e) = self.map.get(&row) { + if e.age == age && !skip(row) { + out.push((row, e.slot)); + } + } + } + if out.len() < need { + let mut all: Vec<(u64, u64, u32)> = Vec::new(); + all.try_reserve_exact(self.map.len()) + .map_err(|_| Error::InputAllocation)?; + all.extend( + self.map + .iter() + .filter(|(r, e)| e.age < below && !skip(**r)) + .map(|(r, e)| (e.age, *r, e.slot)), + ); + examined += self.map.len(); + if all.len() > out.len() { + let take = need.min(all.len()); + if take < all.len() { + all.select_nth_unstable_by_key(take - 1, |c| (c.0, c.1)); + all.truncate(take); + } + all.sort_unstable_by_key(|c| (c.0, c.1)); + out.clear(); + out.extend(all.into_iter().map(|(_, r, s)| (r, s))); + } + } + #[cfg(test)] + self.examined.fetch_add(examined, std::sync::atomic::Ordering::Relaxed); + Ok((out, examined)) + } +} +/// A chunk's PLE rows resolved to cache slots (`KarPleCache::stage_batch`): the update records the device must +/// scatter and the slot of every row, plus the mapping changes `commit` publishes once the device has accepted them. +pub(super) struct KarPleStaged { + updates: Vec, + slots: Vec, + inserts: Vec<(u64, u32, Option)>, + next_slot: u32, + stamp: u64, +} +impl KarPleStaged { + pub(super) fn updates(&self) -> &[u8] { + &self.updates + } + pub(super) fn slots(&self) -> &[u32] { + &self.slots + } +} +/// Rows of a chunk against the cache map: the slot of every row the cache holds (its age refreshed to `stamp`), and +/// the distinct rows it lacks with, per position, which of them the position names (`u32::MAX` placeholder in `slots`). +struct Lookup { + slots: Vec, + miss_rows: Vec, + pending: Vec<(u32, u32)>, +} +fn lookup_rows(entries: &mut Residents, rows: &[[u64; 16]], stamp: u64) -> Result { + let total = rows.len().checked_mul(16).ok_or(Error::Overflow)?; + let mut slots = Vec::new(); + slots + .try_reserve_exact(total) + .map_err(|_| Error::InputAllocation)?; + let mut miss_rows = Vec::::new(); + let mut miss_of = RowMap::::default(); + let mut pending = Vec::<(u32, u32)>::new(); + for (at, row) in rows.iter().flatten().enumerate() { + if let Some(slot) = entries.touch(row, stamp) { + slots.push(slot); + continue; + } + let miss = match miss_of.get(row) { + Some(&m) => m, + None => { + let m = u32::try_from(miss_rows.len()).map_err(|_| Error::Overflow)?; + miss_rows.push(*row); + miss_of.insert(*row, m); + m + } + }; + slots.push(u32::MAX); + pending.push((at as u32, miss)); + } + Ok(Lookup { + slots, + miss_rows, + pending, + }) +} +/// A slot for each missing row: free slots first (`next_slot..capacity`), then the least recently used rows the chunk +/// did not touch (age below `stamp`). Returns the slot and the evicted row (if any) per miss, and the new `next_slot`. +#[allow(clippy::type_complexity)] +fn assign_slots( + entries: &Residents, + next_slot: u32, + capacity: u32, + stamp: u64, + misses: usize, +) -> Result<(Vec, Vec>, u32)> { + let free = (capacity - next_slot) as usize; + let from_free = free.min(misses); + let mut miss_slot = Vec::::new(); + miss_slot + .try_reserve_exact(misses) + .map_err(|_| Error::InputAllocation)?; + let mut victims = Vec::>::new(); + victims + .try_reserve_exact(misses) + .map_err(|_| Error::InputAllocation)?; + for i in 0..from_free { + miss_slot.push(next_slot + i as u32); + victims.push(None); + } + let need = misses - from_free; + if need > 0 { + let (oldest, _) = entries.oldest(need, stamp, |_| false)?; + if oldest.len() < need { + return Err(Error::InvalidDimension); + } + for (row, slot) in oldest { + miss_slot.push(slot); + victims.push(Some(row)); + } + } + Ok((miss_slot, victims, next_slot + from_free as u32)) +} +/// One row of a gather the cache lacks: its position in the 16 rows, the slot it gets and the row evicted from that slot. +struct PlannedMiss { + at: usize, + row: u64, + slot: u32, + victim: Option, +} +struct GatherPlan { + misses: Vec, + selected: [u32; 16], + next_slot: u32, +} +/// The slot of each of the sixteen rows of one token: held rows keep theirs, each distinct missing row gets a free slot +/// (`next_slot..capacity`) or the slot of the least recently used row that is neither one of the sixteen nor already a victim. +/// Nothing is mutated. +fn plan_gather(entries: &Residents, mut next_slot: u32, capacity: u32, rows: &[u64; 16]) -> Result { + let mut misses = Vec::::new(); + misses.try_reserve_exact(16).map_err(|_| Error::InputAllocation)?; + let mut selected = [0u32; 16]; + for (i, row) in rows.iter().enumerate() { + if let Some(entry) = entries.get(row) { + selected[i] = entry.slot; + continue; + } + if let Some(miss) = misses.iter().find(|m| m.row == *row) { + selected[i] = miss.slot; + continue; + } + let (slot, victim) = if next_slot < capacity { + let slot = next_slot; + next_slot += 1; + (slot, None) + } else { + let (oldest, _) = entries.oldest(1, u64::MAX, |r| { + rows.contains(&r) || misses.iter().any(|m| m.victim == Some(r)) + })?; + let &(victim, slot) = oldest.first().ok_or(Error::InvalidDimension)?; + (slot, Some(victim)) + }; + selected[i] = slot; + misses.push(PlannedMiss { + at: i, + row: *row, + slot, + victim, + }); + } + Ok(GatherPlan { + misses, + selected, + next_slot, + }) +} +/// Publish a gather the device accepted: evict the victims, map the new rows, and age the sixteen rows `age_base + 1..=16` +/// in order (a row named twice keeps the later age), as the scan-based code did. +fn publish_gather(entries: &mut Residents, misses: &[PlannedMiss], rows: &[u64; 16], age_base: u64) { + for m in misses { + if let Some(victim) = m.victim { + entries.remove(&victim); + } + entries.insert(m.row, m.slot, age_base + 1); + } + for (i, row) in rows.iter().enumerate() { + entries + .touch(row, age_base + i as u64 + 1) + .expect("completed batch mapping"); + } +} +struct Miss { + row: u64, + slot: u32, + victim: Option, + payload: [u8; 50], + part: u16, +} +/// `LELEKA_PLE_AHEAD=on|off` (read once) turns the read-ahead of the next chunk's PLE packets on or off. Unset: on for Windows, where the +/// archive is a file the rows are read from at 20-45 k random reads a second (5 to 12 s of every 6144-token chunk); off elsewhere, where +/// the server profile keeps the archive in a memfd and its rows are a memory read (not measured, so not changed). +fn ahead_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var("LELEKA_PLE_AHEAD").ok().as_deref() { + Some("on" | "1" | "yes") => true, + Some("off" | "0" | "no") => false, + _ => cfg!(windows), + }) +} +/// Threads of the read-ahead: the positional reads are latency-bound (three random pages per row), not CPU-bound. +const AHEAD_THREADS: usize = 24; +/// Packets read ahead and not used yet are dropped past this many (a chunk of 8192 tokens is 131,072 rows). +const AHEAD_KEEP: usize = 1 << 20; +/// The packets of the rows a chunk about to be read will miss, fetched on a thread of their own while the chunk +/// before it computes. A packet is a function of the archive's bytes only, so reading it early changes nothing the +/// device sees; a failed read-ahead is dropped and the rows are read at their use, which reports the error as before. +#[derive(Default)] +struct Ahead { + reader: Option>, + reader_failed: bool, + pending: Option>>, + ready: RowMap, +} +impl Ahead { + /// Wait for the outstanding read-ahead and keep what it read. + fn collect(&mut self) { + if let Some(handle) = self.pending.take() { + if let Ok(rows) = handle.join() { + self.ready.extend(rows); + } + } + } +} +pub(crate) struct KarPleCache<'ctx> { + ahead: Ahead, + context: &'ctx Context<'ctx>, + cache: DeviceBuffer<'ctx>, + books: DeviceBuffer<'ctx>, + slots: DeviceBuffer<'ctx>, + output: DeviceBuffer<'ctx>, + binding: BindingIdentity, + archive: [u8; 32], + profile: [u8; 32], + entries: Residents, + next_slot: u32, + age: u64, + failed: bool, +} +impl<'ctx> KarPleCache<'ctx> { + pub(crate) fn new(context: &'ctx Context<'ctx>, binding: &KarPleBinding) -> Result { + let book_bytes = binding + .books() + .len() + .checked_mul(8) + .ok_or(Error::Overflow)?; + let needed = CACHE_BYTES + .checked_add(book_bytes) + .and_then(|n| n.checked_add(64 + OUTPUT_BYTES + 16 * 56)) + .ok_or(Error::Overflow)?; + if context + .allocated_bytes() + .checked_add(needed) + .is_none_or(|n| n > context.budget_bytes()) + { + return Err(Error::InputAllocation); + } + let mut data = Vec::new(); + data.try_reserve_exact(book_bytes) + .map_err(|_| Error::InputAllocation)?; + for book in binding.books() { + for value in book { + data.extend_from_slice(&value.to_le_bytes()); + } + } + let cache = context + .allocate(CACHE_BYTES) + .map_err(|_| Error::CudaExecution)?; + let mut books = context + .allocate(book_bytes) + .map_err(|_| Error::CudaExecution)?; + books.copy_from(&data).map_err(|_| Error::CudaExecution)?; + let slots = context.allocate(64).map_err(|_| Error::CudaExecution)?; + let output = context + .allocate(OUTPUT_BYTES) + .map_err(|_| Error::CudaExecution)?; + Ok(Self { + ahead: Ahead::default(), + context, + cache, + books, + slots, + output, + binding: binding.identity(), + archive: *binding.archive_digest(), + profile: *binding.profile_digest(), + entries: Residents::default(), + next_slot: 0, + age: 0, + failed: false, + }) + } + pub(super) fn context_matches(&self, context: &Context<'_>) -> bool { + std::ptr::eq(self.context, context) + } + /// The device cache and the partition books, for `OriginalPromptDevice::initialize_staged`. + pub(super) fn device_parts(&mut self) -> (&mut DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>) { + (&mut self.cache, &self.books) + } + /// A device failure after `stage_batch` may have scattered into the cache: no mapping is trusted again. + pub(super) fn invalidate(&mut self) { + self.failed = true; + } + /// `gather` for every PLE row of a chunk at once, on the device. Nothing is gathered here: this resolves each of + /// the `rows.len() * 16` rows to a cache slot (reading the archive packets of the rows the cache lacks, in + /// parallel), assigns slots to the misses (free slots first, then the least recently used rows the chunk does + /// not use) and returns the update records and slot table the driver scatters and decodes with. The decoded + /// value of a row depends only on its packet, so the placement never changes a value. The mapping changes + /// (`commit`) happen only after the device accepted the chunk. + pub(super) fn stage_batch( + &mut self, + binding: &KarPleBinding, + rows: &[[u64; 16]], + ) -> Result { + if self.failed { + return Err(Error::CudaExecution); + } + if !binding.matches(&self.binding) + || &self.archive != binding.archive_digest() + || &self.profile != binding.profile_digest() + { + return Err(Error::IdentityMismatch); + } + if rows.is_empty() || rows.iter().flatten().any(|r| *r >= PLE_ROWS) { + return Err(Error::InvalidDimension); + } + let stamp = self.age.checked_add(1).ok_or(Error::Overflow)?; + let Lookup { + mut slots, + miss_rows, + pending, + } = lookup_rows(&mut self.entries, rows, stamp)?; + let packets = if miss_rows.is_empty() { + Vec::new() + } else { + self.ahead.collect(); + // the rows the read-ahead already holds come from it; the others are read now, as before + let mut packets = Vec::>::new(); + packets + .try_reserve_exact(miss_rows.len()) + .map_err(|_| Error::InputAllocation)?; + let mut rest_at = Vec::::new(); + let mut rest_rows = Vec::::new(); + let mut from_ahead = Vec::<(usize, u64)>::new(); + for (at, row) in miss_rows.iter().enumerate() { + match self.ahead.ready.remove(row) { + Some(packet) => { + from_ahead.push((at, *row)); + packets.push(Some(packet)); + } + None => { + packets.push(None); + rest_at.push(at); + rest_rows.push(*row); + } + } + } + if !rest_rows.is_empty() { + let read = binding + .read_rows_batch(&rest_rows) + .map_err(super::input::binding_error)?; + if read.len() != rest_rows.len() { + return Err(Error::InvalidDimension); + } + for (at, packet) in rest_at.into_iter().zip(read) { + packets[at] = Some(packet); + } + } + // LELEKA_PLE_AHEAD_VERIFY=1: every packet taken from the read-ahead is compared with a direct read of its row + if !from_ahead.is_empty() && std::env::var("LELEKA_PLE_AHEAD_VERIFY").is_ok_and(|v| v == "1") { + let rows: Vec = from_ahead.iter().map(|(_, row)| *row).collect(); + let direct = binding + .read_rows_batch(&rows) + .map_err(super::input::binding_error)?; + for ((at, row), direct) in from_ahead.iter().zip(&direct) { + let held = packets[*at].as_ref().ok_or(Error::InvalidDimension)?; + if held.payload() != direct.payload() || held.partition() != direct.partition() { + eprintln!("leleka-ple-ahead: MISMATCH row {row}"); + return Err(Error::IdentityMismatch); + } + } + eprintln!("leleka-ple-ahead: {} of {} missed rows came from the read-ahead, all equal to a direct read", from_ahead.len(), miss_rows.len()); + } + packets + .into_iter() + .collect::>>() + .ok_or(Error::InvalidDimension)? + }; + let misses = miss_rows.len(); + let (miss_slot, victims, next_slot) = + assign_slots(&self.entries, self.next_slot, SLOTS, stamp, misses)?; + for (at, miss) in pending { + slots[at as usize] = miss_slot[miss as usize]; + } + let mut updates = Vec::new(); + updates + .try_reserve_exact(misses * 56) + .map_err(|_| Error::InputAllocation)?; + let mut inserts = Vec::new(); + inserts + .try_reserve_exact(misses) + .map_err(|_| Error::InputAllocation)?; + for (i, packet) in packets.iter().enumerate() { + updates.extend_from_slice(&miss_slot[i].to_le_bytes()); + updates.extend_from_slice(packet.payload()); + updates.extend_from_slice(&packet.partition().to_le_bytes()); + inserts.push((miss_rows[i], miss_slot[i], victims[i])); + } + Ok(KarPleStaged { + updates, + slots, + inserts, + next_slot, + stamp, + }) + } + /// Start reading, on a thread of its own, the packets of the PLE `rows` (the sixteen rows of each token of the + /// chunk after the one being computed) that neither the device cache nor an earlier read-ahead holds. Call it + /// after `commit` of the current chunk. The result is used by the next `stage_batch`; nothing here can fail a request. + pub(super) fn read_ahead(&mut self, binding: &KarPleBinding, rows: &[u64]) { + if self.failed || rows.is_empty() || !ahead_enabled() { + return; + } + self.ahead.collect(); + if self.ahead.ready.len() > AHEAD_KEEP { + self.ahead.ready.clear(); + } + if self.ahead.reader.is_none() && !self.ahead.reader_failed { + match binding.row_reader() { + Ok(reader) => self.ahead.reader = Some(Arc::new(reader)), + Err(_) => self.ahead.reader_failed = true, + } + } + let Some(reader) = self.ahead.reader.clone() else { return }; + let mut seen = RowMap::<()>::default(); + let mut wanted = Vec::::new(); + for &row in rows { + if row >= PLE_ROWS || self.entries.contains_key(&row) || self.ahead.ready.contains_key(&row) { + continue; + } + if seen.insert(row, ()).is_none() { + wanted.push(row); + } + } + if wanted.is_empty() { + return; + } + let spawned = std::thread::Builder::new().name("ple-ahead".into()).spawn(move || { + match reader.read_rows(&wanted, AHEAD_THREADS) { + Ok(packets) if packets.len() == wanted.len() => wanted.into_iter().zip(packets).collect(), + _ => Vec::new(), + } + }); + if let Ok(handle) = spawned { + self.ahead.pending = Some(handle); + } + } + /// Publish the mapping of a chunk the device decoded and found finite. + pub(super) fn commit(&mut self, staged: KarPleStaged) { + for (_, _, victim) in &staged.inserts { + if let Some(victim) = victim { + self.entries.remove(victim); + } + } + for (row, slot, _) in staged.inserts { + self.entries.insert(row, slot, staged.stamp); + } + self.next_slot = staged.next_slot; + self.age = staged.stamp; + } + pub(super) fn gather( + &mut self, + binding: &KarPleBinding, + rows: &[u64; 16], + ) -> Result> { + if self.failed { + return Err(Error::CudaExecution); + } + if !binding.matches(&self.binding) + || &self.archive != binding.archive_digest() + || &self.profile != binding.profile_digest() + { + return Err(Error::IdentityMismatch); + } + let final_age = self.age.checked_add(16).ok_or(Error::Overflow)?; + // Read/validate every packet before any cache/device mutation. The FD stays in model_binding. + if rows.iter().any(|r| *r >= PLE_ROWS) { + return Err(Error::InvalidDimension); + } + let packets = if rows.iter().any(|r| !self.entries.contains_key(r)) { + let _p = super::original_serve_profile::span("ple.read_rows"); + Some( + binding + .read_rows(rows) + .map_err(super::input::binding_error)?, + ) + } else { + None + }; + let GatherPlan { + misses: planned, + selected, + next_slot, + } = plan_gather(&self.entries, self.next_slot, SLOTS, rows)?; + let mut misses = Vec::::new(); + misses + .try_reserve_exact(planned.len()) + .map_err(|_| Error::InputAllocation)?; + for p in &planned { + let packet = &packets.as_ref().expect("missing rows require packets")[p.at]; + misses.push(Miss { + row: p.row, + slot: p.slot, + victim: p.victim, + payload: *packet.payload(), + part: packet.partition(), + }); + } + let growth = misses.iter().filter(|m| m.victim.is_none()).count(); + self.entries + .try_reserve(growth) + .map_err(|_| Error::InputAllocation)?; + let mut updates = Vec::new(); + updates + .try_reserve_exact(misses.len() * 56) + .map_err(|_| Error::InputAllocation)?; + for m in &misses { + updates.extend_from_slice(&m.slot.to_le_bytes()); + updates.extend_from_slice(&m.payload); + updates.extend_from_slice(&m.part.to_le_bytes()); + } + let mut slot_bytes = [0u8; 64]; + for (i, slot) in selected.iter().enumerate() { + slot_bytes[i * 4..i * 4 + 4].copy_from_slice(&slot.to_le_bytes()); + } + let mut output = Vec::new(); + output + .try_reserve_exact(OUTPUT_BYTES) + .map_err(|_| Error::InputAllocation)?; + output.resize(OUTPUT_BYTES, 0); + let mut values = Vec::new(); + values + .try_reserve_exact(2560) + .map_err(|_| Error::InputAllocation)?; + // From the first mutating operation onward, any failure permanently invalidates + // this cache, including a partial scatter; no stale success mapping is reusable. + let _device_span = super::original_serve_profile::span("ple.device"); + let completed = (|| { + if !updates.is_empty() { + let mut device = self + .context + .allocate(updates.len()) + .map_err(|_| Error::CudaExecution)?; + device + .copy_from(&updates) + .map_err(|_| Error::CudaExecution)?; + self.context + .kar_ple_scatter(&mut self.cache, &device, misses.len() as u32) + .map_err(|_| Error::CudaExecution)?; + device.release().map_err(|_| Error::CudaExecution)?; + } + self.slots + .copy_from(&slot_bytes) + .map_err(|_| Error::CudaExecution)?; + self.context + .kar_ple_decode(&self.cache, &self.slots, &self.books, &mut self.output) + .map_err(|_| Error::CudaExecution)?; + self.output + .copy_to(&mut output) + .map_err(|_| Error::CudaExecution)?; + for word in output.as_chunks::<4>().0 { + let v = f32::from_le_bytes(*word); + if !v.is_finite() { + return Err(Error::NonFinite); + } + values.push(v); + } + Ok(()) + })(); + if let Err(error) = completed { + self.failed = true; + return Err(error); + } + publish_gather(&mut self.entries, &planned, rows, self.age); + self.next_slot = next_slot; + self.age = final_age; + Ok(values.into_boxed_slice()) + } +} + +/// Row-level parity probe against the Original's `strata_next_kar_ple_probe` +/// (gpu/kar/src/kar_ple_cpu_probe.cpp). Test-only: it admits a plain file path +/// through the same `VerifiedKarPleArtifact::verify` + pinned profile as +/// production, but does not touch the sealed-fd admission. +#[cfg(all(test, any(target_os = "linux", target_os = "windows")))] +mod row_parity_probe { + use super::*; + use crate::model_binding::qwen4exp_kar_ple::pinned_profile; + use leleka_cuda_driver::Driver; + use leleka_model_format::kar::{KarInspection, VerifiedKarPleArtifact}; + use std::io::Write; + + fn fnv(values: &[f32]) -> u64 { + let mut hash = 0xcbf29ce484222325u64; + for v in values { + for b in v.to_le_bytes() { + hash ^= u64::from(b); + hash = hash.wrapping_mul(0x100000001b3); + } + } + hash + } + + #[test] + #[ignore = "reads the real 55 GB KAR archive and uses the GPU; set LELEKA_PLE_PROBE_ARCHIVE and LELEKA_PLE_PROBE_ROWS"] + fn dump_decoded_rows_for_original_comparison() { + let archive = std::env::var("LELEKA_PLE_PROBE_ARCHIVE").expect("archive path"); + let rows_path = std::env::var("LELEKA_PLE_PROBE_ROWS").expect("rows file"); + let mut rows: Vec = std::fs::read_to_string(rows_path) + .expect("rows file readable") + .split_whitespace() + .map(|t| t.parse().expect("row number")) + .collect(); + let wanted = rows.len(); + while rows.len() % 16 != 0 { + rows.push(*rows.last().unwrap()); + } + let file = std::fs::File::open(archive).expect("archive opens"); + let inspection = KarInspection::inspect(file).expect("inspect"); + let artifact = + VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) + .expect("pinned verify"); + let identity = BindingIdentity::test_identity(); + let binding = KarPleBinding::new(&identity, artifact).expect("binding"); + let driver = Driver::load().expect("driver"); + let device = driver.device(0).expect("device0"); + let context = device.create_context(2usize << 30).expect("context"); + let mut cache = KarPleCache::new(&context, &binding).expect("cache"); + let mut dump = std::env::var("LELEKA_PLE_PROBE_DUMP") + .ok() + .map(|p| std::fs::File::create(p).expect("dump file")); + let mut done = 0; + for chunk in rows.chunks_exact(16) { + let batch: [u64; 16] = chunk.try_into().unwrap(); + let values = cache.gather(&binding, &batch).expect("gather"); + for (i, row) in batch.iter().enumerate() { + if done + i < wanted { + println!("row={} fnv1a64={:016x}", row, fnv(&values[i * 160..(i + 1) * 160])); + } + } + if let Some(dump) = dump.as_mut() { + for v in values.iter() { + dump.write_all(&v.to_le_bytes()).unwrap(); + } + } + done += 16; + } + } + + #[test] + #[ignore = "reads the real 55 GB KAR archive (full payload verification); set LELEKA_PLE_PROBE_ARCHIVE"] + fn batch_read_equals_the_sixteen_row_reads() { + let archive = std::env::var("LELEKA_PLE_PROBE_ARCHIVE").expect("archive path"); + let file = std::fs::File::open(archive).expect("archive opens"); + let inspection = KarInspection::inspect(file).expect("inspect"); + let artifact = + VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) + .expect("pinned verify"); + let identity = BindingIdentity::test_identity(); + let binding = KarPleBinding::new(&identity, artifact).expect("binding"); + // a deterministic spread over the whole table plus the first and last rows, more than one reader thread's share + let mut state = 0x9e3779b97f4a7c15u64; + let mut rows: Vec = (0..40_000) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % PLE_ROWS + }) + .collect(); + rows[0] = 0; + rows[1] = PLE_ROWS - 1; + while rows.len() % 16 != 0 { + rows.push(7); + } + let batch = binding.read_rows_batch(&rows).expect("batch read"); + assert_eq!(batch.len(), rows.len()); + for (i, chunk) in rows.chunks_exact(16).enumerate() { + let sixteen = binding.read_rows(chunk.try_into().unwrap()).expect("16-row read"); + for (j, packet) in sixteen.iter().enumerate() { + assert_eq!(packet.payload(), batch[i * 16 + j].payload(), "row {}", chunk[j]); + assert_eq!(packet.partition(), batch[i * 16 + j].partition(), "row {}", chunk[j]); + } + } + println!("batch read equals the 16-row reads for {} rows", rows.len()); + } +} + + +#[cfg(test)] +mod slot_tests { + use super::*; + + /// What `KarPleCache::commit` does to the map, over the pure parts. + fn apply( + entries: &mut Residents, + lookup: &Lookup, + miss_slot: &[u32], + victims: &[Option], + stamp: u64, + ) { + for victim in victims.iter().flatten() { + entries.remove(victim); + } + for (i, row) in lookup.miss_rows.iter().enumerate() { + entries.insert(*row, miss_slot[i], stamp); + } + } + fn chunk(rows: &[u64]) -> Vec<[u64; 16]> { + rows.chunks(16) + .map(|c| std::array::from_fn(|i| c[i % c.len()])) + .collect() + } + /// Every row maps to one slot and no slot serves two rows. + fn consistent(entries: &Residents) { + let mut seen = std::collections::HashSet::new(); + for entry in entries.map.values() { + assert!(seen.insert(entry.slot), "slot {} serves two rows", entry.slot); + } + } + + #[test] + fn a_fresh_chunk_gets_distinct_free_slots_and_duplicates_share_one() { + let mut entries = Residents::default(); + let rows = chunk(&[10, 20, 10, 30, 20, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140]); + let lookup = lookup_rows(&mut entries, &rows, 1).unwrap(); + assert_eq!(lookup.miss_rows.len(), 14); + let (miss_slot, victims, next) = assign_slots(&entries, 0, 100, 1, lookup.miss_rows.len()).unwrap(); + assert_eq!(next, 14); + assert!(victims.iter().all(Option::is_none)); + let mut slots = lookup.slots.clone(); + for (at, miss) in &lookup.pending { + slots[*at as usize] = miss_slot[*miss as usize]; + } + assert!(slots.iter().all(|s| *s < 14)); + assert_eq!(slots[0], slots[2]); + assert_eq!(slots[1], slots[4]); + apply(&mut entries, &lookup, &miss_slot, &victims, 1); + consistent(&entries); + assert_eq!(entries.len(), 14); + } + + #[test] + fn hits_keep_their_slots_and_refresh_their_age() { + let mut entries = Residents::default(); + let first = chunk(&[1, 2, 3, 4]); + let lookup = lookup_rows(&mut entries, &first, 1).unwrap(); + let (slot, victims, _) = assign_slots(&entries, 0, 8, 1, lookup.miss_rows.len()).unwrap(); + apply(&mut entries, &lookup, &slot, &victims, 1); + let before: Vec<(u64, u32)> = [1u64, 2, 3, 4].iter().map(|r| (*r, entries.map[r].slot)).collect(); + let second = chunk(&[3, 4, 5, 6]); + let lookup = lookup_rows(&mut entries, &second, 2).unwrap(); + assert_eq!(lookup.miss_rows, vec![5, 6]); + assert_eq!(entries.map[&3].age, 2); + assert_eq!(entries.map[&1].age, 1); + for (row, slot) in before { + assert_eq!(entries.map[&row].slot, slot); + } + } + + #[test] + fn a_full_cache_evicts_the_oldest_rows_the_chunk_does_not_touch() { + let mut entries = Residents::default(); + let capacity = 12u32; + let mut next = 0u32; + // chunk 1 fills 12 slots with rows 100..112 (stamp 1), chunk 2 refreshes 100..104 (stamp 2) + let rows1: Vec = (100..112).collect(); + let lookup = lookup_rows(&mut entries, &chunk(&rows1), 1).unwrap(); + let (slot, victims, n) = assign_slots(&entries, next, capacity, 1, lookup.miss_rows.len()).unwrap(); + apply(&mut entries, &lookup, &slot, &victims, 1); + next = n; + assert_eq!(next, capacity); + let lookup = lookup_rows(&mut entries, &chunk(&[100, 101, 102, 103]), 2).unwrap(); + assert!(lookup.miss_rows.is_empty()); + // chunk 3 touches 100, 101 and needs four new rows: the victims are the four oldest of 104..112 (age 1) + let rows3 = [100u64, 101, 500, 501, 502, 503]; + let lookup = lookup_rows(&mut entries, &chunk(&rows3), 3).unwrap(); + assert_eq!(lookup.miss_rows, vec![500, 501, 502, 503]); + let (slot, victims, n) = assign_slots(&entries, next, capacity, 3, lookup.miss_rows.len()).unwrap(); + assert_eq!(n, capacity); + let evicted: Vec = victims.iter().map(|v| v.expect("eviction")).collect(); + assert!(evicted.iter().all(|r| (104..112).contains(r)), "{evicted:?}"); + let distinct: std::collections::HashSet<_> = slot.iter().collect(); + assert_eq!(distinct.len(), 4); + // the evicted rows' slots are the ones handed out + for (i, v) in evicted.iter().enumerate() { + assert_eq!(entries.map[v].slot, slot[i]); + } + apply(&mut entries, &lookup, &slot, &victims, 3); + consistent(&entries); + assert_eq!(entries.len(), capacity as usize); + for r in [100u64, 101, 102, 103, 500, 501, 502, 503] { + assert!(entries.contains_key(&r), "row {r}"); + } + } + + /// Upstream 41cf05a0 `36381540` (`gather_batch` matched the prefetched rows by position): here rows are looked up by row + /// id, so a reordered, shifted, repeated or partly new chunk finds each row in the slot it was given, and a hit never moves. + #[test] + fn rows_are_matched_by_row_id_never_by_position_in_the_chunk() { + let mut entries = Residents::default(); + let first: Vec = (1..=32).map(|r| r * 1000).collect(); + let lookup = lookup_rows(&mut entries, &chunk(&first), 1).unwrap(); + let (slot, victims, _) = assign_slots(&entries, 0, 64, 1, lookup.miss_rows.len()).unwrap(); + apply(&mut entries, &lookup, &slot, &victims, 1); + let given: std::collections::HashMap = entries.map.iter().map(|(r, e)| (*r, e.slot)).collect(); + let slot_of = |row: u64| given[&row]; + let expect = |rows: &[u64]| -> Vec { rows.iter().map(|&r| slot_of(r)).collect() }; + let flat = |lookup: &Lookup| lookup.slots.clone(); + // a permutation (halves swapped), a reversal, a shift by one position, a repeat of one row and a subset + let mut swapped = first.clone(); + swapped.rotate_left(16); + let mut reversed = first.clone(); + reversed.reverse(); + let mut shifted = first.clone(); + shifted.rotate_left(1); + for (name, rows) in [ + ("swapped", swapped), + ("reversed", reversed), + ("shifted", shifted), + ("one row repeated", vec![first[5]; 16]), + ("subset", (0..16).map(|i| first[(i * 7) % 32]).collect()), + ] { + let lookup = lookup_rows(&mut entries, &chunk(&rows), 2).unwrap(); + assert!(lookup.miss_rows.is_empty() && lookup.pending.is_empty(), "{name}: a cached row is a miss"); + assert_eq!(flat(&lookup), expect(&rows), "{name}: a position got another row's slot"); + } + // a chunk of known and new rows: the known keep their slots wherever they stand, each new row is one miss however often it repeats + let mixed: Vec = vec![first[3], 77_001, first[0], 77_001, 77_002, first[3], first[31], 77_002]; + let lookup = lookup_rows(&mut entries, &chunk(&mixed), 3).unwrap(); + assert_eq!(lookup.miss_rows, vec![77_001, 77_002]); + for (at, &row) in mixed.iter().enumerate() { + let want = if row >= 77_000 { u32::MAX } else { slot_of(row) }; + // `chunk` pads a short chunk by repeating its rows: the first `mixed.len()` positions are the rows themselves + assert_eq!(lookup.slots[at], want, "mixed position {at}"); + } + // 77_001 stands at 2 of the 8 rows and 77_002 at 2: with the padding of the chunk, 4 positions name each + let named = |m: u32| lookup.pending.iter().filter(|(_, miss)| *miss == m).count(); + assert_eq!((named(0), named(1)), (4, 4)); + } + + #[test] + fn a_chunk_that_needs_more_slots_than_the_untouched_rows_hold_is_refused() { + let mut entries = Residents::default(); + let lookup = lookup_rows(&mut entries, &chunk(&(0..8).collect::>()), 1).unwrap(); + let (slot, victims, next) = assign_slots(&entries, 0, 8, 1, lookup.miss_rows.len()).unwrap(); + apply(&mut entries, &lookup, &slot, &victims, 1); + // touches 6 of the 8 rows and needs 4 new ones: only 2 rows are evictable + let lookup = lookup_rows(&mut entries, &chunk(&[0, 1, 2, 3, 4, 5, 90, 91, 92, 93]), 2).unwrap(); + assert_eq!(lookup.miss_rows.len(), 4); + assert_eq!( + assign_slots(&entries, next, 8, 2, 4).err(), + Some(Error::InvalidDimension) + ); + } +} + +#[cfg(test)] +mod lru_tests { + use super::*; + use std::collections::HashMap; + + struct Rng(u64); + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + /// Half the draws from a hot set, the rest from the whole universe. + fn row(&mut self, hot: u64, universe: u64) -> u64 { + if self.next() % 2 == 0 { + self.next() % hot + } else { + self.next() % universe + } + } + } + + /// The previous implementation, kept as the reference: a plain map scanned in full for every victim. + struct Scan { + map: HashMap, + next_slot: u32, + age: u64, + capacity: u32, + } + impl Scan { + fn new(capacity: u32) -> Self { + Self { + map: HashMap::new(), + next_slot: 0, + age: 0, + capacity, + } + } + /// (selected slots, misses as (row, slot, victim)) exactly as `KarPleCache::gather` chose them before the recency queue. + fn gather(&mut self, rows: &[u64; 16]) -> ([u32; 16], Vec<(u64, u32, Option)>) { + let mut misses = Vec::<(u64, u32, Option)>::new(); + let mut selected = [0u32; 16]; + let mut next_slot = self.next_slot; + for (i, row) in rows.iter().enumerate() { + if let Some(&(slot, _)) = self.map.get(row) { + selected[i] = slot; + continue; + } + if let Some(m) = misses.iter().find(|m| m.0 == *row) { + selected[i] = m.1; + continue; + } + let (slot, victim) = if next_slot < self.capacity { + next_slot += 1; + (next_slot - 1, None) + } else { + let (victim, (slot, _)) = self + .map + .iter() + .filter(|(r, _)| !rows.contains(r) && !misses.iter().any(|m| m.2 == Some(**r))) + .min_by_key(|(_, e)| e.1) + .unwrap(); + (*slot, Some(*victim)) + }; + selected[i] = slot; + misses.push((*row, slot, victim)); + } + for m in &misses { + if let Some(v) = m.2 { + self.map.remove(&v); + } + self.map.insert(m.0, (m.1, 0)); + } + for (i, row) in rows.iter().enumerate() { + self.map.get_mut(row).unwrap().1 = self.age + i as u64 + 1; + } + self.next_slot = next_slot; + self.age += 16; + (selected, misses) + } + } + + /// The device side: what a scatter writes into a slot is the row's own packet (here the row number), so a gathered row is right + /// exactly when its slot holds its own number. + struct Device(Vec); + + fn token(rng: &mut Rng, hot: u64, universe: u64) -> [u64; 16] { + std::array::from_fn(|_| rng.row(hot, universe)) + } + + /// Gathers (the decode path) on a cache much smaller than the row universe: the queue picks the same slots, the same victims + /// and ends in the same state as the full scan, and every gathered row is its own row. + #[test] + fn gather_equals_the_full_scan_on_random_sequences() { + for (capacity, hot, universe, seed) in [(64u32, 40u64, 500u64, 1u64), (257, 200, 3000, 2), (1000, 300, 1200, 3), (32, 20, 40, 4)] { + let mut rng = Rng(0x9e3779b97f4a7c15 ^ seed); + let mut old = Scan::new(capacity); + let mut new = Residents::default(); + let (mut next_slot, mut age) = (0u32, 0u64); + let mut device = Device(vec![u64::MAX; capacity as usize]); + let mut evictions = 0usize; + for step in 0..6000 { + let rows = token(&mut rng, hot, universe); + let (old_selected, old_misses) = old.gather(&rows); + let plan = plan_gather(&new, next_slot, capacity, &rows).unwrap(); + assert_eq!(plan.selected, old_selected, "step {step}"); + let planned: Vec<_> = plan.misses.iter().map(|m| (m.row, m.slot, m.victim)).collect(); + assert_eq!(planned, old_misses, "step {step}"); + evictions += planned.iter().filter(|m| m.2.is_some()).count(); + for m in &plan.misses { + device.0[m.slot as usize] = m.row; + } + publish_gather(&mut new, &plan.misses, &rows, age); + next_slot = plan.next_slot; + age += 16; + for (i, row) in rows.iter().enumerate() { + assert_eq!(device.0[plan.selected[i] as usize], *row, "step {step} position {i}: wrong row in the slot"); + } + } + assert!(evictions > 1000, "capacity {capacity}: the cache never filled ({evictions} evictions)"); + let mut a: Vec<_> = old.map.iter().map(|(r, (s, g))| (*r, *s, *g)).collect(); + let mut b: Vec<_> = new.map.iter().map(|(r, e)| (*r, e.slot, e.age)).collect(); + a.sort(); + b.sort(); + assert_eq!(a, b, "capacity {capacity}: final state"); + assert!(new.order.len() <= 2 * new.len() + 4096 + 16, "queue grew to {} for {} rows", new.order.len(), new.len()); + } + } + + /// Prompt chunks (`lookup_rows` + `assign_slots` + commit) mixed with decode gathers: every row always reads its own slot, no slot + /// serves two rows, and each victim is among the oldest untouched rows (no kept row is older than a victim). + #[test] + fn chunks_and_gathers_interleaved_keep_every_row_in_its_own_slot() { + let capacity = 300u32; + let mut rng = Rng(0x2545f4914f6cdd1d); + let mut entries = Residents::default(); + let (mut next_slot, mut age) = (0u32, 0u64); + let mut device = Device(vec![u64::MAX; capacity as usize]); + let mut chunk_evictions = 0usize; + for step in 0..1500 { + if step % 3 == 0 { + let n = 1 + (rng.next() % 6) as usize; + let rows: Vec<[u64; 16]> = (0..n).map(|_| token(&mut rng, 150, 2500)).collect(); + let stamp = age + 1; + let lookup = lookup_rows(&mut entries, &rows, stamp).unwrap(); + let (miss_slot, victims, next) = assign_slots(&entries, next_slot, capacity, stamp, lookup.miss_rows.len()).unwrap(); + // a victim is no younger than any row left in the cache that the chunk did not touch + let youngest_victim = victims.iter().flatten().map(|v| entries.map[v].age).max(); + if let Some(limit) = youngest_victim { + let victims_set: std::collections::HashSet = victims.iter().flatten().copied().collect(); + for (r, e) in &entries.map { + if e.age < stamp && !victims_set.contains(r) { + assert!(e.age >= limit, "step {step}: row {r} (age {}) outlived a victim of age {limit}", e.age); + } + } + } + chunk_evictions += victims.iter().flatten().count(); + let mut slots = lookup.slots.clone(); + for (at, miss) in &lookup.pending { + slots[*at as usize] = miss_slot[*miss as usize]; + } + for (i, row) in lookup.miss_rows.iter().enumerate() { + device.0[miss_slot[i] as usize] = *row; + } + for v in victims.iter().flatten() { + entries.remove(v); + } + for (i, row) in lookup.miss_rows.iter().enumerate() { + entries.insert(*row, miss_slot[i], stamp); + } + next_slot = next; + age = stamp; + for (at, row) in rows.iter().flatten().enumerate() { + assert_eq!(device.0[slots[at] as usize], *row, "step {step}: chunk position {at}"); + } + } else { + let rows = token(&mut rng, 150, 2500); + let plan = plan_gather(&entries, next_slot, capacity, &rows).unwrap(); + for m in &plan.misses { + device.0[m.slot as usize] = m.row; + } + publish_gather(&mut entries, &plan.misses, &rows, age); + next_slot = plan.next_slot; + age += 16; + for (i, row) in rows.iter().enumerate() { + assert_eq!(device.0[plan.selected[i] as usize], *row, "step {step}: gather position {i}"); + } + } + let mut seen = std::collections::HashSet::new(); + for e in entries.map.values() { + assert!(seen.insert(e.slot), "step {step}: slot {} serves two rows", e.slot); + } + assert!(entries.len() <= capacity as usize); + // one live queue item per row + let live = entries + .order + .iter() + .filter(|(a, r)| entries.map.get(r).is_some_and(|e| e.age == *a)) + .count(); + assert_eq!(live, entries.len(), "step {step}"); + } + assert!(chunk_evictions > 500, "the chunks never evicted ({chunk_evictions})"); + } + + /// A full cache of 200,000 rows: each missed row costs a handful of queue items, never the 200,000 entries the scan read. + #[test] + fn eviction_in_a_full_cache_examines_a_handful_of_items_not_the_cache() { + let capacity = 200_000u32; + let mut entries = Residents::default(); + let (mut next_slot, mut age) = (0u32, 0u64); + let mut row = 0u64; + let mut batches = 0; + let mut examined_after_full = 0usize; + let mut misses_after_full = 0usize; + while batches < capacity as usize / 16 + 2000 { + let rows: [u64; 16] = std::array::from_fn(|i| row + i as u64); + row += 16; + let before = entries.examined.load(std::sync::atomic::Ordering::Relaxed); + let plan = plan_gather(&entries, next_slot, capacity, &rows).unwrap(); + publish_gather(&mut entries, &plan.misses, &rows, age); + next_slot = plan.next_slot; + age += 16; + if next_slot == capacity { + examined_after_full += entries.examined.load(std::sync::atomic::Ordering::Relaxed) - before; + misses_after_full += plan.misses.len(); + } + batches += 1; + } + assert!(misses_after_full >= 16 * 1900, "{misses_after_full}"); + // each miss examines its victim plus the sixteen protected rows at most; the old scan examined `capacity` entries per miss + assert!( + examined_after_full <= misses_after_full * 40, + "{examined_after_full} items examined for {misses_after_full} misses (a scan would be {})", + misses_after_full * capacity as usize + ); + // and a hot row touched over and over leaves the queue bounded + for i in 0..50_000u64 { + entries.touch(&(row - 1 - (i % 4)), age + i + 1); + } + assert!(entries.order.len() <= 2 * entries.len() + 4096 + 1, "queue {}", entries.order.len()); + } + + /// A prompt chunk of 50,000 misses in a full cache reads the front of the queue, not the cache once per chunk. + #[test] + fn a_chunk_eviction_examines_about_as_many_items_as_it_needs() { + let capacity = 100_000u32; + let mut entries = Residents::default(); + for r in 0..capacity as u64 { + entries.insert(r, r as u32, 1 + r / 10); + } + let before = entries.examined.load(std::sync::atomic::Ordering::Relaxed); + let (victims, _) = entries.oldest(50_000, 1_000_000, |_| false).unwrap(); + assert_eq!(victims.len(), 50_000); + assert!(victims.iter().enumerate().all(|(i, (r, _))| *r == i as u64)); + let examined = entries.examined.load(std::sync::atomic::Ordering::Relaxed) - before; + assert_eq!(examined, 50_000); + } + + /// Fewer evictable rows than asked is refused by the caller; `oldest` itself returns what exists, found by the full scan. + #[test] + fn oldest_returns_what_exists_when_the_queue_runs_short() { + let mut entries = Residents::default(); + for r in 0..10u64 { + entries.insert(r, r as u32, r + 1); + } + let (victims, _) = entries.oldest(8, 6, |r| r == 2).unwrap(); + let rows: Vec = victims.iter().map(|v| v.0).collect(); + assert_eq!(rows, vec![0, 1, 3, 4]); + // a queue out of order (cannot happen by construction) is settled by the full scan, still oldest first + let mut entries = Residents::default(); + entries.insert(100, 0, 50); + entries.insert(101, 1, 10); + entries.insert(102, 2, 12); + let (victims, examined) = entries.oldest(2, 20, |_| false).unwrap(); + assert_eq!(victims, vec![(101, 1), (102, 2)]); + assert!(examined >= entries.len()); + } + + /// Cost of the old scan against the queue on a full cache of 1,048,576 rows (the production size): + /// `cargo test --release -p leleka-runtime scan_against_queue -- --ignored --nocapture`. + #[test] + #[ignore = "timing probe; prints the per-miss cost of the old scan and of the queue"] + fn scan_against_queue_on_a_full_cache() { + let capacity = SLOTS; + let mut entries = Residents::default(); + let mut old = Scan::new(capacity); + for r in 0..capacity as u64 { + entries.insert(r * 7 + 3, r as u32, 1 + r); + old.map.insert(r * 7 + 3, (r as u32, 1 + r)); + } + let rows: [u64; 16] = std::array::from_fn(|i| 1_000_000_007 + i as u64 * 2); + let t = std::time::Instant::now(); + let n = 20; + for _ in 0..n { + std::hint::black_box( + old.map + .iter() + .filter(|(r, _)| !rows.contains(r)) + .min_by_key(|(_, e)| e.1) + .map(|(r, _)| *r), + ); + } + let scan = t.elapsed() / n; + let t = std::time::Instant::now(); + for _ in 0..1000 { + std::hint::black_box(entries.oldest(1, u64::MAX, |r| rows.contains(&r)).unwrap()); + } + let queue = t.elapsed() / 1000; + println!("per missed row: old scan {scan:?}, recency queue {queue:?} (full cache of {capacity} rows)"); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs index ebf2320a..6f3d44fb 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs @@ -1,627 +1,627 @@ -//! The real owners behind `NativeServePort`: the serving host of the Original verified-window decode. -//! -//! One `OriginalServeHost` lives for one decode phase (one request). It borrows the target session, the -//! MTP draft session, the prompt executor (which owns the MTP actor), the penalty-history stage, the PLE -//! operator source and the routed-expert pool, and it implements every callback the serve port demands: -//! -//! * `validate_current` / `checkpoint_target` / `restore_target` over the committed-lineage ledger; -//! * `run_window`: window PLE rows, the literal penalty-history tail plus request sampling, and the -//! expert pool callback around `Verifier::run`; -//! * `publish_committed`: after the commit event, the twelve resident QSA witnesses are read from the -//! verifier's own journal and the accepted rows are published to the session (position, predecessors, -//! witnesses; the recurrent GDN/PLE state follows at `settle_state`); -//! * `draft_committed`: the literal `MtpDrafter::draft_from_verifier` over the published branch; -//! * `stage_draft_history` / `restore_draft` / `drain_draft` over the MTP actor and the draft session. -//! -//! Nothing here computes a model number or certifies one: it moves the owners' own receipts between each -//! other in the order generate.cpp does, and refuses every receipt that does not match the session. -use super::{ - contract::{Error, Result, Stage}, - dense_weight_cache::DenseWeightCache, - executor::original_prompt::OriginalPromptExecutor, - gdn::GdnPrior, - input::{InputStage, PlePrior}, - kar_ple_cache::KarPleCache, - original_mtp_verified_adapter::{OriginalCommittedMtpReceipt, OriginalLaunchedMtpDraft}, - original_serve_engine::DraftCompletion, - original_serve_ledger::{LedgerCheckpoint, ServeLedger}, - original_serve_native::NativeServeHost, - original_serve_pool::OriginalServePool, - original_serve_profile as profile, - original_serve_verifier::{driver_error, read_ple_history, ServeFailure}, - output_native::OriginalNativePenaltyHistory, - session::{ - original_prompt::draft::{OriginalDraftCheckpoint, OriginalDraftSession}, - QwenSession, TargetStepOrigin, - }, -}; -use crate::model_binding::qwen4exp_input::{BoundLayerKind, ModelBinding}; -use leleka_cuda_driver::{ - Context, DeviceBuffer, NativeHeadSelection, OriginalGpuEvent, OriginalNativeHeadGraphResources, OriginalMtpFullPolicy, - OriginalVerifier, OriginalVerifyGraphResources, OriginalVerifyQsaJournal, OriginalVerifyWindow, - OriginalVerifyWindowResult, SamplerParams, SamplerPath, -}; -use std::rc::Rc; - -/// What the request asked of the sampler: the CPU-reference parameters mapped field for field, the kernel -/// path chosen once from the environment. -#[derive(Clone, Copy, Debug)] -pub(in crate::qwen_forward) struct RequestSampling { - pub(in crate::qwen_forward) params: SamplerParams, - pub(in crate::qwen_forward) path: SamplerPath, -} -impl RequestSampling { - pub(in crate::qwen_forward) fn new(params: SamplerParams, path: SamplerPath) -> Result { - params.validate().map_err(|e| driver_error(&e))?; - Ok(Self { params, path }) - } - /// `req_sampling`: the head samples only when the request is stochastic or penalized; a greedy request - /// without history takes the plain argmax even if the flag is set, so setting it is always safe. - pub(in crate::qwen_forward) fn enabled(&self) -> bool { - !self.params.greedy || self.params.penalty_last_n > 0 - } -} - -/// The ending state of a host: what the stack needs to decide whether the physical owners need a repair -/// and whether the session can serve another request without a reset. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub(in crate::qwen_forward) struct HostOutcome { - /// The ledger saw an inconsistency (a failed publication, an unrecoverable restore). - pub(in crate::qwen_forward) failed: bool, - /// A window ran whose physical effects were never published: the QSA owners need their rollback. - pub(in crate::qwen_forward) dirty: bool, - /// The session's recurrent GDN/PLE priors lag its position (see `settle_state`). - pub(in crate::qwen_forward) state_lag: bool, - pub(in crate::qwen_forward) position: u64, -} - -pub(in crate::qwen_forward) struct OriginalServeHost<'a, 'ctx> { - binding: &'a ModelBinding, - dense: &'a DenseWeightCache<'ctx>, - context: &'ctx Context<'ctx>, - session: &'a mut QwenSession<'ctx>, - draft: &'a mut OriginalDraftSession<'ctx>, - executor: &'a mut OriginalPromptExecutor<'ctx>, - kar: Option<&'a mut KarPleCache<'ctx>>, - history: &'a mut OriginalNativePenaltyHistory<'ctx>, - pool: &'a mut dyn OriginalServePool<'ctx>, - /// A second reference to the verifier's QSA journal, only to read the committed mapped prefixes. - qsa: Rc>, - /// Model layer index of journal layer `i`. - slots: [usize; 12], - ple_history: &'a DeviceBuffer<'ctx>, - policy: &'a OriginalMtpFullPolicy, - sampling: RequestSampling, - ledger: ServeLedger, - /// The session origin the last window started from (the draft receipt names it). - window_origin: Option, - /// A draft launched behind the enqueued commit, completed after the publication (`launch_draft`). - launched: Option, - /// The round whose adaptive swaps are still to be planned and queued (`LELEKA_SERVE_ADAPT_DEFER`, default on): the host does that - /// work while the GPU runs the draft instead of before the commit and the draft are enqueued. - deferred_adaptation: Option, -} - -/// Everything a host borrows, in one place so the stack can build it in one expression. -pub(in crate::qwen_forward) struct HostOwners<'a, 'ctx> { - pub(in crate::qwen_forward) binding: &'a ModelBinding, - pub(in crate::qwen_forward) dense: &'a DenseWeightCache<'ctx>, - pub(in crate::qwen_forward) context: &'ctx Context<'ctx>, - pub(in crate::qwen_forward) session: &'a mut QwenSession<'ctx>, - pub(in crate::qwen_forward) draft: &'a mut OriginalDraftSession<'ctx>, - pub(in crate::qwen_forward) executor: &'a mut OriginalPromptExecutor<'ctx>, - pub(in crate::qwen_forward) kar: Option<&'a mut KarPleCache<'ctx>>, - pub(in crate::qwen_forward) history: &'a mut OriginalNativePenaltyHistory<'ctx>, - pub(in crate::qwen_forward) pool: &'a mut dyn OriginalServePool<'ctx>, - pub(in crate::qwen_forward) qsa: Rc>, - pub(in crate::qwen_forward) slots: [usize; 12], - pub(in crate::qwen_forward) ple_history: &'a DeviceBuffer<'ctx>, - pub(in crate::qwen_forward) policy: &'a OriginalMtpFullPolicy, -} - -/// `LELEKA_SERVE_PUBLISH=serial`: the per-layer checkpoint publication (A/B control of the batched one). -fn serial_publish() -> bool { - static SERIAL: std::sync::OnceLock = std::sync::OnceLock::new(); - *SERIAL.get_or_init(|| std::env::var("LELEKA_SERVE_PUBLISH").is_ok_and(|v| v == "serial")) -} - -fn operator_line(what: &str, failure: &ServeFailure) { - use std::io::Write; - // Fixed driver strings and error classes only; never request data. - let _ = writeln!(std::io::stderr().lock(), "leleka-serve {what}: {}", failure.describe()); -} - -impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { - /// `committed` is the token sequence the session holds (the prompt without its last token); `limit` is - /// the last position a state may end at. The session must stand exactly there, in step. - pub(in crate::qwen_forward) fn new( - owners: HostOwners<'a, 'ctx>, - committed: Vec, - limit: u64, - sampling: RequestSampling, - ) -> Result { - let HostOwners { binding, dense, context, session, draft, executor, kar, history, pool, qsa, slots, ple_history, policy } = - owners; - let position = session.target_origin()?.next_position(); - if session.original_state_lag().is_some() - || committed.len() as u64 != position - || !std::ptr::eq(context, session.mtp_context()?) - || binding.kar_ple_binding().is_some() != kar.is_some() - { - return Err(Error::IdentityMismatch); - } - let ledger = ServeLedger::new(committed, limit)?; - Ok(Self { - binding, - dense, - context, - session, - draft, - executor, - kar, - history, - pool, - qsa, - slots, - ple_history, - policy, - sampling, - ledger, - window_origin: None, - launched: None, - deferred_adaptation: None, - }) - } - - fn position(&self) -> Result { - Ok(self.session.target_origin()?.next_position()) - } - - /// The session's recurrent GDN and PLE priors, brought to its position from the verifier's canonical - /// image (one device-to-host transfer per request). Not needed for a request that is followed by a - /// reset; required before the session is checkpointed or reused as a resume source. - pub(in crate::qwen_forward) fn settle_state(&mut self, verifier: &mut OriginalVerifier<'ctx, R>) -> Result<()> - where - R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, - { - let Some(from) = self.session.original_state_lag() else { return Ok(()) }; - let position = self.position()?; - let rows = usize::try_from(position.checked_sub(from).ok_or(Error::InvalidPosition)?).map_err(|_| Error::Overflow)?; - let base = self.session.original_verified_base()?; - let mut gdn: [Option; 48] = std::array::from_fn(|_| None); - let mut ordinal = 0usize; - for layer in self.binding.ordered_layers() { - if layer.kind() != BoundLayerKind::Gdn { - continue; - } - let slot = layer.index() as usize; - let prior = base.gdn[slot].as_ref().ok_or(Error::IdentityMismatch)?; - let (values, history) = verifier - .with_committed_gdn(ordinal, |values, history| { - let mut v = Vec::new(); - v.try_reserve_exact(values.len()).map_err(|_| leleka_cuda_driver::Error::HostAllocation)?; - v.extend_from_slice(values); - let mut h = Vec::new(); - h.try_reserve_exact(history.len()).map_err(|_| leleka_cuda_driver::Error::HostAllocation)?; - h.extend_from_slice(history); - Ok((v.into_boxed_slice(), h.into_boxed_slice())) - }) - .map_err(|e| driver_error(&e))?; - gdn[slot] = Some(GdnPrior::from_original_verified(prior, rows, values, history)?); - ordinal += 1; - } - if ordinal != 36 { - return Err(Error::IdentityMismatch); - } - let ple = match base.ple.as_ref() { - Some(prior) => Some(PlePrior::from_original_verified(prior, rows, read_ple_history(self.ple_history)?)?), - None => None, - }; - self.session.publish_original_resident_state(gdn, ple) - } - - /// The tokens the session holds (the prompt without its last token, then every committed window input): - /// generate.cpp's `consumed`, what a continuing request must start with. - pub(in crate::qwen_forward) fn committed(&self) -> &[i32] { - self.ledger.committed() - } - - /// Whether the MTP draft ring stands at the session's position, so the next request could continue from - /// the session as is. False after a request that stopped on EOS/length: generate.cpp skips the draft of - /// the last window, so the ring never received that window's cells. - pub(in crate::qwen_forward) fn draft_in_step(&self) -> bool { - !self.ledger.is_failed() && !self.ledger.is_dirty() && self.draft.in_step(self.binding, self.session) - } - - /// The end of the decode phase: nothing is borrowed from the owners any more except through the - /// returned outcome. The caller drops the host (releasing its journal reference) before it closes the - /// verifier and takes the QSA owners back. - pub(in crate::qwen_forward) fn finish(self) -> HostOutcome { - let position = self.session.target_origin().map(|o| o.next_position()).unwrap_or(0); - HostOutcome { - failed: self.ledger.is_failed(), - dirty: self.ledger.is_dirty(), - state_lag: self.session.original_state_lag().is_some(), - position, - } - } -} - -/// `LELEKA_SERVE_ADAPT_DEFER=off`: plan and queue the adaptive swaps before the commit (the earlier order; the A/B control). -fn adapt_defer() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| !std::env::var("LELEKA_SERVE_ADAPT_DEFER").is_ok_and(|v| v == "off" || v == "0")) -} - -impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { - /// The MTP actor drafts as many chain steps as it is configured for (`set_max_drafts`); an adaptive round's plan is - /// applied here (the engine has already bounded it by the request's cap). Equal values cost one comparison. - fn apply_draft_cap(&mut self, max_drafts: usize) -> Result<()> { - let want = i32::try_from(max_drafts).map_err(|_| Error::Overflow)?; - let actor = self.executor.mtp_actor(self.binding)?; - if actor.settings().max_drafts() != want { - actor.set_max_drafts(want); - } - Ok(()) - } -} - -impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { - type TargetCheckpoint = LedgerCheckpoint; - type DraftCheckpoint = OriginalDraftCheckpoint; - type Adaptive = (); - type Seed = (); - - fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()> { - self.ledger.validate_current(consumed, input, position, self.position()?) - } - fn checkpoint_target(&self) -> Result { - self.ledger.checkpoint(self.position()?) - } - fn checkpoint_draft(&self) -> Result { - self.draft.checkpoint(self.binding, self.session) - } - fn restore_target(&mut self, checkpoint: &LedgerCheckpoint) -> Result<()> { - // An unpublished window never touched the session; its physical effects are rolled back when the - // phase ends. A commit that was enqueued cannot be undone and poisons the ledger. - self.window_origin = None; - let position = self.position()?; - self.ledger.restore(checkpoint, position) - } - fn restore_draft(&mut self, checkpoint: &OriginalDraftCheckpoint) -> Result<()> { - self.draft.restore_current(self.binding, self.dense, self.session, checkpoint) - } - fn apply_pending(&mut self) -> Result<()> { - // generate.cpp `apply_pending(false)`: completed adaptive swaps become resident (no work for the - // all-CPU tier). - self.pool.apply_pending() - } - - fn run_window( - &mut self, - verifier: &mut OriginalVerifier<'ctx, R>, - position: i64, - inputs: &[i32], - consumed: &[i32], - ) -> Result - where - R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, - { - let window_clock = super::original_serve_pool::window_trace::now(); - let _ = super::original_serve_pool::window_trace::take(); - let session_position = self.position()?; - self.ledger.begin_window(position, inputs, consumed, session_position)?; - let first = usize::try_from(position).map_err(|_| Error::InvalidPosition)?; - let origin = self.session.target_origin()?; - let ple_span = profile::span("window.ple"); - let ple = if self.session.original_ple_required() { - let predecessors = self.session.original_predecessors()?; - Some(InputStage::original_window_ple(self.binding, self.kar.as_deref_mut(), self.context, predecessors, inputs)?) - } else { - None - }; - let ple_ms = window_clock.map(|c| c.elapsed().as_secs_f64() * 1e3); - let mut verifier_ms = 0.0f64; - drop(ple_span); - let mut history_span = profile::span("window.history"); - let (params, path, enabled) = (self.sampling.params, self.sampling.path, self.sampling.enabled()); - let mut pool_error: Option = None; - let mut driver_failure: Option = None; - let Self { binding, session, history, pool, ledger, .. } = &mut *self; - let committed = ledger.committed(); - let result = history.with_sampling( - binding, - &**session, - &origin, - consumed, - inputs, - params, - path, - enabled, - || if committed == consumed { Ok(()) } else { Err(Error::IdentityMismatch) }, - |sampling| { - history_span.stop(); - let _p = profile::span("window.verifier"); - let verifier_clock = super::original_serve_pool::window_trace::now(); - let ran = verifier - .run(inputs, first, ple.as_deref(), sampling, |rows, sink, copy| { - let group_clock = super::original_serve_pool::window_trace::now(); - let ran = pool.run_group(rows, sink, copy).map_err(|error| { - pool_error = Some(error); - leleka_cuda_driver::Error::InvalidDriverValue("Original serve expert pool refused a layer group") - }); - if let Some(c) = group_clock { - super::original_serve_pool::window_trace::add(super::original_serve_pool::window_trace::POOL, c.elapsed().as_secs_f64() * 1e3); - } - ran - }); - if let Some(c) = verifier_clock { - verifier_ms = c.elapsed().as_secs_f64() * 1e3; - } - ran - .map_err(|error| { - let failure = ServeFailure::from(error); - let class = failure.error; - driver_failure = Some(failure); - class - }) - }, - ); - if let (Some(c), Some(ple_ms)) = (window_clock, ple_ms) { - let total = c.elapsed().as_secs_f64() * 1e3; - let sums = super::original_serve_pool::window_trace::take(); - let parts: Vec = super::original_serve_pool::window_trace::NAMES - .iter() - .zip(sums) - .map(|(name, v)| format!("{name}={v:.2}")) - .collect(); - eprintln!( - "DBG window rows={} total={total:.2} ple={ple_ms:.2} sampling_setup={:.2} verifier={verifier_ms:.2} gpu_wait_and_head={:.2} {}", - inputs.len(), - total - ple_ms - verifier_ms, - verifier_ms - sums[super::original_serve_pool::window_trace::POOL], - parts.join(" ") - ); - } - match result { - Ok(window) => { - self.window_origin = Some(origin); - Ok(window) - } - Err(error) => { - if let Some(failure) = driver_failure.as_ref() { - operator_line("window", failure); - } - // A pool refusal is the cause; the driver error it provoked is its echo. - Err(pool_error.unwrap_or(error)) - } - } - } - - fn commit_enqueued(&mut self, keep: usize) -> Result<()> { - self.ledger.commit_enqueued(keep) - } - - fn publish_committed(&mut self, verifier: &mut OriginalVerifier<'ctx, R>, position: i64, committed: &[i32]) -> Result<()> - where - R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, - { - let p = profile::span("publish.witnesses"); - let origin_after = self.session.original_origin_after(committed.len())?; - let witnesses = self.session.original_qsa_witnesses()?; - drop(p); - let mut next: [Option<_>; 48] = std::array::from_fn(|_| None); - { - let p = profile::span("publish.workspace"); - let mut workspace = self.dense.native_batch_workspace(self.binding, self.context)?.ok_or(Error::IdentityMismatch)?; - drop(p); - // The twelve index checkpoints in one batch after the commit event (one stream drain, pooled buffers), - // or one by one with a context synchronize each (LELEKA_SERVE_PUBLISH=serial, the earlier path). - let p = profile::span("publish.index_checkpoint"); - let mut batched = if serial_publish() { - None - } else { - Some(verifier.checkpoint_committed_qsa_all(&mut workspace).map_err(|e| driver_error(&e))?.map(Some)) - }; - drop(p); - for (journal_layer, &slot) in self.slots.iter().enumerate() { - let prior = witnesses[slot].as_ref().ok_or(Error::IdentityMismatch)?; - let p = profile::span("publish.index_checkpoint"); - let index = match batched.as_mut() { - Some(all) => all[journal_layer].take().ok_or(Error::IdentityMismatch)?, - None => verifier - .with_committed_qsa(journal_layer, |index| index.checkpoint(&mut workspace)) - .map_err(|e| driver_error(&e))?, - }; - drop(p); - let p = profile::span("publish.kv_prefix"); - let kv = self.qsa.committed_mapped_prefix(journal_layer).map_err(|e| driver_error(&e))?; - drop(p); - next[slot] = Some(prior.advanced(origin_after.clone(), index, kv)?); - } - } - let p = profile::span("publish.session"); - if serial_publish() { - self.session.publish_original_verified_rows(committed, self.ledger.limit(), next)?; - } else { - // fenced: the commit event was waited and the batched witness checkpoints drained above - self.session.publish_original_verified_rows_fenced(committed, self.ledger.limit(), next)?; - } - drop(p); - self.ledger.published(position, committed) - } - - fn begin_adaptation(&mut self, next_round: u64) -> Result<()> { - // generate.cpp `adapt()` when `(rounds + 1) % adapt_every == 0`, issued before the commit; its copies - // run on the tier's own stream beside the commit and the draft (no work for the all-CPU tier). - // The planning and the queueing are host work (0.6 ms on an adaptation round) that sat between the window and the commit/draft - // launch; with the deferral they run once the draft is launched (`run_deferred_adaptation`) or, at the latest, at the join, - // always before the next round's `apply_pending`. LELEKA_SERVE_ADAPT_DEFER=off runs them here as before. - if adapt_defer() { - if self.deferred_adaptation.is_some() { - return Err(Error::IdentityMismatch); - } - self.deferred_adaptation = Some(next_round); - return Ok(()); - } - self.pool.begin_adaptation(next_round) - } - fn run_deferred_adaptation(&mut self) -> Result<()> { - match self.deferred_adaptation.take() { - Some(round) => self.pool.begin_adaptation(round), - None => Ok(()), - } - } - fn join_adaptation(&mut self, _work: ()) -> Result<()> { - self.run_deferred_adaptation() - } - fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()> { - self.executor.set_mtp_draft_history(self.binding, consumed, next) - } - - fn draft_committed( - &mut self, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - position: i64, - accepted_row: usize, - max_drafts: usize, - min_p: f32, - _coupled: bool, - ) -> Result { - let before = self.window_origin.take().ok_or(Error::IdentityMismatch)?; - let first = u64::try_from(position).map_err(|_| Error::InvalidPosition)?; - if before.next_position() != first { - return Err(Error::IdentityMismatch); - } - // The actor drafts the chain length it is configured with: the request's cap, or the adaptive window's plan for this round. - self.apply_draft_cap(max_drafts)?; - let p = profile::span("draft.receipt"); - let receipt = OriginalCommittedMtpReceipt::for_published_window( - self.binding, - self.session, - self.context, - window, - selection, - before, - accepted_row, - )?; - drop(p); - let _p = profile::span("draft.drafter"); - let drafted = self.executor.draft_committed_mtp(self.binding, self.session, self.draft, receipt, min_p, self.policy)?; - let first_cell = i64::try_from(drafted.first_position()).map_err(|_| Error::Overflow)? - + i64::try_from(drafted.accepted_row()).map_err(|_| Error::Overflow)?; - Ok(DraftCompletion { - ids: drafted.ids().to_vec(), - probabilities: drafted.probabilities().to_vec(), - first_cell, - accepted_row: drafted.accepted_row(), - }) - } - fn launch_draft( - &mut self, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - position: i64, - accepted_row: usize, - max_drafts: usize, - min_p: f32, - after: Option<&mut OriginalGpuEvent<'ctx>>, - ) -> Result<()> { - if self.launched.is_some() { - return Err(Error::IdentityMismatch); - } - let before = self.window_origin.take().ok_or(Error::IdentityMismatch)?; - let first = u64::try_from(position).map_err(|_| Error::InvalidPosition)?; - if before.next_position() != first { - return Err(Error::IdentityMismatch); - } - // The actor drafts the chain length it is configured with: the request's cap, or the adaptive window's plan for this round. - self.apply_draft_cap(max_drafts)?; - let launched = self.executor.launch_committing_mtp( - self.binding, - self.session, - self.draft, - window, - selection, - before, - accepted_row, - min_p, - self.policy, - after, - )?; - self.launched = Some(launched); - Ok(()) - } - fn finish_draft(&mut self) -> Result { - let launched = self.launched.take().ok_or(Error::IdentityMismatch)?; - let drafted = self.executor.finish_committing_mtp(self.binding, self.session, self.draft, launched, self.policy)?; - let first_cell = i64::try_from(drafted.first_position()).map_err(|_| Error::Overflow)? - + i64::try_from(drafted.accepted_row()).map_err(|_| Error::Overflow)?; - Ok(DraftCompletion { - ids: drafted.ids().to_vec(), - probabilities: drafted.probabilities().to_vec(), - first_cell, - accepted_row: drafted.accepted_row(), - }) - } - fn drain_draft(&mut self) -> Result<()> { - self.executor.mtp_idle(self.binding) - } - fn draft_first( - &mut self, - _seed: &(), - _t: usize, - _cell: i64, - _token: i32, - _max_drafts: usize, - _min_p: f32, - _coupled: bool, - ) -> Result { - // generate.cpp calls `draft_first` only on the CLI's first window; the serve loop drafts from the - // verifier window of the first decode round. There is no seed receipt to draft from here. - Err(Error::Unsupported(Stage::Session)) - } - fn drain_first(&mut self) -> Result<()> { - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn greedy() -> SamplerParams { - crate::qwen_forward::original_serve_config::greedy_params(1) - } - - #[test] - fn a_greedy_request_without_penalties_does_not_enable_the_sampling_head() { - let sampling = RequestSampling::new(greedy(), SamplerPath::Split).unwrap(); - assert!(!sampling.enabled()); - let mut penalized = greedy(); - penalized.penalty_last_n = 64; - assert!(RequestSampling::new(penalized, SamplerPath::Split).unwrap().enabled()); - let mut stochastic = SamplerParams::default(); - stochastic.temperature = 0.7; - stochastic.greedy = false; - assert!(RequestSampling::new(stochastic, SamplerPath::OneBlock).unwrap().enabled()); - } - - #[test] - fn invalid_sampler_parameters_are_refused_before_any_window() { - let mut bad = greedy(); - bad.top_p = 1.5; - assert!(RequestSampling::new(bad, SamplerPath::Split).is_err()); - let mut nan = greedy(); - nan.temperature = f32::NAN; - assert!(RequestSampling::new(nan, SamplerPath::Split).is_err()); - } - - #[test] - fn the_host_outcome_names_the_four_things_the_stack_decides_on() { - let outcome = HostOutcome { failed: false, dirty: true, state_lag: true, position: 9 }; - assert!(outcome.dirty && outcome.state_lag && !outcome.failed); - assert_eq!(outcome.position, 9); - } -} +//! The real owners behind `NativeServePort`: the serving host of the Original verified-window decode. +//! +//! One `OriginalServeHost` lives for one decode phase (one request). It borrows the target session, the +//! MTP draft session, the prompt executor (which owns the MTP actor), the penalty-history stage, the PLE +//! operator source and the routed-expert pool, and it implements every callback the serve port demands: +//! +//! * `validate_current` / `checkpoint_target` / `restore_target` over the committed-lineage ledger; +//! * `run_window`: window PLE rows, the literal penalty-history tail plus request sampling, and the +//! expert pool callback around `Verifier::run`; +//! * `publish_committed`: after the commit event, the twelve resident QSA witnesses are read from the +//! verifier's own journal and the accepted rows are published to the session (position, predecessors, +//! witnesses; the recurrent GDN/PLE state follows at `settle_state`); +//! * `draft_committed`: the literal `MtpDrafter::draft_from_verifier` over the published branch; +//! * `stage_draft_history` / `restore_draft` / `drain_draft` over the MTP actor and the draft session. +//! +//! Nothing here computes a model number or certifies one: it moves the owners' own receipts between each +//! other in the order generate.cpp does, and refuses every receipt that does not match the session. +use super::{ + contract::{Error, Result, Stage}, + dense_weight_cache::DenseWeightCache, + executor::original_prompt::OriginalPromptExecutor, + gdn::GdnPrior, + input::{InputStage, PlePrior}, + kar_ple_cache::KarPleCache, + original_mtp_verified_adapter::{OriginalCommittedMtpReceipt, OriginalLaunchedMtpDraft}, + original_serve_engine::DraftCompletion, + original_serve_ledger::{LedgerCheckpoint, ServeLedger}, + original_serve_native::NativeServeHost, + original_serve_pool::OriginalServePool, + original_serve_profile as profile, + original_serve_verifier::{driver_error, read_ple_history, ServeFailure}, + output_native::OriginalNativePenaltyHistory, + session::{ + original_prompt::draft::{OriginalDraftCheckpoint, OriginalDraftSession}, + QwenSession, TargetStepOrigin, + }, +}; +use crate::model_binding::qwen4exp_input::{BoundLayerKind, ModelBinding}; +use leleka_cuda_driver::{ + Context, DeviceBuffer, NativeHeadSelection, OriginalGpuEvent, OriginalNativeHeadGraphResources, OriginalMtpFullPolicy, + OriginalVerifier, OriginalVerifyGraphResources, OriginalVerifyQsaJournal, OriginalVerifyWindow, + OriginalVerifyWindowResult, SamplerParams, SamplerPath, +}; +use std::rc::Rc; + +/// What the request asked of the sampler: the CPU-reference parameters mapped field for field, the kernel +/// path chosen once from the environment. +#[derive(Clone, Copy, Debug)] +pub(in crate::qwen_forward) struct RequestSampling { + pub(in crate::qwen_forward) params: SamplerParams, + pub(in crate::qwen_forward) path: SamplerPath, +} +impl RequestSampling { + pub(in crate::qwen_forward) fn new(params: SamplerParams, path: SamplerPath) -> Result { + params.validate().map_err(|e| driver_error(&e))?; + Ok(Self { params, path }) + } + /// `req_sampling`: the head samples only when the request is stochastic or penalized; a greedy request + /// without history takes the plain argmax even if the flag is set, so setting it is always safe. + pub(in crate::qwen_forward) fn enabled(&self) -> bool { + !self.params.greedy || self.params.penalty_last_n > 0 + } +} + +/// The ending state of a host: what the stack needs to decide whether the physical owners need a repair +/// and whether the session can serve another request without a reset. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(in crate::qwen_forward) struct HostOutcome { + /// The ledger saw an inconsistency (a failed publication, an unrecoverable restore). + pub(in crate::qwen_forward) failed: bool, + /// A window ran whose physical effects were never published: the QSA owners need their rollback. + pub(in crate::qwen_forward) dirty: bool, + /// The session's recurrent GDN/PLE priors lag its position (see `settle_state`). + pub(in crate::qwen_forward) state_lag: bool, + pub(in crate::qwen_forward) position: u64, +} + +pub(in crate::qwen_forward) struct OriginalServeHost<'a, 'ctx> { + binding: &'a ModelBinding, + dense: &'a DenseWeightCache<'ctx>, + context: &'ctx Context<'ctx>, + session: &'a mut QwenSession<'ctx>, + draft: &'a mut OriginalDraftSession<'ctx>, + executor: &'a mut OriginalPromptExecutor<'ctx>, + kar: Option<&'a mut KarPleCache<'ctx>>, + history: &'a mut OriginalNativePenaltyHistory<'ctx>, + pool: &'a mut dyn OriginalServePool<'ctx>, + /// A second reference to the verifier's QSA journal, only to read the committed mapped prefixes. + qsa: Rc>, + /// Model layer index of journal layer `i`. + slots: [usize; 12], + ple_history: &'a DeviceBuffer<'ctx>, + policy: &'a OriginalMtpFullPolicy, + sampling: RequestSampling, + ledger: ServeLedger, + /// The session origin the last window started from (the draft receipt names it). + window_origin: Option, + /// A draft launched behind the enqueued commit, completed after the publication (`launch_draft`). + launched: Option, + /// The round whose adaptive swaps are still to be planned and queued (`LELEKA_SERVE_ADAPT_DEFER`, default on): the host does that + /// work while the GPU runs the draft instead of before the commit and the draft are enqueued. + deferred_adaptation: Option, +} + +/// Everything a host borrows, in one place so the stack can build it in one expression. +pub(in crate::qwen_forward) struct HostOwners<'a, 'ctx> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) dense: &'a DenseWeightCache<'ctx>, + pub(in crate::qwen_forward) context: &'ctx Context<'ctx>, + pub(in crate::qwen_forward) session: &'a mut QwenSession<'ctx>, + pub(in crate::qwen_forward) draft: &'a mut OriginalDraftSession<'ctx>, + pub(in crate::qwen_forward) executor: &'a mut OriginalPromptExecutor<'ctx>, + pub(in crate::qwen_forward) kar: Option<&'a mut KarPleCache<'ctx>>, + pub(in crate::qwen_forward) history: &'a mut OriginalNativePenaltyHistory<'ctx>, + pub(in crate::qwen_forward) pool: &'a mut dyn OriginalServePool<'ctx>, + pub(in crate::qwen_forward) qsa: Rc>, + pub(in crate::qwen_forward) slots: [usize; 12], + pub(in crate::qwen_forward) ple_history: &'a DeviceBuffer<'ctx>, + pub(in crate::qwen_forward) policy: &'a OriginalMtpFullPolicy, +} + +/// `LELEKA_SERVE_PUBLISH=serial`: the per-layer checkpoint publication (A/B control of the batched one). +fn serial_publish() -> bool { + static SERIAL: std::sync::OnceLock = std::sync::OnceLock::new(); + *SERIAL.get_or_init(|| std::env::var("LELEKA_SERVE_PUBLISH").is_ok_and(|v| v == "serial")) +} + +fn operator_line(what: &str, failure: &ServeFailure) { + use std::io::Write; + // Fixed driver strings and error classes only; never request data. + let _ = writeln!(std::io::stderr().lock(), "leleka-serve {what}: {}", failure.describe()); +} + +impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { + /// `committed` is the token sequence the session holds (the prompt without its last token); `limit` is + /// the last position a state may end at. The session must stand exactly there, in step. + pub(in crate::qwen_forward) fn new( + owners: HostOwners<'a, 'ctx>, + committed: Vec, + limit: u64, + sampling: RequestSampling, + ) -> Result { + let HostOwners { binding, dense, context, session, draft, executor, kar, history, pool, qsa, slots, ple_history, policy } = + owners; + let position = session.target_origin()?.next_position(); + if session.original_state_lag().is_some() + || committed.len() as u64 != position + || !std::ptr::eq(context, session.mtp_context()?) + || binding.kar_ple_binding().is_some() != kar.is_some() + { + return Err(Error::IdentityMismatch); + } + let ledger = ServeLedger::new(committed, limit)?; + Ok(Self { + binding, + dense, + context, + session, + draft, + executor, + kar, + history, + pool, + qsa, + slots, + ple_history, + policy, + sampling, + ledger, + window_origin: None, + launched: None, + deferred_adaptation: None, + }) + } + + fn position(&self) -> Result { + Ok(self.session.target_origin()?.next_position()) + } + + /// The session's recurrent GDN and PLE priors, brought to its position from the verifier's canonical + /// image (one device-to-host transfer per request). Not needed for a request that is followed by a + /// reset; required before the session is checkpointed or reused as a resume source. + pub(in crate::qwen_forward) fn settle_state(&mut self, verifier: &mut OriginalVerifier<'ctx, R>) -> Result<()> + where + R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, + { + let Some(from) = self.session.original_state_lag() else { return Ok(()) }; + let position = self.position()?; + let rows = usize::try_from(position.checked_sub(from).ok_or(Error::InvalidPosition)?).map_err(|_| Error::Overflow)?; + let base = self.session.original_verified_base()?; + let mut gdn: [Option; 48] = std::array::from_fn(|_| None); + let mut ordinal = 0usize; + for layer in self.binding.ordered_layers() { + if layer.kind() != BoundLayerKind::Gdn { + continue; + } + let slot = layer.index() as usize; + let prior = base.gdn[slot].as_ref().ok_or(Error::IdentityMismatch)?; + let (values, history) = verifier + .with_committed_gdn(ordinal, |values, history| { + let mut v = Vec::new(); + v.try_reserve_exact(values.len()).map_err(|_| leleka_cuda_driver::Error::HostAllocation)?; + v.extend_from_slice(values); + let mut h = Vec::new(); + h.try_reserve_exact(history.len()).map_err(|_| leleka_cuda_driver::Error::HostAllocation)?; + h.extend_from_slice(history); + Ok((v.into_boxed_slice(), h.into_boxed_slice())) + }) + .map_err(|e| driver_error(&e))?; + gdn[slot] = Some(GdnPrior::from_original_verified(prior, rows, values, history)?); + ordinal += 1; + } + if ordinal != 36 { + return Err(Error::IdentityMismatch); + } + let ple = match base.ple.as_ref() { + Some(prior) => Some(PlePrior::from_original_verified(prior, rows, read_ple_history(self.ple_history)?)?), + None => None, + }; + self.session.publish_original_resident_state(gdn, ple) + } + + /// The tokens the session holds (the prompt without its last token, then every committed window input): + /// generate.cpp's `consumed`, what a continuing request must start with. + pub(in crate::qwen_forward) fn committed(&self) -> &[i32] { + self.ledger.committed() + } + + /// Whether the MTP draft ring stands at the session's position, so the next request could continue from + /// the session as is. False after a request that stopped on EOS/length: generate.cpp skips the draft of + /// the last window, so the ring never received that window's cells. + pub(in crate::qwen_forward) fn draft_in_step(&self) -> bool { + !self.ledger.is_failed() && !self.ledger.is_dirty() && self.draft.in_step(self.binding, self.session) + } + + /// The end of the decode phase: nothing is borrowed from the owners any more except through the + /// returned outcome. The caller drops the host (releasing its journal reference) before it closes the + /// verifier and takes the QSA owners back. + pub(in crate::qwen_forward) fn finish(self) -> HostOutcome { + let position = self.session.target_origin().map(|o| o.next_position()).unwrap_or(0); + HostOutcome { + failed: self.ledger.is_failed(), + dirty: self.ledger.is_dirty(), + state_lag: self.session.original_state_lag().is_some(), + position, + } + } +} + +/// `LELEKA_SERVE_ADAPT_DEFER=off`: plan and queue the adaptive swaps before the commit (the earlier order; the A/B control). +fn adapt_defer() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("LELEKA_SERVE_ADAPT_DEFER").is_ok_and(|v| v == "off" || v == "0")) +} + +impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { + /// The MTP actor drafts as many chain steps as it is configured for (`set_max_drafts`); an adaptive round's plan is + /// applied here (the engine has already bounded it by the request's cap). Equal values cost one comparison. + fn apply_draft_cap(&mut self, max_drafts: usize) -> Result<()> { + let want = i32::try_from(max_drafts).map_err(|_| Error::Overflow)?; + let actor = self.executor.mtp_actor(self.binding)?; + if actor.settings().max_drafts() != want { + actor.set_max_drafts(want); + } + Ok(()) + } +} + +impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { + type TargetCheckpoint = LedgerCheckpoint; + type DraftCheckpoint = OriginalDraftCheckpoint; + type Adaptive = (); + type Seed = (); + + fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()> { + self.ledger.validate_current(consumed, input, position, self.position()?) + } + fn checkpoint_target(&self) -> Result { + self.ledger.checkpoint(self.position()?) + } + fn checkpoint_draft(&self) -> Result { + self.draft.checkpoint(self.binding, self.session) + } + fn restore_target(&mut self, checkpoint: &LedgerCheckpoint) -> Result<()> { + // An unpublished window never touched the session; its physical effects are rolled back when the + // phase ends. A commit that was enqueued cannot be undone and poisons the ledger. + self.window_origin = None; + let position = self.position()?; + self.ledger.restore(checkpoint, position) + } + fn restore_draft(&mut self, checkpoint: &OriginalDraftCheckpoint) -> Result<()> { + self.draft.restore_current(self.binding, self.dense, self.session, checkpoint) + } + fn apply_pending(&mut self) -> Result<()> { + // generate.cpp `apply_pending(false)`: completed adaptive swaps become resident (no work for the + // all-CPU tier). + self.pool.apply_pending() + } + + fn run_window( + &mut self, + verifier: &mut OriginalVerifier<'ctx, R>, + position: i64, + inputs: &[i32], + consumed: &[i32], + ) -> Result + where + R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, + { + let window_clock = super::original_serve_pool::window_trace::now(); + let _ = super::original_serve_pool::window_trace::take(); + let session_position = self.position()?; + self.ledger.begin_window(position, inputs, consumed, session_position)?; + let first = usize::try_from(position).map_err(|_| Error::InvalidPosition)?; + let origin = self.session.target_origin()?; + let ple_span = profile::span("window.ple"); + let ple = if self.session.original_ple_required() { + let predecessors = self.session.original_predecessors()?; + Some(InputStage::original_window_ple(self.binding, self.kar.as_deref_mut(), self.context, predecessors, inputs)?) + } else { + None + }; + let ple_ms = window_clock.map(|c| c.elapsed().as_secs_f64() * 1e3); + let mut verifier_ms = 0.0f64; + drop(ple_span); + let mut history_span = profile::span("window.history"); + let (params, path, enabled) = (self.sampling.params, self.sampling.path, self.sampling.enabled()); + let mut pool_error: Option = None; + let mut driver_failure: Option = None; + let Self { binding, session, history, pool, ledger, .. } = &mut *self; + let committed = ledger.committed(); + let result = history.with_sampling( + binding, + &**session, + &origin, + consumed, + inputs, + params, + path, + enabled, + || if committed == consumed { Ok(()) } else { Err(Error::IdentityMismatch) }, + |sampling| { + history_span.stop(); + let _p = profile::span("window.verifier"); + let verifier_clock = super::original_serve_pool::window_trace::now(); + let ran = verifier + .run(inputs, first, ple.as_deref(), sampling, |rows, sink, copy| { + let group_clock = super::original_serve_pool::window_trace::now(); + let ran = pool.run_group(rows, sink, copy).map_err(|error| { + pool_error = Some(error); + leleka_cuda_driver::Error::InvalidDriverValue("Original serve expert pool refused a layer group") + }); + if let Some(c) = group_clock { + super::original_serve_pool::window_trace::add(super::original_serve_pool::window_trace::POOL, c.elapsed().as_secs_f64() * 1e3); + } + ran + }); + if let Some(c) = verifier_clock { + verifier_ms = c.elapsed().as_secs_f64() * 1e3; + } + ran + .map_err(|error| { + let failure = ServeFailure::from(error); + let class = failure.error; + driver_failure = Some(failure); + class + }) + }, + ); + if let (Some(c), Some(ple_ms)) = (window_clock, ple_ms) { + let total = c.elapsed().as_secs_f64() * 1e3; + let sums = super::original_serve_pool::window_trace::take(); + let parts: Vec = super::original_serve_pool::window_trace::NAMES + .iter() + .zip(sums) + .map(|(name, v)| format!("{name}={v:.2}")) + .collect(); + eprintln!( + "DBG window rows={} total={total:.2} ple={ple_ms:.2} sampling_setup={:.2} verifier={verifier_ms:.2} gpu_wait_and_head={:.2} {}", + inputs.len(), + total - ple_ms - verifier_ms, + verifier_ms - sums[super::original_serve_pool::window_trace::POOL], + parts.join(" ") + ); + } + match result { + Ok(window) => { + self.window_origin = Some(origin); + Ok(window) + } + Err(error) => { + if let Some(failure) = driver_failure.as_ref() { + operator_line("window", failure); + } + // A pool refusal is the cause; the driver error it provoked is its echo. + Err(pool_error.unwrap_or(error)) + } + } + } + + fn commit_enqueued(&mut self, keep: usize) -> Result<()> { + self.ledger.commit_enqueued(keep) + } + + fn publish_committed(&mut self, verifier: &mut OriginalVerifier<'ctx, R>, position: i64, committed: &[i32]) -> Result<()> + where + R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, + { + let p = profile::span("publish.witnesses"); + let origin_after = self.session.original_origin_after(committed.len())?; + let witnesses = self.session.original_qsa_witnesses()?; + drop(p); + let mut next: [Option<_>; 48] = std::array::from_fn(|_| None); + { + let p = profile::span("publish.workspace"); + let mut workspace = self.dense.native_batch_workspace(self.binding, self.context)?.ok_or(Error::IdentityMismatch)?; + drop(p); + // The twelve index checkpoints in one batch after the commit event (one stream drain, pooled buffers), + // or one by one with a context synchronize each (LELEKA_SERVE_PUBLISH=serial, the earlier path). + let p = profile::span("publish.index_checkpoint"); + let mut batched = if serial_publish() { + None + } else { + Some(verifier.checkpoint_committed_qsa_all(&mut workspace).map_err(|e| driver_error(&e))?.map(Some)) + }; + drop(p); + for (journal_layer, &slot) in self.slots.iter().enumerate() { + let prior = witnesses[slot].as_ref().ok_or(Error::IdentityMismatch)?; + let p = profile::span("publish.index_checkpoint"); + let index = match batched.as_mut() { + Some(all) => all[journal_layer].take().ok_or(Error::IdentityMismatch)?, + None => verifier + .with_committed_qsa(journal_layer, |index| index.checkpoint(&mut workspace)) + .map_err(|e| driver_error(&e))?, + }; + drop(p); + let p = profile::span("publish.kv_prefix"); + let kv = self.qsa.committed_mapped_prefix(journal_layer).map_err(|e| driver_error(&e))?; + drop(p); + next[slot] = Some(prior.advanced(origin_after.clone(), index, kv)?); + } + } + let p = profile::span("publish.session"); + if serial_publish() { + self.session.publish_original_verified_rows(committed, self.ledger.limit(), next)?; + } else { + // fenced: the commit event was waited and the batched witness checkpoints drained above + self.session.publish_original_verified_rows_fenced(committed, self.ledger.limit(), next)?; + } + drop(p); + self.ledger.published(position, committed) + } + + fn begin_adaptation(&mut self, next_round: u64) -> Result<()> { + // generate.cpp `adapt()` when `(rounds + 1) % adapt_every == 0`, issued before the commit; its copies + // run on the tier's own stream beside the commit and the draft (no work for the all-CPU tier). + // The planning and the queueing are host work (0.6 ms on an adaptation round) that sat between the window and the commit/draft + // launch; with the deferral they run once the draft is launched (`run_deferred_adaptation`) or, at the latest, at the join, + // always before the next round's `apply_pending`. LELEKA_SERVE_ADAPT_DEFER=off runs them here as before. + if adapt_defer() { + if self.deferred_adaptation.is_some() { + return Err(Error::IdentityMismatch); + } + self.deferred_adaptation = Some(next_round); + return Ok(()); + } + self.pool.begin_adaptation(next_round) + } + fn run_deferred_adaptation(&mut self) -> Result<()> { + match self.deferred_adaptation.take() { + Some(round) => self.pool.begin_adaptation(round), + None => Ok(()), + } + } + fn join_adaptation(&mut self, _work: ()) -> Result<()> { + self.run_deferred_adaptation() + } + fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()> { + self.executor.set_mtp_draft_history(self.binding, consumed, next) + } + + fn draft_committed( + &mut self, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + position: i64, + accepted_row: usize, + max_drafts: usize, + min_p: f32, + _coupled: bool, + ) -> Result { + let before = self.window_origin.take().ok_or(Error::IdentityMismatch)?; + let first = u64::try_from(position).map_err(|_| Error::InvalidPosition)?; + if before.next_position() != first { + return Err(Error::IdentityMismatch); + } + // The actor drafts the chain length it is configured with: the request's cap, or the adaptive window's plan for this round. + self.apply_draft_cap(max_drafts)?; + let p = profile::span("draft.receipt"); + let receipt = OriginalCommittedMtpReceipt::for_published_window( + self.binding, + self.session, + self.context, + window, + selection, + before, + accepted_row, + )?; + drop(p); + let _p = profile::span("draft.drafter"); + let drafted = self.executor.draft_committed_mtp(self.binding, self.session, self.draft, receipt, min_p, self.policy)?; + let first_cell = i64::try_from(drafted.first_position()).map_err(|_| Error::Overflow)? + + i64::try_from(drafted.accepted_row()).map_err(|_| Error::Overflow)?; + Ok(DraftCompletion { + ids: drafted.ids().to_vec(), + probabilities: drafted.probabilities().to_vec(), + first_cell, + accepted_row: drafted.accepted_row(), + }) + } + fn launch_draft( + &mut self, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + position: i64, + accepted_row: usize, + max_drafts: usize, + min_p: f32, + after: Option<&mut OriginalGpuEvent<'ctx>>, + ) -> Result<()> { + if self.launched.is_some() { + return Err(Error::IdentityMismatch); + } + let before = self.window_origin.take().ok_or(Error::IdentityMismatch)?; + let first = u64::try_from(position).map_err(|_| Error::InvalidPosition)?; + if before.next_position() != first { + return Err(Error::IdentityMismatch); + } + // The actor drafts the chain length it is configured with: the request's cap, or the adaptive window's plan for this round. + self.apply_draft_cap(max_drafts)?; + let launched = self.executor.launch_committing_mtp( + self.binding, + self.session, + self.draft, + window, + selection, + before, + accepted_row, + min_p, + self.policy, + after, + )?; + self.launched = Some(launched); + Ok(()) + } + fn finish_draft(&mut self) -> Result { + let launched = self.launched.take().ok_or(Error::IdentityMismatch)?; + let drafted = self.executor.finish_committing_mtp(self.binding, self.session, self.draft, launched, self.policy)?; + let first_cell = i64::try_from(drafted.first_position()).map_err(|_| Error::Overflow)? + + i64::try_from(drafted.accepted_row()).map_err(|_| Error::Overflow)?; + Ok(DraftCompletion { + ids: drafted.ids().to_vec(), + probabilities: drafted.probabilities().to_vec(), + first_cell, + accepted_row: drafted.accepted_row(), + }) + } + fn drain_draft(&mut self) -> Result<()> { + self.executor.mtp_idle(self.binding) + } + fn draft_first( + &mut self, + _seed: &(), + _t: usize, + _cell: i64, + _token: i32, + _max_drafts: usize, + _min_p: f32, + _coupled: bool, + ) -> Result { + // generate.cpp calls `draft_first` only on the CLI's first window; the serve loop drafts from the + // verifier window of the first decode round. There is no seed receipt to draft from here. + Err(Error::Unsupported(Stage::Session)) + } + fn drain_first(&mut self) -> Result<()> { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn greedy() -> SamplerParams { + crate::qwen_forward::original_serve_config::greedy_params(1) + } + + #[test] + fn a_greedy_request_without_penalties_does_not_enable_the_sampling_head() { + let sampling = RequestSampling::new(greedy(), SamplerPath::Split).unwrap(); + assert!(!sampling.enabled()); + let mut penalized = greedy(); + penalized.penalty_last_n = 64; + assert!(RequestSampling::new(penalized, SamplerPath::Split).unwrap().enabled()); + let mut stochastic = SamplerParams::default(); + stochastic.temperature = 0.7; + stochastic.greedy = false; + assert!(RequestSampling::new(stochastic, SamplerPath::OneBlock).unwrap().enabled()); + } + + #[test] + fn invalid_sampler_parameters_are_refused_before_any_window() { + let mut bad = greedy(); + bad.top_p = 1.5; + assert!(RequestSampling::new(bad, SamplerPath::Split).is_err()); + let mut nan = greedy(); + nan.temperature = f32::NAN; + assert!(RequestSampling::new(nan, SamplerPath::Split).is_err()); + } + + #[test] + fn the_host_outcome_names_the_four_things_the_stack_decides_on() { + let outcome = HostOutcome { failed: false, dirty: true, state_lag: true, position: 9 }; + assert!(outcome.dirty && outcome.state_lag && !outcome.failed); + assert_eq!(outcome.position, 9); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_native.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_native.rs index 98bd95b3..f9c144df 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_native.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_native.rs @@ -1,283 +1,283 @@ -//! Native binding of `OriginalServePort` to the genuine driver Verifier. -//! -//! The Verifier itself (`OriginalVerifier::run/commit/wait_commit/completed_window`) -//! is bound here directly: windows are only the receipts of a genuinely completed -//! `run`, the commit is the driver's asynchronous event commit, and the accepted -//! prefix is cross-checked against the driver's own staged commit tokens before the -//! session lineage is published. Everything that needs owners that do not exist as -//! typed runtime objects yet is demanded from a `NativeServeHost` implementation -//! (PLE rows, request penalty history/sampler, the CPU expert pool and PCIe plan -//! callbacks, target/draft lineage checkpoints, the MTP ring and drafter, and the -//! verified-window session publication; see `original_serve_host.rs`). Nothing here fabricates one of them. -use super::contract::{Error,Result}; -use super::original_serve_profile as profile; -use super::original_serve_engine::{DraftCompletion,OriginalServePort}; -use leleka_cuda_driver::{NativeHeadSelection,OriginalGpuEvent,OriginalNativeHeadGraphResources,OriginalVerifier, - OriginalVerifyGraphResources,OriginalVerifyWindow,OriginalVerifyWindowResult}; -use std::cell::RefCell; - -/// What the serving owner must supply for the verified-window serve path. -pub(in crate::qwen_forward) trait NativeServeHost<'ctx> { - type TargetCheckpoint; - type DraftCheckpoint; - type Adaptive; - type Seed; - fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()>; - fn checkpoint_target(&self)->Result; - fn checkpoint_draft(&self)->Result; - fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()>; - fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()>; - fn apply_pending(&mut self)->Result<()>; - /// Stage literal per-row penalty histories (counter = cell), the PLE rows and the CPU - /// pool/PCIe callbacks, and call `verifier.run` on the authenticated window. - fn run_window+OriginalNativeHeadGraphResources<'ctx>>( - &mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,inputs:&[i32],consumed:&[i32], - )->Result; - /// The driver commit for `keep` rows is about to be enqueued (called BEFORE `verifier.commit`, so - /// that an uncertain enqueue is already on the books as a commit that may have changed the verifier). - fn commit_enqueued(&mut self,keep:usize)->Result<()>; - /// Publish the accepted prefix (target position, predecessors and QSA witnesses; the recurrent - /// GDN/PLE state follows lazily) AFTER the driver commit event completed. `committed` are the - /// accepted input tokens exactly as the driver staged them. - fn publish_committed+OriginalNativeHeadGraphResources<'ctx>>( - &mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,committed:&[i32], - )->Result<()>; - fn begin_adaptation(&mut self,next_round:u64)->Result; - /// Adaptive work a host deferred at `begin_adaptation`: run it now (the draft is launched, the GPU is busy). A host that does its work - /// at `begin_adaptation` has nothing to run. `join_adaptation` must run whatever is still deferred. - fn run_deferred_adaptation(&mut self)->Result<()> {Ok(())} - fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()>; - fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()>; - /// Literal `OriginalMtpDrafter::draft_from_verifier` over the same ring/snapshot lineage. - #[allow(clippy::too_many_arguments)] - fn draft_committed(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64, - accepted_row:usize,max_drafts:usize,min_p:f32,coupled:bool)->Result; - /// `draft_committed` in generate.cpp's order: launched while the commit is enqueued and NOT yet published (the - /// draft stream waits `after`, the commit event, on the device), BEFORE `publish_committed`... - #[allow(clippy::too_many_arguments)] - fn launch_draft(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64, - accepted_row:usize,max_drafts:usize,min_p:f32,after:Option<&mut OriginalGpuEvent<'ctx>>)->Result<()>; - /// ...and completed AFTER it, over the published branch. - fn finish_draft(&mut self)->Result; - fn drain_draft(&mut self)->Result<()>; - #[allow(clippy::too_many_arguments)] - fn draft_first(&mut self,seed:&Self::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result; - fn drain_first(&mut self)->Result<()>; -} - -/// Receipt of one completed driver window. The head selection is single-use: the -/// draft consumes it exactly once, mirroring `draft_from_verifier`'s by-value argument. -pub(in crate::qwen_forward) struct NativeWindow { - generation:u64,position:i64,rows:usize,ids:Vec,inputs:Vec, - selection:RefCell>,keep:Option, -} -impl NativeWindow { - pub(in crate::qwen_forward) fn generation(&self)->u64 {self.generation} -} - -pub(in crate::qwen_forward) struct NativeServePort<'ctx,R,H> -where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { - verifier:OriginalVerifier<'ctx,R>,host:H,pending_publish:Option<(i64,Vec)>,failed:bool, -} -impl<'ctx,R,H> NativeServePort<'ctx,R,H> -where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { - pub(in crate::qwen_forward) fn new(verifier:OriginalVerifier<'ctx,R>,host:H)->Self { - Self{verifier,host,pending_publish:None,failed:false} - } - pub(in crate::qwen_forward) fn verifier(&self)->&OriginalVerifier<'ctx,R> {&self.verifier} - pub(in crate::qwen_forward) fn verifier_mut(&mut self)->&mut OriginalVerifier<'ctx,R> {&mut self.verifier} - pub(in crate::qwen_forward) fn host(&self)->&H {&self.host} - pub(in crate::qwen_forward) fn into_parts(self)->(OriginalVerifier<'ctx,R>,H) {(self.verifier,self.host)} - fn live(&self)->Result<()> {if self.failed {Err(Error::IdentityMismatch)} else {Ok(())}} - /// Wait the driver commit event and publish the accepted prefix to the session. Idempotent: with - /// nothing outstanding on our side the driver event must agree. The draft needs the PUBLISHED target - /// branch, so `draft_committed` settles through here too (the engine's later settle is then a no-op). - fn settle_commit(&mut self)->Result<()> { - let Some((position,expected))=self.pending_publish.take() else { - return match self.verifier.wait_commit() {Ok(())=>Ok(()),Err(_)=>{self.failed=true;Err(Error::CudaExecution)}}; - }; - let waited={let _p=profile::span("commit.wait");self.verifier.wait_commit()}; - if waited.is_err() {self.failed=true;return Err(Error::CudaExecution);} - // The driver staged the commit tokens itself; they must be exactly the accepted prefix. - let staged=match self.verifier.accepted_tokens() {Ok(t)=>t.to_vec(),Err(_)=>{self.failed=true;return Err(Error::CudaExecution);}}; - if staged!=expected {self.failed=true;return Err(Error::IdentityMismatch);} - let _p=profile::span("commit.publish"); - let published=self.host.publish_committed(&mut self.verifier,position,&expected); - if published.is_err() {self.failed=true;}published - } -} - -/// The two bring-up window traces, read once (they sat on the per-window path). -fn trace_logprobs()->Option { - static TOPK:std::sync::OnceLock>=std::sync::OnceLock::new(); - *TOPK.get_or_init(||std::env::var("LELEKA_TRACE_LOGPROBS").ok().and_then(|v|v.parse::().ok()).filter(|k|*k>0)) -} -fn trace_residual()->Option<&'static std::ffi::OsString> { - static DIR:std::sync::OnceLock>=std::sync::OnceLock::new(); - DIR.get_or_init(||std::env::var_os("LELEKA_TRACE_RESIDUAL")).as_ref() -} - -/// `LELEKA_SERVE_OVERLAP=off`: settle the commit (wait + publish) before the draft launches (the earlier, serialized -/// order; A/B control). Default: generate.cpp's order, the draft enqueued behind the commit event. -fn overlap()->bool { - static ON:std::sync::OnceLock=std::sync::OnceLock::new(); - *ON.get_or_init(||!std::env::var("LELEKA_SERVE_OVERLAP").is_ok_and(|v|v=="off"||v=="0")) -} - -impl<'ctx,R,H> OriginalServePort for NativeServePort<'ctx,R,H> -where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { - type Window=NativeWindow; - type Seed=H::Seed; - type TargetCheckpoint=H::TargetCheckpoint; - type DraftCheckpoint=H::DraftCheckpoint; - type Adaptive=H::Adaptive; - fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> { - self.live()?;self.host.validate_current(consumed,input,position) - } - fn checkpoint_target(&self)->Result {self.live()?;self.host.checkpoint_target()} - fn checkpoint_draft(&self)->Result {self.live()?;self.host.checkpoint_draft()} - fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()> { - // Whatever was in flight is dead: the window state is discarded by the driver (the - // uncommitted window never touched GDN state, and a committed one is fenced first). - self.pending_publish=None; - let restored=self.host.restore_target(checkpoint); - if restored.is_err() {self.failed=true;}restored - } - fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()> { - let restored=self.host.restore_draft(checkpoint); - if restored.is_err() {self.failed=true;}restored - } - fn apply_pending(&mut self)->Result<()> {self.live()?;let _p=profile::span("round.apply_pending");self.host.apply_pending()} - fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { - self.live()?; - let first=usize::try_from(position).map_err(|_|Error::InvalidPosition)?; - let result={let _p=profile::span("round.run_window");self.host.run_window(&mut self.verifier,position,inputs,consumed)?}; - // The driver's own receipt is authoritative: it must describe exactly this window. - let t=inputs.len(); - let ok=result.rows==t&&result.first_position==first&&result.selection.ids().len()==t - &&result.selection.position()==position as u64; - if !ok {self.failed=true;return Err(Error::IdentityMismatch);} - let mut ids=result.selection.ids().to_vec(); - // Quality gate only (an installed `quality_force` sequence; nothing installs one in production): the picks - // the controller verifies drafts against and commits next are the forced text's tokens. - let forced_differ=super::quality_force::apply(position,&mut ids); - if forced_differ>0 {crate::bringup_trace!("DBG forced window position={position} picks_replaced={forced_differ}");} - // Bring-up diagnostic (LELEKA_TRACE_LOGPROBS=): top-k head logprobs of every row of the completed window. - if let Some(k)=trace_logprobs() { - let mut line:Vec=Vec::new(); - crate::bringup_trace!("DBG logprobs window position={position} inputs={inputs:?} argmax_ids={ids:?}"); - match self.verifier.window_logprobs_topk(&ids,-1,k,&mut line) { - Ok(())=>eprintln!("{}",String::from_utf8_lossy(&line).trim_end()), - Err(e)=>crate::bringup_trace!("DBG logprobs err {e:?}"), - } - } - // Bring-up diagnostic (LELEKA_TRACE_RESIDUAL=): the final residual R of every row of the completed window, - // raw little-endian f32 (rows, hc*n_embd), file `r_win_pos.f32`. - if let Some(dir)=trace_residual() { - match self.verifier.window_residual_rows() { - Ok((rows,start,values))=>{ - let bytes:Vec=values.iter().flat_map(|v|v.to_le_bytes()).collect(); - static WINDOW_SEQ:std::sync::atomic::AtomicUsize=std::sync::atomic::AtomicUsize::new(0); - let seq=WINDOW_SEQ.fetch_add(1,std::sync::atomic::Ordering::Relaxed); - let path=std::path::Path::new(&dir).join(format!("r_win{seq:05}_pos{start}.f32")); - eprintln!("DBG residual window seq={seq} first={start} rows={rows} inputs={inputs:?} floats={} -> {}",values.len(),path.display()); - if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG residual write err {e:?}"); } - if let Ok(Some(ladder))=self.verifier.window_ladder_rows() { - let bytes:Vec=ladder.iter().flat_map(|v|v.to_le_bytes()).collect(); - let path=std::path::Path::new(&dir).join(format!("l_win{seq:05}_pos{start}.f32")); - if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG ladder write err {e:?}"); } - } - } - Err(e)=>eprintln!("DBG residual err {e:?}"), - } - } - Ok(NativeWindow{generation:result.generation,position,rows:t,ids,inputs:inputs.to_vec(), - selection:RefCell::new(Some(result.selection)),keep:None}) - } - fn validate_window(&self,window:&NativeWindow,position:i64,inputs:&[i32])->Result<()> { - self.live()?; - if window.position!=position||window.inputs!=inputs {return Err(Error::IdentityMismatch);} - // A capture-only or already-superseded window cannot pass: the driver mints - // `completed_window` only for the genuinely completed current generation. - let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch)?; - if completed.generation()!=window.generation||completed.rows()!=window.rows - ||completed.first_position()!=usize::try_from(position).map_err(|_|Error::InvalidPosition)? { - return Err(Error::IdentityMismatch); - } - if let Some(selection)=window.selection.borrow().as_ref() { - completed.validate_selection(selection).map_err(|_|Error::IdentityMismatch)?; - } - Ok(()) - } - fn window_outputs<'a>(&self,window:&'a NativeWindow)->&'a[i32] {&window.ids} - fn commit_window(&mut self,window:&mut NativeWindow,keep:usize)->Result<()> { - self.live()?; - if keep==0||keep>window.rows||window.keep.is_some()||self.pending_publish.is_some() {return Err(Error::IdentityMismatch);} - let _p=profile::span("round.commit"); - if let Err(e)=self.host.commit_enqueued(keep) {self.failed=true;return Err(e);} - if let Err(_e)=self.verifier.commit(keep,true) {self.failed=true;return Err(Error::CudaExecution);} - window.keep=Some(keep); - self.pending_publish=Some((window.position,window.inputs[..keep].to_vec()));Ok(()) - } - fn wait_commit(&mut self)->Result<()> {self.settle_commit()} - fn drain_window(&mut self,_window:NativeWindow)->Result<()> { - // The retained residuals belong to the driver bank; they stay alive until the next - // window (the bank, not this receipt, owns them), so draining releases only the receipt. - Ok(()) - } - fn discard_window(&mut self)->Result<()> { - // an enqueued commit cannot be undone; the controller restores the checkpoints first (which clears `pending_publish`) - if self.pending_publish.is_some() {self.failed=true;return Err(Error::IdentityMismatch);} - let _p=profile::span("round.discard_window"); - if let Err(e)=self.verifier.discard_window() { - eprintln!("leleka-serve nan-guard: the verifier could not take the refused window back ({e:?})"); - self.failed=true;return Err(super::original_serve_verifier::driver_error(&e)); - } - Ok(()) - } - fn begin_adaptation(&mut self,next_round:u64)->Result {self.live()?;let _p=profile::span("round.adapt");self.host.begin_adaptation(next_round)} - fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()> {self.host.join_adaptation(work)} - fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()> {self.live()?;self.host.stage_draft_history(consumed,next)} - fn draft_committed(&mut self,window:&NativeWindow,position:i64,accepted_row:usize,outputs:&[i32], - max_drafts:usize,min_p:f32,coupled:bool)->Result { - self.live()?; - let _p=profile::span("round.draft_committed"); - // Literal order: commit enqueued first, draft depends on its event on the same stream. - if window.keep!=Some(accepted_row+1)||window.position!=position||outputs!=window.ids.as_slice() { - return Err(Error::IdentityMismatch); - } - if overlap() && self.pending_publish.is_some() { - // generate.cpp: commit -> draft on one stream, the host waits only for the draft's tokens. The draft is - // enqueued behind the commit event; the session is published (commit wait, witnesses) while it runs, and - // the draft completes only over that published branch. - let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch); - let selection=window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch); - let (completed,selection)=match (completed,selection) {(Ok(c),Ok(s))=>(c,s),(Err(e),_)|(_,Err(e))=>return Err(e)}; - let launched={let _p=profile::span("draft.launch"); - self.host.launch_draft(completed,selection,position,accepted_row,max_drafts,min_p,self.verifier.pending_commit_event())}; - if let Err(e)=launched {self.failed=true;return Err(e);} - // the GPU is on the draft now: the adaptive planning/queueing the host deferred runs in its shadow - if let Err(e)={let _p=profile::span("round.adapt_deferred");self.host.run_deferred_adaptation()} {self.failed=true;return Err(e);} - self.settle_commit()?; - let finished={let _p=profile::span("draft.finish");self.host.finish_draft()}; - if finished.is_err() {self.failed=true;} - return finished; - } - // Serialized: the MTP receipt names the PUBLISHED branch, the commit event completes and the session is - // published before the draft launches. - self.settle_commit()?; - let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch); - let selection=window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch); - let (completed,selection)=match (completed,selection) {(Ok(c),Ok(s))=>(c,s),(Err(e),_)|(_,Err(e))=>return Err(e)}; - let draft={let _p=profile::span("draft.mtp");self.host.draft_committed(completed,selection,position,accepted_row,max_drafts,min_p,coupled)}; - if draft.is_err() {self.failed=true;}draft - } - fn drain_draft(&mut self)->Result<()> { - let drained=self.host.drain_draft(); - if drained.is_err() {self.failed=true;}drained - } - fn draft_first(&mut self,seed:&H::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result { - self.live()?;self.host.draft_first(seed,t,cell,token,max_drafts,min_p,coupled) - } - fn drain_first(&mut self)->Result<()> {self.host.drain_first()} -} +//! Native binding of `OriginalServePort` to the genuine driver Verifier. +//! +//! The Verifier itself (`OriginalVerifier::run/commit/wait_commit/completed_window`) +//! is bound here directly: windows are only the receipts of a genuinely completed +//! `run`, the commit is the driver's asynchronous event commit, and the accepted +//! prefix is cross-checked against the driver's own staged commit tokens before the +//! session lineage is published. Everything that needs owners that do not exist as +//! typed runtime objects yet is demanded from a `NativeServeHost` implementation +//! (PLE rows, request penalty history/sampler, the CPU expert pool and PCIe plan +//! callbacks, target/draft lineage checkpoints, the MTP ring and drafter, and the +//! verified-window session publication; see `original_serve_host.rs`). Nothing here fabricates one of them. +use super::contract::{Error,Result}; +use super::original_serve_profile as profile; +use super::original_serve_engine::{DraftCompletion,OriginalServePort}; +use leleka_cuda_driver::{NativeHeadSelection,OriginalGpuEvent,OriginalNativeHeadGraphResources,OriginalVerifier, + OriginalVerifyGraphResources,OriginalVerifyWindow,OriginalVerifyWindowResult}; +use std::cell::RefCell; + +/// What the serving owner must supply for the verified-window serve path. +pub(in crate::qwen_forward) trait NativeServeHost<'ctx> { + type TargetCheckpoint; + type DraftCheckpoint; + type Adaptive; + type Seed; + fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()>; + fn checkpoint_target(&self)->Result; + fn checkpoint_draft(&self)->Result; + fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()>; + fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()>; + fn apply_pending(&mut self)->Result<()>; + /// Stage literal per-row penalty histories (counter = cell), the PLE rows and the CPU + /// pool/PCIe callbacks, and call `verifier.run` on the authenticated window. + fn run_window+OriginalNativeHeadGraphResources<'ctx>>( + &mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,inputs:&[i32],consumed:&[i32], + )->Result; + /// The driver commit for `keep` rows is about to be enqueued (called BEFORE `verifier.commit`, so + /// that an uncertain enqueue is already on the books as a commit that may have changed the verifier). + fn commit_enqueued(&mut self,keep:usize)->Result<()>; + /// Publish the accepted prefix (target position, predecessors and QSA witnesses; the recurrent + /// GDN/PLE state follows lazily) AFTER the driver commit event completed. `committed` are the + /// accepted input tokens exactly as the driver staged them. + fn publish_committed+OriginalNativeHeadGraphResources<'ctx>>( + &mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,committed:&[i32], + )->Result<()>; + fn begin_adaptation(&mut self,next_round:u64)->Result; + /// Adaptive work a host deferred at `begin_adaptation`: run it now (the draft is launched, the GPU is busy). A host that does its work + /// at `begin_adaptation` has nothing to run. `join_adaptation` must run whatever is still deferred. + fn run_deferred_adaptation(&mut self)->Result<()> {Ok(())} + fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()>; + fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()>; + /// Literal `OriginalMtpDrafter::draft_from_verifier` over the same ring/snapshot lineage. + #[allow(clippy::too_many_arguments)] + fn draft_committed(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64, + accepted_row:usize,max_drafts:usize,min_p:f32,coupled:bool)->Result; + /// `draft_committed` in generate.cpp's order: launched while the commit is enqueued and NOT yet published (the + /// draft stream waits `after`, the commit event, on the device), BEFORE `publish_committed`... + #[allow(clippy::too_many_arguments)] + fn launch_draft(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64, + accepted_row:usize,max_drafts:usize,min_p:f32,after:Option<&mut OriginalGpuEvent<'ctx>>)->Result<()>; + /// ...and completed AFTER it, over the published branch. + fn finish_draft(&mut self)->Result; + fn drain_draft(&mut self)->Result<()>; + #[allow(clippy::too_many_arguments)] + fn draft_first(&mut self,seed:&Self::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result; + fn drain_first(&mut self)->Result<()>; +} + +/// Receipt of one completed driver window. The head selection is single-use: the +/// draft consumes it exactly once, mirroring `draft_from_verifier`'s by-value argument. +pub(in crate::qwen_forward) struct NativeWindow { + generation:u64,position:i64,rows:usize,ids:Vec,inputs:Vec, + selection:RefCell>,keep:Option, +} +impl NativeWindow { + pub(in crate::qwen_forward) fn generation(&self)->u64 {self.generation} +} + +pub(in crate::qwen_forward) struct NativeServePort<'ctx,R,H> +where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { + verifier:OriginalVerifier<'ctx,R>,host:H,pending_publish:Option<(i64,Vec)>,failed:bool, +} +impl<'ctx,R,H> NativeServePort<'ctx,R,H> +where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { + pub(in crate::qwen_forward) fn new(verifier:OriginalVerifier<'ctx,R>,host:H)->Self { + Self{verifier,host,pending_publish:None,failed:false} + } + pub(in crate::qwen_forward) fn verifier(&self)->&OriginalVerifier<'ctx,R> {&self.verifier} + pub(in crate::qwen_forward) fn verifier_mut(&mut self)->&mut OriginalVerifier<'ctx,R> {&mut self.verifier} + pub(in crate::qwen_forward) fn host(&self)->&H {&self.host} + pub(in crate::qwen_forward) fn into_parts(self)->(OriginalVerifier<'ctx,R>,H) {(self.verifier,self.host)} + fn live(&self)->Result<()> {if self.failed {Err(Error::IdentityMismatch)} else {Ok(())}} + /// Wait the driver commit event and publish the accepted prefix to the session. Idempotent: with + /// nothing outstanding on our side the driver event must agree. The draft needs the PUBLISHED target + /// branch, so `draft_committed` settles through here too (the engine's later settle is then a no-op). + fn settle_commit(&mut self)->Result<()> { + let Some((position,expected))=self.pending_publish.take() else { + return match self.verifier.wait_commit() {Ok(())=>Ok(()),Err(_)=>{self.failed=true;Err(Error::CudaExecution)}}; + }; + let waited={let _p=profile::span("commit.wait");self.verifier.wait_commit()}; + if waited.is_err() {self.failed=true;return Err(Error::CudaExecution);} + // The driver staged the commit tokens itself; they must be exactly the accepted prefix. + let staged=match self.verifier.accepted_tokens() {Ok(t)=>t.to_vec(),Err(_)=>{self.failed=true;return Err(Error::CudaExecution);}}; + if staged!=expected {self.failed=true;return Err(Error::IdentityMismatch);} + let _p=profile::span("commit.publish"); + let published=self.host.publish_committed(&mut self.verifier,position,&expected); + if published.is_err() {self.failed=true;}published + } +} + +/// The two bring-up window traces, read once (they sat on the per-window path). +fn trace_logprobs()->Option { + static TOPK:std::sync::OnceLock>=std::sync::OnceLock::new(); + *TOPK.get_or_init(||std::env::var("LELEKA_TRACE_LOGPROBS").ok().and_then(|v|v.parse::().ok()).filter(|k|*k>0)) +} +fn trace_residual()->Option<&'static std::ffi::OsString> { + static DIR:std::sync::OnceLock>=std::sync::OnceLock::new(); + DIR.get_or_init(||std::env::var_os("LELEKA_TRACE_RESIDUAL")).as_ref() +} + +/// `LELEKA_SERVE_OVERLAP=off`: settle the commit (wait + publish) before the draft launches (the earlier, serialized +/// order; A/B control). Default: generate.cpp's order, the draft enqueued behind the commit event. +fn overlap()->bool { + static ON:std::sync::OnceLock=std::sync::OnceLock::new(); + *ON.get_or_init(||!std::env::var("LELEKA_SERVE_OVERLAP").is_ok_and(|v|v=="off"||v=="0")) +} + +impl<'ctx,R,H> OriginalServePort for NativeServePort<'ctx,R,H> +where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { + type Window=NativeWindow; + type Seed=H::Seed; + type TargetCheckpoint=H::TargetCheckpoint; + type DraftCheckpoint=H::DraftCheckpoint; + type Adaptive=H::Adaptive; + fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> { + self.live()?;self.host.validate_current(consumed,input,position) + } + fn checkpoint_target(&self)->Result {self.live()?;self.host.checkpoint_target()} + fn checkpoint_draft(&self)->Result {self.live()?;self.host.checkpoint_draft()} + fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()> { + // Whatever was in flight is dead: the window state is discarded by the driver (the + // uncommitted window never touched GDN state, and a committed one is fenced first). + self.pending_publish=None; + let restored=self.host.restore_target(checkpoint); + if restored.is_err() {self.failed=true;}restored + } + fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()> { + let restored=self.host.restore_draft(checkpoint); + if restored.is_err() {self.failed=true;}restored + } + fn apply_pending(&mut self)->Result<()> {self.live()?;let _p=profile::span("round.apply_pending");self.host.apply_pending()} + fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { + self.live()?; + let first=usize::try_from(position).map_err(|_|Error::InvalidPosition)?; + let result={let _p=profile::span("round.run_window");self.host.run_window(&mut self.verifier,position,inputs,consumed)?}; + // The driver's own receipt is authoritative: it must describe exactly this window. + let t=inputs.len(); + let ok=result.rows==t&&result.first_position==first&&result.selection.ids().len()==t + &&result.selection.position()==position as u64; + if !ok {self.failed=true;return Err(Error::IdentityMismatch);} + let mut ids=result.selection.ids().to_vec(); + // Quality gate only (an installed `quality_force` sequence; nothing installs one in production): the picks + // the controller verifies drafts against and commits next are the forced text's tokens. + let forced_differ=super::quality_force::apply(position,&mut ids); + if forced_differ>0 {crate::bringup_trace!("DBG forced window position={position} picks_replaced={forced_differ}");} + // Bring-up diagnostic (LELEKA_TRACE_LOGPROBS=): top-k head logprobs of every row of the completed window. + if let Some(k)=trace_logprobs() { + let mut line:Vec=Vec::new(); + crate::bringup_trace!("DBG logprobs window position={position} inputs={inputs:?} argmax_ids={ids:?}"); + match self.verifier.window_logprobs_topk(&ids,-1,k,&mut line) { + Ok(())=>eprintln!("{}",String::from_utf8_lossy(&line).trim_end()), + Err(e)=>crate::bringup_trace!("DBG logprobs err {e:?}"), + } + } + // Bring-up diagnostic (LELEKA_TRACE_RESIDUAL=): the final residual R of every row of the completed window, + // raw little-endian f32 (rows, hc*n_embd), file `r_win_pos.f32`. + if let Some(dir)=trace_residual() { + match self.verifier.window_residual_rows() { + Ok((rows,start,values))=>{ + let bytes:Vec=values.iter().flat_map(|v|v.to_le_bytes()).collect(); + static WINDOW_SEQ:std::sync::atomic::AtomicUsize=std::sync::atomic::AtomicUsize::new(0); + let seq=WINDOW_SEQ.fetch_add(1,std::sync::atomic::Ordering::Relaxed); + let path=std::path::Path::new(&dir).join(format!("r_win{seq:05}_pos{start}.f32")); + eprintln!("DBG residual window seq={seq} first={start} rows={rows} inputs={inputs:?} floats={} -> {}",values.len(),path.display()); + if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG residual write err {e:?}"); } + if let Ok(Some(ladder))=self.verifier.window_ladder_rows() { + let bytes:Vec=ladder.iter().flat_map(|v|v.to_le_bytes()).collect(); + let path=std::path::Path::new(&dir).join(format!("l_win{seq:05}_pos{start}.f32")); + if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG ladder write err {e:?}"); } + } + } + Err(e)=>eprintln!("DBG residual err {e:?}"), + } + } + Ok(NativeWindow{generation:result.generation,position,rows:t,ids,inputs:inputs.to_vec(), + selection:RefCell::new(Some(result.selection)),keep:None}) + } + fn validate_window(&self,window:&NativeWindow,position:i64,inputs:&[i32])->Result<()> { + self.live()?; + if window.position!=position||window.inputs!=inputs {return Err(Error::IdentityMismatch);} + // A capture-only or already-superseded window cannot pass: the driver mints + // `completed_window` only for the genuinely completed current generation. + let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch)?; + if completed.generation()!=window.generation||completed.rows()!=window.rows + ||completed.first_position()!=usize::try_from(position).map_err(|_|Error::InvalidPosition)? { + return Err(Error::IdentityMismatch); + } + if let Some(selection)=window.selection.borrow().as_ref() { + completed.validate_selection(selection).map_err(|_|Error::IdentityMismatch)?; + } + Ok(()) + } + fn window_outputs<'a>(&self,window:&'a NativeWindow)->&'a[i32] {&window.ids} + fn commit_window(&mut self,window:&mut NativeWindow,keep:usize)->Result<()> { + self.live()?; + if keep==0||keep>window.rows||window.keep.is_some()||self.pending_publish.is_some() {return Err(Error::IdentityMismatch);} + let _p=profile::span("round.commit"); + if let Err(e)=self.host.commit_enqueued(keep) {self.failed=true;return Err(e);} + if let Err(_e)=self.verifier.commit(keep,true) {self.failed=true;return Err(Error::CudaExecution);} + window.keep=Some(keep); + self.pending_publish=Some((window.position,window.inputs[..keep].to_vec()));Ok(()) + } + fn wait_commit(&mut self)->Result<()> {self.settle_commit()} + fn drain_window(&mut self,_window:NativeWindow)->Result<()> { + // The retained residuals belong to the driver bank; they stay alive until the next + // window (the bank, not this receipt, owns them), so draining releases only the receipt. + Ok(()) + } + fn discard_window(&mut self)->Result<()> { + // an enqueued commit cannot be undone; the controller restores the checkpoints first (which clears `pending_publish`) + if self.pending_publish.is_some() {self.failed=true;return Err(Error::IdentityMismatch);} + let _p=profile::span("round.discard_window"); + if let Err(e)=self.verifier.discard_window() { + eprintln!("leleka-serve nan-guard: the verifier could not take the refused window back ({e:?})"); + self.failed=true;return Err(super::original_serve_verifier::driver_error(&e)); + } + Ok(()) + } + fn begin_adaptation(&mut self,next_round:u64)->Result {self.live()?;let _p=profile::span("round.adapt");self.host.begin_adaptation(next_round)} + fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()> {self.host.join_adaptation(work)} + fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()> {self.live()?;self.host.stage_draft_history(consumed,next)} + fn draft_committed(&mut self,window:&NativeWindow,position:i64,accepted_row:usize,outputs:&[i32], + max_drafts:usize,min_p:f32,coupled:bool)->Result { + self.live()?; + let _p=profile::span("round.draft_committed"); + // Literal order: commit enqueued first, draft depends on its event on the same stream. + if window.keep!=Some(accepted_row+1)||window.position!=position||outputs!=window.ids.as_slice() { + return Err(Error::IdentityMismatch); + } + if overlap() && self.pending_publish.is_some() { + // generate.cpp: commit -> draft on one stream, the host waits only for the draft's tokens. The draft is + // enqueued behind the commit event; the session is published (commit wait, witnesses) while it runs, and + // the draft completes only over that published branch. + let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch); + let selection=window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch); + let (completed,selection)=match (completed,selection) {(Ok(c),Ok(s))=>(c,s),(Err(e),_)|(_,Err(e))=>return Err(e)}; + let launched={let _p=profile::span("draft.launch"); + self.host.launch_draft(completed,selection,position,accepted_row,max_drafts,min_p,self.verifier.pending_commit_event())}; + if let Err(e)=launched {self.failed=true;return Err(e);} + // the GPU is on the draft now: the adaptive planning/queueing the host deferred runs in its shadow + if let Err(e)={let _p=profile::span("round.adapt_deferred");self.host.run_deferred_adaptation()} {self.failed=true;return Err(e);} + self.settle_commit()?; + let finished={let _p=profile::span("draft.finish");self.host.finish_draft()}; + if finished.is_err() {self.failed=true;} + return finished; + } + // Serialized: the MTP receipt names the PUBLISHED branch, the commit event completes and the session is + // published before the draft launches. + self.settle_commit()?; + let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch); + let selection=window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch); + let (completed,selection)=match (completed,selection) {(Ok(c),Ok(s))=>(c,s),(Err(e),_)|(_,Err(e))=>return Err(e)}; + let draft={let _p=profile::span("draft.mtp");self.host.draft_committed(completed,selection,position,accepted_row,max_drafts,min_p,coupled)}; + if draft.is_err() {self.failed=true;}draft + } + fn drain_draft(&mut self)->Result<()> { + let drained=self.host.drain_draft(); + if drained.is_err() {self.failed=true;}drained + } + fn draft_first(&mut self,seed:&H::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result { + self.live()?;self.host.draft_first(seed,t,cell,token,max_drafts,min_p,coupled) + } + fn drain_first(&mut self)->Result<()> {self.host.drain_first()} +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs index 3fea17bb..d71cda9b 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs @@ -1,1503 +1,1503 @@ -//! The VRAM expert tier of the Original serve path: generate.cpp R4 / R4.2 (`--expert-cache auto|N`, -//! `--expert-cache-per-layer`, `--expert-profile`), the window's GPU/PCIe/CPU split of -//! expert_source.cpp `expert_pool_dispatch_multi` (plan v0.3 P6), the serve loop's adaptive tier -//! (`adapt` every `--adapt-every` rounds, `apply_pending`) and the prompt path's slot loan and refill. -//! -//! * **Placement.** The cache (`OriginalExpertCache`) is sized and opened by `original_cache_startup::open` -//! (the literal auto/explicit sizing, the profile-sized slots and the 3/4 retry) after every other owner -//! of the stack, then filled from the profile in rank order through the registered model bank, one -//! blocking copy per admitted pair, and slot 0 is read back and compared (generate.cpp 2949..2985). -//! * **Window split** (`split_group`). On a layer group's own routed ids: distinct experts in routing -//! order; a resident one is a VRAM group, and of the missed ones the last `nmiss * pcie_num >> 8` (at -//! most the group's staging blobs, at most 64) are staged over PCIe; the rest are the CPU's. The plan is -//! published before the CPU starts, so the GPU computes its share while the pool computes the misses. -//! * **Adaptive tier** (`choose_swaps`). Routed counts per (layer, expert); every `adapt_every` rounds, per -//! layer, the most-routed missing experts (count >= 2) replace the least-routed resident ones while the -//! gain is at least 1.5, the best `adapt_swaps` overall, then every count decays by 0.7. A swapped-out -//! expert is a miss at once, the new one resident once its copy has landed (`apply_pending`). -//! * **Prompt loan.** With a profile (and unless disabled) the prompt path borrows the cache's last slots -//! for its buffers when the configured chunk fits with 128 slots to spare; the unlent prefix still serves -//! prompt-path hits, and every lent slot is refilled from the bank before the first window reads. -//! -//! GPU experts round differently from the CPU's (bench/results/2026-09-27-cache-parity: 95-98 % same top-1, -//! equal perplexity); a reply with the cache on can differ slightly from one without it. Default off. -use super::{ - contract::{Error, Result}, - moe_weight_cache::MoeWeightCache, - original_cache_startup::{self, OriginalCacheOptions, OriginalRankedExperts}, - original_serve_pool::{CpuExpertPool, OriginalServePool}, - original_serve_verifier::driver_error, -}; -use crate::model_binding::qwen4exp_input::ModelBinding; -use leleka_model_format::qwen4exp::ResidentExpertBankSpan; -use leleka_cuda_driver::{ - Context, MappedExpertBank, ORIGINAL_VERIFY_MAX_PCIE_FETCHES, OriginalExpertCache, OriginalGpuStream, - OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyGpuPlan, OriginalVerifyPcieSource, -}; -use std::{ - path::PathBuf, - rc::Rc, - sync::atomic::{AtomicU32, Ordering}, -}; - -const LAYERS: usize = 48; -const EXPERTS: usize = 512; -const TOP_K: usize = 10; -/// expert_source.cpp `kMaxWindowEntries`. -const MAX_WINDOW_ENTRIES: usize = 128; -/// generate.cpp: a loan keeps at least this many slots for the decode tier. -const LOAN_FLOOR: usize = 128; - -/// **EXPERIMENTAL, changes the output** (docs/upstream-port-plan.md row 3.1; upstream `STRATA_ROUTE_TAIL_SKIP`): -/// `LELEKA_ROUTE_TAIL_SKIP=N` (1..=9, unset or 0 = off): a missed expert that every token of the window routes at rank `N` or -/// lower (the rank of the router's descending top-10, 0 = the heaviest) is neither copied over PCIe nor computed on the CPU; -/// its contribution is zero and the other weights are not renormalised. Off while at least `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED` -/// percent (default 90) of the experts are in VRAM. Not a default of any profile until its own quality gate passes. -const TAIL_UNRESOLVED: u32 = u32::MAX; -static TAIL_SKIP_RANK: AtomicU32 = AtomicU32::new(TAIL_UNRESOLVED); -/// The tail-skip rank in force (0 = off): the environment, read once, unless a replay arm set it. -pub(crate) fn tail_skip_rank() -> u32 { - let rank = TAIL_SKIP_RANK.load(Ordering::Relaxed); - if rank != TAIL_UNRESOLVED { - return rank; - } - let rank = std::env::var("LELEKA_ROUTE_TAIL_SKIP").ok().and_then(|v| v.trim().parse::().ok()).filter(|r| (1..TOP_K as u32).contains(r)).unwrap_or(0); - TAIL_SKIP_RANK.store(rank, Ordering::Relaxed); - rank -} -/// Set the rank of an A/B arm of the replay harness (`adaptive@0+tail7`; 0 or out of range = off); `None` goes back to the environment. -pub(crate) fn set_tail_skip_arm(rank: Option) { - TAIL_SKIP_RANK.store(rank.map_or(TAIL_UNRESOLVED, |r| if (1..TOP_K as u32).contains(&r) { r } else { 0 }), Ordering::Relaxed); -} -/// The rank this decode phase uses: `tail_skip_rank()` unless the cache holds at least the configured share of all experts. -pub(crate) fn effective_tail_rank(cache: &OriginalExpertCache<'_>) -> u32 { - let rank = tail_skip_rank(); - if rank == 0 { - return 0; - } - let cached: usize = (0..LAYERS).map(|l| (0..EXPERTS).filter(|&e| cache.resident_slot(l, e).is_some()).count()).sum(); - let percent = 100.0 * cached as f64 / (LAYERS * EXPERTS) as f64; - let limit = std::env::var("LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(90.0); - let effective = if percent >= limit { 0 } else { rank }; - static ANNOUNCED: AtomicU32 = AtomicU32::new(TAIL_UNRESOLVED); - if ANNOUNCED.swap(effective, Ordering::Relaxed) != effective { - if effective == 0 { - eprintln!("leleka-serve: route tail skip {rank} is OFF: {percent:.1}% of the experts are in VRAM (limit {limit:.0}%)"); - } else { - eprintln!("leleka-serve: EXPERIMENTAL route tail skip is ON (LELEKA_ROUTE_TAIL_SKIP={rank}, {percent:.1}% of the experts in VRAM): a missed expert every token of a window routes at rank {rank} or lower is skipped; the OUTPUT CHANGES"); - } - } - effective -} - -/// generate.cpp `--pcie-mode auto|dma|kernel` (`direct`, the mapped arena, is not ported): how a window stages its -/// PCIe share. `Auto` is DMA on the copy stream (job 981/982, RTX 5090, 6 prompts x 2 passes: +16 % static and +12-15 % -/// adaptive over the copy kernel, which generate.cpp makes its default); `kernel` is the in-graph copy kernel, available -/// wherever the expert source has device aliases (a registered resident bank). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum PcieMode { - Auto, - Dma, - Kernel, -} -impl PcieMode { - /// The `Verifier::set_pcie_mode` value the window graphs are recorded with (0 DMA, 2 copy kernel). `None` when - /// the copy kernel was asked for and the source cannot feed it. - pub(crate) fn graph_mode(self, pageable_source: bool, spans_tile: bool) -> Option { - let kernel_ok = !pageable_source && spans_tile; - match self { - PcieMode::Dma => Some(0), - PcieMode::Kernel => kernel_ok.then_some(2), - PcieMode::Auto => Some(0), - } - } -} - -/// The operator's choices for the VRAM expert tier. `off()` is the default and keeps the all-CPU pool. -#[derive(Clone, Debug, PartialEq)] -pub(crate) struct ExpertTierConfig { - /// `--expert-cache`: 0 off, -1 auto (free VRAM less the reserves), N slots. A profile with 0 means auto. - pub(crate) slots: i32, - /// `--expert-cache-per-layer` (R4.2g). - pub(crate) per_layer: bool, - /// `--expert-profile P` (a `tools/make_profile.py` STRP file). - pub(crate) profile: Option, - /// `--vram-reserve-mib` (700). - pub(crate) reserve_mib: usize, - /// Port: the per-request verifier (bank, canonical GDN image, eight window graphs and the commit graph) - /// is assembled for every decode phase, after the cache; auto sizing keeps this much more free for it. - pub(crate) decode_reserve_mib: usize, - /// `--pcie-frac` (0.45 here; generate.cpp's default is 0.55): the share of a group's missed experts staged over PCIe (by the - /// copy kernel or DMA, `pcie_mode`). Only used while the tier is on. - pub(crate) pcie_frac: f64, - /// `pcie_frac` was set by the operator. Unset, a pageable (low-RAM, file-mapped) bank stages nothing over PCIe: - /// its misses would be DMA'd from pageable pages (job report: 6.7 vs 10-12 tok/s on the 3080 laptop). - pub(crate) pcie_frac_set: bool, - /// `--pcie-mode` (auto). - pub(crate) pcie_mode: PcieMode, - /// `--adapt-every` (4) and `--adapt-swaps` (96); either 0 turns the adaptive tier off. - pub(crate) adapt_every: u32, - pub(crate) adapt_swaps: u32, - /// `!--no-prefill-borrow` (the loan is taken only with a profile, as in the Original). - pub(crate) prefill_borrow: bool, - /// `--resident-budget-gib` over the low-RAM file-mapped bank (0: off): see `pin_resident_complement`. - pub(crate) resident_budget_gib: f64, - /// EXPERIMENTAL, port-only (`LELEKA_ORIGINAL_SERVE_SEED`): at the end of each request's prompt phase the experts the - /// prompt's own prefill routed to replace the least-routed resident ones, in one batch of at most this many swaps - /// (0: off). Default when the configuration comes from the environment: `DEFAULT_SEED_SWAPS` (on); `ExpertTierConfig::off()` keeps 0. See `original_serve_seed`. - pub(crate) seed_swaps: usize, - /// `_SEED_KEEP`: routed-row credit given to every resident expert when ranking the seed's swaps (the blend with the - /// starting profile; 0 = the prompt's counts alone). - pub(crate) seed_keep: f32, - /// `_SEED_USAGE`: the prompt's counts, times this, are added to the adaptive tier's routed counts after the seed - /// (0 = the adaptive counts start empty, as without the seed). - pub(crate) seed_usage: f32, - /// `_SEED_DECAY`: at each prompt chunk the earlier chunks' counts are multiplied by this (1 = a plain sum over the - /// prompt, 0 = the last chunk alone): the end of a long prompt predicts the answer better than its beginning. - pub(crate) seed_decay: f32, - /// EXPERIMENTAL, off by default (0 = no cap; placement-class change, no quality gate yet). `_SEED_MAX_ROWS`: no seed for a prompt whose prefill routed more than this many rows through the experts. The - /// prompt's top experts cover only 9-10 % of the decode routing at 16k tokens (docs/original-serve.md), and a 100k+ prompt - /// replaces a good starting set with a worse one. - pub(crate) seed_max_rows: usize, -} -impl ExpertTierConfig { - pub(crate) fn off() -> Self { - Self { - slots: 0, - per_layer: false, - profile: None, - reserve_mib: 700, - // measured (jobs 989/990/988): the per-request verifier needs ~450 MiB, so 1024 left ~550 MiB idle (180k smoke - // included); 300 gives the auto-sized cache ~+330 slots - decode_reserve_mib: 300, - // the PCIe share that equalises the legs when the CPU pool and the DMA share the host's memory ceiling - // (P/(P+C) = 0.45, job 987-b/909; 0.45 vs 0.55: +0.5 % / +4.7 % at the auto-sized cache, equal at 2048 slots) - pcie_frac: 0.45, - pcie_frac_set: false, - pcie_mode: PcieMode::Auto, - adapt_every: 4, - adapt_swaps: 96, - prefill_borrow: true, - resident_budget_gib: 0.0, - seed_swaps: 0, - seed_keep: 0.0, - seed_usage: 0.0, - seed_decay: 1.0, - seed_max_rows: 0, - } - } - /// The tier is on with a slot count or a profile. - pub(crate) fn enabled(&self) -> bool { - self.slots != 0 || self.profile.is_some() - } - /// generate.cpp: a profile with `--expert-cache 0` takes the auto count. - pub(crate) fn effective_slots(&self) -> i32 { - if self.slots == 0 && self.profile.is_some() { -1 } else { self.slots } - } - pub(crate) fn validate(&self) -> Result<()> { - if self.slots < -1 || !self.pcie_frac.is_finite() || !(0.0..=1.0).contains(&self.pcie_frac) || self.adapt_swaps > 4096 - || !self.resident_budget_gib.is_finite() || self.resident_budget_gib < 0.0 - || !self.seed_keep.is_finite() || self.seed_keep < 0.0 || !self.seed_usage.is_finite() || self.seed_usage < 0.0 - || !(0.0..=1.0).contains(&self.seed_decay) || self.seed_swaps > LAYERS * EXPERTS - { - return Err(Error::InvalidDimension); - } - Ok(()) - } - /// `pcie_num = clamp(round(pcie_frac * 256), 0, 256)`. - pub(crate) fn pcie_num(&self) -> u32 { - (self.pcie_frac * 256.0 + 0.5).clamp(0.0, 256.0) as u32 - } - /// `pcie_num` for the bank the tier reads: the default 0.55 needs a registered (pinned, aliased) source; a - /// pageable mapped bank takes 0 unless the operator set a share. - pub(crate) fn pcie_num_for(&self, pageable_source: bool) -> u32 { - if pageable_source && !self.pcie_frac_set { 0 } else { self.pcie_num() } - } - pub(crate) fn adaptive(&self) -> bool { - self.adapt_every > 0 && self.adapt_swaps > 0 - } - /// The serve stack's environment switches (also the smoke's): `LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS` - /// (`auto` | N), `_EXPERT_PROFILE` (path), `_EXPERT_PER_LAYER` (`yes`), `_VRAM_RESERVE_MIB`, - /// `_DECODE_RESERVE_MIB`, `_PCIE_FRAC`, `_ADAPT_EVERY`, `_ADAPT_SWAPS`, `_PREFILL_BORROW` (`no`). - /// A value that does not parse is refused, never ignored. - pub(crate) fn from_environment() -> Result { - let var = |name: &str| std::env::var(format!("LELEKA_ORIGINAL_SERVE_{name}")).ok(); - let mut config = Self::off(); - if let Some(v) = var("EXPERT_SLOTS") { - config.slots = if v == "auto" { -1 } else { v.parse().map_err(|_| Error::InvalidDimension)? }; - } - config.profile = std::env::var_os("LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE").map(PathBuf::from); - if let Some(v) = var("EXPERT_PER_LAYER") { - config.per_layer = matches!(v.as_str(), "yes" | "1" | "on"); - } - let number = |name: &str, into: &mut usize| -> Result<()> { - if let Some(v) = var(name) { - *into = v.parse().map_err(|_| Error::InvalidDimension)?; - } - Ok(()) - }; - number("VRAM_RESERVE_MIB", &mut config.reserve_mib)?; - number("DECODE_RESERVE_MIB", &mut config.decode_reserve_mib)?; - if let Some(v) = var("PCIE_FRAC") { - config.pcie_frac = v.parse().map_err(|_| Error::InvalidDimension)?; - config.pcie_frac_set = true; - } - if let Some(v) = var("PCIE_MODE") { - config.pcie_mode = match v.as_str() { - "auto" => PcieMode::Auto, - "dma" => PcieMode::Dma, - "kernel" => PcieMode::Kernel, - _ => return Err(Error::InvalidDimension), - }; - } - if let Some(v) = var("ADAPT_EVERY") { - config.adapt_every = v.parse().map_err(|_| Error::InvalidDimension)?; - } - if let Some(v) = var("ADAPT_SWAPS") { - config.adapt_swaps = v.parse().map_err(|_| Error::InvalidDimension)?; - } - if let Some(v) = var("PREFILL_BORROW") { - config.prefill_borrow = !matches!(v.as_str(), "no" | "0" | "off"); - } - if let Some(v) = var("RESIDENT_BUDGET_GIB") { - config.resident_budget_gib = v.parse().map_err(|_| Error::InvalidDimension)?; - } - // Default ON (operator decision: long-running agent sessions; a fresh process starts from the prompt's own - // routing). `LELEKA_ORIGINAL_SERVE_SEED=off` restores the plain profile start. - config.seed_swaps = super::original_serve_seed::DEFAULT_SEED_SWAPS; - if let Some(v) = var("SEED") { - config.seed_swaps = match v.as_str() { - "off" | "no" | "0" => 0, - "on" | "yes" => super::original_serve_seed::DEFAULT_SEED_SWAPS, - n => n.parse().map_err(|_| Error::InvalidDimension)?, - }; - } - if let Some(v) = var("SEED_KEEP") { - config.seed_keep = v.parse().map_err(|_| Error::InvalidDimension)?; - } - if let Some(v) = var("SEED_USAGE") { - config.seed_usage = v.parse().map_err(|_| Error::InvalidDimension)?; - } - if let Some(v) = var("SEED_DECAY") { - config.seed_decay = v.parse().map_err(|_| Error::InvalidDimension)?; - } - if let Some(v) = var("SEED_MAX_ROWS") { - config.seed_max_rows = v.parse().map_err(|_| Error::InvalidDimension)?; - } - config.validate()?; - Ok(config) - } -} - -/// One window group's split: the GPU plan, the kind of every entry (-2 skipped by the route tail skip, -1 CPU, 0 VRAM, -/// 1 PCIe) and the expert of every PCIe group (staging slot order). -#[derive(Clone, Debug, PartialEq, Eq)] -pub(in crate::qwen_forward) struct GroupSplit { - pub(in crate::qwen_forward) plan: OriginalVerifyGpuPlan, - pub(in crate::qwen_forward) kinds: Vec, - pub(in crate::qwen_forward) pcie_experts: Vec, - /// Distinct experts the route tail skip left out (their entries are kind -2). - pub(in crate::qwen_forward) skipped_experts: usize, -} - -/// expert_source.cpp `expert_pool_dispatch_multi`, the GPU share: `ids` are the group's `rows * k` routed -/// ids, `resident(e)` the VRAM slot of expert `e` of this layer, `pcie_num` the PCIe share in 256ths (0: no -/// PCIe), `staging` the group's staging blobs. `cap` is the window's plan capacity (`max_t * k`). -#[cfg(test)] -pub(in crate::qwen_forward) fn split_group( - ids: &[i32], - k: usize, - cap: usize, - resident: impl Fn(u32) -> Option, - pcie_num: u32, - staging: usize, -) -> Result { - split_group_tail(ids, k, cap, resident, pcie_num, staging, 0) -} - -/// `split_group` with the route tail skip: `tail_rank > 0` (1..k) leaves out every missed expert whose best rank over the -/// entries that route it is at least `tail_rank` (expert_source.cpp `STRATA_ROUTE_TAIL_SKIP`); its entries are kind -2: not -/// in the plan, not staged, not computed. They are taken out of the miss count before the PCIe share is rounded. -pub(in crate::qwen_forward) fn split_group_tail( - ids: &[i32], - k: usize, - cap: usize, - resident: impl Fn(u32) -> Option, - pcie_num: u32, - staging: usize, - tail_rank: u32, -) -> Result { - split_group_pcie(ids, k, cap, resident, pcie_num, staging, tail_rank, |_| true) -} - -/// `split_group_tail` with a say in which misses may take the PCIe share: only an expert `pcie_ok` accepts is staged, the share -/// is still `nmiss * pcie_num >> 8` of ALL the misses but capped by the number that are eligible, and it is the last eligible -/// misses in routing order. `|_| true` is the unrestricted split. The pageable file-mapped bank uses it to keep PCIe to experts -/// whose pages are page-locked (`LELEKA_PCIE_LOCKED_ONLY`): a copy out of pageable pages is staged by the driver on the calling -/// thread, which is the thread that drives the whole window. -#[allow(clippy::too_many_arguments)] -pub(in crate::qwen_forward) fn split_group_pcie( - ids: &[i32], - k: usize, - cap: usize, - resident: impl Fn(u32) -> Option, - pcie_num: u32, - staging: usize, - tail_rank: u32, - pcie_ok: impl Fn(u32) -> bool, -) -> Result { - let n = ids.len(); - if k == 0 || n == 0 || n % k != 0 || n > MAX_WINDOW_ENTRIES || n > cap || pcie_num > 256 { - return Err(Error::InvalidDimension); - } - let valid = |e: i32| (0..EXPERTS as i32).contains(&e); - // first_of[i]: the first entry with the same id; distinct: the first entries in routing order - let mut first_of = vec![0usize; n]; - let mut distinct = Vec::with_capacity(n); - let mut nmiss = 0usize; - for i in 0..n { - first_of[i] = (0..i).find(|&j| ids[j] == ids[i]).map_or(i, |j| first_of[j]); - if first_of[i] == i { - distinct.push(i); - if valid(ids[i]) && resident(ids[i] as u32).is_none() { - nmiss += 1; - } - } - } - // the route tail skip: a missed expert no token of the window routes above rank `tail_rank` is dropped - let mut skip = vec![false; n]; - let mut skipped_experts = 0usize; - if tail_rank > 0 { - let mut best = vec![usize::MAX; n]; - for i in 0..n { - best[first_of[i]] = best[first_of[i]].min(i % k); - } - for &i0 in &distinct { - if valid(ids[i0]) && resident(ids[i0] as u32).is_none() && best[i0] >= tail_rank as usize { - skip[i0] = true; - skipped_experts += 1; - nmiss -= 1; - } - } - } - let mut m = if pcie_num > 0 { (nmiss * pcie_num as usize) >> 8 } else { 0 }; - // the misses that may be staged (all of them unless the caller restricts the share) - let eligible = distinct.iter().filter(|&&i0| !skip[i0] && valid(ids[i0]) && resident(ids[i0] as u32).is_none() && pcie_ok(ids[i0] as u32)).count(); - m = m.min(eligible); - let mut eligible_rank = 0usize; - let mut kinds = vec![-1i8; n]; - let mut plan = OriginalVerifyGpuPlan::new(); - let mut pcie_groups: Vec> = Vec::new(); - let mut pcie_experts = Vec::new(); - for &i0 in &distinct { - let e = ids[i0]; - let mut kind = -1i8; - let mut slot = None; - if skip[i0] { - kind = -2; - } else if valid(e) { - match resident(e as u32) { - Some(s) => { - kind = 0; - slot = Some(s); - } - None => { - if pcie_ok(e as u32) { - if eligible_rank >= eligible - m && pcie_groups.len() < staging && pcie_groups.len() < ORIGINAL_VERIFY_MAX_PCIE_FETCHES { - kind = 1; - } - eligible_rank += 1; - } - } - } - } - let members: Vec = (i0..n).filter(|&i| first_of[i] == i0).map(|i| i as u16).collect(); - for &i in &members { - kinds[usize::from(i)] = kind; - } - match (kind, slot) { - (0, Some(s)) => plan.push_vram(s, members), - (1, _) => { - pcie_groups.push(members); - pcie_experts.push(e as u32); - } - _ => {} - } - } - for members in pcie_groups { - plan.push_pcie(members); - } - Ok(GroupSplit { plan, kinds, pcie_experts, skipped_experts }) -} - -/// One adaptive swap: in layer `layer`, expert `incoming` takes the slot of `outgoing`. -#[derive(Clone, Copy, Debug, PartialEq)] -pub(in crate::qwen_forward) struct Swap { - pub(in crate::qwen_forward) gain: f32, - pub(in crate::qwen_forward) layer: usize, - pub(in crate::qwen_forward) incoming: usize, - pub(in crate::qwen_forward) outgoing: usize, -} - -/// `LELEKA_PCIE_LOCKED_ONLY=on|1` (read once): over a pageable file-mapped bank only the experts whose pages `pin_resident` locked may -/// take the PCIe share; every other miss stays with the CPU pool. Off by default (the unrestricted split). -pub(in crate::qwen_forward) fn pcie_locked_only() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("LELEKA_PCIE_LOCKED_ONLY").is_ok_and(|v| v == "on" || v == "1")) -} - -/// Experiment knobs of the adaptive tier (claude/decode-parity; the defaults are generate.cpp's constants): -/// `LELEKA_ADAPT_MIN_COUNT` (2.0: the least routed count a missing expert needs to be swapped in), -/// `LELEKA_ADAPT_MARGIN` (1.5: the count lead over the victim), `LELEKA_ADAPT_DECAY` (0.7: counts decay per adaptation). -fn adapt_tuning() -> (f32, f32, f32) { - static TUNING: std::sync::OnceLock<(f32, f32, f32)> = std::sync::OnceLock::new(); - *TUNING.get_or_init(|| { - let var = |name: &str, default: f32| std::env::var(name).ok().and_then(|v| v.parse::().ok()).filter(|v| v.is_finite()).unwrap_or(default); - (var("LELEKA_ADAPT_MIN_COUNT", 2.0), var("LELEKA_ADAPT_MARGIN", 1.5), var("LELEKA_ADAPT_DECAY", 0.7)) - }) -} - -/// generate.cpp `adapt`'s ranking over `usage[l * 512 + e]`: per layer the non-resident experts routed at -/// least twice (most first) against the resident ones (least first), pairwise while -/// `cand >= vict + 1.5`; all layers' swaps by gain, the best `max_swaps`. Ties keep ascending expert / layer -/// order (`std::sort` leaves tie order unspecified). -pub(in crate::qwen_forward) fn choose_swaps(usage: &[f32], resident: impl Fn(usize, usize) -> bool, max_swaps: usize) -> Vec { - let (min_count, margin, _) = adapt_tuning(); - let mut swaps = Vec::new(); - if usage.len() != LAYERS * EXPERTS { - return swaps; - } - let mut cand: Vec<(f32, usize)> = Vec::with_capacity(EXPERTS); - let mut vict: Vec<(f32, usize)> = Vec::with_capacity(EXPERTS); - for layer in 0..LAYERS { - let u = &usage[layer * EXPERTS..(layer + 1) * EXPERTS]; - cand.clear(); - vict.clear(); - for (e, &value) in u.iter().enumerate() { - if !resident(layer, e) { - if value >= min_count { - cand.push((value, e)); - } - } else { - vict.push((value, e)); - } - } - if cand.is_empty() || vict.is_empty() { - continue; - } - cand.sort_by(|a, b| b.0.total_cmp(&a.0)); - // Only as many victims as there are candidates can pair. The stable sort by value of experts pushed in ascending order is the order - // by (value, expert): selecting the `m` least of that total order and sorting only those gives the same first `m` without sorting all residents. - let m = cand.len().min(vict.len()); - let by_value_then_expert = |a: &(f32, usize), b: &(f32, usize)| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)); - if m < vict.len() { - vict.select_nth_unstable_by(m - 1, by_value_then_expert); - vict.truncate(m); - } - vict.sort_by(by_value_then_expert); - for (c, v) in cand.iter().zip(&vict) { - if c.0 < v.0 + margin { - break; - } - swaps.push(Swap { gain: c.0 - v.0, layer, incoming: c.1, outgoing: v.1 }); - } - } - swaps.sort_by(|a, b| b.gain.total_cmp(&a.gain)); - swaps.truncate(max_swaps); - swaps -} - -/// The earlier implementation (full sorts), kept to prove the faster one picks exactly the same swaps in the same order. -#[cfg(test)] -fn choose_swaps_reference(usage: &[f32], resident: impl Fn(usize, usize) -> bool, max_swaps: usize) -> Vec { - let (min_count, margin, _) = adapt_tuning(); - let mut swaps = Vec::new(); - if usage.len() != LAYERS * EXPERTS { - return swaps; - } - for layer in 0..LAYERS { - let u = &usage[layer * EXPERTS..(layer + 1) * EXPERTS]; - let mut cand: Vec<(f32, usize)> = Vec::new(); - let mut vict: Vec<(f32, usize)> = Vec::new(); - for (e, &value) in u.iter().enumerate() { - if !resident(layer, e) { - if value >= min_count { - cand.push((value, e)); - } - } else { - vict.push((value, e)); - } - } - if cand.is_empty() || vict.is_empty() { - continue; - } - cand.sort_by(|a, b| b.0.total_cmp(&a.0)); - vict.sort_by(|a, b| a.0.total_cmp(&b.0)); - for (c, v) in cand.iter().zip(&vict) { - if c.0 < v.0 + margin { - break; - } - swaps.push(Swap { gain: c.0 - v.0, layer, incoming: c.1, outgoing: v.1 }); - } - } - swaps.sort_by(|a, b| b.gain.total_cmp(&a.gain)); - swaps.truncate(max_swaps); - swaps -} - -/// Counters of the tier (the Original's `R4 expert-cache hits` / `adaptive tier` report lines). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct ResidencyStats { - pub(crate) groups: u64, - pub(crate) vram_entries: u64, - pub(crate) pcie_entries: u64, - pub(crate) cpu_entries: u64, - pub(crate) adaptations: u64, - pub(crate) swaps: u64, - /// Route tail skip (experimental): entries and distinct experts left out. - pub(crate) tail_entries: u64, - pub(crate) tail_experts: u64, -} -impl ResidencyStats { - pub(crate) fn describe(&self) -> String { - let all = (self.vram_entries + self.pcie_entries + self.cpu_entries).max(1) as f64; - let tail = if self.tail_entries > 0 { format!(", route tail skip {} entries / {} experts", self.tail_entries, self.tail_experts) } else { String::new() }; - format!( - "expert tier: {} layer groups, entries vram {} ({:.1}%) pcie {} ({:.1}%) cpu {} ({:.1}%), {} adaptations, {} swaps{}", - self.groups, - self.vram_entries, - 100.0 * self.vram_entries as f64 / all, - self.pcie_entries, - 100.0 * self.pcie_entries as f64 / all, - self.cpu_entries, - 100.0 * self.cpu_entries as f64 / all, - self.adaptations, - self.swaps, - tail - ) - } -} - -/// The registered source spans (gate, up, down) of routed experts by (layer, expert), kept for the life of the stack: -/// the mapped bank never moves, so a span set found once (the per-call scan through the binding costs 30-70 us) is -/// the span set of every later PCIe stage, adaptive swap and lent-slot refill of that expert. -/// `LELEKA_SPAN_CACHE=off` looks every set up again (A/B control). -#[derive(Default)] -pub(crate) struct SpanCache { - sets: std::collections::HashMap, -} -impl std::fmt::Debug for SpanCache { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "SpanCache({} sets)", self.sets.len()) - } -} -fn span_cache_enabled() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| !std::env::var("LELEKA_SPAN_CACHE").is_ok_and(|v| v == "off" || v == "0")) -} -impl SpanCache { - fn key(layer: usize, expert: u32) -> u32 { - (layer * EXPERTS) as u32 + expert - } - fn get(&self, layer: usize, expert: u32) -> Option<[ResidentExpertBankSpan; 3]> { - self.sets.get(&Self::key(layer, expert)).cloned() - } - fn contains(&self, layer: usize, expert: u32) -> bool { - self.sets.contains_key(&Self::key(layer, expert)) - } - fn insert(&mut self, layer: usize, expert: u32, spans: [ResidentExpertBankSpan; 3]) { - self.sets.insert(Self::key(layer, expert), spans); - } -} - -/// `LELEKA_PCIE_AUTO=lag` (claude/decode-parity): equalises the two legs of a layer's miss phase. After the CPU pool has -/// computed its share the host looks at flag B (the PCIe copies landed?) and, when they have not, spins until they do: -/// that wait is how much longer the PCIe leg took than the CPU leg (the host would wait for the GPU there anyway, so the -/// measurement costs nothing). Per round the mean lag drives the share in 256ths: a PCIe leg that finishes last lowers -/// it, a PCIe leg that finishes first (no lag at all) raises it a little, probing for the point where they meet. Only the -/// split changes, never what an expert computes. -#[derive(Debug)] -pub(crate) struct PcieLag { - num: u32, - lag_us: f64, - groups: u32, - ema_us: Option, - rounds_since_up: u32, -} -impl PcieLag { - const MIN: u32 = 32; - const MAX: u32 = 176; - const WAIT: std::time::Duration = std::time::Duration::from_millis(3); - pub(crate) fn from_environment(start_num: u32) -> Option { - if !std::env::var("LELEKA_PCIE_AUTO").is_ok_and(|v| v == "lag") || start_num == 0 { - return None; - } - Some(Self { num: start_num.clamp(Self::MIN, Self::MAX), lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }) - } - pub(crate) fn pcie_num(&self) -> u32 { - self.num - } - /// One group with PCIe experts: how long after the CPU leg the copies landed (spins until then, bounded). - pub(crate) fn measure(&mut self, landed: impl Fn() -> bool) { - let started = std::time::Instant::now(); - while !landed() { - if started.elapsed() > Self::WAIT { - break; - } - std::hint::spin_loop(); - } - self.lag_us += started.elapsed().as_secs_f64() * 1e6; - self.groups += 1; - } - /// Round boundary: move the share by the round's mean lag per measured group. - pub(crate) fn round(&mut self) { - let (lag, groups) = (std::mem::take(&mut self.lag_us), std::mem::take(&mut self.groups)); - if groups < 8 { - return; - } - let mean = lag / f64::from(groups); - let ema = self.ema_us.map_or(mean, |old| 0.6 * old + 0.4 * mean); - self.ema_us = Some(ema); - self.rounds_since_up += 1; - if ema > 25.0 { - self.num = self.num.saturating_sub(if ema > 120.0 { 10 } else { 5 }).max(Self::MIN); - self.rounds_since_up = 0; - } else if ema < 4.0 && self.rounds_since_up >= 3 { - self.num = (self.num + 3).min(Self::MAX); - self.rounds_since_up = 0; - } - } -} - -/// `LELEKA_PCIE_AUTO=on` (claude/decode-parity): a hill-climbing controller of the PCIe share. The static share is a -/// balance between the PCIe leg and the CPU pool of a layer, and the best value moves with the staging mode, the link and -/// the hit rate. Rounds are timed from one `apply_pending` to the next; the cost of a round is its time per -/// (misses + 40) entries (the entries the PCIe/CPU legs carry, plus a floor for the fixed work). Levels are shares in 256ths; -/// every `EXPLORE_EVERY` rounds the neighbours of the incumbent are tried for `TRIAL` rounds each and the cheaper one (by -/// EMA) becomes the incumbent. Only the split changes, never what an expert computes. -#[derive(Debug)] -pub(crate) struct PcieAuto { - levels: Vec, - ema: Vec>, - incumbent: usize, - trying: usize, - left: u32, - since_explore: u32, - next_probe_up: bool, - last: Option, - misses: u64, -} -impl PcieAuto { - const TRIAL: u32 = 6; - const EXPLORE_EVERY: u32 = 30; - pub(crate) fn from_environment(start_num: u32) -> Option { - if !std::env::var("LELEKA_PCIE_AUTO").is_ok_and(|v| v == "on") || start_num == 0 { - return None; - } - let levels: Vec = (2..=10).map(|i| i * 16).collect(); // 0.125 .. 0.625 - let incumbent = levels.iter().enumerate().min_by_key(|(_, l)| l.abs_diff(start_num)).map_or(0, |(i, _)| i); - Some(Self { - ema: vec![None; levels.len()], - levels, - incumbent, - trying: incumbent, - left: Self::TRIAL, - since_explore: 0, - next_probe_up: false, - last: None, - misses: 0, - }) - } - pub(crate) fn pcie_num(&self) -> u32 { - self.levels[self.trying] - } - pub(crate) fn add_misses(&mut self, n: usize) { - self.misses += n as u64; - } - /// Round boundary: score the round that just ended under `trying`, then pick the level of the next one. - pub(crate) fn round(&mut self) { - let now = std::time::Instant::now(); - let ended = self.last.replace(now); - let misses = std::mem::take(&mut self.misses); - let Some(then) = ended else { return }; - if misses == 0 { - return; - } - let cost = now.duration_since(then).as_secs_f64() * 1e3 / (misses as f64 + 40.0 * 48.0); - let slot = &mut self.ema[self.trying]; - *slot = Some(slot.map_or(cost, |old| 0.7 * old + 0.3 * cost)); - self.left = self.left.saturating_sub(1); - self.since_explore += 1; - if self.trying != self.incumbent { - if self.left == 0 { - // the trial ended: keep the cheaper of the two - let (a, b) = (self.ema[self.trying].unwrap_or(f64::MAX), self.ema[self.incumbent].unwrap_or(f64::MAX)); - if a < b { - self.incumbent = self.trying; - } - self.trying = self.incumbent; - self.left = 0; - } - } else if self.since_explore >= Self::EXPLORE_EVERY { - self.since_explore = 0; - let target = if self.next_probe_up { self.incumbent + 1 } else { self.incumbent.wrapping_sub(1) }; - self.next_probe_up = !self.next_probe_up; - if target < self.levels.len() { - self.ema[target] = None; - self.trying = target; - self.left = Self::TRIAL; - } - } - } -} - -/// What survives requests: the routed counts of the adaptive tier (`drive.d.usage`) and the counters. -#[derive(Debug, Default)] -pub(crate) struct ResidencyState { - usage: Vec, - pub(crate) stats: ResidencyStats, - /// generate.cpp `--dump-routing FILE` (`LELEKA_ORIGINAL_SERVE_DUMP_ROUTING`): every decode window row's routed - /// experts, as `tools/make_profile.py` reads them (layer i32, k i32, k ids i32, k weights f32). - routing: Option>, - /// Cumulative (vram, pcie, cpu) window entries after each verified round of the current request (for the first-rounds - /// hit rates; recorded where the adaptive tier is asked for its round). - marks: Vec<[u64; 3]>, - /// The counters when the current request began. - mark_base: [u64; 3], - pub(crate) spans: SpanCache, - pub(crate) pcie_auto: Option, - pub(crate) pcie_lag: Option, - pcie_auto_checked: bool, -} -impl ResidencyState { - pub(crate) fn new(config: &ExpertTierConfig) -> Self { - let routing = std::env::var_os("LELEKA_ORIGINAL_SERVE_DUMP_ROUTING") - .and_then(|path| std::fs::File::create(path).ok()) - .map(std::io::BufWriter::new); - Self { - usage: if config.adaptive() { vec![0.0; LAYERS * EXPERTS] } else { Vec::new() }, - stats: ResidencyStats::default(), - routing, - pcie_auto: None, - pcie_lag: None, - pcie_auto_checked: false, - marks: Vec::new(), - mark_base: [0; 3], - spans: SpanCache::default(), - } - } - /// A new request: the per-round marks start over (the counters and the adaptive counts survive). - pub(crate) fn begin_request(&mut self) { - self.marks.clear(); - self.mark_base = [self.stats.vram_entries, self.stats.pcie_entries, self.stats.cpu_entries]; - } - /// Cumulative (vram, pcie, cpu) entries after each round of the last request, from the request's own start. - pub(crate) fn round_marks(&self) -> Vec<[u64; 3]> { - self.marks.iter().map(|m| [m[0] - self.mark_base[0], m[1] - self.mark_base[1], m[2] - self.mark_base[2]]).collect() - } - /// The adaptive tier's routed counts (`layer * 512 + expert`; empty when the tier is off). - pub(crate) fn usage(&self) -> &[f32] { - &self.usage - } - /// A fresh adaptive history: the routed counts start empty (the experiments' first-request state). - pub(crate) fn clear_usage(&mut self) { - self.usage.iter_mut().for_each(|v| *v = 0.0); - } - /// Add `scale * counts` (`layer * 512 + expert`) to the adaptive tier's routed counts (no-op when it is off). - pub(crate) fn add_usage(&mut self, counts: &[f32], scale: f32) { - if self.usage.len() == counts.len() && scale > 0.0 { - for (u, &c) in self.usage.iter_mut().zip(counts) { - *u += scale * c; - } - } - } - /// Write the buffered routing records out (end of a request). - pub(crate) fn flush_routing(&mut self) { - if let Some(routing) = self.routing.as_mut() { - let _ = std::io::Write::flush(routing); - } - } - fn record_routing(&mut self, layer: usize, ids: &[i32], weights: &[f32]) { - let Some(routing) = self.routing.as_mut() else { return }; - if ids.len() != weights.len() { - return; - } - let mut record = Vec::with_capacity(8 + 8 * TOP_K); - for (row, w) in ids.chunks_exact(TOP_K).zip(weights.chunks_exact(TOP_K)) { - record.clear(); - record.extend_from_slice(&(layer as i32).to_le_bytes()); - record.extend_from_slice(&(TOP_K as i32).to_le_bytes()); - row.iter().for_each(|e| record.extend_from_slice(&e.to_le_bytes())); - w.iter().for_each(|x| record.extend_from_slice(&x.to_le_bytes())); - let _ = std::io::Write::write_all(routing, &record); - } - } -} - -/// The window pool with the VRAM tier: the GPU share of every group published first, the CPU pool on the -/// rest. Lives for one decode phase; borrows the stack's cache, CPU pool and persistent state. -pub(in crate::qwen_forward) struct GpuExpertPool<'p, 'a, 'ctx> { - pub(in crate::qwen_forward) binding: &'a ModelBinding, - pub(in crate::qwen_forward) moe: &'p MoeWeightCache<'ctx>, - pub(in crate::qwen_forward) cache: &'p mut OriginalExpertCache<'ctx>, - pub(in crate::qwen_forward) bank: Rc>, - pub(in crate::qwen_forward) cpu: &'p mut CpuExpertPool<'a>, - pub(in crate::qwen_forward) state: &'p mut ResidencyState, - pub(in crate::qwen_forward) pcie_num: u32, - pub(in crate::qwen_forward) adapt_every: u32, - pub(in crate::qwen_forward) adapt_swaps: usize, - /// The route tail skip rank of this decode phase (0 = off; `effective_tail_rank`). - pub(in crate::qwen_forward) tail_rank: u32, - /// `layer * 512 + expert` -> the expert's pages are page-locked (`MappedExpertBank::locked_experts`); empty = every expert may - /// take the PCIe share. Filled only under `LELEKA_PCIE_LOCKED_ONLY` on a pageable bank. - pub(in crate::qwen_forward) pcie_locked: Vec, -} -impl GpuExpertPool<'_, '_, '_> { - fn source_spans(&mut self, layer: usize, experts: &[u32]) -> Result> { - source_spans(&mut *self.cpu, &self.bank, self.moe, self.binding, &mut self.state.spans, layer, experts) - } -} -/// The source spans of `experts` of `layer`, in order: from the cache when seen before, else through the CPU -/// tier's admission (or the binding's own scan on the legacy path) and remembered. -pub(super) fn source_spans( - cpu: &mut CpuExpertPool<'_>, - bank: &MappedExpertBank<'_>, - moe: &MoeWeightCache<'_>, - binding: &ModelBinding, - known: &mut SpanCache, - layer: usize, - experts: &[u32], -) -> Result> { - { - let cached = span_cache_enabled(); - let fetch: Vec = if cached { - experts.iter().copied().filter(|&e| !known.contains(layer, e)).collect() - } else { - experts.to_vec() - }; - let mut fetched: Vec<[ResidentExpertBankSpan; 3]> = Vec::new(); - fetched.try_reserve_exact(fetch.len()).map_err(|_| Error::InputAllocation)?; - if !fetch.is_empty() { - // The direct CPU tier's admission (one fence per group, rows scanned once per expert) serves the - // PCIe sources too; the legacy path keeps the per-expert full scan. - match cpu.admitted_spans(layer as u32, &fetch) { - Some(admitted) => { - for spans_of in admitted? { - if !bank.eligible(&spans_of) { - return Err(Error::IdentityMismatch); - } - fetched.push(spans_of); - } - } - None => { - for &e in &fetch { - fetched.push(moe.original_expert_spans(binding, layer as u32, e)?); - } - } - } - } - if !cached { - return Ok(fetched); - } - for (&e, spans_of) in fetch.iter().zip(fetched) { - known.insert(layer, e, spans_of); - } - let mut spans = Vec::new(); - spans.try_reserve_exact(experts.len()).map_err(|_| Error::InputAllocation)?; - for &e in experts { - spans.push(known.get(layer, e).ok_or(Error::IdentityMismatch)?); - } - Ok(spans) - } -} -impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { - fn run_group( - &mut self, - rows: OriginalVerifyCpuRows<'_>, - sink: &mut OriginalVerifyCpuSink<'_, 'ctx>, - copy: &mut OriginalGpuStream<'ctx>, - ) -> Result<()> { - let layer = rows.layer; - if layer >= LAYERS || rows.ids.is_empty() || rows.ids.len() % TOP_K != 0 { - return Err(Error::InvalidDimension); - } - let mut clock = super::original_serve_pool::window_trace::now(); - self.state.record_routing(layer, rows.ids, rows.route_weights); - if !self.state.usage.is_empty() { - for &e in rows.ids { - if (0..EXPERTS as i32).contains(&e) { - self.state.usage[layer * EXPERTS + e as usize] += 1.0; - } - } - } - let profile_split = super::original_serve_profile::span("pool.split"); - let cache = &*self.cache; - let locked = &self.pcie_locked; - let split = split_group_pcie( - rows.ids, - TOP_K, - sink.plan_capacity(), - |e| cache.resident_slot(layer, e as usize), - self.state.pcie_lag.as_ref().map(PcieLag::pcie_num).or_else(|| self.state.pcie_auto.as_ref().map(PcieAuto::pcie_num)).unwrap_or(self.pcie_num), - sink.staging_capacity(), - self.tail_rank, - |e| locked.is_empty() || locked.get(layer * EXPERTS + e as usize).copied().unwrap_or(false), - )?; - if let Some(auto) = self.state.pcie_auto.as_mut() { - auto.add_misses(split.kinds.iter().filter(|&&k| k == -1 || k == 1).count()); - } - super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock); - drop(profile_split); - let profile_spans = super::original_serve_profile::span("pool.spans"); - let spans = source_spans(&mut *self.cpu, &self.bank, self.moe, self.binding, &mut self.state.spans, layer, &split.pcie_experts)?; - super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::PCIE_SPANS, &mut clock); - super::original_serve_pool::window_trace::add(super::original_serve_pool::window_trace::PCIE_EXPERTS, split.pcie_experts.len() as f64); - drop(profile_spans); - let profile_publish = super::original_serve_profile::span("pool.publish_plan"); - let pcie = (self.pcie_num > 0).then_some(OriginalVerifyPcieSource { bank: &self.bank, spans: &spans }); - sink.publish_gpu_plan(&split.plan, cache, pcie, copy).map_err(|e| driver_error(&e))?; - drop(profile_publish); - // only the CPU's own entries are computed; the GPU's and the skipped ones are written as zeros (the window's copy kernel - // takes a skipped entry from the mapped sink, so its zero row is its contribution) - let include: Vec = split.kinds.iter().map(|&k| k == -1).collect(); - let stats = &mut self.state.stats; - stats.groups += 1; - stats.tail_experts += split.skipped_experts as u64; - for &kind in &split.kinds { - match kind { - 0 => stats.vram_entries += 1, - 1 => stats.pcie_entries += 1, - -2 => stats.tail_entries += 1, - _ => stats.cpu_entries += 1, - } - } - if self.cpu.lookahead_running() && layer + 1 < LAYERS { - let next = layer + 1; - self.cpu.set_next_resident(|e| cache.resident_slot(next, e).is_some()); - } - super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock); - let _p = super::original_serve_profile::span("pool.cpu"); - let ran = self.cpu.run_entries(rows, sink, Some(&include)); - if ran.is_ok() && !split.pcie_experts.is_empty() { - if let Some(lag) = self.state.pcie_lag.as_mut() { - lag.measure(|| sink.copies_landed().unwrap_or(true)); - } - } - ran - } - fn apply_pending(&mut self) -> Result<()> { - if !self.state.pcie_auto_checked { - self.state.pcie_auto_checked = true; - self.state.pcie_auto = PcieAuto::from_environment(self.pcie_num); - self.state.pcie_lag = PcieLag::from_environment(self.pcie_num); - } - if let Some(auto) = self.state.pcie_auto.as_mut() { - auto.round(); - } - if let Some(lag) = self.state.pcie_lag.as_mut() { - lag.round(); - } - // The swaps issued beside the previous commit land before this window (`apply_pending(true)`): their copies - // would otherwise read host memory while the CPU pool streams its experts (job 803: the overlap costs the CPU - // share more than the wait), and the resident set no longer depends on when the copies finished. - // LELEKA_SERVE_SWAP_WAIT=off polls instead (generate.cpp `apply_pending(false)`). - if swap_wait() { - return self.cache.wait_swaps().map_err(|e| driver_error(&e)); - } - self.cache.poll_swaps().map(|_| ()).map_err(|e| driver_error(&e)) - } - fn begin_adaptation(&mut self, next_round: u64) -> Result<()> { - let stats = self.state.stats; - self.state.marks.push([stats.vram_entries, stats.pcie_entries, stats.cpu_entries]); - if self.state.usage.is_empty() || self.adapt_every == 0 || next_round % u64::from(self.adapt_every) != 0 { - return Ok(()); - } - // `if (!pending.empty()) return true;`: the previous swaps are still in flight (no decay either) - if self.cache.swaps_pending() { - return Ok(()); - } - let cache = &*self.cache; - let p = super::original_serve_profile::span("adapt.choose"); - let swaps = choose_swaps(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some(), self.adapt_swaps); - drop(p); - let p = super::original_serve_profile::span("adapt.queue"); - for swap in &swaps { - let slot = self.cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?; - let spans = self.source_spans(swap.layer, &[swap.incoming as u32])?.pop().ok_or(Error::IdentityMismatch)?; - self.cache.swap_slot_queued(slot, Rc::clone(&self.bank), spans).map_err(|e| driver_error(&e))?; - } - drop(p); - let p = super::original_serve_profile::span("adapt.arm"); - self.cache.arm_swaps().map_err(|e| driver_error(&e))?; - drop(p); - let _p = super::original_serve_profile::span("adapt.decay"); - let decay = adapt_tuning().2; - for value in &mut self.state.usage { - *value *= decay; - } - self.state.stats.adaptations += 1; - self.state.stats.swaps += swaps.len() as u64; - Ok(()) - } -} - -/// `LELEKA_SERVE_SWAP_WAIT=off`: poll the adaptive swaps at a round start instead of waiting for them. -fn swap_wait() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| !std::env::var("LELEKA_SERVE_SWAP_WAIT").is_ok_and(|v| v == "off" || v == "0")) -} - -/// generate.cpp startup of the tier for the serve stack: size and open the cache after every other owner, -/// fill it from the profile through the registered bank (blocking, rank order; per-layer skips a full -/// layer's pairs, global stops at the first refusal) and read slot 0 back. `None`: the tier is off or no -/// slot fits. -pub(in crate::qwen_forward) fn open_tier<'ctx>( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - moe: &MoeWeightCache<'ctx>, - config: &ExpertTierConfig, - prefill_capacity: usize, -) -> Result, usize)>> { - config.validate()?; - if !config.enabled() { - return Ok(None); - } - let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?; - let profile = match &config.profile { - Some(path) => Some(OriginalRankedExperts::read(path, binding)?), - None => None, - }; - let options = OriginalCacheOptions { - slots: config.effective_slots(), - reserve_mib: config.reserve_mib.checked_add(config.decode_reserve_mib).ok_or(Error::Overflow)?, - prefill_capacity, - prefill_borrow: config.prefill_borrow && profile.is_some(), - per_layer: config.per_layer, - }; - // The MTP head is bound before the cache in this stack: nothing pending to reserve for it. - let Some(mut cache) = original_cache_startup::open(binding, context, options, profile.as_ref(), 0)? else { - return Ok(None); - }; - let mut filled = 0usize; - if let Some(profile) = profile.as_ref().filter(|p| !p.is_empty()) { - let per_layer = cache.per_layer_admission(); - let want = if per_layer { profile.pairs().len() } else { profile.pairs().len().min(cache.slots()) }; - for &(layer, expert) in &profile.pairs()[..want] { - let slot = cache.admit(usize::from(layer), usize::from(expert)).map_err(|e| driver_error(&e))?; - if slot < 0 { - if per_layer { - continue; - } - break; - } - let spans = moe.original_expert_spans(binding, u32::from(layer), u32::from(expert))?; - cache.fill_slot_blocking(slot as usize, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?; - filled += 1; - } - if filled > 0 { - let (layer, expert) = profile.pairs()[0]; - let slot = usize::try_from(cache.slot_of(usize::from(layer), usize::from(expert))).map_err(|_| Error::IdentityMismatch)?; - let spans = moe.original_expert_spans(binding, u32::from(layer), u32::from(expert))?; - cache.verify_slot(slot, &bank, &spans).map_err(|e| driver_error(&e))?; - } - if config.resident_budget_gib > 0.0 && bank.pageable() { - pin_resident_complement(&bank, &cache, profile, config.resident_budget_gib)?; - } - } - Ok(Some((cache, filled))) -} - -/// generate.cpp `--resident-budget-gib N` over the low-RAM (file-mapped) bank: the experts the VRAM cache does -/// not hold, in profile order, page-locked in RAM while they fit N GiB, clamped like -/// `FileExpertSource::pin_cache_complement` to `MemAvailable` less the 4 GiB headroom and a 0.25 GiB margin. -fn pin_resident_complement( - bank: &leleka_cuda_driver::MappedExpertBank<'_>, - cache: &OriginalExpertCache<'_>, - profile: &OriginalRankedExperts, - budget_gib: f64, -) -> Result<()> { - const GIB: f64 = 1_073_741_824.0; - #[cfg(not(target_os = "windows"))] - let meminfo = std::fs::read_to_string("/proc/meminfo"); - // Windows: the same text, rendered from GlobalMemoryStatusEx by leleka-memory. - #[cfg(target_os = "windows")] - let meminfo = { - use leleka_memory::ProcSource; - leleka_memory::RealProc.read("/proc/meminfo") - }; - let available = meminfo - .ok() - .and_then(|t| { - t.lines() - .find(|l| l.starts_with("MemAvailable:")) - .and_then(|l| l.split_ascii_whitespace().nth(1)?.parse::().ok()) - }) - .map_or(0, |kib| kib * 1024); - // the governor's soft floor + reserve (4 GiB headroom and a 0.25 GiB margin without one) - let room = crate::memory_governor::complement_room(available); - let budget = ((budget_gib * GIB) as u64).min(room); - let ranked: Vec<(u8, u32)> = profile - .pairs() - .iter() - .filter(|&&(layer, expert)| cache.slot_of(usize::from(layer), usize::from(expert)) < 0) - .map(|&(layer, expert)| (layer as u8, u32::from(expert))) - .collect(); - let started = std::time::Instant::now(); - match bank.pin_resident(&ranked, budget) { - Ok((held, bytes)) => eprintln!( - "leleka-serve: resident RAM budget {:.2} GiB (asked {budget_gib:.2}, {:.2} GiB available): {held} experts the \ - VRAM cache does not hold page-locked by profile rank ({:.2} GiB) in {:.1} s; the rest read from the file", - budget as f64 / GIB, - available as f64 / GIB, - bytes as f64 / GIB, - started.elapsed().as_secs_f64() - ), - // #403: a budget that cannot be kept is a warning; every miss is read from the file pages instead - Err(e) => eprintln!("leleka-serve: WARNING: the resident RAM budget cannot be kept ({e:?}); experts are read from the file"), - } - Ok(()) -} - -/// The serve stack's loan test (generate.cpp `fits_one`, fixed chunk): the prompt path's buffers for the -/// configured chunk come from the cache's last `k` slots when `0 < k` and `k + 128 <= slots`. Unlike the -/// Original the chunk is not halved to fit: the prompt executor is built for exactly this capacity. -pub(in crate::qwen_forward) fn loan_slots(cache: &OriginalExpertCache<'_>, bytes_needed: usize) -> Result> { - let k = cache.lend_slots(bytes_needed).map_err(|e| driver_error(&e))?; - Ok((k > 0 && k.checked_add(LOAN_FLOOR).is_some_and(|n| n <= cache.slots())).then_some(k)) -} - -/// generate.cpp `refill`: every lent slot gets its own expert's bytes back from the bank (queued, one wait), -/// so the windows always see the whole cache. Returns the slots refilled. -pub(in crate::qwen_forward) fn refill_lent<'ctx>( - binding: &ModelBinding, - moe: &MoeWeightCache<'ctx>, - cache: &mut OriginalExpertCache<'ctx>, - known: &mut SpanCache, - defer_wait: bool, -) -> Result { - let cached = span_cache_enabled(); - let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?; - let mut refilled = 0usize; - for slot in 0..cache.slots() { - let Some((layer, expert)) = cache.needs_refill(slot).map_err(|e| driver_error(&e))? else { continue }; - let span_spans = super::original_serve_profile::span("refill.spans"); - let spans = match if cached { known.get(layer, expert as u32) } else { None } { - Some(spans) => spans, - None => { - let spans = moe.original_expert_spans(binding, layer as u32, expert as u32)?; - if cached { - known.insert(layer, expert as u32, spans.clone()); - } - spans - } - }; - drop(span_spans); - let _span_queue = super::original_serve_profile::span("refill.queue"); - if defer_wait { - cache.fill_slot_queued_async(slot, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?; - } else { - cache.fill_slot_queued(slot, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?; - } - refilled += 1; - } - if defer_wait { - // the copies run behind the host's assembly of the decode phase; `settle_refill` waits for them before any - // window reads the cache - return Ok(refilled); - } - settle_refill(cache)?; - Ok(refilled) -} - -/// Wait for the refill copies queued by `refill_lent(.., defer_wait = true)` (a no-op when none are queued). -pub(in crate::qwen_forward) fn settle_refill(cache: &mut OriginalExpertCache<'_>) -> Result<()> { - let _span_sync = super::original_serve_profile::span("refill.sync"); - cache.sync_queued().map_err(|e| driver_error(&e)) -} - -/// `LELEKA_REFILL_DEFER=on` (EXPERIMENTAL, off by default): queue the lent-slot refill inside the decode phase's assembly, after -/// its intake uploads and before the graph capture, instead of waiting for it at the end of the prompt phase. Job 902 measured -/// the earlier variant (queued at the end of the prompt phase, waited later) as no gain: the PLE seed upload waited for the same -/// DMA. The current variant has no GPU result yet (job 904), so it stays opt-in. -pub(in crate::qwen_forward) fn refill_defer_enabled() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("LELEKA_REFILL_DEFER").is_ok_and(|v| v == "on" || v == "1")) -} - -#[cfg(test)] -mod tests { - #[test] - fn the_selection_based_ranking_picks_the_reference_swaps_in_the_same_order() { - // xorshift: deterministic usage with many ties (small integer counts) and a random resident set per layer - let mut x = 0x9e3779b97f4a7c15u64; - let mut next = move || { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x - }; - for case in 0..40 { - let skew = 1 + case % 7; - let usage: Vec = (0..LAYERS * EXPERTS).map(|_| ((next() % 11) as f32 / skew as f32).floor() + if next() % 5 == 0 { 0.5 } else { 0.0 }).collect(); - let resident_bits: Vec = (0..LAYERS * EXPERTS).map(|_| next() % (2 + (case % 4) as u64) != 0).collect(); - let resident = |l: usize, e: usize| resident_bits[l * EXPERTS + e]; - for max_swaps in [1usize, 5, 96, 4096] { - let fast = choose_swaps(&usage, resident, max_swaps); - let slow = choose_swaps_reference(&usage, resident, max_swaps); - assert_eq!(fast.len(), slow.len(), "case {case} max {max_swaps}"); - for (a, b) in fast.iter().zip(&slow) { - assert_eq!((a.layer, a.incoming, a.outgoing, a.gain.to_bits()), (b.layer, b.incoming, b.outgoing, b.gain.to_bits()), "case {case} max {max_swaps}"); - } - } - } - } - - #[test] - #[ignore = "timing probe: cargo test --release -p leleka-runtime --lib choose_swaps_timing -- --ignored --nocapture"] - fn choose_swaps_timing() { - let mut x = 0x2545f4914f6cdd1du64; - let mut next = move || { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x - }; - let usage: Vec = (0..LAYERS * EXPERTS).map(|_| if next() % 6 == 0 { (next() % 9) as f32 } else { 0.0 }).collect(); - let resident_bits: Vec = (0..LAYERS * EXPERTS).map(|_| next() % 100 < 46).collect(); - let resident = |l: usize, e: usize| resident_bits[l * EXPERTS + e]; - let time = |f: &dyn Fn() -> usize| { - let t = std::time::Instant::now(); - let mut n = 0; - for _ in 0..200 { - n += f(); - } - (t.elapsed().as_secs_f64() * 1e6 / 200.0, n) - }; - let (fast, a) = time(&|| choose_swaps(&usage, resident, 96).len()); - let (slow, b) = time(&|| choose_swaps_reference(&usage, resident, 96).len()); - eprintln!("choose_swaps: new {fast:.0} us, reference {slow:.0} us per call ({a} {b})"); - } - - use super::*; - - fn row(ids: [i32; 10]) -> Vec { - ids.to_vec() - } - - #[test] - fn residents_are_vram_groups_in_routing_order_and_the_rest_is_the_cpus_without_pcie() { - let mut ids = row([5, 1, 9, 2, 3, 4, 6, 7, 8, 0]); - ids.extend(row([9, 5, 11, 12, 13, 14, 15, 16, 17, 18])); - let resident = |e: u32| match e { - 9 => Some(40), - 5 => Some(7), - 17 => Some(3), - _ => None, - }; - let s = split_group(&ids, 10, 80, resident, 0, 16).unwrap(); - // first use order: 5 (entries 0, 11), 9 (2, 10), 17 (18) - assert_eq!(s.plan.vram(), &[(7, vec![0, 11]), (40, vec![2, 10]), (3, vec![18])]); - assert!(s.plan.pcie().is_empty() && s.pcie_experts.is_empty()); - for (i, &kind) in s.kinds.iter().enumerate() { - let want = if [0, 11, 2, 10, 18].contains(&i) { 0 } else { -1 }; - assert_eq!(kind, want, "entry {i}"); - } - assert_eq!(s.plan.entries(), 5); - } - - #[test] - fn the_pcie_share_is_the_last_misses_in_routing_order_capped_by_staging() { - // 10 distinct misses, pcie_frac 0.55 -> pcie_num 141, m = 10 * 141 >> 8 = 5 - let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); - let none = |_: u32| None; - let s = split_group(&ids, 10, 40, none, 141, 16).unwrap(); - assert_eq!(s.pcie_experts, vec![15, 16, 17, 18, 19]); - assert_eq!(s.plan.pcie(), &[vec![5], vec![6], vec![7], vec![8], vec![9]]); - assert_eq!(s.kinds, vec![-1, -1, -1, -1, -1, 1, 1, 1, 1, 1]); - // staging holds 3: the first three of the selected tail - let s = split_group(&ids, 10, 40, none, 141, 3).unwrap(); - assert_eq!(s.pcie_experts, vec![15, 16, 17]); - assert_eq!(s.kinds.iter().filter(|&&k| k == 1).count(), 3); - // pcie_num 256: every miss; 0: none - assert_eq!(split_group(&ids, 10, 40, none, 256, 16).unwrap().pcie_experts.len(), 10); - assert!(split_group(&ids, 10, 40, none, 0, 16).unwrap().plan.is_empty()); - } - - #[test] - fn a_restricted_pcie_share_takes_only_eligible_misses_and_never_more_than_the_unrestricted_one() { - // 10 misses, share 141/256 -> m = 5 of all misses; only 11, 14, 16, 17 may be staged - let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); - let none = |_: u32| None; - let ok = |e: u32| matches!(e, 11 | 14 | 16 | 17); - let s = split_group_pcie(&ids, 10, 40, none, 141, 16, 0, ok).unwrap(); - assert_eq!(s.pcie_experts, vec![11, 14, 16, 17], "capped by the eligible misses, routing order"); - assert_eq!(s.kinds, vec![-1, 1, -1, -1, 1, -1, 1, 1, -1, -1]); - // a smaller share takes the last eligible misses - let s = split_group_pcie(&ids, 10, 40, none, 64, 16, 0, ok).unwrap(); // m = 10 * 64 >> 8 = 2 - assert_eq!(s.pcie_experts, vec![16, 17]); - // nothing eligible, nothing staged; and the unrestricted split is the old one - assert!(split_group_pcie(&ids, 10, 40, none, 256, 16, 0, |_| false).unwrap().plan.pcie().is_empty()); - let all = split_group_pcie(&ids, 10, 40, none, 141, 16, 0, |_| true).unwrap(); - let old = split_group(&ids, 10, 40, none, 141, 16).unwrap(); - assert_eq!((all.pcie_experts, all.kinds), (old.pcie_experts, old.kinds)); - // residents and skipped experts are not eligible misses - let resident = |e: u32| (e == 11).then_some(2usize); - let s = split_group_pcie(&ids, 10, 40, resident, 256, 16, 0, ok).unwrap(); - assert_eq!(s.pcie_experts, vec![14, 16, 17]); - } - - #[test] - fn a_resident_expert_never_counts_as_a_miss_for_the_pcie_rank() { - // 1 and 3 resident; the misses are 2, 4, 20..=25 - let padded = row([1, 2, 3, 4, 20, 21, 22, 23, 24, 25]); - let resident = |e: u32| (e == 1 || e == 3).then_some(e as usize); - let s = split_group(&padded, 10, 40, resident, 128, 16).unwrap(); - // 8 misses (2, 4, 20..=25), m = 8 * 128 >> 8 = 4: the last four misses in routing order - assert_eq!(s.pcie_experts, vec![22, 23, 24, 25]); - assert_eq!(s.plan.vram().len(), 2); - } - - #[test] - fn the_tail_skip_drops_missed_experts_every_token_routes_at_or_below_the_rank() { - // row 0 ranks: 12 at 6, 30 at 7, 31 at 8, 40 (resident) at 9; row 1 ranks: 15 at 7, 12 at 8, 30 at 9 - let mut ids = row([1, 2, 3, 4, 5, 6, 12, 30, 31, 40]); - ids.extend(row([7, 8, 9, 10, 11, 13, 14, 15, 12, 30])); - let resident = |e: u32| (e == 40).then_some(3usize); - let off = split_group_tail(&ids, 10, 20, resident, 0, 16, 0).unwrap(); - assert_eq!(off.skipped_experts, 0); - assert!(off.kinds.iter().all(|&k| k != -2)); - let on = split_group_tail(&ids, 10, 20, resident, 0, 16, 7).unwrap(); - // 30: best rank min(7, 9) = 7 -> skipped (entries 7 and 19); 31: rank 8 -> skipped (entry 8); 15: rank 7 -> skipped (entry 17); - // 12: best rank min(6, 8) = 6 < 7 -> kept in both rows (entries 6 and 18) - assert_eq!(on.skipped_experts, 3); - assert_eq!(on.kinds.iter().enumerate().filter(|&(_, &k)| k == -2).map(|(i, _)| i).collect::>(), vec![7, 8, 17, 19]); - assert_eq!((on.kinds[6], on.kinds[18]), (-1, -1)); - assert_eq!(on.kinds[9], 0, "a resident expert is never skipped"); - // everything else is exactly what the skip-off split produced - for i in 0..20 { - if on.kinds[i] != -2 { - assert_eq!(on.kinds[i], off.kinds[i], "entry {i}"); - } - } - assert_eq!(on.plan.vram(), off.plan.vram()); - // rank 8: only expert 31 (rank 8 in its only row); rank 9: nothing (the rank-9 entries are resident 40 and 30, best rank 7) - assert_eq!(split_group_tail(&ids, 10, 20, resident, 0, 16, 8).unwrap().skipped_experts, 1); - assert_eq!(split_group_tail(&ids, 10, 20, resident, 0, 16, 9).unwrap().skipped_experts, 0); - } - - #[test] - fn the_tail_skip_shrinks_the_miss_count_before_the_pcie_share_is_taken() { - // ten misses, rank 7..9 are three experts: 7 misses remain, pcie_num 141 -> m = 7 * 141 >> 8 = 3 (instead of 5 of ten) - let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); - let none = |_: u32| None; - let s = split_group_tail(&ids, 10, 40, none, 141, 16, 7).unwrap(); - assert_eq!(s.skipped_experts, 3); - assert_eq!(s.kinds, vec![-1, -1, -1, -1, 1, 1, 1, -2, -2, -2]); - assert_eq!(s.pcie_experts, vec![14, 15, 16]); - // a rank past the last slot skips nothing - let off = split_group_tail(&ids, 10, 40, none, 141, 16, 10).unwrap(); - assert_eq!(off.skipped_experts, 0); - } - - #[test] - fn the_tail_skip_leaves_invalid_ids_to_the_cpu_check() { - let ids = row([600, 1, 2, 3, 4, 5, 6, 7, 8, 9]); - let s = split_group_tail(&ids, 10, 40, |_| None, 0, 16, 1).unwrap(); - assert_eq!(s.kinds[0], -1, "an out-of-range id is never a skip: the CPU path reports it"); - } - - #[test] - fn out_of_range_ids_stay_with_the_cpu_and_oversized_groups_are_refused() { - let ids = row([600, 1, 2, 3, 4, 5, 6, 7, 8, 9]); - let s = split_group(&ids, 10, 40, |_| Some(1), 256, 16).unwrap(); - assert_eq!(s.kinds[0], -1); - assert!(split_group(&ids, 10, 5, |_| None, 0, 16).is_err()); - assert!(split_group(&vec![0; 130], 10, 200, |_| None, 0, 16).is_err()); - assert!(split_group(&ids[..9], 10, 40, |_| None, 0, 16).is_err()); - } - - #[test] - fn swaps_take_the_most_routed_misses_over_the_least_routed_residents() { - let mut usage = vec![0.0f32; LAYERS * EXPERTS]; - // layer 2: residents 0 (5.0), 1 (0.5), 2 (3.0); candidates 10 (9.0), 11 (2.5), 12 (1.9: below 2) - for (e, u) in [(0, 5.0), (1, 0.5), (2, 3.0), (10, 9.0), (11, 2.5), (12, 1.9)] { - usage[2 * EXPERTS + e] = u; - } - // layer 7: resident 4 (0.0), candidate 30 (2.0: the least count a candidate may have) - usage[7 * EXPERTS + 30] = 2.0; - let resident = |l: usize, e: usize| (l == 2 && e < 3) || (l == 7 && e == 4); - let swaps = choose_swaps(&usage, resident, 96); - // layer 2 pairs: (10, 1) gain 8.5; (11, 2): 2.5 < 3.0 + 1.5 stops; layer 7: (30, 4) gain 2.0 - assert_eq!(swaps.len(), 2); - assert_eq!((swaps[0].layer, swaps[0].incoming, swaps[0].outgoing), (2, 10, 1)); - assert_eq!((swaps[1].layer, swaps[1].incoming, swaps[1].outgoing), (7, 30, 4)); - assert_eq!(choose_swaps(&usage, resident, 1).len(), 1); - // no resident in a layer: no swap there (a native pack's cache only changes through its profile) - assert!(choose_swaps(&usage, |_, _| false, 96).is_empty()); - } - - #[test] - fn the_lag_controller_lowers_the_share_when_the_copies_land_last_and_probes_up_when_they_land_first() { - let mut c = PcieLag { num: 141, lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }; - // the PCIe leg finishes 200 us after the CPU leg on average: the share drops by 10 - c.lag_us = 200.0 * 48.0; - c.groups = 48; - c.round(); - assert_eq!(c.pcie_num(), 131); - // too few measured groups: nothing moves - c.lag_us = 9999.0; - c.groups = 3; - c.round(); - assert_eq!(c.pcie_num(), 131); - // copies always first: after three quiet rounds the share rises by 3 - let mut c = PcieLag { num: 100, lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }; - for _ in 0..3 { - c.groups = 20; - c.round(); - } - assert_eq!(c.pcie_num(), 103); - // the share stays inside its bounds - let mut c = PcieLag { num: PcieLag::MIN, lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }; - c.lag_us = 1e6; - c.groups = 10; - c.round(); - assert_eq!(c.pcie_num(), PcieLag::MIN); - } - - #[test] - fn the_pcie_mode_auto_is_dma_and_the_kernel_needs_device_aliases() { - // auto: DMA staging (this port's default; generate.cpp's is the copy kernel), the kernel only on request - assert_eq!(PcieMode::Auto.graph_mode(false, true), Some(0)); - assert_eq!(PcieMode::Auto.graph_mode(true, true), Some(0)); - assert_eq!(PcieMode::Auto.graph_mode(false, false), Some(0)); - assert_eq!(PcieMode::Kernel.graph_mode(false, true), Some(2)); - assert_eq!(PcieMode::Kernel.graph_mode(true, true), None); - assert_eq!(PcieMode::Dma.graph_mode(false, true), Some(0)); - assert_eq!(ExpertTierConfig::off().pcie_mode, PcieMode::Auto); - } - - #[test] - fn the_configuration_is_off_by_default_and_refuses_what_it_cannot_honour() { - let off = ExpertTierConfig::off(); - assert!(!off.enabled() && off.validate().is_ok() && off.pcie_num() == 115); - // the prompt-routing seed is an opt-in experiment - assert_eq!((off.seed_swaps, off.seed_keep, off.seed_usage, off.seed_decay), (0, 0.0, 0.0, 1.0)); - assert!(ExpertTierConfig { seed_keep: -1.0, ..off.clone() }.validate().is_err()); - let with_profile = ExpertTierConfig { profile: Some("p.bin".into()), ..off.clone() }; - assert!(with_profile.enabled()); - assert_eq!(with_profile.effective_slots(), -1); - assert_eq!(ExpertTierConfig { slots: 2048, ..off.clone() }.effective_slots(), 2048); - assert_eq!(ExpertTierConfig { pcie_frac: 0.55, ..off.clone() }.pcie_num(), 141); - // the default share needs a pinned source; an operator's share applies to a pageable bank too - assert_eq!(off.pcie_num_for(false), 115); - assert_eq!(off.pcie_num_for(true), 0); - assert_eq!(ExpertTierConfig { pcie_frac: 0.3, pcie_frac_set: true, ..off.clone() }.pcie_num_for(true), 77); - assert_eq!(ExpertTierConfig { pcie_frac: 1.0, ..off.clone() }.pcie_num(), 256); - assert!(ExpertTierConfig { slots: -2, ..off.clone() }.validate().is_err()); - assert!(ExpertTierConfig { pcie_frac: 1.5, ..off.clone() }.validate().is_err()); - assert!(ExpertTierConfig { pcie_frac: f64::NAN, ..off.clone() }.validate().is_err()); - assert!(!ExpertTierConfig { adapt_every: 0, ..off.clone() }.adaptive()); - assert!(ResidencyState::new(&ExpertTierConfig { adapt_swaps: 0, ..off.clone() }).usage.is_empty()); - assert_eq!(ResidencyState::new(&off).usage.len(), LAYERS * EXPERTS); - } -} +//! The VRAM expert tier of the Original serve path: generate.cpp R4 / R4.2 (`--expert-cache auto|N`, +//! `--expert-cache-per-layer`, `--expert-profile`), the window's GPU/PCIe/CPU split of +//! expert_source.cpp `expert_pool_dispatch_multi` (plan v0.3 P6), the serve loop's adaptive tier +//! (`adapt` every `--adapt-every` rounds, `apply_pending`) and the prompt path's slot loan and refill. +//! +//! * **Placement.** The cache (`OriginalExpertCache`) is sized and opened by `original_cache_startup::open` +//! (the literal auto/explicit sizing, the profile-sized slots and the 3/4 retry) after every other owner +//! of the stack, then filled from the profile in rank order through the registered model bank, one +//! blocking copy per admitted pair, and slot 0 is read back and compared (generate.cpp 2949..2985). +//! * **Window split** (`split_group`). On a layer group's own routed ids: distinct experts in routing +//! order; a resident one is a VRAM group, and of the missed ones the last `nmiss * pcie_num >> 8` (at +//! most the group's staging blobs, at most 64) are staged over PCIe; the rest are the CPU's. The plan is +//! published before the CPU starts, so the GPU computes its share while the pool computes the misses. +//! * **Adaptive tier** (`choose_swaps`). Routed counts per (layer, expert); every `adapt_every` rounds, per +//! layer, the most-routed missing experts (count >= 2) replace the least-routed resident ones while the +//! gain is at least 1.5, the best `adapt_swaps` overall, then every count decays by 0.7. A swapped-out +//! expert is a miss at once, the new one resident once its copy has landed (`apply_pending`). +//! * **Prompt loan.** With a profile (and unless disabled) the prompt path borrows the cache's last slots +//! for its buffers when the configured chunk fits with 128 slots to spare; the unlent prefix still serves +//! prompt-path hits, and every lent slot is refilled from the bank before the first window reads. +//! +//! GPU experts round differently from the CPU's (bench/results/2026-09-27-cache-parity: 95-98 % same top-1, +//! equal perplexity); a reply with the cache on can differ slightly from one without it. Default off. +use super::{ + contract::{Error, Result}, + moe_weight_cache::MoeWeightCache, + original_cache_startup::{self, OriginalCacheOptions, OriginalRankedExperts}, + original_serve_pool::{CpuExpertPool, OriginalServePool}, + original_serve_verifier::driver_error, +}; +use crate::model_binding::qwen4exp_input::ModelBinding; +use leleka_model_format::qwen4exp::ResidentExpertBankSpan; +use leleka_cuda_driver::{ + Context, MappedExpertBank, ORIGINAL_VERIFY_MAX_PCIE_FETCHES, OriginalExpertCache, OriginalGpuStream, + OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyGpuPlan, OriginalVerifyPcieSource, +}; +use std::{ + path::PathBuf, + rc::Rc, + sync::atomic::{AtomicU32, Ordering}, +}; + +const LAYERS: usize = 48; +const EXPERTS: usize = 512; +const TOP_K: usize = 10; +/// expert_source.cpp `kMaxWindowEntries`. +const MAX_WINDOW_ENTRIES: usize = 128; +/// generate.cpp: a loan keeps at least this many slots for the decode tier. +const LOAN_FLOOR: usize = 128; + +/// **EXPERIMENTAL, changes the output** (docs/upstream-port-plan.md row 3.1; upstream `STRATA_ROUTE_TAIL_SKIP`): +/// `LELEKA_ROUTE_TAIL_SKIP=N` (1..=9, unset or 0 = off): a missed expert that every token of the window routes at rank `N` or +/// lower (the rank of the router's descending top-10, 0 = the heaviest) is neither copied over PCIe nor computed on the CPU; +/// its contribution is zero and the other weights are not renormalised. Off while at least `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED` +/// percent (default 90) of the experts are in VRAM. Not a default of any profile until its own quality gate passes. +const TAIL_UNRESOLVED: u32 = u32::MAX; +static TAIL_SKIP_RANK: AtomicU32 = AtomicU32::new(TAIL_UNRESOLVED); +/// The tail-skip rank in force (0 = off): the environment, read once, unless a replay arm set it. +pub(crate) fn tail_skip_rank() -> u32 { + let rank = TAIL_SKIP_RANK.load(Ordering::Relaxed); + if rank != TAIL_UNRESOLVED { + return rank; + } + let rank = std::env::var("LELEKA_ROUTE_TAIL_SKIP").ok().and_then(|v| v.trim().parse::().ok()).filter(|r| (1..TOP_K as u32).contains(r)).unwrap_or(0); + TAIL_SKIP_RANK.store(rank, Ordering::Relaxed); + rank +} +/// Set the rank of an A/B arm of the replay harness (`adaptive@0+tail7`; 0 or out of range = off); `None` goes back to the environment. +pub(crate) fn set_tail_skip_arm(rank: Option) { + TAIL_SKIP_RANK.store(rank.map_or(TAIL_UNRESOLVED, |r| if (1..TOP_K as u32).contains(&r) { r } else { 0 }), Ordering::Relaxed); +} +/// The rank this decode phase uses: `tail_skip_rank()` unless the cache holds at least the configured share of all experts. +pub(crate) fn effective_tail_rank(cache: &OriginalExpertCache<'_>) -> u32 { + let rank = tail_skip_rank(); + if rank == 0 { + return 0; + } + let cached: usize = (0..LAYERS).map(|l| (0..EXPERTS).filter(|&e| cache.resident_slot(l, e).is_some()).count()).sum(); + let percent = 100.0 * cached as f64 / (LAYERS * EXPERTS) as f64; + let limit = std::env::var("LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(90.0); + let effective = if percent >= limit { 0 } else { rank }; + static ANNOUNCED: AtomicU32 = AtomicU32::new(TAIL_UNRESOLVED); + if ANNOUNCED.swap(effective, Ordering::Relaxed) != effective { + if effective == 0 { + eprintln!("leleka-serve: route tail skip {rank} is OFF: {percent:.1}% of the experts are in VRAM (limit {limit:.0}%)"); + } else { + eprintln!("leleka-serve: EXPERIMENTAL route tail skip is ON (LELEKA_ROUTE_TAIL_SKIP={rank}, {percent:.1}% of the experts in VRAM): a missed expert every token of a window routes at rank {rank} or lower is skipped; the OUTPUT CHANGES"); + } + } + effective +} + +/// generate.cpp `--pcie-mode auto|dma|kernel` (`direct`, the mapped arena, is not ported): how a window stages its +/// PCIe share. `Auto` is DMA on the copy stream (job 981/982, RTX 5090, 6 prompts x 2 passes: +16 % static and +12-15 % +/// adaptive over the copy kernel, which generate.cpp makes its default); `kernel` is the in-graph copy kernel, available +/// wherever the expert source has device aliases (a registered resident bank). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PcieMode { + Auto, + Dma, + Kernel, +} +impl PcieMode { + /// The `Verifier::set_pcie_mode` value the window graphs are recorded with (0 DMA, 2 copy kernel). `None` when + /// the copy kernel was asked for and the source cannot feed it. + pub(crate) fn graph_mode(self, pageable_source: bool, spans_tile: bool) -> Option { + let kernel_ok = !pageable_source && spans_tile; + match self { + PcieMode::Dma => Some(0), + PcieMode::Kernel => kernel_ok.then_some(2), + PcieMode::Auto => Some(0), + } + } +} + +/// The operator's choices for the VRAM expert tier. `off()` is the default and keeps the all-CPU pool. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct ExpertTierConfig { + /// `--expert-cache`: 0 off, -1 auto (free VRAM less the reserves), N slots. A profile with 0 means auto. + pub(crate) slots: i32, + /// `--expert-cache-per-layer` (R4.2g). + pub(crate) per_layer: bool, + /// `--expert-profile P` (a `tools/make_profile.py` STRP file). + pub(crate) profile: Option, + /// `--vram-reserve-mib` (700). + pub(crate) reserve_mib: usize, + /// Port: the per-request verifier (bank, canonical GDN image, eight window graphs and the commit graph) + /// is assembled for every decode phase, after the cache; auto sizing keeps this much more free for it. + pub(crate) decode_reserve_mib: usize, + /// `--pcie-frac` (0.45 here; generate.cpp's default is 0.55): the share of a group's missed experts staged over PCIe (by the + /// copy kernel or DMA, `pcie_mode`). Only used while the tier is on. + pub(crate) pcie_frac: f64, + /// `pcie_frac` was set by the operator. Unset, a pageable (low-RAM, file-mapped) bank stages nothing over PCIe: + /// its misses would be DMA'd from pageable pages (job report: 6.7 vs 10-12 tok/s on the 3080 laptop). + pub(crate) pcie_frac_set: bool, + /// `--pcie-mode` (auto). + pub(crate) pcie_mode: PcieMode, + /// `--adapt-every` (4) and `--adapt-swaps` (96); either 0 turns the adaptive tier off. + pub(crate) adapt_every: u32, + pub(crate) adapt_swaps: u32, + /// `!--no-prefill-borrow` (the loan is taken only with a profile, as in the Original). + pub(crate) prefill_borrow: bool, + /// `--resident-budget-gib` over the low-RAM file-mapped bank (0: off): see `pin_resident_complement`. + pub(crate) resident_budget_gib: f64, + /// EXPERIMENTAL, port-only (`LELEKA_ORIGINAL_SERVE_SEED`): at the end of each request's prompt phase the experts the + /// prompt's own prefill routed to replace the least-routed resident ones, in one batch of at most this many swaps + /// (0: off). Default when the configuration comes from the environment: `DEFAULT_SEED_SWAPS` (on); `ExpertTierConfig::off()` keeps 0. See `original_serve_seed`. + pub(crate) seed_swaps: usize, + /// `_SEED_KEEP`: routed-row credit given to every resident expert when ranking the seed's swaps (the blend with the + /// starting profile; 0 = the prompt's counts alone). + pub(crate) seed_keep: f32, + /// `_SEED_USAGE`: the prompt's counts, times this, are added to the adaptive tier's routed counts after the seed + /// (0 = the adaptive counts start empty, as without the seed). + pub(crate) seed_usage: f32, + /// `_SEED_DECAY`: at each prompt chunk the earlier chunks' counts are multiplied by this (1 = a plain sum over the + /// prompt, 0 = the last chunk alone): the end of a long prompt predicts the answer better than its beginning. + pub(crate) seed_decay: f32, + /// EXPERIMENTAL, off by default (0 = no cap; placement-class change, no quality gate yet). `_SEED_MAX_ROWS`: no seed for a prompt whose prefill routed more than this many rows through the experts. The + /// prompt's top experts cover only 9-10 % of the decode routing at 16k tokens (docs/original-serve.md), and a 100k+ prompt + /// replaces a good starting set with a worse one. + pub(crate) seed_max_rows: usize, +} +impl ExpertTierConfig { + pub(crate) fn off() -> Self { + Self { + slots: 0, + per_layer: false, + profile: None, + reserve_mib: 700, + // measured (jobs 989/990/988): the per-request verifier needs ~450 MiB, so 1024 left ~550 MiB idle (180k smoke + // included); 300 gives the auto-sized cache ~+330 slots + decode_reserve_mib: 300, + // the PCIe share that equalises the legs when the CPU pool and the DMA share the host's memory ceiling + // (P/(P+C) = 0.45, job 987-b/909; 0.45 vs 0.55: +0.5 % / +4.7 % at the auto-sized cache, equal at 2048 slots) + pcie_frac: 0.45, + pcie_frac_set: false, + pcie_mode: PcieMode::Auto, + adapt_every: 4, + adapt_swaps: 96, + prefill_borrow: true, + resident_budget_gib: 0.0, + seed_swaps: 0, + seed_keep: 0.0, + seed_usage: 0.0, + seed_decay: 1.0, + seed_max_rows: 0, + } + } + /// The tier is on with a slot count or a profile. + pub(crate) fn enabled(&self) -> bool { + self.slots != 0 || self.profile.is_some() + } + /// generate.cpp: a profile with `--expert-cache 0` takes the auto count. + pub(crate) fn effective_slots(&self) -> i32 { + if self.slots == 0 && self.profile.is_some() { -1 } else { self.slots } + } + pub(crate) fn validate(&self) -> Result<()> { + if self.slots < -1 || !self.pcie_frac.is_finite() || !(0.0..=1.0).contains(&self.pcie_frac) || self.adapt_swaps > 4096 + || !self.resident_budget_gib.is_finite() || self.resident_budget_gib < 0.0 + || !self.seed_keep.is_finite() || self.seed_keep < 0.0 || !self.seed_usage.is_finite() || self.seed_usage < 0.0 + || !(0.0..=1.0).contains(&self.seed_decay) || self.seed_swaps > LAYERS * EXPERTS + { + return Err(Error::InvalidDimension); + } + Ok(()) + } + /// `pcie_num = clamp(round(pcie_frac * 256), 0, 256)`. + pub(crate) fn pcie_num(&self) -> u32 { + (self.pcie_frac * 256.0 + 0.5).clamp(0.0, 256.0) as u32 + } + /// `pcie_num` for the bank the tier reads: the default 0.55 needs a registered (pinned, aliased) source; a + /// pageable mapped bank takes 0 unless the operator set a share. + pub(crate) fn pcie_num_for(&self, pageable_source: bool) -> u32 { + if pageable_source && !self.pcie_frac_set { 0 } else { self.pcie_num() } + } + pub(crate) fn adaptive(&self) -> bool { + self.adapt_every > 0 && self.adapt_swaps > 0 + } + /// The serve stack's environment switches (also the smoke's): `LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS` + /// (`auto` | N), `_EXPERT_PROFILE` (path), `_EXPERT_PER_LAYER` (`yes`), `_VRAM_RESERVE_MIB`, + /// `_DECODE_RESERVE_MIB`, `_PCIE_FRAC`, `_ADAPT_EVERY`, `_ADAPT_SWAPS`, `_PREFILL_BORROW` (`no`). + /// A value that does not parse is refused, never ignored. + pub(crate) fn from_environment() -> Result { + let var = |name: &str| std::env::var(format!("LELEKA_ORIGINAL_SERVE_{name}")).ok(); + let mut config = Self::off(); + if let Some(v) = var("EXPERT_SLOTS") { + config.slots = if v == "auto" { -1 } else { v.parse().map_err(|_| Error::InvalidDimension)? }; + } + config.profile = std::env::var_os("LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE").map(PathBuf::from); + if let Some(v) = var("EXPERT_PER_LAYER") { + config.per_layer = matches!(v.as_str(), "yes" | "1" | "on"); + } + let number = |name: &str, into: &mut usize| -> Result<()> { + if let Some(v) = var(name) { + *into = v.parse().map_err(|_| Error::InvalidDimension)?; + } + Ok(()) + }; + number("VRAM_RESERVE_MIB", &mut config.reserve_mib)?; + number("DECODE_RESERVE_MIB", &mut config.decode_reserve_mib)?; + if let Some(v) = var("PCIE_FRAC") { + config.pcie_frac = v.parse().map_err(|_| Error::InvalidDimension)?; + config.pcie_frac_set = true; + } + if let Some(v) = var("PCIE_MODE") { + config.pcie_mode = match v.as_str() { + "auto" => PcieMode::Auto, + "dma" => PcieMode::Dma, + "kernel" => PcieMode::Kernel, + _ => return Err(Error::InvalidDimension), + }; + } + if let Some(v) = var("ADAPT_EVERY") { + config.adapt_every = v.parse().map_err(|_| Error::InvalidDimension)?; + } + if let Some(v) = var("ADAPT_SWAPS") { + config.adapt_swaps = v.parse().map_err(|_| Error::InvalidDimension)?; + } + if let Some(v) = var("PREFILL_BORROW") { + config.prefill_borrow = !matches!(v.as_str(), "no" | "0" | "off"); + } + if let Some(v) = var("RESIDENT_BUDGET_GIB") { + config.resident_budget_gib = v.parse().map_err(|_| Error::InvalidDimension)?; + } + // Default ON (operator decision: long-running agent sessions; a fresh process starts from the prompt's own + // routing). `LELEKA_ORIGINAL_SERVE_SEED=off` restores the plain profile start. + config.seed_swaps = super::original_serve_seed::DEFAULT_SEED_SWAPS; + if let Some(v) = var("SEED") { + config.seed_swaps = match v.as_str() { + "off" | "no" | "0" => 0, + "on" | "yes" => super::original_serve_seed::DEFAULT_SEED_SWAPS, + n => n.parse().map_err(|_| Error::InvalidDimension)?, + }; + } + if let Some(v) = var("SEED_KEEP") { + config.seed_keep = v.parse().map_err(|_| Error::InvalidDimension)?; + } + if let Some(v) = var("SEED_USAGE") { + config.seed_usage = v.parse().map_err(|_| Error::InvalidDimension)?; + } + if let Some(v) = var("SEED_DECAY") { + config.seed_decay = v.parse().map_err(|_| Error::InvalidDimension)?; + } + if let Some(v) = var("SEED_MAX_ROWS") { + config.seed_max_rows = v.parse().map_err(|_| Error::InvalidDimension)?; + } + config.validate()?; + Ok(config) + } +} + +/// One window group's split: the GPU plan, the kind of every entry (-2 skipped by the route tail skip, -1 CPU, 0 VRAM, +/// 1 PCIe) and the expert of every PCIe group (staging slot order). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(in crate::qwen_forward) struct GroupSplit { + pub(in crate::qwen_forward) plan: OriginalVerifyGpuPlan, + pub(in crate::qwen_forward) kinds: Vec, + pub(in crate::qwen_forward) pcie_experts: Vec, + /// Distinct experts the route tail skip left out (their entries are kind -2). + pub(in crate::qwen_forward) skipped_experts: usize, +} + +/// expert_source.cpp `expert_pool_dispatch_multi`, the GPU share: `ids` are the group's `rows * k` routed +/// ids, `resident(e)` the VRAM slot of expert `e` of this layer, `pcie_num` the PCIe share in 256ths (0: no +/// PCIe), `staging` the group's staging blobs. `cap` is the window's plan capacity (`max_t * k`). +#[cfg(test)] +pub(in crate::qwen_forward) fn split_group( + ids: &[i32], + k: usize, + cap: usize, + resident: impl Fn(u32) -> Option, + pcie_num: u32, + staging: usize, +) -> Result { + split_group_tail(ids, k, cap, resident, pcie_num, staging, 0) +} + +/// `split_group` with the route tail skip: `tail_rank > 0` (1..k) leaves out every missed expert whose best rank over the +/// entries that route it is at least `tail_rank` (expert_source.cpp `STRATA_ROUTE_TAIL_SKIP`); its entries are kind -2: not +/// in the plan, not staged, not computed. They are taken out of the miss count before the PCIe share is rounded. +pub(in crate::qwen_forward) fn split_group_tail( + ids: &[i32], + k: usize, + cap: usize, + resident: impl Fn(u32) -> Option, + pcie_num: u32, + staging: usize, + tail_rank: u32, +) -> Result { + split_group_pcie(ids, k, cap, resident, pcie_num, staging, tail_rank, |_| true) +} + +/// `split_group_tail` with a say in which misses may take the PCIe share: only an expert `pcie_ok` accepts is staged, the share +/// is still `nmiss * pcie_num >> 8` of ALL the misses but capped by the number that are eligible, and it is the last eligible +/// misses in routing order. `|_| true` is the unrestricted split. The pageable file-mapped bank uses it to keep PCIe to experts +/// whose pages are page-locked (`LELEKA_PCIE_LOCKED_ONLY`): a copy out of pageable pages is staged by the driver on the calling +/// thread, which is the thread that drives the whole window. +#[allow(clippy::too_many_arguments)] +pub(in crate::qwen_forward) fn split_group_pcie( + ids: &[i32], + k: usize, + cap: usize, + resident: impl Fn(u32) -> Option, + pcie_num: u32, + staging: usize, + tail_rank: u32, + pcie_ok: impl Fn(u32) -> bool, +) -> Result { + let n = ids.len(); + if k == 0 || n == 0 || n % k != 0 || n > MAX_WINDOW_ENTRIES || n > cap || pcie_num > 256 { + return Err(Error::InvalidDimension); + } + let valid = |e: i32| (0..EXPERTS as i32).contains(&e); + // first_of[i]: the first entry with the same id; distinct: the first entries in routing order + let mut first_of = vec![0usize; n]; + let mut distinct = Vec::with_capacity(n); + let mut nmiss = 0usize; + for i in 0..n { + first_of[i] = (0..i).find(|&j| ids[j] == ids[i]).map_or(i, |j| first_of[j]); + if first_of[i] == i { + distinct.push(i); + if valid(ids[i]) && resident(ids[i] as u32).is_none() { + nmiss += 1; + } + } + } + // the route tail skip: a missed expert no token of the window routes above rank `tail_rank` is dropped + let mut skip = vec![false; n]; + let mut skipped_experts = 0usize; + if tail_rank > 0 { + let mut best = vec![usize::MAX; n]; + for i in 0..n { + best[first_of[i]] = best[first_of[i]].min(i % k); + } + for &i0 in &distinct { + if valid(ids[i0]) && resident(ids[i0] as u32).is_none() && best[i0] >= tail_rank as usize { + skip[i0] = true; + skipped_experts += 1; + nmiss -= 1; + } + } + } + let mut m = if pcie_num > 0 { (nmiss * pcie_num as usize) >> 8 } else { 0 }; + // the misses that may be staged (all of them unless the caller restricts the share) + let eligible = distinct.iter().filter(|&&i0| !skip[i0] && valid(ids[i0]) && resident(ids[i0] as u32).is_none() && pcie_ok(ids[i0] as u32)).count(); + m = m.min(eligible); + let mut eligible_rank = 0usize; + let mut kinds = vec![-1i8; n]; + let mut plan = OriginalVerifyGpuPlan::new(); + let mut pcie_groups: Vec> = Vec::new(); + let mut pcie_experts = Vec::new(); + for &i0 in &distinct { + let e = ids[i0]; + let mut kind = -1i8; + let mut slot = None; + if skip[i0] { + kind = -2; + } else if valid(e) { + match resident(e as u32) { + Some(s) => { + kind = 0; + slot = Some(s); + } + None => { + if pcie_ok(e as u32) { + if eligible_rank >= eligible - m && pcie_groups.len() < staging && pcie_groups.len() < ORIGINAL_VERIFY_MAX_PCIE_FETCHES { + kind = 1; + } + eligible_rank += 1; + } + } + } + } + let members: Vec = (i0..n).filter(|&i| first_of[i] == i0).map(|i| i as u16).collect(); + for &i in &members { + kinds[usize::from(i)] = kind; + } + match (kind, slot) { + (0, Some(s)) => plan.push_vram(s, members), + (1, _) => { + pcie_groups.push(members); + pcie_experts.push(e as u32); + } + _ => {} + } + } + for members in pcie_groups { + plan.push_pcie(members); + } + Ok(GroupSplit { plan, kinds, pcie_experts, skipped_experts }) +} + +/// One adaptive swap: in layer `layer`, expert `incoming` takes the slot of `outgoing`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::qwen_forward) struct Swap { + pub(in crate::qwen_forward) gain: f32, + pub(in crate::qwen_forward) layer: usize, + pub(in crate::qwen_forward) incoming: usize, + pub(in crate::qwen_forward) outgoing: usize, +} + +/// `LELEKA_PCIE_LOCKED_ONLY=on|1` (read once): over a pageable file-mapped bank only the experts whose pages `pin_resident` locked may +/// take the PCIe share; every other miss stays with the CPU pool. Off by default (the unrestricted split). +pub(in crate::qwen_forward) fn pcie_locked_only() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("LELEKA_PCIE_LOCKED_ONLY").is_ok_and(|v| v == "on" || v == "1")) +} + +/// Experiment knobs of the adaptive tier (claude/decode-parity; the defaults are generate.cpp's constants): +/// `LELEKA_ADAPT_MIN_COUNT` (2.0: the least routed count a missing expert needs to be swapped in), +/// `LELEKA_ADAPT_MARGIN` (1.5: the count lead over the victim), `LELEKA_ADAPT_DECAY` (0.7: counts decay per adaptation). +fn adapt_tuning() -> (f32, f32, f32) { + static TUNING: std::sync::OnceLock<(f32, f32, f32)> = std::sync::OnceLock::new(); + *TUNING.get_or_init(|| { + let var = |name: &str, default: f32| std::env::var(name).ok().and_then(|v| v.parse::().ok()).filter(|v| v.is_finite()).unwrap_or(default); + (var("LELEKA_ADAPT_MIN_COUNT", 2.0), var("LELEKA_ADAPT_MARGIN", 1.5), var("LELEKA_ADAPT_DECAY", 0.7)) + }) +} + +/// generate.cpp `adapt`'s ranking over `usage[l * 512 + e]`: per layer the non-resident experts routed at +/// least twice (most first) against the resident ones (least first), pairwise while +/// `cand >= vict + 1.5`; all layers' swaps by gain, the best `max_swaps`. Ties keep ascending expert / layer +/// order (`std::sort` leaves tie order unspecified). +pub(in crate::qwen_forward) fn choose_swaps(usage: &[f32], resident: impl Fn(usize, usize) -> bool, max_swaps: usize) -> Vec { + let (min_count, margin, _) = adapt_tuning(); + let mut swaps = Vec::new(); + if usage.len() != LAYERS * EXPERTS { + return swaps; + } + let mut cand: Vec<(f32, usize)> = Vec::with_capacity(EXPERTS); + let mut vict: Vec<(f32, usize)> = Vec::with_capacity(EXPERTS); + for layer in 0..LAYERS { + let u = &usage[layer * EXPERTS..(layer + 1) * EXPERTS]; + cand.clear(); + vict.clear(); + for (e, &value) in u.iter().enumerate() { + if !resident(layer, e) { + if value >= min_count { + cand.push((value, e)); + } + } else { + vict.push((value, e)); + } + } + if cand.is_empty() || vict.is_empty() { + continue; + } + cand.sort_by(|a, b| b.0.total_cmp(&a.0)); + // Only as many victims as there are candidates can pair. The stable sort by value of experts pushed in ascending order is the order + // by (value, expert): selecting the `m` least of that total order and sorting only those gives the same first `m` without sorting all residents. + let m = cand.len().min(vict.len()); + let by_value_then_expert = |a: &(f32, usize), b: &(f32, usize)| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)); + if m < vict.len() { + vict.select_nth_unstable_by(m - 1, by_value_then_expert); + vict.truncate(m); + } + vict.sort_by(by_value_then_expert); + for (c, v) in cand.iter().zip(&vict) { + if c.0 < v.0 + margin { + break; + } + swaps.push(Swap { gain: c.0 - v.0, layer, incoming: c.1, outgoing: v.1 }); + } + } + swaps.sort_by(|a, b| b.gain.total_cmp(&a.gain)); + swaps.truncate(max_swaps); + swaps +} + +/// The earlier implementation (full sorts), kept to prove the faster one picks exactly the same swaps in the same order. +#[cfg(test)] +fn choose_swaps_reference(usage: &[f32], resident: impl Fn(usize, usize) -> bool, max_swaps: usize) -> Vec { + let (min_count, margin, _) = adapt_tuning(); + let mut swaps = Vec::new(); + if usage.len() != LAYERS * EXPERTS { + return swaps; + } + for layer in 0..LAYERS { + let u = &usage[layer * EXPERTS..(layer + 1) * EXPERTS]; + let mut cand: Vec<(f32, usize)> = Vec::new(); + let mut vict: Vec<(f32, usize)> = Vec::new(); + for (e, &value) in u.iter().enumerate() { + if !resident(layer, e) { + if value >= min_count { + cand.push((value, e)); + } + } else { + vict.push((value, e)); + } + } + if cand.is_empty() || vict.is_empty() { + continue; + } + cand.sort_by(|a, b| b.0.total_cmp(&a.0)); + vict.sort_by(|a, b| a.0.total_cmp(&b.0)); + for (c, v) in cand.iter().zip(&vict) { + if c.0 < v.0 + margin { + break; + } + swaps.push(Swap { gain: c.0 - v.0, layer, incoming: c.1, outgoing: v.1 }); + } + } + swaps.sort_by(|a, b| b.gain.total_cmp(&a.gain)); + swaps.truncate(max_swaps); + swaps +} + +/// Counters of the tier (the Original's `R4 expert-cache hits` / `adaptive tier` report lines). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct ResidencyStats { + pub(crate) groups: u64, + pub(crate) vram_entries: u64, + pub(crate) pcie_entries: u64, + pub(crate) cpu_entries: u64, + pub(crate) adaptations: u64, + pub(crate) swaps: u64, + /// Route tail skip (experimental): entries and distinct experts left out. + pub(crate) tail_entries: u64, + pub(crate) tail_experts: u64, +} +impl ResidencyStats { + pub(crate) fn describe(&self) -> String { + let all = (self.vram_entries + self.pcie_entries + self.cpu_entries).max(1) as f64; + let tail = if self.tail_entries > 0 { format!(", route tail skip {} entries / {} experts", self.tail_entries, self.tail_experts) } else { String::new() }; + format!( + "expert tier: {} layer groups, entries vram {} ({:.1}%) pcie {} ({:.1}%) cpu {} ({:.1}%), {} adaptations, {} swaps{}", + self.groups, + self.vram_entries, + 100.0 * self.vram_entries as f64 / all, + self.pcie_entries, + 100.0 * self.pcie_entries as f64 / all, + self.cpu_entries, + 100.0 * self.cpu_entries as f64 / all, + self.adaptations, + self.swaps, + tail + ) + } +} + +/// The registered source spans (gate, up, down) of routed experts by (layer, expert), kept for the life of the stack: +/// the mapped bank never moves, so a span set found once (the per-call scan through the binding costs 30-70 us) is +/// the span set of every later PCIe stage, adaptive swap and lent-slot refill of that expert. +/// `LELEKA_SPAN_CACHE=off` looks every set up again (A/B control). +#[derive(Default)] +pub(crate) struct SpanCache { + sets: std::collections::HashMap, +} +impl std::fmt::Debug for SpanCache { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "SpanCache({} sets)", self.sets.len()) + } +} +fn span_cache_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("LELEKA_SPAN_CACHE").is_ok_and(|v| v == "off" || v == "0")) +} +impl SpanCache { + fn key(layer: usize, expert: u32) -> u32 { + (layer * EXPERTS) as u32 + expert + } + fn get(&self, layer: usize, expert: u32) -> Option<[ResidentExpertBankSpan; 3]> { + self.sets.get(&Self::key(layer, expert)).cloned() + } + fn contains(&self, layer: usize, expert: u32) -> bool { + self.sets.contains_key(&Self::key(layer, expert)) + } + fn insert(&mut self, layer: usize, expert: u32, spans: [ResidentExpertBankSpan; 3]) { + self.sets.insert(Self::key(layer, expert), spans); + } +} + +/// `LELEKA_PCIE_AUTO=lag` (claude/decode-parity): equalises the two legs of a layer's miss phase. After the CPU pool has +/// computed its share the host looks at flag B (the PCIe copies landed?) and, when they have not, spins until they do: +/// that wait is how much longer the PCIe leg took than the CPU leg (the host would wait for the GPU there anyway, so the +/// measurement costs nothing). Per round the mean lag drives the share in 256ths: a PCIe leg that finishes last lowers +/// it, a PCIe leg that finishes first (no lag at all) raises it a little, probing for the point where they meet. Only the +/// split changes, never what an expert computes. +#[derive(Debug)] +pub(crate) struct PcieLag { + num: u32, + lag_us: f64, + groups: u32, + ema_us: Option, + rounds_since_up: u32, +} +impl PcieLag { + const MIN: u32 = 32; + const MAX: u32 = 176; + const WAIT: std::time::Duration = std::time::Duration::from_millis(3); + pub(crate) fn from_environment(start_num: u32) -> Option { + if !std::env::var("LELEKA_PCIE_AUTO").is_ok_and(|v| v == "lag") || start_num == 0 { + return None; + } + Some(Self { num: start_num.clamp(Self::MIN, Self::MAX), lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }) + } + pub(crate) fn pcie_num(&self) -> u32 { + self.num + } + /// One group with PCIe experts: how long after the CPU leg the copies landed (spins until then, bounded). + pub(crate) fn measure(&mut self, landed: impl Fn() -> bool) { + let started = std::time::Instant::now(); + while !landed() { + if started.elapsed() > Self::WAIT { + break; + } + std::hint::spin_loop(); + } + self.lag_us += started.elapsed().as_secs_f64() * 1e6; + self.groups += 1; + } + /// Round boundary: move the share by the round's mean lag per measured group. + pub(crate) fn round(&mut self) { + let (lag, groups) = (std::mem::take(&mut self.lag_us), std::mem::take(&mut self.groups)); + if groups < 8 { + return; + } + let mean = lag / f64::from(groups); + let ema = self.ema_us.map_or(mean, |old| 0.6 * old + 0.4 * mean); + self.ema_us = Some(ema); + self.rounds_since_up += 1; + if ema > 25.0 { + self.num = self.num.saturating_sub(if ema > 120.0 { 10 } else { 5 }).max(Self::MIN); + self.rounds_since_up = 0; + } else if ema < 4.0 && self.rounds_since_up >= 3 { + self.num = (self.num + 3).min(Self::MAX); + self.rounds_since_up = 0; + } + } +} + +/// `LELEKA_PCIE_AUTO=on` (claude/decode-parity): a hill-climbing controller of the PCIe share. The static share is a +/// balance between the PCIe leg and the CPU pool of a layer, and the best value moves with the staging mode, the link and +/// the hit rate. Rounds are timed from one `apply_pending` to the next; the cost of a round is its time per +/// (misses + 40) entries (the entries the PCIe/CPU legs carry, plus a floor for the fixed work). Levels are shares in 256ths; +/// every `EXPLORE_EVERY` rounds the neighbours of the incumbent are tried for `TRIAL` rounds each and the cheaper one (by +/// EMA) becomes the incumbent. Only the split changes, never what an expert computes. +#[derive(Debug)] +pub(crate) struct PcieAuto { + levels: Vec, + ema: Vec>, + incumbent: usize, + trying: usize, + left: u32, + since_explore: u32, + next_probe_up: bool, + last: Option, + misses: u64, +} +impl PcieAuto { + const TRIAL: u32 = 6; + const EXPLORE_EVERY: u32 = 30; + pub(crate) fn from_environment(start_num: u32) -> Option { + if !std::env::var("LELEKA_PCIE_AUTO").is_ok_and(|v| v == "on") || start_num == 0 { + return None; + } + let levels: Vec = (2..=10).map(|i| i * 16).collect(); // 0.125 .. 0.625 + let incumbent = levels.iter().enumerate().min_by_key(|(_, l)| l.abs_diff(start_num)).map_or(0, |(i, _)| i); + Some(Self { + ema: vec![None; levels.len()], + levels, + incumbent, + trying: incumbent, + left: Self::TRIAL, + since_explore: 0, + next_probe_up: false, + last: None, + misses: 0, + }) + } + pub(crate) fn pcie_num(&self) -> u32 { + self.levels[self.trying] + } + pub(crate) fn add_misses(&mut self, n: usize) { + self.misses += n as u64; + } + /// Round boundary: score the round that just ended under `trying`, then pick the level of the next one. + pub(crate) fn round(&mut self) { + let now = std::time::Instant::now(); + let ended = self.last.replace(now); + let misses = std::mem::take(&mut self.misses); + let Some(then) = ended else { return }; + if misses == 0 { + return; + } + let cost = now.duration_since(then).as_secs_f64() * 1e3 / (misses as f64 + 40.0 * 48.0); + let slot = &mut self.ema[self.trying]; + *slot = Some(slot.map_or(cost, |old| 0.7 * old + 0.3 * cost)); + self.left = self.left.saturating_sub(1); + self.since_explore += 1; + if self.trying != self.incumbent { + if self.left == 0 { + // the trial ended: keep the cheaper of the two + let (a, b) = (self.ema[self.trying].unwrap_or(f64::MAX), self.ema[self.incumbent].unwrap_or(f64::MAX)); + if a < b { + self.incumbent = self.trying; + } + self.trying = self.incumbent; + self.left = 0; + } + } else if self.since_explore >= Self::EXPLORE_EVERY { + self.since_explore = 0; + let target = if self.next_probe_up { self.incumbent + 1 } else { self.incumbent.wrapping_sub(1) }; + self.next_probe_up = !self.next_probe_up; + if target < self.levels.len() { + self.ema[target] = None; + self.trying = target; + self.left = Self::TRIAL; + } + } + } +} + +/// What survives requests: the routed counts of the adaptive tier (`drive.d.usage`) and the counters. +#[derive(Debug, Default)] +pub(crate) struct ResidencyState { + usage: Vec, + pub(crate) stats: ResidencyStats, + /// generate.cpp `--dump-routing FILE` (`LELEKA_ORIGINAL_SERVE_DUMP_ROUTING`): every decode window row's routed + /// experts, as `tools/make_profile.py` reads them (layer i32, k i32, k ids i32, k weights f32). + routing: Option>, + /// Cumulative (vram, pcie, cpu) window entries after each verified round of the current request (for the first-rounds + /// hit rates; recorded where the adaptive tier is asked for its round). + marks: Vec<[u64; 3]>, + /// The counters when the current request began. + mark_base: [u64; 3], + pub(crate) spans: SpanCache, + pub(crate) pcie_auto: Option, + pub(crate) pcie_lag: Option, + pcie_auto_checked: bool, +} +impl ResidencyState { + pub(crate) fn new(config: &ExpertTierConfig) -> Self { + let routing = std::env::var_os("LELEKA_ORIGINAL_SERVE_DUMP_ROUTING") + .and_then(|path| std::fs::File::create(path).ok()) + .map(std::io::BufWriter::new); + Self { + usage: if config.adaptive() { vec![0.0; LAYERS * EXPERTS] } else { Vec::new() }, + stats: ResidencyStats::default(), + routing, + pcie_auto: None, + pcie_lag: None, + pcie_auto_checked: false, + marks: Vec::new(), + mark_base: [0; 3], + spans: SpanCache::default(), + } + } + /// A new request: the per-round marks start over (the counters and the adaptive counts survive). + pub(crate) fn begin_request(&mut self) { + self.marks.clear(); + self.mark_base = [self.stats.vram_entries, self.stats.pcie_entries, self.stats.cpu_entries]; + } + /// Cumulative (vram, pcie, cpu) entries after each round of the last request, from the request's own start. + pub(crate) fn round_marks(&self) -> Vec<[u64; 3]> { + self.marks.iter().map(|m| [m[0] - self.mark_base[0], m[1] - self.mark_base[1], m[2] - self.mark_base[2]]).collect() + } + /// The adaptive tier's routed counts (`layer * 512 + expert`; empty when the tier is off). + pub(crate) fn usage(&self) -> &[f32] { + &self.usage + } + /// A fresh adaptive history: the routed counts start empty (the experiments' first-request state). + pub(crate) fn clear_usage(&mut self) { + self.usage.iter_mut().for_each(|v| *v = 0.0); + } + /// Add `scale * counts` (`layer * 512 + expert`) to the adaptive tier's routed counts (no-op when it is off). + pub(crate) fn add_usage(&mut self, counts: &[f32], scale: f32) { + if self.usage.len() == counts.len() && scale > 0.0 { + for (u, &c) in self.usage.iter_mut().zip(counts) { + *u += scale * c; + } + } + } + /// Write the buffered routing records out (end of a request). + pub(crate) fn flush_routing(&mut self) { + if let Some(routing) = self.routing.as_mut() { + let _ = std::io::Write::flush(routing); + } + } + fn record_routing(&mut self, layer: usize, ids: &[i32], weights: &[f32]) { + let Some(routing) = self.routing.as_mut() else { return }; + if ids.len() != weights.len() { + return; + } + let mut record = Vec::with_capacity(8 + 8 * TOP_K); + for (row, w) in ids.chunks_exact(TOP_K).zip(weights.chunks_exact(TOP_K)) { + record.clear(); + record.extend_from_slice(&(layer as i32).to_le_bytes()); + record.extend_from_slice(&(TOP_K as i32).to_le_bytes()); + row.iter().for_each(|e| record.extend_from_slice(&e.to_le_bytes())); + w.iter().for_each(|x| record.extend_from_slice(&x.to_le_bytes())); + let _ = std::io::Write::write_all(routing, &record); + } + } +} + +/// The window pool with the VRAM tier: the GPU share of every group published first, the CPU pool on the +/// rest. Lives for one decode phase; borrows the stack's cache, CPU pool and persistent state. +pub(in crate::qwen_forward) struct GpuExpertPool<'p, 'a, 'ctx> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) moe: &'p MoeWeightCache<'ctx>, + pub(in crate::qwen_forward) cache: &'p mut OriginalExpertCache<'ctx>, + pub(in crate::qwen_forward) bank: Rc>, + pub(in crate::qwen_forward) cpu: &'p mut CpuExpertPool<'a>, + pub(in crate::qwen_forward) state: &'p mut ResidencyState, + pub(in crate::qwen_forward) pcie_num: u32, + pub(in crate::qwen_forward) adapt_every: u32, + pub(in crate::qwen_forward) adapt_swaps: usize, + /// The route tail skip rank of this decode phase (0 = off; `effective_tail_rank`). + pub(in crate::qwen_forward) tail_rank: u32, + /// `layer * 512 + expert` -> the expert's pages are page-locked (`MappedExpertBank::locked_experts`); empty = every expert may + /// take the PCIe share. Filled only under `LELEKA_PCIE_LOCKED_ONLY` on a pageable bank. + pub(in crate::qwen_forward) pcie_locked: Vec, +} +impl GpuExpertPool<'_, '_, '_> { + fn source_spans(&mut self, layer: usize, experts: &[u32]) -> Result> { + source_spans(&mut *self.cpu, &self.bank, self.moe, self.binding, &mut self.state.spans, layer, experts) + } +} +/// The source spans of `experts` of `layer`, in order: from the cache when seen before, else through the CPU +/// tier's admission (or the binding's own scan on the legacy path) and remembered. +pub(super) fn source_spans( + cpu: &mut CpuExpertPool<'_>, + bank: &MappedExpertBank<'_>, + moe: &MoeWeightCache<'_>, + binding: &ModelBinding, + known: &mut SpanCache, + layer: usize, + experts: &[u32], +) -> Result> { + { + let cached = span_cache_enabled(); + let fetch: Vec = if cached { + experts.iter().copied().filter(|&e| !known.contains(layer, e)).collect() + } else { + experts.to_vec() + }; + let mut fetched: Vec<[ResidentExpertBankSpan; 3]> = Vec::new(); + fetched.try_reserve_exact(fetch.len()).map_err(|_| Error::InputAllocation)?; + if !fetch.is_empty() { + // The direct CPU tier's admission (one fence per group, rows scanned once per expert) serves the + // PCIe sources too; the legacy path keeps the per-expert full scan. + match cpu.admitted_spans(layer as u32, &fetch) { + Some(admitted) => { + for spans_of in admitted? { + if !bank.eligible(&spans_of) { + return Err(Error::IdentityMismatch); + } + fetched.push(spans_of); + } + } + None => { + for &e in &fetch { + fetched.push(moe.original_expert_spans(binding, layer as u32, e)?); + } + } + } + } + if !cached { + return Ok(fetched); + } + for (&e, spans_of) in fetch.iter().zip(fetched) { + known.insert(layer, e, spans_of); + } + let mut spans = Vec::new(); + spans.try_reserve_exact(experts.len()).map_err(|_| Error::InputAllocation)?; + for &e in experts { + spans.push(known.get(layer, e).ok_or(Error::IdentityMismatch)?); + } + Ok(spans) + } +} +impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { + fn run_group( + &mut self, + rows: OriginalVerifyCpuRows<'_>, + sink: &mut OriginalVerifyCpuSink<'_, 'ctx>, + copy: &mut OriginalGpuStream<'ctx>, + ) -> Result<()> { + let layer = rows.layer; + if layer >= LAYERS || rows.ids.is_empty() || rows.ids.len() % TOP_K != 0 { + return Err(Error::InvalidDimension); + } + let mut clock = super::original_serve_pool::window_trace::now(); + self.state.record_routing(layer, rows.ids, rows.route_weights); + if !self.state.usage.is_empty() { + for &e in rows.ids { + if (0..EXPERTS as i32).contains(&e) { + self.state.usage[layer * EXPERTS + e as usize] += 1.0; + } + } + } + let profile_split = super::original_serve_profile::span("pool.split"); + let cache = &*self.cache; + let locked = &self.pcie_locked; + let split = split_group_pcie( + rows.ids, + TOP_K, + sink.plan_capacity(), + |e| cache.resident_slot(layer, e as usize), + self.state.pcie_lag.as_ref().map(PcieLag::pcie_num).or_else(|| self.state.pcie_auto.as_ref().map(PcieAuto::pcie_num)).unwrap_or(self.pcie_num), + sink.staging_capacity(), + self.tail_rank, + |e| locked.is_empty() || locked.get(layer * EXPERTS + e as usize).copied().unwrap_or(false), + )?; + if let Some(auto) = self.state.pcie_auto.as_mut() { + auto.add_misses(split.kinds.iter().filter(|&&k| k == -1 || k == 1).count()); + } + super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock); + drop(profile_split); + let profile_spans = super::original_serve_profile::span("pool.spans"); + let spans = source_spans(&mut *self.cpu, &self.bank, self.moe, self.binding, &mut self.state.spans, layer, &split.pcie_experts)?; + super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::PCIE_SPANS, &mut clock); + super::original_serve_pool::window_trace::add(super::original_serve_pool::window_trace::PCIE_EXPERTS, split.pcie_experts.len() as f64); + drop(profile_spans); + let profile_publish = super::original_serve_profile::span("pool.publish_plan"); + let pcie = (self.pcie_num > 0).then_some(OriginalVerifyPcieSource { bank: &self.bank, spans: &spans }); + sink.publish_gpu_plan(&split.plan, cache, pcie, copy).map_err(|e| driver_error(&e))?; + drop(profile_publish); + // only the CPU's own entries are computed; the GPU's and the skipped ones are written as zeros (the window's copy kernel + // takes a skipped entry from the mapped sink, so its zero row is its contribution) + let include: Vec = split.kinds.iter().map(|&k| k == -1).collect(); + let stats = &mut self.state.stats; + stats.groups += 1; + stats.tail_experts += split.skipped_experts as u64; + for &kind in &split.kinds { + match kind { + 0 => stats.vram_entries += 1, + 1 => stats.pcie_entries += 1, + -2 => stats.tail_entries += 1, + _ => stats.cpu_entries += 1, + } + } + if self.cpu.lookahead_running() && layer + 1 < LAYERS { + let next = layer + 1; + self.cpu.set_next_resident(|e| cache.resident_slot(next, e).is_some()); + } + super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock); + let _p = super::original_serve_profile::span("pool.cpu"); + let ran = self.cpu.run_entries(rows, sink, Some(&include)); + if ran.is_ok() && !split.pcie_experts.is_empty() { + if let Some(lag) = self.state.pcie_lag.as_mut() { + lag.measure(|| sink.copies_landed().unwrap_or(true)); + } + } + ran + } + fn apply_pending(&mut self) -> Result<()> { + if !self.state.pcie_auto_checked { + self.state.pcie_auto_checked = true; + self.state.pcie_auto = PcieAuto::from_environment(self.pcie_num); + self.state.pcie_lag = PcieLag::from_environment(self.pcie_num); + } + if let Some(auto) = self.state.pcie_auto.as_mut() { + auto.round(); + } + if let Some(lag) = self.state.pcie_lag.as_mut() { + lag.round(); + } + // The swaps issued beside the previous commit land before this window (`apply_pending(true)`): their copies + // would otherwise read host memory while the CPU pool streams its experts (job 803: the overlap costs the CPU + // share more than the wait), and the resident set no longer depends on when the copies finished. + // LELEKA_SERVE_SWAP_WAIT=off polls instead (generate.cpp `apply_pending(false)`). + if swap_wait() { + return self.cache.wait_swaps().map_err(|e| driver_error(&e)); + } + self.cache.poll_swaps().map(|_| ()).map_err(|e| driver_error(&e)) + } + fn begin_adaptation(&mut self, next_round: u64) -> Result<()> { + let stats = self.state.stats; + self.state.marks.push([stats.vram_entries, stats.pcie_entries, stats.cpu_entries]); + if self.state.usage.is_empty() || self.adapt_every == 0 || next_round % u64::from(self.adapt_every) != 0 { + return Ok(()); + } + // `if (!pending.empty()) return true;`: the previous swaps are still in flight (no decay either) + if self.cache.swaps_pending() { + return Ok(()); + } + let cache = &*self.cache; + let p = super::original_serve_profile::span("adapt.choose"); + let swaps = choose_swaps(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some(), self.adapt_swaps); + drop(p); + let p = super::original_serve_profile::span("adapt.queue"); + for swap in &swaps { + let slot = self.cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?; + let spans = self.source_spans(swap.layer, &[swap.incoming as u32])?.pop().ok_or(Error::IdentityMismatch)?; + self.cache.swap_slot_queued(slot, Rc::clone(&self.bank), spans).map_err(|e| driver_error(&e))?; + } + drop(p); + let p = super::original_serve_profile::span("adapt.arm"); + self.cache.arm_swaps().map_err(|e| driver_error(&e))?; + drop(p); + let _p = super::original_serve_profile::span("adapt.decay"); + let decay = adapt_tuning().2; + for value in &mut self.state.usage { + *value *= decay; + } + self.state.stats.adaptations += 1; + self.state.stats.swaps += swaps.len() as u64; + Ok(()) + } +} + +/// `LELEKA_SERVE_SWAP_WAIT=off`: poll the adaptive swaps at a round start instead of waiting for them. +fn swap_wait() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("LELEKA_SERVE_SWAP_WAIT").is_ok_and(|v| v == "off" || v == "0")) +} + +/// generate.cpp startup of the tier for the serve stack: size and open the cache after every other owner, +/// fill it from the profile through the registered bank (blocking, rank order; per-layer skips a full +/// layer's pairs, global stops at the first refusal) and read slot 0 back. `None`: the tier is off or no +/// slot fits. +pub(in crate::qwen_forward) fn open_tier<'ctx>( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + moe: &MoeWeightCache<'ctx>, + config: &ExpertTierConfig, + prefill_capacity: usize, +) -> Result, usize)>> { + config.validate()?; + if !config.enabled() { + return Ok(None); + } + let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?; + let profile = match &config.profile { + Some(path) => Some(OriginalRankedExperts::read(path, binding)?), + None => None, + }; + let options = OriginalCacheOptions { + slots: config.effective_slots(), + reserve_mib: config.reserve_mib.checked_add(config.decode_reserve_mib).ok_or(Error::Overflow)?, + prefill_capacity, + prefill_borrow: config.prefill_borrow && profile.is_some(), + per_layer: config.per_layer, + }; + // The MTP head is bound before the cache in this stack: nothing pending to reserve for it. + let Some(mut cache) = original_cache_startup::open(binding, context, options, profile.as_ref(), 0)? else { + return Ok(None); + }; + let mut filled = 0usize; + if let Some(profile) = profile.as_ref().filter(|p| !p.is_empty()) { + let per_layer = cache.per_layer_admission(); + let want = if per_layer { profile.pairs().len() } else { profile.pairs().len().min(cache.slots()) }; + for &(layer, expert) in &profile.pairs()[..want] { + let slot = cache.admit(usize::from(layer), usize::from(expert)).map_err(|e| driver_error(&e))?; + if slot < 0 { + if per_layer { + continue; + } + break; + } + let spans = moe.original_expert_spans(binding, u32::from(layer), u32::from(expert))?; + cache.fill_slot_blocking(slot as usize, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?; + filled += 1; + } + if filled > 0 { + let (layer, expert) = profile.pairs()[0]; + let slot = usize::try_from(cache.slot_of(usize::from(layer), usize::from(expert))).map_err(|_| Error::IdentityMismatch)?; + let spans = moe.original_expert_spans(binding, u32::from(layer), u32::from(expert))?; + cache.verify_slot(slot, &bank, &spans).map_err(|e| driver_error(&e))?; + } + if config.resident_budget_gib > 0.0 && bank.pageable() { + pin_resident_complement(&bank, &cache, profile, config.resident_budget_gib)?; + } + } + Ok(Some((cache, filled))) +} + +/// generate.cpp `--resident-budget-gib N` over the low-RAM (file-mapped) bank: the experts the VRAM cache does +/// not hold, in profile order, page-locked in RAM while they fit N GiB, clamped like +/// `FileExpertSource::pin_cache_complement` to `MemAvailable` less the 4 GiB headroom and a 0.25 GiB margin. +fn pin_resident_complement( + bank: &leleka_cuda_driver::MappedExpertBank<'_>, + cache: &OriginalExpertCache<'_>, + profile: &OriginalRankedExperts, + budget_gib: f64, +) -> Result<()> { + const GIB: f64 = 1_073_741_824.0; + #[cfg(not(target_os = "windows"))] + let meminfo = std::fs::read_to_string("/proc/meminfo"); + // Windows: the same text, rendered from GlobalMemoryStatusEx by leleka-memory. + #[cfg(target_os = "windows")] + let meminfo = { + use leleka_memory::ProcSource; + leleka_memory::RealProc.read("/proc/meminfo") + }; + let available = meminfo + .ok() + .and_then(|t| { + t.lines() + .find(|l| l.starts_with("MemAvailable:")) + .and_then(|l| l.split_ascii_whitespace().nth(1)?.parse::().ok()) + }) + .map_or(0, |kib| kib * 1024); + // the governor's soft floor + reserve (4 GiB headroom and a 0.25 GiB margin without one) + let room = crate::memory_governor::complement_room(available); + let budget = ((budget_gib * GIB) as u64).min(room); + let ranked: Vec<(u8, u32)> = profile + .pairs() + .iter() + .filter(|&&(layer, expert)| cache.slot_of(usize::from(layer), usize::from(expert)) < 0) + .map(|&(layer, expert)| (layer as u8, u32::from(expert))) + .collect(); + let started = std::time::Instant::now(); + match bank.pin_resident(&ranked, budget) { + Ok((held, bytes)) => eprintln!( + "leleka-serve: resident RAM budget {:.2} GiB (asked {budget_gib:.2}, {:.2} GiB available): {held} experts the \ + VRAM cache does not hold page-locked by profile rank ({:.2} GiB) in {:.1} s; the rest read from the file", + budget as f64 / GIB, + available as f64 / GIB, + bytes as f64 / GIB, + started.elapsed().as_secs_f64() + ), + // #403: a budget that cannot be kept is a warning; every miss is read from the file pages instead + Err(e) => eprintln!("leleka-serve: WARNING: the resident RAM budget cannot be kept ({e:?}); experts are read from the file"), + } + Ok(()) +} + +/// The serve stack's loan test (generate.cpp `fits_one`, fixed chunk): the prompt path's buffers for the +/// configured chunk come from the cache's last `k` slots when `0 < k` and `k + 128 <= slots`. Unlike the +/// Original the chunk is not halved to fit: the prompt executor is built for exactly this capacity. +pub(in crate::qwen_forward) fn loan_slots(cache: &OriginalExpertCache<'_>, bytes_needed: usize) -> Result> { + let k = cache.lend_slots(bytes_needed).map_err(|e| driver_error(&e))?; + Ok((k > 0 && k.checked_add(LOAN_FLOOR).is_some_and(|n| n <= cache.slots())).then_some(k)) +} + +/// generate.cpp `refill`: every lent slot gets its own expert's bytes back from the bank (queued, one wait), +/// so the windows always see the whole cache. Returns the slots refilled. +pub(in crate::qwen_forward) fn refill_lent<'ctx>( + binding: &ModelBinding, + moe: &MoeWeightCache<'ctx>, + cache: &mut OriginalExpertCache<'ctx>, + known: &mut SpanCache, + defer_wait: bool, +) -> Result { + let cached = span_cache_enabled(); + let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?; + let mut refilled = 0usize; + for slot in 0..cache.slots() { + let Some((layer, expert)) = cache.needs_refill(slot).map_err(|e| driver_error(&e))? else { continue }; + let span_spans = super::original_serve_profile::span("refill.spans"); + let spans = match if cached { known.get(layer, expert as u32) } else { None } { + Some(spans) => spans, + None => { + let spans = moe.original_expert_spans(binding, layer as u32, expert as u32)?; + if cached { + known.insert(layer, expert as u32, spans.clone()); + } + spans + } + }; + drop(span_spans); + let _span_queue = super::original_serve_profile::span("refill.queue"); + if defer_wait { + cache.fill_slot_queued_async(slot, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?; + } else { + cache.fill_slot_queued(slot, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?; + } + refilled += 1; + } + if defer_wait { + // the copies run behind the host's assembly of the decode phase; `settle_refill` waits for them before any + // window reads the cache + return Ok(refilled); + } + settle_refill(cache)?; + Ok(refilled) +} + +/// Wait for the refill copies queued by `refill_lent(.., defer_wait = true)` (a no-op when none are queued). +pub(in crate::qwen_forward) fn settle_refill(cache: &mut OriginalExpertCache<'_>) -> Result<()> { + let _span_sync = super::original_serve_profile::span("refill.sync"); + cache.sync_queued().map_err(|e| driver_error(&e)) +} + +/// `LELEKA_REFILL_DEFER=on` (EXPERIMENTAL, off by default): queue the lent-slot refill inside the decode phase's assembly, after +/// its intake uploads and before the graph capture, instead of waiting for it at the end of the prompt phase. Job 902 measured +/// the earlier variant (queued at the end of the prompt phase, waited later) as no gain: the PLE seed upload waited for the same +/// DMA. The current variant has no GPU result yet (job 904), so it stays opt-in. +pub(in crate::qwen_forward) fn refill_defer_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("LELEKA_REFILL_DEFER").is_ok_and(|v| v == "on" || v == "1")) +} + +#[cfg(test)] +mod tests { + #[test] + fn the_selection_based_ranking_picks_the_reference_swaps_in_the_same_order() { + // xorshift: deterministic usage with many ties (small integer counts) and a random resident set per layer + let mut x = 0x9e3779b97f4a7c15u64; + let mut next = move || { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x + }; + for case in 0..40 { + let skew = 1 + case % 7; + let usage: Vec = (0..LAYERS * EXPERTS).map(|_| ((next() % 11) as f32 / skew as f32).floor() + if next() % 5 == 0 { 0.5 } else { 0.0 }).collect(); + let resident_bits: Vec = (0..LAYERS * EXPERTS).map(|_| next() % (2 + (case % 4) as u64) != 0).collect(); + let resident = |l: usize, e: usize| resident_bits[l * EXPERTS + e]; + for max_swaps in [1usize, 5, 96, 4096] { + let fast = choose_swaps(&usage, resident, max_swaps); + let slow = choose_swaps_reference(&usage, resident, max_swaps); + assert_eq!(fast.len(), slow.len(), "case {case} max {max_swaps}"); + for (a, b) in fast.iter().zip(&slow) { + assert_eq!((a.layer, a.incoming, a.outgoing, a.gain.to_bits()), (b.layer, b.incoming, b.outgoing, b.gain.to_bits()), "case {case} max {max_swaps}"); + } + } + } + } + + #[test] + #[ignore = "timing probe: cargo test --release -p leleka-runtime --lib choose_swaps_timing -- --ignored --nocapture"] + fn choose_swaps_timing() { + let mut x = 0x2545f4914f6cdd1du64; + let mut next = move || { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x + }; + let usage: Vec = (0..LAYERS * EXPERTS).map(|_| if next() % 6 == 0 { (next() % 9) as f32 } else { 0.0 }).collect(); + let resident_bits: Vec = (0..LAYERS * EXPERTS).map(|_| next() % 100 < 46).collect(); + let resident = |l: usize, e: usize| resident_bits[l * EXPERTS + e]; + let time = |f: &dyn Fn() -> usize| { + let t = std::time::Instant::now(); + let mut n = 0; + for _ in 0..200 { + n += f(); + } + (t.elapsed().as_secs_f64() * 1e6 / 200.0, n) + }; + let (fast, a) = time(&|| choose_swaps(&usage, resident, 96).len()); + let (slow, b) = time(&|| choose_swaps_reference(&usage, resident, 96).len()); + eprintln!("choose_swaps: new {fast:.0} us, reference {slow:.0} us per call ({a} {b})"); + } + + use super::*; + + fn row(ids: [i32; 10]) -> Vec { + ids.to_vec() + } + + #[test] + fn residents_are_vram_groups_in_routing_order_and_the_rest_is_the_cpus_without_pcie() { + let mut ids = row([5, 1, 9, 2, 3, 4, 6, 7, 8, 0]); + ids.extend(row([9, 5, 11, 12, 13, 14, 15, 16, 17, 18])); + let resident = |e: u32| match e { + 9 => Some(40), + 5 => Some(7), + 17 => Some(3), + _ => None, + }; + let s = split_group(&ids, 10, 80, resident, 0, 16).unwrap(); + // first use order: 5 (entries 0, 11), 9 (2, 10), 17 (18) + assert_eq!(s.plan.vram(), &[(7, vec![0, 11]), (40, vec![2, 10]), (3, vec![18])]); + assert!(s.plan.pcie().is_empty() && s.pcie_experts.is_empty()); + for (i, &kind) in s.kinds.iter().enumerate() { + let want = if [0, 11, 2, 10, 18].contains(&i) { 0 } else { -1 }; + assert_eq!(kind, want, "entry {i}"); + } + assert_eq!(s.plan.entries(), 5); + } + + #[test] + fn the_pcie_share_is_the_last_misses_in_routing_order_capped_by_staging() { + // 10 distinct misses, pcie_frac 0.55 -> pcie_num 141, m = 10 * 141 >> 8 = 5 + let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); + let none = |_: u32| None; + let s = split_group(&ids, 10, 40, none, 141, 16).unwrap(); + assert_eq!(s.pcie_experts, vec![15, 16, 17, 18, 19]); + assert_eq!(s.plan.pcie(), &[vec![5], vec![6], vec![7], vec![8], vec![9]]); + assert_eq!(s.kinds, vec![-1, -1, -1, -1, -1, 1, 1, 1, 1, 1]); + // staging holds 3: the first three of the selected tail + let s = split_group(&ids, 10, 40, none, 141, 3).unwrap(); + assert_eq!(s.pcie_experts, vec![15, 16, 17]); + assert_eq!(s.kinds.iter().filter(|&&k| k == 1).count(), 3); + // pcie_num 256: every miss; 0: none + assert_eq!(split_group(&ids, 10, 40, none, 256, 16).unwrap().pcie_experts.len(), 10); + assert!(split_group(&ids, 10, 40, none, 0, 16).unwrap().plan.is_empty()); + } + + #[test] + fn a_restricted_pcie_share_takes_only_eligible_misses_and_never_more_than_the_unrestricted_one() { + // 10 misses, share 141/256 -> m = 5 of all misses; only 11, 14, 16, 17 may be staged + let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); + let none = |_: u32| None; + let ok = |e: u32| matches!(e, 11 | 14 | 16 | 17); + let s = split_group_pcie(&ids, 10, 40, none, 141, 16, 0, ok).unwrap(); + assert_eq!(s.pcie_experts, vec![11, 14, 16, 17], "capped by the eligible misses, routing order"); + assert_eq!(s.kinds, vec![-1, 1, -1, -1, 1, -1, 1, 1, -1, -1]); + // a smaller share takes the last eligible misses + let s = split_group_pcie(&ids, 10, 40, none, 64, 16, 0, ok).unwrap(); // m = 10 * 64 >> 8 = 2 + assert_eq!(s.pcie_experts, vec![16, 17]); + // nothing eligible, nothing staged; and the unrestricted split is the old one + assert!(split_group_pcie(&ids, 10, 40, none, 256, 16, 0, |_| false).unwrap().plan.pcie().is_empty()); + let all = split_group_pcie(&ids, 10, 40, none, 141, 16, 0, |_| true).unwrap(); + let old = split_group(&ids, 10, 40, none, 141, 16).unwrap(); + assert_eq!((all.pcie_experts, all.kinds), (old.pcie_experts, old.kinds)); + // residents and skipped experts are not eligible misses + let resident = |e: u32| (e == 11).then_some(2usize); + let s = split_group_pcie(&ids, 10, 40, resident, 256, 16, 0, ok).unwrap(); + assert_eq!(s.pcie_experts, vec![14, 16, 17]); + } + + #[test] + fn a_resident_expert_never_counts_as_a_miss_for_the_pcie_rank() { + // 1 and 3 resident; the misses are 2, 4, 20..=25 + let padded = row([1, 2, 3, 4, 20, 21, 22, 23, 24, 25]); + let resident = |e: u32| (e == 1 || e == 3).then_some(e as usize); + let s = split_group(&padded, 10, 40, resident, 128, 16).unwrap(); + // 8 misses (2, 4, 20..=25), m = 8 * 128 >> 8 = 4: the last four misses in routing order + assert_eq!(s.pcie_experts, vec![22, 23, 24, 25]); + assert_eq!(s.plan.vram().len(), 2); + } + + #[test] + fn the_tail_skip_drops_missed_experts_every_token_routes_at_or_below_the_rank() { + // row 0 ranks: 12 at 6, 30 at 7, 31 at 8, 40 (resident) at 9; row 1 ranks: 15 at 7, 12 at 8, 30 at 9 + let mut ids = row([1, 2, 3, 4, 5, 6, 12, 30, 31, 40]); + ids.extend(row([7, 8, 9, 10, 11, 13, 14, 15, 12, 30])); + let resident = |e: u32| (e == 40).then_some(3usize); + let off = split_group_tail(&ids, 10, 20, resident, 0, 16, 0).unwrap(); + assert_eq!(off.skipped_experts, 0); + assert!(off.kinds.iter().all(|&k| k != -2)); + let on = split_group_tail(&ids, 10, 20, resident, 0, 16, 7).unwrap(); + // 30: best rank min(7, 9) = 7 -> skipped (entries 7 and 19); 31: rank 8 -> skipped (entry 8); 15: rank 7 -> skipped (entry 17); + // 12: best rank min(6, 8) = 6 < 7 -> kept in both rows (entries 6 and 18) + assert_eq!(on.skipped_experts, 3); + assert_eq!(on.kinds.iter().enumerate().filter(|&(_, &k)| k == -2).map(|(i, _)| i).collect::>(), vec![7, 8, 17, 19]); + assert_eq!((on.kinds[6], on.kinds[18]), (-1, -1)); + assert_eq!(on.kinds[9], 0, "a resident expert is never skipped"); + // everything else is exactly what the skip-off split produced + for i in 0..20 { + if on.kinds[i] != -2 { + assert_eq!(on.kinds[i], off.kinds[i], "entry {i}"); + } + } + assert_eq!(on.plan.vram(), off.plan.vram()); + // rank 8: only expert 31 (rank 8 in its only row); rank 9: nothing (the rank-9 entries are resident 40 and 30, best rank 7) + assert_eq!(split_group_tail(&ids, 10, 20, resident, 0, 16, 8).unwrap().skipped_experts, 1); + assert_eq!(split_group_tail(&ids, 10, 20, resident, 0, 16, 9).unwrap().skipped_experts, 0); + } + + #[test] + fn the_tail_skip_shrinks_the_miss_count_before_the_pcie_share_is_taken() { + // ten misses, rank 7..9 are three experts: 7 misses remain, pcie_num 141 -> m = 7 * 141 >> 8 = 3 (instead of 5 of ten) + let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); + let none = |_: u32| None; + let s = split_group_tail(&ids, 10, 40, none, 141, 16, 7).unwrap(); + assert_eq!(s.skipped_experts, 3); + assert_eq!(s.kinds, vec![-1, -1, -1, -1, 1, 1, 1, -2, -2, -2]); + assert_eq!(s.pcie_experts, vec![14, 15, 16]); + // a rank past the last slot skips nothing + let off = split_group_tail(&ids, 10, 40, none, 141, 16, 10).unwrap(); + assert_eq!(off.skipped_experts, 0); + } + + #[test] + fn the_tail_skip_leaves_invalid_ids_to_the_cpu_check() { + let ids = row([600, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + let s = split_group_tail(&ids, 10, 40, |_| None, 0, 16, 1).unwrap(); + assert_eq!(s.kinds[0], -1, "an out-of-range id is never a skip: the CPU path reports it"); + } + + #[test] + fn out_of_range_ids_stay_with_the_cpu_and_oversized_groups_are_refused() { + let ids = row([600, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + let s = split_group(&ids, 10, 40, |_| Some(1), 256, 16).unwrap(); + assert_eq!(s.kinds[0], -1); + assert!(split_group(&ids, 10, 5, |_| None, 0, 16).is_err()); + assert!(split_group(&vec![0; 130], 10, 200, |_| None, 0, 16).is_err()); + assert!(split_group(&ids[..9], 10, 40, |_| None, 0, 16).is_err()); + } + + #[test] + fn swaps_take_the_most_routed_misses_over_the_least_routed_residents() { + let mut usage = vec![0.0f32; LAYERS * EXPERTS]; + // layer 2: residents 0 (5.0), 1 (0.5), 2 (3.0); candidates 10 (9.0), 11 (2.5), 12 (1.9: below 2) + for (e, u) in [(0, 5.0), (1, 0.5), (2, 3.0), (10, 9.0), (11, 2.5), (12, 1.9)] { + usage[2 * EXPERTS + e] = u; + } + // layer 7: resident 4 (0.0), candidate 30 (2.0: the least count a candidate may have) + usage[7 * EXPERTS + 30] = 2.0; + let resident = |l: usize, e: usize| (l == 2 && e < 3) || (l == 7 && e == 4); + let swaps = choose_swaps(&usage, resident, 96); + // layer 2 pairs: (10, 1) gain 8.5; (11, 2): 2.5 < 3.0 + 1.5 stops; layer 7: (30, 4) gain 2.0 + assert_eq!(swaps.len(), 2); + assert_eq!((swaps[0].layer, swaps[0].incoming, swaps[0].outgoing), (2, 10, 1)); + assert_eq!((swaps[1].layer, swaps[1].incoming, swaps[1].outgoing), (7, 30, 4)); + assert_eq!(choose_swaps(&usage, resident, 1).len(), 1); + // no resident in a layer: no swap there (a native pack's cache only changes through its profile) + assert!(choose_swaps(&usage, |_, _| false, 96).is_empty()); + } + + #[test] + fn the_lag_controller_lowers_the_share_when_the_copies_land_last_and_probes_up_when_they_land_first() { + let mut c = PcieLag { num: 141, lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }; + // the PCIe leg finishes 200 us after the CPU leg on average: the share drops by 10 + c.lag_us = 200.0 * 48.0; + c.groups = 48; + c.round(); + assert_eq!(c.pcie_num(), 131); + // too few measured groups: nothing moves + c.lag_us = 9999.0; + c.groups = 3; + c.round(); + assert_eq!(c.pcie_num(), 131); + // copies always first: after three quiet rounds the share rises by 3 + let mut c = PcieLag { num: 100, lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }; + for _ in 0..3 { + c.groups = 20; + c.round(); + } + assert_eq!(c.pcie_num(), 103); + // the share stays inside its bounds + let mut c = PcieLag { num: PcieLag::MIN, lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }; + c.lag_us = 1e6; + c.groups = 10; + c.round(); + assert_eq!(c.pcie_num(), PcieLag::MIN); + } + + #[test] + fn the_pcie_mode_auto_is_dma_and_the_kernel_needs_device_aliases() { + // auto: DMA staging (this port's default; generate.cpp's is the copy kernel), the kernel only on request + assert_eq!(PcieMode::Auto.graph_mode(false, true), Some(0)); + assert_eq!(PcieMode::Auto.graph_mode(true, true), Some(0)); + assert_eq!(PcieMode::Auto.graph_mode(false, false), Some(0)); + assert_eq!(PcieMode::Kernel.graph_mode(false, true), Some(2)); + assert_eq!(PcieMode::Kernel.graph_mode(true, true), None); + assert_eq!(PcieMode::Dma.graph_mode(false, true), Some(0)); + assert_eq!(ExpertTierConfig::off().pcie_mode, PcieMode::Auto); + } + + #[test] + fn the_configuration_is_off_by_default_and_refuses_what_it_cannot_honour() { + let off = ExpertTierConfig::off(); + assert!(!off.enabled() && off.validate().is_ok() && off.pcie_num() == 115); + // the prompt-routing seed is an opt-in experiment + assert_eq!((off.seed_swaps, off.seed_keep, off.seed_usage, off.seed_decay), (0, 0.0, 0.0, 1.0)); + assert!(ExpertTierConfig { seed_keep: -1.0, ..off.clone() }.validate().is_err()); + let with_profile = ExpertTierConfig { profile: Some("p.bin".into()), ..off.clone() }; + assert!(with_profile.enabled()); + assert_eq!(with_profile.effective_slots(), -1); + assert_eq!(ExpertTierConfig { slots: 2048, ..off.clone() }.effective_slots(), 2048); + assert_eq!(ExpertTierConfig { pcie_frac: 0.55, ..off.clone() }.pcie_num(), 141); + // the default share needs a pinned source; an operator's share applies to a pageable bank too + assert_eq!(off.pcie_num_for(false), 115); + assert_eq!(off.pcie_num_for(true), 0); + assert_eq!(ExpertTierConfig { pcie_frac: 0.3, pcie_frac_set: true, ..off.clone() }.pcie_num_for(true), 77); + assert_eq!(ExpertTierConfig { pcie_frac: 1.0, ..off.clone() }.pcie_num(), 256); + assert!(ExpertTierConfig { slots: -2, ..off.clone() }.validate().is_err()); + assert!(ExpertTierConfig { pcie_frac: 1.5, ..off.clone() }.validate().is_err()); + assert!(ExpertTierConfig { pcie_frac: f64::NAN, ..off.clone() }.validate().is_err()); + assert!(!ExpertTierConfig { adapt_every: 0, ..off.clone() }.adaptive()); + assert!(ResidencyState::new(&ExpertTierConfig { adapt_swaps: 0, ..off.clone() }).usage.is_empty()); + assert_eq!(ResidencyState::new(&off).usage.len(), LAYERS * EXPERTS); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_seed.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_seed.rs index e695180d..cf7fd135 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_seed.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_seed.rs @@ -1,197 +1,197 @@ -//! ON by default when the configuration is read from the environment (`LELEKA_ORIGINAL_SERVE_SEED=off` disables; formerly experimental): residency seeded from the prompt's own routing. -//! -//! The Original's adaptive tier learns which experts to keep in VRAM from the verified windows, a few rounds at a time -//! (`ADAPT_EVERY` rounds, at most `ADAPT_SWAPS` swaps), so a first request decodes on the starting profile's placement -//! while the adaptation catches up. The prompt's prefill already knows, per layer, how many of its rows each expert -//! served (the MoE stage reads the route IDs on the host to group the rows by expert, `OriginalMoePromptLayer::counts`). -//! This module adds that signal to the placement: at the end of the prompt phase, after the lent slots are refilled, the -//! most-routed missing experts of every layer replace the least-routed resident ones (the same ranking as the adaptive -//! tier, `choose_swaps`, with the prompt's counts as the usage) in ONE batch of swaps queued on the tier's own copy -//! stream. The verifier assembly that follows overlaps the copies; the first round's `apply_pending` lands them. -//! -//! Also here: `restore_placement`, which puts the tier back on the starting profile's set between requests, so an -//! experiment can compare first-request behaviour with and without the seed inside one process. -use super::{ - contract::{Error, Result}, - moe_weight_cache::MoeWeightCache, - original_serve_pool::CpuExpertPool, - original_serve_residency::{choose_swaps, source_spans, SpanCache, Swap}, - original_serve_verifier::driver_error, -}; -use crate::model_binding::qwen4exp_input::ModelBinding; -use leleka_cuda_driver::OriginalExpertCache; -use leleka_model_format::qwen4exp::ResidentExpertBankSpan; -use std::rc::Rc; - -const LAYERS: usize = 48; -const EXPERTS: usize = 512; - -/// What `LELEKA_ORIGINAL_SERVE_SEED=on` allows: every slot may change (the ranking's own gain floor decides). -pub(crate) const DEFAULT_SEED_SWAPS: usize = 4096; - -/// A suggested cap for `LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS` (EXPERIMENTAL, not a default): the "agent-sized prompts up to a few thousand tokens" of -/// docs/original-serve.md. Prompts of 45k-247k tokens measured worse than no seed on the ranked upstream profile. -#[allow(dead_code)] -pub(crate) const SUGGESTED_SEED_MAX_ROWS: usize = 4096; - -/// One request's seed, for the operator's lines and the experiments. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub(crate) struct SeedReport { - /// Routed (layer, row) entries counted, divided by the layers and the top-k: the prompt rows the prefill routed. - pub(crate) rows: u64, - pub(crate) planned: usize, - pub(crate) plan_ms: f64, - pub(crate) queue_ms: f64, - /// Sum of the swaps' gains (routed rows won) and the most any layer changed. - pub(crate) gain: f64, - pub(crate) max_layer_swaps: usize, -} - -/// The seed's swaps: `counts[layer * 512 + expert]` are the prompt's routed rows per expert, `keep` a credit for every -/// resident expert (the blend with the profile's placement). -pub(super) fn plan(counts: &[f32], cache: &OriginalExpertCache<'_>, max_swaps: usize, keep: f32) -> Vec { - let mut usage: Vec = counts.to_vec(); - if keep > 0.0 { - for layer in 0..LAYERS { - for expert in 0..EXPERTS { - if cache.resident_slot(layer, expert).is_some() { - usage[layer * EXPERTS + expert] += keep; - } - } - } - } - choose_swaps(&usage, |layer, expert| cache.resident_slot(layer, expert).is_some(), max_swaps) -} - -/// Queue `swaps` (any number, one expert per slot, distinct within a layer) on the tier's copy stream and arm the batch; -/// the caller (or the next round's `apply_pending`) lands it. The source spans of a layer's incoming experts are opened -/// under one fence (the direct CPU tier's admission when it is on). -pub(super) fn queue_swaps<'ctx>( - binding: &ModelBinding, - moe: &MoeWeightCache<'ctx>, - cache: &mut OriginalExpertCache<'ctx>, - cpu: &mut CpuExpertPool<'_>, - known: &mut SpanCache, - swaps: &[Swap], -) -> Result<()> { - let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?; - let mut layer_swaps: Vec> = vec![Vec::new(); LAYERS]; - for swap in swaps { - layer_swaps.get_mut(swap.layer).ok_or(Error::InvalidExpert)?.push(swap); - } - for (layer, group) in layer_swaps.iter().enumerate() { - if group.is_empty() { - continue; - } - let incoming: Vec = group.iter().map(|s| s.incoming as u32).collect(); - let spans: Vec<[ResidentExpertBankSpan; 3]> = source_spans(cpu, &bank, moe, binding, known, layer, &incoming)?; - for (swap, spans) in group.iter().zip(spans) { - let slot = cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?; - cache.swap_slot_queued(slot, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?; - } - } - cache.arm_swaps().map_err(|e| driver_error(&e)) -} - -/// Put the tier back on the starting placement `initial` (every slot's owner right after the profile fill, by slot): -/// the same expert in the same slot, so a run after a restore cannot differ from a run in a new process by slot order. -/// Swaps are queued in rounds and awaited (blocking); a slot whose target is still held by another slot waits for it, and a -/// cycle is broken through one temporary expert. Returns the swaps made. -pub(super) fn restore_placement<'ctx>( - binding: &ModelBinding, - moe: &MoeWeightCache<'ctx>, - cache: &mut OriginalExpertCache<'ctx>, - cpu: &mut CpuExpertPool<'_>, - known: &mut SpanCache, - initial: &[Option<(usize, usize)>], -) -> Result { - let mut made = 0usize; - for _round in 0..64 { - cache.wait_swaps().map_err(|e| driver_error(&e))?; - let mut mapped = vec![false; LAYERS * EXPERTS]; - for slot in 0..cache.slots() { - if let Some((layer, expert)) = cache.slot_owner(slot) { - mapped[layer * EXPERTS + expert] = true; - } - } - let mut swaps = Vec::new(); - let mut stuck = None; - for (slot, target) in initial.iter().enumerate() { - let (Some((layer, want)), Some((_, have))) = (*target, cache.slot_owner(slot)) else { continue }; - if have == want { - continue; - } - if mapped[layer * EXPERTS + want] { - stuck.get_or_insert((layer, have)); - continue; - } - swaps.push(Swap { gain: 0.0, layer, incoming: want, outgoing: have }); - mapped[layer * EXPERTS + have] = false; - mapped[layer * EXPERTS + want] = true; - } - if swaps.is_empty() { - let Some((layer, have)) = stuck else { return Ok(made) }; - // only cycles are left: move one slot to an expert nobody holds, the next round resolves the rest - let temporary = (0..EXPERTS).find(|&e| !mapped[layer * EXPERTS + e]).ok_or(Error::IdentityMismatch)?; - swaps.push(Swap { gain: 0.0, layer, incoming: temporary, outgoing: have }); - } - made += swaps.len(); - queue_swaps(binding, moe, cache, cpu, known, &swaps)?; - } - Err(Error::IdentityMismatch) -} - -/// The report of a planned batch (`rows`: from the counts). -pub(super) fn summarize(counts: &[f32], swaps: &[Swap]) -> SeedReport { - let mut per_layer = [0usize; LAYERS]; - for swap in swaps { - per_layer[swap.layer] += 1; - } - SeedReport { - rows: (counts.iter().map(|&c| f64::from(c)).sum::() / (10 * LAYERS) as f64).round() as u64, - planned: swaps.len(), - plan_ms: 0.0, - queue_ms: 0.0, - gain: swaps.iter().map(|s| f64::from(s.gain)).sum(), - max_layer_swaps: per_layer.into_iter().max().unwrap_or(0), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_report_counts_prompt_rows_and_the_busiest_layer() { - let mut counts = vec![0f32; LAYERS * EXPERTS]; - // 3 rows routed to 10 experts in every layer - for layer in 0..LAYERS { - for expert in 0..10 { - counts[layer * EXPERTS + expert] = 3.0; - } - } - let swaps = [ - Swap { gain: 4.0, layer: 2, incoming: 1, outgoing: 2 }, - Swap { gain: 2.5, layer: 2, incoming: 3, outgoing: 4 }, - Swap { gain: 9.0, layer: 7, incoming: 5, outgoing: 6 }, - ]; - let report = summarize(&counts, &swaps); - assert_eq!((report.rows, report.planned, report.max_layer_swaps), (3, 3, 2)); - assert_eq!(report.gain, 15.5); - assert_eq!(summarize(&counts, &[]).max_layer_swaps, 0); - } - - #[test] - fn the_seed_ranking_is_the_adaptive_tiers_with_the_prompts_counts() { - let mut usage = vec![0.0f32; LAYERS * EXPERTS]; - // layer 3: resident 0 (never routed by the prompt) and 1 (routed 6 times); candidates 20 (9 rows), 21 (2 rows) - for (e, u) in [(1, 6.0), (20, 9.0), (21, 2.0)] { - usage[3 * EXPERTS + e] = u; - } - let resident = |l: usize, e: usize| l == 3 && e < 2; - let swaps = choose_swaps(&usage, resident, DEFAULT_SEED_SWAPS); - // (20 over 0): gain 9; (21 over 1): 2 < 6 + 1.5 stops - assert_eq!(swaps.len(), 1); - assert_eq!((swaps[0].layer, swaps[0].incoming, swaps[0].outgoing), (3, 20, 0)); - } -} +//! ON by default when the configuration is read from the environment (`LELEKA_ORIGINAL_SERVE_SEED=off` disables; formerly experimental): residency seeded from the prompt's own routing. +//! +//! The Original's adaptive tier learns which experts to keep in VRAM from the verified windows, a few rounds at a time +//! (`ADAPT_EVERY` rounds, at most `ADAPT_SWAPS` swaps), so a first request decodes on the starting profile's placement +//! while the adaptation catches up. The prompt's prefill already knows, per layer, how many of its rows each expert +//! served (the MoE stage reads the route IDs on the host to group the rows by expert, `OriginalMoePromptLayer::counts`). +//! This module adds that signal to the placement: at the end of the prompt phase, after the lent slots are refilled, the +//! most-routed missing experts of every layer replace the least-routed resident ones (the same ranking as the adaptive +//! tier, `choose_swaps`, with the prompt's counts as the usage) in ONE batch of swaps queued on the tier's own copy +//! stream. The verifier assembly that follows overlaps the copies; the first round's `apply_pending` lands them. +//! +//! Also here: `restore_placement`, which puts the tier back on the starting profile's set between requests, so an +//! experiment can compare first-request behaviour with and without the seed inside one process. +use super::{ + contract::{Error, Result}, + moe_weight_cache::MoeWeightCache, + original_serve_pool::CpuExpertPool, + original_serve_residency::{choose_swaps, source_spans, SpanCache, Swap}, + original_serve_verifier::driver_error, +}; +use crate::model_binding::qwen4exp_input::ModelBinding; +use leleka_cuda_driver::OriginalExpertCache; +use leleka_model_format::qwen4exp::ResidentExpertBankSpan; +use std::rc::Rc; + +const LAYERS: usize = 48; +const EXPERTS: usize = 512; + +/// What `LELEKA_ORIGINAL_SERVE_SEED=on` allows: every slot may change (the ranking's own gain floor decides). +pub(crate) const DEFAULT_SEED_SWAPS: usize = 4096; + +/// A suggested cap for `LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS` (EXPERIMENTAL, not a default): the "agent-sized prompts up to a few thousand tokens" of +/// docs/original-serve.md. Prompts of 45k-247k tokens measured worse than no seed on the ranked upstream profile. +#[allow(dead_code)] +pub(crate) const SUGGESTED_SEED_MAX_ROWS: usize = 4096; + +/// One request's seed, for the operator's lines and the experiments. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct SeedReport { + /// Routed (layer, row) entries counted, divided by the layers and the top-k: the prompt rows the prefill routed. + pub(crate) rows: u64, + pub(crate) planned: usize, + pub(crate) plan_ms: f64, + pub(crate) queue_ms: f64, + /// Sum of the swaps' gains (routed rows won) and the most any layer changed. + pub(crate) gain: f64, + pub(crate) max_layer_swaps: usize, +} + +/// The seed's swaps: `counts[layer * 512 + expert]` are the prompt's routed rows per expert, `keep` a credit for every +/// resident expert (the blend with the profile's placement). +pub(super) fn plan(counts: &[f32], cache: &OriginalExpertCache<'_>, max_swaps: usize, keep: f32) -> Vec { + let mut usage: Vec = counts.to_vec(); + if keep > 0.0 { + for layer in 0..LAYERS { + for expert in 0..EXPERTS { + if cache.resident_slot(layer, expert).is_some() { + usage[layer * EXPERTS + expert] += keep; + } + } + } + } + choose_swaps(&usage, |layer, expert| cache.resident_slot(layer, expert).is_some(), max_swaps) +} + +/// Queue `swaps` (any number, one expert per slot, distinct within a layer) on the tier's copy stream and arm the batch; +/// the caller (or the next round's `apply_pending`) lands it. The source spans of a layer's incoming experts are opened +/// under one fence (the direct CPU tier's admission when it is on). +pub(super) fn queue_swaps<'ctx>( + binding: &ModelBinding, + moe: &MoeWeightCache<'ctx>, + cache: &mut OriginalExpertCache<'ctx>, + cpu: &mut CpuExpertPool<'_>, + known: &mut SpanCache, + swaps: &[Swap], +) -> Result<()> { + let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?; + let mut layer_swaps: Vec> = vec![Vec::new(); LAYERS]; + for swap in swaps { + layer_swaps.get_mut(swap.layer).ok_or(Error::InvalidExpert)?.push(swap); + } + for (layer, group) in layer_swaps.iter().enumerate() { + if group.is_empty() { + continue; + } + let incoming: Vec = group.iter().map(|s| s.incoming as u32).collect(); + let spans: Vec<[ResidentExpertBankSpan; 3]> = source_spans(cpu, &bank, moe, binding, known, layer, &incoming)?; + for (swap, spans) in group.iter().zip(spans) { + let slot = cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?; + cache.swap_slot_queued(slot, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?; + } + } + cache.arm_swaps().map_err(|e| driver_error(&e)) +} + +/// Put the tier back on the starting placement `initial` (every slot's owner right after the profile fill, by slot): +/// the same expert in the same slot, so a run after a restore cannot differ from a run in a new process by slot order. +/// Swaps are queued in rounds and awaited (blocking); a slot whose target is still held by another slot waits for it, and a +/// cycle is broken through one temporary expert. Returns the swaps made. +pub(super) fn restore_placement<'ctx>( + binding: &ModelBinding, + moe: &MoeWeightCache<'ctx>, + cache: &mut OriginalExpertCache<'ctx>, + cpu: &mut CpuExpertPool<'_>, + known: &mut SpanCache, + initial: &[Option<(usize, usize)>], +) -> Result { + let mut made = 0usize; + for _round in 0..64 { + cache.wait_swaps().map_err(|e| driver_error(&e))?; + let mut mapped = vec![false; LAYERS * EXPERTS]; + for slot in 0..cache.slots() { + if let Some((layer, expert)) = cache.slot_owner(slot) { + mapped[layer * EXPERTS + expert] = true; + } + } + let mut swaps = Vec::new(); + let mut stuck = None; + for (slot, target) in initial.iter().enumerate() { + let (Some((layer, want)), Some((_, have))) = (*target, cache.slot_owner(slot)) else { continue }; + if have == want { + continue; + } + if mapped[layer * EXPERTS + want] { + stuck.get_or_insert((layer, have)); + continue; + } + swaps.push(Swap { gain: 0.0, layer, incoming: want, outgoing: have }); + mapped[layer * EXPERTS + have] = false; + mapped[layer * EXPERTS + want] = true; + } + if swaps.is_empty() { + let Some((layer, have)) = stuck else { return Ok(made) }; + // only cycles are left: move one slot to an expert nobody holds, the next round resolves the rest + let temporary = (0..EXPERTS).find(|&e| !mapped[layer * EXPERTS + e]).ok_or(Error::IdentityMismatch)?; + swaps.push(Swap { gain: 0.0, layer, incoming: temporary, outgoing: have }); + } + made += swaps.len(); + queue_swaps(binding, moe, cache, cpu, known, &swaps)?; + } + Err(Error::IdentityMismatch) +} + +/// The report of a planned batch (`rows`: from the counts). +pub(super) fn summarize(counts: &[f32], swaps: &[Swap]) -> SeedReport { + let mut per_layer = [0usize; LAYERS]; + for swap in swaps { + per_layer[swap.layer] += 1; + } + SeedReport { + rows: (counts.iter().map(|&c| f64::from(c)).sum::() / (10 * LAYERS) as f64).round() as u64, + planned: swaps.len(), + plan_ms: 0.0, + queue_ms: 0.0, + gain: swaps.iter().map(|s| f64::from(s.gain)).sum(), + max_layer_swaps: per_layer.into_iter().max().unwrap_or(0), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_report_counts_prompt_rows_and_the_busiest_layer() { + let mut counts = vec![0f32; LAYERS * EXPERTS]; + // 3 rows routed to 10 experts in every layer + for layer in 0..LAYERS { + for expert in 0..10 { + counts[layer * EXPERTS + expert] = 3.0; + } + } + let swaps = [ + Swap { gain: 4.0, layer: 2, incoming: 1, outgoing: 2 }, + Swap { gain: 2.5, layer: 2, incoming: 3, outgoing: 4 }, + Swap { gain: 9.0, layer: 7, incoming: 5, outgoing: 6 }, + ]; + let report = summarize(&counts, &swaps); + assert_eq!((report.rows, report.planned, report.max_layer_swaps), (3, 3, 2)); + assert_eq!(report.gain, 15.5); + assert_eq!(summarize(&counts, &[]).max_layer_swaps, 0); + } + + #[test] + fn the_seed_ranking_is_the_adaptive_tiers_with_the_prompts_counts() { + let mut usage = vec![0.0f32; LAYERS * EXPERTS]; + // layer 3: resident 0 (never routed by the prompt) and 1 (routed 6 times); candidates 20 (9 rows), 21 (2 rows) + for (e, u) in [(1, 6.0), (20, 9.0), (21, 2.0)] { + usage[3 * EXPERTS + e] = u; + } + let resident = |l: usize, e: usize| l == 3 && e < 2; + let swaps = choose_swaps(&usage, resident, DEFAULT_SEED_SWAPS); + // (20 over 0): gain 9; (21 over 1): 2 < 6 + 1.5 stops + assert_eq!(swaps.len(), 1); + assert_eq!((swaps[0].layer, swaps[0].incoming, swaps[0].outgoing), (3, 20, 0)); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs index f84bf597..f65d8fee 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs @@ -1,1974 +1,1974 @@ -//! The Original serving stack: every model-lifetime owner of the `generate.cpp` mode17 serve path, opened -//! once, and the per-request flow over them (prompt conditioning with the batched Original prefill, then the -//! verified-window decode with MTP drafting). -//! -//! Lifetime of the pieces: the dense weights, the MoE arena cache, the native head/embedding, the target -//! session, the prompt executor (which owns the MTP actor and the twelve resident QSA layers), the MTP draft -//! session, the prefill arena, the penalty-history stage and the PLE history image live as long as the -//! stack. Each request resets them to the empty prompt (the checkpoints taken at load, re-stamped onto the -//! current branch generation), conditions the prompt through the executor, and then hands the QSA owners to a -//! freshly assembled native Verifier for the decode phase; the verifier is closed and the owners are taken -//! back afterwards (see `original_serve_verifier`). With `StackConfig::conversation` set, generate.cpp's -//! conversation cache decides where a request starts reading instead (`original_serve_conversation`); -//! without it every request starts at position 0. -//! -//! With `StackConfig::expert_tier` on, the stack also owns the VRAM expert tier (`original_serve_residency`): -//! the cache is opened last, filled from the profile, lent to the prompt path for each chunk and refilled -//! before the decode phase (on every exit path), whose windows compute the resident experts on the GPU. -//! -//! Nothing here computes a model number. Where an asset or a producer the Original needs is not available the -//! error comes from its owner and is surfaced untouched (`ServeFailure`). -use super::{ - contract::{Error, Result}, - dense_weight_cache::DenseWeightCache, - executor::original_prompt::{embedding::OriginalPromptEmbedding, OriginalPromptExecutor}, - kar_ple_cache::KarPleCache, - moe_weight_cache::MoeWeightCache, - original_mtp_full_owner::{OriginalMtpFullOwner, OriginalMtpRequest}, - original_serve_config::{expert_formats, mtp_full_policy, mtp_scalar_policy, prefill_layout_options, ExpertBlobSizes, RopeConstants}, - original_serve_engine::{serve_request, OriginalServeEngine, OriginalServeSettings, ServeOutcome}, - original_serve_host::{HostOwners, OriginalServeHost, RequestSampling}, - original_serve_native::NativeServePort, - original_serve_pool::{CpuExpertPool, OriginalServePool}, - original_serve_profile as profile, - original_serve_residency::{self, ExpertTierConfig, GpuExpertPool, ResidencyState}, - original_serve_seed::{self, SeedReport}, - original_serve_request::{run_request, RequestOwners, ServeError, ServeRequest}, - original_serve_verifier::{assemble, disassemble, seed_ple_history, DecodeResources, ServeFailure, VerifyWeights, PLE_HISTORY_BYTES}, - original_spec_controller::{OriginalSpecController, SpecError}, - output_native::{OriginalNativeOutput, OriginalNativePenaltyHistory}, - session::{ - original_prompt::{draft::OriginalDraftCheckpoint, OriginalPromptInput, OriginalSessionCheckpoint, ParkedBlock, ParkedSession}, - QwenSession, - }, -}; -use crate::backend::original_prompt::{PlanError, PromptOptions, PromptPath, PromptPlan}; -use crate::model_binding::qwen4exp_input::ModelBinding; -use leleka_context::memory_plan::KvFormat; -use leleka_cuda_driver::{ - Context, DeviceBuffer, NativeHeadDispatch, OriginalExpertCache, OriginalMtpFullPolicy, OriginalMtpScalarPolicy, - OriginalPrefillArena, OriginalVerifyExpertFormats, PLE_SCRATCH_BYTES, PrefillLayoutOptions, -}; -use std::{path::PathBuf, rc::Rc, time::Instant}; - -/// One timed, measured step of opening the stack: the load ledger records what it cost in host and device memory. -macro_rules! staged { - ($name:expr, $ctx:expr, $body:expr) => {{ - let __stage = crate::memory_governor::begin($name, Some($ctx)); - let __result = $body; - crate::memory_governor::end(__stage, Some($ctx)); - __result - }}; -} - -#[path = "original_serve_conversation.rs"] -mod conversation; -pub(crate) use conversation::{ConversationConfig, TURN_TOKEN}; -use conversation::{ResumeDevice, ServeConversation}; - -#[path = "original_serve_prefix.rs"] -mod prefix; -pub(crate) use prefix::{PrefixBudget, PrefixConfig, TailMode}; -use prefix::{ChunkOutcome, PrefixDevice, PrefixServe}; -use crate::prefix_cache::{ByteSize, PrefixMatch, PrefixSummary}; - -/// Stage marks of one request's time to first token (milliseconds since `serve` was entered). -#[derive(Clone, Copy, Debug)] -struct TtftMarks { - started: Option, - resumed: f64, - prefilled: f64, - assembled: f64, - first_round: f64, -} -impl Default for TtftMarks { - fn default() -> Self { - Self { started: None, resumed: f64::NAN, prefilled: f64::NAN, assembled: f64::NAN, first_round: f64::NAN } - } -} -impl TtftMarks { - fn start() -> Self { - Self { started: Some(Instant::now()), ..Self::default() } - } - fn since(&self) -> f64 { - self.started.map_or(f64::NAN, |at| at.elapsed().as_secs_f64() * 1e3) - } - fn as_array(&self) -> [f64; 4] { - [self.resumed, self.prefilled, self.assembled, self.first_round] - } -} - -/// The digest of the pinned model's first shard: part of the prefix cache's namespace. -const PINNED_MODEL: &str = "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"; - -/// Prompt-chunk capacities the Original prefill admits (`PromptPlan::new`), ascending. -pub(crate) const ADMITTED_CAPACITIES: [usize; 10] = [256, 512, 1024, 2048, 3072, 4096, 6144, 8192, 16384, 32768]; -/// The default chunk. The Original sizes it from the free expert-cache slots (`--prefill-auto`); with no GPU -/// expert tier there is no slot count to derive it from, so the operator picks it (the arena is a few GiB at -/// 8192) and a hardware run settles the default. -pub(crate) const DEFAULT_CAPACITY: usize = 2048; -/// `qsa_kv_resident_min()`: the shipped resident draft-K/V budget in cells. -const MTP_RESIDENT_CELLS: u64 = 20_480; -const CPU_WORKERS: i32 = 15; -const VOCABULARY: u32 = 248_320; - -/// Operator-visible choices of the stack. -#[derive(Clone, Debug)] -pub(crate) struct StackConfig { - pub(crate) capacity: usize, - /// The request ceiling (`--max-context`): at most the process serving cell count. - pub(crate) max_context: i64, - /// `--mtp DIR`: the Original-literal RT directory; `None` takes the digest-pinned pack of the binding. - pub(crate) rt_directory: Option, - pub(crate) coupled: bool, - pub(crate) cpu_workers: i32, - /// Read the verifier's GDN/PLE state back into the session at the end of every request (needed only by - /// a consumer that reuses the session; the default reset-per-request flow skips the 110 MB transfer). - pub(crate) settle_state: bool, - /// `--kv`: QSA K/V storage. Only `int8` (the production `--kv int8`) has sealed owners; fp16, q4_0 and - /// k8v4 are refused (docs/kv-streaming.md). - pub(crate) kv_format: KvFormat, - /// `--kv-resident N`: cells of each QSA layer kept in VRAM, the rest streamed from pinned host memory - /// (raised to 20480; 0 = the whole context). Default 32768, the window every earlier build used. - pub(crate) kv_resident: usize, - /// generate.cpp's conversation cache (`--prompt-cache` and friends); on by default with the Original's - /// settings (`--prompt-cache 6`). `None` reads every request from the empty prompt. - pub(crate) conversation: Option, - /// The cross-session prefix cache (`--prefix-cache-mib`, `docs/prefix-cache.md`). When it is on it REPLACES the - /// conversation cache: the prompt is read on a token grid and any request resumes from the deepest checkpoint - /// that is a prefix of its prompt, whichever session built it. `None` (the default) leaves the conversation - /// cache in charge. - pub(crate) prefix: Option, - /// The VRAM expert tier (`--expert-cache`, `--expert-cache-per-layer`, `--expert-profile`, `--pcie-frac`, - /// `--adapt-every/--adapt-swaps`). Off by default: every routed expert on the CPU pool. - pub(crate) expert_tier: ExpertTierConfig, - /// Smaller prompt loans for smaller chunks (`LELEKA_PREFILL_LOAN_TIERS=1`; off: every chunk borrows the full loan of `capacity`). - pub(crate) loan_tiers: bool, -} -impl StackConfig { - pub(crate) fn new(max_context: i64) -> Self { - Self { - capacity: DEFAULT_CAPACITY, - max_context, - rt_directory: None, - coupled: OriginalServeSettings::coupled_from_environment(), - // LELEKA_ORIGINAL_SERVE_CPU_WORKERS: experiment knob (the Original's default on this host is 15) - // LELEKA_CPU_POOL_PLAN=on: when the count is not set, the plan of `native-cpu-expert::pool_plan` (physical cores but the host's, hybrid and quota aware; - // docs/upstream-port-plan.md row 2.3) instead of the constant 15 (opt-in: the same 15 on the server's 16-core CPU, not measured on any other) - cpu_workers: std::env::var("LELEKA_ORIGINAL_SERVE_CPU_WORKERS").ok().and_then(|v| v.parse().ok()).filter(|n| (1..=64).contains(n)).unwrap_or_else(|| { - if std::env::var("LELEKA_CPU_POOL_PLAN").is_ok_and(|v| v == "on") { leleka_native_cpu_expert::pool_plan::default_workers() } else { CPU_WORKERS } - }), - settle_state: false, - kv_format: KvFormat::Int8, - kv_resident: leleka_cuda_driver::KV_RESIDENT_DEFAULT_CELLS, - conversation: Some(ConversationConfig::original()), - prefix: None, - expert_tier: ExpertTierConfig::off(), - loan_tiers: loan_tiers_enabled(), - } - } - /// The streamed KV of this configuration (`None` when the window is not servable). - pub(crate) fn kv_footprint(&self) -> Option { - leleka_cuda_driver::serving_context().geometry.kv_stream_footprint(self.kv_resident).ok() - } - pub(crate) fn validate(&self) -> Result<()> { - if self.kv_format != KvFormat::Int8 { - return Err(Error::Unsupported(super::contract::Stage::Session)); - } - if !ADMITTED_CAPACITIES.contains(&self.capacity) - || self.kv_footprint().is_none() - || self.capacity > 8192 - || self.max_context < 1 - || self.max_context as u64 > super::contract::serving_cells() - || !(1..=64).contains(&self.cpu_workers) - { - return Err(Error::InvalidDimension); - } - if let Some(conversation) = &self.conversation { - conversation.validate()?; - } - if let Some(prefix) = &self.prefix { - prefix.validate(self.capacity)?; - } - self.expert_tier.validate() - } -} - -/// Bytes the prompt path's buffers need at `options.capacity` (what a loan must cover). -fn prefill_bytes(options: PrefillLayoutOptions) -> Result { - let carve = options.carve().map_err(|e| super::original_serve_verifier::driver_error(&e))?; - Ok(carve.borrowed_bytes.max(carve.source_bytes_needed)) -} - -/// One rung of the loan ladder: the arena layout for chunks of at most `rows` rows and the slots it needs. -#[derive(Clone, Copy, Debug)] -struct LoanTier { - rows: usize, - layout: PrefillLayoutOptions, - slots: usize, -} - -/// Chunk sizes (rows) that get their own, smaller loan below the configured capacity. -const LOAN_TIER_ROWS: [usize; 2] = [512, 2048]; - -/// The smallest rung of the ladder that holds a chunk of `count` rows (`None`: the full loan). -fn tier_for(tiers: &[LoanTier], count: usize) -> Option<&LoanTier> { - tiers.iter().find(|t| count <= t.rows) -} - -/// `LELEKA_PREFILL_LOAN_TIERS=1` turns the ladder on. It is OFF by default until the real-model identity gate (job p34: the final residual R of -/// every chunk equal with and without the ladder) and the paired A/B (job p35) have run (docs/prefill-throughput.md). -fn loan_tiers_enabled() -> bool { - std::env::var("LELEKA_PREFILL_LOAN_TIERS").is_ok_and(|v| v == "1" || v == "on") -} - -/// One conversation checkpoint of the stack: the session's Original checkpoint and the draft ring's snapshot, -/// taken together at a published prompt-chunk boundary. -struct StackPoint<'ctx> { - session: OriginalSessionCheckpoint<'ctx>, - draft: OriginalDraftCheckpoint, -} - -/// A prefix-cache checkpoint of the stack: the session's recurrent state and the draft ring's snapshot at one grid point. -struct StackState { - session: ParkedSession, - draft: OriginalDraftCheckpoint, -} -impl ByteSize for StackState { - fn byte_size(&self) -> usize { - self.session.host_bytes() + self.draft.host_bytes() - } -} -/// The K/V cells and index rows of one block of the twelve resident QSA layers. -struct StackBlock(ParkedBlock); -impl ByteSize for StackBlock { - fn byte_size(&self) -> usize { - self.0.host_bytes() - } -} -/// Bytes of one cell across the twelve layers: INT8 K+V with scales (1056 B) and the pooled index key (128 B). -const PARKED_BYTES_PER_TOKEN: usize = 12 * (1056 + 128); -/// Expected size of a parked state before one was measured (GDN/PLE images, the draft ring, the index tails). -const PARKED_STATE_ESTIMATE: usize = 120 << 20; - -fn plan_error(error: PlanError) -> Error { - match error { - PlanError::InvalidInput => Error::InvalidDimension, - PlanError::Overflow => Error::Overflow, - } -} - -pub(crate) struct OriginalServeStack<'a, 'ctx> { - binding: &'a ModelBinding, - context: &'ctx Context<'ctx>, - config: StackConfig, - settings: OriginalServeSettings, - max_cells: usize, - rope: RopeConstants, - blobs: ExpertBlobSizes, - formats: OriginalVerifyExpertFormats, - full_policy: OriginalMtpFullPolicy, - scalar_policy: OriginalMtpScalarPolicy, - controller: OriginalSpecController, - /// Window policies other than the live one (`LELEKA_SPEC_ARMS`), parked with their controllers (each keeps its learned - /// state across requests), and the live one's label. The verifier is built for `verifier_max_t`, the widest arm. - parked: Vec<(String, OriginalServeSettings, OriginalSpecController)>, - arm_label: String, - arm_order: Vec, - verifier_max_t: usize, - /// Why the stack can serve no more (a lost physical owner); `None` while healthy. - broken: Option, - // The empty-prompt lineage taken at load: the reset target of every request. - empty_session: OriginalSessionCheckpoint<'ctx>, - empty_draft: OriginalDraftCheckpoint, - /// The conversation cache (checkpoints hold priors and snapshots of the owners below: dropped first). - conversation: Option>>, - /// The prefix cache (`StackConfig::prefix`); replaces `conversation` when set. - prefix: Option>, - /// The tokens the session holds at the end of a decode that left it settled with the draft ring in step (`TailMode::Reply`). - tail_consumed: Option>, - /// Prompt tokens the last request did not read again. - reused: usize, - /// Where the conversation cache placed the last request (`reused`, or the re-read checkpoint's length). - resume_point: usize, - // Owners, dependents first (fields drop in declaration order). - history: OriginalNativePenaltyHistory<'ctx>, - ple_history: DeviceBuffer<'ctx>, - ple_scratch: DeviceBuffer<'ctx>, - /// The prompt path's own buffers; `None` while it borrows the expert cache's last slots instead. - arena: Option>, - layout: PrefillLayoutOptions, - /// The VRAM expert tier (`None`: off), the slots the prompt path borrows per chunk, the adaptive counts - /// that survive requests. - expert_cache: Option>, - loan: Option, - /// Smaller loans for smaller chunks, ascending by rows (empty unless `LELEKA_PREFILL_LOAN_TIERS=1`: only `loan`): a chunk of at most - /// `rows` rows borrows `slots` slots instead of the full loan, so a request that reads a few hundred tokens refills a few - /// hundred slots, not the 1.9 GB of an 8192-row arena. - loan_tiers: Vec, - residency: ResidencyState, - /// The (layer, expert) pairs the tier held right after the profile fill (`reset_expert_tier`). - initial_owners: Vec>, - /// The last request's prompt-routing seed (`LELEKA_ORIGINAL_SERVE_SEED`), if one was made. - seed_report: Option, - /// The prompt counts of the last seed (kept for the `LELEKA_SEED_TRACE` coverage line). - seed_counts: Option>, - /// Lent-slot refill copies are queued and not yet waited (`LELEKA_REFILL_DEFER`): the decode phase waits before any - /// window reads the cache; every other user of the cache waits inside its own entry points. - refill_pending: bool, - /// The lent slots still have to be refilled: the decode phase queues the copies right after its host-side intake - /// uploads (so they overlap the graph capture instead of queueing small uploads behind 1.4 GB of DMA). - refill_due: bool, - /// Wall-clock milliseconds of the last request's prompt and decode phases (operator measurements). - timing: (f64, f64), - /// Milliseconds since the request entered `serve` at which each stage of the time to first token ended (`ttft_marks`). - marks: TtftMarks, - executor: OriginalPromptExecutor<'ctx>, - draft: super::session::original_prompt::draft::OriginalDraftSession<'ctx>, - session: QwenSession<'ctx>, - pool: CpuExpertPool<'a>, - kar: Option>, - moe: MoeWeightCache<'ctx>, - dense: DenseWeightCache<'ctx>, - output: OriginalNativeOutput<'ctx>, - embedding: OriginalPromptEmbedding<'ctx>, -} - -fn failure(error: Error) -> ServeFailure { - ServeFailure::from(error) -} - -/// Name the startup step in a refusal so a failed open says where it stopped. -fn at>(step: &'static str) -> impl FnOnce(E) -> ServeFailure { - move |error| { - let mut failure: ServeFailure = error.into(); - failure.detail = Some(match failure.detail.take() { - Some(detail) => format!("{step}: {detail}"), - None => format!("{step}: {:?}", failure.error), - }); - failure - } -} - -impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { - /// `generate.cpp` startup over the binding: embedding table, native head + embedding, dense weights at - /// the prompt capacity, the MoE arena cache, the target session, the prompt executor with the MTP - /// drafter, the prefill arena, and the per-request stages. `shared` is the session's reference to the - /// very context `context` borrows. - pub(crate) fn open( - binding: &'a ModelBinding, - context: &'ctx Context<'ctx>, - shared: Rc>, - config: StackConfig, - ) -> std::result::Result { - crate::bringup_trace!("DBG[{:.0}s] OriginalServeStack::open begin", dbg_el()); - config.validate().map_err(at("config.validate"))?; - // generate.cpp: qsa_set_kv_resident before any QSA state exists (every streamed owner sizes from it) - leleka_cuda_driver::configure_kv_resident(config.kv_resident).map_err(|_| ServeFailure { - error: Error::InvalidDimension, - detail: Some(format!("--kv-resident {}: the process already serves another resident KV window", config.kv_resident)), - })?; - if let Some(footprint) = config.kv_footprint() { - operator_note(&footprint.to_string()); - } - if !std::ptr::eq(context, &*shared) { - return Err(failure(Error::IdentityMismatch)); - } - if binding.layer_count() != 48 { - return Err(ServeFailure { error: Error::IdentityMismatch, detail: Some("the Original serve stack serves the 48-layer model only".to_owned()) }); - } - if !binding.has_mtp() { - return Err(ServeFailure { - error: Error::Unsupported(super::contract::Stage::Session), - detail: Some("the binding carries no MTP pack: the Original serve loop drafts with the MTP layer".to_owned()), - }); - } - let max_cells = usize::try_from(super::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?; - let mut settings = OriginalServeSettings::from_environment(config.max_context, VOCABULARY, config.coupled); - let mut arm_label = String::from("env"); - let arm_order: Vec = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled).into_iter().map(|(l, _)| l).collect(); - let mut parked = Vec::new(); - let arms = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled); - let verifier_max_t = arms.iter().map(|(_, s)| s.max_t).chain([settings.max_t]).max().unwrap_or(settings.max_t); - if let Some(((label, first), rest)) = arms.split_first() { - settings = *first; - arm_label = label.clone(); - for (label, s) in rest { - parked.push((label.clone(), *s, s.controller().map_err(at("settings.controller"))?)); - } - } - let controller = settings.controller().map_err(at("settings.controller"))?; - let rope = RopeConstants::from_serving_context(); - let blobs = ExpertBlobSizes::from_binding(binding).map_err(at("ExpertBlobSizes::from_binding"))?; - let formats = expert_formats(binding).map_err(at("expert_formats"))?; - let layout = prefill_layout_options(config.capacity, max_cells, &blobs); - - vram_note(context, "open begin"); - let embedding = staged!("embedding table", context, OriginalPromptEmbedding::load(binding, context).map_err(at("OriginalPromptEmbedding::load"))?); - let output = staged!("native head + embedding", context, OriginalNativeOutput::load(binding, context, NativeHeadDispatch::default(), true).map_err(at("OriginalNativeOutput::load"))?); - let kar = staged!("KAR PLE cache", context, match binding.kar_ple_binding() { - Some(provider) => Some(KarPleCache::new(context, provider).map_err(at("KarPleCache::new"))?), - None => None, - }); - let dense = staged!("dense weights", context, DenseWeightCache::new_original_prompt_capacity(binding, context, config.capacity).map_err(at("DenseWeightCache::new_original_prompt_capacity"))?); - let moe = staged!("MoE arena cache", context, MoeWeightCache::new_original_prompt_arena(binding, context, layout).map_err(at("MoeWeightCache::new_original_prompt_arena"))?); - vram_note(context, "after embedding, output, kar, dense, moe arena"); - let mut session = QwenSession::for_binding_on_shared_device(binding, shared); - let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, settings.coupled, MTP_RESIDENT_CELLS); - let executor_stage = crate::memory_governor::begin("prompt executor + MTP drafter", Some(context)); - let (executor, draft) = match &config.rt_directory { - Some(directory) => OriginalPromptExecutor::select_rt_mtp( - binding, &dense, &mut session, context, &embedding, &output, directory, config.capacity, true, &request, - ) - .map_err(|e| ServeFailure { error: e.error, detail: e.message })?, - None => { - let mut executor = OriginalPromptExecutor::new( - binding, &dense, &mut session, context, &moe, &embedding, config.capacity, verifier_max_t, true, - ).map_err(at("OriginalPromptExecutor::new"))?; - let assembly = OriginalMtpFullOwner::assemble(binding, &session, context, &moe, &embedding, &output, &request) - .map_err(|e| ServeFailure { error: e.error, detail: e.message })?; - let draft = executor.install_full_mtp(binding, &session, assembly).map_err(at("install_full_mtp"))?; - (executor, draft) - } - }; - vram_note(context, "after prompt executor and draft"); - let mut executor = executor; - crate::memory_governor::end(executor_stage, Some(context)); - // generate.cpp: the expert cache is sized after everything else, and the prompt path's own buffers - // after the cache when it cannot borrow them; without the tier the order is unchanged. - let tier = config.expert_tier.enabled(); - let mut arena = staged!("prefill arena", context, if tier { None } else { Some(context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?) }); - vram_note(context, "before cache"); - let history = staged!("penalty history", context, OriginalNativePenaltyHistory::new(binding, context).map_err(at("OriginalNativePenaltyHistory::new"))?); - let ple_history = context.allocate(PLE_HISTORY_BYTES).map_err(at("ple_history"))?; - let ple_scratch = context.allocate(PLE_SCRATCH_BYTES).map_err(at("ple_scratch"))?; - let pool = staged!("CPU expert pool", context, CpuExpertPool::new(binding, config.cpu_workers).map_err(at("CpuExpertPool::new"))?); - let empty_session = staged!("empty-prompt session checkpoint", context, executor.checkpoint_session(binding, &mut session).map_err(at("checkpoint_session"))?); - let empty_draft = staged!("empty-prompt draft checkpoint", context, draft.checkpoint(binding, &session).map_err(at("draft.checkpoint"))?); - let prefix = match &config.prefix { - Some(prefix_config) => { - let available = crate::conversation::memory::available_memory(); - // the budget comes from the memory governor (what is left above the floors), not from an independent default - let complement_pending = (config.expert_tier.resident_budget_gib.max(0.0) * (1u64 << 30) as f64) as u64; - let bytes = crate::memory_governor::resolve_prefix_budget(prefix_config.budget, available, complement_pending) - .unwrap_or_else(|| prefix_config.resolve_budget(available)); - let mut prefix_config = prefix_config.clone(); - if let Some(g) = leleka_memory::Governor::global() { - // stop admitting before anything has to be shed: soft floor + reserve (the real CRM session sat 4.4 GiB above a 3 GiB floor) - prefix_config.memory_floor = prefix_config.memory_floor.max(g.policy().admit_floor()); - } - let prefix_config = &prefix_config; - if bytes == 0 { - operator_note(&format!( - "prefix cache off (budget {:?}, available host memory {:?} MiB)", - prefix_config.budget, - available.map(|b| b >> 20) - )); - None - } else { - let identity = format!("qwen4exp:{PINNED_MODEL}:kv={:?}:resident={}", config.kv_format, config.kv_resident); - let serve = PrefixServe::new(prefix_config.clone(), config.capacity, bytes, &identity); - operator_note(&format!( - "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, host memory available {:?} MiB, namespace {}", - serve.block_tokens(), - bytes >> 20, - PARKED_STATE_ESTIMATE >> 20, - PARKED_BYTES_PER_TOKEN, - available.map(|b| b >> 20), - crate::prefix_cache::summary::hex(serve.namespace()) - )); - Some(serve) - } - } - None => None, - }; - let conversation = if prefix.is_some() { None } else { config.conversation.clone().map(ServeConversation::new) }; - let residency = ResidencyState::new(&config.expert_tier); - report_kernel_selection(); - vram_note(context, "before expert tier"); - let mut loan = None; - let tier_open = staged!("expert tier (VRAM slots + profile fill)", context, original_serve_residency::open_tier(binding, context, &moe, &config.expert_tier, config.capacity).map_err(at("expert tier"))?); - let expert_cache = match tier_open { - Some((cache, filled)) => { - if config.expert_tier.prefill_borrow && config.expert_tier.profile.is_some() { - loan = original_serve_residency::loan_slots(&cache, prefill_bytes(layout).map_err(at("prefill bytes"))?) - .map_err(at("expert-cache loan"))?; - } - operator_note(&format!( - "expert cache {} slots ({:.2} GiB, {}), {filled} filled from the profile; the prompt path {}; GPU experts round differently from the CPU's (bench/results/2026-09-27-cache-parity)", - cache.slots(), - cache.bytes() as f64 / f64::from(1u32 << 30), - if cache.per_layer_admission() { "per layer" } else { "global" }, - match loan { - Some(k) => format!("borrows its last {k} slots"), - None => "allocates its own buffers".to_owned(), - } - )); - Some(cache) - } - None => None, - }; - vram_note(context, "after expert tier"); - let mut loan_tiers: Vec = Vec::new(); - if let (Some(full), Some(cache), true) = (loan, expert_cache.as_ref(), config.loan_tiers) { - for rows in LOAN_TIER_ROWS.into_iter().filter(|&r| r < config.capacity) { - let tier_layout = PrefillLayoutOptions { capacity: rows, ..layout }; - let slots = original_serve_residency::loan_slots(cache, prefill_bytes(tier_layout).map_err(at("prefill bytes (tier)"))?).map_err(at("expert-cache loan (tier)"))?; - if let Some(slots) = slots.filter(|&s| s < full && loan_tiers.last().is_none_or(|t| s > t.slots)) { - loan_tiers.push(LoanTier { rows, layout: tier_layout, slots }); - } - } - if !loan_tiers.is_empty() { - operator_note(&format!( - "prompt loan ladder: {}, up to {} rows {full} slots", - loan_tiers.iter().map(|t| format!("up to {} rows {} slots", t.rows, t.slots)).collect::>().join(", "), - config.capacity - )); - } - } - let initial_owners: Vec> = expert_cache - .as_ref() - .map(|cache| (0..cache.slots()).map(|slot| cache.slot_owner(slot)).collect()) - .unwrap_or_default(); - if arena.is_none() && loan.is_none() { - arena = Some(staged!("prefill arena (after the expert tier)", context, context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?)); - } - let this = Self { - binding, - context, - conversation, - prefix, - tail_consumed: None, - reused: 0, - resume_point: 0, - full_policy: mtp_full_policy(&rope), - scalar_policy: mtp_scalar_policy(&rope), - config, - settings, - max_cells, - rope, - blobs, - formats, - controller, - parked, - arm_label, - arm_order, - verifier_max_t, - broken: None, - empty_session, - empty_draft, - history, - ple_history, - ple_scratch, - arena, - layout, - expert_cache, - loan, - loan_tiers, - residency, - initial_owners, - seed_report: None, - seed_counts: None, - refill_pending: false, - refill_due: false, - timing: (0.0, 0.0), - marks: TtftMarks::default(), - executor, - draft, - session, - pool, - kar, - moe, - dense, - output, - embedding, - }; - this.register_memory_classes(); - crate::memory_governor::post_open(); - if let Some(governor) = leleka_memory::Governor::global() { - governor.log(&format!("stack open; inventory of allocation classes (accounted by their owners): -{}", governor.inventory().table())); - governor.log(&format!("load ledger (measured: kernel and driver deltas per opening step): -{}", governor.ledger().table())); - governor.publish(); - } - Ok(this) - } - - /// `Some` once a physical owner was lost: the stack must be closed and rebuilt. - pub(crate) fn health(&self) -> Option { - self.broken - } - - /// One request. Admission, reset, prompt conditioning and decode in order; see `run_request`. - pub(crate) fn serve( - &mut self, - request: &ServeRequest, - emit: &mut dyn FnMut(&[i32]) -> Result<()>, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result { - self.apply_memory_directive(); - self.marks = TtftMarks::start(); - let max_context = self.config.max_context; - let result = run_request(self, request, max_context, emit, cancel); - self.note_memory(); - result - } - - /// Follow the memory governor between requests: under pressure the prefix cache evicts (and restores its budget when the - /// pressure is over), and the conversation checkpoints are dropped. Cheap: a few atomics when nothing changed. - fn apply_memory_directive(&mut self) { - let Some(governor) = leleka_memory::Governor::global() else { return }; - let used = self.prefix.as_ref().map_or(0, |p| p.bytes() as u64); - let directive = governor.directive(used); - if let Some(prefix) = self.prefix.as_mut() { - let before = prefix.bytes(); - let freed = prefix.apply_shed(directive.prefix_budget, governor); - if freed > 0 { - operator_note(&format!( - "memory pressure ({}): prefix cache evicted {} MiB ({} -> {} MiB), budget {} MiB", - directive.level.as_str(), - freed >> 20, - before >> 20, - prefix.bytes() >> 20, - prefix.budget_bytes() >> 20 - )); - } - } - if directive.drop_conversation - && let Some(conversation) = self.conversation.as_mut() - && conversation.checkpoint_count() > 0 - { - conversation.invalidate(); - operator_note(&format!("memory pressure ({}): conversation checkpoints dropped", directive.level.as_str())); - } - } - - /// Keep the inventory's elastic classes current (the prefix store and the conversation checkpoints). - fn note_memory(&self) { - if leleka_memory::Governor::global().is_none() { - return; - } - if let Some(prefix) = self.prefix.as_ref() { - crate::memory_governor::set_bytes("prefix.store", prefix.bytes() as u64); - if let Some(g) = leleka_memory::Governor::global() { - g.note_prefix_used(prefix.bytes() as u64); - } - } - if let Some(conversation) = self.conversation.as_ref() { - crate::memory_governor::set_bytes("conversation.checkpoints", conversation.checkpoint_count() as u64 * crate::memory_governor::CHECKPOINT_BYTES); - } - } - - /// Register the stack's allocation classes with the inventory (sizes from the owners' own formulas and counters). - fn register_memory_classes(&self) { - use leleka_memory::{Space, When}; - let Some(governor) = leleka_memory::Governor::global() else { return }; - let _ = governor; - if let Some(f) = self.config.kv_footprint() { - crate::memory_governor::account("kv", "host_pinned", Space::HostPinned, When::Startup, "12 QSA layers x serving cells x 1056 B, pinned and device-mapped (the whole serving context, allocated at open)", f.pinned_host_bytes as u64); - crate::memory_governor::account("kv", "vram_window", Space::Device, When::Startup, "12 layers x resident pages x 4244 B (+ page table + resolver state)", f.vram_bytes as u64); - crate::memory_governor::account("kv", "prompt_stage", Space::Device, When::Startup, "one INT8 staging pool of the prompt path (identity layout)", f.stage_bytes as u64); - } - if let Ok(bytes) = prefill_bytes(self.layout) { - crate::memory_governor::account( - "prefill", - if self.loan.is_some() { "arena_borrowed" } else { "arena" }, - Space::Device, - When::Startup, - if self.loan.is_some() { "carve of the prefill arena, borrowed from the last slots of the expert cache (not additional)" } else { "carve of the prefill arena at the chunk capacity" }, - if self.loan.is_some() { 0 } else { bytes as u64 }, - ); - } - if let Some(cache) = self.expert_cache.as_ref() { - crate::memory_governor::account("expert_cache", "slots", Space::Device, When::Startup, "slots x slot bytes (VRAM expert tier)", cache.bytes() as u64); - } - crate::memory_governor::account("ple", "history_and_scratch", Space::Device, When::Startup, "PLE history image + scratch", (PLE_HISTORY_BYTES + PLE_SCRATCH_BYTES) as u64); - crate::memory_governor::account("context", "accounted_total", Space::Device, When::Lazy, "sum of the context's budgeted allocations (not additive with the classes above; see the ledger for the driver-seen total)", 0); - if let Some(prefix) = self.prefix.as_ref() { - crate::memory_governor::account( - "prefix", - "store", - Space::HostPageable, - When::Elastic, - "blocks (14,208 B per token) + node states (~127 MiB each) under the governor-granted budget", - prefix.bytes() as u64, - ); - } - if self.conversation.is_some() { - crate::memory_governor::account( - "conversation", - "checkpoints", - Space::HostPageable, - When::Elastic, - "checkpoints x ~118 MiB (GDN/PLE images, draft ring, index tails)", - 0, - ); - } - } - - /// Labels of the window policies of `LELEKA_SPEC_ARMS` in the order given (empty when unset), the live one included. - #[allow(dead_code)] - pub(crate) fn spec_arms(&self) -> Vec { - self.arm_order.clone() - } - /// Make `label` the window policy of the following requests (between requests only). Returns false for an unknown label. - #[allow(dead_code)] - pub(crate) fn select_spec_arm(&mut self, label: &str) -> bool { - if self.arm_label == label { - return true; - } - let Some(at) = self.parked.iter().position(|(l, _, _)| l == label) else { return false }; - let (new_label, new_settings, new_controller) = self.parked.swap_remove(at); - let old_label = std::mem::replace(&mut self.arm_label, new_label); - let old_settings = std::mem::replace(&mut self.settings, new_settings); - let old_controller = std::mem::replace(&mut self.controller, new_controller); - self.parked.push((old_label, old_settings, old_controller)); - true - } - /// The live arm's own request floor, if its label pinned one (`fixed4@0`). - #[allow(dead_code)] - pub(crate) fn spec_arm_min_p(&self) -> Option { - self.settings.request_min_p - } - #[allow(dead_code)] - pub(crate) fn spec_arm(&self) -> &str { - &self.arm_label - } - - /// Wall-clock milliseconds of the last request's prompt phase and decode phase. - #[cfg_attr(not(test), allow(dead_code))] - pub(crate) fn last_timing(&self) -> (f64, f64) { - self.timing - } - - /// Where the last request's time to first token went: `(resumed, prefilled, assembled, first_round)`, each the - /// milliseconds since `serve` was entered when that stage ended (`resumed`: the cache lookup, import and any reset; - /// `prefilled`: the prompt chunks, the lent-slot refill and the seed; `assembled`: the verifier (graphs, canonical - /// state upload); `first_round`: the first verified round was emitted). NaN for a stage the request did not reach. - #[allow(dead_code)] - pub(crate) fn ttft_marks(&self) -> [f64; 4] { - self.marks.as_array() - } - - /// The VRAM expert tier's counters (`None` when the tier is off). - pub(crate) fn expert_tier_stats(&self) -> Option { - self.expert_cache.as_ref().map(|cache| { - let mut stats = self.residency.stats; - stats.swaps = cache.swaps(); - stats - }) - } - - /// The tier's configuration, for an experiment that switches the adaptive tier or the seed between requests (the - /// adaptive counts are allocated at open, so `adapt_every` may be changed freely, a seed needs the tier on). - #[allow(dead_code)] - pub(crate) fn expert_tier_mut(&mut self) -> &mut ExpertTierConfig { - &mut self.config.expert_tier - } - - /// The last request's seed from the prompt's routing (`None`: seed off, or no prompt rows were read). - #[allow(dead_code)] - pub(crate) fn last_seed(&self) -> Option { - self.seed_report - } - - /// Cumulative (vram, pcie, cpu) window entries after each verified round of the last request. - #[allow(dead_code)] - pub(crate) fn round_marks(&self) -> Vec<[u64; 3]> { - self.residency.round_marks() - } - - /// A first-request state for an experiment: the tier back on the starting profile's set, the adaptive counts and - /// the draft/adaptation controller as in a new process. Returns the swaps the restore needed. - #[allow(dead_code)] - pub(crate) fn reset_expert_tier(&mut self) -> Result { - if let Some(error) = self.broken { - return Err(error); - } - self.residency.clear_usage(); - self.controller = self.settings.controller()?; - match self.expert_cache.as_mut() { - Some(cache) => original_serve_seed::restore_placement(self.binding, &self.moe, cache, &mut self.pool, &mut self.residency.spans, &self.initial_owners), - None => Ok(0), - } - } - - /// Prompt tokens the last request reused from the conversation cache (generate.cpp `REUSED`). - pub(crate) fn reused_tokens(&self) -> usize { - self.reused - } - - /// The position the conversation cache resumed the last request at (equals `reused_tokens` unless - /// `STRATA_CKPT_REREAD` re-read that prefix from 0). - #[cfg_attr(not(test), allow(dead_code))] - pub(crate) fn resume_point(&self) -> usize { - self.resume_point - } - - /// Drop every conversation checkpoint and the live state: the next request reads its whole prompt. - #[cfg_attr(not(test), allow(dead_code))] - pub(crate) fn forget_conversation(&mut self) { - if let Some(conversation) = self.conversation.as_mut() { - conversation.invalidate(); - } - if let Some(prefix) = self.prefix.as_mut() { - prefix.invalidate(); - } - } - - /// Verification arm: while set, requests read their whole prompt on the grid without using or changing the prefix - /// cache (the reference a cached request must reproduce). - #[allow(dead_code)] - pub(crate) fn prefix_bypass(&mut self, bypass: bool) { - if let Some(prefix) = self.prefix.as_mut() { - prefix.set_bypass(bypass); - } - } - - /// Drop the cached sessions nobody used for the retention time (60 minutes by default); the idle loop calls this. - pub(crate) fn prefix_expire_idle(&mut self) -> usize { - self.prefix.as_mut().map_or(0, |prefix| prefix.expire_idle()) - } - - /// The prefix cache's summary for a front router (`None` when the cache is off). - #[allow(dead_code)] - pub(crate) fn prefix_summary(&self, max_heads: usize) -> Option { - self.prefix.as_ref().map(|prefix| prefix.summary(max_heads)) - } - - /// The `prefix_match` query: how many tokens of the prompt whose block hash chain is `chain` are cached. - #[allow(dead_code)] - pub(crate) fn prefix_match(&self, chain: &[u64]) -> Option { - self.prefix.as_ref().map(|prefix| prefix.prefix_match(chain)) - } - - /// The prefix cache's metrics line (`None` when the cache is off). - #[allow(dead_code)] - pub(crate) fn prefix_metrics(&self) -> Option { - self.prefix.as_ref().map(|prefix| prefix.describe()) - } - - /// Bytes the prefix cache holds now (0 when it is off). - #[allow(dead_code)] - pub(crate) fn prefix_bytes(&self) -> usize { - self.prefix.as_ref().map_or(0, |prefix| prefix.bytes()) - } - - /// The prefix cache's current byte budget (0 when it is off or fully shed). - #[allow(dead_code)] - pub(crate) fn prefix_budget_bytes(&self) -> usize { - self.prefix.as_ref().map_or(0, |prefix| prefix.budget_bytes()) - } - - /// Close every owner in dependency order; the first failure is reported after all were attempted. - pub(crate) fn close(self) -> Result<()> { - let Self { - conversation, residency, history, ple_history, ple_scratch, arena, expert_cache, executor, draft, session, pool, kar, - moe, dense, output, embedding, .. - } = self; - drop(conversation); - // the span cache retains registered-source spans of the bank `moe` closes below - drop(residency); - let mut first: Option = None; - let mut note = |result: Result<()>| { - if let Err(error) = result { - first.get_or_insert(error); - } - }; - note(history.close()); - note(ple_history.release().map_err(|_| Error::CudaExecution)); - note(ple_scratch.release().map_err(|_| Error::CudaExecution)); - drop(arena); - if let Some(cache) = expert_cache { - note(cache.close().map_err(|e| super::original_serve_verifier::driver_error(&e))); - } - note(executor.close()); - note(draft.close()); - drop((session, pool, kar)); - note(moe.close()); - note(dense.close()); - note(output.close()); - note(embedding.close()); - first.map_or(Ok(()), Err) - } - - fn mark_broken(&mut self, error: Error) { - self.broken.get_or_insert(error); - } - - /// Hand the twelve QSA owners to a fresh verifier and run the request's decode phase over it. - fn decode_phase( - &mut self, - request: &ServeRequest, - emit: &mut dyn FnMut(&[i32]) -> Result<()>, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result { - let Self { - binding, - context, - config, - settings, - max_cells, - rope, - blobs, - formats, - full_policy, - controller, - arm_label, - verifier_max_t, - history, - ple_history, - ple_scratch, - executor, - draft, - session, - pool, - kar, - moe, - dense, - output, - broken, - conversation, - expert_cache, - residency, - refill_pending, - refill_due, - marks, - prefix, - tail_consumed, - .. - } = self; - let binding: &ModelBinding = *binding; - let context: &'ctx Context<'ctx> = *context; - if controller.is_failed() { - // a failed restore/finish poisoned the controller; its adaptive cadence is the only thing lost - *controller = settings.controller()?; - } - crate::bringup_trace!("DBG[{:.0}s] decode_phase start", dbg_el()); - let sampling = RequestSampling::new(request.params, request.path)?; - let n = request.prompt.len(); - let base = session.original_verified_base()?; - crate::bringup_trace!("DBG[{:.0}s] decode: base position {} (n-1 = {})", dbg_el(), base.position, n as u64 - 1); - if base.position != (n as u64 - 1) { - return Err(Error::IdentityMismatch.into()); - } - // generate.cpp `ver.set_pcie_mode`: only a window that can stage anything over PCIe records the copy kernel. - let pcie_mode = match (expert_cache.as_ref(), moe.original_expert_bank()) { - (Some(_), Some(bank)) if config.expert_tier.pcie_num_for(bank.pageable()) > 0 => { - config.expert_tier.pcie_mode.graph_mode(bank.pageable(), blobs.spans_tile_blobs()).ok_or(Error::Unsupported( - super::contract::Stage::Session, - ))? - } - _ => 0, - }; - let p = profile::span("decode.seed_ple"); - seed_ple_history(&base, ple_history).map_err(|f| SpecError::Forward(f.error))?; - drop(p); - // the window reads the shared experts of all 48 layers in place: load/refresh them together first - let p = profile::span("decode.shared"); - let shared = moe.ensure_original_verify_shared(binding)?; - drop(p); - crate::bringup_trace!("DBG[{:.0}s] decode: shared experts loaded", dbg_el()); - let owners = executor.take_qsa_owners()?; - let ple_history: &DeviceBuffer<'ctx> = &*ple_history; - let weights = VerifyWeights { dense: &*dense, moe: &*moe, shared: &shared, formats: &*formats, ple_scratch: &*ple_scratch }; - let p = profile::span("decode.assemble"); - // queued after assembly's own uploads (canonical GDN image), before the graph capture - let mut queue_refill = || -> Result<()> { - if !std::mem::take(&mut *refill_due) { - return Ok(()); - } - if let Some(cache) = expert_cache.as_mut() { - let _p = profile::span("prefill.refill"); - original_serve_residency::refill_lent(binding, &*moe, cache, &mut residency.spans, true)?; - *refill_pending = true; - } - Ok(()) - }; - let assembled = assemble( - binding, &weights, context, &*output, &base, owners, ple_history, rope, blobs, *verifier_max_t, *max_cells, - pcie_mode, &mut queue_refill, - ); - drop(p); - marks.assembled = marks.since(); - // the lent slots' refill copies (queued at the end of the prompt phase) have run behind the assembly: wait for them - // before a window or the tier's own bookkeeping touches the cache - if std::mem::take(refill_pending) { - if let Some(cache) = expert_cache.as_mut() { - if let Err(error) = original_serve_residency::settle_refill(cache) { - broken.get_or_insert(error); - if let Ok(resources) = assembled { - let _ = disassemble(resources).map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); - } - return Err(SpecError::Forward(error)); - } - } - } - vram_note(context, "decode after assemble"); - crate::bringup_trace!("DBG[{:.0}s] decode: assemble -> {}", dbg_el(), if assembled.is_ok() { "ok" } else { "ERR" }); - let resources = match assembled { - Ok(resources) => resources, - Err(lost) => { - operator_line("assemble", &lost.failure); - if let Some(owners) = lost.owners { - if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners) { - broken.get_or_insert(error); - } - } else { - broken.get_or_insert(Error::IdentityMismatch); - } - return Err(SpecError::Forward(lost.failure.error)); - } - }; - let DecodeResources { verifier, qsa, slots } = resources; - // the NaN guard's retry takes a refused window back from these (OriginalVerifier::discard_window) - qsa.set_window_snapshots(settings.nan_guard.retries > 0); - let committed = request.prompt[..n - 1].to_vec(); - // The window's expert tier: the GPU share first and the CPU pool on the rest, or the CPU pool alone. - let mut gpu_pool; - let pool: &mut dyn OriginalServePool<'ctx> = match (expert_cache.as_mut(), moe.original_expert_bank()) { - (Some(cache), Some(bank)) => { - let pcie_num = config.expert_tier.pcie_num_for(bank.pageable()); - let tail_rank = original_serve_residency::effective_tail_rank(&*cache); - let pcie_locked = if pcie_num > 0 && original_serve_residency::pcie_locked_only() { bank.locked_experts() } else { Vec::new() }; - gpu_pool = GpuExpertPool { - binding, - moe: &*moe, - cache, - bank, - cpu: &mut *pool, - state: &mut *residency, - pcie_num, - adapt_every: config.expert_tier.adapt_every, - adapt_swaps: config.expert_tier.adapt_swaps as usize, - tail_rank, - pcie_locked, - }; - &mut gpu_pool - } - (Some(_), None) => return Err(SpecError::Forward(Error::IdentityMismatch)), - (None, _) => &mut *pool, - }; - let owners = HostOwners { - binding, - dense: &*dense, - context, - session: &mut *session, - draft: &mut *draft, - executor: &mut *executor, - kar: kar.as_mut(), - history: &mut *history, - pool, - qsa: Rc::clone(&qsa), - slots, - ple_history, - policy: &*full_policy, - }; - let want_tail = config.prefix.as_ref().is_some_and(|p| p.tail == TailMode::Reply) && prefix.is_some(); - controller.set_final_draft(want_tail); - *tail_consumed = None; - let host = OriginalServeHost::new(owners, committed, config.max_context as u64, sampling); - let (served, verifier, outcome) = match host { - Err(error) => (Err(SpecError::Forward(error)), verifier, None), - Ok(host) => { - let port = super::original_serve_engine::TracePort(NativeServePort::new(verifier, host)); - let engine = OriginalServeEngine::new(port, VOCABULARY, settings.max_t, settings.max_drafts()); - match engine { - Err(error) => { - // `new` consumed the port on failure; the verifier is gone with it. Treated as lost below. - let _ = error; - broken.get_or_insert(Error::IdentityMismatch); - return Err(SpecError::Forward(Error::IdentityMismatch)); - } - Ok(mut engine) => { - crate::bringup_trace!("DBG[{:.0}s] decode: engine ready, serving", dbg_el()); - let started = Instant::now(); - let serve_span = profile::span("decode.serve"); - let result = engine.set_min_p(request.spec_min_p).map_err(SpecError::Forward).and_then(|()| { - serve_request( - controller, - &mut engine, - &request.prompt, - request.max_new, - request.spec_min_p, - &request.eos, - |tokens| { - if marks.first_round.is_nan() { - marks.first_round = marks.since(); - } - emit(tokens) - }, - &mut *cancel, - || started.elapsed().as_secs_f64() * 1e3, - ) - }); - drop(serve_span); - { - // the controller's round counters belong to this request in every window policy - let stats = controller.take_stats(); - if super::original_spec_controller::stats_enabled() { - eprintln!("DBG spec-stats arm={} {}", arm_label, stats.line()); - } - } - if let Err(e) = &result { crate::bringup_trace!("DBG[{:.0}s] serve_request err {e:?}", dbg_el()); } - let (mut verifier, mut host) = engine.into_port().0.into_parts(); - // STRATA_VERIFY_PROFILE=1: the GPU stage times of the request's windows (empty otherwise) - let gpu_profile = verifier.profile_report(); - if !gpu_profile.is_empty() { - eprintln!("DBG verify-profile:{gpu_profile}"); - } - // conversation cache: the session can be continued as is only when the draft ring - // stands at its position (then its recurrent state is settled to match) - let live = conversation.is_some() - && matches!(result, Ok(_) | Err(SpecError::Cancelled)) - && host.draft_in_step(); - // prefix cache, TailMode::Reply: the session settled and the ring in step (the final window was drafted) - let tail = want_tail && result.is_ok() && prefix.is_some() && host.draft_in_step(); - if want_tail && result.is_ok() && !tail { - operator_text("prefix tail: the draft ring is not at the session's position; no checkpoint at the end of this decode"); - } - if (result.is_ok() && config.settle_state) || live || tail { - match host.settle_state(&mut verifier) { - Ok(()) if live => { - if let Some(conversation) = conversation.as_mut() { - conversation.note_live(host.committed().to_vec()); - } - } - Ok(()) if tail => *tail_consumed = Some(host.committed().to_vec()), - Ok(()) => {} - Err(error) => { - broken.get_or_insert(error); - } - } - } - let outcome = host.finish(); - (result, verifier, Some(outcome)) - } - } - } - }; - // The MTP drafter's cached round programs and staged window are bound to THIS verifier's bank: release them before the - // bank closes (it is shared while they live) and so the next request captures against its own bank. - let p = profile::span("decode.release_mtp"); - let released = executor.mtp_release_verifier(binding); - drop(p); - if let Err(error) = released { - operator_line("release MTP verifier bindings", &failure(error)); - broken.get_or_insert(error); - } - // Close the verifier (drains both streams, drops the graphs) and take the physical owners back at - // the session's lineage; an abandoned window is rolled back there. - let p = profile::span("decode.disassemble"); - let disassembled = disassemble(DecodeResources { verifier, qsa, slots }); - drop(p); - match disassembled { - Ok(owners) => { - let _p = profile::span("decode.adopt"); - if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners) { - broken.get_or_insert(error); - } - } - Err(lost) => { - operator_line("disassemble", &lost); - broken.get_or_insert(lost.error); - } - } - if outcome.is_some_and(|o| o.failed) { - broken.get_or_insert(Error::IdentityMismatch); - } - served - } - - /// Condition `prompt[resume..n-1]` through the batched Original prefill, one chunk transaction at a time - /// (the session and the draft ring stand at `resume`; with the conversation cache's `STRATA_CKPT_REREAD` - /// they stand at 0 and the reread segment comes first). After each published chunk the conversation cache - /// takes its periodic and turn/root checkpoints. - /// - /// With the expert tier, the swaps in flight land first (generate.cpp `apply_pending(true)`), every chunk - /// borrows the cache's last slots (`prefill_chunk`) and every lent slot is refilled before the decode - /// phase, whatever the read's outcome (generate.cpp `refill`). - fn prefill_phase( - &mut self, - request: &ServeRequest, - resume: usize, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result<(), SpecError> { - self.residency.begin_request(); - self.seed_report = None; - if let Some(cache) = self.expert_cache.as_mut() { - let _p = profile::span("prefill.wait_swaps"); - cache.wait_swaps().map_err(|e| SpecError::Forward(super::original_serve_verifier::driver_error(&e)))?; - } - // LELEKA_ORIGINAL_SERVE_SEED: the MoE stage adds its host-known route counts per (layer, expert) - let seeding = self.config.expert_tier.seed_swaps > 0 && self.expert_cache.is_some(); - if seeding { - self.moe.capture_prompt_routing(true, self.config.expert_tier.seed_decay); - } - let p = profile::span("prefill.read"); - let read = self.prefill_actions(request, resume, cancel); - drop(p); - let _p = profile::span("prefill.refill"); - // a failed or cancelled read still refills at once (generate.cpp `refill`); a good one overlaps the copies with the - // decode phase's host-side assembly - // (the prompt-routing seed needs the lent slots refilled first, so it turns the deferral off for its requests) - let defer = read.is_ok() && !seeding && original_serve_residency::refill_defer_enabled() && self.loan.is_some() && self.expert_cache.is_some(); - let refilled = match (self.loan, self.expert_cache.as_mut()) { - (Some(_), Some(cache)) if !defer => { - original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false).map(|_| ()) - } - _ => Ok(()), - }; - let routing = if seeding { self.moe.take_prompt_routing() } else { None }; - let seeded = match (&read, &refilled, routing) { - (Ok(()), Ok(()), Some(counts)) if !defer => { - let _p = profile::span("prefill.seed"); - self.seed_residency(&counts) - } - _ => Ok(()), - }; - self.refill_due = defer; - match (read, refilled, seeded) { - (Ok(()), Err(error), _) | (Ok(()), Ok(()), Err(error)) => { - self.mark_broken(error); - Err(SpecError::Forward(error)) - } - (read, _, _) => read, - } - } - - /// Put the prompt's own routing into the tier's placement before the first window (see `original_serve_seed`). - fn seed_residency(&mut self, counts: &[f32]) -> Result<()> { - let tier = &self.config.expert_tier; - let (max, keep, usage) = (tier.seed_swaps, tier.seed_keep, tier.seed_usage); - let Some(cache) = self.expert_cache.as_mut() else { return Ok(()) }; - let started = Instant::now(); - let max_rows = tier.seed_max_rows; - if max_rows > 0 { - let rows = original_serve_seed::summarize(counts, &[]).rows; - if rows > max_rows as u64 { - if std::env::var_os("LELEKA_SEED_TRACE").is_some() { - eprintln!("DBG seed: skipped, the prompt routed {rows} rows (cap {max_rows})"); - } - return Ok(()); - } - } - let swaps = original_serve_seed::plan(counts, cache, max, keep); - let planned = started.elapsed(); - let mut report = original_serve_seed::summarize(counts, &swaps); - original_serve_seed::queue_swaps(self.binding, &self.moe, cache, &mut self.pool, &mut self.residency.spans, &swaps)?; - report.plan_ms = planned.as_secs_f64() * 1e3; - report.queue_ms = (started.elapsed() - planned).as_secs_f64() * 1e3; - self.residency.add_usage(counts, usage); - if std::env::var_os("LELEKA_SEED_TRACE").is_some() { - eprintln!( - "DBG seed: prompt rows {} routed -> {} swaps (gain {:.0}, most in one layer {}), plan {:.2} ms, queue {:.2} ms", - report.rows, report.planned, report.gain, report.max_layer_swaps, report.plan_ms, report.queue_ms - ); - } - self.seed_report = Some(report); - if std::env::var_os("LELEKA_SEED_TRACE").is_some() { - self.seed_counts = Some(counts.to_vec()); - } - Ok(()) - } - - /// `LELEKA_SEED_TRACE`: how much of the request's decode routing (the adaptive counts, so for a static arm) the resident - /// set covers: the starting profile's set, the prompt's top experts (what the seed installs, per layer slot counts of the - /// profile) and the best any static set could do (the decode's own top experts). - fn seed_coverage_trace(&mut self) { - let Some(prompt) = self.seed_counts.take() else { return }; - let usage = self.residency.usage(); - if usage.len() != prompt.len() || self.config.expert_tier.adapt_every != 0 { - return; - } - let mut slots = [0usize; 48]; - let mut initial = vec![false; 48 * 512]; - for &(layer, expert) in self.initial_owners.iter().flatten() { - slots[layer] += 1; - initial[layer * 512 + expert] = true; - } - let total: f64 = usage.iter().map(|&u| f64::from(u)).sum(); - if total <= 0.0 { - return; - } - let (mut by_prompt, mut oracle, mut by_initial) = (0f64, 0f64, 0f64); - for layer in 0..48 { - let range = layer * 512..(layer + 1) * 512; - let mut order: Vec = (0..512).collect(); - order.sort_by(|&a, &b| prompt[range.start + b].total_cmp(&prompt[range.start + a])); - by_prompt += order.iter().take(slots[layer]).map(|&e| f64::from(usage[range.start + e])).sum::(); - let mut best: Vec = usage[range.clone()].to_vec(); - best.sort_by(|a, b| b.total_cmp(a)); - oracle += best.iter().take(slots[layer]).map(|&u| f64::from(u)).sum::(); - by_initial += (0..512).filter(|&e| initial[range.start + e]).map(|e| f64::from(usage[range.start + e])).sum::(); - } - // Opt-in: `seed_counts` is only recorded under LELEKA_SEED_TRACE, so this returns early (and prints nothing) otherwise. - eprintln!( - "DBG seed-coverage: decode entries {total:.0}; covered by the starting set {:.1}%, the prompt's top experts {:.1}%, the decode's own top experts {:.1}% (oracle)", - 100.0 * by_initial / total, - 100.0 * by_prompt / total, - 100.0 * oracle / total - ); - } - - fn prefill_actions( - &mut self, - request: &ServeRequest, - resume: usize, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result<(), SpecError> { - let binding: &ModelBinding = self.binding; - let n = request.prompt.len(); - crate::bringup_trace!("DBG[{:.0}s] prefill_phase start n={n} resume={resume}", dbg_el()); - // generate.cpp: mtp.set_prompt_len(n) before the prompt is read; the draft cap and the request's - // sampling parameters configure the actor for the whole request. - let mtp_setup_span = profile::span("prefill.mtp_setup"); - self.executor.set_mtp_prompt_len(binding, n as i64)?; - self.executor.set_mtp_max_drafts(binding, i32::try_from(self.settings.max_drafts()).map_err(|_| Error::Overflow)?)?; - self.executor.set_mtp_draft_sampling(binding, &request.params)?; - drop(mtp_setup_span); - if n < 2 { - return Ok(()); - } - let setup_span = profile::span("prefill.setup"); - let tokens: Vec = request.prompt.iter().map(|&t| t as u32).collect(); - let source = OriginalPromptInput::from_tokenized(binding, &tokens)?; - let options = PromptOptions { - context_tokens: usize::try_from(self.config.max_context).map_err(|_| Error::Overflow)?, - prompt_cache: false, - turn_token: None, - root_min: 0, - // every conditioning read goes through the batched prefill (the verify-window read of short - // prompts needs the verifier during the prompt phase; see the open items) - short_read: 64, - force_batched: true, - verify_width: 4, - auto_max: 8192, - grid: 0, - }; - let (options, reread_to) = match (&self.prefix, &self.conversation) { - // the prefix cache reads on its grid and has no turn/root cuts: every checkpoint is a pure function of its tokens - // (a request that resumes between two grid points, from a request-end checkpoint, reads its suffix in as few chunks as the - // capacity allows: its states are not grid-canonical anyway) - (Some(prefix), _) => (PromptOptions { grid: if resume % prefix.block_tokens() == 0 { prefix.block_tokens() } else { 0 }, ..options }, None), - (None, Some(conversation)) => (conversation.config().plan_options(options), conversation.reread_to()), - (None, None) => (options, None), - }; - let capacity = self.config.capacity; - let plan = PromptPlan::new(&tokens, resume, reread_to, None, options, capacity).map_err(|e| { crate::bringup_trace!("DBG[{:.0}s] PromptPlan::new err {e:?} (n={n} capacity={capacity})", dbg_el()); plan_error(e) })?; - crate::bringup_trace!("DBG[{:.0}s] prompt plan ok", dbg_el()); - drop(setup_span); - for action in plan { - crate::bringup_trace!("DBG[{:.0}s] prompt action path={:?} first={} count={}", dbg_el(), action.path, action.first, action.count); - if action.path == PromptPath::FinalSeed { - // the last prompt token is the first verify input of the decode phase - break; - } - let PromptPath::Batched { .. } = action.path else { - return Err(Error::IdentityMismatch.into()); - }; - if self.session.target_origin()?.next_position() != action.first as u64 { - return Err(Error::IdentityMismatch.into()); - } - if cancel() { - return Err(SpecError::Cancelled); - } - if let Some(prefix) = self.prefix.as_mut() { - prefix.before_chunk(action.first); - } - self.prefill_chunk(&source, action.count, cancel)?; - self.after_prompt_action(&request.prompt, &action); - self.prefix_after_chunk(&request.prompt, action.first + action.count); - } - if self.session.target_origin()?.next_position() != (n as u64 - 1) { - return Err(Error::IdentityMismatch.into()); - } - self.prefix_after_prefill(&request.prompt); - Ok(()) - } - - /// One batched chunk of `count` rows from the session's position: the forward transaction and its publication. - /// With a loan the chunk's buffers are the expert cache's last slots, lent for this chunk only (the lent - /// slots stay misses until `prefill_phase` refills them); otherwise the stack's own buffers. - fn prefill_chunk( - &mut self, - source: &Rc, - count: usize, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result<(), SpecError> { - let Self { - binding, moe, arena, layout, expert_cache, loan, loan_tiers, executor, draft, session, kar, dense, embedding, - scalar_policy, .. - } = self; - let mut chunk = PromptChunk { - binding: *binding, - executor: &mut *executor, - dense: &*dense, - session: &mut *session, - source, - kar: kar.as_mut(), - moe: &mut *moe, - draft: &mut *draft, - embedding: &*embedding, - scalar_policy: &*scalar_policy, - }; - let first = chunk.session.target_origin().map(|o| o.next_position()).unwrap_or(0); - super::prefill_profile::begin_chunk(); - let ran = match (*loan, expert_cache.as_mut(), arena.as_mut()) { - (Some(slots), Some(cache), _) => match { - let _span = super::prefill_profile::span(super::prefill_profile::Stage::Lend, None); - // the smallest rung of the ladder that holds the chunk - let (slots, options) = tier_for(loan_tiers, count).map_or((slots, *layout), |t| (t.slots, t.layout)); - cache.lend_prefill_tail(slots, options) - } { - Ok(mut lent) => chunk.run(count, &mut lent, cancel), - Err(e) => Err(SpecError::Forward(super::original_serve_verifier::driver_error(&e))), - }, - (_, _, Some(own)) => chunk.run(count, own, cancel), - _ => Err(Error::IdentityMismatch.into()), - }; - if ran.is_ok() { - super::prefill_profile::end_chunk(first, count); - } - ran - } - - /// The prefix cache at the end of the prefill: with `TailMode::Prompt` or `Reply` a checkpoint at `n - 1`, where the next turn of - /// the session resumes (its prompt starts with this one). A checkpoint that cannot be taken costs only itself. - fn prefix_after_prefill(&mut self, prompt: &[i32]) { - let Some(mut prefix) = self.prefix.take() else { return }; - let _span = profile::span("prefix.after_prefill"); - match prefix.after_prefill(self, prompt) { - Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { - operator_text(&format!("prefix tail admit (prompt end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); - } - Ok(other) => operator_text(&format!("prefix tail (prompt end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())), - Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the prefill; skipped")), - } - self.prefix = Some(prefix); - } - - /// The end of the decode (`TailMode::Reply`): a checkpoint at the end of the prompt and the committed reply. The session is settled and the - /// draft ring stands at its position (`decode_phase` made sure); the cells past the prompt were produced by the decode. - fn prefix_after_decode(&mut self, consumed: &[i32]) { - let Some(mut prefix) = self.prefix.take() else { return }; - let _span = profile::span("prefix.after_decode"); - match prefix.after_decode(self, consumed) { - Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { - operator_text(&format!("prefix tail admit (decode end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); - } - Ok(other) => operator_text(&format!("prefix tail (decode end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())), - Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the decode; skipped")), - } - self.prefix = Some(prefix); - } - - /// The prefix cache after a published chunk: a checkpoint at the grid point if the policy wants one. A checkpoint - /// that cannot be built costs the cache, never the request. - fn prefix_after_chunk(&mut self, prompt: &[i32], end: usize) { - let Some(mut prefix) = self.prefix.take() else { return }; - let _span = profile::span("prefix.after_chunk"); - match prefix.after_chunk(self, prompt, end) { - Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { - if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() { - operator_text(&format!("prefix admit: tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); - } - } - Ok(other) => { - if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() && !matches!(other, ChunkOutcome::Nothing) { - operator_text(&format!("prefix admit (grid point {end}) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())); - } - } - Err(error) => { - operator_text(&format!("prefix cache: {error:?} while checkpointing; dropping the cache")); - prefix.invalidate(); - } - } - self.prefix = Some(prefix); - } - - /// A cancel between two prompt chunks leaves the session at the last published one: that is still the request's conversation - /// (`ServeConversation::note_cancelled_prefill`). The claim needs the same state a live continuation needs at the next - /// request: nothing lost, the recurrent state settled and the draft ring at the session's position. - fn keep_conversation_after_cancelled_prefill(&mut self, request: &ServeRequest) { - let Some(mut conversation) = self.conversation.take() else { return }; - if let Ok(position) = ResumeDevice::position(self) { - let in_step = ResumeDevice::live_in_step(self); - if conversation.note_cancelled_prefill(&request.prompt, position, in_step) { - operator_text(&format!("cancelled request keeps its conversation: {position} tokens live")); - } - } - self.conversation = Some(conversation); - } - - /// The conversation cache's bookkeeping after a published chunk. A checkpoint that cannot be saved costs - /// the cache, never the request: the cache is dropped and the request goes on. - fn after_prompt_action(&mut self, prompt: &[i32], action: &crate::backend::original_prompt::PromptAction) { - let Some(mut conversation) = self.conversation.take() else { return }; - let _span = profile::span("conv.after_action"); - if let Err(error) = conversation.after_action(self, prompt, action) { - operator_text(&format!("conversation cache: {error}; dropping the cache")); - conversation.invalidate(); - } - self.conversation = Some(conversation); - } -} - -/// The owners one batched prompt chunk needs, so the chunk runs over the stack's own buffers or a loan. -struct PromptChunk<'s, 'ctx> { - binding: &'s ModelBinding, - executor: &'s mut OriginalPromptExecutor<'ctx>, - dense: &'s DenseWeightCache<'ctx>, - session: &'s mut QwenSession<'ctx>, - source: &'s Rc, - kar: Option<&'s mut KarPleCache<'ctx>>, - moe: &'s mut MoeWeightCache<'ctx>, - draft: &'s mut super::session::original_prompt::draft::OriginalDraftSession<'ctx>, - embedding: &'s OriginalPromptEmbedding<'ctx>, - scalar_policy: &'s OriginalMtpScalarPolicy, -} -impl<'ctx> PromptChunk<'_, 'ctx> { - fn run( - &mut self, - count: usize, - arena: &mut OriginalPrefillArena<'_, 'ctx>, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result<(), SpecError> { - let pending = self.executor.forward( - self.binding, - self.dense, - &mut *self.session, - self.source, - count, - self.kar.as_deref_mut(), - &mut *self.moe, - &mut *arena, - &mut *self.draft, - self.embedding, - self.scalar_policy, - || cancel(), - ); - if let Err(e) = &pending { crate::bringup_trace!("DBG[{:.0}s] executor.forward err {e:?}", dbg_el()); } - let pending = match pending { - Ok(pending) => pending, - Err(error) if cancel() => { - let _ = error; - return Err(SpecError::Cancelled); - } - Err(error) => return Err(SpecError::Forward(error)), - }; - crate::bringup_trace!("DBG[{:.0}s] forward ok, publishing", dbg_el()); - let _span = super::prefill_profile::span(super::prefill_profile::Stage::Publish, None); - pending.publish()?; - crate::bringup_trace!("DBG[{:.0}s] published", dbg_el()); - Ok(()) - } -} - -static DBG_T0: std::sync::OnceLock = std::sync::OnceLock::new(); -/// Bring-up tracing clock (seconds since the first call); remove together with the DBG lines. -/// `LELEKA_SERVE_PROFILE=1`: the card's free VRAM at a point of the stack's life (where the auto-sized cache's room goes). -fn vram_note(context: &Context<'_>, label: &str) { - if profile::enabled() { - if let Ok((free, total)) = context.memory_info() { - eprintln!("DBG vram {label}: free {} MiB of {} MiB", free >> 20, total >> 20); - } - } -} -pub(crate) fn dbg_el() -> f32 { - DBG_T0.get_or_init(std::time::Instant::now).elapsed().as_secs_f32() -} - -/// One operator line per CPU kind and per CUDA device: which kernel family the process runs on each (logging only). -fn report_kernel_selection() { - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - for line in leleka_native_cpu_expert::cpu_kernel_report() { - operator_note(&line); - } - for line in leleka_cuda_driver::gpu_kernel_report() { - operator_note(&line); - } -} - -fn operator_note(text: &str) { - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve {text}"); -} - -fn operator_line(what: &str, failure: &ServeFailure) { - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve {what}: {}", failure.describe()); -} - -fn operator_text(line: &str) { - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve {line}"); -} - -/// The conversation cache's device side over the stack's own owners. -impl<'a, 'ctx> ResumeDevice for OriginalServeStack<'a, 'ctx> { - type Point = StackPoint<'ctx>; - fn zero(&mut self) -> Result<()> { - if RequestOwners::is_fresh(self) { - return Ok(()); - } - RequestOwners::reset(self) - } - fn position(&self) -> Result { - Ok(self.session.target_origin()?.next_position()) - } - fn save(&mut self) -> Result> { - if let Some(error) = self.broken { - return Err(error); - } - let session = self.executor.checkpoint_session(self.binding, &mut self.session)?; - let draft = self.draft.checkpoint(self.binding, &self.session)?; - Ok(StackPoint { session, draft }) - } - fn point_position(point: &StackPoint<'ctx>) -> u64 { - point.session.next_position() - } - fn restore(&mut self, point: &StackPoint<'ctx>) -> Result<()> { - if let Some(error) = self.broken { - return Err(error); - } - // a refused re-stamp touches nothing; a failed physical restore poisons the executor - let rebased = point.session.rebased_onto_current(&self.session)?; - let restored = self.executor.restore_session(self.binding, &self.dense, &mut self.session, &rebased); - if let Err(error) = restored { - self.mark_broken(error); - } - restored - } - fn restore_draft(&mut self, point: &StackPoint<'ctx>, resume: usize) -> Result<()> { - if let Some(error) = self.broken { - return Err(error); - } - let result = (|| { - self.draft.resume_at(self.binding, &self.dense, &self.session, &point.draft)?; - let upto = i64::try_from(resume).map_err(|_| Error::Overflow)?; - self.executor.mtp_kv_restore(self.binding, &self.session, &mut self.draft, upto) - })(); - if let Err(error) = result { - self.mark_broken(error); - } - result - } - fn live_in_step(&self) -> bool { - self.broken.is_none() - && self.session.original_state_lag().is_none() - && self.draft.in_step(self.binding, &self.session) - } -} - -impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { - /// `RequestOwners::resume` with the prefix cache: install the deepest checkpoint that is a prefix of the prompt. - fn prefix_resume(&mut self, request: &ServeRequest) -> Option { - let mut prefix = self.prefix.take()?; - let _resume_span = profile::span("request.resume"); - let n = request.prompt.len(); - let resume = if self.broken.is_some() { - prefix.invalidate(); - None - } else { - match prefix.begin(self, &request.prompt) { - Ok(Some(start)) => { - self.reused = start.resume; - self.resume_point = start.resume; - operator_text(&format!( - "prefix request: n={n} hit=yes resume={} switched={} branch={} copied_tokens={} import_ms={:.1} (state+kv {:.1}, draft {:.1}) match_us={:.0} live_tokens={}", - start.resume, - start.switched, - start.branch, - start.copied_tokens, - start.import_ms, - prefix.last_import_split().0, - prefix.last_import_split().1, - start.match_us, - prefix.live_tokens() - )); - Some(start.resume) - } - Ok(None) => { - operator_text(&format!("prefix request: n={n} hit=no resume=0 match_us={:.0}", prefix.last_match_us())); - None - } - Err(error) => { - // the cache is an optimisation: drop it and start from the empty prompt (`reset`) - operator_text(&format!("prefix cache: {error:?}; reading the whole prompt")); - prefix.invalidate(); - None - } - } - }; - self.prefix = Some(prefix); - resume - } -} - -/// The prefix cache's device side over the stack's own owners. -impl<'a, 'ctx> PrefixDevice for OriginalServeStack<'a, 'ctx> { - type State = StackState; - type Block = StackBlock; - fn position(&self) -> Result { - Ok(self.session.target_origin()?.next_position()) - } - fn estimate(&self, block_tokens: usize) -> (usize, usize) { - (PARKED_STATE_ESTIMATE, block_tokens * PARKED_BYTES_PER_TOKEN) - } - fn park_state(&mut self) -> Result { - if let Some(error) = self.broken { - return Err(error); - } - let _p = profile::span("prefix.park_state"); - let session = self.executor.park_session(self.binding, &mut self.session)?; - let draft = self.draft.checkpoint(self.binding, &self.session)?; - Ok(StackState { session, draft }) - } - fn park_block(&mut self, first: usize, tokens: usize) -> Result { - if let Some(error) = self.broken { - return Err(error); - } - let _p = profile::span("prefix.park_block"); - self.executor.park_block(&self.session, first, tokens).map(StackBlock) - } - fn park_tail(&mut self, first: usize, tokens: usize) -> Result { - if let Some(error) = self.broken { - return Err(error); - } - let _p = profile::span("prefix.park_tail"); - self.executor.park_block(&self.session, first, tokens).map(StackBlock) - } - fn import(&mut self, state: &StackState, blocks: &[(usize, &StackBlock)]) -> Result<()> { - if let Some(error) = self.broken { - return Err(error); - } - let blocks: Vec<&ParkedBlock> = blocks.iter().map(|(_, block)| &block.0).collect(); - let _p = profile::span("prefix.import_session"); - // a refused import touches nothing; a failed physical one poisons the executor - let imported = self.executor.import_session(self.binding, &self.dense, &mut self.session, &state.session, &blocks); - if let Err(error) = imported { - self.mark_broken(error); - } - imported - } - fn restore_draft(&mut self, state: &StackState, resume: usize) -> Result<()> { - if let Some(error) = self.broken { - return Err(error); - } - let result = (|| { - { - let _p = profile::span("prefix.draft_resume_at"); - self.draft.resume_at(self.binding, &self.dense, &self.session, &state.draft)?; - } - let upto = i64::try_from(resume).map_err(|_| Error::Overflow)?; - let _p = profile::span("prefix.mtp_kv_restore"); - self.executor.mtp_kv_restore(self.binding, &self.session, &mut self.draft, upto) - })(); - if let Err(error) = result { - self.mark_broken(error); - } - result - } -} - -impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { - fn is_fresh(&self) -> bool { - self.broken.is_none() - && self.session.original_state_lag().is_none() - && self.session.target_origin().is_ok_and(|origin| origin.next_position() == 0) - } - fn reset(&mut self) -> std::result::Result<(), Error> { - if let Some(error) = self.broken { - return Err(error); - } - let _p = profile::span("request.reset"); - let result = (|| { - let empty = self.empty_session.rebased_empty(&self.session)?; - self.executor.restore_session(self.binding, &self.dense, &mut self.session, &empty)?; - self.draft.reset_to_empty(self.binding, &self.dense, &self.session, &self.empty_draft) - })(); - if let Err(error) = result { - self.mark_broken(error); - } - result - } - fn resume(&mut self, request: &ServeRequest) -> Option { - self.reused = 0; - self.resume_point = 0; - if self.prefix.is_some() { - return self.prefix_resume(request); - } - let mut conversation = self.conversation.take()?; - let _resume_span = profile::span("request.resume"); - let resume = if self.broken.is_some() { - conversation.invalidate(); - None - } else { - match conversation.begin(self, &request.prompt) { - Ok(start) => { - self.reused = start.read_from; - self.resume_point = start.resume; - Some(start.resume) - } - Err(error) => { - // the cache is an optimisation: drop it and start from the empty prompt (`reset`) - operator_text(&format!("conversation cache: {error}; reading the whole prompt")); - conversation.invalidate(); - None - } - } - }; - self.conversation = Some(conversation); - resume - } - fn prefill(&mut self, request: &ServeRequest, resume: usize, cancel: &mut dyn FnMut() -> bool) -> std::result::Result<(), SpecError> { - let started = Instant::now(); - self.timing = (0.0, 0.0); - self.marks.resumed = self.marks.since(); - let result = self.prefill_phase(request, resume, cancel); - if matches!(result, Err(SpecError::Cancelled)) { - self.keep_conversation_after_cancelled_prefill(request); - } - self.marks.prefilled = self.marks.since(); - self.timing.0 = started.elapsed().as_secs_f64() * 1e3; - result - } - fn decode( - &mut self, - request: &ServeRequest, - emit: &mut dyn FnMut(&[i32]) -> Result<()>, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result { - let started = Instant::now(); - let tier0 = self.residency.stats; - let result = self.decode_phase(request, emit, cancel); - match (result.is_ok(), self.tail_consumed.take()) { - (true, Some(consumed)) if self.broken.is_none() => self.prefix_after_decode(&consumed), - _ => {} - } - // an exit before the decode phase queued the refill still refills now; one before it waited still waits - if std::mem::take(&mut self.refill_due) { - if let Some(cache) = self.expert_cache.as_mut() { - if let Err(error) = original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false) { - self.mark_broken(error); - } - } - } - if std::mem::take(&mut self.refill_pending) { - if let Some(cache) = self.expert_cache.as_mut() { - if let Err(error) = original_serve_residency::settle_refill(cache) { - self.mark_broken(error); - } - } - } - self.timing.1 = started.elapsed().as_secs_f64() * 1e3; - profile::add("decode.phase", self.timing.1); - if profile::enabled() { - let t1 = self.residency.stats; - let (v, p, c) = (t1.vram_entries - tier0.vram_entries, t1.pcie_entries - tier0.pcie_entries, t1.cpu_entries - tier0.cpu_entries); - let all = (v + p + c).max(1) as f64; - // the Original's hit rate: VRAM entries over VRAM + CPU entries (PCIe entries are in neither count) - eprintln!( - "DBG tier request: vram {v} ({:.1}%) pcie {p} ({:.1}%) cpu {c} ({:.1}%) hit_rate_original_def {:.1}% adaptations {} swaps {} pcie_num {}", - 100.0 * v as f64 / all, 100.0 * p as f64 / all, 100.0 * c as f64 / all, - 100.0 * v as f64 / ((v + c).max(1) as f64), t1.adaptations - tier0.adaptations, t1.swaps - tier0.swaps, - self.residency.pcie_lag.as_ref().map(|l| l.pcie_num()).or_else(|| self.residency.pcie_auto.as_ref().map(|a| a.pcie_num())).unwrap_or(self.config.expert_tier.pcie_num()) - ); - } - // graphs captured after the window/commit graphs: the MTP round programs of this request's drafts - let (capture_ms, instantiate_ms, _) = leleka_cuda_driver::original_capture_timing::take(); - profile::add("mtp.capture", capture_ms); - profile::add("mtp.instantiate", instantiate_ms); - profile::add("prefill.phase", self.timing.0); - profile::report("request"); - self.residency.flush_routing(); - self.seed_coverage_trace(); - result - } - fn finish(&mut self, ended: std::result::Result<(), ServeError>) { - let completed = self.broken.is_none() && matches!(ended, Ok(()) | Err(ServeError::Cancelled)); - if let Some(conversation) = self.conversation.as_mut() { - conversation.finish(completed); - } - if let Some(prefix) = self.prefix.as_mut() { - prefix.finish(completed); - let (admitted, park_ms, consider_ms) = prefix.request_parking(); - operator_text(&format!("prefix request done: admitted={admitted} park_ms={park_ms:.1} policy_ms={consider_ms:.1} {}", prefix.describe())); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_chunk_borrows_the_smallest_rung_that_holds_it() { - let blobs = ExpertBlobSizes::from_layer_bytes(std::array::from_fn(|l| 700_000 + 4096 * l), [700_000; 48], [900_000; 48]).unwrap(); - let layout = prefill_layout_options(8192, 262_144, &blobs); - let tiers: Vec = [(512usize, 600usize), (2048, 900)] - .into_iter() - .map(|(rows, slots)| LoanTier { rows, layout: PrefillLayoutOptions { capacity: rows, ..layout }, slots }) - .collect(); - assert_eq!(tier_for(&tiers, 1).map(|t| t.rows), Some(512)); - assert_eq!(tier_for(&tiers, 512).map(|t| t.rows), Some(512)); - assert_eq!(tier_for(&tiers, 513).map(|t| t.rows), Some(2048)); - assert_eq!(tier_for(&tiers, 2048).map(|t| t.slots), Some(900)); - assert!(tier_for(&tiers, 2049).is_none(), "above the ladder the chunk borrows the full loan"); - assert!(tier_for(&[], 100).is_none()); - // the arena of a smaller rung is smaller - assert!(prefill_bytes(tiers[0].layout).unwrap() < prefill_bytes(tiers[1].layout).unwrap()); - assert!(prefill_bytes(tiers[1].layout).unwrap() < prefill_bytes(layout).unwrap()); - } - - #[test] - fn the_default_chunk_is_an_admitted_capacity_and_validation_follows_the_prefill_rules() { - let config = StackConfig::new(4096); - assert!(ADMITTED_CAPACITIES.contains(&config.capacity)); - for capacity in [256usize, 1024, 8192] { - assert!(StackConfig { capacity, ..config.clone() }.validate().is_ok(), "{capacity}"); - } - for capacity in [0usize, 255, 300, 16384, 32768] { - assert!(StackConfig { capacity, ..config.clone() }.validate().is_err(), "{capacity}"); - } - assert!(StackConfig { max_context: 0, ..config.clone() }.validate().is_err()); - assert!(StackConfig { cpu_workers: 0, ..config.clone() }.validate().is_err()); - assert!(StackConfig { cpu_workers: 65, ..config.clone() }.validate().is_err()); - assert!(StackConfig { max_context: i64::MAX, ..config }.validate().is_err()); - } - - #[test] - fn the_conversation_cache_is_on_by_default_with_the_original_settings() { - let config = StackConfig::new(4096); - let conversation = config.conversation.as_ref().expect("--prompt-cache 6 is the default, as in the Original"); - assert_eq!((conversation.prompt_cache, conversation.prompt_cache_every, conversation.prompt_cache_root), (6, 16_384, 2048)); - assert_eq!(conversation.turn_token, Some(TURN_TOKEN)); - assert!(config.validate().is_ok()); - assert!(StackConfig { conversation: None, ..config }.validate().is_ok(), "the cache can be turned off"); - } - - #[test] - fn kv_defaults_to_the_production_int8_window_and_refuses_unported_formats() { - let config = StackConfig::new(4096); - assert_eq!((config.kv_format, config.kv_resident), (KvFormat::Int8, 32_768)); - assert_eq!(config.kv_footprint().map(|f| f.resident_pages), Some(8192)); - for kv_resident in [0usize, 1, 20_480, 40_000, 262_144] { - assert!(StackConfig { kv_resident, ..config.clone() }.validate().is_ok(), "{kv_resident}"); - } - assert!(StackConfig { kv_resident: 524_292, ..config.clone() }.validate().is_err()); - for kv_format in [KvFormat::Fp16, KvFormat::Q4_0, KvFormat::K8V4, KvFormat::Int8Keyless] { - assert_eq!( - StackConfig { kv_format, ..config.clone() }.validate(), - Err(Error::Unsupported(crate::qwen_forward::contract::Stage::Session)) - ); - } - } - - #[test] - fn plan_errors_keep_their_class() { - assert_eq!(plan_error(PlanError::InvalidInput), Error::InvalidDimension); - assert_eq!(plan_error(PlanError::Overflow), Error::Overflow); - } -} +//! The Original serving stack: every model-lifetime owner of the `generate.cpp` mode17 serve path, opened +//! once, and the per-request flow over them (prompt conditioning with the batched Original prefill, then the +//! verified-window decode with MTP drafting). +//! +//! Lifetime of the pieces: the dense weights, the MoE arena cache, the native head/embedding, the target +//! session, the prompt executor (which owns the MTP actor and the twelve resident QSA layers), the MTP draft +//! session, the prefill arena, the penalty-history stage and the PLE history image live as long as the +//! stack. Each request resets them to the empty prompt (the checkpoints taken at load, re-stamped onto the +//! current branch generation), conditions the prompt through the executor, and then hands the QSA owners to a +//! freshly assembled native Verifier for the decode phase; the verifier is closed and the owners are taken +//! back afterwards (see `original_serve_verifier`). With `StackConfig::conversation` set, generate.cpp's +//! conversation cache decides where a request starts reading instead (`original_serve_conversation`); +//! without it every request starts at position 0. +//! +//! With `StackConfig::expert_tier` on, the stack also owns the VRAM expert tier (`original_serve_residency`): +//! the cache is opened last, filled from the profile, lent to the prompt path for each chunk and refilled +//! before the decode phase (on every exit path), whose windows compute the resident experts on the GPU. +//! +//! Nothing here computes a model number. Where an asset or a producer the Original needs is not available the +//! error comes from its owner and is surfaced untouched (`ServeFailure`). +use super::{ + contract::{Error, Result}, + dense_weight_cache::DenseWeightCache, + executor::original_prompt::{embedding::OriginalPromptEmbedding, OriginalPromptExecutor}, + kar_ple_cache::KarPleCache, + moe_weight_cache::MoeWeightCache, + original_mtp_full_owner::{OriginalMtpFullOwner, OriginalMtpRequest}, + original_serve_config::{expert_formats, mtp_full_policy, mtp_scalar_policy, prefill_layout_options, ExpertBlobSizes, RopeConstants}, + original_serve_engine::{serve_request, OriginalServeEngine, OriginalServeSettings, ServeOutcome}, + original_serve_host::{HostOwners, OriginalServeHost, RequestSampling}, + original_serve_native::NativeServePort, + original_serve_pool::{CpuExpertPool, OriginalServePool}, + original_serve_profile as profile, + original_serve_residency::{self, ExpertTierConfig, GpuExpertPool, ResidencyState}, + original_serve_seed::{self, SeedReport}, + original_serve_request::{run_request, RequestOwners, ServeError, ServeRequest}, + original_serve_verifier::{assemble, disassemble, seed_ple_history, DecodeResources, ServeFailure, VerifyWeights, PLE_HISTORY_BYTES}, + original_spec_controller::{OriginalSpecController, SpecError}, + output_native::{OriginalNativeOutput, OriginalNativePenaltyHistory}, + session::{ + original_prompt::{draft::OriginalDraftCheckpoint, OriginalPromptInput, OriginalSessionCheckpoint, ParkedBlock, ParkedSession}, + QwenSession, + }, +}; +use crate::backend::original_prompt::{PlanError, PromptOptions, PromptPath, PromptPlan}; +use crate::model_binding::qwen4exp_input::ModelBinding; +use leleka_context::memory_plan::KvFormat; +use leleka_cuda_driver::{ + Context, DeviceBuffer, NativeHeadDispatch, OriginalExpertCache, OriginalMtpFullPolicy, OriginalMtpScalarPolicy, + OriginalPrefillArena, OriginalVerifyExpertFormats, PLE_SCRATCH_BYTES, PrefillLayoutOptions, +}; +use std::{path::PathBuf, rc::Rc, time::Instant}; + +/// One timed, measured step of opening the stack: the load ledger records what it cost in host and device memory. +macro_rules! staged { + ($name:expr, $ctx:expr, $body:expr) => {{ + let __stage = crate::memory_governor::begin($name, Some($ctx)); + let __result = $body; + crate::memory_governor::end(__stage, Some($ctx)); + __result + }}; +} + +#[path = "original_serve_conversation.rs"] +mod conversation; +pub(crate) use conversation::{ConversationConfig, TURN_TOKEN}; +use conversation::{ResumeDevice, ServeConversation}; + +#[path = "original_serve_prefix.rs"] +mod prefix; +pub(crate) use prefix::{PrefixBudget, PrefixConfig, TailMode}; +use prefix::{ChunkOutcome, PrefixDevice, PrefixServe}; +use crate::prefix_cache::{ByteSize, PrefixMatch, PrefixSummary}; + +/// Stage marks of one request's time to first token (milliseconds since `serve` was entered). +#[derive(Clone, Copy, Debug)] +struct TtftMarks { + started: Option, + resumed: f64, + prefilled: f64, + assembled: f64, + first_round: f64, +} +impl Default for TtftMarks { + fn default() -> Self { + Self { started: None, resumed: f64::NAN, prefilled: f64::NAN, assembled: f64::NAN, first_round: f64::NAN } + } +} +impl TtftMarks { + fn start() -> Self { + Self { started: Some(Instant::now()), ..Self::default() } + } + fn since(&self) -> f64 { + self.started.map_or(f64::NAN, |at| at.elapsed().as_secs_f64() * 1e3) + } + fn as_array(&self) -> [f64; 4] { + [self.resumed, self.prefilled, self.assembled, self.first_round] + } +} + +/// The digest of the pinned model's first shard: part of the prefix cache's namespace. +const PINNED_MODEL: &str = "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"; + +/// Prompt-chunk capacities the Original prefill admits (`PromptPlan::new`), ascending. +pub(crate) const ADMITTED_CAPACITIES: [usize; 10] = [256, 512, 1024, 2048, 3072, 4096, 6144, 8192, 16384, 32768]; +/// The default chunk. The Original sizes it from the free expert-cache slots (`--prefill-auto`); with no GPU +/// expert tier there is no slot count to derive it from, so the operator picks it (the arena is a few GiB at +/// 8192) and a hardware run settles the default. +pub(crate) const DEFAULT_CAPACITY: usize = 2048; +/// `qsa_kv_resident_min()`: the shipped resident draft-K/V budget in cells. +const MTP_RESIDENT_CELLS: u64 = 20_480; +const CPU_WORKERS: i32 = 15; +const VOCABULARY: u32 = 248_320; + +/// Operator-visible choices of the stack. +#[derive(Clone, Debug)] +pub(crate) struct StackConfig { + pub(crate) capacity: usize, + /// The request ceiling (`--max-context`): at most the process serving cell count. + pub(crate) max_context: i64, + /// `--mtp DIR`: the Original-literal RT directory; `None` takes the digest-pinned pack of the binding. + pub(crate) rt_directory: Option, + pub(crate) coupled: bool, + pub(crate) cpu_workers: i32, + /// Read the verifier's GDN/PLE state back into the session at the end of every request (needed only by + /// a consumer that reuses the session; the default reset-per-request flow skips the 110 MB transfer). + pub(crate) settle_state: bool, + /// `--kv`: QSA K/V storage. Only `int8` (the production `--kv int8`) has sealed owners; fp16, q4_0 and + /// k8v4 are refused (docs/kv-streaming.md). + pub(crate) kv_format: KvFormat, + /// `--kv-resident N`: cells of each QSA layer kept in VRAM, the rest streamed from pinned host memory + /// (raised to 20480; 0 = the whole context). Default 32768, the window every earlier build used. + pub(crate) kv_resident: usize, + /// generate.cpp's conversation cache (`--prompt-cache` and friends); on by default with the Original's + /// settings (`--prompt-cache 6`). `None` reads every request from the empty prompt. + pub(crate) conversation: Option, + /// The cross-session prefix cache (`--prefix-cache-mib`, `docs/prefix-cache.md`). When it is on it REPLACES the + /// conversation cache: the prompt is read on a token grid and any request resumes from the deepest checkpoint + /// that is a prefix of its prompt, whichever session built it. `None` (the default) leaves the conversation + /// cache in charge. + pub(crate) prefix: Option, + /// The VRAM expert tier (`--expert-cache`, `--expert-cache-per-layer`, `--expert-profile`, `--pcie-frac`, + /// `--adapt-every/--adapt-swaps`). Off by default: every routed expert on the CPU pool. + pub(crate) expert_tier: ExpertTierConfig, + /// Smaller prompt loans for smaller chunks (`LELEKA_PREFILL_LOAN_TIERS=1`; off: every chunk borrows the full loan of `capacity`). + pub(crate) loan_tiers: bool, +} +impl StackConfig { + pub(crate) fn new(max_context: i64) -> Self { + Self { + capacity: DEFAULT_CAPACITY, + max_context, + rt_directory: None, + coupled: OriginalServeSettings::coupled_from_environment(), + // LELEKA_ORIGINAL_SERVE_CPU_WORKERS: experiment knob (the Original's default on this host is 15) + // LELEKA_CPU_POOL_PLAN=on: when the count is not set, the plan of `native-cpu-expert::pool_plan` (physical cores but the host's, hybrid and quota aware; + // docs/upstream-port-plan.md row 2.3) instead of the constant 15 (opt-in: the same 15 on the server's 16-core CPU, not measured on any other) + cpu_workers: std::env::var("LELEKA_ORIGINAL_SERVE_CPU_WORKERS").ok().and_then(|v| v.parse().ok()).filter(|n| (1..=64).contains(n)).unwrap_or_else(|| { + if std::env::var("LELEKA_CPU_POOL_PLAN").is_ok_and(|v| v == "on") { leleka_native_cpu_expert::pool_plan::default_workers() } else { CPU_WORKERS } + }), + settle_state: false, + kv_format: KvFormat::Int8, + kv_resident: leleka_cuda_driver::KV_RESIDENT_DEFAULT_CELLS, + conversation: Some(ConversationConfig::original()), + prefix: None, + expert_tier: ExpertTierConfig::off(), + loan_tiers: loan_tiers_enabled(), + } + } + /// The streamed KV of this configuration (`None` when the window is not servable). + pub(crate) fn kv_footprint(&self) -> Option { + leleka_cuda_driver::serving_context().geometry.kv_stream_footprint(self.kv_resident).ok() + } + pub(crate) fn validate(&self) -> Result<()> { + if self.kv_format != KvFormat::Int8 { + return Err(Error::Unsupported(super::contract::Stage::Session)); + } + if !ADMITTED_CAPACITIES.contains(&self.capacity) + || self.kv_footprint().is_none() + || self.capacity > 8192 + || self.max_context < 1 + || self.max_context as u64 > super::contract::serving_cells() + || !(1..=64).contains(&self.cpu_workers) + { + return Err(Error::InvalidDimension); + } + if let Some(conversation) = &self.conversation { + conversation.validate()?; + } + if let Some(prefix) = &self.prefix { + prefix.validate(self.capacity)?; + } + self.expert_tier.validate() + } +} + +/// Bytes the prompt path's buffers need at `options.capacity` (what a loan must cover). +fn prefill_bytes(options: PrefillLayoutOptions) -> Result { + let carve = options.carve().map_err(|e| super::original_serve_verifier::driver_error(&e))?; + Ok(carve.borrowed_bytes.max(carve.source_bytes_needed)) +} + +/// One rung of the loan ladder: the arena layout for chunks of at most `rows` rows and the slots it needs. +#[derive(Clone, Copy, Debug)] +struct LoanTier { + rows: usize, + layout: PrefillLayoutOptions, + slots: usize, +} + +/// Chunk sizes (rows) that get their own, smaller loan below the configured capacity. +const LOAN_TIER_ROWS: [usize; 2] = [512, 2048]; + +/// The smallest rung of the ladder that holds a chunk of `count` rows (`None`: the full loan). +fn tier_for(tiers: &[LoanTier], count: usize) -> Option<&LoanTier> { + tiers.iter().find(|t| count <= t.rows) +} + +/// `LELEKA_PREFILL_LOAN_TIERS=1` turns the ladder on. It is OFF by default until the real-model identity gate (job p34: the final residual R of +/// every chunk equal with and without the ladder) and the paired A/B (job p35) have run (docs/prefill-throughput.md). +fn loan_tiers_enabled() -> bool { + std::env::var("LELEKA_PREFILL_LOAN_TIERS").is_ok_and(|v| v == "1" || v == "on") +} + +/// One conversation checkpoint of the stack: the session's Original checkpoint and the draft ring's snapshot, +/// taken together at a published prompt-chunk boundary. +struct StackPoint<'ctx> { + session: OriginalSessionCheckpoint<'ctx>, + draft: OriginalDraftCheckpoint, +} + +/// A prefix-cache checkpoint of the stack: the session's recurrent state and the draft ring's snapshot at one grid point. +struct StackState { + session: ParkedSession, + draft: OriginalDraftCheckpoint, +} +impl ByteSize for StackState { + fn byte_size(&self) -> usize { + self.session.host_bytes() + self.draft.host_bytes() + } +} +/// The K/V cells and index rows of one block of the twelve resident QSA layers. +struct StackBlock(ParkedBlock); +impl ByteSize for StackBlock { + fn byte_size(&self) -> usize { + self.0.host_bytes() + } +} +/// Bytes of one cell across the twelve layers: INT8 K+V with scales (1056 B) and the pooled index key (128 B). +const PARKED_BYTES_PER_TOKEN: usize = 12 * (1056 + 128); +/// Expected size of a parked state before one was measured (GDN/PLE images, the draft ring, the index tails). +const PARKED_STATE_ESTIMATE: usize = 120 << 20; + +fn plan_error(error: PlanError) -> Error { + match error { + PlanError::InvalidInput => Error::InvalidDimension, + PlanError::Overflow => Error::Overflow, + } +} + +pub(crate) struct OriginalServeStack<'a, 'ctx> { + binding: &'a ModelBinding, + context: &'ctx Context<'ctx>, + config: StackConfig, + settings: OriginalServeSettings, + max_cells: usize, + rope: RopeConstants, + blobs: ExpertBlobSizes, + formats: OriginalVerifyExpertFormats, + full_policy: OriginalMtpFullPolicy, + scalar_policy: OriginalMtpScalarPolicy, + controller: OriginalSpecController, + /// Window policies other than the live one (`LELEKA_SPEC_ARMS`), parked with their controllers (each keeps its learned + /// state across requests), and the live one's label. The verifier is built for `verifier_max_t`, the widest arm. + parked: Vec<(String, OriginalServeSettings, OriginalSpecController)>, + arm_label: String, + arm_order: Vec, + verifier_max_t: usize, + /// Why the stack can serve no more (a lost physical owner); `None` while healthy. + broken: Option, + // The empty-prompt lineage taken at load: the reset target of every request. + empty_session: OriginalSessionCheckpoint<'ctx>, + empty_draft: OriginalDraftCheckpoint, + /// The conversation cache (checkpoints hold priors and snapshots of the owners below: dropped first). + conversation: Option>>, + /// The prefix cache (`StackConfig::prefix`); replaces `conversation` when set. + prefix: Option>, + /// The tokens the session holds at the end of a decode that left it settled with the draft ring in step (`TailMode::Reply`). + tail_consumed: Option>, + /// Prompt tokens the last request did not read again. + reused: usize, + /// Where the conversation cache placed the last request (`reused`, or the re-read checkpoint's length). + resume_point: usize, + // Owners, dependents first (fields drop in declaration order). + history: OriginalNativePenaltyHistory<'ctx>, + ple_history: DeviceBuffer<'ctx>, + ple_scratch: DeviceBuffer<'ctx>, + /// The prompt path's own buffers; `None` while it borrows the expert cache's last slots instead. + arena: Option>, + layout: PrefillLayoutOptions, + /// The VRAM expert tier (`None`: off), the slots the prompt path borrows per chunk, the adaptive counts + /// that survive requests. + expert_cache: Option>, + loan: Option, + /// Smaller loans for smaller chunks, ascending by rows (empty unless `LELEKA_PREFILL_LOAN_TIERS=1`: only `loan`): a chunk of at most + /// `rows` rows borrows `slots` slots instead of the full loan, so a request that reads a few hundred tokens refills a few + /// hundred slots, not the 1.9 GB of an 8192-row arena. + loan_tiers: Vec, + residency: ResidencyState, + /// The (layer, expert) pairs the tier held right after the profile fill (`reset_expert_tier`). + initial_owners: Vec>, + /// The last request's prompt-routing seed (`LELEKA_ORIGINAL_SERVE_SEED`), if one was made. + seed_report: Option, + /// The prompt counts of the last seed (kept for the `LELEKA_SEED_TRACE` coverage line). + seed_counts: Option>, + /// Lent-slot refill copies are queued and not yet waited (`LELEKA_REFILL_DEFER`): the decode phase waits before any + /// window reads the cache; every other user of the cache waits inside its own entry points. + refill_pending: bool, + /// The lent slots still have to be refilled: the decode phase queues the copies right after its host-side intake + /// uploads (so they overlap the graph capture instead of queueing small uploads behind 1.4 GB of DMA). + refill_due: bool, + /// Wall-clock milliseconds of the last request's prompt and decode phases (operator measurements). + timing: (f64, f64), + /// Milliseconds since the request entered `serve` at which each stage of the time to first token ended (`ttft_marks`). + marks: TtftMarks, + executor: OriginalPromptExecutor<'ctx>, + draft: super::session::original_prompt::draft::OriginalDraftSession<'ctx>, + session: QwenSession<'ctx>, + pool: CpuExpertPool<'a>, + kar: Option>, + moe: MoeWeightCache<'ctx>, + dense: DenseWeightCache<'ctx>, + output: OriginalNativeOutput<'ctx>, + embedding: OriginalPromptEmbedding<'ctx>, +} + +fn failure(error: Error) -> ServeFailure { + ServeFailure::from(error) +} + +/// Name the startup step in a refusal so a failed open says where it stopped. +fn at>(step: &'static str) -> impl FnOnce(E) -> ServeFailure { + move |error| { + let mut failure: ServeFailure = error.into(); + failure.detail = Some(match failure.detail.take() { + Some(detail) => format!("{step}: {detail}"), + None => format!("{step}: {:?}", failure.error), + }); + failure + } +} + +impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { + /// `generate.cpp` startup over the binding: embedding table, native head + embedding, dense weights at + /// the prompt capacity, the MoE arena cache, the target session, the prompt executor with the MTP + /// drafter, the prefill arena, and the per-request stages. `shared` is the session's reference to the + /// very context `context` borrows. + pub(crate) fn open( + binding: &'a ModelBinding, + context: &'ctx Context<'ctx>, + shared: Rc>, + config: StackConfig, + ) -> std::result::Result { + crate::bringup_trace!("DBG[{:.0}s] OriginalServeStack::open begin", dbg_el()); + config.validate().map_err(at("config.validate"))?; + // generate.cpp: qsa_set_kv_resident before any QSA state exists (every streamed owner sizes from it) + leleka_cuda_driver::configure_kv_resident(config.kv_resident).map_err(|_| ServeFailure { + error: Error::InvalidDimension, + detail: Some(format!("--kv-resident {}: the process already serves another resident KV window", config.kv_resident)), + })?; + if let Some(footprint) = config.kv_footprint() { + operator_note(&footprint.to_string()); + } + if !std::ptr::eq(context, &*shared) { + return Err(failure(Error::IdentityMismatch)); + } + if binding.layer_count() != 48 { + return Err(ServeFailure { error: Error::IdentityMismatch, detail: Some("the Original serve stack serves the 48-layer model only".to_owned()) }); + } + if !binding.has_mtp() { + return Err(ServeFailure { + error: Error::Unsupported(super::contract::Stage::Session), + detail: Some("the binding carries no MTP pack: the Original serve loop drafts with the MTP layer".to_owned()), + }); + } + let max_cells = usize::try_from(super::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?; + let mut settings = OriginalServeSettings::from_environment(config.max_context, VOCABULARY, config.coupled); + let mut arm_label = String::from("env"); + let arm_order: Vec = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled).into_iter().map(|(l, _)| l).collect(); + let mut parked = Vec::new(); + let arms = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled); + let verifier_max_t = arms.iter().map(|(_, s)| s.max_t).chain([settings.max_t]).max().unwrap_or(settings.max_t); + if let Some(((label, first), rest)) = arms.split_first() { + settings = *first; + arm_label = label.clone(); + for (label, s) in rest { + parked.push((label.clone(), *s, s.controller().map_err(at("settings.controller"))?)); + } + } + let controller = settings.controller().map_err(at("settings.controller"))?; + let rope = RopeConstants::from_serving_context(); + let blobs = ExpertBlobSizes::from_binding(binding).map_err(at("ExpertBlobSizes::from_binding"))?; + let formats = expert_formats(binding).map_err(at("expert_formats"))?; + let layout = prefill_layout_options(config.capacity, max_cells, &blobs); + + vram_note(context, "open begin"); + let embedding = staged!("embedding table", context, OriginalPromptEmbedding::load(binding, context).map_err(at("OriginalPromptEmbedding::load"))?); + let output = staged!("native head + embedding", context, OriginalNativeOutput::load(binding, context, NativeHeadDispatch::default(), true).map_err(at("OriginalNativeOutput::load"))?); + let kar = staged!("KAR PLE cache", context, match binding.kar_ple_binding() { + Some(provider) => Some(KarPleCache::new(context, provider).map_err(at("KarPleCache::new"))?), + None => None, + }); + let dense = staged!("dense weights", context, DenseWeightCache::new_original_prompt_capacity(binding, context, config.capacity).map_err(at("DenseWeightCache::new_original_prompt_capacity"))?); + let moe = staged!("MoE arena cache", context, MoeWeightCache::new_original_prompt_arena(binding, context, layout).map_err(at("MoeWeightCache::new_original_prompt_arena"))?); + vram_note(context, "after embedding, output, kar, dense, moe arena"); + let mut session = QwenSession::for_binding_on_shared_device(binding, shared); + let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, settings.coupled, MTP_RESIDENT_CELLS); + let executor_stage = crate::memory_governor::begin("prompt executor + MTP drafter", Some(context)); + let (executor, draft) = match &config.rt_directory { + Some(directory) => OriginalPromptExecutor::select_rt_mtp( + binding, &dense, &mut session, context, &embedding, &output, directory, config.capacity, true, &request, + ) + .map_err(|e| ServeFailure { error: e.error, detail: e.message })?, + None => { + let mut executor = OriginalPromptExecutor::new( + binding, &dense, &mut session, context, &moe, &embedding, config.capacity, verifier_max_t, true, + ).map_err(at("OriginalPromptExecutor::new"))?; + let assembly = OriginalMtpFullOwner::assemble(binding, &session, context, &moe, &embedding, &output, &request) + .map_err(|e| ServeFailure { error: e.error, detail: e.message })?; + let draft = executor.install_full_mtp(binding, &session, assembly).map_err(at("install_full_mtp"))?; + (executor, draft) + } + }; + vram_note(context, "after prompt executor and draft"); + let mut executor = executor; + crate::memory_governor::end(executor_stage, Some(context)); + // generate.cpp: the expert cache is sized after everything else, and the prompt path's own buffers + // after the cache when it cannot borrow them; without the tier the order is unchanged. + let tier = config.expert_tier.enabled(); + let mut arena = staged!("prefill arena", context, if tier { None } else { Some(context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?) }); + vram_note(context, "before cache"); + let history = staged!("penalty history", context, OriginalNativePenaltyHistory::new(binding, context).map_err(at("OriginalNativePenaltyHistory::new"))?); + let ple_history = context.allocate(PLE_HISTORY_BYTES).map_err(at("ple_history"))?; + let ple_scratch = context.allocate(PLE_SCRATCH_BYTES).map_err(at("ple_scratch"))?; + let pool = staged!("CPU expert pool", context, CpuExpertPool::new(binding, config.cpu_workers).map_err(at("CpuExpertPool::new"))?); + let empty_session = staged!("empty-prompt session checkpoint", context, executor.checkpoint_session(binding, &mut session).map_err(at("checkpoint_session"))?); + let empty_draft = staged!("empty-prompt draft checkpoint", context, draft.checkpoint(binding, &session).map_err(at("draft.checkpoint"))?); + let prefix = match &config.prefix { + Some(prefix_config) => { + let available = crate::conversation::memory::available_memory(); + // the budget comes from the memory governor (what is left above the floors), not from an independent default + let complement_pending = (config.expert_tier.resident_budget_gib.max(0.0) * (1u64 << 30) as f64) as u64; + let bytes = crate::memory_governor::resolve_prefix_budget(prefix_config.budget, available, complement_pending) + .unwrap_or_else(|| prefix_config.resolve_budget(available)); + let mut prefix_config = prefix_config.clone(); + if let Some(g) = leleka_memory::Governor::global() { + // stop admitting before anything has to be shed: soft floor + reserve (the real CRM session sat 4.4 GiB above a 3 GiB floor) + prefix_config.memory_floor = prefix_config.memory_floor.max(g.policy().admit_floor()); + } + let prefix_config = &prefix_config; + if bytes == 0 { + operator_note(&format!( + "prefix cache off (budget {:?}, available host memory {:?} MiB)", + prefix_config.budget, + available.map(|b| b >> 20) + )); + None + } else { + let identity = format!("qwen4exp:{PINNED_MODEL}:kv={:?}:resident={}", config.kv_format, config.kv_resident); + let serve = PrefixServe::new(prefix_config.clone(), config.capacity, bytes, &identity); + operator_note(&format!( + "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, host memory available {:?} MiB, namespace {}", + serve.block_tokens(), + bytes >> 20, + PARKED_STATE_ESTIMATE >> 20, + PARKED_BYTES_PER_TOKEN, + available.map(|b| b >> 20), + crate::prefix_cache::summary::hex(serve.namespace()) + )); + Some(serve) + } + } + None => None, + }; + let conversation = if prefix.is_some() { None } else { config.conversation.clone().map(ServeConversation::new) }; + let residency = ResidencyState::new(&config.expert_tier); + report_kernel_selection(); + vram_note(context, "before expert tier"); + let mut loan = None; + let tier_open = staged!("expert tier (VRAM slots + profile fill)", context, original_serve_residency::open_tier(binding, context, &moe, &config.expert_tier, config.capacity).map_err(at("expert tier"))?); + let expert_cache = match tier_open { + Some((cache, filled)) => { + if config.expert_tier.prefill_borrow && config.expert_tier.profile.is_some() { + loan = original_serve_residency::loan_slots(&cache, prefill_bytes(layout).map_err(at("prefill bytes"))?) + .map_err(at("expert-cache loan"))?; + } + operator_note(&format!( + "expert cache {} slots ({:.2} GiB, {}), {filled} filled from the profile; the prompt path {}; GPU experts round differently from the CPU's (bench/results/2026-09-27-cache-parity)", + cache.slots(), + cache.bytes() as f64 / f64::from(1u32 << 30), + if cache.per_layer_admission() { "per layer" } else { "global" }, + match loan { + Some(k) => format!("borrows its last {k} slots"), + None => "allocates its own buffers".to_owned(), + } + )); + Some(cache) + } + None => None, + }; + vram_note(context, "after expert tier"); + let mut loan_tiers: Vec = Vec::new(); + if let (Some(full), Some(cache), true) = (loan, expert_cache.as_ref(), config.loan_tiers) { + for rows in LOAN_TIER_ROWS.into_iter().filter(|&r| r < config.capacity) { + let tier_layout = PrefillLayoutOptions { capacity: rows, ..layout }; + let slots = original_serve_residency::loan_slots(cache, prefill_bytes(tier_layout).map_err(at("prefill bytes (tier)"))?).map_err(at("expert-cache loan (tier)"))?; + if let Some(slots) = slots.filter(|&s| s < full && loan_tiers.last().is_none_or(|t| s > t.slots)) { + loan_tiers.push(LoanTier { rows, layout: tier_layout, slots }); + } + } + if !loan_tiers.is_empty() { + operator_note(&format!( + "prompt loan ladder: {}, up to {} rows {full} slots", + loan_tiers.iter().map(|t| format!("up to {} rows {} slots", t.rows, t.slots)).collect::>().join(", "), + config.capacity + )); + } + } + let initial_owners: Vec> = expert_cache + .as_ref() + .map(|cache| (0..cache.slots()).map(|slot| cache.slot_owner(slot)).collect()) + .unwrap_or_default(); + if arena.is_none() && loan.is_none() { + arena = Some(staged!("prefill arena (after the expert tier)", context, context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?)); + } + let this = Self { + binding, + context, + conversation, + prefix, + tail_consumed: None, + reused: 0, + resume_point: 0, + full_policy: mtp_full_policy(&rope), + scalar_policy: mtp_scalar_policy(&rope), + config, + settings, + max_cells, + rope, + blobs, + formats, + controller, + parked, + arm_label, + arm_order, + verifier_max_t, + broken: None, + empty_session, + empty_draft, + history, + ple_history, + ple_scratch, + arena, + layout, + expert_cache, + loan, + loan_tiers, + residency, + initial_owners, + seed_report: None, + seed_counts: None, + refill_pending: false, + refill_due: false, + timing: (0.0, 0.0), + marks: TtftMarks::default(), + executor, + draft, + session, + pool, + kar, + moe, + dense, + output, + embedding, + }; + this.register_memory_classes(); + crate::memory_governor::post_open(); + if let Some(governor) = leleka_memory::Governor::global() { + governor.log(&format!("stack open; inventory of allocation classes (accounted by their owners): +{}", governor.inventory().table())); + governor.log(&format!("load ledger (measured: kernel and driver deltas per opening step): +{}", governor.ledger().table())); + governor.publish(); + } + Ok(this) + } + + /// `Some` once a physical owner was lost: the stack must be closed and rebuilt. + pub(crate) fn health(&self) -> Option { + self.broken + } + + /// One request. Admission, reset, prompt conditioning and decode in order; see `run_request`. + pub(crate) fn serve( + &mut self, + request: &ServeRequest, + emit: &mut dyn FnMut(&[i32]) -> Result<()>, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result { + self.apply_memory_directive(); + self.marks = TtftMarks::start(); + let max_context = self.config.max_context; + let result = run_request(self, request, max_context, emit, cancel); + self.note_memory(); + result + } + + /// Follow the memory governor between requests: under pressure the prefix cache evicts (and restores its budget when the + /// pressure is over), and the conversation checkpoints are dropped. Cheap: a few atomics when nothing changed. + fn apply_memory_directive(&mut self) { + let Some(governor) = leleka_memory::Governor::global() else { return }; + let used = self.prefix.as_ref().map_or(0, |p| p.bytes() as u64); + let directive = governor.directive(used); + if let Some(prefix) = self.prefix.as_mut() { + let before = prefix.bytes(); + let freed = prefix.apply_shed(directive.prefix_budget, governor); + if freed > 0 { + operator_note(&format!( + "memory pressure ({}): prefix cache evicted {} MiB ({} -> {} MiB), budget {} MiB", + directive.level.as_str(), + freed >> 20, + before >> 20, + prefix.bytes() >> 20, + prefix.budget_bytes() >> 20 + )); + } + } + if directive.drop_conversation + && let Some(conversation) = self.conversation.as_mut() + && conversation.checkpoint_count() > 0 + { + conversation.invalidate(); + operator_note(&format!("memory pressure ({}): conversation checkpoints dropped", directive.level.as_str())); + } + } + + /// Keep the inventory's elastic classes current (the prefix store and the conversation checkpoints). + fn note_memory(&self) { + if leleka_memory::Governor::global().is_none() { + return; + } + if let Some(prefix) = self.prefix.as_ref() { + crate::memory_governor::set_bytes("prefix.store", prefix.bytes() as u64); + if let Some(g) = leleka_memory::Governor::global() { + g.note_prefix_used(prefix.bytes() as u64); + } + } + if let Some(conversation) = self.conversation.as_ref() { + crate::memory_governor::set_bytes("conversation.checkpoints", conversation.checkpoint_count() as u64 * crate::memory_governor::CHECKPOINT_BYTES); + } + } + + /// Register the stack's allocation classes with the inventory (sizes from the owners' own formulas and counters). + fn register_memory_classes(&self) { + use leleka_memory::{Space, When}; + let Some(governor) = leleka_memory::Governor::global() else { return }; + let _ = governor; + if let Some(f) = self.config.kv_footprint() { + crate::memory_governor::account("kv", "host_pinned", Space::HostPinned, When::Startup, "12 QSA layers x serving cells x 1056 B, pinned and device-mapped (the whole serving context, allocated at open)", f.pinned_host_bytes as u64); + crate::memory_governor::account("kv", "vram_window", Space::Device, When::Startup, "12 layers x resident pages x 4244 B (+ page table + resolver state)", f.vram_bytes as u64); + crate::memory_governor::account("kv", "prompt_stage", Space::Device, When::Startup, "one INT8 staging pool of the prompt path (identity layout)", f.stage_bytes as u64); + } + if let Ok(bytes) = prefill_bytes(self.layout) { + crate::memory_governor::account( + "prefill", + if self.loan.is_some() { "arena_borrowed" } else { "arena" }, + Space::Device, + When::Startup, + if self.loan.is_some() { "carve of the prefill arena, borrowed from the last slots of the expert cache (not additional)" } else { "carve of the prefill arena at the chunk capacity" }, + if self.loan.is_some() { 0 } else { bytes as u64 }, + ); + } + if let Some(cache) = self.expert_cache.as_ref() { + crate::memory_governor::account("expert_cache", "slots", Space::Device, When::Startup, "slots x slot bytes (VRAM expert tier)", cache.bytes() as u64); + } + crate::memory_governor::account("ple", "history_and_scratch", Space::Device, When::Startup, "PLE history image + scratch", (PLE_HISTORY_BYTES + PLE_SCRATCH_BYTES) as u64); + crate::memory_governor::account("context", "accounted_total", Space::Device, When::Lazy, "sum of the context's budgeted allocations (not additive with the classes above; see the ledger for the driver-seen total)", 0); + if let Some(prefix) = self.prefix.as_ref() { + crate::memory_governor::account( + "prefix", + "store", + Space::HostPageable, + When::Elastic, + "blocks (14,208 B per token) + node states (~127 MiB each) under the governor-granted budget", + prefix.bytes() as u64, + ); + } + if self.conversation.is_some() { + crate::memory_governor::account( + "conversation", + "checkpoints", + Space::HostPageable, + When::Elastic, + "checkpoints x ~118 MiB (GDN/PLE images, draft ring, index tails)", + 0, + ); + } + } + + /// Labels of the window policies of `LELEKA_SPEC_ARMS` in the order given (empty when unset), the live one included. + #[allow(dead_code)] + pub(crate) fn spec_arms(&self) -> Vec { + self.arm_order.clone() + } + /// Make `label` the window policy of the following requests (between requests only). Returns false for an unknown label. + #[allow(dead_code)] + pub(crate) fn select_spec_arm(&mut self, label: &str) -> bool { + if self.arm_label == label { + return true; + } + let Some(at) = self.parked.iter().position(|(l, _, _)| l == label) else { return false }; + let (new_label, new_settings, new_controller) = self.parked.swap_remove(at); + let old_label = std::mem::replace(&mut self.arm_label, new_label); + let old_settings = std::mem::replace(&mut self.settings, new_settings); + let old_controller = std::mem::replace(&mut self.controller, new_controller); + self.parked.push((old_label, old_settings, old_controller)); + true + } + /// The live arm's own request floor, if its label pinned one (`fixed4@0`). + #[allow(dead_code)] + pub(crate) fn spec_arm_min_p(&self) -> Option { + self.settings.request_min_p + } + #[allow(dead_code)] + pub(crate) fn spec_arm(&self) -> &str { + &self.arm_label + } + + /// Wall-clock milliseconds of the last request's prompt phase and decode phase. + #[cfg_attr(not(test), allow(dead_code))] + pub(crate) fn last_timing(&self) -> (f64, f64) { + self.timing + } + + /// Where the last request's time to first token went: `(resumed, prefilled, assembled, first_round)`, each the + /// milliseconds since `serve` was entered when that stage ended (`resumed`: the cache lookup, import and any reset; + /// `prefilled`: the prompt chunks, the lent-slot refill and the seed; `assembled`: the verifier (graphs, canonical + /// state upload); `first_round`: the first verified round was emitted). NaN for a stage the request did not reach. + #[allow(dead_code)] + pub(crate) fn ttft_marks(&self) -> [f64; 4] { + self.marks.as_array() + } + + /// The VRAM expert tier's counters (`None` when the tier is off). + pub(crate) fn expert_tier_stats(&self) -> Option { + self.expert_cache.as_ref().map(|cache| { + let mut stats = self.residency.stats; + stats.swaps = cache.swaps(); + stats + }) + } + + /// The tier's configuration, for an experiment that switches the adaptive tier or the seed between requests (the + /// adaptive counts are allocated at open, so `adapt_every` may be changed freely, a seed needs the tier on). + #[allow(dead_code)] + pub(crate) fn expert_tier_mut(&mut self) -> &mut ExpertTierConfig { + &mut self.config.expert_tier + } + + /// The last request's seed from the prompt's routing (`None`: seed off, or no prompt rows were read). + #[allow(dead_code)] + pub(crate) fn last_seed(&self) -> Option { + self.seed_report + } + + /// Cumulative (vram, pcie, cpu) window entries after each verified round of the last request. + #[allow(dead_code)] + pub(crate) fn round_marks(&self) -> Vec<[u64; 3]> { + self.residency.round_marks() + } + + /// A first-request state for an experiment: the tier back on the starting profile's set, the adaptive counts and + /// the draft/adaptation controller as in a new process. Returns the swaps the restore needed. + #[allow(dead_code)] + pub(crate) fn reset_expert_tier(&mut self) -> Result { + if let Some(error) = self.broken { + return Err(error); + } + self.residency.clear_usage(); + self.controller = self.settings.controller()?; + match self.expert_cache.as_mut() { + Some(cache) => original_serve_seed::restore_placement(self.binding, &self.moe, cache, &mut self.pool, &mut self.residency.spans, &self.initial_owners), + None => Ok(0), + } + } + + /// Prompt tokens the last request reused from the conversation cache (generate.cpp `REUSED`). + pub(crate) fn reused_tokens(&self) -> usize { + self.reused + } + + /// The position the conversation cache resumed the last request at (equals `reused_tokens` unless + /// `STRATA_CKPT_REREAD` re-read that prefix from 0). + #[cfg_attr(not(test), allow(dead_code))] + pub(crate) fn resume_point(&self) -> usize { + self.resume_point + } + + /// Drop every conversation checkpoint and the live state: the next request reads its whole prompt. + #[cfg_attr(not(test), allow(dead_code))] + pub(crate) fn forget_conversation(&mut self) { + if let Some(conversation) = self.conversation.as_mut() { + conversation.invalidate(); + } + if let Some(prefix) = self.prefix.as_mut() { + prefix.invalidate(); + } + } + + /// Verification arm: while set, requests read their whole prompt on the grid without using or changing the prefix + /// cache (the reference a cached request must reproduce). + #[allow(dead_code)] + pub(crate) fn prefix_bypass(&mut self, bypass: bool) { + if let Some(prefix) = self.prefix.as_mut() { + prefix.set_bypass(bypass); + } + } + + /// Drop the cached sessions nobody used for the retention time (60 minutes by default); the idle loop calls this. + pub(crate) fn prefix_expire_idle(&mut self) -> usize { + self.prefix.as_mut().map_or(0, |prefix| prefix.expire_idle()) + } + + /// The prefix cache's summary for a front router (`None` when the cache is off). + #[allow(dead_code)] + pub(crate) fn prefix_summary(&self, max_heads: usize) -> Option { + self.prefix.as_ref().map(|prefix| prefix.summary(max_heads)) + } + + /// The `prefix_match` query: how many tokens of the prompt whose block hash chain is `chain` are cached. + #[allow(dead_code)] + pub(crate) fn prefix_match(&self, chain: &[u64]) -> Option { + self.prefix.as_ref().map(|prefix| prefix.prefix_match(chain)) + } + + /// The prefix cache's metrics line (`None` when the cache is off). + #[allow(dead_code)] + pub(crate) fn prefix_metrics(&self) -> Option { + self.prefix.as_ref().map(|prefix| prefix.describe()) + } + + /// Bytes the prefix cache holds now (0 when it is off). + #[allow(dead_code)] + pub(crate) fn prefix_bytes(&self) -> usize { + self.prefix.as_ref().map_or(0, |prefix| prefix.bytes()) + } + + /// The prefix cache's current byte budget (0 when it is off or fully shed). + #[allow(dead_code)] + pub(crate) fn prefix_budget_bytes(&self) -> usize { + self.prefix.as_ref().map_or(0, |prefix| prefix.budget_bytes()) + } + + /// Close every owner in dependency order; the first failure is reported after all were attempted. + pub(crate) fn close(self) -> Result<()> { + let Self { + conversation, residency, history, ple_history, ple_scratch, arena, expert_cache, executor, draft, session, pool, kar, + moe, dense, output, embedding, .. + } = self; + drop(conversation); + // the span cache retains registered-source spans of the bank `moe` closes below + drop(residency); + let mut first: Option = None; + let mut note = |result: Result<()>| { + if let Err(error) = result { + first.get_or_insert(error); + } + }; + note(history.close()); + note(ple_history.release().map_err(|_| Error::CudaExecution)); + note(ple_scratch.release().map_err(|_| Error::CudaExecution)); + drop(arena); + if let Some(cache) = expert_cache { + note(cache.close().map_err(|e| super::original_serve_verifier::driver_error(&e))); + } + note(executor.close()); + note(draft.close()); + drop((session, pool, kar)); + note(moe.close()); + note(dense.close()); + note(output.close()); + note(embedding.close()); + first.map_or(Ok(()), Err) + } + + fn mark_broken(&mut self, error: Error) { + self.broken.get_or_insert(error); + } + + /// Hand the twelve QSA owners to a fresh verifier and run the request's decode phase over it. + fn decode_phase( + &mut self, + request: &ServeRequest, + emit: &mut dyn FnMut(&[i32]) -> Result<()>, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result { + let Self { + binding, + context, + config, + settings, + max_cells, + rope, + blobs, + formats, + full_policy, + controller, + arm_label, + verifier_max_t, + history, + ple_history, + ple_scratch, + executor, + draft, + session, + pool, + kar, + moe, + dense, + output, + broken, + conversation, + expert_cache, + residency, + refill_pending, + refill_due, + marks, + prefix, + tail_consumed, + .. + } = self; + let binding: &ModelBinding = *binding; + let context: &'ctx Context<'ctx> = *context; + if controller.is_failed() { + // a failed restore/finish poisoned the controller; its adaptive cadence is the only thing lost + *controller = settings.controller()?; + } + crate::bringup_trace!("DBG[{:.0}s] decode_phase start", dbg_el()); + let sampling = RequestSampling::new(request.params, request.path)?; + let n = request.prompt.len(); + let base = session.original_verified_base()?; + crate::bringup_trace!("DBG[{:.0}s] decode: base position {} (n-1 = {})", dbg_el(), base.position, n as u64 - 1); + if base.position != (n as u64 - 1) { + return Err(Error::IdentityMismatch.into()); + } + // generate.cpp `ver.set_pcie_mode`: only a window that can stage anything over PCIe records the copy kernel. + let pcie_mode = match (expert_cache.as_ref(), moe.original_expert_bank()) { + (Some(_), Some(bank)) if config.expert_tier.pcie_num_for(bank.pageable()) > 0 => { + config.expert_tier.pcie_mode.graph_mode(bank.pageable(), blobs.spans_tile_blobs()).ok_or(Error::Unsupported( + super::contract::Stage::Session, + ))? + } + _ => 0, + }; + let p = profile::span("decode.seed_ple"); + seed_ple_history(&base, ple_history).map_err(|f| SpecError::Forward(f.error))?; + drop(p); + // the window reads the shared experts of all 48 layers in place: load/refresh them together first + let p = profile::span("decode.shared"); + let shared = moe.ensure_original_verify_shared(binding)?; + drop(p); + crate::bringup_trace!("DBG[{:.0}s] decode: shared experts loaded", dbg_el()); + let owners = executor.take_qsa_owners()?; + let ple_history: &DeviceBuffer<'ctx> = &*ple_history; + let weights = VerifyWeights { dense: &*dense, moe: &*moe, shared: &shared, formats: &*formats, ple_scratch: &*ple_scratch }; + let p = profile::span("decode.assemble"); + // queued after assembly's own uploads (canonical GDN image), before the graph capture + let mut queue_refill = || -> Result<()> { + if !std::mem::take(&mut *refill_due) { + return Ok(()); + } + if let Some(cache) = expert_cache.as_mut() { + let _p = profile::span("prefill.refill"); + original_serve_residency::refill_lent(binding, &*moe, cache, &mut residency.spans, true)?; + *refill_pending = true; + } + Ok(()) + }; + let assembled = assemble( + binding, &weights, context, &*output, &base, owners, ple_history, rope, blobs, *verifier_max_t, *max_cells, + pcie_mode, &mut queue_refill, + ); + drop(p); + marks.assembled = marks.since(); + // the lent slots' refill copies (queued at the end of the prompt phase) have run behind the assembly: wait for them + // before a window or the tier's own bookkeeping touches the cache + if std::mem::take(refill_pending) { + if let Some(cache) = expert_cache.as_mut() { + if let Err(error) = original_serve_residency::settle_refill(cache) { + broken.get_or_insert(error); + if let Ok(resources) = assembled { + let _ = disassemble(resources).map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); + } + return Err(SpecError::Forward(error)); + } + } + } + vram_note(context, "decode after assemble"); + crate::bringup_trace!("DBG[{:.0}s] decode: assemble -> {}", dbg_el(), if assembled.is_ok() { "ok" } else { "ERR" }); + let resources = match assembled { + Ok(resources) => resources, + Err(lost) => { + operator_line("assemble", &lost.failure); + if let Some(owners) = lost.owners { + if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners) { + broken.get_or_insert(error); + } + } else { + broken.get_or_insert(Error::IdentityMismatch); + } + return Err(SpecError::Forward(lost.failure.error)); + } + }; + let DecodeResources { verifier, qsa, slots } = resources; + // the NaN guard's retry takes a refused window back from these (OriginalVerifier::discard_window) + qsa.set_window_snapshots(settings.nan_guard.retries > 0); + let committed = request.prompt[..n - 1].to_vec(); + // The window's expert tier: the GPU share first and the CPU pool on the rest, or the CPU pool alone. + let mut gpu_pool; + let pool: &mut dyn OriginalServePool<'ctx> = match (expert_cache.as_mut(), moe.original_expert_bank()) { + (Some(cache), Some(bank)) => { + let pcie_num = config.expert_tier.pcie_num_for(bank.pageable()); + let tail_rank = original_serve_residency::effective_tail_rank(&*cache); + let pcie_locked = if pcie_num > 0 && original_serve_residency::pcie_locked_only() { bank.locked_experts() } else { Vec::new() }; + gpu_pool = GpuExpertPool { + binding, + moe: &*moe, + cache, + bank, + cpu: &mut *pool, + state: &mut *residency, + pcie_num, + adapt_every: config.expert_tier.adapt_every, + adapt_swaps: config.expert_tier.adapt_swaps as usize, + tail_rank, + pcie_locked, + }; + &mut gpu_pool + } + (Some(_), None) => return Err(SpecError::Forward(Error::IdentityMismatch)), + (None, _) => &mut *pool, + }; + let owners = HostOwners { + binding, + dense: &*dense, + context, + session: &mut *session, + draft: &mut *draft, + executor: &mut *executor, + kar: kar.as_mut(), + history: &mut *history, + pool, + qsa: Rc::clone(&qsa), + slots, + ple_history, + policy: &*full_policy, + }; + let want_tail = config.prefix.as_ref().is_some_and(|p| p.tail == TailMode::Reply) && prefix.is_some(); + controller.set_final_draft(want_tail); + *tail_consumed = None; + let host = OriginalServeHost::new(owners, committed, config.max_context as u64, sampling); + let (served, verifier, outcome) = match host { + Err(error) => (Err(SpecError::Forward(error)), verifier, None), + Ok(host) => { + let port = super::original_serve_engine::TracePort(NativeServePort::new(verifier, host)); + let engine = OriginalServeEngine::new(port, VOCABULARY, settings.max_t, settings.max_drafts()); + match engine { + Err(error) => { + // `new` consumed the port on failure; the verifier is gone with it. Treated as lost below. + let _ = error; + broken.get_or_insert(Error::IdentityMismatch); + return Err(SpecError::Forward(Error::IdentityMismatch)); + } + Ok(mut engine) => { + crate::bringup_trace!("DBG[{:.0}s] decode: engine ready, serving", dbg_el()); + let started = Instant::now(); + let serve_span = profile::span("decode.serve"); + let result = engine.set_min_p(request.spec_min_p).map_err(SpecError::Forward).and_then(|()| { + serve_request( + controller, + &mut engine, + &request.prompt, + request.max_new, + request.spec_min_p, + &request.eos, + |tokens| { + if marks.first_round.is_nan() { + marks.first_round = marks.since(); + } + emit(tokens) + }, + &mut *cancel, + || started.elapsed().as_secs_f64() * 1e3, + ) + }); + drop(serve_span); + { + // the controller's round counters belong to this request in every window policy + let stats = controller.take_stats(); + if super::original_spec_controller::stats_enabled() { + eprintln!("DBG spec-stats arm={} {}", arm_label, stats.line()); + } + } + if let Err(e) = &result { crate::bringup_trace!("DBG[{:.0}s] serve_request err {e:?}", dbg_el()); } + let (mut verifier, mut host) = engine.into_port().0.into_parts(); + // STRATA_VERIFY_PROFILE=1: the GPU stage times of the request's windows (empty otherwise) + let gpu_profile = verifier.profile_report(); + if !gpu_profile.is_empty() { + eprintln!("DBG verify-profile:{gpu_profile}"); + } + // conversation cache: the session can be continued as is only when the draft ring + // stands at its position (then its recurrent state is settled to match) + let live = conversation.is_some() + && matches!(result, Ok(_) | Err(SpecError::Cancelled)) + && host.draft_in_step(); + // prefix cache, TailMode::Reply: the session settled and the ring in step (the final window was drafted) + let tail = want_tail && result.is_ok() && prefix.is_some() && host.draft_in_step(); + if want_tail && result.is_ok() && !tail { + operator_text("prefix tail: the draft ring is not at the session's position; no checkpoint at the end of this decode"); + } + if (result.is_ok() && config.settle_state) || live || tail { + match host.settle_state(&mut verifier) { + Ok(()) if live => { + if let Some(conversation) = conversation.as_mut() { + conversation.note_live(host.committed().to_vec()); + } + } + Ok(()) if tail => *tail_consumed = Some(host.committed().to_vec()), + Ok(()) => {} + Err(error) => { + broken.get_or_insert(error); + } + } + } + let outcome = host.finish(); + (result, verifier, Some(outcome)) + } + } + } + }; + // The MTP drafter's cached round programs and staged window are bound to THIS verifier's bank: release them before the + // bank closes (it is shared while they live) and so the next request captures against its own bank. + let p = profile::span("decode.release_mtp"); + let released = executor.mtp_release_verifier(binding); + drop(p); + if let Err(error) = released { + operator_line("release MTP verifier bindings", &failure(error)); + broken.get_or_insert(error); + } + // Close the verifier (drains both streams, drops the graphs) and take the physical owners back at + // the session's lineage; an abandoned window is rolled back there. + let p = profile::span("decode.disassemble"); + let disassembled = disassemble(DecodeResources { verifier, qsa, slots }); + drop(p); + match disassembled { + Ok(owners) => { + let _p = profile::span("decode.adopt"); + if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners) { + broken.get_or_insert(error); + } + } + Err(lost) => { + operator_line("disassemble", &lost); + broken.get_or_insert(lost.error); + } + } + if outcome.is_some_and(|o| o.failed) { + broken.get_or_insert(Error::IdentityMismatch); + } + served + } + + /// Condition `prompt[resume..n-1]` through the batched Original prefill, one chunk transaction at a time + /// (the session and the draft ring stand at `resume`; with the conversation cache's `STRATA_CKPT_REREAD` + /// they stand at 0 and the reread segment comes first). After each published chunk the conversation cache + /// takes its periodic and turn/root checkpoints. + /// + /// With the expert tier, the swaps in flight land first (generate.cpp `apply_pending(true)`), every chunk + /// borrows the cache's last slots (`prefill_chunk`) and every lent slot is refilled before the decode + /// phase, whatever the read's outcome (generate.cpp `refill`). + fn prefill_phase( + &mut self, + request: &ServeRequest, + resume: usize, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result<(), SpecError> { + self.residency.begin_request(); + self.seed_report = None; + if let Some(cache) = self.expert_cache.as_mut() { + let _p = profile::span("prefill.wait_swaps"); + cache.wait_swaps().map_err(|e| SpecError::Forward(super::original_serve_verifier::driver_error(&e)))?; + } + // LELEKA_ORIGINAL_SERVE_SEED: the MoE stage adds its host-known route counts per (layer, expert) + let seeding = self.config.expert_tier.seed_swaps > 0 && self.expert_cache.is_some(); + if seeding { + self.moe.capture_prompt_routing(true, self.config.expert_tier.seed_decay); + } + let p = profile::span("prefill.read"); + let read = self.prefill_actions(request, resume, cancel); + drop(p); + let _p = profile::span("prefill.refill"); + // a failed or cancelled read still refills at once (generate.cpp `refill`); a good one overlaps the copies with the + // decode phase's host-side assembly + // (the prompt-routing seed needs the lent slots refilled first, so it turns the deferral off for its requests) + let defer = read.is_ok() && !seeding && original_serve_residency::refill_defer_enabled() && self.loan.is_some() && self.expert_cache.is_some(); + let refilled = match (self.loan, self.expert_cache.as_mut()) { + (Some(_), Some(cache)) if !defer => { + original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false).map(|_| ()) + } + _ => Ok(()), + }; + let routing = if seeding { self.moe.take_prompt_routing() } else { None }; + let seeded = match (&read, &refilled, routing) { + (Ok(()), Ok(()), Some(counts)) if !defer => { + let _p = profile::span("prefill.seed"); + self.seed_residency(&counts) + } + _ => Ok(()), + }; + self.refill_due = defer; + match (read, refilled, seeded) { + (Ok(()), Err(error), _) | (Ok(()), Ok(()), Err(error)) => { + self.mark_broken(error); + Err(SpecError::Forward(error)) + } + (read, _, _) => read, + } + } + + /// Put the prompt's own routing into the tier's placement before the first window (see `original_serve_seed`). + fn seed_residency(&mut self, counts: &[f32]) -> Result<()> { + let tier = &self.config.expert_tier; + let (max, keep, usage) = (tier.seed_swaps, tier.seed_keep, tier.seed_usage); + let Some(cache) = self.expert_cache.as_mut() else { return Ok(()) }; + let started = Instant::now(); + let max_rows = tier.seed_max_rows; + if max_rows > 0 { + let rows = original_serve_seed::summarize(counts, &[]).rows; + if rows > max_rows as u64 { + if std::env::var_os("LELEKA_SEED_TRACE").is_some() { + eprintln!("DBG seed: skipped, the prompt routed {rows} rows (cap {max_rows})"); + } + return Ok(()); + } + } + let swaps = original_serve_seed::plan(counts, cache, max, keep); + let planned = started.elapsed(); + let mut report = original_serve_seed::summarize(counts, &swaps); + original_serve_seed::queue_swaps(self.binding, &self.moe, cache, &mut self.pool, &mut self.residency.spans, &swaps)?; + report.plan_ms = planned.as_secs_f64() * 1e3; + report.queue_ms = (started.elapsed() - planned).as_secs_f64() * 1e3; + self.residency.add_usage(counts, usage); + if std::env::var_os("LELEKA_SEED_TRACE").is_some() { + eprintln!( + "DBG seed: prompt rows {} routed -> {} swaps (gain {:.0}, most in one layer {}), plan {:.2} ms, queue {:.2} ms", + report.rows, report.planned, report.gain, report.max_layer_swaps, report.plan_ms, report.queue_ms + ); + } + self.seed_report = Some(report); + if std::env::var_os("LELEKA_SEED_TRACE").is_some() { + self.seed_counts = Some(counts.to_vec()); + } + Ok(()) + } + + /// `LELEKA_SEED_TRACE`: how much of the request's decode routing (the adaptive counts, so for a static arm) the resident + /// set covers: the starting profile's set, the prompt's top experts (what the seed installs, per layer slot counts of the + /// profile) and the best any static set could do (the decode's own top experts). + fn seed_coverage_trace(&mut self) { + let Some(prompt) = self.seed_counts.take() else { return }; + let usage = self.residency.usage(); + if usage.len() != prompt.len() || self.config.expert_tier.adapt_every != 0 { + return; + } + let mut slots = [0usize; 48]; + let mut initial = vec![false; 48 * 512]; + for &(layer, expert) in self.initial_owners.iter().flatten() { + slots[layer] += 1; + initial[layer * 512 + expert] = true; + } + let total: f64 = usage.iter().map(|&u| f64::from(u)).sum(); + if total <= 0.0 { + return; + } + let (mut by_prompt, mut oracle, mut by_initial) = (0f64, 0f64, 0f64); + for layer in 0..48 { + let range = layer * 512..(layer + 1) * 512; + let mut order: Vec = (0..512).collect(); + order.sort_by(|&a, &b| prompt[range.start + b].total_cmp(&prompt[range.start + a])); + by_prompt += order.iter().take(slots[layer]).map(|&e| f64::from(usage[range.start + e])).sum::(); + let mut best: Vec = usage[range.clone()].to_vec(); + best.sort_by(|a, b| b.total_cmp(a)); + oracle += best.iter().take(slots[layer]).map(|&u| f64::from(u)).sum::(); + by_initial += (0..512).filter(|&e| initial[range.start + e]).map(|e| f64::from(usage[range.start + e])).sum::(); + } + // Opt-in: `seed_counts` is only recorded under LELEKA_SEED_TRACE, so this returns early (and prints nothing) otherwise. + eprintln!( + "DBG seed-coverage: decode entries {total:.0}; covered by the starting set {:.1}%, the prompt's top experts {:.1}%, the decode's own top experts {:.1}% (oracle)", + 100.0 * by_initial / total, + 100.0 * by_prompt / total, + 100.0 * oracle / total + ); + } + + fn prefill_actions( + &mut self, + request: &ServeRequest, + resume: usize, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result<(), SpecError> { + let binding: &ModelBinding = self.binding; + let n = request.prompt.len(); + crate::bringup_trace!("DBG[{:.0}s] prefill_phase start n={n} resume={resume}", dbg_el()); + // generate.cpp: mtp.set_prompt_len(n) before the prompt is read; the draft cap and the request's + // sampling parameters configure the actor for the whole request. + let mtp_setup_span = profile::span("prefill.mtp_setup"); + self.executor.set_mtp_prompt_len(binding, n as i64)?; + self.executor.set_mtp_max_drafts(binding, i32::try_from(self.settings.max_drafts()).map_err(|_| Error::Overflow)?)?; + self.executor.set_mtp_draft_sampling(binding, &request.params)?; + drop(mtp_setup_span); + if n < 2 { + return Ok(()); + } + let setup_span = profile::span("prefill.setup"); + let tokens: Vec = request.prompt.iter().map(|&t| t as u32).collect(); + let source = OriginalPromptInput::from_tokenized(binding, &tokens)?; + let options = PromptOptions { + context_tokens: usize::try_from(self.config.max_context).map_err(|_| Error::Overflow)?, + prompt_cache: false, + turn_token: None, + root_min: 0, + // every conditioning read goes through the batched prefill (the verify-window read of short + // prompts needs the verifier during the prompt phase; see the open items) + short_read: 64, + force_batched: true, + verify_width: 4, + auto_max: 8192, + grid: 0, + }; + let (options, reread_to) = match (&self.prefix, &self.conversation) { + // the prefix cache reads on its grid and has no turn/root cuts: every checkpoint is a pure function of its tokens + // (a request that resumes between two grid points, from a request-end checkpoint, reads its suffix in as few chunks as the + // capacity allows: its states are not grid-canonical anyway) + (Some(prefix), _) => (PromptOptions { grid: if resume % prefix.block_tokens() == 0 { prefix.block_tokens() } else { 0 }, ..options }, None), + (None, Some(conversation)) => (conversation.config().plan_options(options), conversation.reread_to()), + (None, None) => (options, None), + }; + let capacity = self.config.capacity; + let plan = PromptPlan::new(&tokens, resume, reread_to, None, options, capacity).map_err(|e| { crate::bringup_trace!("DBG[{:.0}s] PromptPlan::new err {e:?} (n={n} capacity={capacity})", dbg_el()); plan_error(e) })?; + crate::bringup_trace!("DBG[{:.0}s] prompt plan ok", dbg_el()); + drop(setup_span); + for action in plan { + crate::bringup_trace!("DBG[{:.0}s] prompt action path={:?} first={} count={}", dbg_el(), action.path, action.first, action.count); + if action.path == PromptPath::FinalSeed { + // the last prompt token is the first verify input of the decode phase + break; + } + let PromptPath::Batched { .. } = action.path else { + return Err(Error::IdentityMismatch.into()); + }; + if self.session.target_origin()?.next_position() != action.first as u64 { + return Err(Error::IdentityMismatch.into()); + } + if cancel() { + return Err(SpecError::Cancelled); + } + if let Some(prefix) = self.prefix.as_mut() { + prefix.before_chunk(action.first); + } + self.prefill_chunk(&source, action.count, cancel)?; + self.after_prompt_action(&request.prompt, &action); + self.prefix_after_chunk(&request.prompt, action.first + action.count); + } + if self.session.target_origin()?.next_position() != (n as u64 - 1) { + return Err(Error::IdentityMismatch.into()); + } + self.prefix_after_prefill(&request.prompt); + Ok(()) + } + + /// One batched chunk of `count` rows from the session's position: the forward transaction and its publication. + /// With a loan the chunk's buffers are the expert cache's last slots, lent for this chunk only (the lent + /// slots stay misses until `prefill_phase` refills them); otherwise the stack's own buffers. + fn prefill_chunk( + &mut self, + source: &Rc, + count: usize, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result<(), SpecError> { + let Self { + binding, moe, arena, layout, expert_cache, loan, loan_tiers, executor, draft, session, kar, dense, embedding, + scalar_policy, .. + } = self; + let mut chunk = PromptChunk { + binding: *binding, + executor: &mut *executor, + dense: &*dense, + session: &mut *session, + source, + kar: kar.as_mut(), + moe: &mut *moe, + draft: &mut *draft, + embedding: &*embedding, + scalar_policy: &*scalar_policy, + }; + let first = chunk.session.target_origin().map(|o| o.next_position()).unwrap_or(0); + super::prefill_profile::begin_chunk(); + let ran = match (*loan, expert_cache.as_mut(), arena.as_mut()) { + (Some(slots), Some(cache), _) => match { + let _span = super::prefill_profile::span(super::prefill_profile::Stage::Lend, None); + // the smallest rung of the ladder that holds the chunk + let (slots, options) = tier_for(loan_tiers, count).map_or((slots, *layout), |t| (t.slots, t.layout)); + cache.lend_prefill_tail(slots, options) + } { + Ok(mut lent) => chunk.run(count, &mut lent, cancel), + Err(e) => Err(SpecError::Forward(super::original_serve_verifier::driver_error(&e))), + }, + (_, _, Some(own)) => chunk.run(count, own, cancel), + _ => Err(Error::IdentityMismatch.into()), + }; + if ran.is_ok() { + super::prefill_profile::end_chunk(first, count); + } + ran + } + + /// The prefix cache at the end of the prefill: with `TailMode::Prompt` or `Reply` a checkpoint at `n - 1`, where the next turn of + /// the session resumes (its prompt starts with this one). A checkpoint that cannot be taken costs only itself. + fn prefix_after_prefill(&mut self, prompt: &[i32]) { + let Some(mut prefix) = self.prefix.take() else { return }; + let _span = profile::span("prefix.after_prefill"); + match prefix.after_prefill(self, prompt) { + Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { + operator_text(&format!("prefix tail admit (prompt end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); + } + Ok(other) => operator_text(&format!("prefix tail (prompt end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())), + Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the prefill; skipped")), + } + self.prefix = Some(prefix); + } + + /// The end of the decode (`TailMode::Reply`): a checkpoint at the end of the prompt and the committed reply. The session is settled and the + /// draft ring stands at its position (`decode_phase` made sure); the cells past the prompt were produced by the decode. + fn prefix_after_decode(&mut self, consumed: &[i32]) { + let Some(mut prefix) = self.prefix.take() else { return }; + let _span = profile::span("prefix.after_decode"); + match prefix.after_decode(self, consumed) { + Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { + operator_text(&format!("prefix tail admit (decode end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); + } + Ok(other) => operator_text(&format!("prefix tail (decode end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())), + Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the decode; skipped")), + } + self.prefix = Some(prefix); + } + + /// The prefix cache after a published chunk: a checkpoint at the grid point if the policy wants one. A checkpoint + /// that cannot be built costs the cache, never the request. + fn prefix_after_chunk(&mut self, prompt: &[i32], end: usize) { + let Some(mut prefix) = self.prefix.take() else { return }; + let _span = profile::span("prefix.after_chunk"); + match prefix.after_chunk(self, prompt, end) { + Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { + if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() { + operator_text(&format!("prefix admit: tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); + } + } + Ok(other) => { + if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() && !matches!(other, ChunkOutcome::Nothing) { + operator_text(&format!("prefix admit (grid point {end}) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())); + } + } + Err(error) => { + operator_text(&format!("prefix cache: {error:?} while checkpointing; dropping the cache")); + prefix.invalidate(); + } + } + self.prefix = Some(prefix); + } + + /// A cancel between two prompt chunks leaves the session at the last published one: that is still the request's conversation + /// (`ServeConversation::note_cancelled_prefill`). The claim needs the same state a live continuation needs at the next + /// request: nothing lost, the recurrent state settled and the draft ring at the session's position. + fn keep_conversation_after_cancelled_prefill(&mut self, request: &ServeRequest) { + let Some(mut conversation) = self.conversation.take() else { return }; + if let Ok(position) = ResumeDevice::position(self) { + let in_step = ResumeDevice::live_in_step(self); + if conversation.note_cancelled_prefill(&request.prompt, position, in_step) { + operator_text(&format!("cancelled request keeps its conversation: {position} tokens live")); + } + } + self.conversation = Some(conversation); + } + + /// The conversation cache's bookkeeping after a published chunk. A checkpoint that cannot be saved costs + /// the cache, never the request: the cache is dropped and the request goes on. + fn after_prompt_action(&mut self, prompt: &[i32], action: &crate::backend::original_prompt::PromptAction) { + let Some(mut conversation) = self.conversation.take() else { return }; + let _span = profile::span("conv.after_action"); + if let Err(error) = conversation.after_action(self, prompt, action) { + operator_text(&format!("conversation cache: {error}; dropping the cache")); + conversation.invalidate(); + } + self.conversation = Some(conversation); + } +} + +/// The owners one batched prompt chunk needs, so the chunk runs over the stack's own buffers or a loan. +struct PromptChunk<'s, 'ctx> { + binding: &'s ModelBinding, + executor: &'s mut OriginalPromptExecutor<'ctx>, + dense: &'s DenseWeightCache<'ctx>, + session: &'s mut QwenSession<'ctx>, + source: &'s Rc, + kar: Option<&'s mut KarPleCache<'ctx>>, + moe: &'s mut MoeWeightCache<'ctx>, + draft: &'s mut super::session::original_prompt::draft::OriginalDraftSession<'ctx>, + embedding: &'s OriginalPromptEmbedding<'ctx>, + scalar_policy: &'s OriginalMtpScalarPolicy, +} +impl<'ctx> PromptChunk<'_, 'ctx> { + fn run( + &mut self, + count: usize, + arena: &mut OriginalPrefillArena<'_, 'ctx>, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result<(), SpecError> { + let pending = self.executor.forward( + self.binding, + self.dense, + &mut *self.session, + self.source, + count, + self.kar.as_deref_mut(), + &mut *self.moe, + &mut *arena, + &mut *self.draft, + self.embedding, + self.scalar_policy, + || cancel(), + ); + if let Err(e) = &pending { crate::bringup_trace!("DBG[{:.0}s] executor.forward err {e:?}", dbg_el()); } + let pending = match pending { + Ok(pending) => pending, + Err(error) if cancel() => { + let _ = error; + return Err(SpecError::Cancelled); + } + Err(error) => return Err(SpecError::Forward(error)), + }; + crate::bringup_trace!("DBG[{:.0}s] forward ok, publishing", dbg_el()); + let _span = super::prefill_profile::span(super::prefill_profile::Stage::Publish, None); + pending.publish()?; + crate::bringup_trace!("DBG[{:.0}s] published", dbg_el()); + Ok(()) + } +} + +static DBG_T0: std::sync::OnceLock = std::sync::OnceLock::new(); +/// Bring-up tracing clock (seconds since the first call); remove together with the DBG lines. +/// `LELEKA_SERVE_PROFILE=1`: the card's free VRAM at a point of the stack's life (where the auto-sized cache's room goes). +fn vram_note(context: &Context<'_>, label: &str) { + if profile::enabled() { + if let Ok((free, total)) = context.memory_info() { + eprintln!("DBG vram {label}: free {} MiB of {} MiB", free >> 20, total >> 20); + } + } +} +pub(crate) fn dbg_el() -> f32 { + DBG_T0.get_or_init(std::time::Instant::now).elapsed().as_secs_f32() +} + +/// One operator line per CPU kind and per CUDA device: which kernel family the process runs on each (logging only). +fn report_kernel_selection() { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + for line in leleka_native_cpu_expert::cpu_kernel_report() { + operator_note(&line); + } + for line in leleka_cuda_driver::gpu_kernel_report() { + operator_note(&line); + } +} + +fn operator_note(text: &str) { + use std::io::Write; + let _ = writeln!(std::io::stderr().lock(), "leleka-serve {text}"); +} + +fn operator_line(what: &str, failure: &ServeFailure) { + use std::io::Write; + let _ = writeln!(std::io::stderr().lock(), "leleka-serve {what}: {}", failure.describe()); +} + +fn operator_text(line: &str) { + use std::io::Write; + let _ = writeln!(std::io::stderr().lock(), "leleka-serve {line}"); +} + +/// The conversation cache's device side over the stack's own owners. +impl<'a, 'ctx> ResumeDevice for OriginalServeStack<'a, 'ctx> { + type Point = StackPoint<'ctx>; + fn zero(&mut self) -> Result<()> { + if RequestOwners::is_fresh(self) { + return Ok(()); + } + RequestOwners::reset(self) + } + fn position(&self) -> Result { + Ok(self.session.target_origin()?.next_position()) + } + fn save(&mut self) -> Result> { + if let Some(error) = self.broken { + return Err(error); + } + let session = self.executor.checkpoint_session(self.binding, &mut self.session)?; + let draft = self.draft.checkpoint(self.binding, &self.session)?; + Ok(StackPoint { session, draft }) + } + fn point_position(point: &StackPoint<'ctx>) -> u64 { + point.session.next_position() + } + fn restore(&mut self, point: &StackPoint<'ctx>) -> Result<()> { + if let Some(error) = self.broken { + return Err(error); + } + // a refused re-stamp touches nothing; a failed physical restore poisons the executor + let rebased = point.session.rebased_onto_current(&self.session)?; + let restored = self.executor.restore_session(self.binding, &self.dense, &mut self.session, &rebased); + if let Err(error) = restored { + self.mark_broken(error); + } + restored + } + fn restore_draft(&mut self, point: &StackPoint<'ctx>, resume: usize) -> Result<()> { + if let Some(error) = self.broken { + return Err(error); + } + let result = (|| { + self.draft.resume_at(self.binding, &self.dense, &self.session, &point.draft)?; + let upto = i64::try_from(resume).map_err(|_| Error::Overflow)?; + self.executor.mtp_kv_restore(self.binding, &self.session, &mut self.draft, upto) + })(); + if let Err(error) = result { + self.mark_broken(error); + } + result + } + fn live_in_step(&self) -> bool { + self.broken.is_none() + && self.session.original_state_lag().is_none() + && self.draft.in_step(self.binding, &self.session) + } +} + +impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { + /// `RequestOwners::resume` with the prefix cache: install the deepest checkpoint that is a prefix of the prompt. + fn prefix_resume(&mut self, request: &ServeRequest) -> Option { + let mut prefix = self.prefix.take()?; + let _resume_span = profile::span("request.resume"); + let n = request.prompt.len(); + let resume = if self.broken.is_some() { + prefix.invalidate(); + None + } else { + match prefix.begin(self, &request.prompt) { + Ok(Some(start)) => { + self.reused = start.resume; + self.resume_point = start.resume; + operator_text(&format!( + "prefix request: n={n} hit=yes resume={} switched={} branch={} copied_tokens={} import_ms={:.1} (state+kv {:.1}, draft {:.1}) match_us={:.0} live_tokens={}", + start.resume, + start.switched, + start.branch, + start.copied_tokens, + start.import_ms, + prefix.last_import_split().0, + prefix.last_import_split().1, + start.match_us, + prefix.live_tokens() + )); + Some(start.resume) + } + Ok(None) => { + operator_text(&format!("prefix request: n={n} hit=no resume=0 match_us={:.0}", prefix.last_match_us())); + None + } + Err(error) => { + // the cache is an optimisation: drop it and start from the empty prompt (`reset`) + operator_text(&format!("prefix cache: {error:?}; reading the whole prompt")); + prefix.invalidate(); + None + } + } + }; + self.prefix = Some(prefix); + resume + } +} + +/// The prefix cache's device side over the stack's own owners. +impl<'a, 'ctx> PrefixDevice for OriginalServeStack<'a, 'ctx> { + type State = StackState; + type Block = StackBlock; + fn position(&self) -> Result { + Ok(self.session.target_origin()?.next_position()) + } + fn estimate(&self, block_tokens: usize) -> (usize, usize) { + (PARKED_STATE_ESTIMATE, block_tokens * PARKED_BYTES_PER_TOKEN) + } + fn park_state(&mut self) -> Result { + if let Some(error) = self.broken { + return Err(error); + } + let _p = profile::span("prefix.park_state"); + let session = self.executor.park_session(self.binding, &mut self.session)?; + let draft = self.draft.checkpoint(self.binding, &self.session)?; + Ok(StackState { session, draft }) + } + fn park_block(&mut self, first: usize, tokens: usize) -> Result { + if let Some(error) = self.broken { + return Err(error); + } + let _p = profile::span("prefix.park_block"); + self.executor.park_block(&self.session, first, tokens).map(StackBlock) + } + fn park_tail(&mut self, first: usize, tokens: usize) -> Result { + if let Some(error) = self.broken { + return Err(error); + } + let _p = profile::span("prefix.park_tail"); + self.executor.park_block(&self.session, first, tokens).map(StackBlock) + } + fn import(&mut self, state: &StackState, blocks: &[(usize, &StackBlock)]) -> Result<()> { + if let Some(error) = self.broken { + return Err(error); + } + let blocks: Vec<&ParkedBlock> = blocks.iter().map(|(_, block)| &block.0).collect(); + let _p = profile::span("prefix.import_session"); + // a refused import touches nothing; a failed physical one poisons the executor + let imported = self.executor.import_session(self.binding, &self.dense, &mut self.session, &state.session, &blocks); + if let Err(error) = imported { + self.mark_broken(error); + } + imported + } + fn restore_draft(&mut self, state: &StackState, resume: usize) -> Result<()> { + if let Some(error) = self.broken { + return Err(error); + } + let result = (|| { + { + let _p = profile::span("prefix.draft_resume_at"); + self.draft.resume_at(self.binding, &self.dense, &self.session, &state.draft)?; + } + let upto = i64::try_from(resume).map_err(|_| Error::Overflow)?; + let _p = profile::span("prefix.mtp_kv_restore"); + self.executor.mtp_kv_restore(self.binding, &self.session, &mut self.draft, upto) + })(); + if let Err(error) = result { + self.mark_broken(error); + } + result + } +} + +impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { + fn is_fresh(&self) -> bool { + self.broken.is_none() + && self.session.original_state_lag().is_none() + && self.session.target_origin().is_ok_and(|origin| origin.next_position() == 0) + } + fn reset(&mut self) -> std::result::Result<(), Error> { + if let Some(error) = self.broken { + return Err(error); + } + let _p = profile::span("request.reset"); + let result = (|| { + let empty = self.empty_session.rebased_empty(&self.session)?; + self.executor.restore_session(self.binding, &self.dense, &mut self.session, &empty)?; + self.draft.reset_to_empty(self.binding, &self.dense, &self.session, &self.empty_draft) + })(); + if let Err(error) = result { + self.mark_broken(error); + } + result + } + fn resume(&mut self, request: &ServeRequest) -> Option { + self.reused = 0; + self.resume_point = 0; + if self.prefix.is_some() { + return self.prefix_resume(request); + } + let mut conversation = self.conversation.take()?; + let _resume_span = profile::span("request.resume"); + let resume = if self.broken.is_some() { + conversation.invalidate(); + None + } else { + match conversation.begin(self, &request.prompt) { + Ok(start) => { + self.reused = start.read_from; + self.resume_point = start.resume; + Some(start.resume) + } + Err(error) => { + // the cache is an optimisation: drop it and start from the empty prompt (`reset`) + operator_text(&format!("conversation cache: {error}; reading the whole prompt")); + conversation.invalidate(); + None + } + } + }; + self.conversation = Some(conversation); + resume + } + fn prefill(&mut self, request: &ServeRequest, resume: usize, cancel: &mut dyn FnMut() -> bool) -> std::result::Result<(), SpecError> { + let started = Instant::now(); + self.timing = (0.0, 0.0); + self.marks.resumed = self.marks.since(); + let result = self.prefill_phase(request, resume, cancel); + if matches!(result, Err(SpecError::Cancelled)) { + self.keep_conversation_after_cancelled_prefill(request); + } + self.marks.prefilled = self.marks.since(); + self.timing.0 = started.elapsed().as_secs_f64() * 1e3; + result + } + fn decode( + &mut self, + request: &ServeRequest, + emit: &mut dyn FnMut(&[i32]) -> Result<()>, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result { + let started = Instant::now(); + let tier0 = self.residency.stats; + let result = self.decode_phase(request, emit, cancel); + match (result.is_ok(), self.tail_consumed.take()) { + (true, Some(consumed)) if self.broken.is_none() => self.prefix_after_decode(&consumed), + _ => {} + } + // an exit before the decode phase queued the refill still refills now; one before it waited still waits + if std::mem::take(&mut self.refill_due) { + if let Some(cache) = self.expert_cache.as_mut() { + if let Err(error) = original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false) { + self.mark_broken(error); + } + } + } + if std::mem::take(&mut self.refill_pending) { + if let Some(cache) = self.expert_cache.as_mut() { + if let Err(error) = original_serve_residency::settle_refill(cache) { + self.mark_broken(error); + } + } + } + self.timing.1 = started.elapsed().as_secs_f64() * 1e3; + profile::add("decode.phase", self.timing.1); + if profile::enabled() { + let t1 = self.residency.stats; + let (v, p, c) = (t1.vram_entries - tier0.vram_entries, t1.pcie_entries - tier0.pcie_entries, t1.cpu_entries - tier0.cpu_entries); + let all = (v + p + c).max(1) as f64; + // the Original's hit rate: VRAM entries over VRAM + CPU entries (PCIe entries are in neither count) + eprintln!( + "DBG tier request: vram {v} ({:.1}%) pcie {p} ({:.1}%) cpu {c} ({:.1}%) hit_rate_original_def {:.1}% adaptations {} swaps {} pcie_num {}", + 100.0 * v as f64 / all, 100.0 * p as f64 / all, 100.0 * c as f64 / all, + 100.0 * v as f64 / ((v + c).max(1) as f64), t1.adaptations - tier0.adaptations, t1.swaps - tier0.swaps, + self.residency.pcie_lag.as_ref().map(|l| l.pcie_num()).or_else(|| self.residency.pcie_auto.as_ref().map(|a| a.pcie_num())).unwrap_or(self.config.expert_tier.pcie_num()) + ); + } + // graphs captured after the window/commit graphs: the MTP round programs of this request's drafts + let (capture_ms, instantiate_ms, _) = leleka_cuda_driver::original_capture_timing::take(); + profile::add("mtp.capture", capture_ms); + profile::add("mtp.instantiate", instantiate_ms); + profile::add("prefill.phase", self.timing.0); + profile::report("request"); + self.residency.flush_routing(); + self.seed_coverage_trace(); + result + } + fn finish(&mut self, ended: std::result::Result<(), ServeError>) { + let completed = self.broken.is_none() && matches!(ended, Ok(()) | Err(ServeError::Cancelled)); + if let Some(conversation) = self.conversation.as_mut() { + conversation.finish(completed); + } + if let Some(prefix) = self.prefix.as_mut() { + prefix.finish(completed); + let (admitted, park_ms, consider_ms) = prefix.request_parking(); + operator_text(&format!("prefix request done: admitted={admitted} park_ms={park_ms:.1} policy_ms={consider_ms:.1} {}", prefix.describe())); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_chunk_borrows_the_smallest_rung_that_holds_it() { + let blobs = ExpertBlobSizes::from_layer_bytes(std::array::from_fn(|l| 700_000 + 4096 * l), [700_000; 48], [900_000; 48]).unwrap(); + let layout = prefill_layout_options(8192, 262_144, &blobs); + let tiers: Vec = [(512usize, 600usize), (2048, 900)] + .into_iter() + .map(|(rows, slots)| LoanTier { rows, layout: PrefillLayoutOptions { capacity: rows, ..layout }, slots }) + .collect(); + assert_eq!(tier_for(&tiers, 1).map(|t| t.rows), Some(512)); + assert_eq!(tier_for(&tiers, 512).map(|t| t.rows), Some(512)); + assert_eq!(tier_for(&tiers, 513).map(|t| t.rows), Some(2048)); + assert_eq!(tier_for(&tiers, 2048).map(|t| t.slots), Some(900)); + assert!(tier_for(&tiers, 2049).is_none(), "above the ladder the chunk borrows the full loan"); + assert!(tier_for(&[], 100).is_none()); + // the arena of a smaller rung is smaller + assert!(prefill_bytes(tiers[0].layout).unwrap() < prefill_bytes(tiers[1].layout).unwrap()); + assert!(prefill_bytes(tiers[1].layout).unwrap() < prefill_bytes(layout).unwrap()); + } + + #[test] + fn the_default_chunk_is_an_admitted_capacity_and_validation_follows_the_prefill_rules() { + let config = StackConfig::new(4096); + assert!(ADMITTED_CAPACITIES.contains(&config.capacity)); + for capacity in [256usize, 1024, 8192] { + assert!(StackConfig { capacity, ..config.clone() }.validate().is_ok(), "{capacity}"); + } + for capacity in [0usize, 255, 300, 16384, 32768] { + assert!(StackConfig { capacity, ..config.clone() }.validate().is_err(), "{capacity}"); + } + assert!(StackConfig { max_context: 0, ..config.clone() }.validate().is_err()); + assert!(StackConfig { cpu_workers: 0, ..config.clone() }.validate().is_err()); + assert!(StackConfig { cpu_workers: 65, ..config.clone() }.validate().is_err()); + assert!(StackConfig { max_context: i64::MAX, ..config }.validate().is_err()); + } + + #[test] + fn the_conversation_cache_is_on_by_default_with_the_original_settings() { + let config = StackConfig::new(4096); + let conversation = config.conversation.as_ref().expect("--prompt-cache 6 is the default, as in the Original"); + assert_eq!((conversation.prompt_cache, conversation.prompt_cache_every, conversation.prompt_cache_root), (6, 16_384, 2048)); + assert_eq!(conversation.turn_token, Some(TURN_TOKEN)); + assert!(config.validate().is_ok()); + assert!(StackConfig { conversation: None, ..config }.validate().is_ok(), "the cache can be turned off"); + } + + #[test] + fn kv_defaults_to_the_production_int8_window_and_refuses_unported_formats() { + let config = StackConfig::new(4096); + assert_eq!((config.kv_format, config.kv_resident), (KvFormat::Int8, 32_768)); + assert_eq!(config.kv_footprint().map(|f| f.resident_pages), Some(8192)); + for kv_resident in [0usize, 1, 20_480, 40_000, 262_144] { + assert!(StackConfig { kv_resident, ..config.clone() }.validate().is_ok(), "{kv_resident}"); + } + assert!(StackConfig { kv_resident: 524_292, ..config.clone() }.validate().is_err()); + for kv_format in [KvFormat::Fp16, KvFormat::Q4_0, KvFormat::K8V4, KvFormat::Int8Keyless] { + assert_eq!( + StackConfig { kv_format, ..config.clone() }.validate(), + Err(Error::Unsupported(crate::qwen_forward::contract::Stage::Session)) + ); + } + } + + #[test] + fn plan_errors_keep_their_class() { + assert_eq!(plan_error(PlanError::InvalidInput), Error::InvalidDimension); + assert_eq!(plan_error(PlanError::Overflow), Error::Overflow); + } +} diff --git a/scripts/decode-sm120/build_rt.sh b/scripts/decode-sm120/build_rt.sh index 29cd8bf0..d6e207b1 100644 --- a/scripts/decode-sm120/build_rt.sh +++ b/scripts/decode-sm120/build_rt.sh @@ -1,23 +1,23 @@ -#!/usr/bin/env bash -# Build the leleka-runtime test binary (the replay smoke) of THIS worktree in WSL (never on the server). -# scripts/decode-sm120/build_rt.sh TAG run from Git Bash in the worktree -# Result: WSL ~/sm120-stack/rt-TAG; copy to rnr5090:/data/leleka-e2e/sm120/rt-TAG. -set -euo pipefail -tag=${1:?tag} -root=$(git rev-parse --show-toplevel) -tar_win="$root/../wt-sm120-rt.tar" -git -C "$root" -c core.autocrlf=false ls-files -co --exclude-standard -z | tar --force-local -C "$root" --null -T - -cf "$tar_win" -w=$(cygpath -m "$tar_win"); tar_wsl="/mnt/c${w#C:}" -wsl -d Ubuntu -e bash -lc " -set -e -source ~/.cargo/env -export PATH=\$HOME/cuda-toolkits/13.2.2/bin:\$HOME/.cargo/bin:/usr/local/bin:/usr/bin:/bin -rm -rf ~/sm120-src-rt && mkdir -p ~/sm120-src-rt ~/sm120-stack && tar -xf '$tar_wsl' -C ~/sm120-src-rt -cd ~/sm120-src-rt -export CARGO_TARGET_DIR=\$HOME/sm120-target-rel -nice -n 10 cargo test --no-run --locked --release -p leleka-runtime --lib > ~/sm120-stack/build-rt-$tag.log 2>&1 -exe=\$(grep -o 'release/deps/leleka_runtime-[0-9a-f]*' ~/sm120-stack/build-rt-$tag.log | tail -1) -cp \$CARGO_TARGET_DIR/\$exe ~/sm120-stack/rt-$tag -sha256sum ~/sm120-stack/rt-$tag -" -rm -f "$tar_win" +#!/usr/bin/env bash +# Build the leleka-runtime test binary (the replay smoke) of THIS worktree in WSL (never on the server). +# scripts/decode-sm120/build_rt.sh TAG run from Git Bash in the worktree +# Result: WSL ~/sm120-stack/rt-TAG; copy to rnr5090:/data/leleka-e2e/sm120/rt-TAG. +set -euo pipefail +tag=${1:?tag} +root=$(git rev-parse --show-toplevel) +tar_win="$root/../wt-sm120-rt.tar" +git -C "$root" -c core.autocrlf=false ls-files -co --exclude-standard -z | tar --force-local -C "$root" --null -T - -cf "$tar_win" +w=$(cygpath -m "$tar_win"); tar_wsl="/mnt/c${w#C:}" +wsl -d Ubuntu -e bash -lc " +set -e +source ~/.cargo/env +export PATH=\$HOME/cuda-toolkits/13.2.2/bin:\$HOME/.cargo/bin:/usr/local/bin:/usr/bin:/bin +rm -rf ~/sm120-src-rt && mkdir -p ~/sm120-src-rt ~/sm120-stack && tar -xf '$tar_wsl' -C ~/sm120-src-rt +cd ~/sm120-src-rt +export CARGO_TARGET_DIR=\$HOME/sm120-target-rel +nice -n 10 cargo test --no-run --locked --release -p leleka-runtime --lib > ~/sm120-stack/build-rt-$tag.log 2>&1 +exe=\$(grep -o 'release/deps/leleka_runtime-[0-9a-f]*' ~/sm120-stack/build-rt-$tag.log | tail -1) +cp \$CARGO_TARGET_DIR/\$exe ~/sm120-stack/rt-$tag +sha256sum ~/sm120-stack/rt-$tag +" +rm -f "$tar_win"