diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..0f1b7a7d --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# Rust sources under crates/ and the GPU bring-up scripts are LF in the repository. +# text=auto leaves files that already carry CRLF in the index untouched (no mass renormalization) +# and skips binary-looking files; it only stops CRLF from entering LF files at commit time. +crates/**/*.rs text=auto eol=lf +scripts/gpu-bringup/**/*.py text=auto eol=lf diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index d8258c51..c6778995 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -1,3507 +1,3507 @@ -//! Opt-in CUDA Driver context and bounded byte buffers, without inference. -//! -//! Enable `cuda-driver` and explicitly call [`Driver::load`] on Linux 64-bit. -//! Resources are confined to their creating thread and borrow their owners. -//! Copies stage owned bytes and synchronize before publishing host output. -//! A failed synchronization poisons the context and intentionally leaks the -//! bounded staging allocation: completion cannot safely be inferred from an -//! error, including a subsequent context-destruction result. -#![deny(unsafe_code)] -#![deny(unsafe_op_in_unsafe_fn)] - -// Windows: `libc::dlopen` and friends resolve to the shim (Linux keeps the real libc crate). -#[cfg(windows)] -extern crate leleka_libc_shim as libc; - - -/// Bring-up tracing: `LELEKA_BRINGUP_TRACE` set (any value) enables the `DBG`/`PROBE` diagnostics on stderr. -/// Off by default so production serving prints nothing extra. -pub(crate) fn bringup_trace_enabled() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("LELEKA_BRINGUP_TRACE").is_some()) -} -macro_rules! bringup_trace { - ($($arg:tt)*) => { - if $crate::bringup_trace_enabled() { - eprintln!($($arg)*); - } - }; -} -pub(crate) use bringup_trace; - -/// Bring-up: with `LELEKA_BRINGUP_TRACE` and `LELEKA_CUDA_TRACE_SYNC` set (Windows), every kernel launched while a guard -/// is alive is followed by a `cuStreamSynchronize`, so a device fault is named by the launch that caused it (the -/// non-blocking replacement of `CUDA_LAUNCH_BLOCKING`, scoped to the prompt forward because the decode windows would -/// deadlock). Elsewhere the guard does nothing. -pub struct PromptSyncTrace(()); -impl PromptSyncTrace { - pub fn enter() -> Self { - #[cfg(windows)] - libc::cuda_trace_set_sync(true); - Self(()) - } -} -impl Drop for PromptSyncTrace { - fn drop(&mut self) { - #[cfg(windows)] - libc::cuda_trace_set_sync(false); - } -} - -use std::{cell::{Cell, RefCell}, fmt, marker::PhantomData, rc::Rc}; - -#[allow(unsafe_code)] -mod ffi; -pub mod compute_drain; -pub mod vram_ledger; -mod device_slab; -pub use device_slab::{DeviceSlice, SlabAllocator, SlabPolicy, SlabStats}; -pub mod nvml; -mod deferred_status; -#[allow(unsafe_code)] -mod original_gpu_schedule; -pub use original_gpu_schedule::{ - OriginalCapture, OriginalCapturePolicy, OriginalEventKind, OriginalGpuEvent, OriginalGpuGraph, - OriginalGpuStream, OriginalGraphFlight, OriginalGraphKey, OriginalGraphRegistry, - OriginalGraphResources, OriginalStreamKind, OriginalWait, -}; -mod original_expert_cache; -mod original_expert_slots; -pub use original_expert_cache::OriginalExpertCache; -mod original_moe_prompt_device; -pub use original_moe_prompt_device::{OriginalMoePromptDevice, OriginalMoePromptLayer}; -mod original_prefill_arena; -pub use original_prefill_arena::{ - OriginalPrefillArena, OriginalPromptLeaseIdentity, OriginalPromptRows, -}; -mod original_prefill_layout; -pub use original_prefill_layout::{ - OriginalPrefillLayout, PrefillKvStage, PrefillLayoutOptions, PrefillPhase, PrefillSpan, -}; -mod head_greedy; -pub use head_greedy::{HEAD_GREEDY_WORKSPACE_BYTES, HeadGreedySelection, HeadGreedyWorkspace}; -mod gdn_state_finite_guard; -pub use gdn_state_finite_guard::GdnStateFiniteGuard; -mod routed_group_workspace; -mod routed_stage_finite_guard; -pub use routed_group_workspace::RoutedColumnsLoan; -pub use routed_group_workspace::RoutedGroupWorkspace; -pub use routed_stage_finite_guard::{RoutedFiniteStage, RoutedStageFiniteGuard}; -mod gr_read_guard; -mod mmq; -mod mmq_native; -pub use mmq::resident::original_group::{ - OriginalMmqCopySchedule, OriginalMmqLayer, OriginalMmqOutput, original_mmq_group_bank_bytes, -}; -pub(crate) use mmq::resident::original_group::prefetch_point; -pub use mmq::resident::{ - FiniteMmqOutput, MmqChunkActivation, MmqGroupActivation, MmqHidden, MmqWorkspace, -}; -pub use mmq::{MmqExperiment, MmqFormat, MmqProfile, MmqWeights}; -use mmq_native::NativeWeights; -mod moe_group_down_columns; -mod moe_group_projection; -mod mtp_dense_kv; -mod original_mtp_actor; -mod original_mtp_coupled; -mod original_mtp_loader; -mod original_mtp_rt; -mod original_mtp_bank; -pub use original_mtp_bank::{ - OriginalMtpLoadFailure, original_mtp_draft_vocab_bytes, OriginalMtpRtBank, OriginalMtpRtTensor, OriginalMtpTensorKind, -}; -pub use original_mtp_actor::{ - ActorRefusal as OriginalMtpActorRefusal, DraftSettings as OriginalMtpDraftSettings, -}; -pub use original_mtp_loader::{ - CoupledPlan as OriginalMtpCoupledPlan, KvFormat as OriginalMtpKvFormat, - KvMode as OriginalMtpKvMode, KvPlan as OriginalMtpKvPlan, LoaderError as OriginalMtpPlanError, - OriginalMtpCapture, OriginalMtpKvStartup, OriginalMtpLoadPlan, original_mtp_bind_reserve, - WeightBankPlan as OriginalMtpWeightBankPlan, -}; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use original_mtp_actor::{OriginalMtpActor, OriginalMtpLoadEvidence, OriginalMtpLoadMeter}; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -mod original_mtp_draft_head; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use original_mtp_draft_head::OriginalMtpDraftHead; -mod original_session_state; -pub use original_session_state::{ - OriginalGeometryFacts, OriginalHostKv, OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, - OriginalRegion, OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts, -}; -mod qwen_dispatch; -pub use qwen_dispatch::gr_batch_read::{GrMicroValues, GrMicrobatchRead}; -mod qsa_selected_kv; -mod serving_context; -pub use serving_context::{ - KV_RESIDENT_DEFAULT_CELLS, KV_RESIDENT_MIN_CELLS, MAX_CONTEXT_CELLS, ServingContext, TRAINED_CONTEXT_CELLS, - configure_kv_resident, configure_serving_context, kv_resident_cells, - serving_context, -}; -pub use mtp_dense_kv::MtpDenseKvRing; -pub use mtp_dense_kv::MTP_ORIGINAL_WINDOW; -pub use mtp_dense_kv::{ - CompletedMtpAttention, CompletedMtpKvReplay, MtpInt8OwnerId, MtpInt8Snapshot, MtpOriginalInt8, - MtpOriginalMixed, MtpOriginalQuery, -}; -pub use qsa_selected_kv::{QsaSelectedKvProducts, QsaSelectedKvWorkspace}; -#[allow(unsafe_code)] -mod qwen_ffi; - -pub mod host_profile; -pub mod experimental; -/// Per-command timing of the batched prompt producers (bring-up profiling only). -pub mod command_profile; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub mod experimental_gpu; -#[cfg(all( - test, - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] -#[path = "experimental_gpu_smoke.rs"] -mod experimental_gpu_smoke; -pub mod kar_decode_levels; -// Pure selection/geometry half of the Original QSA prompt-attention variants (any host). -pub mod qsa_prompt_attention_select; -// Pure scheduling model of the Original Prefill::run (expert stream plan, PLE read-ahead, fusion, hand-off). -pub mod original_prefill_schedule; -// Pure halves of small Original kernels/host files: prefill/moe_mmq.cu copy1/strata_q2/iota, core/device.cu. -pub mod mmq_original_prefill_misc; -pub mod device_arena; -// Pure half of the Original native_flash_attn.cu (admission, geometry, step rule, FP64 specification). -pub mod native_flash_attn; -pub mod s_gemv_legacy; -// Closed driver programs for native_flash_attn / s_gemv_legacy / device_poison: pins, entry signatures, argument slots (pure half). -pub mod closed_kernels; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub mod closed_kernels_gpu; -#[cfg(all( - test, - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] -#[path = "closed_kernels_gpu_smoke.rs"] -mod closed_kernels_gpu_smoke; -#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] -mod original_prefill_schedule_crosscheck; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub mod kar_decode_levels_gpu; -#[cfg(all( - test, - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] -#[path = "kar_decode_levels_gpu_smoke.rs"] -mod kar_decode_levels_gpu_smoke; -// Model-free stress of DMA out of a read-only file mapping that is page-locked in place, under working-set trimming (Windows only). -#[cfg(all(test, windows, feature = "cuda-driver", target_pointer_width = "64"))] -#[path = "mapped_file_dma_stress_gpu.rs"] -mod mapped_file_dma_stress_gpu; - -/// Errors retain CUDA operation names/codes and any subsequent cleanup errors. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Error { - Disabled, - UnsupportedPlatform, - LibraryUnavailable, - MissingSymbol(&'static str), - InvalidDriverValue(&'static str), - Driver { - operation: &'static str, - code: i32, - }, - ContextMismatch, - InvalidVectorShape, - InvalidMatvecShape, - InvalidQ5KProjectionShape, - InvalidQ6KProjectionShape, - InvalidQ8Activation, - NonFiniteMmqOutput(&'static str), - UnsupportedProjection, - UnsupportedQwenOperation, - InvalidQwenShape, - InvalidBf16ProjectionShape, - InvalidProjectionShape, - OutputAliasesInput, - InvalidOrdinal, - InvalidSize, - BudgetExceeded, - ShapeMismatch { - expected: usize, - actual: usize, - }, - HostAllocation, - ContextPoisoned, - UnexpectedContext, - /// A verifier graph did not fit in device memory when it was instantiated (upstream a8c1d4b7). The context is intact and the - /// verifier holds the windows recorded before it: `window` is the T of the window graph that did not fit, 0 for the commit - /// graph (recorded after every window). A caller can record again with fewer windows. - GraphOutOfMemory { - window: usize, - }, - Multiple { - primary: Box, - secondary: Box, - }, -} - -impl Error { - fn environment_message(&self) -> Option<&'static str> { - Some(match self { - Self::Disabled => "CUDA Driver feature is disabled", - Self::UnsupportedPlatform => "CUDA Driver requires Linux with 64-bit pointers", - Self::LibraryUnavailable => "cannot load libcuda.so.1", - Self::InvalidOrdinal => "device ordinal must be nonnegative", - Self::HostAllocation => "cannot allocate owned host staging memory", - Self::ContextPoisoned => { - "context is poisoned after uncertain completion or restoration" - } - Self::UnexpectedContext => "CUDA pop returned a different context", - _ => return None, - }) - } - fn validation_message(&self) -> Option<&'static str> { - Some(match self { - Self::ContextMismatch => "buffers must belong to this exact context", - Self::InvalidVectorShape => { - "vector shape must be nonempty f32 bytes with a bounded u32 count/grid" - } - Self::InvalidMatvecShape => { - "matvec requires exact nonempty bounded row-major f32 shapes" - } - Self::InvalidQ5KProjectionShape => { - "Q5_K projection requires exact bounded row-major single-column shapes" - } - Self::InvalidQ6KProjectionShape => { - "Q6_K projection requires exact bounded row-major single-column shapes" - } - Self::UnsupportedProjection => "projection format is not integrated", - Self::UnsupportedQwenOperation => "Qwen operation has no qualified fixed asset", - Self::InvalidQwenShape => { - "Qwen operation requires its exact pinned topology and byte layout" - } - Self::InvalidBf16ProjectionShape => { - "BF16 projection requires exact bounded rows and positive even columns" - } - Self::InvalidProjectionShape => { - "projection requires exact bounded packed single-column shapes" - } - Self::InvalidQ8Activation => "activation cannot be represented by native Q8_1", - Self::NonFiniteMmqOutput(_) => "MMQ produced a nonfinite stage output", - Self::OutputAliasesInput => "output must not alias an input", - Self::InvalidSize => "byte size must be nonzero and fit isize", - Self::BudgetExceeded => "allocation exceeds context byte budget", - _ => return None, - }) - } -} -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if let Some(message) = self - .environment_message() - .or_else(|| self.validation_message()) - { - return f.write_str(message); - } - match self { - Self::MissingSymbol(symbol) => write!(f, "missing CUDA Driver symbol {symbol}"), - Self::InvalidDriverValue(operation) => { - write!(f, "{operation} returned an invalid handle on success") - } - Self::Driver { operation, code } => { - write!(f, "{operation} failed with CUDA code {code}") - } - Self::ShapeMismatch { expected, actual } => { - write!(f, "byte shape mismatch: expected {expected}, got {actual}") - } - Self::GraphOutOfMemory { window: 0 } => { - write!(f, "the verifier commit graph did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)") - } - Self::GraphOutOfMemory { window } => { - write!(f, "the verifier window graph T={window} did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)") - } - Self::Multiple { primary, secondary } => { - write!(f, "{primary}; subsequent error: {secondary}") - } - _ => unreachable!("static errors have a message"), - } - } -} -impl std::error::Error for Error {} -pub type Result = std::result::Result; - -/// Exact whole row-major BF16 matrix and one unchanged F32 input vector. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Bf16ProjectionShape { - pub rows: usize, - pub columns: usize, -} - -fn combine(primary: Result, secondary: Result<()>) -> Result { - match (primary, secondary) { - (Ok(value), Ok(())) => Ok(value), - (Err(error), Ok(())) | (Ok(_), Err(error)) => Err(error), - (Err(primary), Err(secondary)) => Err(Error::Multiple { - primary: Box::new(primary), - secondary: Box::new(secondary), - }), - } -} -fn valid_size(bytes: usize) -> Result<()> { - if bytes == 0 || bytes > isize::MAX as usize { - Err(Error::InvalidSize) - } else { - Ok(()) - } -} - -/// A loaded fixed ABI. No resources can be sent or shared between threads. -pub struct Driver { - api: Rc, - version: i32, -} -impl Driver { - /// Resolve the entire fixed ABI before initializing CUDA. - pub fn load() -> Result { - let api = Rc::new(ffi::Api::load()?); - api.init()?; - let version = api.version()?; - Ok(Self { api, version }) - } - pub fn version(&self) -> i32 { - self.version - } - pub fn device(&self, ordinal: i32) -> Result> { - if ordinal < 0 { - return Err(Error::InvalidOrdinal); - } - Ok(Device { - driver: self, - handle: self.api.device(ordinal)?, - ordinal, - }) - } -} - -/// A device selected through its owner driver, without a public raw handle. -pub struct Device<'driver> { - driver: &'driver Driver, - handle: i32, - ordinal: i32, -} -impl<'driver> Device<'driver> { - pub fn create_context(&self, byte_budget: usize) -> Result> { - valid_size(byte_budget)?; - let api = &self.driver.api; - let handle = api.create(self.handle)?; - let restore = api.pop().and_then(|popped| { - if popped == handle { - Ok(()) - } else { - Err(Error::UnexpectedContext) - } - }); - if let Err(error) = restore { - let cleanup = api.destroy(handle); - if cleanup.is_err() { - // The driver may still own a live context; keep its ABI loaded. - std::mem::forget(Rc::clone(api)); - } - return combine(Err(error), cleanup); - } - Ok(Context { - driver: self.driver, - handle: Some(handle), - ordinal: self.ordinal, - budget: byte_budget, - allocated: Cell::new(0), - poisoned: PoisonCell::new(false), - vector_add_kernel: Cell::new(None), - matvec_kernel: Cell::new(None), - q5_k_kernel: Cell::new(None), - q6_k_kernel: Cell::new(None), - common_quantizer: Cell::new(None), - grouped_iq3: Cell::new(None), - grouped_iq2: Cell::new(None), - grouped_iq3_s: Cell::new(None), - grouped_iq4_xs: Cell::new(None), - grouped_iq3_s_nc4: Cell::new(None), - grouped_iq4_xs_nc4: Cell::new(None), - grouped_swiglu: Cell::new(None), - grouped_down_iq4: Cell::new(None), - grouped_down_q2: Cell::new(None), - gr_read_guard_kernel: Cell::new(None), - projection_kernels: std::array::from_fn(|_| Cell::new(None)), - qwen_kernels: qwen_dispatch::Cache::new(), - kar_levels: Cell::new(None), - experimental: std::array::from_fn(|_| Cell::new(None)), - window_modules: RefCell::new(Vec::new()), - deferred_frees: RefCell::new(Vec::new()), - }) - } -} - -/// A private context with a budget for actual live allocations. - -/// Bring-up diagnostic: a `Cell` that prints the stack of the first `set(true)` when LELEKA_TRACE_POISON is set. -pub(crate) struct PoisonCell(Cell); -impl PoisonCell { - pub(crate) fn new(v: bool) -> Self { Self(Cell::new(v)) } - pub(crate) fn get(&self) -> bool { self.0.get() } - pub(crate) fn set(&self, v: bool) { - if v && !self.0.get() && std::env::var_os("LELEKA_TRACE_POISON").is_some() { - crate::bringup_trace!("DBG context poisoned here: -{}", std::backtrace::Backtrace::force_capture()); - } - self.0.set(v); - } -} - -pub struct Context<'driver> { - driver: &'driver Driver, - handle: Option, - /// Ordinal given to `Driver::device`: the `cudaGetDevice` answer for work - /// issued under this context (MtpDrafter records it at load). - ordinal: i32, - budget: usize, - allocated: Cell, - poisoned: PoisonCell, - vector_add_kernel: Cell>, - matvec_kernel: Cell>, - q5_k_kernel: Cell>, - q6_k_kernel: Cell>, - common_quantizer: Cell>, - grouped_iq3: Cell>, - grouped_iq2: Cell>, - grouped_iq3_s: Cell>, - grouped_iq4_xs: Cell>, - grouped_iq3_s_nc4: Cell>, - grouped_iq4_xs_nc4: Cell>, - grouped_swiglu: Cell>, - grouped_down_iq4: Cell>, - grouped_down_q2: Cell>, - gr_read_guard_kernel: Cell>, - projection_kernels: [Cell>; 8], - qwen_kernels: qwen_dispatch::Cache, - kar_levels: Cell>, - experimental: [Cell>; 6], - /// Sealed verify-window modules loaded under this context, shared by every verifier bank created later - /// (the serve path assembles one per request) and unloaded with the context. - window_modules: RefCell, Vec<&'static str>)>>, - /// Buffers released while a prompt chunk's expert copies are in flight (cuMemFree synchronizes the whole - /// device and would wait for every queued copy): freed by `flush_deferred_frees`. They stay charged. - deferred_frees: RefCell>, -} -#[derive(Clone, Copy)] -struct FixedKernel { - module: ffi::ModuleHandle, - function: ffi::FunctionHandle, -} -#[derive(Clone, Copy)] -struct FixedPairKernels { - module: ffi::ModuleHandle, - quantize: ffi::FunctionHandle, - project: ffi::FunctionHandle, -} - -// Closed selector: callers cannot choose executable bytes, names or geometry. -#[derive(Clone, Copy)] -enum FixedOperation { - VectorAdd, - GrReadFinite, - Matvec, - Q5K, - Q5KQuantize, - Q5KProject, - Q6K, - Q6KQuantize, - Q6KProject, - CommonQuantize, - GroupedIq3, - GroupedIq2, - GroupedIq3S, - GroupedIq4Xs, - GroupedIq3SNc4, - GroupedIq4XsNc4, - GroupedSwiglu, - GroupedDownIq4, - GroupedDownQ2, - Projection(ProjectionKind), -} - -/// Closed ordinary packed matrix formats. No raw executable selector. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[allow(non_camel_case_types)] // Canonical format spellings are the fixed public ABI. -pub enum DenseFormat { - Q8_0, - Q4_K, - IQ4_NL, - IQ4_XS, -} -/// Closed preselected expert formats; output is unweighted. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[allow(non_camel_case_types)] // Canonical format spellings are the fixed public ABI. -pub enum RoutedFormat { - IQ3_XXS, - IQ3_S, - IQ2_S, - IQ4_NL, - IQ4_XS, - Q2_0, -} -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ProjectionKind { - Dense(DenseFormat), - Routed(RoutedFormat), -} -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ProjectionSpec { - pub kind: ProjectionKind, - pub rows: usize, - pub columns: usize, -} - -/// One synchronized native Q8_1 activation for fixed routed Gate/Up projections. -/// The original activation stays immutably borrowed until this owner is closed. -/// Callers must scope this owner to one layer/step, never a weight cache. -pub struct RoutedGateUpQ8<'context> { - activation: &'context DeviceBuffer<'context>, - scratch: Option>, -} -impl RoutedGateUpQ8<'_> { - /// Consume the owner and report its one scratch release attempt. - pub fn close(mut self) -> Result<()> { - self.release() - } - fn release(&mut self) -> Result<()> { - let Some(scratch) = self.scratch.take() else { - return Ok(()); - }; - if scratch.context.poisoned.get() { - // Unknown work retains the allocation and charge until containment - // by context destruction; no free against an uncertain context. - std::mem::forget(scratch); - return Err(Error::ContextPoisoned); - } - scratch.release() - } -} -impl Drop for RoutedGateUpQ8<'_> { - fn drop(&mut self) { - let _ = self.release(); - } -} - -#[derive(Clone, Copy)] -struct ProjectionKernels { - module: ffi::ModuleHandle, - dense: Option, - routed: Option, -} -impl ProjectionKind { - fn layout(self) -> (usize, usize, usize, Option) { - use DenseFormat as D; - use RoutedFormat as R; - match self { - Self::Dense(D::Q8_0) => (0, 32, 34, Some(1024)), - Self::Dense(D::Q4_K) => (1, 256, 144, Some(2048)), - Self::Routed(R::IQ3_XXS) => (2, 256, 98, None), - Self::Routed(R::IQ3_S) => (3, 256, 110, None), - Self::Routed(R::IQ2_S) => (4, 256, 82, None), - Self::Dense(D::IQ4_NL) => (5, 32, 18, Some(2048)), - Self::Routed(R::IQ4_NL) => (5, 32, 18, None), - Self::Dense(D::IQ4_XS) => (6, 256, 136, Some(4096)), - Self::Routed(R::IQ4_XS) => (6, 256, 136, None), - Self::Routed(R::Q2_0) => (7, 64, 18, None), - } - } - fn weight_alignment(self) -> u64 { - // Native Q4_K half2/u32 fields and IQ4_XS qs at offset8 require - // aligned 32-bit loads. The remaining packed blocks use halfwords. - match self { - Self::Dense(DenseFormat::Q4_K | DenseFormat::IQ4_XS) - | Self::Routed(RoutedFormat::IQ4_XS) => 4, - _ => 2, - } - } - fn required_modes(self) -> (Option, Option) { - match self { - Self::Dense(DenseFormat::IQ4_NL) | Self::Routed(RoutedFormat::IQ4_NL) => ( - Some(Self::Dense(DenseFormat::IQ4_NL)), - Some(Self::Routed(RoutedFormat::IQ4_NL)), - ), - Self::Dense(DenseFormat::IQ4_XS) | Self::Routed(RoutedFormat::IQ4_XS) => ( - Some(Self::Dense(DenseFormat::IQ4_XS)), - Some(Self::Routed(RoutedFormat::IQ4_XS)), - ), - Self::Dense(_) => (Some(self), None), - Self::Routed(_) => (None, Some(self)), - } - } -} -#[derive(Debug, PartialEq, Eq)] -struct ProjectionShape { - weight_bytes: usize, - activation_bytes: usize, - output_bytes: usize, - scratch_bytes: usize, - temporary_bytes: usize, - rows: u32, - columns: u32, - quant_grid: u32, - projection_grid: u32, -} - -// The Q4_K PTX forms signed 32-bit packed-byte offsets, including the -// three-row arms of its four-row CTA when N < 2048. Those offsets are -// calculated before per-row guards, so admission must cover the padded -// launch rows, not only the final caller-visible row. -fn q4_k_native_indices_fit(rows: usize, columns: usize) -> bool { - const Q4_K_BLOCK: usize = 256; - const Q4_K_BLOCK_BYTES: usize = 144; - const Q4_K_ROWS_PER_CTA_SMALL: usize = 4; - - if rows == 0 || columns == 0 || !columns.is_multiple_of(Q4_K_BLOCK) { - return false; - } - - let rows_per_cta = if columns < 2048 { - Q4_K_ROWS_PER_CTA_SMALL - } else { - 1 - }; - let last_cta_base_row = match rows - .div_ceil(rows_per_cta) - .checked_sub(1) - .and_then(|index| index.checked_mul(rows_per_cta)) - { - Some(value) => value, - None => return false, - }; - // PTX materializes row, row+1, row+2, and row+3 offsets even for the - // one-row large-N launch; the invalid output arms are only guarded later. - let last_computed_row = match last_cta_base_row.checked_add(3) { - Some(value) if value <= i32::MAX as usize => value, - _ => return false, - }; - let blocks_per_row = columns / Q4_K_BLOCK; - // Each lane group starts at r362=0..7 and advances by eight until its - // index is >= B. The largest final, subsequently unconsumed index is - // B+7; this also covers the single small-N path's common increment. - let loop_advance_blocks = match blocks_per_row.checked_add(7) { - Some(value) => value, - None => return false, - }; - let last_executed_block_offset = match last_computed_row - .checked_mul(blocks_per_row) - .and_then(|row_base| row_base.checked_add(loop_advance_blocks)) - { - Some(value) => value, - None => return false, - }; - let last_signed_byte_offset = match last_executed_block_offset.checked_mul(Q4_K_BLOCK_BYTES) { - Some(value) => value, - None => return false, - }; - last_signed_byte_offset <= i32::MAX as usize -} - -fn projection_shape(spec: ProjectionSpec) -> Result { - let invalid = Error::InvalidProjectionShape; - let (_, block, bytes, small) = spec.kind.layout(); - let (m, n) = (spec.rows, spec.columns); - if m == 0 - || n == 0 - || m > i32::MAX as usize - || n > i32::MAX as usize - || !n.is_multiple_of(block) - || !n.is_multiple_of(32) - { - return Err(invalid); - } - let bounded = |value: Option| -> Result { - let value = value.ok_or(Error::InvalidProjectionShape)?; - valid_size(value).map_err(|_| Error::InvalidProjectionShape)?; - Ok(value) - }; - let weight_bytes = bounded(m.checked_mul(n / block).and_then(|v| v.checked_mul(bytes)))?; - if spec.kind == ProjectionKind::Dense(DenseFormat::Q4_K) && !q4_k_native_indices_fit(m, n) { - return Err(invalid); - } - let activation_bytes = bounded(n.checked_mul(4))?; - let output_bytes = bounded(m.checked_mul(4))?; - let scratch_bytes = bounded((n / 32).checked_mul(36))?; - let temporary_bytes = bounded(scratch_bytes.checked_add(4))?; - let quant_grid = u32::try_from(n.div_ceil(256)).map_err(|_| Error::InvalidProjectionShape)?; - let grid = if small.is_none_or(|limit| n < limit) { - m.div_ceil(4) - } else { - m - }; - let projection_grid = u32::try_from(grid).map_err(|_| Error::InvalidProjectionShape)?; - Ok(ProjectionShape { - weight_bytes, - activation_bytes, - output_bytes, - scratch_bytes, - temporary_bytes, - rows: m as u32, - columns: n as u32, - quant_grid, - projection_grid, - }) -} - -// Pure structural admission shared by production and the private mock caller. -// No availability bypass, Driver call, cache publication or budget mutation. -fn projection_ranges( - kind: ProjectionKind, - shape: &ProjectionShape, - handles: [ffi::BufferHandle; 3], -) -> Result<()> { - for (handle, bytes, alignment) in [ - (handles[0], shape.weight_bytes, kind.weight_alignment()), - (handles[1], shape.activation_bytes, 4), - (handles[2], shape.output_bytes, 4), - ] { - handle.validate_projection_extent(bytes, alignment)?; - } - if handles[2].overlaps(shape.output_bytes, handles[0], shape.weight_bytes) - || handles[2].overlaps(shape.output_bytes, handles[1], shape.activation_bytes) - { - return Err(Error::OutputAliasesInput); - } - Ok(()) -} - -/// Exact one-column Q5_K matrix geometry: `rows × columns` packed weights. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Q5KProjectionShape { - pub rows: usize, - pub columns: usize, -} - -/// Exact one-column Q6_K matrix geometry: `rows × columns` packed weights. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Q6KProjectionShape { - pub rows: usize, - pub columns: usize, -} - -#[derive(Debug, PartialEq, Eq)] -struct Q5KShape { - weight_bytes: usize, - activation_bytes: usize, - output_bytes: usize, - scratch_bytes: usize, - rows: u32, - columns: u32, - quant_grid: u32, - projection_grid: u32, -} - -fn q5_k_shape(rows: usize, columns: usize) -> Result { - if rows == 0 || columns == 0 || !columns.is_multiple_of(256) { - return Err(Error::InvalidQ5KProjectionShape); - } - let rows_abi = u32::try_from(rows).map_err(|_| Error::InvalidQ5KProjectionShape)?; - let columns_abi = u32::try_from(columns).map_err(|_| Error::InvalidQ5KProjectionShape)?; - if rows_abi > i32::MAX as u32 || columns_abi > i32::MAX as u32 { - return Err(Error::InvalidQ5KProjectionShape); - } - let checked_bytes = |elements: usize, width: usize| -> Result { - let bytes = elements - .checked_mul(width) - .ok_or(Error::InvalidQ5KProjectionShape)?; - valid_size(bytes).map_err(|_| Error::InvalidQ5KProjectionShape)?; - Ok(bytes) - }; - let weight_blocks = rows - .checked_mul(columns / 256) - .ok_or(Error::InvalidQ5KProjectionShape)?; - let weight_bytes = checked_bytes(weight_blocks, 176)?; - let activation_bytes = checked_bytes(columns, 4)?; - let output_bytes = checked_bytes(rows, 4)?; - let scratch_bytes = checked_bytes(columns / 32, 36)?; - let quant_grid = columns / 256; - if quant_grid == 0 || quant_grid > i32::MAX as usize { - return Err(Error::InvalidQ5KProjectionShape); - } - let small_k = columns / 256 < 8; - let projection_ctas = if small_k { rows.div_ceil(4) } else { rows }; - if projection_ctas == 0 || projection_ctas > i32::MAX as usize { - return Err(Error::InvalidQ5KProjectionShape); - } - Ok(Q5KShape { - weight_bytes, - activation_bytes, - output_bytes, - scratch_bytes, - rows: rows_abi, - columns: columns_abi, - quant_grid: u32::try_from(quant_grid).map_err(|_| Error::InvalidQ5KProjectionShape)?, - projection_grid: u32::try_from(projection_ctas) - .map_err(|_| Error::InvalidQ5KProjectionShape)?, - }) -} - -#[derive(Debug, PartialEq, Eq)] -struct Q6KShape { - weight_bytes: usize, - activation_bytes: usize, - output_bytes: usize, - scratch_bytes: usize, - rows: u32, - columns: u32, - quant_grid: u32, - projection_grid: u32, -} - -fn q6_k_shape(rows: usize, columns: usize) -> Result { - if rows == 0 || columns == 0 || !columns.is_multiple_of(256) { - return Err(Error::InvalidQ6KProjectionShape); - } - let rows_abi = u32::try_from(rows).map_err(|_| Error::InvalidQ6KProjectionShape)?; - let columns_abi = u32::try_from(columns).map_err(|_| Error::InvalidQ6KProjectionShape)?; - if rows_abi > i32::MAX as u32 || columns_abi > i32::MAX as u32 { - return Err(Error::InvalidQ6KProjectionShape); - } - let checked_bytes = |elements: usize, width: usize| -> Result { - let bytes = elements - .checked_mul(width) - .ok_or(Error::InvalidQ6KProjectionShape)?; - valid_size(bytes).map_err(|_| Error::InvalidQ6KProjectionShape)?; - Ok(bytes) - }; - let weight_blocks = rows - .checked_mul(columns / 256) - .ok_or(Error::InvalidQ6KProjectionShape)?; - let weight_bytes = checked_bytes(weight_blocks, 210)?; - let activation_bytes = checked_bytes(columns, 4)?; - let output_bytes = checked_bytes(rows, 4)?; - let scratch_bytes = checked_bytes(columns / 32, 36)?; - let quant_grid = columns / 256; - if quant_grid == 0 || quant_grid > i32::MAX as usize { - return Err(Error::InvalidQ6KProjectionShape); - } - let small_k = columns / 256 < 4; - let projection_ctas = if small_k { rows.div_ceil(4) } else { rows }; - if projection_ctas == 0 || projection_ctas > i32::MAX as usize { - return Err(Error::InvalidQ6KProjectionShape); - } - Ok(Q6KShape { - weight_bytes, - activation_bytes, - output_bytes, - scratch_bytes, - rows: rows_abi, - columns: columns_abi, - quant_grid: u32::try_from(quant_grid).map_err(|_| Error::InvalidQ6KProjectionShape)?, - projection_grid: u32::try_from(projection_ctas) - .map_err(|_| Error::InvalidQ6KProjectionShape)?, - }) -} - -#[derive(Debug, PartialEq, Eq)] -struct MatvecShape { - matrix_bytes: usize, - vector_bytes: usize, - output_bytes: usize, - rows: u32, - columns: u32, - grid: u32, -} -fn matvec_shape(rows: usize, columns: usize) -> Result { - let rows_abi = u32::try_from(rows).map_err(|_| Error::InvalidMatvecShape)?; - let columns_abi = u32::try_from(columns).map_err(|_| Error::InvalidMatvecShape)?; - let bytes = |elements: Option| -> Result { - let bytes = elements - .and_then(|v| v.checked_mul(4)) - .ok_or(Error::InvalidMatvecShape)?; - valid_size(bytes).map_err(|_| Error::InvalidMatvecShape)?; - Ok(bytes) - }; - let matrix_bytes = bytes(rows.checked_mul(columns))?; - let vector_bytes = bytes(Some(columns))?; - let output_bytes = bytes(Some(rows))?; - let grid = u64::from(rows_abi).div_ceil(128); - if grid == 0 || grid > i32::MAX as u64 { - return Err(Error::InvalidMatvecShape); - } - Ok(MatvecShape { - matrix_bytes, - vector_bytes, - output_bytes, - rows: rows_abi, - columns: columns_abi, - grid: u32::try_from(grid).map_err(|_| Error::InvalidMatvecShape)?, - }) -} - -fn matvec_allocations( - matrix: Option, - vector: Option, - output: Option, - shape: &MatvecShape, -) -> Result<(ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle)> { - let matrix = matrix.ok_or(Error::ContextPoisoned)?; - let vector = vector.ok_or(Error::ContextPoisoned)?; - let output = output.ok_or(Error::ContextPoisoned)?; - if matrix == output || vector == output { - return Err(Error::OutputAliasesInput); - } - matrix.validate_extent(shape.matrix_bytes)?; - vector.validate_extent(shape.vector_bytes)?; - output.validate_extent(shape.output_bytes)?; - Ok((matrix, vector, output)) -} - -// Wider integer arithmetic also covers the final partial block at u32::MAX. -fn vector_shape(bytes: usize) -> Result<(u32, u32)> { - if valid_size(bytes).is_err() || !bytes.is_multiple_of(4) { - return Err(Error::InvalidVectorShape); - } - let count = u32::try_from(bytes / 4).map_err(|_| Error::InvalidVectorShape)?; - let grid = u64::from(count) - .checked_add(127) - .ok_or(Error::InvalidVectorShape)? - / 128; - if grid == 0 || grid > i32::MAX as u64 { - return Err(Error::InvalidVectorShape); - } - Ok(( - count, - u32::try_from(grid).map_err(|_| Error::InvalidVectorShape)?, - )) -} -impl Context<'_> { - /// Private sticky failure primitive shared by native owners. - fn poison(&self) { - self.poisoned.set(true); - } - /// Retain the actual loaded API after uncertain completion/restoration. - fn retain_driver(&self) { - std::mem::forget(Rc::clone(&self.driver.api)); - } - pub fn budget_bytes(&self) -> usize { - self.budget - } - /// The device ordinal this context was created on. - pub fn device_ordinal(&self) -> i32 { - self.ordinal - } - /// Failed frees remain charged until context destruction. - pub fn allocated_bytes(&self) -> usize { - self.allocated.get() - } - /// Actual `(free, total)` physical device bytes for this current Context. - /// This is a snapshot, not a reservation guarantee; it allocates/frees nothing. - /// Zero free is valid, zero total or free above total refuses the query. - pub fn memory_info(&self) -> Result<(usize, usize)> { - let guard = self.enter()?; - let query = self.driver.api.memory_info(); - if matches!(&query, Err(Error::Driver { .. })) { - // CUDA may report an earlier asynchronous failure here. Do not - // admit further resource use under an uncertain execution state. - self.poisoned.set(true); - } - // CurrentGuard verifies the popped identity and poisons on pop failure. - combine(query, guard.finish()) - } - fn enter(&self) -> Result> { - if self.poisoned.get() { - return Err(Error::ContextPoisoned); - } - let handle = self.handle.ok_or(Error::ContextPoisoned)?; - if let Err(error) = self.driver.api.push(handle) { - // A failed current-context transport leaves the execution state - // uncertain. Every owner sharing this Context must refuse reuse. - self.poison(); - self.retain_driver(); - return Err(error); - } - Ok(CurrentGuard { - context: self, - active: true, - }) - } - pub fn allocate(&self, bytes: usize) -> Result> { - valid_size(bytes)?; - let total = self - .allocated - .get() - .checked_add(bytes) - .ok_or(Error::BudgetExceeded)?; - if total > self.budget { - return Err(Error::BudgetExceeded); - } - let guard = self.enter()?; - let allocation = self.driver.api.allocate(bytes); - if allocation.is_ok() { - self.allocated.set(total); - } - // A successful allocation whose pop fails stays charged. The poisoned - // context owns that allocation until destruction, so no unguarded free. - let handle = combine(allocation, guard.finish())?; - vram_ledger::note_alloc(handle.qwen_address(), bytes); - Ok(DeviceBuffer { - context: self, - handle: Some(handle), - bytes, - _thread: PhantomData, - borrowed: false, - }) - } - /// Queue a buffer's release for after the chunk's expert stream (it stays charged until then); when the - /// queued bytes pass `LELEKA_PREFILL_DEFER_FREE_MIB` (512) they are freed at once. - fn defer_free(&self, handle: ffi::BufferHandle, bytes: usize) -> Result<()> { - let pending = { - let mut list = self.deferred_frees.borrow_mut(); - list.push((handle, bytes)); - list.iter().map(|b| b.1).sum::() - }; - static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); - let limit = *LIMIT.get_or_init(|| { - std::env::var("LELEKA_PREFILL_DEFER_FREE_MIB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(512) << 20 - }); - if pending > limit { self.flush_deferred_frees() } else { Ok(()) } - } - /// Free every deferred buffer (one device synchronization). - pub(crate) fn flush_deferred_frees(&self) -> Result<()> { - let list = std::mem::take(&mut *self.deferred_frees.borrow_mut()); - if list.is_empty() { - return Ok(()); - } - let guard = self.enter()?; - let mut result = Ok(()); - for (handle, bytes) in list { - let free = self.driver.api.free(handle); - if free.is_ok() { - self.allocated.set(self.allocated.get() - bytes); - } - result = combine(result, free); - } - combine(result, guard.finish()) - } - /// Read-only sticky completion fence; never resets or changes the context. - pub fn is_poisoned(&self) -> bool { - self.poisoned.get() - } - pub fn synchronize(&self) -> Result<()> { - let guard = self.enter()?; - let sync = self.driver.api.synchronize(); - if sync.is_err() { - self.poisoned.set(true); - } - combine(sync, guard.finish()) - } - /// Copy one complete2560-F32 MoE Down result into its fixed ordered slot. - /// This performs no arithmetic or finite admission; callers retain the - /// actual producer's finite proof. Successful return attests completed copy. - pub fn pack_moe_down_f32( - &self, - source: &DeviceBuffer<'_>, - destination: &mut DeviceBuffer<'_>, - slot: u32, - ) -> Result<()> { - if self.poisoned.get() { - return Err(Error::ContextPoisoned); - } - if !std::ptr::eq(self, source.context) || !std::ptr::eq(self, destination.context) { - return Err(Error::ContextMismatch); - } - if source.bytes != 10_240 || destination.bytes != 102_400 || slot >= 10 { - return Err(Error::InvalidQwenShape); - } - let source = source.handle.ok_or(Error::ContextPoisoned)?; - let destination = destination.handle.ok_or(Error::ContextPoisoned)?; - source.validate_projection_extent(10_240, 4)?; - destination.validate_projection_extent(102_400, 4)?; - if source.overlaps(10_240, destination, 102_400) { - return Err(Error::OutputAliasesInput); - } - let target = destination.moe_down_slot(slot)?; - let guard = match self.enter() { - Ok(guard) => guard, - Err(error) => { - self.poisoned.set(true); - return Err(error); - } - }; - let copy = self.driver.api.copy_moe_down(target, source); - // A failed copy can report earlier work. Always attempt synchronization - // and restore, preserving primary copy→sync→restore error precedence. - let sync = self.driver.api.synchronize(); - let restore = guard.finish(); - if copy.is_err() || sync.is_err() || restore.is_err() { - self.poisoned.set(true); - } - combine(combine(copy, sync), restore) - } - /// Add two exact f32 byte vectors with the fixed trusted kernel. The - /// output is usable as a computed vector only after a successful return. - pub fn vector_add_f32( - &self, - a: &DeviceBuffer<'_>, - b: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - let (handles, count, grid) = self.vector_admission(a, b, output)?; - let [a_handle, b_handle, out_handle] = handles; - // Establish the owned parameter addresses after their stable heap - // placement, before any native mutation. No caller host data is used. - let mut arguments = ffi::LaunchArguments::new(a_handle, b_handle, out_handle, count); - let guard = self.enter()?; - let kernel = match self.fixed_kernel(FixedOperation::VectorAdd) { - Ok(kernel) => kernel, - Err(error) => return combine(Err(error), guard.finish()), - }; - let launch = self - .driver - .api - .launch(kernel.function, grid, &mut arguments); - self.complete_launch(launch, arguments, guard) - } - fn vector_admission( - &self, - a: &DeviceBuffer<'_>, - b: &DeviceBuffer<'_>, - output: &DeviceBuffer<'_>, - ) -> Result<([ffi::BufferHandle; 3], u32, u32)> { - if self.poisoned.get() { - return Err(Error::ContextPoisoned); - } - if !std::ptr::eq(self, a.context) - || !std::ptr::eq(self, b.context) - || !std::ptr::eq(self, output.context) - { - return Err(Error::ContextMismatch); - } - let (count, grid) = vector_shape(a.bytes)?; - if a.bytes != b.bytes || a.bytes != output.bytes { - return Err(Error::InvalidVectorShape); - } - let a_handle = a.handle.ok_or(Error::ContextPoisoned)?; - let b_handle = b.handle.ok_or(Error::ContextPoisoned)?; - let out_handle = output.handle.ok_or(Error::ContextPoisoned)?; - if a_handle == out_handle || b_handle == out_handle { - return Err(Error::OutputAliasesInput); - } - Ok(([a_handle, b_handle, out_handle], count, grid)) - } - fn complete_launch( - &self, - launch: Result<()>, - arguments: T, - guard: CurrentGuard<'_, '_>, - ) -> Result<()> { - // A launch error may describe earlier asynchronous work. Synchronize - // every attempted launch; preserve launch/sync/pop error order. - let sync = self.driver.api.synchronize(); - if sync.is_err() { - self.poisoned.set(true); - } - let restore = guard.finish(); - if restore.is_err() { - self.poisoned.set(true); - } - if sync.is_err() || restore.is_err() { - // Both scalars and their table may still be read. The raw owner - // remains forgotten even if later context destruction succeeds. - std::mem::forget(arguments); - } - combine(combine(launch, sync), restore) - } - /// Compute each row's dot product in ascending column order with separate - /// binary32 multiply/add rounding. All buffers are exact whole allocations; - /// output is usable as a computed vector only after a successful return. - pub fn matvec_f32( - &self, - matrix: &DeviceBuffer<'_>, - vector: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - rows: usize, - columns: usize, - ) -> Result<()> { - let (shape, handles) = self.matvec_admission([matrix, vector, output], rows, columns)?; - let [matrix_handle, vector_handle, output_handle] = handles; - let mut arguments = ffi::MatvecArguments::new( - matrix_handle, - vector_handle, - output_handle, - shape.rows, - shape.columns, - ); - let guard = self.enter()?; - let kernel = match self.fixed_kernel(FixedOperation::Matvec) { - Ok(kernel) => kernel, - Err(error) => return combine(Err(error), guard.finish()), - }; - let launch = self - .driver - .api - .launch_matvec(kernel.function, shape.grid, &mut arguments); - self.complete_launch(launch, arguments, guard) - } - - /// Project one resident F32 activation through row-major Q5_K weights. - /// Activations are quantized using the native Q8_1 block/reduction contract. - pub fn q5_k_q8_1( - &self, - weights: &DeviceBuffer<'_>, - activation: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - shape: Q5KProjectionShape, - ) -> Result<()> { - let (shape, handles, temporary_bytes) = - self.q5_k_admission(weights, activation, output, shape)?; - - // Account the complete worst-case scratch/status requirement before - // the first context push, module load, or allocation. - let total = self - .allocated - .get() - .checked_add(temporary_bytes) - .ok_or(Error::BudgetExceeded)?; - if total > self.budget { - return Err(Error::BudgetExceeded); - } - - let scratch = self.allocate(shape.scratch_bytes)?; - let mut status = match self.allocate(4) { - Ok(status) => status, - Err(error) => { - if self.poisoned.get() { - std::mem::forget(scratch); - return Err(error); - } - return combine(Err(error), scratch.release()); - } - }; - - let operation = (|| { - status.copy_from(&[0; 4])?; - let kernels = { - let guard = self.enter()?; - let kernels = match self.q5_kernels() { - Ok(kernels) => kernels, - Err(error) => return combine(Err(error), guard.finish()), - }; - combine(Ok(kernels), guard.finish())? - }; - - let mut quant_arguments = ffi::Q8QuantizeArguments::new( - handles[1], - scratch.handle.ok_or(Error::ContextPoisoned)?, - status.handle.ok_or(Error::ContextPoisoned)?, - shape.columns, - ); - let quant_guard = self.enter()?; - let quantize = self.driver.api.launch_q8_quantize( - kernels.quantize, - shape.quant_grid, - &mut quant_arguments, - ); - self.complete_launch(quantize, quant_arguments, quant_guard)?; - - let mut native_status = [0u8; 4]; - status.copy_to(&mut native_status)?; - if u32::from_le_bytes(native_status) != 0 { - return Err(Error::InvalidQ8Activation); - } - - let mut project_arguments = ffi::Q5ProjectionArguments::new( - handles[0], - scratch.handle.ok_or(Error::ContextPoisoned)?, - handles[2], - shape.rows, - shape.columns, - ); - let project_guard = self.enter()?; - let project = self.driver.api.launch_q5_projection( - kernels.project, - shape.projection_grid, - &mut project_arguments, - ); - self.complete_launch(project, project_arguments, project_guard) - })(); - - self.release_quantized_temporaries(operation, scratch, status) - } - - /// Project one resident F32 activation through row-major Q6_K weights. - /// Activations use the native Q8_1 block and reduction contract. - pub fn q6_k_q8_1( - &self, - weights: &DeviceBuffer<'_>, - activation: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - dimensions: Q6KProjectionShape, - ) -> Result<()> { - let (shape, handles, temporary_bytes) = - self.q6_k_admission(weights, activation, output, dimensions)?; - - // Charge the complete scratch/status requirement before native mutation. - let total = self - .allocated - .get() - .checked_add(temporary_bytes) - .ok_or(Error::BudgetExceeded)?; - if total > self.budget { - return Err(Error::BudgetExceeded); - } - - let scratch = self.allocate(shape.scratch_bytes)?; - let mut status = match self.allocate(4) { - Ok(status) => status, - Err(error) => { - if self.poisoned.get() { - std::mem::forget(scratch); - return Err(error); - } - return combine(Err(error), scratch.release()); - } - }; - - let operation = (|| { - status.copy_from(&[0; 4])?; - let kernels = { - let guard = self.enter()?; - let kernels = match self.q6_kernels() { - Ok(kernels) => kernels, - Err(error) => return combine(Err(error), guard.finish()), - }; - combine(Ok(kernels), guard.finish())? - }; - - let mut quant_arguments = ffi::Q8QuantizeArguments::new( - handles[1], - scratch.handle.ok_or(Error::ContextPoisoned)?, - status.handle.ok_or(Error::ContextPoisoned)?, - shape.columns, - ); - let quant_guard = self.enter()?; - let quantize = self.driver.api.launch_q8_quantize( - kernels.quantize, - shape.quant_grid, - &mut quant_arguments, - ); - self.complete_launch(quantize, quant_arguments, quant_guard)?; - - let mut native_status = [0u8; 4]; - status.copy_to(&mut native_status)?; - if u32::from_le_bytes(native_status) != 0 { - return Err(Error::InvalidQ8Activation); - } - - let mut project_arguments = ffi::Q6ProjectionArguments::new( - handles[0], - scratch.handle.ok_or(Error::ContextPoisoned)?, - handles[2], - shape.rows, - shape.columns, - ); - let project_guard = self.enter()?; - let project = self.driver.api.launch_q6_projection( - kernels.project, - shape.projection_grid, - &mut project_arguments, - ); - self.complete_launch(project, project_arguments, project_guard) - })(); - - self.release_quantized_temporaries(operation, scratch, status) - } - - /// Project one resident activation using a closed packed format/role. - /// Unintegrated formats refuse before any native mutation. Output is usable - /// only after successful synchronized return, never after a partial failure. - pub fn project_q8_1( - &self, - weights: &DeviceBuffer<'_>, - activation: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - spec: ProjectionSpec, - ) -> Result<()> { - self.project_q8_1_weight(NativeWeights::Raw(weights), activation, output, spec) - } - fn project_q8_1_weight( - &self, - weights: NativeWeights<'_, '_>, - activation: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - spec: ProjectionSpec, - ) -> Result<()> { - let (shape, handles, temporary_bytes) = - self.projection_admission_weight(weights, activation, output, spec)?; - - // Charge the complete scratch/status requirement before native mutation. - let total = self - .allocated - .get() - .checked_add(temporary_bytes) - .ok_or(Error::BudgetExceeded)?; - if total > self.budget { - return Err(Error::BudgetExceeded); - } - - let scratch = self.allocate(shape.scratch_bytes)?; - let mut status = match self.allocate(4) { - Ok(status) => status, - Err(error) => { - if self.poisoned.get() { - std::mem::forget(scratch); - return Err(error); - } - return combine(Err(error), scratch.release()); - } - }; - - let operation = (|| { - status.copy_from(&[0; 4])?; - let kernels = { - let guard = self.enter()?; - let kernels = match self.common_kernels(spec.kind) { - Ok(kernels) => kernels, - Err(error) => return combine(Err(error), guard.finish()), - }; - combine(Ok(kernels), guard.finish())? - }; - - let mut quant_arguments = ffi::Q8QuantizeArguments::new( - handles[1], - scratch.handle.ok_or(Error::ContextPoisoned)?, - status.handle.ok_or(Error::ContextPoisoned)?, - shape.columns, - ); - let quant_guard = self.enter()?; - let quantize = self.driver.api.launch_q8_quantize( - kernels.0, - shape.quant_grid, - &mut quant_arguments, - ); - self.complete_launch(quantize, quant_arguments, quant_guard)?; - - let mut native_status = [0u8; 4]; - status.copy_to(&mut native_status)?; - if u32::from_le_bytes(native_status) != 0 { - return Err(Error::InvalidQ8Activation); - } - - let mut project_arguments = ffi::ProjectionArguments::new( - handles[0], - scratch.handle.ok_or(Error::ContextPoisoned)?, - handles[2], - shape.rows, - shape.columns, - ); - let project_guard = self.enter()?; - let project = self.driver.api.launch_projection( - kernels.1, - shape.projection_grid, - &mut project_arguments, - ); - self.complete_launch(project, project_arguments, project_guard) - })(); - - self.release_quantized_temporaries(operation, scratch, status) - } - - /// Prepare exactly 2560 F32 values with the existing native quantizer. - /// Success attests synchronized completion, restored context and status0. - pub fn prepare_routed_gate_up_q8<'context>( - &'context self, - activation: &'context DeviceBuffer<'context>, - ) -> Result> { - if self.poisoned.get() || self.handle.is_none() { - return Err(Error::ContextPoisoned); - } - if !std::ptr::eq(self, activation.context) { - return Err(Error::ContextMismatch); - } - let source = activation.handle.ok_or(Error::ContextPoisoned)?; - if activation.bytes != 10240 { - return Err(Error::InvalidProjectionShape); - } - source.validate_projection_extent(10240, 4)?; - let total = self - .allocated - .get() - .checked_add(2884) - .ok_or(Error::BudgetExceeded)?; - if total > self.budget { - return Err(Error::BudgetExceeded); - } - let scratch = self.allocate(2880)?; - let mut status = match self.allocate(4) { - Ok(status) => status, - Err(error) => { - if self.poisoned.get() { - std::mem::forget(scratch); - return Err(error); - } - return combine(Err(error), scratch.release()); - } - }; - let operation = (|| { - let quantized = scratch.handle.ok_or(Error::ContextPoisoned)?; - let status_handle = status.handle.ok_or(Error::ContextPoisoned)?; - quantized.validate_projection_extent(2880, 4)?; - status_handle.validate_projection_extent(4, 4)?; - if quantized.overlaps(2880, source, 10240) - || status_handle.overlaps(4, source, 10240) - || status_handle.overlaps(4, quantized, 2880) - { - return Err(Error::OutputAliasesInput); - } - status.copy_from(&[0; 4])?; - let kernel = { - let guard = self.enter()?; - let kernel = match self.fixed_kernel(FixedOperation::CommonQuantize) { - Ok(kernel) => kernel, - Err(error) => return combine(Err(error), guard.finish()), - }; - combine(Ok(kernel), guard.finish())? - }; - let mut arguments = - ffi::Q8QuantizeArguments::new(source, quantized, status_handle, 2560); - let guard = self.enter()?; - let launch = self - .driver - .api - .launch_q8_quantize(kernel.function, 10, &mut arguments); - self.complete_launch(launch, arguments, guard)?; - let mut native_status = [0u8; 4]; - status.copy_to(&mut native_status)?; - if u32::from_le_bytes(native_status) != 0 { - return Err(Error::InvalidQ8Activation); - } - Ok(()) - })(); - if let Err(error) = operation { - return self.release_quantized_temporaries(Err(error), scratch, status); - } - // The status owner must be reclaimed successfully before publishing - // the ready activation. Cleanup failure cannot mint a success owner. - if let Err(error) = status.release() { - if self.poisoned.get() { - std::mem::forget(scratch); - return Err(error); - } - return combine(Err(error), scratch.release()); - } - Ok(RoutedGateUpQ8 { - activation, - scratch: Some(scratch), - }) - } - - /// Project a fixed routed 640x2560 Gate/Up matrix using prepared Q8_1. - /// No activation quantization or temporary device allocation is repeated. - pub fn project_routed_gate_up_prepared( - &self, - weights: &DeviceBuffer<'_>, - prepared: &RoutedGateUpQ8<'_>, - output: &mut DeviceBuffer<'_>, - format: RoutedFormat, - ) -> Result<()> { - self.project_routed_gate_up_prepared_weight( - NativeWeights::Raw(weights), - prepared, - output, - format, - ) - } - fn project_routed_gate_up_prepared_weight( - &self, - weight_owner: NativeWeights<'_, '_>, - prepared: &RoutedGateUpQ8<'_>, - output: &mut DeviceBuffer<'_>, - format: RoutedFormat, - ) -> Result<()> { - let weights = weight_owner.buffer()?; - if self.poisoned.get() || self.handle.is_none() { - return Err(Error::ContextPoisoned); - } - let scratch = prepared.scratch.as_ref().ok_or(Error::ContextPoisoned)?; - for buffer in [weights, prepared.activation, scratch, output] { - if !std::ptr::eq(self, buffer.context) { - return Err(Error::ContextMismatch); - } - if buffer.handle.is_none() { - return Err(Error::ContextPoisoned); - } - } - if !matches!( - format, - RoutedFormat::IQ3_XXS - | RoutedFormat::IQ3_S - | RoutedFormat::IQ2_S - | RoutedFormat::IQ4_XS - ) { - return Err(Error::UnsupportedProjection); - } - let kind = ProjectionKind::Routed(format); - if !ffi::projection_available(kind) { - return Err(Error::UnsupportedProjection); - } - let shape = projection_shape(ProjectionSpec { - kind, - rows: 640, - columns: 2560, - })?; - weight_owner.validate( - ProjectionSpec { - kind, - rows: 640, - columns: 2560, - }, - shape.weight_bytes, - )?; - if prepared.activation.bytes != shape.activation_bytes - || scratch.bytes != shape.scratch_bytes - || output.bytes != shape.output_bytes - { - return Err(Error::InvalidProjectionShape); - } - let weight = weights.handle.ok_or(Error::ContextPoisoned)?; - let original = prepared.activation.handle.ok_or(Error::ContextPoisoned)?; - let quantized = scratch.handle.ok_or(Error::ContextPoisoned)?; - let out = output.handle.ok_or(Error::ContextPoisoned)?; - projection_ranges(kind, &shape, [weight, original, out])?; - if out.overlaps(shape.output_bytes, weight, weights.bytes) { - return Err(Error::OutputAliasesInput); - } - quantized.validate_projection_extent(shape.scratch_bytes, 4)?; - if out.overlaps(shape.output_bytes, quantized, shape.scratch_bytes) { - return Err(Error::OutputAliasesInput); - } - // Private construction used this Context's exact CommonQuantize slot. - // The immutable Context borrow prevents teardown/profile replacement. - if self.common_quantizer.get().is_none() { - return Err(Error::InvalidDriverValue("prepared quantizer cache")); - } - // All device storage is already charged. No unused scratch/status - // precharge is imposed on each prepared projection. - if self.allocated.get() > self.budget { - return Err(Error::BudgetExceeded); - } - let kernel = { - let guard = self.enter()?; - let kernels = match self.common_kernels(kind) { - Ok(kernels) => kernels, - Err(error) => return combine(Err(error), guard.finish()), - }; - combine(Ok(kernels.1), guard.finish())? - }; - let mut arguments = - ffi::ProjectionArguments::new(weight, quantized, out, shape.rows, shape.columns); - let guard = self.enter()?; - let launch = - self.driver - .api - .launch_projection(kernel, shape.projection_grid, &mut arguments); - self.complete_launch(launch, arguments, guard) - } - - fn projection_admission_weight( - &self, - weight_owner: NativeWeights<'_, '_>, - activation: &DeviceBuffer<'_>, - output: &DeviceBuffer<'_>, - spec: ProjectionSpec, - ) -> Result<(ProjectionShape, [ffi::BufferHandle; 3], usize)> { - let weights = weight_owner.buffer()?; - if self.poisoned.get() || self.handle.is_none() { - return Err(Error::ContextPoisoned); - } - for buffer in [weights, activation, output] { - if !std::ptr::eq(self, buffer.context) { - return Err(Error::ContextMismatch); - } - if buffer.handle.is_none() { - return Err(Error::ContextPoisoned); - } - } - if !ffi::projection_available(spec.kind) { - return Err(Error::UnsupportedProjection); - } - let shape = projection_shape(spec)?; - weight_owner.validate(spec, shape.weight_bytes)?; - if activation.bytes != shape.activation_bytes || output.bytes != shape.output_bytes { - return Err(Error::InvalidProjectionShape); - } - let handles = [ - weights.handle.ok_or(Error::ContextPoisoned)?, - activation.handle.ok_or(Error::ContextPoisoned)?, - output.handle.ok_or(Error::ContextPoisoned)?, - ]; - projection_ranges(spec.kind, &shape, handles)?; - if handles[2].overlaps(output.bytes, handles[0], weights.bytes) { - return Err(Error::OutputAliasesInput); - } - let temporary_bytes = shape.temporary_bytes; - let total = self - .allocated - .get() - .checked_add(temporary_bytes) - .ok_or(Error::BudgetExceeded)?; - if total > self.budget { - return Err(Error::BudgetExceeded); - } - Ok((shape, handles, temporary_bytes)) - } - fn q5_k_admission( - &self, - weights: &DeviceBuffer<'_>, - activation: &DeviceBuffer<'_>, - output: &DeviceBuffer<'_>, - dimensions: Q5KProjectionShape, - ) -> Result<(Q5KShape, [ffi::BufferHandle; 3], usize)> { - if self.poisoned.get() || self.handle.is_none() { - return Err(Error::ContextPoisoned); - } - if !std::ptr::eq(self, weights.context) - || !std::ptr::eq(self, activation.context) - || !std::ptr::eq(self, output.context) - { - return Err(Error::ContextMismatch); - } - let shape = q5_k_shape(dimensions.rows, dimensions.columns)?; - if weights.bytes != shape.weight_bytes - || activation.bytes != shape.activation_bytes - || output.bytes != shape.output_bytes - { - return Err(Error::InvalidQ5KProjectionShape); - } - let weight = weights.handle.ok_or(Error::ContextPoisoned)?; - let activation = activation.handle.ok_or(Error::ContextPoisoned)?; - let output = output.handle.ok_or(Error::ContextPoisoned)?; - if output == weight || output == activation { - return Err(Error::OutputAliasesInput); - } - weight - .validate_extent(shape.weight_bytes) - .map_err(|_| Error::InvalidQ5KProjectionShape)?; - activation - .validate_extent(shape.activation_bytes) - .map_err(|_| Error::InvalidQ5KProjectionShape)?; - output - .validate_extent(shape.output_bytes) - .map_err(|_| Error::InvalidQ5KProjectionShape)?; - let temporary_bytes = shape - .scratch_bytes - .checked_add(4) - .ok_or(Error::BudgetExceeded)?; - Ok((shape, [weight, activation, output], temporary_bytes)) - } - - fn q6_k_admission( - &self, - weights: &DeviceBuffer<'_>, - activation: &DeviceBuffer<'_>, - output: &DeviceBuffer<'_>, - dimensions: Q6KProjectionShape, - ) -> Result<(Q6KShape, [ffi::BufferHandle; 3], usize)> { - if self.poisoned.get() || self.handle.is_none() { - return Err(Error::ContextPoisoned); - } - if !std::ptr::eq(self, weights.context) - || !std::ptr::eq(self, activation.context) - || !std::ptr::eq(self, output.context) - { - return Err(Error::ContextMismatch); - } - let shape = q6_k_shape(dimensions.rows, dimensions.columns)?; - if weights.bytes != shape.weight_bytes - || activation.bytes != shape.activation_bytes - || output.bytes != shape.output_bytes - { - return Err(Error::InvalidQ6KProjectionShape); - } - let weight = weights.handle.ok_or(Error::ContextPoisoned)?; - let activation = activation.handle.ok_or(Error::ContextPoisoned)?; - let output = output.handle.ok_or(Error::ContextPoisoned)?; - if output == weight || output == activation { - return Err(Error::OutputAliasesInput); - } - weight - .validate_extent(shape.weight_bytes) - .map_err(|_| Error::InvalidQ6KProjectionShape)?; - activation - .validate_extent(shape.activation_bytes) - .map_err(|_| Error::InvalidQ6KProjectionShape)?; - output - .validate_extent(shape.output_bytes) - .map_err(|_| Error::InvalidQ6KProjectionShape)?; - let temporary_bytes = shape - .scratch_bytes - .checked_add(4) - .ok_or(Error::BudgetExceeded)?; - Ok((shape, [weight, activation, output], temporary_bytes)) - } - - fn release_quantized_temporaries( - &self, - operation: Result, - scratch: DeviceBuffer<'_>, - status: DeviceBuffer<'_>, - ) -> Result { - if self.poisoned.get() { - // Unknown completion/restoration means these allocations and - // their context accounting must outlive this call. - std::mem::forget(scratch); - std::mem::forget(status); - return operation; - } - let status_free = status.release(); - if self.poisoned.get() { - std::mem::forget(scratch); - return combine(operation, status_free); - } - combine(combine(operation, status_free), scratch.release()) - } - fn matvec_admission( - &self, - buffers: [&DeviceBuffer<'_>; 3], - rows: usize, - columns: usize, - ) -> Result<(MatvecShape, [ffi::BufferHandle; 3])> { - let [matrix, vector, output] = buffers; - if self.poisoned.get() || self.handle.is_none() { - return Err(Error::ContextPoisoned); - } - if !std::ptr::eq(self, matrix.context) - || !std::ptr::eq(self, vector.context) - || !std::ptr::eq(self, output.context) - { - return Err(Error::ContextMismatch); - } - let shape = matvec_shape(rows, columns)?; - if matrix.bytes != shape.matrix_bytes - || vector.bytes != shape.vector_bytes - || output.bytes != shape.output_bytes - { - return Err(Error::InvalidMatvecShape); - } - let handles = matvec_allocations(matrix.handle, vector.handle, output.handle, &shape)?; - Ok((shape, [handles.0, handles.1, handles.2])) - } - fn kernel_slot(&self, operation: FixedOperation) -> &Cell> { - match operation { - FixedOperation::VectorAdd => &self.vector_add_kernel, - FixedOperation::GrReadFinite => &self.gr_read_guard_kernel, - FixedOperation::Matvec => &self.matvec_kernel, - FixedOperation::CommonQuantize => &self.common_quantizer, - FixedOperation::GroupedIq3 => &self.grouped_iq3, - FixedOperation::GroupedIq2 => &self.grouped_iq2, - FixedOperation::GroupedIq3S => &self.grouped_iq3_s, - FixedOperation::GroupedIq4Xs => &self.grouped_iq4_xs, - FixedOperation::GroupedIq3SNc4 => &self.grouped_iq3_s_nc4, - FixedOperation::GroupedIq4XsNc4 => &self.grouped_iq4_xs_nc4, - FixedOperation::GroupedSwiglu => &self.grouped_swiglu, - FixedOperation::GroupedDownIq4 => &self.grouped_down_iq4, - FixedOperation::GroupedDownQ2 => &self.grouped_down_q2, - FixedOperation::Projection(_) => { - unreachable!("format modules publish all required entries atomically") - } - FixedOperation::Q5K | FixedOperation::Q5KQuantize | FixedOperation::Q5KProject => { - unreachable!("Q5_K kernels are cached as an atomic pair") - } - FixedOperation::Q6K | FixedOperation::Q6KQuantize | FixedOperation::Q6KProject => { - unreachable!("Q6_K kernels are cached as an atomic pair") - } - } - } - fn fixed_kernel(&self, operation: FixedOperation) -> Result { - let slot = self.kernel_slot(operation); - if let Some(kernel) = slot.get() { - return Ok(kernel); - } - let module = self.driver.api.load_fixed_module(operation)?; - match self.driver.api.fixed_function(module, operation) { - Ok(function) => { - let kernel = FixedKernel { module, function }; - slot.set(Some(kernel)); - Ok(kernel) - } - Err(error) => { - // Local usable handle consumed by this single unload attempt; - // no cache publishes a partial module or retries failed unload. - let cleanup = self.driver.api.unload(module); - if cleanup.is_err() { - self.poisoned.set(true); - std::mem::forget(Rc::clone(&self.driver.api)); - } - combine(Err(error), cleanup) - } - } - } - fn unload_kernel(&self, operation: FixedOperation) -> Result<()> { - // Consume BEFORE attempting unload; even an error can invalidate it. - let Some(kernel) = self.kernel_slot(operation).take() else { - return Ok(()); - }; - if self.poisoned.get() { - // An uncertain context may still own code from this module. - std::mem::forget(Rc::clone(&self.driver.api)); - return Ok(()); - } - let guard = match self.enter() { - Ok(guard) => guard, - Err(error) => { - self.poisoned.set(true); - return Err(error); - } - }; - let unload = self.driver.api.unload(kernel.module); - if unload.is_err() { - self.poisoned.set(true); - } - combine(unload, guard.finish()) - } - fn fixed_pair( - &self, - cache: &Cell>, - module_op: FixedOperation, - quantize_op: FixedOperation, - project_op: FixedOperation, - ) -> Result { - if let Some(kernels) = cache.get() { - return Ok(kernels); - } - let module = self.driver.api.load_fixed_module(module_op)?; - let quantize = match self.driver.api.fixed_function(module, quantize_op) { - Ok(function) => function, - Err(error) => { - let cleanup = self.driver.api.unload(module); - if cleanup.is_err() { - self.poisoned.set(true); - std::mem::forget(Rc::clone(&self.driver.api)); - } - return combine(Err(error), cleanup); - } - }; - let project = match self.driver.api.fixed_function(module, project_op) { - Ok(function) => function, - Err(error) => { - let cleanup = self.driver.api.unload(module); - if cleanup.is_err() { - self.poisoned.set(true); - std::mem::forget(Rc::clone(&self.driver.api)); - } - return combine(Err(error), cleanup); - } - }; - let kernels = FixedPairKernels { - module, - quantize, - project, - }; - // Publish only after both closed fixed entries resolve successfully. - cache.set(Some(kernels)); - Ok(kernels) - } - fn q5_kernels(&self) -> Result { - self.fixed_pair( - &self.q5_k_kernel, - FixedOperation::Q5K, - FixedOperation::Q5KQuantize, - FixedOperation::Q5KProject, - ) - } - fn q6_kernels(&self) -> Result { - self.fixed_pair( - &self.q6_k_kernel, - FixedOperation::Q6K, - FixedOperation::Q6KQuantize, - FixedOperation::Q6KProject, - ) - } - fn unload_pair(&self, cache: &Cell>) -> Result<()> { - let Some(kernels) = cache.take() else { - return Ok(()); - }; - if self.poisoned.get() { - // A failed completion makes module use uncertain; retain the - // Driver library with the intentionally abandoned module handle. - std::mem::forget(Rc::clone(&self.driver.api)); - return Ok(()); - } - let guard = match self.enter() { - Ok(guard) => guard, - Err(error) => { - self.poisoned.set(true); - return Err(error); - } - }; - let unload = self.driver.api.unload(kernels.module); - if unload.is_err() { - self.poisoned.set(true); - std::mem::forget(Rc::clone(&self.driver.api)); - } - combine(unload, guard.finish()) - } - fn common_kernels( - &self, - kind: ProjectionKind, - ) -> Result<(ffi::FunctionHandle, ffi::FunctionHandle)> { - let quantizer = self.fixed_kernel(FixedOperation::CommonQuantize)?; - let slot = &self.projection_kernels[kind.layout().0]; - let kernels = if let Some(kernels) = slot.get() { - kernels - } else { - let module = self - .driver - .api - .load_fixed_module(FixedOperation::Projection(kind))?; - let load = (|| { - let (dense, routed) = kind.required_modes(); - let dense = dense - .map(|k| { - self.driver - .api - .fixed_function(module, FixedOperation::Projection(k)) - }) - .transpose()?; - let routed = routed - .map(|k| { - self.driver - .api - .fixed_function(module, FixedOperation::Projection(k)) - }) - .transpose()?; - Ok(ProjectionKernels { - module, - dense, - routed, - }) - })(); - match load { - Ok(kernels) => { - slot.set(Some(kernels)); - kernels - } - Err(error) => { - let cleanup = self.driver.api.unload(module); - if cleanup.is_err() { - self.poisoned.set(true); - std::mem::forget(Rc::clone(&self.driver.api)); - } - return combine(Err(error), cleanup); - } - } - }; - let project = match kind { - ProjectionKind::Dense(_) => kernels.dense, - ProjectionKind::Routed(_) => kernels.routed, - } - .ok_or(Error::InvalidDriverValue("fixed projection cache"))?; - Ok((quantizer.function, project)) - } - fn unload_projections(&self) -> Result<()> { - let mut result = self.unload_kernel(FixedOperation::CommonQuantize); - if result.is_err() { - std::mem::forget(Rc::clone(&self.driver.api)); - } - for slot in &self.projection_kernels { - let Some(kernels) = slot.take() else { - continue; - }; - if self.poisoned.get() { - std::mem::forget(Rc::clone(&self.driver.api)); - continue; - } - let guard = match self.enter() { - Ok(guard) => guard, - Err(error) => { - self.poisoned.set(true); - std::mem::forget(Rc::clone(&self.driver.api)); - result = combine(result, Err(error)); - continue; - } - }; - let unload = combine(self.driver.api.unload(kernels.module), guard.finish()); - if unload.is_err() { - self.poisoned.set(true); - std::mem::forget(Rc::clone(&self.driver.api)); - } - result = combine(result, unload); - } - result - } - fn unload_q5_kernels(&self) -> Result<()> { - self.unload_pair(&self.q5_k_kernel) - } - fn unload_q6_kernels(&self) -> Result<()> { - self.unload_pair(&self.q6_k_kernel) - } - /// Consume the context and report destruction failure. Borrows prevent - /// closing a context while a device buffer can still be used. - pub fn close(mut self) -> Result<()> { - self.destroy() - } - /// The shared verify-window modules: unloaded (current context) once no bank holds them; a module a live - /// bank still shares is left to that bank's own unload. - fn unload_window_modules(&mut self) -> Result<()> { - let modules = std::mem::take(self.window_modules.get_mut()); - if modules.is_empty() { - return Ok(()); - } - if self.is_poisoned() { - std::mem::forget(modules); - return Err(Error::ContextPoisoned); - } - let guard = self.enter()?; - let mut result = Ok(()); - for (_, module, _) in modules { - if let Ok(module) = Rc::try_unwrap(module) { - result = combine(result, module.close()); - } - } - combine(result, guard.finish()) - } - fn destroy(&mut self) -> Result<()> { - // Fixed teardown order; shared poison suppresses the second native unload. - let grouped_down_unload = combine( - combine( - self.unload_kernel(FixedOperation::GroupedSwiglu), - self.unload_kernel(FixedOperation::GroupedDownIq4), - ), - self.unload_kernel(FixedOperation::GroupedDownQ2), - ); - let unload = combine( - grouped_down_unload, - combine( - combine( - combine( - combine( - combine( - combine( - combine( - self.unload_kernel(FixedOperation::GroupedIq3), - self.unload_kernel(FixedOperation::GroupedIq2), - ), - self.unload_kernel(FixedOperation::GroupedIq3S), - ), - self.unload_kernel(FixedOperation::GroupedIq4Xs), - ), - self.unload_kernel(FixedOperation::GroupedIq3SNc4), - ), - self.unload_kernel(FixedOperation::GroupedIq4XsNc4), - ), - combine( - combine(self.unload_projections(), self.unload_qwen_kernels()), - self.unload_kernel(FixedOperation::GrReadFinite), - ), - ), - combine( - combine( - self.unload_kernel(FixedOperation::VectorAdd), - self.unload_kernel(FixedOperation::Matvec), - ), - combine(self.unload_q5_kernels(), self.unload_q6_kernels()), - ), - ), - ); - let unload = combine(unload, self.unload_kar_levels()); - let unload = combine(unload, self.unload_experimental()); - let unload = combine(unload, self.unload_window_modules()); - if let Some(handle) = self.handle.take() { - // cuCtxDestroy accepts an owned non-current context. Pushing here - // would add a stack entry for a handle invalidated by destruction. - let result = self.driver.api.destroy(handle); - if result.is_err() { - std::mem::forget(Rc::clone(&self.driver.api)); - } - if result.is_ok() { - self.allocated.set(0); - } - combine(unload, result) - } else { - unload - } - } -} -impl Drop for Context<'_> { - fn drop(&mut self) { - let _ = self.destroy(); - } -} - -/// Push/pop balance with fallible explicit finish and nonpanicking fallback. -struct CurrentGuard<'context, 'driver> { - context: &'context Context<'driver>, - active: bool, -} -impl CurrentGuard<'_, '_> { - fn finish(mut self) -> Result<()> { - self.restore() - } - fn restore(&mut self) -> Result<()> { - if !self.active { - return Ok(()); - } - self.active = false; - let result = self.context.driver.api.pop().and_then(|popped| { - if Some(popped) == self.context.handle { - Ok(()) - } else { - Err(Error::UnexpectedContext) - } - }); - if result.is_err() { - self.context.poisoned.set(true); - } - result - } -} -impl Drop for CurrentGuard<'_, '_> { - fn drop(&mut self) { - let _ = self.restore(); - } -} - -/// An exact nonempty byte allocation borrowing its owning context. -pub struct DeviceBuffer<'context> { - context: &'context Context<'context>, - handle: Option, - bytes: usize, - _thread: PhantomData>, - /// A non-owning alias of memory somebody else owns (a sub-range of a slab, mapped host memory): dropping or releasing it - /// frees nothing and is never charged to the context. Its owner must outlive every use. - borrowed: bool, -} -impl DeviceBuffer<'_> { - pub fn len(&self) -> usize { - self.bytes - } - pub fn is_empty(&self) -> bool { - false - } - fn staging(&self, actual: usize) -> Result> { - if actual != self.bytes { - return Err(Error::ShapeMismatch { - expected: self.bytes, - actual, - }); - } - if self.context.poisoned.get() { - return Err(Error::ContextPoisoned); - } - let mut staging = Vec::new(); - staging - .try_reserve_exact(self.bytes) - .map_err(|_| Error::HostAllocation)?; - staging.resize(self.bytes, 0); - Ok(staging) - } - pub fn copy_from(&mut self, input: &[u8]) -> Result<()> { - let mut staging = self.staging(input.len())?; - staging.copy_from_slice(input); - self.copy_staged(staging, false).map(|_| ()) - } - /// Consume genuine whole-buffer host staging without an intermediate clone. - /// Byte ownership is not a source, finite or device-completion certificate. - pub fn copy_from_owned(&mut self, input: Vec) -> Result<()> { - // Preserve the original staging() shape-before-poison admission order. - if input.len() != self.bytes { - return Err(Error::ShapeMismatch { - expected: self.bytes, - actual: input.len(), - }); - } - if self.context.poisoned.get() { - return Err(Error::ContextPoisoned); - } - // Exactly the existing attempted-copy/synchronize/restore and retained - // staging rule. No source storage is released while work is uncertain. - self.copy_staged(input, false).map(|_| ()) - } - /// Copy a nonempty checked subspan. Owned staging remains alive through - /// synchronization, with the same poisoning/leak rule as whole-buffer copies. - pub fn copy_from_range(&mut self, offset: usize, input: &[u8]) -> Result<()> { - self.copy_from_range_shared(offset, input) - } - /// The same transfer through a shared borrow, for arenas their single - /// owner thread shares between read-only views (`Rc`). - /// Ranges are checked and the copy is synchronised exactly like - /// `copy_from_range`; callers keep writes to disjoint spans. - pub(crate) fn copy_from_range_shared(&self, offset: usize, input: &[u8]) -> Result<()> { - if self.context.poisoned.get() { - return Err(Error::ContextPoisoned); - } - let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan( - self.bytes, - offset, - input.len(), - )?; - let mut staging = Vec::new(); - staging - .try_reserve_exact(input.len()) - .map_err(|_| Error::HostAllocation)?; - staging.extend_from_slice(input); - let guard = self.context.enter()?; - let copy = self.context.driver.api.copy_from(handle, &staging); - let sync = self.context.driver.api.synchronize(); - if sync.is_err() { - self.context.poisoned.set(true); - std::mem::forget(staging); - return combine(combine(copy, sync), guard.finish()); - } - combine(copy, guard.finish()) - } - /// Read back a nonempty checked subspan. Owned staging stays alive through - /// synchronization with the same poisoning/leak rule as whole-buffer reads; - /// a failed synchronization never returns its bytes. - pub fn copy_to_range(&self, offset: usize, output: &mut [u8]) -> Result<()> { - if self.context.poisoned.get() { - return Err(Error::ContextPoisoned); - } - let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan( - self.bytes, - offset, - output.len(), - )?; - let mut staging = Vec::new(); - staging - .try_reserve_exact(output.len()) - .map_err(|_| Error::HostAllocation)?; - staging.resize(output.len(), 0); - let guard = self.context.enter()?; - let copy = self.context.driver.api.copy_to(handle, &mut staging); - let sync = self.context.driver.api.synchronize(); - if sync.is_err() { - self.context.poisoned.set(true); - std::mem::forget(staging); - return combine(combine(copy, sync), guard.finish()); - } - combine(copy, guard.finish())?; - output.copy_from_slice(&staging); - Ok(()) - } - pub fn copy_to(&self, output: &mut [u8]) -> Result<()> { - let staging = self.staging(output.len())?; - let staging = self.copy_staged(staging, true)?; - output.copy_from_slice(&staging); - Ok(()) - } - /// Return the completed whole-buffer readback without a second host copy. - /// The staging remains owned through the same synchronization and poison - /// handling as `copy_to`; a failed synchronization never returns its bytes. - pub fn copy_to_owned(&self, expected_bytes: usize) -> Result> { - let staging = self.staging(expected_bytes)?; - self.copy_staged(staging, true) - } - fn copy_staged(&self, mut staging: Vec, to_host: bool) -> Result> { - let handle = self.handle.ok_or(Error::ContextPoisoned)?; - let guard = self.context.enter()?; - let copy = if to_host { - self.context.driver.api.copy_to(handle, &mut staging) - } else { - self.context.driver.api.copy_from(handle, &staging) - }; - // Even copy errors can report earlier asynchronous work. Synchronize - // on every attempted copy before considering the staging reclaimable. - let sync = self.context.driver.api.synchronize(); - if sync.is_err() { - self.context.poisoned.set(true); - // CUDA may still reference these owned host bytes. A poisoned - // context admits no further copy, limiting this leak to one buffer - // (at most its context budget), regardless of caller lifetimes. - std::mem::forget(staging); - return combine(combine(copy, sync), guard.finish()).map(|()| Vec::new()); - } - combine(copy, guard.finish())?; - Ok(staging) - } - pub fn release(mut self) -> Result<()> { - self.free() - } - fn free(&mut self) -> Result<()> { - let Some(handle) = self.handle.take() else { - return Ok(()); - }; - if self.borrowed { - return Ok(()); - } - vram_ledger::note_free(handle.qwen_address()); - if compute_drain::background() != 0 && !self.context.poisoned.get() { - // a chunk expert stream is in flight: do not synchronize the device now - return self.context.defer_free(handle, self.bytes); - } - let guard = self.context.enter()?; - let free = self.context.driver.api.free(handle); - if free.is_ok() { - self.context - .allocated - .set(self.context.allocated.get() - self.bytes); - } - combine(free, guard.finish()) - } -} -impl Drop for DeviceBuffer<'_> { - fn drop(&mut self) { - let _ = self.free(); - } -} - -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[path = "moe_down_pack_gpu.rs"] -mod moe_down_pack_gpu_tests; - -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[path = "ple_value_full_gpu.rs"] -mod ple_value_full_gpu_tests; - -#[cfg(test)] -mod tests { - #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - #[test] - #[ignore = "Root-only original-first owned whole-buffer readback proof"] - fn owned_readback_original_first_preserves_gdn_extents_and_raw_words() { - let driver = super::Driver::load().unwrap(); - let context = driver - .device(0) - .unwrap() - .create_context(16 * 1024 * 1024) - .unwrap(); - let mut exact_bytes = 0usize; - let mut bounds = 0usize; - // Full real recurrence state, convolution history and readout extents. - for size in [3_145_728usize, 122_880, 24_576] { - let mut buffer = context.allocate(size).unwrap(); - for round in 0..2u32 { - let words = [ - 0u32, - 0x8000_0000, - 0x3f80_0000, - 0xbf80_0000, - 0x7f80_0000, - 0xff80_0000, - 0x7fc0_0101, - 1, - ]; - let mut source = Vec::with_capacity(size); - for i in 0..size / 4 { - let word = if i < words.len() { - words[i] - } else { - (i as u32).wrapping_mul(0x9e37_79b9).wrapping_add(round) - }; - source.extend_from_slice(&word.to_le_bytes()); - } - buffer.copy_from(&source).unwrap(); - let mut original = vec![0; size]; - buffer.copy_to(&mut original).unwrap(); - assert_eq!(original, source); - let owned = buffer.copy_to_owned(size).unwrap(); - assert_eq!(owned, original); - // The downstream original LE conversion preserves all bits, - // including signed zero and nonfinite values (later rejected - // by the unchanged GDN finite guard). - for (a, b) in original - .as_chunks::<4>() - .0 - .iter() - .zip(owned.as_chunks::<4>().0) - { - assert_eq!( - f32::from_le_bytes(*a).to_bits(), - f32::from_le_bytes(*b).to_bits() - ); - } - exact_bytes += size; - for invalid in [0, size - 1, size + 1] { - assert!(matches!(buffer.copy_to_owned(invalid), - Err(super::Error::ShapeMismatch { expected, actual }) - if expected == size && actual == invalid)); - bounds += 1; - } - assert_eq!(buffer.copy_to_owned(size).unwrap(), original); - exact_bytes += size; - } - buffer.release().unwrap(); - assert_eq!(context.allocated_bytes(), 0); - } - assert_eq!(exact_bytes, 13_172_736); - assert_eq!(bounds, 18); - assert_eq!(context.allocated_bytes(), 0); - context.close().unwrap(); - println!( - "owned_gdn_readback exact_bytes={exact_bytes} bounds={bounds} original_first=true allocated=0 raw_nonfinite_preserved=true" - ); - } - - #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - #[test] - #[ignore = "Root-only installed driver partial-copy guard proof"] - fn checked_subspan_real_copy_preserves_untouched_bytes() { - let driver = super::Driver::load().unwrap(); - let context = driver.device(0).unwrap().create_context(65536).unwrap(); - let mut buffer = context.allocate(1024).unwrap(); - buffer.copy_from(&[0x5a; 1024]).unwrap(); - buffer.copy_from_range(255, &[0x73; 513]).unwrap(); - let mut out = [0; 1024]; - buffer.copy_to(&mut out).unwrap(); - assert_eq!(&out[..255], &[0x5a; 255]); - assert_eq!(&out[255..768], &[0x73; 513]); - assert_eq!(&out[768..], &[0x5a; 256]); - assert!(buffer.copy_from_range(1023, &[1, 2]).is_err()); - assert!(buffer.copy_from_range(0, &[]).is_err()); - let mut after = [0; 1024]; - buffer.copy_to(&mut after).unwrap(); - assert_eq!(out, after); - buffer.release().unwrap(); - assert_eq!(context.allocated_bytes(), 0); - context.close().unwrap(); - } - - use super::*; - #[test] - fn sizes_and_error_composition() { - assert_eq!(valid_size(0), Err(Error::InvalidSize)); - assert_eq!(valid_size(usize::MAX), Err(Error::InvalidSize)); - assert_eq!(valid_size(1), Ok(())); - assert_eq!( - combine::<()>(Err(Error::InvalidSize), Err(Error::UnexpectedContext)), - Err(Error::Multiple { - primary: Box::new(Error::InvalidSize), - secondary: Box::new(Error::UnexpectedContext) - }) - ); - } - #[test] - fn vector_count_geometry_boundaries() { - for bytes in [0, 1, 3, 5, usize::MAX] { - assert!(vector_shape(bytes).is_err()); - } - for n in [1u32, 127, 128, 129, 1025, u32::MAX] { - let bytes = usize::try_from(u64::from(n) * 4).unwrap(); - assert_eq!( - vector_shape(bytes), - Ok((n, u32::try_from(u64::from(n).div_ceil(128)).unwrap())) - ); - } - assert!(vector_shape((u32::MAX as usize + 1) * 4).is_err()); - } - #[test] - fn matvec_shape_boundaries() { - for (m, n) in [ - (0, 1), - (1, 0), - (usize::MAX, 1), - (1, usize::MAX), - (u32::MAX as usize + 1, 1), - (1, u32::MAX as usize + 1), - (u32::MAX as usize, u32::MAX as usize), - ] { - assert_eq!(matvec_shape(m, n), Err(Error::InvalidMatvecShape)); - } - for m in [1u32, 127, 128, 129, 1025, u32::MAX] { - let shape = matvec_shape(m as usize, 1).unwrap(); - assert_eq!(shape.rows, m); - assert_eq!(shape.matrix_bytes, m as usize * 4); - assert_eq!(shape.output_bytes, m as usize * 4); - assert_eq!(shape.grid as u64, u64::from(m).div_ceil(128)); - } - let shape = matvec_shape(1, u32::MAX as usize).unwrap(); - assert_eq!(shape.columns, u32::MAX); - assert_eq!(shape.vector_bytes, u32::MAX as usize * 4); - let largest_columns = (isize::MAX as usize / 4) / u32::MAX as usize; - assert!(matvec_shape(u32::MAX as usize, largest_columns).is_ok()); - assert_eq!( - matvec_shape(u32::MAX as usize, largest_columns + 1), - Err(Error::InvalidMatvecShape) - ); - // Element count is deliberately not restricted to u32. - assert!(matvec_shape(65536, 65536).is_ok()); - } - #[test] - fn matvec_allocation_identity_and_absent_handles() { - let shape = matvec_shape(1, 1).unwrap(); - let h = |v| Some(ffi::BufferHandle::synthetic(v)); - for handles in [(h(4), h(8), h(4)), (h(4), h(8), h(8))] { - assert!(matches!( - matvec_allocations(handles.0, handles.1, handles.2, &shape), - Err(Error::OutputAliasesInput) - )); - } - for handles in [(None, h(8), h(12)), (h(4), None, h(12)), (h(4), h(8), None)] { - assert!(matches!( - matvec_allocations(handles.0, handles.1, handles.2, &shape), - Err(Error::ContextPoisoned) - )); - } - for handles in [ - (h(u64::MAX - 3), h(8), h(12)), - (h(4), h(u64::MAX - 3), h(12)), - (h(4), h(8), h(u64::MAX - 3)), - ] { - assert!(matches!( - matvec_allocations(handles.0, handles.1, handles.2, &shape), - Err(Error::InvalidMatvecShape) - )); - } - assert!(matvec_allocations(h(4), h(4), h(12), &shape).is_ok()); - } - #[cfg(not(feature = "cuda-driver"))] - #[test] - fn matvec_private_admission_refuses_without_cuda() { - let driver = Driver { - api: Rc::new(ffi::Api), - version: 0, - }; - let context = Context { - driver: &driver, - handle: None, - ordinal: 0, - budget: 64, - allocated: Cell::new(12), - poisoned: PoisonCell::new(false), - vector_add_kernel: Cell::new(None), - matvec_kernel: Cell::new(None), - q5_k_kernel: Cell::new(None), - q6_k_kernel: Cell::new(None), - common_quantizer: Cell::new(None), - grouped_iq3: Cell::new(None), - grouped_iq2: Cell::new(None), - grouped_iq3_s: Cell::new(None), - grouped_iq4_xs: Cell::new(None), - grouped_iq3_s_nc4: Cell::new(None), - grouped_iq4_xs_nc4: Cell::new(None), - grouped_swiglu: Cell::new(None), - grouped_down_iq4: Cell::new(None), - grouped_down_q2: Cell::new(None), - gr_read_guard_kernel: Cell::new(None), - projection_kernels: std::array::from_fn(|_| Cell::new(None)), - qwen_kernels: qwen_dispatch::Cache::new(), - kar_levels: Cell::new(None), - experimental: std::array::from_fn(|_| Cell::new(None)), - window_modules: RefCell::new(Vec::new()), - deferred_frees: RefCell::new(Vec::new()), - }; - let make = |handle| DeviceBuffer { - context: &context, - handle, - bytes: 4, - _thread: PhantomData, - borrowed: false, - }; - let matrix = make(Some(ffi::BufferHandle::synthetic(4))); - let vector = make(Some(ffi::BufferHandle::synthetic(8))); - let mut output = make(Some(ffi::BufferHandle::synthetic(12))); - assert_eq!( - context.matvec_f32(&matrix, &vector, &mut output, 1, 1), - Err(Error::ContextPoisoned) - ); - // No native context exists in this test. Pure allocation identity and - // extent instruments supply the remaining impossible-safe-call cases. - assert_eq!(context.allocated_bytes(), 12); - assert!(context.matvec_kernel.get().is_none()); - } - #[cfg(not(feature = "cuda-driver"))] - #[test] - fn default_load_rejects_before_driver_use() { - assert!(matches!(Driver::load(), Err(Error::Disabled))); - } - #[cfg(all( - feature = "cuda-driver", - not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")) - ))] - #[test] - fn unsupported_load_rejects_before_driver_use() { - assert!(matches!(Driver::load(), Err(Error::UnsupportedPlatform))); - } -} - -#[cfg(test)] -#[path = "../tests/projection_family_oracle.rs"] -mod family_expectations; -#[cfg(test)] -mod family_tests { - use super::*; - const KINDS: [ProjectionKind; 10] = [ - ProjectionKind::Dense(DenseFormat::Q8_0), - ProjectionKind::Dense(DenseFormat::Q4_K), - ProjectionKind::Routed(RoutedFormat::IQ3_XXS), - ProjectionKind::Routed(RoutedFormat::IQ3_S), - ProjectionKind::Routed(RoutedFormat::IQ2_S), - ProjectionKind::Dense(DenseFormat::IQ4_NL), - ProjectionKind::Routed(RoutedFormat::IQ4_NL), - ProjectionKind::Dense(DenseFormat::IQ4_XS), - ProjectionKind::Routed(RoutedFormat::IQ4_XS), - ProjectionKind::Routed(RoutedFormat::Q2_0), - ]; - #[test] - fn common_checked_geometry_matches_frozen_native_layouts() { - for (kind, index) in KINDS.into_iter().zip([0, 1, 2, 3, 4, 5, 5, 6, 6, 7]) { - let shape = projection_shape(ProjectionSpec { - kind, - rows: 5, - columns: 256, - }) - .unwrap(); - assert_eq!( - shape.weight_bytes, - 5 * (256 / family_expectations::LAYOUTS[index].0) - * family_expectations::LAYOUTS[index].1 - ); - assert_eq!( - ( - shape.activation_bytes, - shape.output_bytes, - shape.scratch_bytes, - shape.temporary_bytes - ), - (1024, 20, 288, 292) - ); - } - for (n, bytes, grid) in family_expectations::TAILS { - let shape = projection_shape(ProjectionSpec { - kind: KINDS[0], - rows: 5, - columns: n, - }) - .unwrap(); - assert_eq!( - (shape.scratch_bytes, shape.quant_grid, shape.projection_grid), - (bytes, grid as u32, 2) - ); - } - for (kind, limit) in [ - (KINDS[0], 1024), - (KINDS[1], 2048), - (KINDS[5], 2048), - (KINDS[7], 4096), - ] { - for (n, grid) in [(limit - 256, 2), (limit, 5), (limit + 256, 5)] { - assert_eq!( - projection_shape(ProjectionSpec { - kind, - rows: 5, - columns: n - }) - .unwrap() - .projection_grid, - grid - ); - } - } - for kind in [KINDS[2], KINDS[3], KINDS[4], KINDS[6], KINDS[8], KINDS[9]] { - assert_eq!( - projection_shape(ProjectionSpec { - kind, - rows: 5, - columns: 6144 - }) - .unwrap() - .projection_grid, - 2 - ); - } - } - #[test] - fn common_invalid_shapes_have_fixed_errors() { - for kind in KINDS { - for (m, n) in [ - (0, 256), - (1, 0), - (1, 31), - (1, 33), - (usize::MAX, 256), - (1, usize::MAX), - (i32::MAX as usize + 1, 256), - ] { - assert_eq!( - projection_shape(ProjectionSpec { - kind, - rows: m, - columns: n - }), - Err(Error::InvalidProjectionShape) - ); - } - } - assert_eq!( - projection_shape(ProjectionSpec { - kind: KINDS[1], - rows: 1, - columns: 32 - }), - Err(Error::InvalidProjectionShape) - ); - } - - #[test] - fn q4_k_admission_bounds_every_padded_cta_byte_offset() { - // At N=256 the kernel launches four output rows per CTA and computes - // all four row-arm offsets before guarding the final partial CTA. - // The largest admitted padded row count therefore stays on a four - // row boundary and its post-loop signed offset fits i32. - const BLOCK_BYTES: usize = 144; - const ROWS_PER_CTA: usize = 4; - let max_block_index = i32::MAX as usize / BLOCK_BYTES; - // Include the common final +8-block PTX increment after the last - // iteration, then round the small-N four-row CTA down to its boundary. - let max_padded_rows = - ((max_block_index.saturating_sub(7) / ROWS_PER_CTA) * ROWS_PER_CTA).max(ROWS_PER_CTA); - let at_limit_offset = (max_padded_rows + 7) * BLOCK_BYTES; - assert!(at_limit_offset <= i32::MAX as usize); - assert!(q4_k_native_indices_fit(max_padded_rows - ROWS_PER_CTA, 256)); - assert!(q4_k_native_indices_fit(max_padded_rows, 256)); - assert!(!q4_k_native_indices_fit(max_padded_rows + 1, 256)); - assert!( - projection_shape(ProjectionSpec { - kind: ProjectionKind::Dense(DenseFormat::Q4_K), - rows: max_padded_rows, - columns: 256, - }) - .is_ok() - ); - - // The large-N launch uses one CTA per row but still materializes - // row+1 through row+3 and the final offsets of all eight lane groups. - let blocks_per_row = 2048 / 256; - let max_large_n_rows = ((max_block_index - (blocks_per_row + 7)) / blocks_per_row) - 2; - assert!(q4_k_native_indices_fit(max_large_n_rows - 1, 2048)); - assert!(q4_k_native_indices_fit(max_large_n_rows, 2048)); - assert!(!q4_k_native_indices_fit(max_large_n_rows + 1, 2048)); - assert!( - projection_shape(ProjectionSpec { - kind: ProjectionKind::Dense(DenseFormat::Q4_K), - rows: max_large_n_rows, - columns: 2048, - }) - .is_ok() - ); - assert_eq!( - projection_shape(ProjectionSpec { - kind: ProjectionKind::Dense(DenseFormat::Q4_K), - rows: max_large_n_rows + 1, - columns: 2048, - }), - Err(Error::InvalidProjectionShape) - ); - - // N=2304 has nine blocks: lane group 0 visits 0 and 8 then reaches - // 16, the maximum final index across groups 0..7. - let blocks_per_row: usize = 2304 / 256; - let final_loop_index = blocks_per_row + 7; - assert_eq!(final_loop_index, 16); - let max_nonwrapping_rows = ((max_block_index - final_loop_index) / blocks_per_row) - 2; - assert!(q4_k_native_indices_fit(max_nonwrapping_rows, 2304)); - assert!(!q4_k_native_indices_fit(max_nonwrapping_rows + 1, 2304)); - - // For sixteen blocks, lane group 7 visits block 15 and increments to - // 23; checking only the block-zero loop would miss this signed offset. - let blocks_per_row: usize = 4096 / 256; - let final_loop_index = blocks_per_row + 7; - assert_eq!(final_loop_index, 23); - let max_nonwrapping_rows = ((max_block_index - final_loop_index) / blocks_per_row) - 2; - assert!(q4_k_native_indices_fit(max_nonwrapping_rows, 4096)); - assert!(!q4_k_native_indices_fit(max_nonwrapping_rows + 1, 4096)); - - // The independent QA counterexample and its adjacent valid-row - // boundary are rejected before any context, cache, or allocation work. - for rows in [14_913_081, 14_913_082] { - assert!(!q4_k_native_indices_fit(rows, 256)); - assert_eq!( - projection_shape(ProjectionSpec { - kind: ProjectionKind::Dense(DenseFormat::Q4_K), - rows, - columns: 256, - }), - Err(Error::InvalidProjectionShape) - ); - } - - // With one row, a large N may have a large total extent while every - // native signed packed-byte base remains representable. This case is - // structural only and deliberately allocates no host or device data. - let large_n = 256 * 3_000_000; - assert!(q4_k_native_indices_fit(1, large_n)); - assert!( - projection_shape(ProjectionSpec { - kind: ProjectionKind::Dense(DenseFormat::Q4_K), - rows: 1, - columns: large_n, - }) - .is_ok() - ); - - // Positive individually-valid M and N still refuse when their Q4_K - // row/block product would overflow the native signed byte offset. - let max_i32_n = (i32::MAX as usize / 256) * 256; - assert!(!q4_k_native_indices_fit(2, max_i32_n)); - assert_eq!( - projection_shape(ProjectionSpec { - kind: ProjectionKind::Dense(DenseFormat::Q4_K), - rows: 2, - columns: max_i32_n, - }), - Err(Error::InvalidProjectionShape) - ); - } - - #[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" - ))] - #[test] - #[ignore = "private quantizer transport only; isolated CPU mock, not GPU math"] - fn family_quantizer_transport_child() { - assert_eq!( - std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), - Ok("1") - ); - let n: usize = std::env::var("LELEKA_FAMILY_N").unwrap().parse().unwrap(); - let driver = Driver::load().unwrap(); - let context = driver.device(0).unwrap().create_context(8192).unwrap(); - let trace_path = std::env::var("MOCK_CUDA_TRACE").unwrap(); - let before = std::fs::read(&trace_path).unwrap(); - for (kind, alignment) in KINDS.into_iter().zip([2, 4, 2, 2, 2, 2, 2, 4, 4, 2]) { - let shape = projection_shape(ProjectionSpec { - kind, - rows: 1, - columns: 256, - }) - .unwrap(); - let addresses = [ - ffi::BufferHandle::synthetic(2), - ffi::BufferHandle::synthetic(4096), - ffi::BufferHandle::synthetic(8192), - ]; - assert_eq!( - projection_ranges(kind, &shape, addresses), - if alignment == 4 { - Err(Error::InvalidProjectionShape) - } else { - Ok(()) - } - ); - assert_eq!(std::fs::read(&trace_path).unwrap(), before); - assert_eq!(context.allocated_bytes(), 0); - assert!(context.common_quantizer.get().is_none()); - assert!( - context - .projection_kernels - .iter() - .all(|slot| slot.get().is_none()) - ); - } - let mut input = context.allocate(4 * n).unwrap(); - input.copy_from(&vec![0; 4 * n]).unwrap(); - let scratch = context.allocate(n / 32 * 36).unwrap(); - let mut status = context.allocate(4).unwrap(); - let operation = (|| { - status.copy_from(&[0; 4])?; - let guard = context.enter()?; - let kernel = match context.fixed_kernel(FixedOperation::CommonQuantize) { - Ok(k) => k, - Err(e) => return combine(Err(e), guard.finish()), - }; - combine(Ok(()), guard.finish())?; - let mut args = ffi::Q8QuantizeArguments::new( - input.handle.unwrap(), - scratch.handle.unwrap(), - status.handle.unwrap(), - n as u32, - ); - let guard = context.enter()?; - let launch = context.driver.api.launch_q8_quantize( - kernel.function, - n.div_ceil(256) as u32, - &mut args, - ); - context.complete_launch(launch, args, guard)?; - let mut bytes = [0; 4]; - status.copy_to(&mut bytes)?; - let expected = std::env::var("MOCK_FAMILY_STATUS") - .unwrap_or_else(|_| "0".into()) - .parse::() - .unwrap(); - assert_eq!(u32::from_le_bytes(bytes), expected); - Ok(()) - })(); - let result = context.release_quantized_temporaries(operation, scratch, status); - let failure = std::env::var("LELEKA_FAMILY_EXPECT_FAILURE").as_deref() == Ok("1"); - assert_eq!(result.is_err(), failure, "result={result:?}"); - let base = std::env::var("MOCK_CUDA_FAIL").unwrap_or_default(); - let family = std::env::var("MOCK_CUDA_FAMILY_FAIL").unwrap_or_default(); - let expected_charge = if family.contains("quant_sync") - || family.contains("quant_restore") - || base == "lookup:1,unload:1" - { - 4 * n + n / 32 * 36 + 4 - } else if base == "free:1" { - 4 * n + 4 - } else if base == "free:2" { - 4 * n + n / 32 * 36 - } else { - 4 * n - }; - assert_eq!(context.allocated_bytes(), expected_charge); - if family == "quant_launch,quant_sync,quant_restore" { - let error = format!("{result:?}"); - let launch = error.find("cuLaunchKernel").unwrap(); - let sync = error.find("cuCtxSynchronize").unwrap(); - let restore = error.find("cuCtxPopCurrent_v2").unwrap(); - assert!(launch < sync && sync < restore); - } - drop(input); - let close = context.close(); - let close_failure = std::env::var("LELEKA_FAMILY_CLOSE_FAILURE").as_deref() == Ok("1"); - if close_failure { - assert!(close.is_err()); - } else if !failure { - close.unwrap(); - } - } -} - -// Isolated preview only; absent from the serving qualification map. -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] -pub mod q6_layer_preview; - -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] -pub use qwen_dispatch::batch_gr_preview::GrBatchModule; - -#[cfg(all( - test, - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -#[path = "grouped_down_columns_gpu.rs"] -mod grouped_down_columns_gpu; - -pub use qwen_dispatch::qwen_shared_tail::{ - SharedDownKind, SharedExpertWeights, SharedExpertWorkspace, SharedGuKind, SharedTailCompletion, - SharedTailRefusal, -}; - -// Additive closed MTP input transport owners. -pub use qwen_dispatch::gdn_closed_queue::{ - GdnQueueStage, GdnRowCompletion, GdnRowPrefix, GdnRowQueue, -}; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] -pub use qwen_dispatch::gdn_fused_t1::{ - GDN_FUSED_T1_PERSISTENT_BYTES, GDN_FUSED_T1_STATE_BYTES, GdnFusedCompletion, GdnFusedPrefix, - GdnFusedStage, GdnFusedT1, -}; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] -pub use qwen_dispatch::gdn_native_batch::{ - GDN_BATCH_EPSILON, GDN_BATCH_MAX_TOKENS, GdnBatchCompletion, GdnBatchPrefix, GdnBatchStage, - GdnGemm, GdnNativeFormat, GdnPrefillBatch, GdnStream, GemmShape, OriginalGdnPromptDevice, - OriginalGdnPromptWeights, -}; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] -pub use qwen_dispatch::moe_prefill_batch::{ - MOE_BATCH_MAX_TOKENS, MOE_BATCH_SCRATCH_BYTES, MoeBatchCompletion, MoeBatchPrefix, - MoeBatchStage, MoePrefillBatch, MoeRouteBatch, -}; -pub use qwen_dispatch::mtp_input_workspace::{ - MtpInputCompletion, MtpInputPrefix, MtpInputRefusal, MtpInputWorkspace, -}; - -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] -pub use qwen_dispatch::gr_batch_inject_workspace::{ - GR_BATCH_INJECT_WORKSPACE_BYTES, GrBatchInjectShape, GrBatchInjectWorkspace, -}; - -// Separately selected asynchronous owned-copy adapter; original APIs unchanged. -#[allow(unsafe_code)] -mod api; -mod async_owned_copy; -pub use async_owned_copy::{ - CompletedOwnedCopy, MAX_ASYNC_COPY_PAIRS, OwnedCopyPairs, OwnedCopyPoll, PendingOwnedCopy, -}; - -// Explicit experimental resident pipeline; original entry bodies remain unchanged. -mod routed_resident_queue; -pub use routed_resident_queue::{ - RoutedResidentCompletion, RoutedResidentQueue, RoutedResidentRefusal, RoutedResidentWeights, -}; - -pub use qwen_dispatch::ple_closed_queue::{ - PleClosedCompletion, PleClosedParts, PleClosedQueue, PleClosedRefusal, PleClosedWeights, -}; - -mod mapped_expert_bank; -pub use mapped_expert_bank::{ - MappedExpertBank, MappedExpertCopyCompletion, MappedExpertCopyScratch, PendingMappedExpertCopy, -}; - -pub use qwen_dispatch::gr_native_batch::{GrNativeBatch, GrNativeProfile}; - -// Explicit Original prefill transport; no default selection or public raw spans. -#[allow(unsafe_code)] -pub(crate) mod ple_batch_ffi; -mod ple_batch_queue; -pub use ple_batch_queue::{ - PLE_BATCH_QUEUE_BYTES, PleBatchCompletion, PleBatchQueue, PleBatchRow, PleBf16Mode, -}; - -mod native_batch_workspace; -pub use native_batch_workspace::{NATIVE_BATCH_WORKSPACE_BYTES, NativeBatchWorkspace}; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -mod gdn_batch_gemm; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub use gdn_batch_gemm::NativeGdnGemm; - -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -mod qsa_native_batch; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub use qsa_native_batch::{ - QSA_NATIVE_BATCH_BYTES, QsaNativeBatchWorkspace, QsaNativeKind, QsaNativePacking, - QsaNativeProjections, -}; - -// Literal Original QSA prompt index assets share the admitted native stream. -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[allow(unsafe_code)] -mod qsa_index_ffi; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -mod qsa_prompt_index; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub use qsa_prompt_index::{ - OriginalQsaDeviceSelection, OriginalQsaPromptDevice, OriginalQsaPromptWeights, - QSA_PROMPT_INDEX_BYTES, QsaPromptIndexPrefix, QsaPromptIndexState, QsaPromptIndexWorkspace, - QsaPromptSelection, -}; - -// Genuine page4 INT8 owners and literal Original prompt/decode programs. -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -mod qsa_native_decode; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -mod qsa_prompt_attention; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[allow(unsafe_code)] -mod qsa_prompt_attention_ffi; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[allow(unsafe_code)] -mod qsa_prompt_host_ffi; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -mod qsa_prompt_kv; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -mod qsa_prompt_resolver; -pub use qsa_prompt_resolver::KvStreamCounters; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -mod kv_stream_gpu; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub use qsa_native_decode::{QSA_NATIVE_DECODE_BYTES, QsaNativeDecode, QsaNativeDecodeCompletion}; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub use qsa_prompt_attention::{ - QSA_PROMPT_ATTENTION_BYTES, QsaAttentionInputs, QsaPromptAttention, - QsaPromptAttentionCompletion, -}; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub use qsa_prompt_kv::{ - CompletedQsaKvAppend, QSA_PROMPT_MAPPED_HOST_BYTES, QSA_PROMPT_MAX_SNAPSHOT_METADATA_BYTES, - QSA_PROMPT_MAX_SNAPSHOT_PAYLOAD_BYTES, QSA_PROMPT_RESIDENT_BYTES, QSA_PROMPT_STAGE_BYTES, - QsaKvInputs, QsaKvOwnerId, QsaKvSnapshot, QsaPromptKv, QsaPromptStage, -}; - -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub use qsa_native_decode::OriginalQsaResidentDecodeCompletion; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub use qsa_prompt_attention::OriginalQsaResidentAttention; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub use qsa_prompt_index::{ - OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex, - OriginalQsaResidentPromptDevice, OriginalQsaResidentScalarIndex, - OriginalQsaResidentScalarSelection, OriginalQsaResidentSelection, -}; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub use qsa_prompt_kv::{ - OriginalQsaMappedAppend, OriginalQsaMappedJournal, OriginalQsaMappedPrefix, - OriginalQsaResidentTransport, -}; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -mod moe_prompt_packet_copy; -mod qsa_native_gate; -pub use qsa_native_gate::QsaNativeGate; - -mod original_sampler; -mod original_sampler_params; -mod sealed_ptx; -#[allow(unsafe_code)] -mod arch_ptx; -mod gpu_report; -pub use gpu_report::gpu_kernel_report; -#[cfg(feature = "sm86")] -mod sm86_table; -#[allow(unsafe_code)] -mod original_sampler_ffi; -#[allow(unsafe_code)] -mod original_sampler_mapped; -pub use original_sampler::{OriginalSampler, SamplerParams, SamplerPath}; - -mod native_prompt_device; -mod prefill_stage; -mod launch_ex; -mod qsa_cluster; -mod qsa_late; -pub use qsa_late::set_override as set_qsa_late_override; -pub use qsa_late::set_topk_override as set_qsa_topk_override; -pub use qsa_prompt_kv::set_qsa_prefetch_override; -pub use qsa_cluster::{requested as qsa_cluster_requested, set_override as set_qsa_cluster_override}; -pub use prefill_stage::{set_gdn_nostore_override as set_prefill_gdn_nostore_override, set_gdn_override as set_prefill_gdn_override}; -pub use native_prompt_device::{ - OriginalDeviceBlock, OriginalDeviceGrRead, OriginalDeviceNormedResidual, - OriginalDeviceResidual, OriginalPleHistory, OriginalPromptDevice, PromptInputStage, -}; - -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use mtp_dense_kv::OriginalMtpSkippedPrefix; -pub use mtp_dense_kv::{ - CompletedDraftKv, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, OriginalMtpEmbedding, - OriginalMtpPrefill, OriginalMtpPrefillWeights, -}; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use mtp_dense_kv::{ - CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, - OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, - OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpStepOutput, -}; - -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -mod original_expert_stager; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use original_expert_stager::{ - OriginalExpertStager, OriginalFileExpertBlob, OriginalStagerBatch, OriginalStagerCompleted, - OriginalStagerJob, OriginalStagerOptions, OriginalStreamAll, OriginalStreamAllCompleted, - OriginalStreamAllForward, OriginalStreamAllOptions, -}; - -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -mod native_parity; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -#[allow(unsafe_code)] -mod native_parity_ffi; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use native_parity::{ - NativeParity, NativeParityExpert, native_parity_embed_supported, native_parity_iq_supported, - native_parity_row_bytes, -}; - -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use mtp_dense_kv::{ - OriginalMtpGrVariant, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, - OriginalMtpScalarPrefill, -}; - -/// `LELEKA_CHAIN` selects the chain-kernel group `mtp` (claude/chain-kernels): the draft step reads the hyper-connections with the -/// staged variant the Original runs on this card (bit-identical to the plain one) and uses the load-hoisted attention kernels. -#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] -pub fn chain_selects_mtp() -> bool { - original_verify::chain::flags().mtp -} -#[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] -pub fn chain_selects_mtp() -> bool { - false -} -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use original_gpu_schedule::OriginalStreamDrained; -pub use original_gpu_schedule::capture_timing as original_capture_timing; - -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -mod native_head; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use native_head::{ - NativeEmbedFlight, NativeHeadDispatch, NativeHeadFlight, NativeHeadProjectionFlight, - NativeHeadSampling, NativeHeadSelection, OriginalNativeEmbed, OriginalNativeEmbedRows, - OriginalNativeHead, OriginalNativeHeadGraphResources, OriginalNativeHeadRows, - native_embed_supported, native_head_row_bytes, native_head_supported, -}; - -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -mod original_file_expert_source; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use original_file_expert_source::{ - OriginalFileExpertSource, OriginalFileSourceBlob, OriginalFileSourceCounters, - OriginalResidentOptions, OriginalSourceSwap, -}; - -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub(crate) mod original_verify; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use original_verify::chain::set_down_override as set_chain_down_override; -pub use original_verify::sm120::set_overrides as set_sm120_overrides; -/// Without the CUDA driver there is no chain window: the override is a no-op. -#[cfg(not(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -)))] -pub fn set_chain_down_override(_: i8) {} -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use original_verify::{ - MAX_PCIE_FETCHES as ORIGINAL_VERIFY_MAX_PCIE_FETCHES, OriginalVerifyGpuPlan, OriginalVerifyPcieSource, - OriginalVerifier, OriginalVerifyBank, OriginalVerifyCanonicalGdn, OriginalVerifyCpuRows, - OriginalVerifyCpuSink, OriginalVerifyGdnJournal, OriginalVerifyGdnStage, - OriginalVerifyGdnWeights, OriginalVerifyGeometry, OriginalVerifyGraphResources, - OriginalVerifyLayout, OriginalVerifyResources, OriginalVerifyRow, OriginalVerifySpan, - OriginalVerifyWindow, OriginalVerifyWindowResult, -}; -// Live verifier release/diagnostic owner, profile report and completed-logit readout. -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use original_verify::{ - HcHalfBuffers, HcLayerBuffers, HcOutputBuffers, OriginalVerifyExpertFormats, - OriginalVerifyGdnProjections, OriginalVerifyGrBinding, OriginalVerifyMoeBinding, - OriginalVerifyMoeLayerWeights, OriginalVerifyNativeMatrix, OriginalVerifyProjBinding, - OriginalVerifyQsaBinding, OriginalVerifyQsaKvBinding, OriginalVerifyQsaLayerWeights, - OriginalVerifyQsaPolicy, OriginalVerifyQsaProjections, PLE_SCRATCH_BYTES, PleBuffers, PleKeyBuffer, QsaRope, - unsealed_window_assets, -}; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use original_verify::{ - ExpertTier, HcHalf, OriginalVerifyExpertLayout, OriginalVerifyWindowResources, PlanLayout, - Projection, QuantSource, Rows as OriginalVerifyRows, UNBOUND_PRODUCERS, WINDOW_LAYERS, - WindowOps as OriginalVerifyWindowOps, WindowPolicy as OriginalVerifyWindowPolicy, - record_window as record_original_verify_window, - OriginalVerifyDiag, OriginalVerifyProfile, PROFILE_STAMPS_PER_LAYER, RowLogprob, analyse_row, - logpos_topk_from_environment, original_verify_diagnostics, original_verify_live_count, - original_verify_release_live, profile_stamp_slot, profile_stamp_words, top_k, write_row_line, - write_window_logprobs, write_original_verify_diagnostics, -}; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use qsa_prompt_index::{OriginalVerifyQsaJournal, OriginalVerifyRope}; -#[cfg(all( - feature = "cuda-driver", - feature = "expert-tier-probe", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use original_verify::{OriginalExpertTierProbe, expert_probe_geometry}; - -// Which compiled assets the Original serve stack needs, and which of them are sealed in this build. -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -mod original_serve_assets; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use original_serve_assets::{ - OriginalAssetKind, OriginalAssetStatus, original_serve_asset_status, original_serve_assets_sealed, - unsealed_original_serve_assets, -}; -// Session-lineage reads over the verifier QSA journal (see the file header). -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -mod original_serve_access; +//! Opt-in CUDA Driver context and bounded byte buffers, without inference. +//! +//! Enable `cuda-driver` and explicitly call [`Driver::load`] on Linux 64-bit. +//! Resources are confined to their creating thread and borrow their owners. +//! Copies stage owned bytes and synchronize before publishing host output. +//! A failed synchronization poisons the context and intentionally leaks the +//! bounded staging allocation: completion cannot safely be inferred from an +//! error, including a subsequent context-destruction result. +#![deny(unsafe_code)] +#![deny(unsafe_op_in_unsafe_fn)] + +// Windows: `libc::dlopen` and friends resolve to the shim (Linux keeps the real libc crate). +#[cfg(windows)] +extern crate leleka_libc_shim as libc; + + +/// Bring-up tracing: `LELEKA_BRINGUP_TRACE` set (any value) enables the `DBG`/`PROBE` diagnostics on stderr. +/// Off by default so production serving prints nothing extra. +pub(crate) fn bringup_trace_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LELEKA_BRINGUP_TRACE").is_some()) +} +macro_rules! bringup_trace { + ($($arg:tt)*) => { + if $crate::bringup_trace_enabled() { + eprintln!($($arg)*); + } + }; +} +pub(crate) use bringup_trace; + +/// Bring-up: with `LELEKA_BRINGUP_TRACE` and `LELEKA_CUDA_TRACE_SYNC` set (Windows), every kernel launched while a guard +/// is alive is followed by a `cuStreamSynchronize`, so a device fault is named by the launch that caused it (the +/// non-blocking replacement of `CUDA_LAUNCH_BLOCKING`, scoped to the prompt forward because the decode windows would +/// deadlock). Elsewhere the guard does nothing. +pub struct PromptSyncTrace(()); +impl PromptSyncTrace { + pub fn enter() -> Self { + #[cfg(windows)] + libc::cuda_trace_set_sync(true); + Self(()) + } +} +impl Drop for PromptSyncTrace { + fn drop(&mut self) { + #[cfg(windows)] + libc::cuda_trace_set_sync(false); + } +} + +use std::{cell::{Cell, RefCell}, fmt, marker::PhantomData, rc::Rc}; + +#[allow(unsafe_code)] +mod ffi; +pub mod compute_drain; +pub mod vram_ledger; +mod device_slab; +pub use device_slab::{DeviceSlice, SlabAllocator, SlabPolicy, SlabStats}; +pub mod nvml; +mod deferred_status; +#[allow(unsafe_code)] +mod original_gpu_schedule; +pub use original_gpu_schedule::{ + OriginalCapture, OriginalCapturePolicy, OriginalEventKind, OriginalGpuEvent, OriginalGpuGraph, + OriginalGpuStream, OriginalGraphFlight, OriginalGraphKey, OriginalGraphRegistry, + OriginalGraphResources, OriginalStreamKind, OriginalWait, +}; +mod original_expert_cache; +mod original_expert_slots; +pub use original_expert_cache::OriginalExpertCache; +mod original_moe_prompt_device; +pub use original_moe_prompt_device::{OriginalMoePromptDevice, OriginalMoePromptLayer}; +mod original_prefill_arena; +pub use original_prefill_arena::{ + OriginalPrefillArena, OriginalPromptLeaseIdentity, OriginalPromptRows, +}; +mod original_prefill_layout; +pub use original_prefill_layout::{ + OriginalPrefillLayout, PrefillKvStage, PrefillLayoutOptions, PrefillPhase, PrefillSpan, +}; +mod head_greedy; +pub use head_greedy::{HEAD_GREEDY_WORKSPACE_BYTES, HeadGreedySelection, HeadGreedyWorkspace}; +mod gdn_state_finite_guard; +pub use gdn_state_finite_guard::GdnStateFiniteGuard; +mod routed_group_workspace; +mod routed_stage_finite_guard; +pub use routed_group_workspace::RoutedColumnsLoan; +pub use routed_group_workspace::RoutedGroupWorkspace; +pub use routed_stage_finite_guard::{RoutedFiniteStage, RoutedStageFiniteGuard}; +mod gr_read_guard; +mod mmq; +mod mmq_native; +pub use mmq::resident::original_group::{ + OriginalMmqCopySchedule, OriginalMmqLayer, OriginalMmqOutput, original_mmq_group_bank_bytes, +}; +pub(crate) use mmq::resident::original_group::prefetch_point; +pub use mmq::resident::{ + FiniteMmqOutput, MmqChunkActivation, MmqGroupActivation, MmqHidden, MmqWorkspace, +}; +pub use mmq::{MmqExperiment, MmqFormat, MmqProfile, MmqWeights}; +use mmq_native::NativeWeights; +mod moe_group_down_columns; +mod moe_group_projection; +mod mtp_dense_kv; +mod original_mtp_actor; +mod original_mtp_coupled; +mod original_mtp_loader; +mod original_mtp_rt; +mod original_mtp_bank; +pub use original_mtp_bank::{ + OriginalMtpLoadFailure, original_mtp_draft_vocab_bytes, OriginalMtpRtBank, OriginalMtpRtTensor, OriginalMtpTensorKind, +}; +pub use original_mtp_actor::{ + ActorRefusal as OriginalMtpActorRefusal, DraftSettings as OriginalMtpDraftSettings, +}; +pub use original_mtp_loader::{ + CoupledPlan as OriginalMtpCoupledPlan, KvFormat as OriginalMtpKvFormat, + KvMode as OriginalMtpKvMode, KvPlan as OriginalMtpKvPlan, LoaderError as OriginalMtpPlanError, + OriginalMtpCapture, OriginalMtpKvStartup, OriginalMtpLoadPlan, original_mtp_bind_reserve, + WeightBankPlan as OriginalMtpWeightBankPlan, +}; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use original_mtp_actor::{OriginalMtpActor, OriginalMtpLoadEvidence, OriginalMtpLoadMeter}; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +mod original_mtp_draft_head; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use original_mtp_draft_head::OriginalMtpDraftHead; +mod original_session_state; +pub use original_session_state::{ + OriginalGeometryFacts, OriginalHostKv, OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, + OriginalRegion, OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts, +}; +mod qwen_dispatch; +pub use qwen_dispatch::gr_batch_read::{GrMicroValues, GrMicrobatchRead}; +mod qsa_selected_kv; +mod serving_context; +pub use serving_context::{ + KV_RESIDENT_DEFAULT_CELLS, KV_RESIDENT_MIN_CELLS, MAX_CONTEXT_CELLS, ServingContext, TRAINED_CONTEXT_CELLS, + configure_kv_resident, configure_serving_context, kv_resident_cells, + serving_context, +}; +pub use mtp_dense_kv::MtpDenseKvRing; +pub use mtp_dense_kv::MTP_ORIGINAL_WINDOW; +pub use mtp_dense_kv::{ + CompletedMtpAttention, CompletedMtpKvReplay, MtpInt8OwnerId, MtpInt8Snapshot, MtpOriginalInt8, + MtpOriginalMixed, MtpOriginalQuery, +}; +pub use qsa_selected_kv::{QsaSelectedKvProducts, QsaSelectedKvWorkspace}; +#[allow(unsafe_code)] +mod qwen_ffi; + +pub mod host_profile; +pub mod experimental; +/// Per-command timing of the batched prompt producers (bring-up profiling only). +pub mod command_profile; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub mod experimental_gpu; +#[cfg(all( + test, + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] +#[path = "experimental_gpu_smoke.rs"] +mod experimental_gpu_smoke; +pub mod kar_decode_levels; +// Pure selection/geometry half of the Original QSA prompt-attention variants (any host). +pub mod qsa_prompt_attention_select; +// Pure scheduling model of the Original Prefill::run (expert stream plan, PLE read-ahead, fusion, hand-off). +pub mod original_prefill_schedule; +// Pure halves of small Original kernels/host files: prefill/moe_mmq.cu copy1/strata_q2/iota, core/device.cu. +pub mod mmq_original_prefill_misc; +pub mod device_arena; +// Pure half of the Original native_flash_attn.cu (admission, geometry, step rule, FP64 specification). +pub mod native_flash_attn; +pub mod s_gemv_legacy; +// Closed driver programs for native_flash_attn / s_gemv_legacy / device_poison: pins, entry signatures, argument slots (pure half). +pub mod closed_kernels; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub mod closed_kernels_gpu; +#[cfg(all( + test, + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] +#[path = "closed_kernels_gpu_smoke.rs"] +mod closed_kernels_gpu_smoke; +#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +mod original_prefill_schedule_crosscheck; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub mod kar_decode_levels_gpu; +#[cfg(all( + test, + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] +#[path = "kar_decode_levels_gpu_smoke.rs"] +mod kar_decode_levels_gpu_smoke; +// Model-free stress of DMA out of a read-only file mapping that is page-locked in place, under working-set trimming (Windows only). +#[cfg(all(test, windows, feature = "cuda-driver", target_pointer_width = "64"))] +#[path = "mapped_file_dma_stress_gpu.rs"] +mod mapped_file_dma_stress_gpu; + +/// Errors retain CUDA operation names/codes and any subsequent cleanup errors. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + Disabled, + UnsupportedPlatform, + LibraryUnavailable, + MissingSymbol(&'static str), + InvalidDriverValue(&'static str), + Driver { + operation: &'static str, + code: i32, + }, + ContextMismatch, + InvalidVectorShape, + InvalidMatvecShape, + InvalidQ5KProjectionShape, + InvalidQ6KProjectionShape, + InvalidQ8Activation, + NonFiniteMmqOutput(&'static str), + UnsupportedProjection, + UnsupportedQwenOperation, + InvalidQwenShape, + InvalidBf16ProjectionShape, + InvalidProjectionShape, + OutputAliasesInput, + InvalidOrdinal, + InvalidSize, + BudgetExceeded, + ShapeMismatch { + expected: usize, + actual: usize, + }, + HostAllocation, + ContextPoisoned, + UnexpectedContext, + /// A verifier graph did not fit in device memory when it was instantiated (upstream a8c1d4b7). The context is intact and the + /// verifier holds the windows recorded before it: `window` is the T of the window graph that did not fit, 0 for the commit + /// graph (recorded after every window). A caller can record again with fewer windows. + GraphOutOfMemory { + window: usize, + }, + Multiple { + primary: Box, + secondary: Box, + }, +} + +impl Error { + fn environment_message(&self) -> Option<&'static str> { + Some(match self { + Self::Disabled => "CUDA Driver feature is disabled", + Self::UnsupportedPlatform => "CUDA Driver requires Linux with 64-bit pointers", + Self::LibraryUnavailable => "cannot load libcuda.so.1", + Self::InvalidOrdinal => "device ordinal must be nonnegative", + Self::HostAllocation => "cannot allocate owned host staging memory", + Self::ContextPoisoned => { + "context is poisoned after uncertain completion or restoration" + } + Self::UnexpectedContext => "CUDA pop returned a different context", + _ => return None, + }) + } + fn validation_message(&self) -> Option<&'static str> { + Some(match self { + Self::ContextMismatch => "buffers must belong to this exact context", + Self::InvalidVectorShape => { + "vector shape must be nonempty f32 bytes with a bounded u32 count/grid" + } + Self::InvalidMatvecShape => { + "matvec requires exact nonempty bounded row-major f32 shapes" + } + Self::InvalidQ5KProjectionShape => { + "Q5_K projection requires exact bounded row-major single-column shapes" + } + Self::InvalidQ6KProjectionShape => { + "Q6_K projection requires exact bounded row-major single-column shapes" + } + Self::UnsupportedProjection => "projection format is not integrated", + Self::UnsupportedQwenOperation => "Qwen operation has no qualified fixed asset", + Self::InvalidQwenShape => { + "Qwen operation requires its exact pinned topology and byte layout" + } + Self::InvalidBf16ProjectionShape => { + "BF16 projection requires exact bounded rows and positive even columns" + } + Self::InvalidProjectionShape => { + "projection requires exact bounded packed single-column shapes" + } + Self::InvalidQ8Activation => "activation cannot be represented by native Q8_1", + Self::NonFiniteMmqOutput(_) => "MMQ produced a nonfinite stage output", + Self::OutputAliasesInput => "output must not alias an input", + Self::InvalidSize => "byte size must be nonzero and fit isize", + Self::BudgetExceeded => "allocation exceeds context byte budget", + _ => return None, + }) + } +} +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if let Some(message) = self + .environment_message() + .or_else(|| self.validation_message()) + { + return f.write_str(message); + } + match self { + Self::MissingSymbol(symbol) => write!(f, "missing CUDA Driver symbol {symbol}"), + Self::InvalidDriverValue(operation) => { + write!(f, "{operation} returned an invalid handle on success") + } + Self::Driver { operation, code } => { + write!(f, "{operation} failed with CUDA code {code}") + } + Self::ShapeMismatch { expected, actual } => { + write!(f, "byte shape mismatch: expected {expected}, got {actual}") + } + Self::GraphOutOfMemory { window: 0 } => { + write!(f, "the verifier commit graph did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)") + } + Self::GraphOutOfMemory { window } => { + write!(f, "the verifier window graph T={window} did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)") + } + Self::Multiple { primary, secondary } => { + write!(f, "{primary}; subsequent error: {secondary}") + } + _ => unreachable!("static errors have a message"), + } + } +} +impl std::error::Error for Error {} +pub type Result = std::result::Result; + +/// Exact whole row-major BF16 matrix and one unchanged F32 input vector. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Bf16ProjectionShape { + pub rows: usize, + pub columns: usize, +} + +fn combine(primary: Result, secondary: Result<()>) -> Result { + match (primary, secondary) { + (Ok(value), Ok(())) => Ok(value), + (Err(error), Ok(())) | (Ok(_), Err(error)) => Err(error), + (Err(primary), Err(secondary)) => Err(Error::Multiple { + primary: Box::new(primary), + secondary: Box::new(secondary), + }), + } +} +fn valid_size(bytes: usize) -> Result<()> { + if bytes == 0 || bytes > isize::MAX as usize { + Err(Error::InvalidSize) + } else { + Ok(()) + } +} + +/// A loaded fixed ABI. No resources can be sent or shared between threads. +pub struct Driver { + api: Rc, + version: i32, +} +impl Driver { + /// Resolve the entire fixed ABI before initializing CUDA. + pub fn load() -> Result { + let api = Rc::new(ffi::Api::load()?); + api.init()?; + let version = api.version()?; + Ok(Self { api, version }) + } + pub fn version(&self) -> i32 { + self.version + } + pub fn device(&self, ordinal: i32) -> Result> { + if ordinal < 0 { + return Err(Error::InvalidOrdinal); + } + Ok(Device { + driver: self, + handle: self.api.device(ordinal)?, + ordinal, + }) + } +} + +/// A device selected through its owner driver, without a public raw handle. +pub struct Device<'driver> { + driver: &'driver Driver, + handle: i32, + ordinal: i32, +} +impl<'driver> Device<'driver> { + pub fn create_context(&self, byte_budget: usize) -> Result> { + valid_size(byte_budget)?; + let api = &self.driver.api; + let handle = api.create(self.handle)?; + let restore = api.pop().and_then(|popped| { + if popped == handle { + Ok(()) + } else { + Err(Error::UnexpectedContext) + } + }); + if let Err(error) = restore { + let cleanup = api.destroy(handle); + if cleanup.is_err() { + // The driver may still own a live context; keep its ABI loaded. + std::mem::forget(Rc::clone(api)); + } + return combine(Err(error), cleanup); + } + Ok(Context { + driver: self.driver, + handle: Some(handle), + ordinal: self.ordinal, + budget: byte_budget, + allocated: Cell::new(0), + poisoned: PoisonCell::new(false), + vector_add_kernel: Cell::new(None), + matvec_kernel: Cell::new(None), + q5_k_kernel: Cell::new(None), + q6_k_kernel: Cell::new(None), + common_quantizer: Cell::new(None), + grouped_iq3: Cell::new(None), + grouped_iq2: Cell::new(None), + grouped_iq3_s: Cell::new(None), + grouped_iq4_xs: Cell::new(None), + grouped_iq3_s_nc4: Cell::new(None), + grouped_iq4_xs_nc4: Cell::new(None), + grouped_swiglu: Cell::new(None), + grouped_down_iq4: Cell::new(None), + grouped_down_q2: Cell::new(None), + gr_read_guard_kernel: Cell::new(None), + projection_kernels: std::array::from_fn(|_| Cell::new(None)), + qwen_kernels: qwen_dispatch::Cache::new(), + kar_levels: Cell::new(None), + experimental: std::array::from_fn(|_| Cell::new(None)), + window_modules: RefCell::new(Vec::new()), + deferred_frees: RefCell::new(Vec::new()), + }) + } +} + +/// A private context with a budget for actual live allocations. + +/// Bring-up diagnostic: a `Cell` that prints the stack of the first `set(true)` when LELEKA_TRACE_POISON is set. +pub(crate) struct PoisonCell(Cell); +impl PoisonCell { + pub(crate) fn new(v: bool) -> Self { Self(Cell::new(v)) } + pub(crate) fn get(&self) -> bool { self.0.get() } + pub(crate) fn set(&self, v: bool) { + if v && !self.0.get() && std::env::var_os("LELEKA_TRACE_POISON").is_some() { + crate::bringup_trace!("DBG context poisoned here: +{}", std::backtrace::Backtrace::force_capture()); + } + self.0.set(v); + } +} + +pub struct Context<'driver> { + driver: &'driver Driver, + handle: Option, + /// Ordinal given to `Driver::device`: the `cudaGetDevice` answer for work + /// issued under this context (MtpDrafter records it at load). + ordinal: i32, + budget: usize, + allocated: Cell, + poisoned: PoisonCell, + vector_add_kernel: Cell>, + matvec_kernel: Cell>, + q5_k_kernel: Cell>, + q6_k_kernel: Cell>, + common_quantizer: Cell>, + grouped_iq3: Cell>, + grouped_iq2: Cell>, + grouped_iq3_s: Cell>, + grouped_iq4_xs: Cell>, + grouped_iq3_s_nc4: Cell>, + grouped_iq4_xs_nc4: Cell>, + grouped_swiglu: Cell>, + grouped_down_iq4: Cell>, + grouped_down_q2: Cell>, + gr_read_guard_kernel: Cell>, + projection_kernels: [Cell>; 8], + qwen_kernels: qwen_dispatch::Cache, + kar_levels: Cell>, + experimental: [Cell>; 6], + /// Sealed verify-window modules loaded under this context, shared by every verifier bank created later + /// (the serve path assembles one per request) and unloaded with the context. + window_modules: RefCell, Vec<&'static str>)>>, + /// Buffers released while a prompt chunk's expert copies are in flight (cuMemFree synchronizes the whole + /// device and would wait for every queued copy): freed by `flush_deferred_frees`. They stay charged. + deferred_frees: RefCell>, +} +#[derive(Clone, Copy)] +struct FixedKernel { + module: ffi::ModuleHandle, + function: ffi::FunctionHandle, +} +#[derive(Clone, Copy)] +struct FixedPairKernels { + module: ffi::ModuleHandle, + quantize: ffi::FunctionHandle, + project: ffi::FunctionHandle, +} + +// Closed selector: callers cannot choose executable bytes, names or geometry. +#[derive(Clone, Copy)] +enum FixedOperation { + VectorAdd, + GrReadFinite, + Matvec, + Q5K, + Q5KQuantize, + Q5KProject, + Q6K, + Q6KQuantize, + Q6KProject, + CommonQuantize, + GroupedIq3, + GroupedIq2, + GroupedIq3S, + GroupedIq4Xs, + GroupedIq3SNc4, + GroupedIq4XsNc4, + GroupedSwiglu, + GroupedDownIq4, + GroupedDownQ2, + Projection(ProjectionKind), +} + +/// Closed ordinary packed matrix formats. No raw executable selector. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow(non_camel_case_types)] // Canonical format spellings are the fixed public ABI. +pub enum DenseFormat { + Q8_0, + Q4_K, + IQ4_NL, + IQ4_XS, +} +/// Closed preselected expert formats; output is unweighted. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow(non_camel_case_types)] // Canonical format spellings are the fixed public ABI. +pub enum RoutedFormat { + IQ3_XXS, + IQ3_S, + IQ2_S, + IQ4_NL, + IQ4_XS, + Q2_0, +} +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ProjectionKind { + Dense(DenseFormat), + Routed(RoutedFormat), +} +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ProjectionSpec { + pub kind: ProjectionKind, + pub rows: usize, + pub columns: usize, +} + +/// One synchronized native Q8_1 activation for fixed routed Gate/Up projections. +/// The original activation stays immutably borrowed until this owner is closed. +/// Callers must scope this owner to one layer/step, never a weight cache. +pub struct RoutedGateUpQ8<'context> { + activation: &'context DeviceBuffer<'context>, + scratch: Option>, +} +impl RoutedGateUpQ8<'_> { + /// Consume the owner and report its one scratch release attempt. + pub fn close(mut self) -> Result<()> { + self.release() + } + fn release(&mut self) -> Result<()> { + let Some(scratch) = self.scratch.take() else { + return Ok(()); + }; + if scratch.context.poisoned.get() { + // Unknown work retains the allocation and charge until containment + // by context destruction; no free against an uncertain context. + std::mem::forget(scratch); + return Err(Error::ContextPoisoned); + } + scratch.release() + } +} +impl Drop for RoutedGateUpQ8<'_> { + fn drop(&mut self) { + let _ = self.release(); + } +} + +#[derive(Clone, Copy)] +struct ProjectionKernels { + module: ffi::ModuleHandle, + dense: Option, + routed: Option, +} +impl ProjectionKind { + fn layout(self) -> (usize, usize, usize, Option) { + use DenseFormat as D; + use RoutedFormat as R; + match self { + Self::Dense(D::Q8_0) => (0, 32, 34, Some(1024)), + Self::Dense(D::Q4_K) => (1, 256, 144, Some(2048)), + Self::Routed(R::IQ3_XXS) => (2, 256, 98, None), + Self::Routed(R::IQ3_S) => (3, 256, 110, None), + Self::Routed(R::IQ2_S) => (4, 256, 82, None), + Self::Dense(D::IQ4_NL) => (5, 32, 18, Some(2048)), + Self::Routed(R::IQ4_NL) => (5, 32, 18, None), + Self::Dense(D::IQ4_XS) => (6, 256, 136, Some(4096)), + Self::Routed(R::IQ4_XS) => (6, 256, 136, None), + Self::Routed(R::Q2_0) => (7, 64, 18, None), + } + } + fn weight_alignment(self) -> u64 { + // Native Q4_K half2/u32 fields and IQ4_XS qs at offset8 require + // aligned 32-bit loads. The remaining packed blocks use halfwords. + match self { + Self::Dense(DenseFormat::Q4_K | DenseFormat::IQ4_XS) + | Self::Routed(RoutedFormat::IQ4_XS) => 4, + _ => 2, + } + } + fn required_modes(self) -> (Option, Option) { + match self { + Self::Dense(DenseFormat::IQ4_NL) | Self::Routed(RoutedFormat::IQ4_NL) => ( + Some(Self::Dense(DenseFormat::IQ4_NL)), + Some(Self::Routed(RoutedFormat::IQ4_NL)), + ), + Self::Dense(DenseFormat::IQ4_XS) | Self::Routed(RoutedFormat::IQ4_XS) => ( + Some(Self::Dense(DenseFormat::IQ4_XS)), + Some(Self::Routed(RoutedFormat::IQ4_XS)), + ), + Self::Dense(_) => (Some(self), None), + Self::Routed(_) => (None, Some(self)), + } + } +} +#[derive(Debug, PartialEq, Eq)] +struct ProjectionShape { + weight_bytes: usize, + activation_bytes: usize, + output_bytes: usize, + scratch_bytes: usize, + temporary_bytes: usize, + rows: u32, + columns: u32, + quant_grid: u32, + projection_grid: u32, +} + +// The Q4_K PTX forms signed 32-bit packed-byte offsets, including the +// three-row arms of its four-row CTA when N < 2048. Those offsets are +// calculated before per-row guards, so admission must cover the padded +// launch rows, not only the final caller-visible row. +fn q4_k_native_indices_fit(rows: usize, columns: usize) -> bool { + const Q4_K_BLOCK: usize = 256; + const Q4_K_BLOCK_BYTES: usize = 144; + const Q4_K_ROWS_PER_CTA_SMALL: usize = 4; + + if rows == 0 || columns == 0 || !columns.is_multiple_of(Q4_K_BLOCK) { + return false; + } + + let rows_per_cta = if columns < 2048 { + Q4_K_ROWS_PER_CTA_SMALL + } else { + 1 + }; + let last_cta_base_row = match rows + .div_ceil(rows_per_cta) + .checked_sub(1) + .and_then(|index| index.checked_mul(rows_per_cta)) + { + Some(value) => value, + None => return false, + }; + // PTX materializes row, row+1, row+2, and row+3 offsets even for the + // one-row large-N launch; the invalid output arms are only guarded later. + let last_computed_row = match last_cta_base_row.checked_add(3) { + Some(value) if value <= i32::MAX as usize => value, + _ => return false, + }; + let blocks_per_row = columns / Q4_K_BLOCK; + // Each lane group starts at r362=0..7 and advances by eight until its + // index is >= B. The largest final, subsequently unconsumed index is + // B+7; this also covers the single small-N path's common increment. + let loop_advance_blocks = match blocks_per_row.checked_add(7) { + Some(value) => value, + None => return false, + }; + let last_executed_block_offset = match last_computed_row + .checked_mul(blocks_per_row) + .and_then(|row_base| row_base.checked_add(loop_advance_blocks)) + { + Some(value) => value, + None => return false, + }; + let last_signed_byte_offset = match last_executed_block_offset.checked_mul(Q4_K_BLOCK_BYTES) { + Some(value) => value, + None => return false, + }; + last_signed_byte_offset <= i32::MAX as usize +} + +fn projection_shape(spec: ProjectionSpec) -> Result { + let invalid = Error::InvalidProjectionShape; + let (_, block, bytes, small) = spec.kind.layout(); + let (m, n) = (spec.rows, spec.columns); + if m == 0 + || n == 0 + || m > i32::MAX as usize + || n > i32::MAX as usize + || !n.is_multiple_of(block) + || !n.is_multiple_of(32) + { + return Err(invalid); + } + let bounded = |value: Option| -> Result { + let value = value.ok_or(Error::InvalidProjectionShape)?; + valid_size(value).map_err(|_| Error::InvalidProjectionShape)?; + Ok(value) + }; + let weight_bytes = bounded(m.checked_mul(n / block).and_then(|v| v.checked_mul(bytes)))?; + if spec.kind == ProjectionKind::Dense(DenseFormat::Q4_K) && !q4_k_native_indices_fit(m, n) { + return Err(invalid); + } + let activation_bytes = bounded(n.checked_mul(4))?; + let output_bytes = bounded(m.checked_mul(4))?; + let scratch_bytes = bounded((n / 32).checked_mul(36))?; + let temporary_bytes = bounded(scratch_bytes.checked_add(4))?; + let quant_grid = u32::try_from(n.div_ceil(256)).map_err(|_| Error::InvalidProjectionShape)?; + let grid = if small.is_none_or(|limit| n < limit) { + m.div_ceil(4) + } else { + m + }; + let projection_grid = u32::try_from(grid).map_err(|_| Error::InvalidProjectionShape)?; + Ok(ProjectionShape { + weight_bytes, + activation_bytes, + output_bytes, + scratch_bytes, + temporary_bytes, + rows: m as u32, + columns: n as u32, + quant_grid, + projection_grid, + }) +} + +// Pure structural admission shared by production and the private mock caller. +// No availability bypass, Driver call, cache publication or budget mutation. +fn projection_ranges( + kind: ProjectionKind, + shape: &ProjectionShape, + handles: [ffi::BufferHandle; 3], +) -> Result<()> { + for (handle, bytes, alignment) in [ + (handles[0], shape.weight_bytes, kind.weight_alignment()), + (handles[1], shape.activation_bytes, 4), + (handles[2], shape.output_bytes, 4), + ] { + handle.validate_projection_extent(bytes, alignment)?; + } + if handles[2].overlaps(shape.output_bytes, handles[0], shape.weight_bytes) + || handles[2].overlaps(shape.output_bytes, handles[1], shape.activation_bytes) + { + return Err(Error::OutputAliasesInput); + } + Ok(()) +} + +/// Exact one-column Q5_K matrix geometry: `rows × columns` packed weights. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Q5KProjectionShape { + pub rows: usize, + pub columns: usize, +} + +/// Exact one-column Q6_K matrix geometry: `rows × columns` packed weights. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Q6KProjectionShape { + pub rows: usize, + pub columns: usize, +} + +#[derive(Debug, PartialEq, Eq)] +struct Q5KShape { + weight_bytes: usize, + activation_bytes: usize, + output_bytes: usize, + scratch_bytes: usize, + rows: u32, + columns: u32, + quant_grid: u32, + projection_grid: u32, +} + +fn q5_k_shape(rows: usize, columns: usize) -> Result { + if rows == 0 || columns == 0 || !columns.is_multiple_of(256) { + return Err(Error::InvalidQ5KProjectionShape); + } + let rows_abi = u32::try_from(rows).map_err(|_| Error::InvalidQ5KProjectionShape)?; + let columns_abi = u32::try_from(columns).map_err(|_| Error::InvalidQ5KProjectionShape)?; + if rows_abi > i32::MAX as u32 || columns_abi > i32::MAX as u32 { + return Err(Error::InvalidQ5KProjectionShape); + } + let checked_bytes = |elements: usize, width: usize| -> Result { + let bytes = elements + .checked_mul(width) + .ok_or(Error::InvalidQ5KProjectionShape)?; + valid_size(bytes).map_err(|_| Error::InvalidQ5KProjectionShape)?; + Ok(bytes) + }; + let weight_blocks = rows + .checked_mul(columns / 256) + .ok_or(Error::InvalidQ5KProjectionShape)?; + let weight_bytes = checked_bytes(weight_blocks, 176)?; + let activation_bytes = checked_bytes(columns, 4)?; + let output_bytes = checked_bytes(rows, 4)?; + let scratch_bytes = checked_bytes(columns / 32, 36)?; + let quant_grid = columns / 256; + if quant_grid == 0 || quant_grid > i32::MAX as usize { + return Err(Error::InvalidQ5KProjectionShape); + } + let small_k = columns / 256 < 8; + let projection_ctas = if small_k { rows.div_ceil(4) } else { rows }; + if projection_ctas == 0 || projection_ctas > i32::MAX as usize { + return Err(Error::InvalidQ5KProjectionShape); + } + Ok(Q5KShape { + weight_bytes, + activation_bytes, + output_bytes, + scratch_bytes, + rows: rows_abi, + columns: columns_abi, + quant_grid: u32::try_from(quant_grid).map_err(|_| Error::InvalidQ5KProjectionShape)?, + projection_grid: u32::try_from(projection_ctas) + .map_err(|_| Error::InvalidQ5KProjectionShape)?, + }) +} + +#[derive(Debug, PartialEq, Eq)] +struct Q6KShape { + weight_bytes: usize, + activation_bytes: usize, + output_bytes: usize, + scratch_bytes: usize, + rows: u32, + columns: u32, + quant_grid: u32, + projection_grid: u32, +} + +fn q6_k_shape(rows: usize, columns: usize) -> Result { + if rows == 0 || columns == 0 || !columns.is_multiple_of(256) { + return Err(Error::InvalidQ6KProjectionShape); + } + let rows_abi = u32::try_from(rows).map_err(|_| Error::InvalidQ6KProjectionShape)?; + let columns_abi = u32::try_from(columns).map_err(|_| Error::InvalidQ6KProjectionShape)?; + if rows_abi > i32::MAX as u32 || columns_abi > i32::MAX as u32 { + return Err(Error::InvalidQ6KProjectionShape); + } + let checked_bytes = |elements: usize, width: usize| -> Result { + let bytes = elements + .checked_mul(width) + .ok_or(Error::InvalidQ6KProjectionShape)?; + valid_size(bytes).map_err(|_| Error::InvalidQ6KProjectionShape)?; + Ok(bytes) + }; + let weight_blocks = rows + .checked_mul(columns / 256) + .ok_or(Error::InvalidQ6KProjectionShape)?; + let weight_bytes = checked_bytes(weight_blocks, 210)?; + let activation_bytes = checked_bytes(columns, 4)?; + let output_bytes = checked_bytes(rows, 4)?; + let scratch_bytes = checked_bytes(columns / 32, 36)?; + let quant_grid = columns / 256; + if quant_grid == 0 || quant_grid > i32::MAX as usize { + return Err(Error::InvalidQ6KProjectionShape); + } + let small_k = columns / 256 < 4; + let projection_ctas = if small_k { rows.div_ceil(4) } else { rows }; + if projection_ctas == 0 || projection_ctas > i32::MAX as usize { + return Err(Error::InvalidQ6KProjectionShape); + } + Ok(Q6KShape { + weight_bytes, + activation_bytes, + output_bytes, + scratch_bytes, + rows: rows_abi, + columns: columns_abi, + quant_grid: u32::try_from(quant_grid).map_err(|_| Error::InvalidQ6KProjectionShape)?, + projection_grid: u32::try_from(projection_ctas) + .map_err(|_| Error::InvalidQ6KProjectionShape)?, + }) +} + +#[derive(Debug, PartialEq, Eq)] +struct MatvecShape { + matrix_bytes: usize, + vector_bytes: usize, + output_bytes: usize, + rows: u32, + columns: u32, + grid: u32, +} +fn matvec_shape(rows: usize, columns: usize) -> Result { + let rows_abi = u32::try_from(rows).map_err(|_| Error::InvalidMatvecShape)?; + let columns_abi = u32::try_from(columns).map_err(|_| Error::InvalidMatvecShape)?; + let bytes = |elements: Option| -> Result { + let bytes = elements + .and_then(|v| v.checked_mul(4)) + .ok_or(Error::InvalidMatvecShape)?; + valid_size(bytes).map_err(|_| Error::InvalidMatvecShape)?; + Ok(bytes) + }; + let matrix_bytes = bytes(rows.checked_mul(columns))?; + let vector_bytes = bytes(Some(columns))?; + let output_bytes = bytes(Some(rows))?; + let grid = u64::from(rows_abi).div_ceil(128); + if grid == 0 || grid > i32::MAX as u64 { + return Err(Error::InvalidMatvecShape); + } + Ok(MatvecShape { + matrix_bytes, + vector_bytes, + output_bytes, + rows: rows_abi, + columns: columns_abi, + grid: u32::try_from(grid).map_err(|_| Error::InvalidMatvecShape)?, + }) +} + +fn matvec_allocations( + matrix: Option, + vector: Option, + output: Option, + shape: &MatvecShape, +) -> Result<(ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle)> { + let matrix = matrix.ok_or(Error::ContextPoisoned)?; + let vector = vector.ok_or(Error::ContextPoisoned)?; + let output = output.ok_or(Error::ContextPoisoned)?; + if matrix == output || vector == output { + return Err(Error::OutputAliasesInput); + } + matrix.validate_extent(shape.matrix_bytes)?; + vector.validate_extent(shape.vector_bytes)?; + output.validate_extent(shape.output_bytes)?; + Ok((matrix, vector, output)) +} + +// Wider integer arithmetic also covers the final partial block at u32::MAX. +fn vector_shape(bytes: usize) -> Result<(u32, u32)> { + if valid_size(bytes).is_err() || !bytes.is_multiple_of(4) { + return Err(Error::InvalidVectorShape); + } + let count = u32::try_from(bytes / 4).map_err(|_| Error::InvalidVectorShape)?; + let grid = u64::from(count) + .checked_add(127) + .ok_or(Error::InvalidVectorShape)? + / 128; + if grid == 0 || grid > i32::MAX as u64 { + return Err(Error::InvalidVectorShape); + } + Ok(( + count, + u32::try_from(grid).map_err(|_| Error::InvalidVectorShape)?, + )) +} +impl Context<'_> { + /// Private sticky failure primitive shared by native owners. + fn poison(&self) { + self.poisoned.set(true); + } + /// Retain the actual loaded API after uncertain completion/restoration. + fn retain_driver(&self) { + std::mem::forget(Rc::clone(&self.driver.api)); + } + pub fn budget_bytes(&self) -> usize { + self.budget + } + /// The device ordinal this context was created on. + pub fn device_ordinal(&self) -> i32 { + self.ordinal + } + /// Failed frees remain charged until context destruction. + pub fn allocated_bytes(&self) -> usize { + self.allocated.get() + } + /// Actual `(free, total)` physical device bytes for this current Context. + /// This is a snapshot, not a reservation guarantee; it allocates/frees nothing. + /// Zero free is valid, zero total or free above total refuses the query. + pub fn memory_info(&self) -> Result<(usize, usize)> { + let guard = self.enter()?; + let query = self.driver.api.memory_info(); + if matches!(&query, Err(Error::Driver { .. })) { + // CUDA may report an earlier asynchronous failure here. Do not + // admit further resource use under an uncertain execution state. + self.poisoned.set(true); + } + // CurrentGuard verifies the popped identity and poisons on pop failure. + combine(query, guard.finish()) + } + fn enter(&self) -> Result> { + if self.poisoned.get() { + return Err(Error::ContextPoisoned); + } + let handle = self.handle.ok_or(Error::ContextPoisoned)?; + if let Err(error) = self.driver.api.push(handle) { + // A failed current-context transport leaves the execution state + // uncertain. Every owner sharing this Context must refuse reuse. + self.poison(); + self.retain_driver(); + return Err(error); + } + Ok(CurrentGuard { + context: self, + active: true, + }) + } + pub fn allocate(&self, bytes: usize) -> Result> { + valid_size(bytes)?; + let total = self + .allocated + .get() + .checked_add(bytes) + .ok_or(Error::BudgetExceeded)?; + if total > self.budget { + return Err(Error::BudgetExceeded); + } + let guard = self.enter()?; + let allocation = self.driver.api.allocate(bytes); + if allocation.is_ok() { + self.allocated.set(total); + } + // A successful allocation whose pop fails stays charged. The poisoned + // context owns that allocation until destruction, so no unguarded free. + let handle = combine(allocation, guard.finish())?; + vram_ledger::note_alloc(handle.qwen_address(), bytes); + Ok(DeviceBuffer { + context: self, + handle: Some(handle), + bytes, + _thread: PhantomData, + borrowed: false, + }) + } + /// Queue a buffer's release for after the chunk's expert stream (it stays charged until then); when the + /// queued bytes pass `LELEKA_PREFILL_DEFER_FREE_MIB` (512) they are freed at once. + fn defer_free(&self, handle: ffi::BufferHandle, bytes: usize) -> Result<()> { + let pending = { + let mut list = self.deferred_frees.borrow_mut(); + list.push((handle, bytes)); + list.iter().map(|b| b.1).sum::() + }; + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + std::env::var("LELEKA_PREFILL_DEFER_FREE_MIB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(512) << 20 + }); + if pending > limit { self.flush_deferred_frees() } else { Ok(()) } + } + /// Free every deferred buffer (one device synchronization). + pub(crate) fn flush_deferred_frees(&self) -> Result<()> { + let list = std::mem::take(&mut *self.deferred_frees.borrow_mut()); + if list.is_empty() { + return Ok(()); + } + let guard = self.enter()?; + let mut result = Ok(()); + for (handle, bytes) in list { + let free = self.driver.api.free(handle); + if free.is_ok() { + self.allocated.set(self.allocated.get() - bytes); + } + result = combine(result, free); + } + combine(result, guard.finish()) + } + /// Read-only sticky completion fence; never resets or changes the context. + pub fn is_poisoned(&self) -> bool { + self.poisoned.get() + } + pub fn synchronize(&self) -> Result<()> { + let guard = self.enter()?; + let sync = self.driver.api.synchronize(); + if sync.is_err() { + self.poisoned.set(true); + } + combine(sync, guard.finish()) + } + /// Copy one complete2560-F32 MoE Down result into its fixed ordered slot. + /// This performs no arithmetic or finite admission; callers retain the + /// actual producer's finite proof. Successful return attests completed copy. + pub fn pack_moe_down_f32( + &self, + source: &DeviceBuffer<'_>, + destination: &mut DeviceBuffer<'_>, + slot: u32, + ) -> Result<()> { + if self.poisoned.get() { + return Err(Error::ContextPoisoned); + } + if !std::ptr::eq(self, source.context) || !std::ptr::eq(self, destination.context) { + return Err(Error::ContextMismatch); + } + if source.bytes != 10_240 || destination.bytes != 102_400 || slot >= 10 { + return Err(Error::InvalidQwenShape); + } + let source = source.handle.ok_or(Error::ContextPoisoned)?; + let destination = destination.handle.ok_or(Error::ContextPoisoned)?; + source.validate_projection_extent(10_240, 4)?; + destination.validate_projection_extent(102_400, 4)?; + if source.overlaps(10_240, destination, 102_400) { + return Err(Error::OutputAliasesInput); + } + let target = destination.moe_down_slot(slot)?; + let guard = match self.enter() { + Ok(guard) => guard, + Err(error) => { + self.poisoned.set(true); + return Err(error); + } + }; + let copy = self.driver.api.copy_moe_down(target, source); + // A failed copy can report earlier work. Always attempt synchronization + // and restore, preserving primary copy→sync→restore error precedence. + let sync = self.driver.api.synchronize(); + let restore = guard.finish(); + if copy.is_err() || sync.is_err() || restore.is_err() { + self.poisoned.set(true); + } + combine(combine(copy, sync), restore) + } + /// Add two exact f32 byte vectors with the fixed trusted kernel. The + /// output is usable as a computed vector only after a successful return. + pub fn vector_add_f32( + &self, + a: &DeviceBuffer<'_>, + b: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + let (handles, count, grid) = self.vector_admission(a, b, output)?; + let [a_handle, b_handle, out_handle] = handles; + // Establish the owned parameter addresses after their stable heap + // placement, before any native mutation. No caller host data is used. + let mut arguments = ffi::LaunchArguments::new(a_handle, b_handle, out_handle, count); + let guard = self.enter()?; + let kernel = match self.fixed_kernel(FixedOperation::VectorAdd) { + Ok(kernel) => kernel, + Err(error) => return combine(Err(error), guard.finish()), + }; + let launch = self + .driver + .api + .launch(kernel.function, grid, &mut arguments); + self.complete_launch(launch, arguments, guard) + } + fn vector_admission( + &self, + a: &DeviceBuffer<'_>, + b: &DeviceBuffer<'_>, + output: &DeviceBuffer<'_>, + ) -> Result<([ffi::BufferHandle; 3], u32, u32)> { + if self.poisoned.get() { + return Err(Error::ContextPoisoned); + } + if !std::ptr::eq(self, a.context) + || !std::ptr::eq(self, b.context) + || !std::ptr::eq(self, output.context) + { + return Err(Error::ContextMismatch); + } + let (count, grid) = vector_shape(a.bytes)?; + if a.bytes != b.bytes || a.bytes != output.bytes { + return Err(Error::InvalidVectorShape); + } + let a_handle = a.handle.ok_or(Error::ContextPoisoned)?; + let b_handle = b.handle.ok_or(Error::ContextPoisoned)?; + let out_handle = output.handle.ok_or(Error::ContextPoisoned)?; + if a_handle == out_handle || b_handle == out_handle { + return Err(Error::OutputAliasesInput); + } + Ok(([a_handle, b_handle, out_handle], count, grid)) + } + fn complete_launch( + &self, + launch: Result<()>, + arguments: T, + guard: CurrentGuard<'_, '_>, + ) -> Result<()> { + // A launch error may describe earlier asynchronous work. Synchronize + // every attempted launch; preserve launch/sync/pop error order. + let sync = self.driver.api.synchronize(); + if sync.is_err() { + self.poisoned.set(true); + } + let restore = guard.finish(); + if restore.is_err() { + self.poisoned.set(true); + } + if sync.is_err() || restore.is_err() { + // Both scalars and their table may still be read. The raw owner + // remains forgotten even if later context destruction succeeds. + std::mem::forget(arguments); + } + combine(combine(launch, sync), restore) + } + /// Compute each row's dot product in ascending column order with separate + /// binary32 multiply/add rounding. All buffers are exact whole allocations; + /// output is usable as a computed vector only after a successful return. + pub fn matvec_f32( + &self, + matrix: &DeviceBuffer<'_>, + vector: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + rows: usize, + columns: usize, + ) -> Result<()> { + let (shape, handles) = self.matvec_admission([matrix, vector, output], rows, columns)?; + let [matrix_handle, vector_handle, output_handle] = handles; + let mut arguments = ffi::MatvecArguments::new( + matrix_handle, + vector_handle, + output_handle, + shape.rows, + shape.columns, + ); + let guard = self.enter()?; + let kernel = match self.fixed_kernel(FixedOperation::Matvec) { + Ok(kernel) => kernel, + Err(error) => return combine(Err(error), guard.finish()), + }; + let launch = self + .driver + .api + .launch_matvec(kernel.function, shape.grid, &mut arguments); + self.complete_launch(launch, arguments, guard) + } + + /// Project one resident F32 activation through row-major Q5_K weights. + /// Activations are quantized using the native Q8_1 block/reduction contract. + pub fn q5_k_q8_1( + &self, + weights: &DeviceBuffer<'_>, + activation: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + shape: Q5KProjectionShape, + ) -> Result<()> { + let (shape, handles, temporary_bytes) = + self.q5_k_admission(weights, activation, output, shape)?; + + // Account the complete worst-case scratch/status requirement before + // the first context push, module load, or allocation. + let total = self + .allocated + .get() + .checked_add(temporary_bytes) + .ok_or(Error::BudgetExceeded)?; + if total > self.budget { + return Err(Error::BudgetExceeded); + } + + let scratch = self.allocate(shape.scratch_bytes)?; + let mut status = match self.allocate(4) { + Ok(status) => status, + Err(error) => { + if self.poisoned.get() { + std::mem::forget(scratch); + return Err(error); + } + return combine(Err(error), scratch.release()); + } + }; + + let operation = (|| { + status.copy_from(&[0; 4])?; + let kernels = { + let guard = self.enter()?; + let kernels = match self.q5_kernels() { + Ok(kernels) => kernels, + Err(error) => return combine(Err(error), guard.finish()), + }; + combine(Ok(kernels), guard.finish())? + }; + + let mut quant_arguments = ffi::Q8QuantizeArguments::new( + handles[1], + scratch.handle.ok_or(Error::ContextPoisoned)?, + status.handle.ok_or(Error::ContextPoisoned)?, + shape.columns, + ); + let quant_guard = self.enter()?; + let quantize = self.driver.api.launch_q8_quantize( + kernels.quantize, + shape.quant_grid, + &mut quant_arguments, + ); + self.complete_launch(quantize, quant_arguments, quant_guard)?; + + let mut native_status = [0u8; 4]; + status.copy_to(&mut native_status)?; + if u32::from_le_bytes(native_status) != 0 { + return Err(Error::InvalidQ8Activation); + } + + let mut project_arguments = ffi::Q5ProjectionArguments::new( + handles[0], + scratch.handle.ok_or(Error::ContextPoisoned)?, + handles[2], + shape.rows, + shape.columns, + ); + let project_guard = self.enter()?; + let project = self.driver.api.launch_q5_projection( + kernels.project, + shape.projection_grid, + &mut project_arguments, + ); + self.complete_launch(project, project_arguments, project_guard) + })(); + + self.release_quantized_temporaries(operation, scratch, status) + } + + /// Project one resident F32 activation through row-major Q6_K weights. + /// Activations use the native Q8_1 block and reduction contract. + pub fn q6_k_q8_1( + &self, + weights: &DeviceBuffer<'_>, + activation: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + dimensions: Q6KProjectionShape, + ) -> Result<()> { + let (shape, handles, temporary_bytes) = + self.q6_k_admission(weights, activation, output, dimensions)?; + + // Charge the complete scratch/status requirement before native mutation. + let total = self + .allocated + .get() + .checked_add(temporary_bytes) + .ok_or(Error::BudgetExceeded)?; + if total > self.budget { + return Err(Error::BudgetExceeded); + } + + let scratch = self.allocate(shape.scratch_bytes)?; + let mut status = match self.allocate(4) { + Ok(status) => status, + Err(error) => { + if self.poisoned.get() { + std::mem::forget(scratch); + return Err(error); + } + return combine(Err(error), scratch.release()); + } + }; + + let operation = (|| { + status.copy_from(&[0; 4])?; + let kernels = { + let guard = self.enter()?; + let kernels = match self.q6_kernels() { + Ok(kernels) => kernels, + Err(error) => return combine(Err(error), guard.finish()), + }; + combine(Ok(kernels), guard.finish())? + }; + + let mut quant_arguments = ffi::Q8QuantizeArguments::new( + handles[1], + scratch.handle.ok_or(Error::ContextPoisoned)?, + status.handle.ok_or(Error::ContextPoisoned)?, + shape.columns, + ); + let quant_guard = self.enter()?; + let quantize = self.driver.api.launch_q8_quantize( + kernels.quantize, + shape.quant_grid, + &mut quant_arguments, + ); + self.complete_launch(quantize, quant_arguments, quant_guard)?; + + let mut native_status = [0u8; 4]; + status.copy_to(&mut native_status)?; + if u32::from_le_bytes(native_status) != 0 { + return Err(Error::InvalidQ8Activation); + } + + let mut project_arguments = ffi::Q6ProjectionArguments::new( + handles[0], + scratch.handle.ok_or(Error::ContextPoisoned)?, + handles[2], + shape.rows, + shape.columns, + ); + let project_guard = self.enter()?; + let project = self.driver.api.launch_q6_projection( + kernels.project, + shape.projection_grid, + &mut project_arguments, + ); + self.complete_launch(project, project_arguments, project_guard) + })(); + + self.release_quantized_temporaries(operation, scratch, status) + } + + /// Project one resident activation using a closed packed format/role. + /// Unintegrated formats refuse before any native mutation. Output is usable + /// only after successful synchronized return, never after a partial failure. + pub fn project_q8_1( + &self, + weights: &DeviceBuffer<'_>, + activation: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + spec: ProjectionSpec, + ) -> Result<()> { + self.project_q8_1_weight(NativeWeights::Raw(weights), activation, output, spec) + } + fn project_q8_1_weight( + &self, + weights: NativeWeights<'_, '_>, + activation: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + spec: ProjectionSpec, + ) -> Result<()> { + let (shape, handles, temporary_bytes) = + self.projection_admission_weight(weights, activation, output, spec)?; + + // Charge the complete scratch/status requirement before native mutation. + let total = self + .allocated + .get() + .checked_add(temporary_bytes) + .ok_or(Error::BudgetExceeded)?; + if total > self.budget { + return Err(Error::BudgetExceeded); + } + + let scratch = self.allocate(shape.scratch_bytes)?; + let mut status = match self.allocate(4) { + Ok(status) => status, + Err(error) => { + if self.poisoned.get() { + std::mem::forget(scratch); + return Err(error); + } + return combine(Err(error), scratch.release()); + } + }; + + let operation = (|| { + status.copy_from(&[0; 4])?; + let kernels = { + let guard = self.enter()?; + let kernels = match self.common_kernels(spec.kind) { + Ok(kernels) => kernels, + Err(error) => return combine(Err(error), guard.finish()), + }; + combine(Ok(kernels), guard.finish())? + }; + + let mut quant_arguments = ffi::Q8QuantizeArguments::new( + handles[1], + scratch.handle.ok_or(Error::ContextPoisoned)?, + status.handle.ok_or(Error::ContextPoisoned)?, + shape.columns, + ); + let quant_guard = self.enter()?; + let quantize = self.driver.api.launch_q8_quantize( + kernels.0, + shape.quant_grid, + &mut quant_arguments, + ); + self.complete_launch(quantize, quant_arguments, quant_guard)?; + + let mut native_status = [0u8; 4]; + status.copy_to(&mut native_status)?; + if u32::from_le_bytes(native_status) != 0 { + return Err(Error::InvalidQ8Activation); + } + + let mut project_arguments = ffi::ProjectionArguments::new( + handles[0], + scratch.handle.ok_or(Error::ContextPoisoned)?, + handles[2], + shape.rows, + shape.columns, + ); + let project_guard = self.enter()?; + let project = self.driver.api.launch_projection( + kernels.1, + shape.projection_grid, + &mut project_arguments, + ); + self.complete_launch(project, project_arguments, project_guard) + })(); + + self.release_quantized_temporaries(operation, scratch, status) + } + + /// Prepare exactly 2560 F32 values with the existing native quantizer. + /// Success attests synchronized completion, restored context and status0. + pub fn prepare_routed_gate_up_q8<'context>( + &'context self, + activation: &'context DeviceBuffer<'context>, + ) -> Result> { + if self.poisoned.get() || self.handle.is_none() { + return Err(Error::ContextPoisoned); + } + if !std::ptr::eq(self, activation.context) { + return Err(Error::ContextMismatch); + } + let source = activation.handle.ok_or(Error::ContextPoisoned)?; + if activation.bytes != 10240 { + return Err(Error::InvalidProjectionShape); + } + source.validate_projection_extent(10240, 4)?; + let total = self + .allocated + .get() + .checked_add(2884) + .ok_or(Error::BudgetExceeded)?; + if total > self.budget { + return Err(Error::BudgetExceeded); + } + let scratch = self.allocate(2880)?; + let mut status = match self.allocate(4) { + Ok(status) => status, + Err(error) => { + if self.poisoned.get() { + std::mem::forget(scratch); + return Err(error); + } + return combine(Err(error), scratch.release()); + } + }; + let operation = (|| { + let quantized = scratch.handle.ok_or(Error::ContextPoisoned)?; + let status_handle = status.handle.ok_or(Error::ContextPoisoned)?; + quantized.validate_projection_extent(2880, 4)?; + status_handle.validate_projection_extent(4, 4)?; + if quantized.overlaps(2880, source, 10240) + || status_handle.overlaps(4, source, 10240) + || status_handle.overlaps(4, quantized, 2880) + { + return Err(Error::OutputAliasesInput); + } + status.copy_from(&[0; 4])?; + let kernel = { + let guard = self.enter()?; + let kernel = match self.fixed_kernel(FixedOperation::CommonQuantize) { + Ok(kernel) => kernel, + Err(error) => return combine(Err(error), guard.finish()), + }; + combine(Ok(kernel), guard.finish())? + }; + let mut arguments = + ffi::Q8QuantizeArguments::new(source, quantized, status_handle, 2560); + let guard = self.enter()?; + let launch = self + .driver + .api + .launch_q8_quantize(kernel.function, 10, &mut arguments); + self.complete_launch(launch, arguments, guard)?; + let mut native_status = [0u8; 4]; + status.copy_to(&mut native_status)?; + if u32::from_le_bytes(native_status) != 0 { + return Err(Error::InvalidQ8Activation); + } + Ok(()) + })(); + if let Err(error) = operation { + return self.release_quantized_temporaries(Err(error), scratch, status); + } + // The status owner must be reclaimed successfully before publishing + // the ready activation. Cleanup failure cannot mint a success owner. + if let Err(error) = status.release() { + if self.poisoned.get() { + std::mem::forget(scratch); + return Err(error); + } + return combine(Err(error), scratch.release()); + } + Ok(RoutedGateUpQ8 { + activation, + scratch: Some(scratch), + }) + } + + /// Project a fixed routed 640x2560 Gate/Up matrix using prepared Q8_1. + /// No activation quantization or temporary device allocation is repeated. + pub fn project_routed_gate_up_prepared( + &self, + weights: &DeviceBuffer<'_>, + prepared: &RoutedGateUpQ8<'_>, + output: &mut DeviceBuffer<'_>, + format: RoutedFormat, + ) -> Result<()> { + self.project_routed_gate_up_prepared_weight( + NativeWeights::Raw(weights), + prepared, + output, + format, + ) + } + fn project_routed_gate_up_prepared_weight( + &self, + weight_owner: NativeWeights<'_, '_>, + prepared: &RoutedGateUpQ8<'_>, + output: &mut DeviceBuffer<'_>, + format: RoutedFormat, + ) -> Result<()> { + let weights = weight_owner.buffer()?; + if self.poisoned.get() || self.handle.is_none() { + return Err(Error::ContextPoisoned); + } + let scratch = prepared.scratch.as_ref().ok_or(Error::ContextPoisoned)?; + for buffer in [weights, prepared.activation, scratch, output] { + if !std::ptr::eq(self, buffer.context) { + return Err(Error::ContextMismatch); + } + if buffer.handle.is_none() { + return Err(Error::ContextPoisoned); + } + } + if !matches!( + format, + RoutedFormat::IQ3_XXS + | RoutedFormat::IQ3_S + | RoutedFormat::IQ2_S + | RoutedFormat::IQ4_XS + ) { + return Err(Error::UnsupportedProjection); + } + let kind = ProjectionKind::Routed(format); + if !ffi::projection_available(kind) { + return Err(Error::UnsupportedProjection); + } + let shape = projection_shape(ProjectionSpec { + kind, + rows: 640, + columns: 2560, + })?; + weight_owner.validate( + ProjectionSpec { + kind, + rows: 640, + columns: 2560, + }, + shape.weight_bytes, + )?; + if prepared.activation.bytes != shape.activation_bytes + || scratch.bytes != shape.scratch_bytes + || output.bytes != shape.output_bytes + { + return Err(Error::InvalidProjectionShape); + } + let weight = weights.handle.ok_or(Error::ContextPoisoned)?; + let original = prepared.activation.handle.ok_or(Error::ContextPoisoned)?; + let quantized = scratch.handle.ok_or(Error::ContextPoisoned)?; + let out = output.handle.ok_or(Error::ContextPoisoned)?; + projection_ranges(kind, &shape, [weight, original, out])?; + if out.overlaps(shape.output_bytes, weight, weights.bytes) { + return Err(Error::OutputAliasesInput); + } + quantized.validate_projection_extent(shape.scratch_bytes, 4)?; + if out.overlaps(shape.output_bytes, quantized, shape.scratch_bytes) { + return Err(Error::OutputAliasesInput); + } + // Private construction used this Context's exact CommonQuantize slot. + // The immutable Context borrow prevents teardown/profile replacement. + if self.common_quantizer.get().is_none() { + return Err(Error::InvalidDriverValue("prepared quantizer cache")); + } + // All device storage is already charged. No unused scratch/status + // precharge is imposed on each prepared projection. + if self.allocated.get() > self.budget { + return Err(Error::BudgetExceeded); + } + let kernel = { + let guard = self.enter()?; + let kernels = match self.common_kernels(kind) { + Ok(kernels) => kernels, + Err(error) => return combine(Err(error), guard.finish()), + }; + combine(Ok(kernels.1), guard.finish())? + }; + let mut arguments = + ffi::ProjectionArguments::new(weight, quantized, out, shape.rows, shape.columns); + let guard = self.enter()?; + let launch = + self.driver + .api + .launch_projection(kernel, shape.projection_grid, &mut arguments); + self.complete_launch(launch, arguments, guard) + } + + fn projection_admission_weight( + &self, + weight_owner: NativeWeights<'_, '_>, + activation: &DeviceBuffer<'_>, + output: &DeviceBuffer<'_>, + spec: ProjectionSpec, + ) -> Result<(ProjectionShape, [ffi::BufferHandle; 3], usize)> { + let weights = weight_owner.buffer()?; + if self.poisoned.get() || self.handle.is_none() { + return Err(Error::ContextPoisoned); + } + for buffer in [weights, activation, output] { + if !std::ptr::eq(self, buffer.context) { + return Err(Error::ContextMismatch); + } + if buffer.handle.is_none() { + return Err(Error::ContextPoisoned); + } + } + if !ffi::projection_available(spec.kind) { + return Err(Error::UnsupportedProjection); + } + let shape = projection_shape(spec)?; + weight_owner.validate(spec, shape.weight_bytes)?; + if activation.bytes != shape.activation_bytes || output.bytes != shape.output_bytes { + return Err(Error::InvalidProjectionShape); + } + let handles = [ + weights.handle.ok_or(Error::ContextPoisoned)?, + activation.handle.ok_or(Error::ContextPoisoned)?, + output.handle.ok_or(Error::ContextPoisoned)?, + ]; + projection_ranges(spec.kind, &shape, handles)?; + if handles[2].overlaps(output.bytes, handles[0], weights.bytes) { + return Err(Error::OutputAliasesInput); + } + let temporary_bytes = shape.temporary_bytes; + let total = self + .allocated + .get() + .checked_add(temporary_bytes) + .ok_or(Error::BudgetExceeded)?; + if total > self.budget { + return Err(Error::BudgetExceeded); + } + Ok((shape, handles, temporary_bytes)) + } + fn q5_k_admission( + &self, + weights: &DeviceBuffer<'_>, + activation: &DeviceBuffer<'_>, + output: &DeviceBuffer<'_>, + dimensions: Q5KProjectionShape, + ) -> Result<(Q5KShape, [ffi::BufferHandle; 3], usize)> { + if self.poisoned.get() || self.handle.is_none() { + return Err(Error::ContextPoisoned); + } + if !std::ptr::eq(self, weights.context) + || !std::ptr::eq(self, activation.context) + || !std::ptr::eq(self, output.context) + { + return Err(Error::ContextMismatch); + } + let shape = q5_k_shape(dimensions.rows, dimensions.columns)?; + if weights.bytes != shape.weight_bytes + || activation.bytes != shape.activation_bytes + || output.bytes != shape.output_bytes + { + return Err(Error::InvalidQ5KProjectionShape); + } + let weight = weights.handle.ok_or(Error::ContextPoisoned)?; + let activation = activation.handle.ok_or(Error::ContextPoisoned)?; + let output = output.handle.ok_or(Error::ContextPoisoned)?; + if output == weight || output == activation { + return Err(Error::OutputAliasesInput); + } + weight + .validate_extent(shape.weight_bytes) + .map_err(|_| Error::InvalidQ5KProjectionShape)?; + activation + .validate_extent(shape.activation_bytes) + .map_err(|_| Error::InvalidQ5KProjectionShape)?; + output + .validate_extent(shape.output_bytes) + .map_err(|_| Error::InvalidQ5KProjectionShape)?; + let temporary_bytes = shape + .scratch_bytes + .checked_add(4) + .ok_or(Error::BudgetExceeded)?; + Ok((shape, [weight, activation, output], temporary_bytes)) + } + + fn q6_k_admission( + &self, + weights: &DeviceBuffer<'_>, + activation: &DeviceBuffer<'_>, + output: &DeviceBuffer<'_>, + dimensions: Q6KProjectionShape, + ) -> Result<(Q6KShape, [ffi::BufferHandle; 3], usize)> { + if self.poisoned.get() || self.handle.is_none() { + return Err(Error::ContextPoisoned); + } + if !std::ptr::eq(self, weights.context) + || !std::ptr::eq(self, activation.context) + || !std::ptr::eq(self, output.context) + { + return Err(Error::ContextMismatch); + } + let shape = q6_k_shape(dimensions.rows, dimensions.columns)?; + if weights.bytes != shape.weight_bytes + || activation.bytes != shape.activation_bytes + || output.bytes != shape.output_bytes + { + return Err(Error::InvalidQ6KProjectionShape); + } + let weight = weights.handle.ok_or(Error::ContextPoisoned)?; + let activation = activation.handle.ok_or(Error::ContextPoisoned)?; + let output = output.handle.ok_or(Error::ContextPoisoned)?; + if output == weight || output == activation { + return Err(Error::OutputAliasesInput); + } + weight + .validate_extent(shape.weight_bytes) + .map_err(|_| Error::InvalidQ6KProjectionShape)?; + activation + .validate_extent(shape.activation_bytes) + .map_err(|_| Error::InvalidQ6KProjectionShape)?; + output + .validate_extent(shape.output_bytes) + .map_err(|_| Error::InvalidQ6KProjectionShape)?; + let temporary_bytes = shape + .scratch_bytes + .checked_add(4) + .ok_or(Error::BudgetExceeded)?; + Ok((shape, [weight, activation, output], temporary_bytes)) + } + + fn release_quantized_temporaries( + &self, + operation: Result, + scratch: DeviceBuffer<'_>, + status: DeviceBuffer<'_>, + ) -> Result { + if self.poisoned.get() { + // Unknown completion/restoration means these allocations and + // their context accounting must outlive this call. + std::mem::forget(scratch); + std::mem::forget(status); + return operation; + } + let status_free = status.release(); + if self.poisoned.get() { + std::mem::forget(scratch); + return combine(operation, status_free); + } + combine(combine(operation, status_free), scratch.release()) + } + fn matvec_admission( + &self, + buffers: [&DeviceBuffer<'_>; 3], + rows: usize, + columns: usize, + ) -> Result<(MatvecShape, [ffi::BufferHandle; 3])> { + let [matrix, vector, output] = buffers; + if self.poisoned.get() || self.handle.is_none() { + return Err(Error::ContextPoisoned); + } + if !std::ptr::eq(self, matrix.context) + || !std::ptr::eq(self, vector.context) + || !std::ptr::eq(self, output.context) + { + return Err(Error::ContextMismatch); + } + let shape = matvec_shape(rows, columns)?; + if matrix.bytes != shape.matrix_bytes + || vector.bytes != shape.vector_bytes + || output.bytes != shape.output_bytes + { + return Err(Error::InvalidMatvecShape); + } + let handles = matvec_allocations(matrix.handle, vector.handle, output.handle, &shape)?; + Ok((shape, [handles.0, handles.1, handles.2])) + } + fn kernel_slot(&self, operation: FixedOperation) -> &Cell> { + match operation { + FixedOperation::VectorAdd => &self.vector_add_kernel, + FixedOperation::GrReadFinite => &self.gr_read_guard_kernel, + FixedOperation::Matvec => &self.matvec_kernel, + FixedOperation::CommonQuantize => &self.common_quantizer, + FixedOperation::GroupedIq3 => &self.grouped_iq3, + FixedOperation::GroupedIq2 => &self.grouped_iq2, + FixedOperation::GroupedIq3S => &self.grouped_iq3_s, + FixedOperation::GroupedIq4Xs => &self.grouped_iq4_xs, + FixedOperation::GroupedIq3SNc4 => &self.grouped_iq3_s_nc4, + FixedOperation::GroupedIq4XsNc4 => &self.grouped_iq4_xs_nc4, + FixedOperation::GroupedSwiglu => &self.grouped_swiglu, + FixedOperation::GroupedDownIq4 => &self.grouped_down_iq4, + FixedOperation::GroupedDownQ2 => &self.grouped_down_q2, + FixedOperation::Projection(_) => { + unreachable!("format modules publish all required entries atomically") + } + FixedOperation::Q5K | FixedOperation::Q5KQuantize | FixedOperation::Q5KProject => { + unreachable!("Q5_K kernels are cached as an atomic pair") + } + FixedOperation::Q6K | FixedOperation::Q6KQuantize | FixedOperation::Q6KProject => { + unreachable!("Q6_K kernels are cached as an atomic pair") + } + } + } + fn fixed_kernel(&self, operation: FixedOperation) -> Result { + let slot = self.kernel_slot(operation); + if let Some(kernel) = slot.get() { + return Ok(kernel); + } + let module = self.driver.api.load_fixed_module(operation)?; + match self.driver.api.fixed_function(module, operation) { + Ok(function) => { + let kernel = FixedKernel { module, function }; + slot.set(Some(kernel)); + Ok(kernel) + } + Err(error) => { + // Local usable handle consumed by this single unload attempt; + // no cache publishes a partial module or retries failed unload. + let cleanup = self.driver.api.unload(module); + if cleanup.is_err() { + self.poisoned.set(true); + std::mem::forget(Rc::clone(&self.driver.api)); + } + combine(Err(error), cleanup) + } + } + } + fn unload_kernel(&self, operation: FixedOperation) -> Result<()> { + // Consume BEFORE attempting unload; even an error can invalidate it. + let Some(kernel) = self.kernel_slot(operation).take() else { + return Ok(()); + }; + if self.poisoned.get() { + // An uncertain context may still own code from this module. + std::mem::forget(Rc::clone(&self.driver.api)); + return Ok(()); + } + let guard = match self.enter() { + Ok(guard) => guard, + Err(error) => { + self.poisoned.set(true); + return Err(error); + } + }; + let unload = self.driver.api.unload(kernel.module); + if unload.is_err() { + self.poisoned.set(true); + } + combine(unload, guard.finish()) + } + fn fixed_pair( + &self, + cache: &Cell>, + module_op: FixedOperation, + quantize_op: FixedOperation, + project_op: FixedOperation, + ) -> Result { + if let Some(kernels) = cache.get() { + return Ok(kernels); + } + let module = self.driver.api.load_fixed_module(module_op)?; + let quantize = match self.driver.api.fixed_function(module, quantize_op) { + Ok(function) => function, + Err(error) => { + let cleanup = self.driver.api.unload(module); + if cleanup.is_err() { + self.poisoned.set(true); + std::mem::forget(Rc::clone(&self.driver.api)); + } + return combine(Err(error), cleanup); + } + }; + let project = match self.driver.api.fixed_function(module, project_op) { + Ok(function) => function, + Err(error) => { + let cleanup = self.driver.api.unload(module); + if cleanup.is_err() { + self.poisoned.set(true); + std::mem::forget(Rc::clone(&self.driver.api)); + } + return combine(Err(error), cleanup); + } + }; + let kernels = FixedPairKernels { + module, + quantize, + project, + }; + // Publish only after both closed fixed entries resolve successfully. + cache.set(Some(kernels)); + Ok(kernels) + } + fn q5_kernels(&self) -> Result { + self.fixed_pair( + &self.q5_k_kernel, + FixedOperation::Q5K, + FixedOperation::Q5KQuantize, + FixedOperation::Q5KProject, + ) + } + fn q6_kernels(&self) -> Result { + self.fixed_pair( + &self.q6_k_kernel, + FixedOperation::Q6K, + FixedOperation::Q6KQuantize, + FixedOperation::Q6KProject, + ) + } + fn unload_pair(&self, cache: &Cell>) -> Result<()> { + let Some(kernels) = cache.take() else { + return Ok(()); + }; + if self.poisoned.get() { + // A failed completion makes module use uncertain; retain the + // Driver library with the intentionally abandoned module handle. + std::mem::forget(Rc::clone(&self.driver.api)); + return Ok(()); + } + let guard = match self.enter() { + Ok(guard) => guard, + Err(error) => { + self.poisoned.set(true); + return Err(error); + } + }; + let unload = self.driver.api.unload(kernels.module); + if unload.is_err() { + self.poisoned.set(true); + std::mem::forget(Rc::clone(&self.driver.api)); + } + combine(unload, guard.finish()) + } + fn common_kernels( + &self, + kind: ProjectionKind, + ) -> Result<(ffi::FunctionHandle, ffi::FunctionHandle)> { + let quantizer = self.fixed_kernel(FixedOperation::CommonQuantize)?; + let slot = &self.projection_kernels[kind.layout().0]; + let kernels = if let Some(kernels) = slot.get() { + kernels + } else { + let module = self + .driver + .api + .load_fixed_module(FixedOperation::Projection(kind))?; + let load = (|| { + let (dense, routed) = kind.required_modes(); + let dense = dense + .map(|k| { + self.driver + .api + .fixed_function(module, FixedOperation::Projection(k)) + }) + .transpose()?; + let routed = routed + .map(|k| { + self.driver + .api + .fixed_function(module, FixedOperation::Projection(k)) + }) + .transpose()?; + Ok(ProjectionKernels { + module, + dense, + routed, + }) + })(); + match load { + Ok(kernels) => { + slot.set(Some(kernels)); + kernels + } + Err(error) => { + let cleanup = self.driver.api.unload(module); + if cleanup.is_err() { + self.poisoned.set(true); + std::mem::forget(Rc::clone(&self.driver.api)); + } + return combine(Err(error), cleanup); + } + } + }; + let project = match kind { + ProjectionKind::Dense(_) => kernels.dense, + ProjectionKind::Routed(_) => kernels.routed, + } + .ok_or(Error::InvalidDriverValue("fixed projection cache"))?; + Ok((quantizer.function, project)) + } + fn unload_projections(&self) -> Result<()> { + let mut result = self.unload_kernel(FixedOperation::CommonQuantize); + if result.is_err() { + std::mem::forget(Rc::clone(&self.driver.api)); + } + for slot in &self.projection_kernels { + let Some(kernels) = slot.take() else { + continue; + }; + if self.poisoned.get() { + std::mem::forget(Rc::clone(&self.driver.api)); + continue; + } + let guard = match self.enter() { + Ok(guard) => guard, + Err(error) => { + self.poisoned.set(true); + std::mem::forget(Rc::clone(&self.driver.api)); + result = combine(result, Err(error)); + continue; + } + }; + let unload = combine(self.driver.api.unload(kernels.module), guard.finish()); + if unload.is_err() { + self.poisoned.set(true); + std::mem::forget(Rc::clone(&self.driver.api)); + } + result = combine(result, unload); + } + result + } + fn unload_q5_kernels(&self) -> Result<()> { + self.unload_pair(&self.q5_k_kernel) + } + fn unload_q6_kernels(&self) -> Result<()> { + self.unload_pair(&self.q6_k_kernel) + } + /// Consume the context and report destruction failure. Borrows prevent + /// closing a context while a device buffer can still be used. + pub fn close(mut self) -> Result<()> { + self.destroy() + } + /// The shared verify-window modules: unloaded (current context) once no bank holds them; a module a live + /// bank still shares is left to that bank's own unload. + fn unload_window_modules(&mut self) -> Result<()> { + let modules = std::mem::take(self.window_modules.get_mut()); + if modules.is_empty() { + return Ok(()); + } + if self.is_poisoned() { + std::mem::forget(modules); + return Err(Error::ContextPoisoned); + } + let guard = self.enter()?; + let mut result = Ok(()); + for (_, module, _) in modules { + if let Ok(module) = Rc::try_unwrap(module) { + result = combine(result, module.close()); + } + } + combine(result, guard.finish()) + } + fn destroy(&mut self) -> Result<()> { + // Fixed teardown order; shared poison suppresses the second native unload. + let grouped_down_unload = combine( + combine( + self.unload_kernel(FixedOperation::GroupedSwiglu), + self.unload_kernel(FixedOperation::GroupedDownIq4), + ), + self.unload_kernel(FixedOperation::GroupedDownQ2), + ); + let unload = combine( + grouped_down_unload, + combine( + combine( + combine( + combine( + combine( + combine( + combine( + self.unload_kernel(FixedOperation::GroupedIq3), + self.unload_kernel(FixedOperation::GroupedIq2), + ), + self.unload_kernel(FixedOperation::GroupedIq3S), + ), + self.unload_kernel(FixedOperation::GroupedIq4Xs), + ), + self.unload_kernel(FixedOperation::GroupedIq3SNc4), + ), + self.unload_kernel(FixedOperation::GroupedIq4XsNc4), + ), + combine( + combine(self.unload_projections(), self.unload_qwen_kernels()), + self.unload_kernel(FixedOperation::GrReadFinite), + ), + ), + combine( + combine( + self.unload_kernel(FixedOperation::VectorAdd), + self.unload_kernel(FixedOperation::Matvec), + ), + combine(self.unload_q5_kernels(), self.unload_q6_kernels()), + ), + ), + ); + let unload = combine(unload, self.unload_kar_levels()); + let unload = combine(unload, self.unload_experimental()); + let unload = combine(unload, self.unload_window_modules()); + if let Some(handle) = self.handle.take() { + // cuCtxDestroy accepts an owned non-current context. Pushing here + // would add a stack entry for a handle invalidated by destruction. + let result = self.driver.api.destroy(handle); + if result.is_err() { + std::mem::forget(Rc::clone(&self.driver.api)); + } + if result.is_ok() { + self.allocated.set(0); + } + combine(unload, result) + } else { + unload + } + } +} +impl Drop for Context<'_> { + fn drop(&mut self) { + let _ = self.destroy(); + } +} + +/// Push/pop balance with fallible explicit finish and nonpanicking fallback. +struct CurrentGuard<'context, 'driver> { + context: &'context Context<'driver>, + active: bool, +} +impl CurrentGuard<'_, '_> { + fn finish(mut self) -> Result<()> { + self.restore() + } + fn restore(&mut self) -> Result<()> { + if !self.active { + return Ok(()); + } + self.active = false; + let result = self.context.driver.api.pop().and_then(|popped| { + if Some(popped) == self.context.handle { + Ok(()) + } else { + Err(Error::UnexpectedContext) + } + }); + if result.is_err() { + self.context.poisoned.set(true); + } + result + } +} +impl Drop for CurrentGuard<'_, '_> { + fn drop(&mut self) { + let _ = self.restore(); + } +} + +/// An exact nonempty byte allocation borrowing its owning context. +pub struct DeviceBuffer<'context> { + context: &'context Context<'context>, + handle: Option, + bytes: usize, + _thread: PhantomData>, + /// A non-owning alias of memory somebody else owns (a sub-range of a slab, mapped host memory): dropping or releasing it + /// frees nothing and is never charged to the context. Its owner must outlive every use. + borrowed: bool, +} +impl DeviceBuffer<'_> { + pub fn len(&self) -> usize { + self.bytes + } + pub fn is_empty(&self) -> bool { + false + } + fn staging(&self, actual: usize) -> Result> { + if actual != self.bytes { + return Err(Error::ShapeMismatch { + expected: self.bytes, + actual, + }); + } + if self.context.poisoned.get() { + return Err(Error::ContextPoisoned); + } + let mut staging = Vec::new(); + staging + .try_reserve_exact(self.bytes) + .map_err(|_| Error::HostAllocation)?; + staging.resize(self.bytes, 0); + Ok(staging) + } + pub fn copy_from(&mut self, input: &[u8]) -> Result<()> { + let mut staging = self.staging(input.len())?; + staging.copy_from_slice(input); + self.copy_staged(staging, false).map(|_| ()) + } + /// Consume genuine whole-buffer host staging without an intermediate clone. + /// Byte ownership is not a source, finite or device-completion certificate. + pub fn copy_from_owned(&mut self, input: Vec) -> Result<()> { + // Preserve the original staging() shape-before-poison admission order. + if input.len() != self.bytes { + return Err(Error::ShapeMismatch { + expected: self.bytes, + actual: input.len(), + }); + } + if self.context.poisoned.get() { + return Err(Error::ContextPoisoned); + } + // Exactly the existing attempted-copy/synchronize/restore and retained + // staging rule. No source storage is released while work is uncertain. + self.copy_staged(input, false).map(|_| ()) + } + /// Copy a nonempty checked subspan. Owned staging remains alive through + /// synchronization, with the same poisoning/leak rule as whole-buffer copies. + pub fn copy_from_range(&mut self, offset: usize, input: &[u8]) -> Result<()> { + self.copy_from_range_shared(offset, input) + } + /// The same transfer through a shared borrow, for arenas their single + /// owner thread shares between read-only views (`Rc`). + /// Ranges are checked and the copy is synchronised exactly like + /// `copy_from_range`; callers keep writes to disjoint spans. + pub(crate) fn copy_from_range_shared(&self, offset: usize, input: &[u8]) -> Result<()> { + if self.context.poisoned.get() { + return Err(Error::ContextPoisoned); + } + let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan( + self.bytes, + offset, + input.len(), + )?; + let mut staging = Vec::new(); + staging + .try_reserve_exact(input.len()) + .map_err(|_| Error::HostAllocation)?; + staging.extend_from_slice(input); + let guard = self.context.enter()?; + let copy = self.context.driver.api.copy_from(handle, &staging); + let sync = self.context.driver.api.synchronize(); + if sync.is_err() { + self.context.poisoned.set(true); + std::mem::forget(staging); + return combine(combine(copy, sync), guard.finish()); + } + combine(copy, guard.finish()) + } + /// Read back a nonempty checked subspan. Owned staging stays alive through + /// synchronization with the same poisoning/leak rule as whole-buffer reads; + /// a failed synchronization never returns its bytes. + pub fn copy_to_range(&self, offset: usize, output: &mut [u8]) -> Result<()> { + if self.context.poisoned.get() { + return Err(Error::ContextPoisoned); + } + let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan( + self.bytes, + offset, + output.len(), + )?; + let mut staging = Vec::new(); + staging + .try_reserve_exact(output.len()) + .map_err(|_| Error::HostAllocation)?; + staging.resize(output.len(), 0); + let guard = self.context.enter()?; + let copy = self.context.driver.api.copy_to(handle, &mut staging); + let sync = self.context.driver.api.synchronize(); + if sync.is_err() { + self.context.poisoned.set(true); + std::mem::forget(staging); + return combine(combine(copy, sync), guard.finish()); + } + combine(copy, guard.finish())?; + output.copy_from_slice(&staging); + Ok(()) + } + pub fn copy_to(&self, output: &mut [u8]) -> Result<()> { + let staging = self.staging(output.len())?; + let staging = self.copy_staged(staging, true)?; + output.copy_from_slice(&staging); + Ok(()) + } + /// Return the completed whole-buffer readback without a second host copy. + /// The staging remains owned through the same synchronization and poison + /// handling as `copy_to`; a failed synchronization never returns its bytes. + pub fn copy_to_owned(&self, expected_bytes: usize) -> Result> { + let staging = self.staging(expected_bytes)?; + self.copy_staged(staging, true) + } + fn copy_staged(&self, mut staging: Vec, to_host: bool) -> Result> { + let handle = self.handle.ok_or(Error::ContextPoisoned)?; + let guard = self.context.enter()?; + let copy = if to_host { + self.context.driver.api.copy_to(handle, &mut staging) + } else { + self.context.driver.api.copy_from(handle, &staging) + }; + // Even copy errors can report earlier asynchronous work. Synchronize + // on every attempted copy before considering the staging reclaimable. + let sync = self.context.driver.api.synchronize(); + if sync.is_err() { + self.context.poisoned.set(true); + // CUDA may still reference these owned host bytes. A poisoned + // context admits no further copy, limiting this leak to one buffer + // (at most its context budget), regardless of caller lifetimes. + std::mem::forget(staging); + return combine(combine(copy, sync), guard.finish()).map(|()| Vec::new()); + } + combine(copy, guard.finish())?; + Ok(staging) + } + pub fn release(mut self) -> Result<()> { + self.free() + } + fn free(&mut self) -> Result<()> { + let Some(handle) = self.handle.take() else { + return Ok(()); + }; + if self.borrowed { + return Ok(()); + } + vram_ledger::note_free(handle.qwen_address()); + if compute_drain::background() != 0 && !self.context.poisoned.get() { + // a chunk expert stream is in flight: do not synchronize the device now + return self.context.defer_free(handle, self.bytes); + } + let guard = self.context.enter()?; + let free = self.context.driver.api.free(handle); + if free.is_ok() { + self.context + .allocated + .set(self.context.allocated.get() - self.bytes); + } + combine(free, guard.finish()) + } +} +impl Drop for DeviceBuffer<'_> { + fn drop(&mut self) { + let _ = self.free(); + } +} + +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[path = "moe_down_pack_gpu.rs"] +mod moe_down_pack_gpu_tests; + +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[path = "ple_value_full_gpu.rs"] +mod ple_value_full_gpu_tests; + +#[cfg(test)] +mod tests { + #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + #[test] + #[ignore = "Root-only original-first owned whole-buffer readback proof"] + fn owned_readback_original_first_preserves_gdn_extents_and_raw_words() { + let driver = super::Driver::load().unwrap(); + let context = driver + .device(0) + .unwrap() + .create_context(16 * 1024 * 1024) + .unwrap(); + let mut exact_bytes = 0usize; + let mut bounds = 0usize; + // Full real recurrence state, convolution history and readout extents. + for size in [3_145_728usize, 122_880, 24_576] { + let mut buffer = context.allocate(size).unwrap(); + for round in 0..2u32 { + let words = [ + 0u32, + 0x8000_0000, + 0x3f80_0000, + 0xbf80_0000, + 0x7f80_0000, + 0xff80_0000, + 0x7fc0_0101, + 1, + ]; + let mut source = Vec::with_capacity(size); + for i in 0..size / 4 { + let word = if i < words.len() { + words[i] + } else { + (i as u32).wrapping_mul(0x9e37_79b9).wrapping_add(round) + }; + source.extend_from_slice(&word.to_le_bytes()); + } + buffer.copy_from(&source).unwrap(); + let mut original = vec![0; size]; + buffer.copy_to(&mut original).unwrap(); + assert_eq!(original, source); + let owned = buffer.copy_to_owned(size).unwrap(); + assert_eq!(owned, original); + // The downstream original LE conversion preserves all bits, + // including signed zero and nonfinite values (later rejected + // by the unchanged GDN finite guard). + for (a, b) in original + .as_chunks::<4>() + .0 + .iter() + .zip(owned.as_chunks::<4>().0) + { + assert_eq!( + f32::from_le_bytes(*a).to_bits(), + f32::from_le_bytes(*b).to_bits() + ); + } + exact_bytes += size; + for invalid in [0, size - 1, size + 1] { + assert!(matches!(buffer.copy_to_owned(invalid), + Err(super::Error::ShapeMismatch { expected, actual }) + if expected == size && actual == invalid)); + bounds += 1; + } + assert_eq!(buffer.copy_to_owned(size).unwrap(), original); + exact_bytes += size; + } + buffer.release().unwrap(); + assert_eq!(context.allocated_bytes(), 0); + } + assert_eq!(exact_bytes, 13_172_736); + assert_eq!(bounds, 18); + assert_eq!(context.allocated_bytes(), 0); + context.close().unwrap(); + println!( + "owned_gdn_readback exact_bytes={exact_bytes} bounds={bounds} original_first=true allocated=0 raw_nonfinite_preserved=true" + ); + } + + #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + #[test] + #[ignore = "Root-only installed driver partial-copy guard proof"] + fn checked_subspan_real_copy_preserves_untouched_bytes() { + let driver = super::Driver::load().unwrap(); + let context = driver.device(0).unwrap().create_context(65536).unwrap(); + let mut buffer = context.allocate(1024).unwrap(); + buffer.copy_from(&[0x5a; 1024]).unwrap(); + buffer.copy_from_range(255, &[0x73; 513]).unwrap(); + let mut out = [0; 1024]; + buffer.copy_to(&mut out).unwrap(); + assert_eq!(&out[..255], &[0x5a; 255]); + assert_eq!(&out[255..768], &[0x73; 513]); + assert_eq!(&out[768..], &[0x5a; 256]); + assert!(buffer.copy_from_range(1023, &[1, 2]).is_err()); + assert!(buffer.copy_from_range(0, &[]).is_err()); + let mut after = [0; 1024]; + buffer.copy_to(&mut after).unwrap(); + assert_eq!(out, after); + buffer.release().unwrap(); + assert_eq!(context.allocated_bytes(), 0); + context.close().unwrap(); + } + + use super::*; + #[test] + fn sizes_and_error_composition() { + assert_eq!(valid_size(0), Err(Error::InvalidSize)); + assert_eq!(valid_size(usize::MAX), Err(Error::InvalidSize)); + assert_eq!(valid_size(1), Ok(())); + assert_eq!( + combine::<()>(Err(Error::InvalidSize), Err(Error::UnexpectedContext)), + Err(Error::Multiple { + primary: Box::new(Error::InvalidSize), + secondary: Box::new(Error::UnexpectedContext) + }) + ); + } + #[test] + fn vector_count_geometry_boundaries() { + for bytes in [0, 1, 3, 5, usize::MAX] { + assert!(vector_shape(bytes).is_err()); + } + for n in [1u32, 127, 128, 129, 1025, u32::MAX] { + let bytes = usize::try_from(u64::from(n) * 4).unwrap(); + assert_eq!( + vector_shape(bytes), + Ok((n, u32::try_from(u64::from(n).div_ceil(128)).unwrap())) + ); + } + assert!(vector_shape((u32::MAX as usize + 1) * 4).is_err()); + } + #[test] + fn matvec_shape_boundaries() { + for (m, n) in [ + (0, 1), + (1, 0), + (usize::MAX, 1), + (1, usize::MAX), + (u32::MAX as usize + 1, 1), + (1, u32::MAX as usize + 1), + (u32::MAX as usize, u32::MAX as usize), + ] { + assert_eq!(matvec_shape(m, n), Err(Error::InvalidMatvecShape)); + } + for m in [1u32, 127, 128, 129, 1025, u32::MAX] { + let shape = matvec_shape(m as usize, 1).unwrap(); + assert_eq!(shape.rows, m); + assert_eq!(shape.matrix_bytes, m as usize * 4); + assert_eq!(shape.output_bytes, m as usize * 4); + assert_eq!(shape.grid as u64, u64::from(m).div_ceil(128)); + } + let shape = matvec_shape(1, u32::MAX as usize).unwrap(); + assert_eq!(shape.columns, u32::MAX); + assert_eq!(shape.vector_bytes, u32::MAX as usize * 4); + let largest_columns = (isize::MAX as usize / 4) / u32::MAX as usize; + assert!(matvec_shape(u32::MAX as usize, largest_columns).is_ok()); + assert_eq!( + matvec_shape(u32::MAX as usize, largest_columns + 1), + Err(Error::InvalidMatvecShape) + ); + // Element count is deliberately not restricted to u32. + assert!(matvec_shape(65536, 65536).is_ok()); + } + #[test] + fn matvec_allocation_identity_and_absent_handles() { + let shape = matvec_shape(1, 1).unwrap(); + let h = |v| Some(ffi::BufferHandle::synthetic(v)); + for handles in [(h(4), h(8), h(4)), (h(4), h(8), h(8))] { + assert!(matches!( + matvec_allocations(handles.0, handles.1, handles.2, &shape), + Err(Error::OutputAliasesInput) + )); + } + for handles in [(None, h(8), h(12)), (h(4), None, h(12)), (h(4), h(8), None)] { + assert!(matches!( + matvec_allocations(handles.0, handles.1, handles.2, &shape), + Err(Error::ContextPoisoned) + )); + } + for handles in [ + (h(u64::MAX - 3), h(8), h(12)), + (h(4), h(u64::MAX - 3), h(12)), + (h(4), h(8), h(u64::MAX - 3)), + ] { + assert!(matches!( + matvec_allocations(handles.0, handles.1, handles.2, &shape), + Err(Error::InvalidMatvecShape) + )); + } + assert!(matvec_allocations(h(4), h(4), h(12), &shape).is_ok()); + } + #[cfg(not(feature = "cuda-driver"))] + #[test] + fn matvec_private_admission_refuses_without_cuda() { + let driver = Driver { + api: Rc::new(ffi::Api), + version: 0, + }; + let context = Context { + driver: &driver, + handle: None, + ordinal: 0, + budget: 64, + allocated: Cell::new(12), + poisoned: PoisonCell::new(false), + vector_add_kernel: Cell::new(None), + matvec_kernel: Cell::new(None), + q5_k_kernel: Cell::new(None), + q6_k_kernel: Cell::new(None), + common_quantizer: Cell::new(None), + grouped_iq3: Cell::new(None), + grouped_iq2: Cell::new(None), + grouped_iq3_s: Cell::new(None), + grouped_iq4_xs: Cell::new(None), + grouped_iq3_s_nc4: Cell::new(None), + grouped_iq4_xs_nc4: Cell::new(None), + grouped_swiglu: Cell::new(None), + grouped_down_iq4: Cell::new(None), + grouped_down_q2: Cell::new(None), + gr_read_guard_kernel: Cell::new(None), + projection_kernels: std::array::from_fn(|_| Cell::new(None)), + qwen_kernels: qwen_dispatch::Cache::new(), + kar_levels: Cell::new(None), + experimental: std::array::from_fn(|_| Cell::new(None)), + window_modules: RefCell::new(Vec::new()), + deferred_frees: RefCell::new(Vec::new()), + }; + let make = |handle| DeviceBuffer { + context: &context, + handle, + bytes: 4, + _thread: PhantomData, + borrowed: false, + }; + let matrix = make(Some(ffi::BufferHandle::synthetic(4))); + let vector = make(Some(ffi::BufferHandle::synthetic(8))); + let mut output = make(Some(ffi::BufferHandle::synthetic(12))); + assert_eq!( + context.matvec_f32(&matrix, &vector, &mut output, 1, 1), + Err(Error::ContextPoisoned) + ); + // No native context exists in this test. Pure allocation identity and + // extent instruments supply the remaining impossible-safe-call cases. + assert_eq!(context.allocated_bytes(), 12); + assert!(context.matvec_kernel.get().is_none()); + } + #[cfg(not(feature = "cuda-driver"))] + #[test] + fn default_load_rejects_before_driver_use() { + assert!(matches!(Driver::load(), Err(Error::Disabled))); + } + #[cfg(all( + feature = "cuda-driver", + not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")) + ))] + #[test] + fn unsupported_load_rejects_before_driver_use() { + assert!(matches!(Driver::load(), Err(Error::UnsupportedPlatform))); + } +} + +#[cfg(test)] +#[path = "../tests/projection_family_oracle.rs"] +mod family_expectations; +#[cfg(test)] +mod family_tests { + use super::*; + const KINDS: [ProjectionKind; 10] = [ + ProjectionKind::Dense(DenseFormat::Q8_0), + ProjectionKind::Dense(DenseFormat::Q4_K), + ProjectionKind::Routed(RoutedFormat::IQ3_XXS), + ProjectionKind::Routed(RoutedFormat::IQ3_S), + ProjectionKind::Routed(RoutedFormat::IQ2_S), + ProjectionKind::Dense(DenseFormat::IQ4_NL), + ProjectionKind::Routed(RoutedFormat::IQ4_NL), + ProjectionKind::Dense(DenseFormat::IQ4_XS), + ProjectionKind::Routed(RoutedFormat::IQ4_XS), + ProjectionKind::Routed(RoutedFormat::Q2_0), + ]; + #[test] + fn common_checked_geometry_matches_frozen_native_layouts() { + for (kind, index) in KINDS.into_iter().zip([0, 1, 2, 3, 4, 5, 5, 6, 6, 7]) { + let shape = projection_shape(ProjectionSpec { + kind, + rows: 5, + columns: 256, + }) + .unwrap(); + assert_eq!( + shape.weight_bytes, + 5 * (256 / family_expectations::LAYOUTS[index].0) + * family_expectations::LAYOUTS[index].1 + ); + assert_eq!( + ( + shape.activation_bytes, + shape.output_bytes, + shape.scratch_bytes, + shape.temporary_bytes + ), + (1024, 20, 288, 292) + ); + } + for (n, bytes, grid) in family_expectations::TAILS { + let shape = projection_shape(ProjectionSpec { + kind: KINDS[0], + rows: 5, + columns: n, + }) + .unwrap(); + assert_eq!( + (shape.scratch_bytes, shape.quant_grid, shape.projection_grid), + (bytes, grid as u32, 2) + ); + } + for (kind, limit) in [ + (KINDS[0], 1024), + (KINDS[1], 2048), + (KINDS[5], 2048), + (KINDS[7], 4096), + ] { + for (n, grid) in [(limit - 256, 2), (limit, 5), (limit + 256, 5)] { + assert_eq!( + projection_shape(ProjectionSpec { + kind, + rows: 5, + columns: n + }) + .unwrap() + .projection_grid, + grid + ); + } + } + for kind in [KINDS[2], KINDS[3], KINDS[4], KINDS[6], KINDS[8], KINDS[9]] { + assert_eq!( + projection_shape(ProjectionSpec { + kind, + rows: 5, + columns: 6144 + }) + .unwrap() + .projection_grid, + 2 + ); + } + } + #[test] + fn common_invalid_shapes_have_fixed_errors() { + for kind in KINDS { + for (m, n) in [ + (0, 256), + (1, 0), + (1, 31), + (1, 33), + (usize::MAX, 256), + (1, usize::MAX), + (i32::MAX as usize + 1, 256), + ] { + assert_eq!( + projection_shape(ProjectionSpec { + kind, + rows: m, + columns: n + }), + Err(Error::InvalidProjectionShape) + ); + } + } + assert_eq!( + projection_shape(ProjectionSpec { + kind: KINDS[1], + rows: 1, + columns: 32 + }), + Err(Error::InvalidProjectionShape) + ); + } + + #[test] + fn q4_k_admission_bounds_every_padded_cta_byte_offset() { + // At N=256 the kernel launches four output rows per CTA and computes + // all four row-arm offsets before guarding the final partial CTA. + // The largest admitted padded row count therefore stays on a four + // row boundary and its post-loop signed offset fits i32. + const BLOCK_BYTES: usize = 144; + const ROWS_PER_CTA: usize = 4; + let max_block_index = i32::MAX as usize / BLOCK_BYTES; + // Include the common final +8-block PTX increment after the last + // iteration, then round the small-N four-row CTA down to its boundary. + let max_padded_rows = + ((max_block_index.saturating_sub(7) / ROWS_PER_CTA) * ROWS_PER_CTA).max(ROWS_PER_CTA); + let at_limit_offset = (max_padded_rows + 7) * BLOCK_BYTES; + assert!(at_limit_offset <= i32::MAX as usize); + assert!(q4_k_native_indices_fit(max_padded_rows - ROWS_PER_CTA, 256)); + assert!(q4_k_native_indices_fit(max_padded_rows, 256)); + assert!(!q4_k_native_indices_fit(max_padded_rows + 1, 256)); + assert!( + projection_shape(ProjectionSpec { + kind: ProjectionKind::Dense(DenseFormat::Q4_K), + rows: max_padded_rows, + columns: 256, + }) + .is_ok() + ); + + // The large-N launch uses one CTA per row but still materializes + // row+1 through row+3 and the final offsets of all eight lane groups. + let blocks_per_row = 2048 / 256; + let max_large_n_rows = ((max_block_index - (blocks_per_row + 7)) / blocks_per_row) - 2; + assert!(q4_k_native_indices_fit(max_large_n_rows - 1, 2048)); + assert!(q4_k_native_indices_fit(max_large_n_rows, 2048)); + assert!(!q4_k_native_indices_fit(max_large_n_rows + 1, 2048)); + assert!( + projection_shape(ProjectionSpec { + kind: ProjectionKind::Dense(DenseFormat::Q4_K), + rows: max_large_n_rows, + columns: 2048, + }) + .is_ok() + ); + assert_eq!( + projection_shape(ProjectionSpec { + kind: ProjectionKind::Dense(DenseFormat::Q4_K), + rows: max_large_n_rows + 1, + columns: 2048, + }), + Err(Error::InvalidProjectionShape) + ); + + // N=2304 has nine blocks: lane group 0 visits 0 and 8 then reaches + // 16, the maximum final index across groups 0..7. + let blocks_per_row: usize = 2304 / 256; + let final_loop_index = blocks_per_row + 7; + assert_eq!(final_loop_index, 16); + let max_nonwrapping_rows = ((max_block_index - final_loop_index) / blocks_per_row) - 2; + assert!(q4_k_native_indices_fit(max_nonwrapping_rows, 2304)); + assert!(!q4_k_native_indices_fit(max_nonwrapping_rows + 1, 2304)); + + // For sixteen blocks, lane group 7 visits block 15 and increments to + // 23; checking only the block-zero loop would miss this signed offset. + let blocks_per_row: usize = 4096 / 256; + let final_loop_index = blocks_per_row + 7; + assert_eq!(final_loop_index, 23); + let max_nonwrapping_rows = ((max_block_index - final_loop_index) / blocks_per_row) - 2; + assert!(q4_k_native_indices_fit(max_nonwrapping_rows, 4096)); + assert!(!q4_k_native_indices_fit(max_nonwrapping_rows + 1, 4096)); + + // The independent QA counterexample and its adjacent valid-row + // boundary are rejected before any context, cache, or allocation work. + for rows in [14_913_081, 14_913_082] { + assert!(!q4_k_native_indices_fit(rows, 256)); + assert_eq!( + projection_shape(ProjectionSpec { + kind: ProjectionKind::Dense(DenseFormat::Q4_K), + rows, + columns: 256, + }), + Err(Error::InvalidProjectionShape) + ); + } + + // With one row, a large N may have a large total extent while every + // native signed packed-byte base remains representable. This case is + // structural only and deliberately allocates no host or device data. + let large_n = 256 * 3_000_000; + assert!(q4_k_native_indices_fit(1, large_n)); + assert!( + projection_shape(ProjectionSpec { + kind: ProjectionKind::Dense(DenseFormat::Q4_K), + rows: 1, + columns: large_n, + }) + .is_ok() + ); + + // Positive individually-valid M and N still refuse when their Q4_K + // row/block product would overflow the native signed byte offset. + let max_i32_n = (i32::MAX as usize / 256) * 256; + assert!(!q4_k_native_indices_fit(2, max_i32_n)); + assert_eq!( + projection_shape(ProjectionSpec { + kind: ProjectionKind::Dense(DenseFormat::Q4_K), + rows: 2, + columns: max_i32_n, + }), + Err(Error::InvalidProjectionShape) + ); + } + + #[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" + ))] + #[test] + #[ignore = "private quantizer transport only; isolated CPU mock, not GPU math"] + fn family_quantizer_transport_child() { + assert_eq!( + std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), + Ok("1") + ); + let n: usize = std::env::var("LELEKA_FAMILY_N").unwrap().parse().unwrap(); + let driver = Driver::load().unwrap(); + let context = driver.device(0).unwrap().create_context(8192).unwrap(); + let trace_path = std::env::var("MOCK_CUDA_TRACE").unwrap(); + let before = std::fs::read(&trace_path).unwrap(); + for (kind, alignment) in KINDS.into_iter().zip([2, 4, 2, 2, 2, 2, 2, 4, 4, 2]) { + let shape = projection_shape(ProjectionSpec { + kind, + rows: 1, + columns: 256, + }) + .unwrap(); + let addresses = [ + ffi::BufferHandle::synthetic(2), + ffi::BufferHandle::synthetic(4096), + ffi::BufferHandle::synthetic(8192), + ]; + assert_eq!( + projection_ranges(kind, &shape, addresses), + if alignment == 4 { + Err(Error::InvalidProjectionShape) + } else { + Ok(()) + } + ); + assert_eq!(std::fs::read(&trace_path).unwrap(), before); + assert_eq!(context.allocated_bytes(), 0); + assert!(context.common_quantizer.get().is_none()); + assert!( + context + .projection_kernels + .iter() + .all(|slot| slot.get().is_none()) + ); + } + let mut input = context.allocate(4 * n).unwrap(); + input.copy_from(&vec![0; 4 * n]).unwrap(); + let scratch = context.allocate(n / 32 * 36).unwrap(); + let mut status = context.allocate(4).unwrap(); + let operation = (|| { + status.copy_from(&[0; 4])?; + let guard = context.enter()?; + let kernel = match context.fixed_kernel(FixedOperation::CommonQuantize) { + Ok(k) => k, + Err(e) => return combine(Err(e), guard.finish()), + }; + combine(Ok(()), guard.finish())?; + let mut args = ffi::Q8QuantizeArguments::new( + input.handle.unwrap(), + scratch.handle.unwrap(), + status.handle.unwrap(), + n as u32, + ); + let guard = context.enter()?; + let launch = context.driver.api.launch_q8_quantize( + kernel.function, + n.div_ceil(256) as u32, + &mut args, + ); + context.complete_launch(launch, args, guard)?; + let mut bytes = [0; 4]; + status.copy_to(&mut bytes)?; + let expected = std::env::var("MOCK_FAMILY_STATUS") + .unwrap_or_else(|_| "0".into()) + .parse::() + .unwrap(); + assert_eq!(u32::from_le_bytes(bytes), expected); + Ok(()) + })(); + let result = context.release_quantized_temporaries(operation, scratch, status); + let failure = std::env::var("LELEKA_FAMILY_EXPECT_FAILURE").as_deref() == Ok("1"); + assert_eq!(result.is_err(), failure, "result={result:?}"); + let base = std::env::var("MOCK_CUDA_FAIL").unwrap_or_default(); + let family = std::env::var("MOCK_CUDA_FAMILY_FAIL").unwrap_or_default(); + let expected_charge = if family.contains("quant_sync") + || family.contains("quant_restore") + || base == "lookup:1,unload:1" + { + 4 * n + n / 32 * 36 + 4 + } else if base == "free:1" { + 4 * n + 4 + } else if base == "free:2" { + 4 * n + n / 32 * 36 + } else { + 4 * n + }; + assert_eq!(context.allocated_bytes(), expected_charge); + if family == "quant_launch,quant_sync,quant_restore" { + let error = format!("{result:?}"); + let launch = error.find("cuLaunchKernel").unwrap(); + let sync = error.find("cuCtxSynchronize").unwrap(); + let restore = error.find("cuCtxPopCurrent_v2").unwrap(); + assert!(launch < sync && sync < restore); + } + drop(input); + let close = context.close(); + let close_failure = std::env::var("LELEKA_FAMILY_CLOSE_FAILURE").as_deref() == Ok("1"); + if close_failure { + assert!(close.is_err()); + } else if !failure { + close.unwrap(); + } + } +} + +// Isolated preview only; absent from the serving qualification map. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] +pub mod q6_layer_preview; + +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] +pub use qwen_dispatch::batch_gr_preview::GrBatchModule; + +#[cfg(all( + test, + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +#[path = "grouped_down_columns_gpu.rs"] +mod grouped_down_columns_gpu; + +pub use qwen_dispatch::qwen_shared_tail::{ + SharedDownKind, SharedExpertWeights, SharedExpertWorkspace, SharedGuKind, SharedTailCompletion, + SharedTailRefusal, +}; + +// Additive closed MTP input transport owners. +pub use qwen_dispatch::gdn_closed_queue::{ + GdnQueueStage, GdnRowCompletion, GdnRowPrefix, GdnRowQueue, +}; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] +pub use qwen_dispatch::gdn_fused_t1::{ + GDN_FUSED_T1_PERSISTENT_BYTES, GDN_FUSED_T1_STATE_BYTES, GdnFusedCompletion, GdnFusedPrefix, + GdnFusedStage, GdnFusedT1, +}; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] +pub use qwen_dispatch::gdn_native_batch::{ + GDN_BATCH_EPSILON, GDN_BATCH_MAX_TOKENS, GdnBatchCompletion, GdnBatchPrefix, GdnBatchStage, + GdnGemm, GdnNativeFormat, GdnPrefillBatch, GdnStream, GemmShape, OriginalGdnPromptDevice, + OriginalGdnPromptWeights, +}; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] +pub use qwen_dispatch::moe_prefill_batch::{ + MOE_BATCH_MAX_TOKENS, MOE_BATCH_SCRATCH_BYTES, MoeBatchCompletion, MoeBatchPrefix, + MoeBatchStage, MoePrefillBatch, MoeRouteBatch, +}; +pub use qwen_dispatch::mtp_input_workspace::{ + MtpInputCompletion, MtpInputPrefix, MtpInputRefusal, MtpInputWorkspace, +}; + +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] +pub use qwen_dispatch::gr_batch_inject_workspace::{ + GR_BATCH_INJECT_WORKSPACE_BYTES, GrBatchInjectShape, GrBatchInjectWorkspace, +}; + +// Separately selected asynchronous owned-copy adapter; original APIs unchanged. +#[allow(unsafe_code)] +mod api; +mod async_owned_copy; +pub use async_owned_copy::{ + CompletedOwnedCopy, MAX_ASYNC_COPY_PAIRS, OwnedCopyPairs, OwnedCopyPoll, PendingOwnedCopy, +}; + +// Explicit experimental resident pipeline; original entry bodies remain unchanged. +mod routed_resident_queue; +pub use routed_resident_queue::{ + RoutedResidentCompletion, RoutedResidentQueue, RoutedResidentRefusal, RoutedResidentWeights, +}; + +pub use qwen_dispatch::ple_closed_queue::{ + PleClosedCompletion, PleClosedParts, PleClosedQueue, PleClosedRefusal, PleClosedWeights, +}; + +mod mapped_expert_bank; +pub use mapped_expert_bank::{ + MappedExpertBank, MappedExpertCopyCompletion, MappedExpertCopyScratch, PendingMappedExpertCopy, +}; + +pub use qwen_dispatch::gr_native_batch::{GrNativeBatch, GrNativeProfile}; + +// Explicit Original prefill transport; no default selection or public raw spans. +#[allow(unsafe_code)] +pub(crate) mod ple_batch_ffi; +mod ple_batch_queue; +pub use ple_batch_queue::{ + PLE_BATCH_QUEUE_BYTES, PleBatchCompletion, PleBatchQueue, PleBatchRow, PleBf16Mode, +}; + +mod native_batch_workspace; +pub use native_batch_workspace::{NATIVE_BATCH_WORKSPACE_BYTES, NativeBatchWorkspace}; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +mod gdn_batch_gemm; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub use gdn_batch_gemm::NativeGdnGemm; + +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +mod qsa_native_batch; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub use qsa_native_batch::{ + QSA_NATIVE_BATCH_BYTES, QsaNativeBatchWorkspace, QsaNativeKind, QsaNativePacking, + QsaNativeProjections, +}; + +// Literal Original QSA prompt index assets share the admitted native stream. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[allow(unsafe_code)] +mod qsa_index_ffi; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +mod qsa_prompt_index; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub use qsa_prompt_index::{ + OriginalQsaDeviceSelection, OriginalQsaPromptDevice, OriginalQsaPromptWeights, + QSA_PROMPT_INDEX_BYTES, QsaPromptIndexPrefix, QsaPromptIndexState, QsaPromptIndexWorkspace, + QsaPromptSelection, +}; + +// Genuine page4 INT8 owners and literal Original prompt/decode programs. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +mod qsa_native_decode; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +mod qsa_prompt_attention; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[allow(unsafe_code)] +mod qsa_prompt_attention_ffi; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[allow(unsafe_code)] +mod qsa_prompt_host_ffi; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +mod qsa_prompt_kv; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +mod qsa_prompt_resolver; +pub use qsa_prompt_resolver::KvStreamCounters; +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +mod kv_stream_gpu; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub use qsa_native_decode::{QSA_NATIVE_DECODE_BYTES, QsaNativeDecode, QsaNativeDecodeCompletion}; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub use qsa_prompt_attention::{ + QSA_PROMPT_ATTENTION_BYTES, QsaAttentionInputs, QsaPromptAttention, + QsaPromptAttentionCompletion, +}; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub use qsa_prompt_kv::{ + CompletedQsaKvAppend, QSA_PROMPT_MAPPED_HOST_BYTES, QSA_PROMPT_MAX_SNAPSHOT_METADATA_BYTES, + QSA_PROMPT_MAX_SNAPSHOT_PAYLOAD_BYTES, QSA_PROMPT_RESIDENT_BYTES, QSA_PROMPT_STAGE_BYTES, + QsaKvInputs, QsaKvOwnerId, QsaKvSnapshot, QsaPromptKv, QsaPromptStage, +}; + +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub use qsa_native_decode::OriginalQsaResidentDecodeCompletion; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub use qsa_prompt_attention::OriginalQsaResidentAttention; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub use qsa_prompt_index::{ + OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex, + OriginalQsaResidentPromptDevice, OriginalQsaResidentScalarIndex, + OriginalQsaResidentScalarSelection, OriginalQsaResidentSelection, +}; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub use qsa_prompt_kv::{ + OriginalQsaMappedAppend, OriginalQsaMappedJournal, OriginalQsaMappedPrefix, + OriginalQsaResidentTransport, +}; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +mod moe_prompt_packet_copy; +mod qsa_native_gate; +pub use qsa_native_gate::QsaNativeGate; + +mod original_sampler; +mod original_sampler_params; +mod sealed_ptx; +#[allow(unsafe_code)] +mod arch_ptx; +mod gpu_report; +pub use gpu_report::gpu_kernel_report; +#[cfg(feature = "sm86")] +mod sm86_table; +#[allow(unsafe_code)] +mod original_sampler_ffi; +#[allow(unsafe_code)] +mod original_sampler_mapped; +pub use original_sampler::{OriginalSampler, SamplerParams, SamplerPath}; + +mod native_prompt_device; +mod prefill_stage; +mod launch_ex; +mod qsa_cluster; +mod qsa_late; +pub use qsa_late::set_override as set_qsa_late_override; +pub use qsa_late::set_topk_override as set_qsa_topk_override; +pub use qsa_prompt_kv::set_qsa_prefetch_override; +pub use qsa_cluster::{requested as qsa_cluster_requested, set_override as set_qsa_cluster_override}; +pub use prefill_stage::{set_gdn_nostore_override as set_prefill_gdn_nostore_override, set_gdn_override as set_prefill_gdn_override}; +pub use native_prompt_device::{ + OriginalDeviceBlock, OriginalDeviceGrRead, OriginalDeviceNormedResidual, + OriginalDeviceResidual, OriginalPleHistory, OriginalPromptDevice, PromptInputStage, +}; + +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use mtp_dense_kv::OriginalMtpSkippedPrefix; +pub use mtp_dense_kv::{ + CompletedDraftKv, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, OriginalMtpEmbedding, + OriginalMtpPrefill, OriginalMtpPrefillWeights, +}; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use mtp_dense_kv::{ + CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, + OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, + OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpStepOutput, +}; + +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +mod original_expert_stager; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use original_expert_stager::{ + OriginalExpertStager, OriginalFileExpertBlob, OriginalStagerBatch, OriginalStagerCompleted, + OriginalStagerJob, OriginalStagerOptions, OriginalStreamAll, OriginalStreamAllCompleted, + OriginalStreamAllForward, OriginalStreamAllOptions, +}; + +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +mod native_parity; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +#[allow(unsafe_code)] +mod native_parity_ffi; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use native_parity::{ + NativeParity, NativeParityExpert, native_parity_embed_supported, native_parity_iq_supported, + native_parity_row_bytes, +}; + +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use mtp_dense_kv::{ + OriginalMtpGrVariant, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, + OriginalMtpScalarPrefill, +}; + +/// `LELEKA_CHAIN` selects the chain-kernel group `mtp` (claude/chain-kernels): the draft step reads the hyper-connections with the +/// staged variant the Original runs on this card (bit-identical to the plain one) and uses the load-hoisted attention kernels. +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +pub fn chain_selects_mtp() -> bool { + original_verify::chain::flags().mtp +} +#[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] +pub fn chain_selects_mtp() -> bool { + false +} +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use original_gpu_schedule::OriginalStreamDrained; +pub use original_gpu_schedule::capture_timing as original_capture_timing; + +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +mod native_head; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use native_head::{ + NativeEmbedFlight, NativeHeadDispatch, NativeHeadFlight, NativeHeadProjectionFlight, + NativeHeadSampling, NativeHeadSelection, OriginalNativeEmbed, OriginalNativeEmbedRows, + OriginalNativeHead, OriginalNativeHeadGraphResources, OriginalNativeHeadRows, + native_embed_supported, native_head_row_bytes, native_head_supported, +}; + +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +mod original_file_expert_source; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use original_file_expert_source::{ + OriginalFileExpertSource, OriginalFileSourceBlob, OriginalFileSourceCounters, + OriginalResidentOptions, OriginalSourceSwap, +}; + +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub(crate) mod original_verify; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use original_verify::chain::set_down_override as set_chain_down_override; +pub use original_verify::sm120::set_overrides as set_sm120_overrides; +/// Without the CUDA driver there is no chain window: the override is a no-op. +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +pub fn set_chain_down_override(_: i8) {} +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use original_verify::{ + MAX_PCIE_FETCHES as ORIGINAL_VERIFY_MAX_PCIE_FETCHES, OriginalVerifyGpuPlan, OriginalVerifyPcieSource, + OriginalVerifier, OriginalVerifyBank, OriginalVerifyCanonicalGdn, OriginalVerifyCpuRows, + OriginalVerifyCpuSink, OriginalVerifyGdnJournal, OriginalVerifyGdnStage, + OriginalVerifyGdnWeights, OriginalVerifyGeometry, OriginalVerifyGraphResources, + OriginalVerifyLayout, OriginalVerifyResources, OriginalVerifyRow, OriginalVerifySpan, + OriginalVerifyWindow, OriginalVerifyWindowResult, +}; +// Live verifier release/diagnostic owner, profile report and completed-logit readout. +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use original_verify::{ + HcHalfBuffers, HcLayerBuffers, HcOutputBuffers, OriginalVerifyExpertFormats, + OriginalVerifyGdnProjections, OriginalVerifyGrBinding, OriginalVerifyMoeBinding, + OriginalVerifyMoeLayerWeights, OriginalVerifyNativeMatrix, OriginalVerifyProjBinding, + OriginalVerifyQsaBinding, OriginalVerifyQsaKvBinding, OriginalVerifyQsaLayerWeights, + OriginalVerifyQsaPolicy, OriginalVerifyQsaProjections, PLE_SCRATCH_BYTES, PleBuffers, PleKeyBuffer, QsaRope, + unsealed_window_assets, +}; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use original_verify::{ + ExpertTier, HcHalf, OriginalVerifyExpertLayout, OriginalVerifyWindowResources, PlanLayout, + Projection, QuantSource, Rows as OriginalVerifyRows, UNBOUND_PRODUCERS, WINDOW_LAYERS, + WindowOps as OriginalVerifyWindowOps, WindowPolicy as OriginalVerifyWindowPolicy, + record_window as record_original_verify_window, + OriginalVerifyDiag, OriginalVerifyProfile, PROFILE_STAMPS_PER_LAYER, RowLogprob, analyse_row, + logpos_topk_from_environment, original_verify_diagnostics, original_verify_live_count, + original_verify_release_live, profile_stamp_slot, profile_stamp_words, top_k, write_row_line, + write_window_logprobs, write_original_verify_diagnostics, +}; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use qsa_prompt_index::{OriginalVerifyQsaJournal, OriginalVerifyRope}; +#[cfg(all( + feature = "cuda-driver", + feature = "expert-tier-probe", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use original_verify::{OriginalExpertTierProbe, expert_probe_geometry}; + +// Which compiled assets the Original serve stack needs, and which of them are sealed in this build. +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +mod original_serve_assets; +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub use original_serve_assets::{ + OriginalAssetKind, OriginalAssetStatus, original_serve_asset_status, original_serve_assets_sealed, + unsealed_original_serve_assets, +}; +// Session-lineage reads over the verifier QSA journal (see the file header). +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +mod original_serve_access; diff --git a/crates/cuda-driver/src/original_gpu_schedule.rs b/crates/cuda-driver/src/original_gpu_schedule.rs index bbc8796e..5ae8f5c4 100644 --- a/crates/cuda-driver/src/original_gpu_schedule.rs +++ b/crates/cuda-driver/src/original_gpu_schedule.rs @@ -1,1258 +1,1258 @@ -//! Original CUDA scheduling owners. Capture resources are real owned/borrowed -//! producers, retained through every replay and through uncertain retirement. -//! No public raw stream, graph, event, kernel address or readiness constructor. -#[path = "original_gpu_schedule_ffi.rs"] -mod abi; -use crate::{Context, Error, Result, combine}; -use std::{ - cell::Cell, - rc::Rc, - time::{Duration, Instant}, -}; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum OriginalStreamKind { - BlockingCapture, - NonBlocking, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum OriginalEventKind { - Timing, - Completion, -} -/// Concrete Original call-site policies: session graphs do not explicitly upload; -/// MTP and verifier window graphs upload+sync; the verifier commit does not. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum OriginalCapturePolicy { - Session, - VerifierWindow, - VerifierCommit, - Mtp, - Registry, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum OriginalWait { - Complete, - TimedOut, -} -/// Implemented only by actual closed driver producer banks. Arbitrary public -/// host floats, pointer tables or caller readiness bits cannot mint this trait. -pub(crate) mod resources { - pub trait Sealed {} -} -pub trait OriginalGraphResources: resources::Sealed { - fn validate_context(&self, context: &Context<'_>) -> Result<()>; - fn validate_replay_context(&self, context: &Context<'_>) -> Result<()> { - self.validate_context(context) - } -} - -#[path = "mtp_original_full_graph.rs"] -mod mtp_full_graph; -fn transport(e: &Error) -> bool { - match e { - Error::Driver { .. } | Error::ContextPoisoned | Error::UnexpectedContext => true, - Error::Multiple { primary, secondary } => transport(primary) || transport(secondary), - _ => false, - } -} -fn poison(c: &Context<'_>) { - c.poison(); - c.retain_driver(); -} -fn healthy(c: &Context<'_>) -> Result<()> { - if c.is_poisoned() || c.handle.is_none() { - Err(Error::ContextPoisoned) - } else { - Ok(()) - } -} -/// `CUDA_ERROR_OUT_OF_MEMORY` of the driver API. Not sticky: the context is intact after it. -const CUDA_ERROR_OUT_OF_MEMORY: i32 = 2; -/// A graph instantiate (or upload) that ran out of device memory. Recoverable: the call did not run, no state changed, and the -/// driver returns the memory-allocation error without a sticky error (upstream a8c1d4b7 / 2a9a67c1: their engine died on it). -/// Only a bare driver error counts; one wrapped in `Multiple` carries a cleanup failure too, and that is fatal. -pub(crate) fn is_graph_out_of_memory(e: &Error) -> bool { - matches!( - e, - Error::Driver { operation: "cuGraphInstantiateWithFlags" | "cuGraphUpload", code: CUDA_ERROR_OUT_OF_MEMORY } - ) -} -/// Whether a driver call that ended with `op` (and whose context pop gave `pop_failed`) leaves the context unusable. -fn poisons(op: &Result, pop_failed: bool, recoverable: fn(&Error) -> bool) -> bool { - pop_failed || op.as_ref().err().is_some_and(|e| !recoverable(e)) -} -fn call(c: &Context<'_>, api: &abi::Api, f: impl FnOnce(&abi::Api) -> Result) -> Result { - call_unless(c, api, f, |_| false) -} -/// `call`, except that an error `recoverable` accepts does not poison the context (the caller undoes what it did and goes on). -fn call_unless(c: &Context<'_>, api: &abi::Api, f: impl FnOnce(&abi::Api) -> Result, recoverable: fn(&Error) -> bool) -> Result { - healthy(c)?; - let guard = c.enter().inspect_err(|_| poison(c))?; - let op = f(api); - let pop = guard.finish(); - if poisons(&op, pop.is_err(), recoverable) { - poison(c); - } - combine(op, pop) -} -/// Test hook (off unless set): `LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT=N` makes the N-th (1-based) verifier-window graph -/// instantiation of the process fail once with the driver's out-of-memory code, so the fallback can be exercised on a card with room. -fn injected_window_oom(policy: OriginalCapturePolicy) -> bool { - static AT: std::sync::OnceLock = std::sync::OnceLock::new(); - static SEEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - if policy != OriginalCapturePolicy::VerifierWindow { - return false; - } - let at = *AT.get_or_init(|| std::env::var("LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)); - at != 0 && SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1 == at -} -struct Stream<'ctx> { - context: &'ctx Context<'ctx>, - api: Rc, - handle: Cell>, - capture: Cell, - failed: Cell, - sequence: Cell, -} -impl Stream<'_> { - fn bump(&self) -> Result { - let next = self - .sequence - .get() - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - self.sequence.set(next); - Ok(next) - } - fn validate(&self) -> Result { - healthy(self.context)?; - if self.failed.get() { - return Err(Error::ContextPoisoned); - } - self.handle.get().ok_or(Error::ContextPoisoned) - } - fn run(&self, f: impl FnOnce(&abi::Api, usize) -> Result) -> Result { - let h = self.validate()?; - let r = call(self.context, &self.api, |a| f(a, h)); - if r.is_err() { - self.failed.set(true); - } - r - } - fn close(&self) -> Result<()> { - let Some(h) = self.handle.take() else { - return Ok(()); - }; - if self.context.is_poisoned() { - self.failed.set(true); - std::mem::forget(self.api.clone()); - return Err(Error::ContextPoisoned); - } - // Ending a capture is mandatory even when its typed body failed. - let mut graph = None; - let op = call(self.context, &self.api, |a| { - let ended = if self.capture.replace(false) { - match a.end(h) { - Ok(g) => { - graph = Some(g); - Ok(()) - } - Err(e) => Err(e), - } - } else { - Ok(()) - }; - let sync = a.stream_sync(h); - let destroy = if sync.is_ok() { - if h == 0 { Ok(()) } else { a.stream_destroy(h) } - } else { - Err(Error::ContextPoisoned) - }; - let destroy_graph = if sync.is_ok() { - graph.take().map_or(Ok(()), |g| a.graph_destroy(g)) - } else { - Err(Error::ContextPoisoned) - }; - combine(combine(combine(ended, sync), destroy), destroy_graph) - }); - if op.is_err() { - self.failed.set(true); - std::mem::forget(self.api.clone()); - } - op - } -} -impl Drop for Stream<'_> { - fn drop(&mut self) { - let _ = self.close(); - } -} -/// Rc is private and only genuine dependencies can retain the actual stream. -pub struct OriginalGpuStream<'ctx> { - inner: Rc>, -} -impl Context<'_> { - /// Genuine legacy default CUDA stream for Original Prefill arithmetic. No - /// stream-create call and no destroy0; Context-affine actual owner identity. - pub fn original_default_gpu_stream(&self) -> Result> { - healthy(self)?; - let api = Rc::new(abi::Api::load()?); - Ok(OriginalGpuStream { - inner: Rc::new(Stream { - context: self, - api, - handle: Cell::new(Some(0)), - capture: Cell::new(false), - failed: Cell::new(false), - sequence: Cell::new(0), - }), - }) - } - pub fn original_gpu_stream(&self, kind: OriginalStreamKind) -> Result> { - healthy(self)?; - let api = Rc::new(abi::Api::load()?); - let h = call(self, &api, |a| { - a.stream_create(kind == OriginalStreamKind::NonBlocking) - }) - .inspect_err(|_| std::mem::forget(api.clone()))?; - Ok(OriginalGpuStream { - inner: Rc::new(Stream { - context: self, - api, - handle: Cell::new(Some(h)), - capture: Cell::new(false), - failed: Cell::new(false), - sequence: Cell::new(0), - }), - }) - } - pub fn original_gpu_event(&self, kind: OriginalEventKind) -> Result> { - healthy(self)?; - let api = Rc::new(abi::Api::load()?); - let h = call(self, &api, |a| { - a.event_create(kind == OriginalEventKind::Timing) - }) - .inspect_err(|_| std::mem::forget(api.clone()))?; - Ok(OriginalGpuEvent { - context: self, - api, - handle: Some(h), - kind, - source: None, - waiters: std::array::from_fn(|_| None), - recorded: false, - sequence: 0, - }) - } -} -impl<'ctx> OriginalGpuStream<'ctx> { - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.inner.context) { - return Err(Error::ContextMismatch); - } - self.inner.validate().map(|_| ()) - } - pub fn is_failed(&self) -> bool { - self.inner.failed.get() - || self.inner.context.is_poisoned() - || self.inner.handle.get().is_none() - } - pub fn priority(&self) -> Result { - self.inner.run(|a, h| a.stream_priority(h)) - } // Observational only; Original never overrides priority. - pub fn query(&self) -> Result { - if self.inner.capture.get() { - return Err(Error::InvalidQwenShape); - } - self.inner.run(|a, h| a.stream_query(h)) - } - pub fn synchronize(&self) -> Result<()> { - if self.inner.capture.get() { - return Err(Error::InvalidQwenShape); - } - self.inner.run(|a, h| a.stream_sync(h)) - } - /// `fetch_dma`'s `cudaMemcpyAsync` of one registered source span into device staging. The caller retains - /// the registered source and the destination allocation until this stream's next fence. - pub(crate) fn enqueue_copy_h2d(&mut self, destination: u64, source: &[u8]) -> Result<()> { - if self.inner.capture.get() || source.is_empty() || destination == 0 { - return Err(Error::InvalidQwenShape); - } - self.inner.bump()?; - self.inner.run(|a, h| a.copy_h2d(destination, source, h)) - } - /// All the DMA pieces of one group in a single context entry (`batch`: one `cuMemcpyBatchAsync`). Same contract as - /// `enqueue_copy_h2d` for every piece. - pub(crate) fn enqueue_copy_h2d_many(&mut self, pieces: &[(u64, &[u8])], batch: bool) -> Result<()> { - if self.inner.capture.get() || pieces.is_empty() || pieces.iter().any(|p| p.0 == 0 || p.1.is_empty()) { - return Err(Error::InvalidQwenShape); - } - self.inner.bump()?; - self.inner.run(|a, h| a.copy_h2d_many(pieces, h, batch)) - } - /// Flag B after every earlier operation of this stream: `cuStreamWriteValue32` of the word's device alias when the - /// driver takes it (no callback thread), else the host callback of `enqueue_raise_u32`. The word's owner must outlive - /// this stream's next fence. - pub(crate) fn enqueue_raise_flag(&mut self, host_word: usize, device_address: u64, value: u32) -> Result<()> { - if self.inner.capture.get() { - return Err(Error::InvalidQwenShape); - } - self.inner.bump()?; - self.inner.run(|a, h| a.raise_flag_after(h, host_word, device_address, value)) - } - /// `fetch_dma`'s `cudaLaunchHostFunc(raise_flag)`: the mapped host word rises to `value` after every - /// earlier operation of this stream. The word's owner must outlive this stream's next fence. - pub(crate) fn enqueue_raise_u32(&mut self, word: usize, value: u32) -> Result<()> { - if self.inner.capture.get() { - return Err(Error::InvalidQwenShape); - } - self.inner.bump()?; - self.inner.run(|a, h| a.raise_u32_after(h, word, value)) - } - /// Only closed typed driver producers may enqueue via this private validated handle. - /// Their stable ABI/device/mapped owners MUST live in capture resources R. - pub(crate) fn with_enqueue(&mut self, f: impl FnOnce(usize) -> Result) -> Result { - let h = self.inner.validate()?; - if self.inner.capture.get() { - return Err(Error::InvalidQwenShape); - } - let _sequence = self.inner.bump()?; - let guard = self - .inner - .context - .enter() - .inspect_err(|_| poison(self.inner.context))?; - let op = f(h); - let pop = guard.finish(); - if op.as_ref().err().is_some_and(transport) || pop.is_err() { - poison(self.inner.context); - self.inner.failed.set(true); - } - combine(op, pop) - } - pub fn capture_owned( - &mut self, - policy: OriginalCapturePolicy, - resources: R, - body: impl FnOnce(&mut OriginalCapture<'_, 'ctx>, &mut R) -> Result<()>, - ) -> Result> { - let started = std::time::Instant::now(); - resources.validate_context(self.inner.context)?; - let h = self.inner.validate()?; - if h == 0 { - return Err(Error::InvalidQwenShape); - } - if self.inner.capture.replace(true) { - return Err(Error::InvalidQwenShape); - } - let mut g = OriginalGpuGraph { - context: self.inner.context, - api: self.inner.api.clone(), - graph: None, - exec: None, - done: None, - resources: Some(resources), - last: None, - launched: false, - nodes: None, - policy, - last_sequence: 0, - }; - // SIDE_MIXER: the side streams and their events exist before the capture begins (stream / event creation is not a capture-time call) - let side = if policy == OriginalCapturePolicy::VerifierWindow && SIDE_STREAMS_WANTED.load(std::sync::atomic::Ordering::Relaxed) { - match make_side(self.inner.context, &self.inner.api) { - Ok(side) => Some(side), - Err(e) => { - self.inner.capture.set(false); - return combine(Err(e), g.close_inner()); - } - } - } else { - None - }; - let begin = call(self.inner.context, &self.inner.api, |a| a.begin(h)); - if let Err(primary) = begin { - self.inner.capture.set(false); - let dropped = side.map_or(Ok(()), |side| drop_side(self.inner.context, &self.inner.api, side)); - return combine(combine(Err(primary), dropped), g.close_inner()); - } - let guard = match self.inner.context.enter() { - Ok(v) => v, - Err(e) => { - poison(self.inner.context); - return combine(Err(e), g.close_inner()); - } - }; - // Body errors are primary, but EndCapture is always attempted before retirement. - let mut token = OriginalCapture { - stream: &self.inner, - side, - target: Cell::new(None), - }; - let body_result = match g.resources.as_mut() { - Some(r) => body(&mut token, r), - None => Err(Error::ContextPoisoned), - }; - let resource_result = g - .resources - .as_ref() - .map_or(Err(Error::ContextPoisoned), |r| { - r.validate_context(self.inner.context) - }); - let body_result = combine(body_result, resource_result); - let end = self.inner.api.end(h); - self.inner.capture.set(false); - if let Ok(graph) = end.as_ref() { - g.graph = Some(*graph); - } - // the side streams ran nothing (their work is in the graph); the context is entered, so the handles are destroyed here - let side_closed = match side { - Some(side) => { - let r = (0..2).fold(Ok(()), |r, i| { - let r = combine(r, self.inner.api.event_destroy(side.fork[i])); - let r = combine(r, self.inner.api.event_destroy(side.join[i])); - combine(r, self.inner.api.stream_destroy(side.streams[i])) - }); - token.side = None; - r - } - None => Ok(()), - }; - let end = combine(end, side_closed); - let pop = guard.finish(); - if end.is_err() || pop.is_err() { - poison(self.inner.context); - self.inner.failed.set(true); - } - let finish = combine(combine(body_result, end.map(|_| ())), pop); - if let Err(primary) = finish { - return combine(Err(primary), g.close_inner()); - } - let graph = g.graph.ok_or(Error::ContextPoisoned)?; - let captured = std::time::Instant::now(); - capture_timing::add(0, (captured - started).as_secs_f64() * 1e3); - if policy == OriginalCapturePolicy::Registry || crate::host_profile::enabled() { - let n = call(g.context, &g.api, |a| a.nodes(graph))?; - g.nodes = Some(n); - if n == 0 { - return combine( - Err(Error::InvalidDriverValue("Original capture ZERO nodes")), - g.close_inner(), - ); - } - } - // Instantiating needs device memory of its own; on a card filled to the limit it can be refused. That refusal is not sticky and - // changes no state, so it must not poison the context: the caller (the window recorder) can fall back to fewer windows. - let exec = call_unless( - g.context, - &g.api, - |a| { - if injected_window_oom(policy) { - return Err(Error::Driver { operation: "cuGraphInstantiateWithFlags", code: CUDA_ERROR_OUT_OF_MEMORY }); - } - a.instantiate(graph) - }, - is_graph_out_of_memory, - ); - match exec { - Ok(exec) => g.exec = Some(exec), - Err(primary) => { - capture_timing::add(1, captured.elapsed().as_secs_f64() * 1e3); - if is_graph_out_of_memory(&primary) { - eprintln!("leleka-serve graph instantiate out of memory ({policy:?}); the context stays usable, the graph is dropped"); - } - return combine(Err(primary), g.close_inner()); - } - } - let instantiate = call(g.context, &g.api, |a| { - if policy == OriginalCapturePolicy::Registry { - g.done = Some(a.event_create(false)?); - } else { - a.graph_destroy(graph)?; - g.graph = None; - } - if matches!( - policy, - OriginalCapturePolicy::Mtp | OriginalCapturePolicy::VerifierWindow - ) { - let upload = a.upload(g.exec.ok_or(Error::ContextPoisoned)?, h); - // The upload only warms the graph up (the first launch would do it): running out of memory there costs the warm-up, - // not the engine (upstream 2a9a67c1). - let upload = match upload { - Err(e) if is_graph_out_of_memory(&e) => { - eprintln!("leleka-serve graph upload out of memory ({policy:?}); skipped, the first launch uploads"); - Ok(()) - } - other => other, - }; - let sync = a.stream_sync(h); - combine(upload, sync)?; - } - Ok(()) - }); - capture_timing::add(1, captured.elapsed().as_secs_f64() * 1e3); - if let Err(primary) = instantiate { - return combine(Err(primary), g.close_inner()); - } - Ok(g) - } - pub fn synchronize_with_receipt(&self) -> Result> { - self.synchronize()?; - Ok(OriginalStreamDrained { - stream: self.inner.clone(), - sequence: self.inner.sequence.get(), - }) - } - pub fn close(self) -> Result<()> { - if Rc::strong_count(&self.inner) != 1 { - return Err(Error::InvalidQwenShape); - } - self.inner.close() - } -} -/// Minted only after actual cuStreamSynchronize succeeds on this same stream. -pub struct OriginalStreamDrained<'ctx> { - stream: Rc>, - sequence: u64, -} -/// Exists only during real ThreadLocal capture. Private typed producers use the -/// actual stream handle; public callers cannot insert arbitrary kernel pointers. -pub struct OriginalCapture<'s, 'ctx> { - stream: &'s Stream<'ctx>, - /// claude/decode-sm120-switches (SIDE_MIXER): two side streams with their fork / join events, created before the capture begins when - /// `set_side_streams_wanted(true)` asked for them (a verifier window with the switch on), destroyed once the capture has ended. - side: Option, - /// While set, `stream_handle` hands out this side stream instead of the capture stream: the producers launch there. - target: Cell>, -} -#[derive(Clone, Copy)] -struct SideStreams { - streams: [usize; 2], - fork: [usize; 2], - join: [usize; 2], -} -static SIDE_STREAMS_WANTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -/// The next `VerifierWindow` capture creates the two side streams (SIDE_MIXER). Set by the window recorder around one recording. -pub(crate) fn set_side_streams_wanted(on: bool) { - SIDE_STREAMS_WANTED.store(on, std::sync::atomic::Ordering::Relaxed); -} -fn make_side(c: &Context<'_>, api: &abi::Api) -> Result { - call(c, api, |a| { - let mut out = SideStreams { streams: [0; 2], fork: [0; 2], join: [0; 2] }; - for i in 0..2 { - out.streams[i] = a.stream_create(true)?; - out.fork[i] = a.event_create(false)?; - out.join[i] = a.event_create(false)?; - } - Ok(out) - }) -} -/// Streams and events of a finished (or abandoned) capture; the side streams never ran anything, so no synchronization is owed. -fn drop_side(c: &Context<'_>, api: &abi::Api, side: SideStreams) -> Result<()> { - call(c, api, |a| { - let mut r = Ok(()); - for i in 0..2 { - r = combine(r, a.event_destroy(side.fork[i])); - r = combine(r, a.event_destroy(side.join[i])); - r = combine(r, a.stream_destroy(side.streams[i])); - } - r - }) -} -impl OriginalCapture<'_, '_> { - pub(crate) fn has_side(&self) -> bool { - self.side.is_some() - } - /// Branch the window's graph: everything captured on the capture stream so far is a dependency of what side stream `i` launches next, and - /// the producers launch on side stream `i` until `side_end(i)`. - pub(crate) fn side_fork(&self, i: usize) -> Result<()> { - let side = self.side.ok_or(Error::InvalidQwenShape)?; - let h = self.stream.validate()?; - self.stream.api.event_record(side.fork[i], h)?; - self.stream.api.stream_wait(side.streams[i], side.fork[i])?; - self.target.set(Some(side.streams[i])); - Ok(()) - } - /// End of side stream `i`'s work: the producers go back to the capture stream; `side_join(i)` makes the capture stream depend on it. - pub(crate) fn side_end(&self, i: usize) -> Result<()> { - let side = self.side.ok_or(Error::InvalidQwenShape)?; - self.stream.api.event_record(side.join[i], side.streams[i])?; - self.target.set(None); - Ok(()) - } - pub(crate) fn side_join(&self, i: usize) -> Result<()> { - let side = self.side.ok_or(Error::InvalidQwenShape)?; - let h = self.stream.validate()?; - self.stream.api.stream_wait(h, side.join[i]) - } - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.stream.context) { - return Err(Error::ContextMismatch); - } - if !self.stream.capture.get() { - return Err(Error::InvalidQwenShape); - } - self.stream.validate().map(|_| ()) - } - pub(crate) fn stream_handle(&self, c: &Context<'_>) -> Result { - self.validate_context(c)?; - let capture = self.stream.validate()?; - Ok(self.target.get().unwrap_or(capture)) - } -} -impl Drop for OriginalCapture<'_, '_> { - fn drop(&mut self) { - if self.stream.capture.replace(false) { - // This also ends a capture during unwinding before the graph's real resource - // owner is dropped. Failure poisons, causing that owner to be retained. - let r = call(self.stream.context, &self.stream.api, |a| { - let graph = a.end(self.stream.handle.get().ok_or(Error::ContextPoisoned)?)?; - a.graph_destroy(graph) - }); - if r.is_err() { - self.stream.failed.set(true); - } - } - } -} -/// One actual event. Re-records are only on its same real source stream, exactly -/// as Original stage copied/used/adapt/commit events; waits retain both streams. -pub struct OriginalGpuEvent<'ctx> { - context: &'ctx Context<'ctx>, - api: Rc, - handle: Option, - kind: OriginalEventKind, - source: Option>>, - waiters: [Option>>; 8], - recorded: bool, - sequence: u64, -} -impl<'ctx> OriginalGpuEvent<'ctx> { - fn handle(&self) -> Result { - healthy(self.context)?; - self.handle.ok_or(Error::ContextPoisoned) - } - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - self.handle().map(|_| ()) - } - pub fn record(&mut self, s: &OriginalGpuStream<'ctx>) -> Result<()> { - s.validate_context(self.context)?; - if s.inner.capture.get() { - return Err(Error::InvalidQwenShape); - } - if self - .source - .as_ref() - .is_some_and(|old| !Rc::ptr_eq(old, &s.inner)) - { - return Err(Error::ContextMismatch); - } - let e = self.handle()?; - let h = s.inner.validate()?; - let sequence = s.inner.bump()?; - self.source = Some(s.inner.clone()); - call(self.context, &self.api, |a| a.event_record(e, h))?; - self.recorded = true; - self.sequence = sequence; - Ok(()) - } - pub fn wait_on(&mut self, s: &OriginalGpuStream<'ctx>) -> Result<()> { - s.validate_context(self.context)?; - if !self.recorded || s.inner.capture.get() { - return Err(Error::InvalidQwenShape); - } - let e = self.handle()?; - let h = s.inner.validate()?; - let _sequence = s.inner.bump()?; - if !self - .waiters - .iter() - .flatten() - .any(|x| Rc::ptr_eq(x, &s.inner)) - { - let index = self - .waiters - .iter() - .position(Option::is_none) - .ok_or(Error::BudgetExceeded)?; - self.waiters[index] = Some(s.inner.clone()); - } - call(self.context, &self.api, |a| a.stream_wait(h, e)) - } - pub fn query(&self) -> Result { - if !self.recorded { - return Err(Error::InvalidQwenShape); - } - let h = self.handle()?; - call(self.context, &self.api, |a| a.event_query(h)) - } - pub fn synchronize(&self) -> Result<()> { - if !self.recorded { - return Err(Error::InvalidQwenShape); - } - let h = self.handle()?; - call(self.context, &self.api, |a| a.event_sync(h)) - } - pub fn elapsed_ms(&self, later: &Self) -> Result { - later.validate_context(self.context)?; - if self.kind != OriginalEventKind::Timing - || later.kind != OriginalEventKind::Timing - || !self.recorded - || !later.recorded - { - return Err(Error::InvalidQwenShape); - } - let a = self.handle()?; - let b = later.handle()?; - call(self.context, &self.api, |api| api.elapsed(a, b)) - } - pub fn is_failed(&self) -> bool { - self.context.is_poisoned() || self.handle.is_none() - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - fn close_inner(&mut self) -> Result<()> { - let Some(e) = self.handle.take() else { - return Ok(()); - }; - if self.context.is_poisoned() { - std::mem::forget(self.api.clone()); - return Err(Error::ContextPoisoned); - } - let r = call(self.context, &self.api, |a| { - let mut op = if self.recorded { - a.event_sync(e) - } else { - Ok(()) - }; - for s in self.waiters.iter().flatten() { - op = combine(op, a.stream_sync(s.validate()?)); - } - if op.is_err() { - return op; - } - a.event_destroy(e) - }); - if r.is_err() { - std::mem::forget(self.api.clone()); - } - r - } -} -impl Drop for OriginalGpuEvent<'_> { - fn drop(&mut self) { - let _ = self.close_inner(); - } -} -/// Keeps actual fixed-address device/mapped-host/modules/ABI resource owner R. -/// Changing replay inputs changes their DATA only, never captured kernel arguments. -pub struct OriginalGpuGraph<'ctx, R: OriginalGraphResources> { - context: &'ctx Context<'ctx>, - api: Rc, - graph: Option, - exec: Option, - done: Option, - resources: Option, - last: Option>>, - launched: bool, - nodes: Option, - policy: OriginalCapturePolicy, - last_sequence: u64, -} -impl<'ctx, R: OriginalGraphResources> OriginalGpuGraph<'ctx, R> { - fn validate(&self) -> Result { - healthy(self.context)?; - self.resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate_context(self.context)?; - self.exec.ok_or(Error::ContextPoisoned) - } - pub fn nodes(&self) -> Option { - self.nodes - } - pub fn policy(&self) -> OriginalCapturePolicy { - self.policy - } - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - self.validate().map(|_| ()) - } - /// Enqueue without a host wait, matching Original pre/post/token replay loops. - /// Same-executable overlapping launches are ordered on its same actual stream. - pub fn enqueue(&mut self, s: &OriginalGpuStream<'ctx>) -> Result<()> { - s.validate_context(self.context)?; - if s.inner.capture.get() { - return Err(Error::InvalidQwenShape); - } - if self.launched - && self - .last - .as_ref() - .is_some_and(|old| !Rc::ptr_eq(old, &s.inner)) - { - return Err(Error::ContextMismatch); - } - let ex = self.validate()?; - self.resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate_replay_context(self.context)?; - let st = s.inner.validate()?; - let sequence = s.inner.bump()?; - self.last = Some(s.inner.clone()); - self.launched = true; - self.last_sequence = sequence; - call(self.context, &self.api, |a| { - a.launch(ex, st)?; - if let Some(e) = self.done { - a.event_record(e, st)?; - } - Ok(()) - }) - } - pub fn launch<'g>( - &'g mut self, - s: &OriginalGpuStream<'ctx>, - ) -> Result> { - self.enqueue(s)?; - Ok(OriginalGraphFlight { - graph: self, - active: true, - }) - } - /// Actual completion receipt from the final same-stream fence. No caller - /// boolean or other Context/stream can authorize retirement. - pub fn resources_after_stream_drain( - &mut self, - done: &OriginalStreamDrained<'ctx>, - ) -> Result<&R> { - self.validate()?; - healthy(self.context)?; - if self.launched { - let last = self.last.as_ref().ok_or(Error::ContextPoisoned)?; - if !Rc::ptr_eq(last, &done.stream) || done.sequence < self.last_sequence { - return Err(Error::InvalidQwenShape); - } - self.launched = false; - } - self.resources.as_ref().ok_or(Error::ContextPoisoned) - } - /// A real later recorded event on the SAME stream can retire many layer graphs - /// with one Original token/commit probe. Its driver query and sequence are checked - /// here; an earlier event or caller boolean never authorizes resource mutation. - pub fn resources_after_event(&mut self, event: &OriginalGpuEvent<'ctx>) -> Result<&R> { - self.validate()?; - event.validate_context(self.context)?; - if self.launched { - let source = self.last.as_ref().ok_or(Error::ContextPoisoned)?; - if !event.source.as_ref().is_some_and(|s| Rc::ptr_eq(s, source)) - || event.sequence <= self.last_sequence - || !event.query()? - { - return Err(Error::InvalidQwenShape); - } - self.launched = false; - } - self.resources.as_ref().ok_or(Error::ContextPoisoned) - } - pub fn resources_after_wait(&mut self) -> Result<&R> { - self.wait_inner()?; - healthy(self.context)?; - self.resources.as_ref().ok_or(Error::ContextPoisoned) - } - fn query_inner(&mut self) -> Result { - self.validate()?; - if !self.launched { - return Ok(true); - } - let stream = self - .last - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate()?; - let q = call(self.context, &self.api, |a| { - if let Some(e) = self.done { - a.event_query(e) - } else { - a.stream_query(stream) - } - })?; - if q { - self.launched = false; - } - Ok(q) - } - fn wait_inner(&mut self) -> Result<()> { - self.validate()?; - if !self.launched { - return Ok(()); - } - let s = self - .last - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate()?; - call(self.context, &self.api, |a| a.stream_sync(s))?; - self.launched = false; - Ok(()) - } - pub fn is_failed(&self) -> bool { - self.context.is_poisoned() || self.exec.is_none() - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - fn close_inner(&mut self) -> Result<()> { - // Failed completion retains actual R (including host DMA sources), not just an - // accounting receipt. A poisoned Context's finalizer likewise retains VRAM. - if self.context.is_poisoned() { - if let Some(r) = self.resources.take() { - std::mem::forget(r); - } - std::mem::forget(self.api.clone()); - self.exec.take(); - self.graph.take(); - self.done.take(); - return Err(Error::ContextPoisoned); - } - if self.exec.is_none() && self.graph.is_none() && self.done.is_none() { - return Ok(()); - } - let stream = self.last.as_ref().and_then(|s| s.handle.get()); - let r = call(self.context, &self.api, |a| { - let drained = if self.launched { - stream.map_or(Err(Error::ContextPoisoned), |s| a.stream_sync(s)) - } else { - Ok(()) - }; - if drained.is_err() { - return drained; - } - // Original reset order is executable -> graph -> completion event. - let mut result = Ok(()); - if let Some(e) = self.exec.take() { - result = combine(result, a.exec_destroy(e)); - } - if let Some(g) = self.graph.take() { - result = combine(result, a.graph_destroy(g)); - } - if let Some(e) = self.done.take() { - result = combine(result, a.event_destroy(e)); - } - result - }); - if r.is_err() { - if let Some(resources) = self.resources.take() { - std::mem::forget(resources); - } - std::mem::forget(self.api.clone()); - self.exec.take(); - self.graph.take(); - self.done.take(); - } else { - self.launched = false; - self.resources.take(); - } - r - } -} -impl Drop for OriginalGpuGraph<'_, R> { - fn drop(&mut self) { - let _ = self.close_inner(); - } -} -/// Actual submitted work exclusively borrows its graph/resources until query or -/// sync observes completion. Dropping an unfinished flight attempts a real drain. -pub struct OriginalGraphFlight<'g, 'ctx, R: OriginalGraphResources> { - graph: &'g mut OriginalGpuGraph<'ctx, R>, - active: bool, -} -impl OriginalGraphFlight<'_, '_, R> { - pub fn query(&mut self) -> Result { - let done = self.graph.query_inner()?; - if done { - self.active = false; - } - Ok(done) - } - pub fn wait(mut self) -> Result<()> { - let result = self.graph.wait_inner(); - if result.is_ok() { - self.active = false; - } - result - } - /// Registry's wait polls actual driver completion on a real monotonic deadline, - /// with64 pauses between polls. Timeout keeps the graph pending; it never means ready. - pub fn wait_ms(mut self, timeout: Duration) -> Result { - let start = Instant::now(); - loop { - if self.query()? { - return Ok(OriginalWait::Complete); - } - if start.elapsed() >= timeout { - self.active = false; - return Ok(OriginalWait::TimedOut); - } - for _ in 0..64 { - std::hint::spin_loop(); - } - } - } -} -impl Drop for OriginalGraphFlight<'_, '_, R> { - fn drop(&mut self) { - if self.active { - let _ = self.graph.wait_inner(); - } - } -} - -/// Literal graph identities, with Original layer/token/window/coupled separation. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum OriginalGraphKey { - LayerPre(u8), - LayerPost(u8), - LayerPreA(u8), - LayerPreB(u8), - LayerPrefix { layer: u8, stages: u8 }, - Token, - VerifyWindow(u8), - VerifyCommit, - MtpPrefill { rows: u8, device_inputs: bool }, - MtpRound { rows: u8, coupled: bool }, - MtpStep { step: u8, coupled: bool }, - Registry { qsa: bool, tokens: u32 }, -} -impl OriginalGraphKey { - fn validate(self) -> Result<()> { - let valid = match self { - Self::LayerPre(l) | Self::LayerPost(l) | Self::LayerPreA(l) | Self::LayerPreB(l) => { - l < 48 - } - Self::LayerPrefix { layer, stages } => layer < 48 && (1..=5).contains(&stages), - Self::Token | Self::VerifyCommit => true, - Self::VerifyWindow(t) => (1..=8).contains(&t), - Self::MtpPrefill { rows, .. } | Self::MtpRound { rows, .. } => (1..=8).contains(&rows), - Self::MtpStep { step, .. } => (1..=6).contains(&step), - Self::Registry { tokens, .. } => tokens > 0, - }; - if valid { - Ok(()) - } else { - Err(Error::InvalidQwenShape) - } - } - fn policy(self) -> OriginalCapturePolicy { - match self { - Self::VerifyWindow(_) => OriginalCapturePolicy::VerifierWindow, - Self::VerifyCommit => OriginalCapturePolicy::VerifierCommit, - Self::MtpPrefill { .. } | Self::MtpRound { .. } | Self::MtpStep { .. } => { - OriginalCapturePolicy::Mtp - } - Self::Registry { .. } => OriginalCapturePolicy::Registry, - _ => OriginalCapturePolicy::Session, - } - } -} -/// Fixed upfront capacity, capture-once/replay-many: a hit never calls either -/// resource preparation or the body. No insertion can realloc captured owners. -pub struct OriginalGraphRegistry<'ctx, R: OriginalGraphResources> { - context: &'ctx Context<'ctx>, - entries: Vec<(OriginalGraphKey, OriginalGpuGraph<'ctx, R>)>, - capacity: usize, - captures: u64, -} -impl<'ctx, R: OriginalGraphResources> OriginalGraphRegistry<'ctx, R> { - pub fn new(context: &'ctx Context<'ctx>, capacity: usize) -> Result { - healthy(context)?; - Self::planned_metadata_bytes(capacity)?; - let mut entries = Vec::new(); - entries - .try_reserve_exact(capacity) - .map_err(|_| Error::HostAllocation)?; - if entries - .capacity() - .checked_mul(std::mem::size_of::<( - OriginalGraphKey, - OriginalGpuGraph<'ctx, R>, - )>()) - .and_then(|n| n.checked_add(std::mem::size_of::())) - .is_none_or(|n| n > 16 * 1024 * 1024) - { - return Err(Error::BudgetExceeded); - } - Ok(Self { - context, - entries, - capacity, - captures: 0, - }) - } - pub fn planned_metadata_bytes(capacity: usize) -> Result { - if !(1..=512).contains(&capacity) { - return Err(Error::InvalidQwenShape); - } - let bytes = capacity - .checked_mul(std::mem::size_of::<( - OriginalGraphKey, - OriginalGpuGraph<'ctx, R>, - )>()) - .and_then(|n| n.checked_add(std::mem::size_of::())) - .ok_or(Error::BudgetExceeded)?; - if bytes > 16 * 1024 * 1024 { - return Err(Error::BudgetExceeded); - } - Ok(bytes) - } - pub fn metadata_bytes(&self) -> usize { - self.entries.capacity() - * std::mem::size_of::<(OriginalGraphKey, OriginalGpuGraph<'ctx, R>)>() - + std::mem::size_of::() - } - pub fn captures(&self) -> u64 { - self.captures - } - pub fn len(&self) -> usize { - self.entries.len() - } - pub fn is_empty(&self) -> bool { - self.entries.is_empty() - } - pub fn find_mut( - &mut self, - key: OriginalGraphKey, - ) -> Result>> { - key.validate()?; - healthy(self.context)?; - Ok(self - .entries - .iter_mut() - .find(|(k, _)| *k == key) - .map(|(_, g)| g)) - } - pub fn record( - &mut self, - key: OriginalGraphKey, - stream: &mut OriginalGpuStream<'ctx>, - prepare: impl FnOnce() -> Result, - body: impl FnOnce(&mut OriginalCapture<'_, 'ctx>, &mut R) -> Result<()>, - ) -> Result<&mut OriginalGpuGraph<'ctx, R>> { - key.validate()?; - stream.validate_context(self.context)?; - if let Some(index) = self.entries.iter().position(|(k, _)| *k == key) { - return Ok(&mut self.entries[index].1); - } - if self.entries.len() == self.capacity { - return Err(Error::BudgetExceeded); - } - let captures = self - .captures - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - let graph = stream.capture_owned(key.policy(), prepare()?, body)?; - let index = self.entries.len(); - self.entries.push((key, graph)); - self.captures = captures; - Ok(&mut self.entries[index].1) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - /// Close every cached graph but keep the registry (and its capture counter) for new captures. - pub fn clear(&mut self) -> Result<()> { - self.close_inner() - } - fn close_inner(&mut self) -> Result<()> { - let mut result = Ok(()); - while let Some((_, g)) = self.entries.pop() { - result = combine(result, g.close()); - } - result - } -} -impl Drop for OriginalGraphRegistry<'_, R> { - fn drop(&mut self) { - let _ = self.close_inner(); - } -} - -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -#[path = "original_gpu_head_bridge.rs"] -mod native_head_bridge; - -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -#[path = "original_gpu_verify_bridge.rs"] -mod verifier_bridge; - -/// Operator timing of `capture_owned` (host ms spent capturing, then instantiating + uploading), summed per thread -/// since the last `take`; read by the serve profile. -pub mod capture_timing { - use std::cell::Cell; - thread_local! { static SUMS: Cell<[f64; 3]> = const { Cell::new([0.0; 3]) }; } - pub(crate) fn add(slot: usize, ms: f64) { - SUMS.with(|s| { - let mut v = s.get(); - v[slot] += ms; - s.set(v); - }); - } - /// (capture ms, instantiate + upload ms, verifier window module loading ms) since the last call. - pub fn take() -> (f64, f64, f64) { - let v = SUMS.with(|s| s.replace([0.0; 3])); - (v[0], v[1], v[2]) - } -} - -#[cfg(test)] -mod oom_tests { - use super::*; - - const OOM: Error = Error::Driver { operation: "cuGraphInstantiateWithFlags", code: CUDA_ERROR_OUT_OF_MEMORY }; - - #[test] - fn an_instantiate_out_of_memory_does_not_poison_the_context_but_every_other_failure_does() { - let failed: Result = Err(OOM); - // `call` (nothing recoverable): any error poisons, as it always did - assert!(poisons(&failed, false, |_| false)); - // the instantiate step: the out-of-memory refusal leaves the context usable ... - assert!(!poisons(&failed, false, is_graph_out_of_memory)); - // ... unless the context pop failed too, or the error is not that refusal - assert!(poisons(&failed, true, is_graph_out_of_memory)); - for other in [ - Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 1 }, - Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 700 }, - Error::Driver { operation: "cuStreamSynchronize", code: CUDA_ERROR_OUT_OF_MEMORY }, - Error::Multiple { primary: Box::new(OOM), secondary: Box::new(Error::ContextPoisoned) }, - ] { - assert!(poisons::(&Err(other.clone()), false, is_graph_out_of_memory), "{other:?}"); - } - assert!(!poisons(&Ok(1usize), false, is_graph_out_of_memory)); - assert!(poisons(&Ok(1usize), true, is_graph_out_of_memory)); - } - - #[test] - fn only_the_graph_calls_count_as_a_recoverable_out_of_memory() { - assert!(is_graph_out_of_memory(&OOM)); - assert!(is_graph_out_of_memory(&Error::Driver { operation: "cuGraphUpload", code: 2 })); - assert!(!is_graph_out_of_memory(&Error::Driver { operation: "cuGraphLaunch", code: 2 })); - assert!(!is_graph_out_of_memory(&Error::Driver { operation: "cuGraphUpload", code: 999 })); - assert!(!is_graph_out_of_memory(&Error::HostAllocation)); - } -} +//! Original CUDA scheduling owners. Capture resources are real owned/borrowed +//! producers, retained through every replay and through uncertain retirement. +//! No public raw stream, graph, event, kernel address or readiness constructor. +#[path = "original_gpu_schedule_ffi.rs"] +mod abi; +use crate::{Context, Error, Result, combine}; +use std::{ + cell::Cell, + rc::Rc, + time::{Duration, Instant}, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OriginalStreamKind { + BlockingCapture, + NonBlocking, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OriginalEventKind { + Timing, + Completion, +} +/// Concrete Original call-site policies: session graphs do not explicitly upload; +/// MTP and verifier window graphs upload+sync; the verifier commit does not. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OriginalCapturePolicy { + Session, + VerifierWindow, + VerifierCommit, + Mtp, + Registry, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OriginalWait { + Complete, + TimedOut, +} +/// Implemented only by actual closed driver producer banks. Arbitrary public +/// host floats, pointer tables or caller readiness bits cannot mint this trait. +pub(crate) mod resources { + pub trait Sealed {} +} +pub trait OriginalGraphResources: resources::Sealed { + fn validate_context(&self, context: &Context<'_>) -> Result<()>; + fn validate_replay_context(&self, context: &Context<'_>) -> Result<()> { + self.validate_context(context) + } +} + +#[path = "mtp_original_full_graph.rs"] +mod mtp_full_graph; +fn transport(e: &Error) -> bool { + match e { + Error::Driver { .. } | Error::ContextPoisoned | Error::UnexpectedContext => true, + Error::Multiple { primary, secondary } => transport(primary) || transport(secondary), + _ => false, + } +} +fn poison(c: &Context<'_>) { + c.poison(); + c.retain_driver(); +} +fn healthy(c: &Context<'_>) -> Result<()> { + if c.is_poisoned() || c.handle.is_none() { + Err(Error::ContextPoisoned) + } else { + Ok(()) + } +} +/// `CUDA_ERROR_OUT_OF_MEMORY` of the driver API. Not sticky: the context is intact after it. +const CUDA_ERROR_OUT_OF_MEMORY: i32 = 2; +/// A graph instantiate (or upload) that ran out of device memory. Recoverable: the call did not run, no state changed, and the +/// driver returns the memory-allocation error without a sticky error (upstream a8c1d4b7 / 2a9a67c1: their engine died on it). +/// Only a bare driver error counts; one wrapped in `Multiple` carries a cleanup failure too, and that is fatal. +pub(crate) fn is_graph_out_of_memory(e: &Error) -> bool { + matches!( + e, + Error::Driver { operation: "cuGraphInstantiateWithFlags" | "cuGraphUpload", code: CUDA_ERROR_OUT_OF_MEMORY } + ) +} +/// Whether a driver call that ended with `op` (and whose context pop gave `pop_failed`) leaves the context unusable. +fn poisons(op: &Result, pop_failed: bool, recoverable: fn(&Error) -> bool) -> bool { + pop_failed || op.as_ref().err().is_some_and(|e| !recoverable(e)) +} +fn call(c: &Context<'_>, api: &abi::Api, f: impl FnOnce(&abi::Api) -> Result) -> Result { + call_unless(c, api, f, |_| false) +} +/// `call`, except that an error `recoverable` accepts does not poison the context (the caller undoes what it did and goes on). +fn call_unless(c: &Context<'_>, api: &abi::Api, f: impl FnOnce(&abi::Api) -> Result, recoverable: fn(&Error) -> bool) -> Result { + healthy(c)?; + let guard = c.enter().inspect_err(|_| poison(c))?; + let op = f(api); + let pop = guard.finish(); + if poisons(&op, pop.is_err(), recoverable) { + poison(c); + } + combine(op, pop) +} +/// Test hook (off unless set): `LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT=N` makes the N-th (1-based) verifier-window graph +/// instantiation of the process fail once with the driver's out-of-memory code, so the fallback can be exercised on a card with room. +fn injected_window_oom(policy: OriginalCapturePolicy) -> bool { + static AT: std::sync::OnceLock = std::sync::OnceLock::new(); + static SEEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + if policy != OriginalCapturePolicy::VerifierWindow { + return false; + } + let at = *AT.get_or_init(|| std::env::var("LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)); + at != 0 && SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1 == at +} +struct Stream<'ctx> { + context: &'ctx Context<'ctx>, + api: Rc, + handle: Cell>, + capture: Cell, + failed: Cell, + sequence: Cell, +} +impl Stream<'_> { + fn bump(&self) -> Result { + let next = self + .sequence + .get() + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + self.sequence.set(next); + Ok(next) + } + fn validate(&self) -> Result { + healthy(self.context)?; + if self.failed.get() { + return Err(Error::ContextPoisoned); + } + self.handle.get().ok_or(Error::ContextPoisoned) + } + fn run(&self, f: impl FnOnce(&abi::Api, usize) -> Result) -> Result { + let h = self.validate()?; + let r = call(self.context, &self.api, |a| f(a, h)); + if r.is_err() { + self.failed.set(true); + } + r + } + fn close(&self) -> Result<()> { + let Some(h) = self.handle.take() else { + return Ok(()); + }; + if self.context.is_poisoned() { + self.failed.set(true); + std::mem::forget(self.api.clone()); + return Err(Error::ContextPoisoned); + } + // Ending a capture is mandatory even when its typed body failed. + let mut graph = None; + let op = call(self.context, &self.api, |a| { + let ended = if self.capture.replace(false) { + match a.end(h) { + Ok(g) => { + graph = Some(g); + Ok(()) + } + Err(e) => Err(e), + } + } else { + Ok(()) + }; + let sync = a.stream_sync(h); + let destroy = if sync.is_ok() { + if h == 0 { Ok(()) } else { a.stream_destroy(h) } + } else { + Err(Error::ContextPoisoned) + }; + let destroy_graph = if sync.is_ok() { + graph.take().map_or(Ok(()), |g| a.graph_destroy(g)) + } else { + Err(Error::ContextPoisoned) + }; + combine(combine(combine(ended, sync), destroy), destroy_graph) + }); + if op.is_err() { + self.failed.set(true); + std::mem::forget(self.api.clone()); + } + op + } +} +impl Drop for Stream<'_> { + fn drop(&mut self) { + let _ = self.close(); + } +} +/// Rc is private and only genuine dependencies can retain the actual stream. +pub struct OriginalGpuStream<'ctx> { + inner: Rc>, +} +impl Context<'_> { + /// Genuine legacy default CUDA stream for Original Prefill arithmetic. No + /// stream-create call and no destroy0; Context-affine actual owner identity. + pub fn original_default_gpu_stream(&self) -> Result> { + healthy(self)?; + let api = Rc::new(abi::Api::load()?); + Ok(OriginalGpuStream { + inner: Rc::new(Stream { + context: self, + api, + handle: Cell::new(Some(0)), + capture: Cell::new(false), + failed: Cell::new(false), + sequence: Cell::new(0), + }), + }) + } + pub fn original_gpu_stream(&self, kind: OriginalStreamKind) -> Result> { + healthy(self)?; + let api = Rc::new(abi::Api::load()?); + let h = call(self, &api, |a| { + a.stream_create(kind == OriginalStreamKind::NonBlocking) + }) + .inspect_err(|_| std::mem::forget(api.clone()))?; + Ok(OriginalGpuStream { + inner: Rc::new(Stream { + context: self, + api, + handle: Cell::new(Some(h)), + capture: Cell::new(false), + failed: Cell::new(false), + sequence: Cell::new(0), + }), + }) + } + pub fn original_gpu_event(&self, kind: OriginalEventKind) -> Result> { + healthy(self)?; + let api = Rc::new(abi::Api::load()?); + let h = call(self, &api, |a| { + a.event_create(kind == OriginalEventKind::Timing) + }) + .inspect_err(|_| std::mem::forget(api.clone()))?; + Ok(OriginalGpuEvent { + context: self, + api, + handle: Some(h), + kind, + source: None, + waiters: std::array::from_fn(|_| None), + recorded: false, + sequence: 0, + }) + } +} +impl<'ctx> OriginalGpuStream<'ctx> { + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.inner.context) { + return Err(Error::ContextMismatch); + } + self.inner.validate().map(|_| ()) + } + pub fn is_failed(&self) -> bool { + self.inner.failed.get() + || self.inner.context.is_poisoned() + || self.inner.handle.get().is_none() + } + pub fn priority(&self) -> Result { + self.inner.run(|a, h| a.stream_priority(h)) + } // Observational only; Original never overrides priority. + pub fn query(&self) -> Result { + if self.inner.capture.get() { + return Err(Error::InvalidQwenShape); + } + self.inner.run(|a, h| a.stream_query(h)) + } + pub fn synchronize(&self) -> Result<()> { + if self.inner.capture.get() { + return Err(Error::InvalidQwenShape); + } + self.inner.run(|a, h| a.stream_sync(h)) + } + /// `fetch_dma`'s `cudaMemcpyAsync` of one registered source span into device staging. The caller retains + /// the registered source and the destination allocation until this stream's next fence. + pub(crate) fn enqueue_copy_h2d(&mut self, destination: u64, source: &[u8]) -> Result<()> { + if self.inner.capture.get() || source.is_empty() || destination == 0 { + return Err(Error::InvalidQwenShape); + } + self.inner.bump()?; + self.inner.run(|a, h| a.copy_h2d(destination, source, h)) + } + /// All the DMA pieces of one group in a single context entry (`batch`: one `cuMemcpyBatchAsync`). Same contract as + /// `enqueue_copy_h2d` for every piece. + pub(crate) fn enqueue_copy_h2d_many(&mut self, pieces: &[(u64, &[u8])], batch: bool) -> Result<()> { + if self.inner.capture.get() || pieces.is_empty() || pieces.iter().any(|p| p.0 == 0 || p.1.is_empty()) { + return Err(Error::InvalidQwenShape); + } + self.inner.bump()?; + self.inner.run(|a, h| a.copy_h2d_many(pieces, h, batch)) + } + /// Flag B after every earlier operation of this stream: `cuStreamWriteValue32` of the word's device alias when the + /// driver takes it (no callback thread), else the host callback of `enqueue_raise_u32`. The word's owner must outlive + /// this stream's next fence. + pub(crate) fn enqueue_raise_flag(&mut self, host_word: usize, device_address: u64, value: u32) -> Result<()> { + if self.inner.capture.get() { + return Err(Error::InvalidQwenShape); + } + self.inner.bump()?; + self.inner.run(|a, h| a.raise_flag_after(h, host_word, device_address, value)) + } + /// `fetch_dma`'s `cudaLaunchHostFunc(raise_flag)`: the mapped host word rises to `value` after every + /// earlier operation of this stream. The word's owner must outlive this stream's next fence. + pub(crate) fn enqueue_raise_u32(&mut self, word: usize, value: u32) -> Result<()> { + if self.inner.capture.get() { + return Err(Error::InvalidQwenShape); + } + self.inner.bump()?; + self.inner.run(|a, h| a.raise_u32_after(h, word, value)) + } + /// Only closed typed driver producers may enqueue via this private validated handle. + /// Their stable ABI/device/mapped owners MUST live in capture resources R. + pub(crate) fn with_enqueue(&mut self, f: impl FnOnce(usize) -> Result) -> Result { + let h = self.inner.validate()?; + if self.inner.capture.get() { + return Err(Error::InvalidQwenShape); + } + let _sequence = self.inner.bump()?; + let guard = self + .inner + .context + .enter() + .inspect_err(|_| poison(self.inner.context))?; + let op = f(h); + let pop = guard.finish(); + if op.as_ref().err().is_some_and(transport) || pop.is_err() { + poison(self.inner.context); + self.inner.failed.set(true); + } + combine(op, pop) + } + pub fn capture_owned( + &mut self, + policy: OriginalCapturePolicy, + resources: R, + body: impl FnOnce(&mut OriginalCapture<'_, 'ctx>, &mut R) -> Result<()>, + ) -> Result> { + let started = std::time::Instant::now(); + resources.validate_context(self.inner.context)?; + let h = self.inner.validate()?; + if h == 0 { + return Err(Error::InvalidQwenShape); + } + if self.inner.capture.replace(true) { + return Err(Error::InvalidQwenShape); + } + let mut g = OriginalGpuGraph { + context: self.inner.context, + api: self.inner.api.clone(), + graph: None, + exec: None, + done: None, + resources: Some(resources), + last: None, + launched: false, + nodes: None, + policy, + last_sequence: 0, + }; + // SIDE_MIXER: the side streams and their events exist before the capture begins (stream / event creation is not a capture-time call) + let side = if policy == OriginalCapturePolicy::VerifierWindow && SIDE_STREAMS_WANTED.load(std::sync::atomic::Ordering::Relaxed) { + match make_side(self.inner.context, &self.inner.api) { + Ok(side) => Some(side), + Err(e) => { + self.inner.capture.set(false); + return combine(Err(e), g.close_inner()); + } + } + } else { + None + }; + let begin = call(self.inner.context, &self.inner.api, |a| a.begin(h)); + if let Err(primary) = begin { + self.inner.capture.set(false); + let dropped = side.map_or(Ok(()), |side| drop_side(self.inner.context, &self.inner.api, side)); + return combine(combine(Err(primary), dropped), g.close_inner()); + } + let guard = match self.inner.context.enter() { + Ok(v) => v, + Err(e) => { + poison(self.inner.context); + return combine(Err(e), g.close_inner()); + } + }; + // Body errors are primary, but EndCapture is always attempted before retirement. + let mut token = OriginalCapture { + stream: &self.inner, + side, + target: Cell::new(None), + }; + let body_result = match g.resources.as_mut() { + Some(r) => body(&mut token, r), + None => Err(Error::ContextPoisoned), + }; + let resource_result = g + .resources + .as_ref() + .map_or(Err(Error::ContextPoisoned), |r| { + r.validate_context(self.inner.context) + }); + let body_result = combine(body_result, resource_result); + let end = self.inner.api.end(h); + self.inner.capture.set(false); + if let Ok(graph) = end.as_ref() { + g.graph = Some(*graph); + } + // the side streams ran nothing (their work is in the graph); the context is entered, so the handles are destroyed here + let side_closed = match side { + Some(side) => { + let r = (0..2).fold(Ok(()), |r, i| { + let r = combine(r, self.inner.api.event_destroy(side.fork[i])); + let r = combine(r, self.inner.api.event_destroy(side.join[i])); + combine(r, self.inner.api.stream_destroy(side.streams[i])) + }); + token.side = None; + r + } + None => Ok(()), + }; + let end = combine(end, side_closed); + let pop = guard.finish(); + if end.is_err() || pop.is_err() { + poison(self.inner.context); + self.inner.failed.set(true); + } + let finish = combine(combine(body_result, end.map(|_| ())), pop); + if let Err(primary) = finish { + return combine(Err(primary), g.close_inner()); + } + let graph = g.graph.ok_or(Error::ContextPoisoned)?; + let captured = std::time::Instant::now(); + capture_timing::add(0, (captured - started).as_secs_f64() * 1e3); + if policy == OriginalCapturePolicy::Registry || crate::host_profile::enabled() { + let n = call(g.context, &g.api, |a| a.nodes(graph))?; + g.nodes = Some(n); + if n == 0 { + return combine( + Err(Error::InvalidDriverValue("Original capture ZERO nodes")), + g.close_inner(), + ); + } + } + // Instantiating needs device memory of its own; on a card filled to the limit it can be refused. That refusal is not sticky and + // changes no state, so it must not poison the context: the caller (the window recorder) can fall back to fewer windows. + let exec = call_unless( + g.context, + &g.api, + |a| { + if injected_window_oom(policy) { + return Err(Error::Driver { operation: "cuGraphInstantiateWithFlags", code: CUDA_ERROR_OUT_OF_MEMORY }); + } + a.instantiate(graph) + }, + is_graph_out_of_memory, + ); + match exec { + Ok(exec) => g.exec = Some(exec), + Err(primary) => { + capture_timing::add(1, captured.elapsed().as_secs_f64() * 1e3); + if is_graph_out_of_memory(&primary) { + eprintln!("leleka-serve graph instantiate out of memory ({policy:?}); the context stays usable, the graph is dropped"); + } + return combine(Err(primary), g.close_inner()); + } + } + let instantiate = call(g.context, &g.api, |a| { + if policy == OriginalCapturePolicy::Registry { + g.done = Some(a.event_create(false)?); + } else { + a.graph_destroy(graph)?; + g.graph = None; + } + if matches!( + policy, + OriginalCapturePolicy::Mtp | OriginalCapturePolicy::VerifierWindow + ) { + let upload = a.upload(g.exec.ok_or(Error::ContextPoisoned)?, h); + // The upload only warms the graph up (the first launch would do it): running out of memory there costs the warm-up, + // not the engine (upstream 2a9a67c1). + let upload = match upload { + Err(e) if is_graph_out_of_memory(&e) => { + eprintln!("leleka-serve graph upload out of memory ({policy:?}); skipped, the first launch uploads"); + Ok(()) + } + other => other, + }; + let sync = a.stream_sync(h); + combine(upload, sync)?; + } + Ok(()) + }); + capture_timing::add(1, captured.elapsed().as_secs_f64() * 1e3); + if let Err(primary) = instantiate { + return combine(Err(primary), g.close_inner()); + } + Ok(g) + } + pub fn synchronize_with_receipt(&self) -> Result> { + self.synchronize()?; + Ok(OriginalStreamDrained { + stream: self.inner.clone(), + sequence: self.inner.sequence.get(), + }) + } + pub fn close(self) -> Result<()> { + if Rc::strong_count(&self.inner) != 1 { + return Err(Error::InvalidQwenShape); + } + self.inner.close() + } +} +/// Minted only after actual cuStreamSynchronize succeeds on this same stream. +pub struct OriginalStreamDrained<'ctx> { + stream: Rc>, + sequence: u64, +} +/// Exists only during real ThreadLocal capture. Private typed producers use the +/// actual stream handle; public callers cannot insert arbitrary kernel pointers. +pub struct OriginalCapture<'s, 'ctx> { + stream: &'s Stream<'ctx>, + /// claude/decode-sm120-switches (SIDE_MIXER): two side streams with their fork / join events, created before the capture begins when + /// `set_side_streams_wanted(true)` asked for them (a verifier window with the switch on), destroyed once the capture has ended. + side: Option, + /// While set, `stream_handle` hands out this side stream instead of the capture stream: the producers launch there. + target: Cell>, +} +#[derive(Clone, Copy)] +struct SideStreams { + streams: [usize; 2], + fork: [usize; 2], + join: [usize; 2], +} +static SIDE_STREAMS_WANTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// The next `VerifierWindow` capture creates the two side streams (SIDE_MIXER). Set by the window recorder around one recording. +pub(crate) fn set_side_streams_wanted(on: bool) { + SIDE_STREAMS_WANTED.store(on, std::sync::atomic::Ordering::Relaxed); +} +fn make_side(c: &Context<'_>, api: &abi::Api) -> Result { + call(c, api, |a| { + let mut out = SideStreams { streams: [0; 2], fork: [0; 2], join: [0; 2] }; + for i in 0..2 { + out.streams[i] = a.stream_create(true)?; + out.fork[i] = a.event_create(false)?; + out.join[i] = a.event_create(false)?; + } + Ok(out) + }) +} +/// Streams and events of a finished (or abandoned) capture; the side streams never ran anything, so no synchronization is owed. +fn drop_side(c: &Context<'_>, api: &abi::Api, side: SideStreams) -> Result<()> { + call(c, api, |a| { + let mut r = Ok(()); + for i in 0..2 { + r = combine(r, a.event_destroy(side.fork[i])); + r = combine(r, a.event_destroy(side.join[i])); + r = combine(r, a.stream_destroy(side.streams[i])); + } + r + }) +} +impl OriginalCapture<'_, '_> { + pub(crate) fn has_side(&self) -> bool { + self.side.is_some() + } + /// Branch the window's graph: everything captured on the capture stream so far is a dependency of what side stream `i` launches next, and + /// the producers launch on side stream `i` until `side_end(i)`. + pub(crate) fn side_fork(&self, i: usize) -> Result<()> { + let side = self.side.ok_or(Error::InvalidQwenShape)?; + let h = self.stream.validate()?; + self.stream.api.event_record(side.fork[i], h)?; + self.stream.api.stream_wait(side.streams[i], side.fork[i])?; + self.target.set(Some(side.streams[i])); + Ok(()) + } + /// End of side stream `i`'s work: the producers go back to the capture stream; `side_join(i)` makes the capture stream depend on it. + pub(crate) fn side_end(&self, i: usize) -> Result<()> { + let side = self.side.ok_or(Error::InvalidQwenShape)?; + self.stream.api.event_record(side.join[i], side.streams[i])?; + self.target.set(None); + Ok(()) + } + pub(crate) fn side_join(&self, i: usize) -> Result<()> { + let side = self.side.ok_or(Error::InvalidQwenShape)?; + let h = self.stream.validate()?; + self.stream.api.stream_wait(h, side.join[i]) + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.stream.context) { + return Err(Error::ContextMismatch); + } + if !self.stream.capture.get() { + return Err(Error::InvalidQwenShape); + } + self.stream.validate().map(|_| ()) + } + pub(crate) fn stream_handle(&self, c: &Context<'_>) -> Result { + self.validate_context(c)?; + let capture = self.stream.validate()?; + Ok(self.target.get().unwrap_or(capture)) + } +} +impl Drop for OriginalCapture<'_, '_> { + fn drop(&mut self) { + if self.stream.capture.replace(false) { + // This also ends a capture during unwinding before the graph's real resource + // owner is dropped. Failure poisons, causing that owner to be retained. + let r = call(self.stream.context, &self.stream.api, |a| { + let graph = a.end(self.stream.handle.get().ok_or(Error::ContextPoisoned)?)?; + a.graph_destroy(graph) + }); + if r.is_err() { + self.stream.failed.set(true); + } + } + } +} +/// One actual event. Re-records are only on its same real source stream, exactly +/// as Original stage copied/used/adapt/commit events; waits retain both streams. +pub struct OriginalGpuEvent<'ctx> { + context: &'ctx Context<'ctx>, + api: Rc, + handle: Option, + kind: OriginalEventKind, + source: Option>>, + waiters: [Option>>; 8], + recorded: bool, + sequence: u64, +} +impl<'ctx> OriginalGpuEvent<'ctx> { + fn handle(&self) -> Result { + healthy(self.context)?; + self.handle.ok_or(Error::ContextPoisoned) + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + self.handle().map(|_| ()) + } + pub fn record(&mut self, s: &OriginalGpuStream<'ctx>) -> Result<()> { + s.validate_context(self.context)?; + if s.inner.capture.get() { + return Err(Error::InvalidQwenShape); + } + if self + .source + .as_ref() + .is_some_and(|old| !Rc::ptr_eq(old, &s.inner)) + { + return Err(Error::ContextMismatch); + } + let e = self.handle()?; + let h = s.inner.validate()?; + let sequence = s.inner.bump()?; + self.source = Some(s.inner.clone()); + call(self.context, &self.api, |a| a.event_record(e, h))?; + self.recorded = true; + self.sequence = sequence; + Ok(()) + } + pub fn wait_on(&mut self, s: &OriginalGpuStream<'ctx>) -> Result<()> { + s.validate_context(self.context)?; + if !self.recorded || s.inner.capture.get() { + return Err(Error::InvalidQwenShape); + } + let e = self.handle()?; + let h = s.inner.validate()?; + let _sequence = s.inner.bump()?; + if !self + .waiters + .iter() + .flatten() + .any(|x| Rc::ptr_eq(x, &s.inner)) + { + let index = self + .waiters + .iter() + .position(Option::is_none) + .ok_or(Error::BudgetExceeded)?; + self.waiters[index] = Some(s.inner.clone()); + } + call(self.context, &self.api, |a| a.stream_wait(h, e)) + } + pub fn query(&self) -> Result { + if !self.recorded { + return Err(Error::InvalidQwenShape); + } + let h = self.handle()?; + call(self.context, &self.api, |a| a.event_query(h)) + } + pub fn synchronize(&self) -> Result<()> { + if !self.recorded { + return Err(Error::InvalidQwenShape); + } + let h = self.handle()?; + call(self.context, &self.api, |a| a.event_sync(h)) + } + pub fn elapsed_ms(&self, later: &Self) -> Result { + later.validate_context(self.context)?; + if self.kind != OriginalEventKind::Timing + || later.kind != OriginalEventKind::Timing + || !self.recorded + || !later.recorded + { + return Err(Error::InvalidQwenShape); + } + let a = self.handle()?; + let b = later.handle()?; + call(self.context, &self.api, |api| api.elapsed(a, b)) + } + pub fn is_failed(&self) -> bool { + self.context.is_poisoned() || self.handle.is_none() + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + let Some(e) = self.handle.take() else { + return Ok(()); + }; + if self.context.is_poisoned() { + std::mem::forget(self.api.clone()); + return Err(Error::ContextPoisoned); + } + let r = call(self.context, &self.api, |a| { + let mut op = if self.recorded { + a.event_sync(e) + } else { + Ok(()) + }; + for s in self.waiters.iter().flatten() { + op = combine(op, a.stream_sync(s.validate()?)); + } + if op.is_err() { + return op; + } + a.event_destroy(e) + }); + if r.is_err() { + std::mem::forget(self.api.clone()); + } + r + } +} +impl Drop for OriginalGpuEvent<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} +/// Keeps actual fixed-address device/mapped-host/modules/ABI resource owner R. +/// Changing replay inputs changes their DATA only, never captured kernel arguments. +pub struct OriginalGpuGraph<'ctx, R: OriginalGraphResources> { + context: &'ctx Context<'ctx>, + api: Rc, + graph: Option, + exec: Option, + done: Option, + resources: Option, + last: Option>>, + launched: bool, + nodes: Option, + policy: OriginalCapturePolicy, + last_sequence: u64, +} +impl<'ctx, R: OriginalGraphResources> OriginalGpuGraph<'ctx, R> { + fn validate(&self) -> Result { + healthy(self.context)?; + self.resources + .as_ref() + .ok_or(Error::ContextPoisoned)? + .validate_context(self.context)?; + self.exec.ok_or(Error::ContextPoisoned) + } + pub fn nodes(&self) -> Option { + self.nodes + } + pub fn policy(&self) -> OriginalCapturePolicy { + self.policy + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + self.validate().map(|_| ()) + } + /// Enqueue without a host wait, matching Original pre/post/token replay loops. + /// Same-executable overlapping launches are ordered on its same actual stream. + pub fn enqueue(&mut self, s: &OriginalGpuStream<'ctx>) -> Result<()> { + s.validate_context(self.context)?; + if s.inner.capture.get() { + return Err(Error::InvalidQwenShape); + } + if self.launched + && self + .last + .as_ref() + .is_some_and(|old| !Rc::ptr_eq(old, &s.inner)) + { + return Err(Error::ContextMismatch); + } + let ex = self.validate()?; + self.resources + .as_ref() + .ok_or(Error::ContextPoisoned)? + .validate_replay_context(self.context)?; + let st = s.inner.validate()?; + let sequence = s.inner.bump()?; + self.last = Some(s.inner.clone()); + self.launched = true; + self.last_sequence = sequence; + call(self.context, &self.api, |a| { + a.launch(ex, st)?; + if let Some(e) = self.done { + a.event_record(e, st)?; + } + Ok(()) + }) + } + pub fn launch<'g>( + &'g mut self, + s: &OriginalGpuStream<'ctx>, + ) -> Result> { + self.enqueue(s)?; + Ok(OriginalGraphFlight { + graph: self, + active: true, + }) + } + /// Actual completion receipt from the final same-stream fence. No caller + /// boolean or other Context/stream can authorize retirement. + pub fn resources_after_stream_drain( + &mut self, + done: &OriginalStreamDrained<'ctx>, + ) -> Result<&R> { + self.validate()?; + healthy(self.context)?; + if self.launched { + let last = self.last.as_ref().ok_or(Error::ContextPoisoned)?; + if !Rc::ptr_eq(last, &done.stream) || done.sequence < self.last_sequence { + return Err(Error::InvalidQwenShape); + } + self.launched = false; + } + self.resources.as_ref().ok_or(Error::ContextPoisoned) + } + /// A real later recorded event on the SAME stream can retire many layer graphs + /// with one Original token/commit probe. Its driver query and sequence are checked + /// here; an earlier event or caller boolean never authorizes resource mutation. + pub fn resources_after_event(&mut self, event: &OriginalGpuEvent<'ctx>) -> Result<&R> { + self.validate()?; + event.validate_context(self.context)?; + if self.launched { + let source = self.last.as_ref().ok_or(Error::ContextPoisoned)?; + if !event.source.as_ref().is_some_and(|s| Rc::ptr_eq(s, source)) + || event.sequence <= self.last_sequence + || !event.query()? + { + return Err(Error::InvalidQwenShape); + } + self.launched = false; + } + self.resources.as_ref().ok_or(Error::ContextPoisoned) + } + pub fn resources_after_wait(&mut self) -> Result<&R> { + self.wait_inner()?; + healthy(self.context)?; + self.resources.as_ref().ok_or(Error::ContextPoisoned) + } + fn query_inner(&mut self) -> Result { + self.validate()?; + if !self.launched { + return Ok(true); + } + let stream = self + .last + .as_ref() + .ok_or(Error::ContextPoisoned)? + .validate()?; + let q = call(self.context, &self.api, |a| { + if let Some(e) = self.done { + a.event_query(e) + } else { + a.stream_query(stream) + } + })?; + if q { + self.launched = false; + } + Ok(q) + } + fn wait_inner(&mut self) -> Result<()> { + self.validate()?; + if !self.launched { + return Ok(()); + } + let s = self + .last + .as_ref() + .ok_or(Error::ContextPoisoned)? + .validate()?; + call(self.context, &self.api, |a| a.stream_sync(s))?; + self.launched = false; + Ok(()) + } + pub fn is_failed(&self) -> bool { + self.context.is_poisoned() || self.exec.is_none() + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + // Failed completion retains actual R (including host DMA sources), not just an + // accounting receipt. A poisoned Context's finalizer likewise retains VRAM. + if self.context.is_poisoned() { + if let Some(r) = self.resources.take() { + std::mem::forget(r); + } + std::mem::forget(self.api.clone()); + self.exec.take(); + self.graph.take(); + self.done.take(); + return Err(Error::ContextPoisoned); + } + if self.exec.is_none() && self.graph.is_none() && self.done.is_none() { + return Ok(()); + } + let stream = self.last.as_ref().and_then(|s| s.handle.get()); + let r = call(self.context, &self.api, |a| { + let drained = if self.launched { + stream.map_or(Err(Error::ContextPoisoned), |s| a.stream_sync(s)) + } else { + Ok(()) + }; + if drained.is_err() { + return drained; + } + // Original reset order is executable -> graph -> completion event. + let mut result = Ok(()); + if let Some(e) = self.exec.take() { + result = combine(result, a.exec_destroy(e)); + } + if let Some(g) = self.graph.take() { + result = combine(result, a.graph_destroy(g)); + } + if let Some(e) = self.done.take() { + result = combine(result, a.event_destroy(e)); + } + result + }); + if r.is_err() { + if let Some(resources) = self.resources.take() { + std::mem::forget(resources); + } + std::mem::forget(self.api.clone()); + self.exec.take(); + self.graph.take(); + self.done.take(); + } else { + self.launched = false; + self.resources.take(); + } + r + } +} +impl Drop for OriginalGpuGraph<'_, R> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} +/// Actual submitted work exclusively borrows its graph/resources until query or +/// sync observes completion. Dropping an unfinished flight attempts a real drain. +pub struct OriginalGraphFlight<'g, 'ctx, R: OriginalGraphResources> { + graph: &'g mut OriginalGpuGraph<'ctx, R>, + active: bool, +} +impl OriginalGraphFlight<'_, '_, R> { + pub fn query(&mut self) -> Result { + let done = self.graph.query_inner()?; + if done { + self.active = false; + } + Ok(done) + } + pub fn wait(mut self) -> Result<()> { + let result = self.graph.wait_inner(); + if result.is_ok() { + self.active = false; + } + result + } + /// Registry's wait polls actual driver completion on a real monotonic deadline, + /// with64 pauses between polls. Timeout keeps the graph pending; it never means ready. + pub fn wait_ms(mut self, timeout: Duration) -> Result { + let start = Instant::now(); + loop { + if self.query()? { + return Ok(OriginalWait::Complete); + } + if start.elapsed() >= timeout { + self.active = false; + return Ok(OriginalWait::TimedOut); + } + for _ in 0..64 { + std::hint::spin_loop(); + } + } + } +} +impl Drop for OriginalGraphFlight<'_, '_, R> { + fn drop(&mut self) { + if self.active { + let _ = self.graph.wait_inner(); + } + } +} + +/// Literal graph identities, with Original layer/token/window/coupled separation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OriginalGraphKey { + LayerPre(u8), + LayerPost(u8), + LayerPreA(u8), + LayerPreB(u8), + LayerPrefix { layer: u8, stages: u8 }, + Token, + VerifyWindow(u8), + VerifyCommit, + MtpPrefill { rows: u8, device_inputs: bool }, + MtpRound { rows: u8, coupled: bool }, + MtpStep { step: u8, coupled: bool }, + Registry { qsa: bool, tokens: u32 }, +} +impl OriginalGraphKey { + fn validate(self) -> Result<()> { + let valid = match self { + Self::LayerPre(l) | Self::LayerPost(l) | Self::LayerPreA(l) | Self::LayerPreB(l) => { + l < 48 + } + Self::LayerPrefix { layer, stages } => layer < 48 && (1..=5).contains(&stages), + Self::Token | Self::VerifyCommit => true, + Self::VerifyWindow(t) => (1..=8).contains(&t), + Self::MtpPrefill { rows, .. } | Self::MtpRound { rows, .. } => (1..=8).contains(&rows), + Self::MtpStep { step, .. } => (1..=6).contains(&step), + Self::Registry { tokens, .. } => tokens > 0, + }; + if valid { + Ok(()) + } else { + Err(Error::InvalidQwenShape) + } + } + fn policy(self) -> OriginalCapturePolicy { + match self { + Self::VerifyWindow(_) => OriginalCapturePolicy::VerifierWindow, + Self::VerifyCommit => OriginalCapturePolicy::VerifierCommit, + Self::MtpPrefill { .. } | Self::MtpRound { .. } | Self::MtpStep { .. } => { + OriginalCapturePolicy::Mtp + } + Self::Registry { .. } => OriginalCapturePolicy::Registry, + _ => OriginalCapturePolicy::Session, + } + } +} +/// Fixed upfront capacity, capture-once/replay-many: a hit never calls either +/// resource preparation or the body. No insertion can realloc captured owners. +pub struct OriginalGraphRegistry<'ctx, R: OriginalGraphResources> { + context: &'ctx Context<'ctx>, + entries: Vec<(OriginalGraphKey, OriginalGpuGraph<'ctx, R>)>, + capacity: usize, + captures: u64, +} +impl<'ctx, R: OriginalGraphResources> OriginalGraphRegistry<'ctx, R> { + pub fn new(context: &'ctx Context<'ctx>, capacity: usize) -> Result { + healthy(context)?; + Self::planned_metadata_bytes(capacity)?; + let mut entries = Vec::new(); + entries + .try_reserve_exact(capacity) + .map_err(|_| Error::HostAllocation)?; + if entries + .capacity() + .checked_mul(std::mem::size_of::<( + OriginalGraphKey, + OriginalGpuGraph<'ctx, R>, + )>()) + .and_then(|n| n.checked_add(std::mem::size_of::())) + .is_none_or(|n| n > 16 * 1024 * 1024) + { + return Err(Error::BudgetExceeded); + } + Ok(Self { + context, + entries, + capacity, + captures: 0, + }) + } + pub fn planned_metadata_bytes(capacity: usize) -> Result { + if !(1..=512).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } + let bytes = capacity + .checked_mul(std::mem::size_of::<( + OriginalGraphKey, + OriginalGpuGraph<'ctx, R>, + )>()) + .and_then(|n| n.checked_add(std::mem::size_of::())) + .ok_or(Error::BudgetExceeded)?; + if bytes > 16 * 1024 * 1024 { + return Err(Error::BudgetExceeded); + } + Ok(bytes) + } + pub fn metadata_bytes(&self) -> usize { + self.entries.capacity() + * std::mem::size_of::<(OriginalGraphKey, OriginalGpuGraph<'ctx, R>)>() + + std::mem::size_of::() + } + pub fn captures(&self) -> u64 { + self.captures + } + pub fn len(&self) -> usize { + self.entries.len() + } + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + pub fn find_mut( + &mut self, + key: OriginalGraphKey, + ) -> Result>> { + key.validate()?; + healthy(self.context)?; + Ok(self + .entries + .iter_mut() + .find(|(k, _)| *k == key) + .map(|(_, g)| g)) + } + pub fn record( + &mut self, + key: OriginalGraphKey, + stream: &mut OriginalGpuStream<'ctx>, + prepare: impl FnOnce() -> Result, + body: impl FnOnce(&mut OriginalCapture<'_, 'ctx>, &mut R) -> Result<()>, + ) -> Result<&mut OriginalGpuGraph<'ctx, R>> { + key.validate()?; + stream.validate_context(self.context)?; + if let Some(index) = self.entries.iter().position(|(k, _)| *k == key) { + return Ok(&mut self.entries[index].1); + } + if self.entries.len() == self.capacity { + return Err(Error::BudgetExceeded); + } + let captures = self + .captures + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + let graph = stream.capture_owned(key.policy(), prepare()?, body)?; + let index = self.entries.len(); + self.entries.push((key, graph)); + self.captures = captures; + Ok(&mut self.entries[index].1) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + /// Close every cached graph but keep the registry (and its capture counter) for new captures. + pub fn clear(&mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + let mut result = Ok(()); + while let Some((_, g)) = self.entries.pop() { + result = combine(result, g.close()); + } + result + } +} +impl Drop for OriginalGraphRegistry<'_, R> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} + +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +#[path = "original_gpu_head_bridge.rs"] +mod native_head_bridge; + +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +#[path = "original_gpu_verify_bridge.rs"] +mod verifier_bridge; + +/// Operator timing of `capture_owned` (host ms spent capturing, then instantiating + uploading), summed per thread +/// since the last `take`; read by the serve profile. +pub mod capture_timing { + use std::cell::Cell; + thread_local! { static SUMS: Cell<[f64; 3]> = const { Cell::new([0.0; 3]) }; } + pub(crate) fn add(slot: usize, ms: f64) { + SUMS.with(|s| { + let mut v = s.get(); + v[slot] += ms; + s.set(v); + }); + } + /// (capture ms, instantiate + upload ms, verifier window module loading ms) since the last call. + pub fn take() -> (f64, f64, f64) { + let v = SUMS.with(|s| s.replace([0.0; 3])); + (v[0], v[1], v[2]) + } +} + +#[cfg(test)] +mod oom_tests { + use super::*; + + const OOM: Error = Error::Driver { operation: "cuGraphInstantiateWithFlags", code: CUDA_ERROR_OUT_OF_MEMORY }; + + #[test] + fn an_instantiate_out_of_memory_does_not_poison_the_context_but_every_other_failure_does() { + let failed: Result = Err(OOM); + // `call` (nothing recoverable): any error poisons, as it always did + assert!(poisons(&failed, false, |_| false)); + // the instantiate step: the out-of-memory refusal leaves the context usable ... + assert!(!poisons(&failed, false, is_graph_out_of_memory)); + // ... unless the context pop failed too, or the error is not that refusal + assert!(poisons(&failed, true, is_graph_out_of_memory)); + for other in [ + Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 1 }, + Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 700 }, + Error::Driver { operation: "cuStreamSynchronize", code: CUDA_ERROR_OUT_OF_MEMORY }, + Error::Multiple { primary: Box::new(OOM), secondary: Box::new(Error::ContextPoisoned) }, + ] { + assert!(poisons::(&Err(other.clone()), false, is_graph_out_of_memory), "{other:?}"); + } + assert!(!poisons(&Ok(1usize), false, is_graph_out_of_memory)); + assert!(poisons(&Ok(1usize), true, is_graph_out_of_memory)); + } + + #[test] + fn only_the_graph_calls_count_as_a_recoverable_out_of_memory() { + assert!(is_graph_out_of_memory(&OOM)); + assert!(is_graph_out_of_memory(&Error::Driver { operation: "cuGraphUpload", code: 2 })); + assert!(!is_graph_out_of_memory(&Error::Driver { operation: "cuGraphLaunch", code: 2 })); + assert!(!is_graph_out_of_memory(&Error::Driver { operation: "cuGraphUpload", code: 999 })); + assert!(!is_graph_out_of_memory(&Error::HostAllocation)); + } +} diff --git a/crates/cuda-driver/src/original_verify_window_ops.rs b/crates/cuda-driver/src/original_verify_window_ops.rs index 4cff784f..afe7b965 100644 --- a/crates/cuda-driver/src/original_verify_window_ops.rs +++ b/crates/cuda-driver/src/original_verify_window_ops.rs @@ -1,820 +1,820 @@ -//! Concrete producer set of the literal Verifier window (child of -//! `original_verify`). It binds the recorder (`window_record`) to the genuine -//! owners and sealed kernels, producer by producer: -//! -//! * the verify module (token/step copies, embedding broadcast, ring waits, plan -//! copy, PCIe blob staging, CPU-row copy, doorbell, GPU stamps), -//! * the retained GDN journal (conv / alpha-beta / recurrence) and QSA journal -//! (tail snapshot and indexer append over the twelve resident images), -//! * the native embedding rows and the native head rows (`capture_head_greedy`), -//! * `Planner` (`original_verify_window_planner.rs`), which plans every other -//! Strata call of `record_window` as launches of SEALED PTX assets: hc read, -//! q8_1 quantization and native MMVQ projections (`proj`), QSA K/V append, norm/RoPE, -//! scores/top-k, KV resolve, decode attention and gate (`qsa`), router, shared expert, -//! routed expert groups, hit add and combine (`moe`), final residual write, head -//! mixing and PLE layer 1 (`gr`). -//! -//! Nothing here substitutes prompt-GEMM or per-token arithmetic. What cannot run is -//! refused by name: a family whose weights are not attached refuses with -//! `Original verifier producer unbound: : ... not attached`, a producer -//! whose policy variant has no genuine kernel refuses with `... producer unavailable: -//! : `, and a kernel asset that is not sealed refuses the whole window -//! BEFORE capture with `... asset unsealed: ()` (`unsealed_window_assets` -//! lists them). A partially bound window can therefore never be recorded or replayed. -use super::*; -use super::gr::{self, GrConfig, OriginalVerifyGrBinding}; -use super::kernels::{A, AssetSpec, Launch}; -use super::chain; -use super::sm120; -use super::window_plan::gdn_index; -use super::moe::{self, MoeLayerAddrs, OriginalVerifyExpertFormats, OriginalVerifyMoeBinding}; -use super::planner::{Planner, WindowWeights}; -use super::proj::{self, GdnProjectionAddrs, OriginalVerifyProjBinding, QsaProjectionAddrs}; -use super::qsa::{self, OriginalVerifyQsaBinding, OriginalVerifyQsaKvBinding, QsaLayerAddrs, QsaRope}; -use super::window_plan::{PlanLayout, WINDOW_LAYERS, staging_blobs_per_group}; -use super::window_record::{ - ExpertTier, HcHalf, Projection, QuantSource, Rows, WindowOps, WindowPolicy, record_window, -}; -use crate::{OriginalNativeEmbedRows, OriginalNativeHeadGraphResources}; - -/// Producers with no genuine capturable owner in this tree: none. Every `WindowOps` call is bound; what is -/// unavailable at run time is reported by `unsealed_window_assets` and by the per-producer refusals above. -pub const UNBOUND_PRODUCERS: &[&str] = &[]; - -/// Every kernel asset a window can launch from (all families), regardless of what is attached. -pub(super) fn all_window_assets() -> Vec<&'static AssetSpec> { - let mut all = Vec::new(); - all.extend(proj::mmvq_assets()); - for family in [gr::assets(), qsa::assets(), qsa::cluster_assets(&qsa::OriginalVerifyQsaPolicy { cluster_topk: true, ..qsa::OriginalVerifyQsaPolicy::mode17() }), moe::assets()] { - for spec in family { - if !all.iter().any(|a: &&AssetSpec| std::ptr::eq(*a, spec)) { - all.push(spec); - } - } - } - all -} -/// The kernel assets that are placeholders or fail their SHA-256 pin (none while every window PTX is the one -/// sealed with nvcc 13.2.86 on 2026-10-15): a window cannot be recorded while any is listed -/// (`scripts/build-original-verify-ptx.sh`, `docs/cuda-seal-plan-additions-window.json`). -pub fn unsealed_window_assets() -> Vec<&'static str> { - unsealed_keys(all_window_assets()) -} - -/// The distinct module keys, in order, of the specs that are not sealed. -fn unsealed_keys(specs: impl IntoIterator) -> Vec<&'static str> { - let mut out: Vec<&'static str> = Vec::new(); - for spec in specs { - if spec.sealed().is_err() && !out.contains(&spec.key()) { - out.push(spec.key()); - } - } - out -} - -/// Per-layer routed-expert blob sizes (`expert_layout().blob_bytes(l)`): the -/// PCIe share staged by a copy kernel moves whole blobs. Retained for the -/// graphs' lifetime with the expert source that defines them. -#[derive(Clone, Debug)] -pub struct OriginalVerifyExpertLayout { - blob_bytes: [usize; WINDOW_LAYERS], - /// Gate, up and down bytes of one expert per layer (the three registered spans the PCIe copy kernel reads). - role_bytes: Option<[[usize; 3]; WINDOW_LAYERS]>, -} -impl OriginalVerifyExpertLayout { - pub fn new(blob_bytes: [usize; WINDOW_LAYERS], max_blob: usize) -> Result { - if blob_bytes.iter().any(|&b| b == 0 || b % 16 != 0 || b > max_blob) { - return Err(Error::InvalidQwenShape); - } - Ok(Self { blob_bytes, role_bytes: None }) - } - /// The per-layer gate/up/down span lengths of the port's three-span source: each a whole number of 16-byte - /// words, together exactly the layer's blob (the staging slot the PCIe copy fills). - pub fn with_role_bytes(mut self, role_bytes: [[usize; 3]; WINDOW_LAYERS]) -> Result { - for (layer, roles) in role_bytes.iter().enumerate() { - if roles.iter().any(|&b| b == 0 || b % 16 != 0) || roles.iter().sum::() != self.blob_bytes[layer] { - return Err(Error::InvalidQwenShape); - } - } - self.role_bytes = Some(role_bytes); - Ok(self) - } - pub fn blob_bytes(&self, layer: usize) -> Result { - self.blob_bytes.get(layer).copied().ok_or(Error::InvalidQwenShape) - } - pub fn role_bytes(&self, layer: usize) -> Result<[usize; 3]> { - self.role_bytes - .as_ref() - .ok_or(Error::InvalidDriverValue("Original verifier producer unbound: pcie_stage: expert span sizes not attached"))? - .get(layer) - .copied() - .ok_or(Error::InvalidQwenShape) - } -} - -/// The all-owner aggregate of one captured window graph: the GDN journal, the -/// twelve QSA images and the head rows (`OriginalVerifyResources`), plus the -/// graph-referenced embedding rows and the expert blob layout, and the weight -/// bindings of every producer family. A graph cannot pair owners of different contexts. -pub struct OriginalVerifyWindowResources<'a, 'ctx> { - base: OriginalVerifyResources<'a, 'ctx>, - embed: OriginalNativeEmbedRows<'ctx>, - experts: OriginalVerifyExpertLayout, - rows: usize, - /// Native MMVQ projection matrices of the 36 GDN and 12 QSA layers (attached by the model adapter). - proj: Option>, - /// hc weights of the 48 layers, the final mixer and the optional PLE block. - gr: Option>, - /// QSA norms and indexer projections of the 12 QSA layers. - qsa: Option>, - /// Router, shared experts and routed expert formats of the 48 layers. - moe: Option>, - /// The per-card fused-GR decisions, read once by `prepare`. - gr_cfg: Option, -} -impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> { - pub fn new( - context: &'ctx Context<'ctx>, - base: OriginalVerifyResources<'a, 'ctx>, - embed: OriginalNativeEmbedRows<'ctx>, - experts: OriginalVerifyExpertLayout, - rows: usize, - ) -> Result { - base.validate_context(context)?; - embed.validate_context(context)?; - if !(1..=8).contains(&rows) || base.head.rows() != rows { - return Err(Error::InvalidQwenShape); - } - Ok(Self { base, embed, experts, rows, proj: None, gr: None, qsa: None, moe: None, gr_cfg: None }) - } - pub fn rows(&self) -> usize { - self.rows - } - /// Attach the GDN/QSA native projection matrices (`quantize_q8_1` + `mmvq` producers). - pub fn with_projections(mut self, proj: OriginalVerifyProjBinding<'a, 'ctx>) -> Result { - let context = self.base.journal.context(); - let geometry = self.base.journal.geometry(); - for i in 0..36 { - proj.gdn_addrs(context, &geometry, i)?; - } - for i in 0..12 { - proj.qsa_addrs(context, &geometry, i)?; - } - self.proj = Some(proj); - Ok(self) - } - /// Attach the hyper-connection weights (`hc_read`, `final_write`, `head`, and `ple_layer1` with PLE). - /// The PLE binding must match the journal: present exactly when the window carries a PLE history, and - /// the SAME history buffer the journal snapshots. - pub fn with_gr(mut self, gr: OriginalVerifyGrBinding<'a, 'ctx>) -> Result { - let journal = &self.base.journal; - if gr.has_ple() != journal.has_ple() { - return Err(Error::InvalidQwenShape); - } - if gr.has_ple() && Some(gr.ple_addrs()?.history) != journal.ple_history_address()? { - return Err(Error::OutputAliasesInput); - } - self.gr = Some(gr); - Ok(self) - } - /// Attach the QSA layer weights (norms, indexer projections). - pub fn with_qsa(mut self, qsa: OriginalVerifyQsaBinding<'a, 'ctx>) -> Result { - qsa.validate_context(self.base.journal.context())?; - for q in 0..12 { - OriginalVerifyQsaKvBinding::from_journal(&self.base.qsa, q)?.validate(&self.base.journal.geometry())?; - } - self.qsa = Some(qsa); - Ok(self) - } - /// Attach the router / shared-expert weights and the routed experts' formats. The formats' blob sizes must - /// equal the expert layout this graph stages PCIe blobs with. - pub fn with_moe(mut self, moe: OriginalVerifyMoeBinding<'a, 'ctx>) -> Result { - moe.validate_context(self.base.journal.context())?; - for layer in 0..WINDOW_LAYERS { - if moe.formats().blob_bytes(layer)? != self.experts.blob_bytes(layer)? { - return Err(Error::InvalidQwenShape); - } - } - self.moe = Some(moe); - Ok(self) - } - /// Every sealed asset the attached producers may launch from. Loaded once, BEFORE capture - /// (module loading is not capturable); a missing/unsealed asset fails closed by name. - fn required_assets(&self, policy: &WindowPolicy) -> Vec<&'static AssetSpec> { - let mut assets: Vec<&'static AssetSpec> = Vec::new(); - if let Some(proj) = &self.proj { - assets.extend(proj.assets()); - } - if self.gr.is_some() { - assets.extend(gr::assets()); - } - if self.qsa.is_some() { - assets.extend(qsa::assets()); - assets.extend(qsa::cluster_assets(&policy.qsa)); - assets.extend(qsa::daily_assets(&policy.qsa)); - } - if self.moe.is_some() { - assets.extend(moe::assets()); - if policy.gu_swiglu { - assets.push(&sm120::GU_SWIGLU); - } - } - assets.extend(chain::assets()); - assets - } - /// Pre-capture work: load the sealed modules, read the card's fused-GR decisions, raise the dynamic - /// shared-memory limits Original raises once. Any failure leaves the window unrecorded. - fn prepare(&mut self, policy: &WindowPolicy) -> Result<()> { - self.base.journal.ensure_window_assets(&self.required_assets(policy))?; - let cfg = GrConfig::query(&self.base.journal, policy.gr_variant, policy.native_mmvf)?; - let mut attributes = Vec::new(); - if self.gr.is_some() { - attributes.extend(gr::shared_attributes(&cfg)); - } - if self.qsa.is_some() { - attributes.extend(qsa::shared_attributes(&policy.qsa, &self.base.journal.geometry())); - } - if self.moe.is_some() { - attributes.extend(moe::shared_attributes(&Planner::moe_knobs_of(policy))); - } - self.base.journal.configure_window_shared(&attributes)?; - self.gr_cfg = Some(cfg); - Ok(()) - } -} -macro_rules! unattached { - ($producer:literal, $what:literal) => { - Error::InvalidDriverValue(concat!("Original verifier producer unbound: ", $producer, ": ", $what, " not attached")) - }; -} -impl WindowWeights for OriginalVerifyWindowResources<'_, '_> { - fn gdn_projections(&self, gdn: usize) -> Result { - let p = self.proj.as_ref().ok_or(unattached!("mmvq", "projection weights"))?; - p.gdn_addrs(self.base.journal.context(), &self.base.journal.geometry(), gdn) - } - fn qsa_projections(&self, q: usize) -> Result { - let p = self.proj.as_ref().ok_or(unattached!("mmvq", "projection weights"))?; - p.qsa_addrs(self.base.journal.context(), &self.base.journal.geometry(), q) - } - fn hc(&self, layer: usize, half: HcHalf) -> Result { - self.gr.as_ref().ok_or(unattached!("hc_read", "hyper-connection weights"))?.half_addrs(layer, half) - } - fn head(&self) -> Result { - self.gr.as_ref().ok_or(unattached!("head", "output hyper-connection weights"))?.head_addrs() - } - fn ple(&self) -> Result> { - let gr = self.gr.as_ref().ok_or(unattached!("ple_layer1", "hyper-connection / PLE weights"))?; - if gr.has_ple() { gr.ple_addrs().map(Some) } else { Ok(None) } - } - fn qsa(&self, q: usize) -> Result { - let b = self.qsa.as_ref().ok_or(unattached!("qsa", "QSA layer weights"))?; - let kv = OriginalVerifyQsaKvBinding::from_journal(&self.base.qsa, q)?; - kv.validate(&self.base.journal.geometry())?; - Ok(QsaLayerAddrs { weights: b.addrs(q)?, kv }) - } - fn rope(&self) -> Result { - QsaRope::from_rope(&self.base.qsa.rope()) - } - fn moe(&self, layer: usize) -> Result { - self.moe.as_ref().ok_or(unattached!("router", "router / shared-expert weights"))?.addrs(layer) - } - fn expert_formats(&self) -> Result<&OriginalVerifyExpertFormats> { - Ok(self.moe.as_ref().ok_or(unattached!("expert_groups", "routed expert formats"))?.formats()) - } -} -impl resources::Sealed for OriginalVerifyWindowResources<'_, '_> {} -impl OriginalGraphResources for OriginalVerifyWindowResources<'_, '_> { - fn validate_context(&self, context: &Context<'_>) -> Result<()> { - self.base.validate_context(context)?; - self.embed.validate_context(context) - } -} -impl<'ctx> OriginalVerifyGraphResources<'ctx> for OriginalVerifyWindowResources<'_, 'ctx> { - fn verifier_qsa(&self) -> &crate::OriginalVerifyQsaJournal<'_, 'ctx> { - self.base.verifier_qsa() - } - fn verifier_journal(&self) -> &OriginalVerifyGdnJournal<'_, 'ctx> { - self.base.verifier_journal() - } -} -impl<'ctx> OriginalNativeHeadGraphResources<'ctx> for OriginalVerifyWindowResources<'_, 'ctx> { - fn native_head_rows(&self) -> Result<&crate::OriginalNativeHeadRows<'ctx>> { - self.base.native_head_rows() - } - fn native_head_rows_mut(&mut self) -> Result<&mut crate::OriginalNativeHeadRows<'ctx>> { - self.base.native_head_rows_mut() - } -} - -/// The recorder's producer set over one graph's capture stream and resources. -pub(crate) struct OriginalVerifyWindowOps<'c, 's, 'a, 'ctx> { - capture: &'c mut OriginalCapture<'s, 'ctx>, - resources: &'c mut OriginalVerifyWindowResources<'a, 'ctx>, - t: usize, - groups: usize, - policy: WindowPolicy, -} -impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> { - /// SIDE_MIXER (upstream `STRATA_SIDE_MIXER=2`, GDN part): the GDN gates and the gate projection run on side streams of the window's graph. Not in a - /// split window (two row groups), as upstream. - fn side_gdn(&self) -> bool { - self.policy.side_mixer && self.groups == 1 && self.capture.has_side() - } - /// The branch of one GDN layer. The gates (`gdn_alpha_beta`) read only the mixed activations, the gate projection only their q8_1 blocks; both - /// are complete before the qkv projection starts, and the qkv projection, the conv and the recurrence's other inputs do not touch their outputs, - /// so they fork right here and join before the recurrence. - fn issue_gdn_side(&mut self, layer: usize, rows: Rows) -> Result<()> { - let g = gdn_index(layer).ok_or(Error::InvalidQwenShape)?; - self.capture.side_fork(0)?; - self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::AlphaBeta, self.capture, g, rows.begin, rows.end)?; - self.capture.side_end(0)?; - self.capture.side_fork(1)?; - self.plan_launch(|p| p.mmvq(layer, Projection::GdnGate, rows))?; - self.capture.side_end(1) - } - fn geometry(&self) -> OriginalVerifyGeometry { - self.resources.base.journal.geometry() - } - fn plan(&self) -> PlanLayout { - let g = self.geometry(); - PlanLayout::new(g.max_t * g.k) - } - /// Byte offset of one group's device plan copy inside the "plan" span. - fn plan_group_offset(&self, group: usize) -> usize { - group * self.plan().device_stride() * 4 - } - fn journal(&self) -> &OriginalVerifyGdnJournal<'a, 'ctx> { - &self.resources.base.journal - } - fn submit(&mut self, commands: Vec) -> Result<()> { - self.resources.base.journal.submit(self.capture, commands) - } - /// Record planned launches of any sealed asset on the capture stream, in order. - fn launch(&mut self, launches: Vec) -> Result<()> { - self.resources.base.journal.submit_launches(self.capture, launches) - } - /// The pure planner over this graph's arena, policy and weight bindings. - fn planner(&self) -> Result> { - let cfg = self - .resources - .gr_cfg - .ok_or(Error::InvalidDriverValue("Original verifier window: resources were not prepared before capture"))?; - Ok(Planner::new(&self.resources.base.journal, self.geometry(), self.policy, cfg, &*self.resources)) - } - /// Plan with the planner, then record the launches. - fn plan_launch(&mut self, plan: impl FnOnce(&Planner<'_>) -> Result>) -> Result<()> { - let launches = { - let planner = self.planner()?; - plan(&planner)? - }; - self.launch(launches) - } - /// Address of a word inside the group's device plan block (`words` int32 units). - fn plan_word(&self, group: usize, word: usize) -> Result { - let layout = self.plan(); - if group >= self.groups || word >= layout.words { - return Err(Error::InvalidQwenShape); - } - self.journal().address("plan", self.plan_group_offset(group) + word * 4, 4) - } - fn mapped_flag(&self, index: usize) -> Result { - self.journal().physical.mapped_address(index, 0, 4) - } - fn wait_flag(&mut self, flag: usize, ring: u32) -> Result<()> { - let address = self.mapped_flag(flag)?; - self.submit(vec![command( - "verify_wait_flag_ge_kernel", - [1, 1, 1], - [1, 1, 1], - vec![Arg::Address(address), Arg::I32(ring as i32)], - )?]) - } -} - -impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { - fn embed(&mut self) -> Result<()> { - let g = self.geometry(); - let t = self.t; - let tokens = handle(self.resources.embed.tokens_mut()?)?.qwen_address(); - let source = self.journal().address("tok", 0, t * 4)?; - // The embedding rows read their own staged token bank; the verifier's staged tokens are - // copied (device to device, in capture order) into it before the gather. - self.submit(vec![command( - "verify_copy_i32_from_mapped_kernel", - [1, 1, 1], - [128, 1, 1], - vec![Arg::Address(tokens), Arg::Address(source), Arg::I32(t as i32)], - )?])?; - self.resources.embed.capture(self.capture)?; - let embedded = handle(self.resources.embed.output_device()?)?.qwen_address(); - let residual = self.journal().address("R", 0, t * g.hc * g.n * 4)?; - self.submit(vec![command( - "verify_broadcast_streams_kernel", - [(g.n * g.hc).div_ceil(256) as u32, t as u32, 1], - [256, 1, 1], - vec![Arg::Address(embedded), Arg::Address(residual), Arg::I64(g.n as i64), Arg::I32(g.hc as i32)], - )?]) - } - fn stamp(&mut self, layer: usize, stage: usize) -> Result<()> { - self.resources.base.journal.capture_stamp(self.capture, layer, stage) - } - fn ple_layer1(&mut self, rows: Rows) -> Result<()> { - let per_row = { - let planner = self.planner()?; - planner.ple_layer1(rows)? - }; - // Each row's history snapshot (`copy_from_mapped(hist_snap_ + t*HS, ss.ple.hist, HS)`) follows that row. - for (row, launches) in per_row { - self.launch(launches)?; - self.resources.base.journal.capture_ple_snapshot(self.capture, row)?; - } - Ok(()) - } - fn hc_read(&mut self, layer: usize, half: HcHalf, apply: bool, rows: Rows) -> Result<()> { - self.plan_launch(|p| p.hc_read(layer, half, apply, rows))?; - let frame = layer * 2 + usize::from(half == HcHalf::Ffn); - self.resources.base.journal.capture_ladder(self.capture, frame, rows.begin, rows.end) - } - fn quantize_q8_1(&mut self, _layer: usize, source: QuantSource, rows: Rows) -> Result<()> { - self.plan_launch(|p| p.quantize_q8_1(source, rows)) - } - fn mmvq(&mut self, layer: usize, projection: Projection, rows: Rows) -> Result<()> { - if self.side_gdn() { - match projection { - // SIDE_MIXER: the gates and the gate projection of this GDN layer are issued here, beside the qkv projection and the conv - Projection::GdnQkv => self.issue_gdn_side(layer, rows)?, - // ... and are not issued again where the literal order has them - Projection::GdnGate => return Ok(()), - _ => {} - } - } - self.plan_launch(|p| p.mmvq(layer, projection, rows)) - } - fn gdn_conv(&mut self, layer: usize, rows: Rows) -> Result<()> { - self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::Conv, self.capture, layer, rows.begin, rows.end) - } - fn gdn_alpha_beta(&mut self, layer: usize, rows: Rows) -> Result<()> { - if self.side_gdn() { - return Ok(()); // issued on side stream 0 by `issue_gdn_side` - } - self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::AlphaBeta, self.capture, layer, rows.begin, rows.end) - } - fn gdn_recurrence(&mut self, layer: usize, rows: Rows) -> Result<()> { - if self.side_gdn() { - // the recurrence reads the gates and the gate projection: the capture stream joins both branches - self.capture.side_join(0)?; - self.capture.side_join(1)?; - } - self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::Recurrence, self.capture, layer, rows.begin, rows.end) - } - fn qsa_index_k(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { - self.plan_launch(|p| p.qsa_index_k(q, rows, batched)) - } - fn qsa_k_norm_rope(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { - self.plan_launch(|p| p.qsa_k_norm_rope(q, rows, batched)) - } - fn qsa_tail_snapshot(&mut self, layer: usize) -> Result<()> { - let base = &self.resources.base; - base.qsa.capture_tail_snapshot(&base.journal, self.capture, layer) - } - fn qsa_kv_append(&mut self, q: usize, rows: Rows) -> Result<()> { - self.plan_launch(|p| p.qsa_kv_append(q, rows)) - } - fn qsa_indexer_append(&mut self, layer: usize, rows: Rows) -> Result<()> { - let base = &self.resources.base; - base.qsa.capture_append_rows(&base.journal, self.capture, layer, rows.begin, rows.end) - } - fn qsa_q_path(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { - self.plan_launch(|p| p.qsa_q_path(q, rows, batched)) - } - fn qsa_index_q_path(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { - self.plan_launch(|p| p.qsa_index_q_path(q, rows, batched)) - } - fn qsa_block_scores_topk(&mut self, q: usize, rows: Rows) -> Result<()> { - self.plan_launch(|p| p.qsa_block_scores_topk(q, rows)) - } - fn qsa_kv_resolve(&mut self, q: usize, rows: Rows) -> Result<()> { - self.plan_launch(|p| p.qsa_kv_resolve(q, rows)) - } - fn qsa_decode_attention(&mut self, q: usize, rows: Rows) -> Result<()> { - self.plan_launch(|p| p.qsa_decode_attention(q, rows)) - } - fn qsa_gate(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { - self.plan_launch(|p| p.qsa_gate(q, rows, batched)) - } - fn router(&mut self, layer: usize, rows: Rows, batched: bool) -> Result<()> { - self.plan_launch(|p| p.router(layer, rows, batched)) - } - fn doorbell(&mut self, rows: Rows) -> Result<()> { - self.resources.base.journal.capture_doorbell(self.capture, rows.begin, rows.end) - } - fn shared_expert(&mut self, layer: usize, rows: Rows, dec_batch: bool) -> Result<()> { - self.plan_launch(|p| p.shared_expert(layer, rows, dec_batch)) - } - fn quantize_expert_input(&mut self, _layer: usize, rows: Rows) -> Result<()> { - self.plan_launch(|p| p.quantize_expert_input(rows)) - } - fn wait_plan(&mut self, ring: u32, rows: Rows) -> Result<()> { - if chain::flags().glue { - // wait flag A and the plan block copy in one launch (chain_window.cu) - let layout = self.plan(); - let flag = self.mapped_flag(11)?; - let device = self.journal().address("plan", self.plan_group_offset(rows.group), layout.words * 4)?; - let mapped = self.journal().physical.mapped_address(14, rows.group * layout.mapped_stride() * 4, layout.words * 4)?; - return self.launch(vec![Launch::new( - &chain::CHAIN, - chain::E_WAIT_COPY_I32, - [1, 1, 1], - [704, 1, 1], - 0, - vec![A::P(flag), A::I32(ring as i32), A::P(device), A::P(mapped), A::I32(layout.words as i32)], - )?]); - } - self.wait_flag(11, ring)?; - // The pool's GPU plan, copied from mapped host memory into this group's device block. - let layout = self.plan(); - let device = self.journal().address("plan", self.plan_group_offset(rows.group), layout.words * 4)?; - let mapped = self.journal().physical.mapped_address(14, rows.group * layout.mapped_stride() * 4, layout.words * 4)?; - self.submit(vec![command( - "verify_copy_i32_from_mapped_kernel", - [1, 1, 1], - [128, 1, 1], - vec![Arg::Address(device), Arg::Address(mapped), Arg::I32(layout.words as i32)], - )?]) - } - fn expert_groups(&mut self, layer: usize, rows: Rows, tier: ExpertTier) -> Result<()> { - self.plan_launch(|p| p.expert_groups(layer, rows, tier)) - } - fn wait_copies(&mut self, ring: u32) -> Result<()> { - self.wait_flag(12, ring) - } - fn pcie_stage(&mut self, layer: usize, rows: Rows) -> Result<()> { - // verify.cpp `fetch_blobs` + `rebase_ptrs` over the port's three-span source: `ptr2[3 q + r]` holds the device - // alias of span r (gate, up, down) of PCIe group q (`publish_gpu_plan`, pcie mode 2); the copy fills staging - // slot q with gate|up|down exactly as the DMA path does, then `ptr2[q]` is pointed at the slot. - let g = self.geometry(); - let layout = self.plan(); - let [gate, up, down] = self.resources.experts.role_bytes(layer)?; - let stride = gate + up + down; - let per = staging_blobs_per_group(self.groups); - if stride > g.max_expert_blob || 3 * per > g.max_t * g.k { - return Err(Error::InvalidQwenShape); - } - let stage_offset = rows.group * per * g.max_expert_blob; - let stage = self.journal().address("staging", stage_offset, per * g.max_expert_blob)?; - let source = self.plan_word(rows.group, layout.ptr2)?; - let count = self.plan_word(rows.group, layout.counts + 2)?; - let words = |bytes: usize| A::I64((bytes / 16) as i64); - let (spec, entry, grid, block) = match moe::pcie_fast_kernel() { - Some((entry, grid, block)) => (&moe::PCIE_FAST, entry, grid, block), - None => (&moe::PCIE, "verify_fetch_spans_kernel", [48 * 8, 1, 1], [256, 1, 1]), - }; - self.launch(vec![Launch::new( - spec, - entry, - grid, - block, - 0, - vec![A::P(source), A::P(count), A::P(stage), words(gate), words(up), words(down)], - )?])?; - self.submit(vec![command( - "verify_rebase_ptrs_kernel", - [1, 1, 1], - [128, 1, 1], - vec![Arg::Address(source), Arg::Address(count), Arg::U64(stage), Arg::I64(stride as i64)], - )?]) - } - fn wait_cpu(&mut self, ring: u32) -> Result<()> { - self.wait_flag(10, ring) - } - fn copy_cpu_rows(&mut self, rows: Rows, only_cpu_hits: bool) -> Result<()> { - let g = self.geometry(); - let n = rows.len(); - let first = rows.begin * g.k * g.n * 4; - let bytes = n * g.k * g.n * 4; - let parts = self.journal().address("parts", first, bytes)?; - let mapped = self.journal().physical.mapped_address(13, first, bytes)?; - if only_cpu_hits && chain::flags().glue { - let layout = self.plan(); - let hit_rows = self.plan_word(rows.group, layout.dst)?; - let count = self.plan_word(rows.group, layout.counts + 1)?; - return self.launch(vec![Launch::new( - &chain::CHAIN, - chain::E_COPY_ROWS, - [(n * g.k) as u32, 1, 1], - [128, 1, 1], - 0, - vec![A::P(parts), A::P(mapped), A::I64((g.n / 4) as i64), A::P(hit_rows), A::P(count)], - )?]); - } - let command = if only_cpu_hits { - let layout = self.plan(); - command( - "verify_copy_rows_from_mapped_kernel", - [(n * g.k) as u32, 1, 1], - [128, 1, 1], - vec![ - Arg::Address(parts), - Arg::Address(mapped), - Arg::I64((g.n / 4) as i64), - Arg::Address(self.plan_word(rows.group, layout.dst)?), - Arg::Address(self.plan_word(rows.group, layout.counts + 1)?), - ], - )? - } else { - let n4 = bytes / 16; - command( - "verify_copy_from_mapped_kernel", - [n4.div_ceil(256).min(64) as u32, 1, 1], - [256, 1, 1], - vec![Arg::Address(parts), Arg::Address(mapped), Arg::I64(n4 as i64)], - )? - }; - self.submit(vec![command]) - } - fn hit_add(&mut self, rows: Rows) -> Result<()> { - self.plan_launch(|p| p.hit_add(rows)) - } - fn combine(&mut self, _layer: usize, rows: Rows, batched: bool) -> Result<()> { - self.plan_launch(|p| p.combine(rows, batched)) - } - fn final_write(&mut self, rows: Rows) -> Result<()> { - self.plan_launch(|p| p.final_write(rows)) - } - fn head(&mut self, rows: usize) -> Result<()> { - // Per token `lm_head_mix` into the head rows' `mixed` buffer, then the head owner's captured tail: - // quantize ALL T, native MMVQ ALL T, greedy argmax (`capture_head_greedy`). - let mixed = handle(self.resources.base.head.mixed_mut()?)?.qwen_address(); - self.plan_launch(|p| p.head_mix(mixed, rows))?; - self.resources.base.head.capture_head_greedy(self.capture) - } -} - -impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> { - /// Record the T-token window graph for `t` (split windows use two groups). - /// `resources` is this graph's own aggregate (its head rows hold `t` rows). - pub fn record_literal_window( - &mut self, - t: usize, - resources: OriginalVerifyWindowResources<'a, 'ctx>, - policy: WindowPolicy, - ) -> Result<()> { - policy.validate_selected()?; - if resources.rows() != t { - return Err(Error::InvalidQwenShape); - } - // the cluster top-k needs sm_90+ and a sealed module; anything else keeps the Original's qsa_topk_ref - let mut policy = policy; - if policy.qsa.cluster_topk { - let cc = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?; - policy.qsa.cluster_topk = cc >= 9 && qsa::CLUSTER.sealed().is_ok(); - static SAID: std::sync::Once = std::sync::Once::new(); - SAID.call_once(|| eprintln!("leleka-serve qsa decode top-k: {} (compute capability {cc})", if policy.qsa.cluster_topk { "thread-block cluster" } else { "qsa_topk_ref (cluster refused)" })); - } - // the sm_120 decode switches (original_verify_window_sm120.rs): resolved from the card and the environment, once per recording - { - let major = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?; - let minor = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MINOR)?; - let want = sm120::Sm120Switches::from_env(major, minor); - policy.qsa.attn_daily = (policy.qsa.attn_daily || want.attn_daily) && sm120::ATTN_DAILY.sealed().is_ok(); - policy.gu_swiglu = (policy.gu_swiglu || want.gu_swiglu) && sm120::GU_SWIGLU.sealed().is_ok(); - policy.side_mixer = policy.side_mixer || want.side_mixer; - static SAID: std::sync::Once = std::sync::Once::new(); - SAID.call_once(|| eprintln!("leleka-serve sm120 switches: attn_daily={} gu_swiglu={} side_mixer={} (compute capability {major}.{minor}, requested {want:?})", policy.qsa.attn_daily, policy.gu_swiglu, policy.side_mixer)); - } - let ple = resources.verifier_journal().has_ple(); - let roles = if policy.pcie_mode == 2 { - let mut roles = [[0usize; 3]; WINDOW_LAYERS]; - for (layer, r) in roles.iter_mut().enumerate() { - *r = resources.experts.role_bytes(layer)?; - } - Some(roles) - } else { - None - }; - self.set_pcie_mode(policy.pcie_mode, roles)?; - // Sealed modules load before capture begins (cuModuleLoadData is not a capturable call). - let mut resources = resources; - resources.prepare(&policy)?; - // SIDE_MIXER: this recording's capture creates the two side streams (a split window just leaves them unused) - crate::original_gpu_schedule::set_side_streams_wanted(policy.side_mixer); - let recorded = self.record_window(t, resources, |capture, resources, groups| { - // The recorder re-validates the shape; the groups come from `set_split`. - let mut ops = OriginalVerifyWindowOps { capture, resources, t, groups, policy }; - record_window(&mut ops, &policy, t, groups, ple) - }); - crate::original_gpu_schedule::set_side_streams_wanted(false); - recorded - } - /// Record every T = 1..=max_t window graph and the real accepted-prefix commit - /// graph, in Original's order, BEFORE the first `run`. `window(t)` supplies each - /// graph's aggregate. All-or-nothing: the first unbound producer or admission - /// failure returns its error and `run` stays refused (`commit` is absent). - pub fn record_all( - &mut self, - policy: WindowPolicy, - mut window: impl FnMut(usize) -> Result>, - commit: OriginalVerifyWindowResources<'a, 'ctx>, - ) -> Result<()> { - policy.validate_selected()?; - let max_t = self.bank()?.geometry().max_t; - for t in 1..=max_t { - self.record_literal_window(t, window(t)?, policy).map_err(|e| graph_oom_at(e, t))?; - } - // The K/V half of a verifier commit is host publication of the mapped journal; the commit - // graph itself is GDN layer replay + QSA tail restore + re-append (+ PLE history). - self.record_commit(commit, |_, _, _| Ok(())).map_err(|e| graph_oom_at(e, 0)) - } -} - -/// A graph instantiate that ran out of device memory, named by the graph that did not fit (`window` = its T, 0 = the commit graph). -/// Any other error, and an out-of-memory that came with a cleanup failure (`Multiple`), stays as it is. -pub(crate) fn graph_oom_at(error: Error, window: usize) -> Error { - if crate::original_gpu_schedule::is_graph_out_of_memory(&error) { Error::GraphOutOfMemory { window } } else { error } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_graph_out_of_memory_is_named_by_the_graph_that_did_not_fit_and_nothing_else_is() { - let oom = Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 2 }; - assert_eq!(graph_oom_at(oom.clone(), 5), Error::GraphOutOfMemory { window: 5 }); - assert_eq!(graph_oom_at(oom.clone(), 0), Error::GraphOutOfMemory { window: 0 }); - // the upload warm-up is not an instantiate, but it shares the code and is treated the same by the capture - assert_eq!( - graph_oom_at(Error::Driver { operation: "cuGraphUpload", code: 2 }, 3), - Error::GraphOutOfMemory { window: 3 } - ); - // another code, another call, and an out-of-memory that carries a cleanup failure all stay fatal as they were - for other in [ - Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 1 }, - Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 700 }, - Error::Driver { operation: "cuStreamEndCapture", code: 2 }, - Error::ContextPoisoned, - Error::InvalidQwenShape, - Error::Multiple { primary: Box::new(oom.clone()), secondary: Box::new(Error::ContextPoisoned) }, - ] { - assert_eq!(graph_oom_at(other.clone(), 4), other); - } - assert!(graph_oom_at(oom, 2).to_string().contains("T=2")); - assert!(Error::GraphOutOfMemory { window: 0 }.to_string().contains("commit")); - } - - #[test] - fn every_window_asset_is_sealed_and_a_corrupted_pin_is_reported_by_name() { - // Sealed with nvcc 13.2.86 on 2026-10-15, so nothing is unsealed and a window may be recorded. - assert_eq!(unsealed_window_assets(), Vec::<&str>::new()); - let all = all_window_assets(); - assert!(!all.is_empty()); - for spec in &all { - spec.assert_sealed_and_fail_closed(); - } - // The two NEW sources (grouped native experts, fast-math QSA gate) are real sealed PTX too. - for new in [&moe::EXPERTS, &qsa::GATE] { - assert!(all.iter().any(|a| std::ptr::eq(*a, new)), "{}", new.name); - } - // Fail-closed reporting is alive: a one-byte-corrupted copy, a wrong digest and a zero pin of a sealed asset - // are each reported by module key (once), and the untouched specs stay out of the list. - let corrupted = moe::EXPERTS.derived(crate::sealed_ptx::test_support::one_byte_corrupted(moe::EXPERTS.ptx), moe::EXPERTS.sha); - let wrong_digest = qsa::GATE.derived(qsa::GATE.ptx, [7; 32]); - let zero_pin = gr::assets()[0].derived(gr::assets()[0].ptx, [0; 32]); - assert_eq!( - unsealed_keys([corrupted, &qsa::GATE, wrong_digest, zero_pin, corrupted]), - [corrupted.key(), wrong_digest.key(), zero_pin.key()] - ); - assert!(unsealed_keys([&moe::EXPERTS, &qsa::GATE]).is_empty()); - } - - #[test] - fn every_window_asset_is_listed_once_and_names_a_distinct_module() { - let all = all_window_assets(); - let mut keys: Vec<&str> = all.iter().map(|a| a.key()).collect(); - let count = keys.len(); - keys.sort_unstable(); - keys.dedup(); - // specs of one PTX file share a key (entries are unioned by the loader); no key hides two different files - assert!(keys.len() <= count); - for key in &keys { - let mut pins = all.iter().filter(|a| a.key() == *key).map(|a| (a.sha, a.ptx.len())); - let first = pins.next().unwrap(); - assert!(pins.all(|p| p == first), "{key}: specs of one module disagree on the file"); - } - assert!(UNBOUND_PRODUCERS.is_empty()); - } - - #[test] - fn expert_layout_requires_whole_16_byte_blobs_within_the_staging_bound() { - assert!(OriginalVerifyExpertLayout::new([1 << 20; WINDOW_LAYERS], 4 << 20).is_ok()); - assert!(OriginalVerifyExpertLayout::new([1 << 20; WINDOW_LAYERS], 1 << 19).is_err()); - let mut odd = [1 << 20; WINDOW_LAYERS]; - odd[7] = (1 << 20) + 8; - assert!(OriginalVerifyExpertLayout::new(odd, 4 << 20).is_err()); - let mut zero = [1 << 20; WINDOW_LAYERS]; - zero[0] = 0; - assert!(OriginalVerifyExpertLayout::new(zero, 4 << 20).is_err()); - assert_eq!(OriginalVerifyExpertLayout::new([32; WINDOW_LAYERS], 64).unwrap().blob_bytes(47), Ok(32)); - assert!(OriginalVerifyExpertLayout::new([32; WINDOW_LAYERS], 64).unwrap().blob_bytes(48).is_err()); - } -} +//! Concrete producer set of the literal Verifier window (child of +//! `original_verify`). It binds the recorder (`window_record`) to the genuine +//! owners and sealed kernels, producer by producer: +//! +//! * the verify module (token/step copies, embedding broadcast, ring waits, plan +//! copy, PCIe blob staging, CPU-row copy, doorbell, GPU stamps), +//! * the retained GDN journal (conv / alpha-beta / recurrence) and QSA journal +//! (tail snapshot and indexer append over the twelve resident images), +//! * the native embedding rows and the native head rows (`capture_head_greedy`), +//! * `Planner` (`original_verify_window_planner.rs`), which plans every other +//! Strata call of `record_window` as launches of SEALED PTX assets: hc read, +//! q8_1 quantization and native MMVQ projections (`proj`), QSA K/V append, norm/RoPE, +//! scores/top-k, KV resolve, decode attention and gate (`qsa`), router, shared expert, +//! routed expert groups, hit add and combine (`moe`), final residual write, head +//! mixing and PLE layer 1 (`gr`). +//! +//! Nothing here substitutes prompt-GEMM or per-token arithmetic. What cannot run is +//! refused by name: a family whose weights are not attached refuses with +//! `Original verifier producer unbound: : ... not attached`, a producer +//! whose policy variant has no genuine kernel refuses with `... producer unavailable: +//! : `, and a kernel asset that is not sealed refuses the whole window +//! BEFORE capture with `... asset unsealed: ()` (`unsealed_window_assets` +//! lists them). A partially bound window can therefore never be recorded or replayed. +use super::*; +use super::gr::{self, GrConfig, OriginalVerifyGrBinding}; +use super::kernels::{A, AssetSpec, Launch}; +use super::chain; +use super::sm120; +use super::window_plan::gdn_index; +use super::moe::{self, MoeLayerAddrs, OriginalVerifyExpertFormats, OriginalVerifyMoeBinding}; +use super::planner::{Planner, WindowWeights}; +use super::proj::{self, GdnProjectionAddrs, OriginalVerifyProjBinding, QsaProjectionAddrs}; +use super::qsa::{self, OriginalVerifyQsaBinding, OriginalVerifyQsaKvBinding, QsaLayerAddrs, QsaRope}; +use super::window_plan::{PlanLayout, WINDOW_LAYERS, staging_blobs_per_group}; +use super::window_record::{ + ExpertTier, HcHalf, Projection, QuantSource, Rows, WindowOps, WindowPolicy, record_window, +}; +use crate::{OriginalNativeEmbedRows, OriginalNativeHeadGraphResources}; + +/// Producers with no genuine capturable owner in this tree: none. Every `WindowOps` call is bound; what is +/// unavailable at run time is reported by `unsealed_window_assets` and by the per-producer refusals above. +pub const UNBOUND_PRODUCERS: &[&str] = &[]; + +/// Every kernel asset a window can launch from (all families), regardless of what is attached. +pub(super) fn all_window_assets() -> Vec<&'static AssetSpec> { + let mut all = Vec::new(); + all.extend(proj::mmvq_assets()); + for family in [gr::assets(), qsa::assets(), qsa::cluster_assets(&qsa::OriginalVerifyQsaPolicy { cluster_topk: true, ..qsa::OriginalVerifyQsaPolicy::mode17() }), moe::assets()] { + for spec in family { + if !all.iter().any(|a: &&AssetSpec| std::ptr::eq(*a, spec)) { + all.push(spec); + } + } + } + all +} +/// The kernel assets that are placeholders or fail their SHA-256 pin (none while every window PTX is the one +/// sealed with nvcc 13.2.86 on 2026-10-15): a window cannot be recorded while any is listed +/// (`scripts/build-original-verify-ptx.sh`, `docs/cuda-seal-plan-additions-window.json`). +pub fn unsealed_window_assets() -> Vec<&'static str> { + unsealed_keys(all_window_assets()) +} + +/// The distinct module keys, in order, of the specs that are not sealed. +fn unsealed_keys(specs: impl IntoIterator) -> Vec<&'static str> { + let mut out: Vec<&'static str> = Vec::new(); + for spec in specs { + if spec.sealed().is_err() && !out.contains(&spec.key()) { + out.push(spec.key()); + } + } + out +} + +/// Per-layer routed-expert blob sizes (`expert_layout().blob_bytes(l)`): the +/// PCIe share staged by a copy kernel moves whole blobs. Retained for the +/// graphs' lifetime with the expert source that defines them. +#[derive(Clone, Debug)] +pub struct OriginalVerifyExpertLayout { + blob_bytes: [usize; WINDOW_LAYERS], + /// Gate, up and down bytes of one expert per layer (the three registered spans the PCIe copy kernel reads). + role_bytes: Option<[[usize; 3]; WINDOW_LAYERS]>, +} +impl OriginalVerifyExpertLayout { + pub fn new(blob_bytes: [usize; WINDOW_LAYERS], max_blob: usize) -> Result { + if blob_bytes.iter().any(|&b| b == 0 || b % 16 != 0 || b > max_blob) { + return Err(Error::InvalidQwenShape); + } + Ok(Self { blob_bytes, role_bytes: None }) + } + /// The per-layer gate/up/down span lengths of the port's three-span source: each a whole number of 16-byte + /// words, together exactly the layer's blob (the staging slot the PCIe copy fills). + pub fn with_role_bytes(mut self, role_bytes: [[usize; 3]; WINDOW_LAYERS]) -> Result { + for (layer, roles) in role_bytes.iter().enumerate() { + if roles.iter().any(|&b| b == 0 || b % 16 != 0) || roles.iter().sum::() != self.blob_bytes[layer] { + return Err(Error::InvalidQwenShape); + } + } + self.role_bytes = Some(role_bytes); + Ok(self) + } + pub fn blob_bytes(&self, layer: usize) -> Result { + self.blob_bytes.get(layer).copied().ok_or(Error::InvalidQwenShape) + } + pub fn role_bytes(&self, layer: usize) -> Result<[usize; 3]> { + self.role_bytes + .as_ref() + .ok_or(Error::InvalidDriverValue("Original verifier producer unbound: pcie_stage: expert span sizes not attached"))? + .get(layer) + .copied() + .ok_or(Error::InvalidQwenShape) + } +} + +/// The all-owner aggregate of one captured window graph: the GDN journal, the +/// twelve QSA images and the head rows (`OriginalVerifyResources`), plus the +/// graph-referenced embedding rows and the expert blob layout, and the weight +/// bindings of every producer family. A graph cannot pair owners of different contexts. +pub struct OriginalVerifyWindowResources<'a, 'ctx> { + base: OriginalVerifyResources<'a, 'ctx>, + embed: OriginalNativeEmbedRows<'ctx>, + experts: OriginalVerifyExpertLayout, + rows: usize, + /// Native MMVQ projection matrices of the 36 GDN and 12 QSA layers (attached by the model adapter). + proj: Option>, + /// hc weights of the 48 layers, the final mixer and the optional PLE block. + gr: Option>, + /// QSA norms and indexer projections of the 12 QSA layers. + qsa: Option>, + /// Router, shared experts and routed expert formats of the 48 layers. + moe: Option>, + /// The per-card fused-GR decisions, read once by `prepare`. + gr_cfg: Option, +} +impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> { + pub fn new( + context: &'ctx Context<'ctx>, + base: OriginalVerifyResources<'a, 'ctx>, + embed: OriginalNativeEmbedRows<'ctx>, + experts: OriginalVerifyExpertLayout, + rows: usize, + ) -> Result { + base.validate_context(context)?; + embed.validate_context(context)?; + if !(1..=8).contains(&rows) || base.head.rows() != rows { + return Err(Error::InvalidQwenShape); + } + Ok(Self { base, embed, experts, rows, proj: None, gr: None, qsa: None, moe: None, gr_cfg: None }) + } + pub fn rows(&self) -> usize { + self.rows + } + /// Attach the GDN/QSA native projection matrices (`quantize_q8_1` + `mmvq` producers). + pub fn with_projections(mut self, proj: OriginalVerifyProjBinding<'a, 'ctx>) -> Result { + let context = self.base.journal.context(); + let geometry = self.base.journal.geometry(); + for i in 0..36 { + proj.gdn_addrs(context, &geometry, i)?; + } + for i in 0..12 { + proj.qsa_addrs(context, &geometry, i)?; + } + self.proj = Some(proj); + Ok(self) + } + /// Attach the hyper-connection weights (`hc_read`, `final_write`, `head`, and `ple_layer1` with PLE). + /// The PLE binding must match the journal: present exactly when the window carries a PLE history, and + /// the SAME history buffer the journal snapshots. + pub fn with_gr(mut self, gr: OriginalVerifyGrBinding<'a, 'ctx>) -> Result { + let journal = &self.base.journal; + if gr.has_ple() != journal.has_ple() { + return Err(Error::InvalidQwenShape); + } + if gr.has_ple() && Some(gr.ple_addrs()?.history) != journal.ple_history_address()? { + return Err(Error::OutputAliasesInput); + } + self.gr = Some(gr); + Ok(self) + } + /// Attach the QSA layer weights (norms, indexer projections). + pub fn with_qsa(mut self, qsa: OriginalVerifyQsaBinding<'a, 'ctx>) -> Result { + qsa.validate_context(self.base.journal.context())?; + for q in 0..12 { + OriginalVerifyQsaKvBinding::from_journal(&self.base.qsa, q)?.validate(&self.base.journal.geometry())?; + } + self.qsa = Some(qsa); + Ok(self) + } + /// Attach the router / shared-expert weights and the routed experts' formats. The formats' blob sizes must + /// equal the expert layout this graph stages PCIe blobs with. + pub fn with_moe(mut self, moe: OriginalVerifyMoeBinding<'a, 'ctx>) -> Result { + moe.validate_context(self.base.journal.context())?; + for layer in 0..WINDOW_LAYERS { + if moe.formats().blob_bytes(layer)? != self.experts.blob_bytes(layer)? { + return Err(Error::InvalidQwenShape); + } + } + self.moe = Some(moe); + Ok(self) + } + /// Every sealed asset the attached producers may launch from. Loaded once, BEFORE capture + /// (module loading is not capturable); a missing/unsealed asset fails closed by name. + fn required_assets(&self, policy: &WindowPolicy) -> Vec<&'static AssetSpec> { + let mut assets: Vec<&'static AssetSpec> = Vec::new(); + if let Some(proj) = &self.proj { + assets.extend(proj.assets()); + } + if self.gr.is_some() { + assets.extend(gr::assets()); + } + if self.qsa.is_some() { + assets.extend(qsa::assets()); + assets.extend(qsa::cluster_assets(&policy.qsa)); + assets.extend(qsa::daily_assets(&policy.qsa)); + } + if self.moe.is_some() { + assets.extend(moe::assets()); + if policy.gu_swiglu { + assets.push(&sm120::GU_SWIGLU); + } + } + assets.extend(chain::assets()); + assets + } + /// Pre-capture work: load the sealed modules, read the card's fused-GR decisions, raise the dynamic + /// shared-memory limits Original raises once. Any failure leaves the window unrecorded. + fn prepare(&mut self, policy: &WindowPolicy) -> Result<()> { + self.base.journal.ensure_window_assets(&self.required_assets(policy))?; + let cfg = GrConfig::query(&self.base.journal, policy.gr_variant, policy.native_mmvf)?; + let mut attributes = Vec::new(); + if self.gr.is_some() { + attributes.extend(gr::shared_attributes(&cfg)); + } + if self.qsa.is_some() { + attributes.extend(qsa::shared_attributes(&policy.qsa, &self.base.journal.geometry())); + } + if self.moe.is_some() { + attributes.extend(moe::shared_attributes(&Planner::moe_knobs_of(policy))); + } + self.base.journal.configure_window_shared(&attributes)?; + self.gr_cfg = Some(cfg); + Ok(()) + } +} +macro_rules! unattached { + ($producer:literal, $what:literal) => { + Error::InvalidDriverValue(concat!("Original verifier producer unbound: ", $producer, ": ", $what, " not attached")) + }; +} +impl WindowWeights for OriginalVerifyWindowResources<'_, '_> { + fn gdn_projections(&self, gdn: usize) -> Result { + let p = self.proj.as_ref().ok_or(unattached!("mmvq", "projection weights"))?; + p.gdn_addrs(self.base.journal.context(), &self.base.journal.geometry(), gdn) + } + fn qsa_projections(&self, q: usize) -> Result { + let p = self.proj.as_ref().ok_or(unattached!("mmvq", "projection weights"))?; + p.qsa_addrs(self.base.journal.context(), &self.base.journal.geometry(), q) + } + fn hc(&self, layer: usize, half: HcHalf) -> Result { + self.gr.as_ref().ok_or(unattached!("hc_read", "hyper-connection weights"))?.half_addrs(layer, half) + } + fn head(&self) -> Result { + self.gr.as_ref().ok_or(unattached!("head", "output hyper-connection weights"))?.head_addrs() + } + fn ple(&self) -> Result> { + let gr = self.gr.as_ref().ok_or(unattached!("ple_layer1", "hyper-connection / PLE weights"))?; + if gr.has_ple() { gr.ple_addrs().map(Some) } else { Ok(None) } + } + fn qsa(&self, q: usize) -> Result { + let b = self.qsa.as_ref().ok_or(unattached!("qsa", "QSA layer weights"))?; + let kv = OriginalVerifyQsaKvBinding::from_journal(&self.base.qsa, q)?; + kv.validate(&self.base.journal.geometry())?; + Ok(QsaLayerAddrs { weights: b.addrs(q)?, kv }) + } + fn rope(&self) -> Result { + QsaRope::from_rope(&self.base.qsa.rope()) + } + fn moe(&self, layer: usize) -> Result { + self.moe.as_ref().ok_or(unattached!("router", "router / shared-expert weights"))?.addrs(layer) + } + fn expert_formats(&self) -> Result<&OriginalVerifyExpertFormats> { + Ok(self.moe.as_ref().ok_or(unattached!("expert_groups", "routed expert formats"))?.formats()) + } +} +impl resources::Sealed for OriginalVerifyWindowResources<'_, '_> {} +impl OriginalGraphResources for OriginalVerifyWindowResources<'_, '_> { + fn validate_context(&self, context: &Context<'_>) -> Result<()> { + self.base.validate_context(context)?; + self.embed.validate_context(context) + } +} +impl<'ctx> OriginalVerifyGraphResources<'ctx> for OriginalVerifyWindowResources<'_, 'ctx> { + fn verifier_qsa(&self) -> &crate::OriginalVerifyQsaJournal<'_, 'ctx> { + self.base.verifier_qsa() + } + fn verifier_journal(&self) -> &OriginalVerifyGdnJournal<'_, 'ctx> { + self.base.verifier_journal() + } +} +impl<'ctx> OriginalNativeHeadGraphResources<'ctx> for OriginalVerifyWindowResources<'_, 'ctx> { + fn native_head_rows(&self) -> Result<&crate::OriginalNativeHeadRows<'ctx>> { + self.base.native_head_rows() + } + fn native_head_rows_mut(&mut self) -> Result<&mut crate::OriginalNativeHeadRows<'ctx>> { + self.base.native_head_rows_mut() + } +} + +/// The recorder's producer set over one graph's capture stream and resources. +pub(crate) struct OriginalVerifyWindowOps<'c, 's, 'a, 'ctx> { + capture: &'c mut OriginalCapture<'s, 'ctx>, + resources: &'c mut OriginalVerifyWindowResources<'a, 'ctx>, + t: usize, + groups: usize, + policy: WindowPolicy, +} +impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> { + /// SIDE_MIXER (upstream `STRATA_SIDE_MIXER=2`, GDN part): the GDN gates and the gate projection run on side streams of the window's graph. Not in a + /// split window (two row groups), as upstream. + fn side_gdn(&self) -> bool { + self.policy.side_mixer && self.groups == 1 && self.capture.has_side() + } + /// The branch of one GDN layer. The gates (`gdn_alpha_beta`) read only the mixed activations, the gate projection only their q8_1 blocks; both + /// are complete before the qkv projection starts, and the qkv projection, the conv and the recurrence's other inputs do not touch their outputs, + /// so they fork right here and join before the recurrence. + fn issue_gdn_side(&mut self, layer: usize, rows: Rows) -> Result<()> { + let g = gdn_index(layer).ok_or(Error::InvalidQwenShape)?; + self.capture.side_fork(0)?; + self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::AlphaBeta, self.capture, g, rows.begin, rows.end)?; + self.capture.side_end(0)?; + self.capture.side_fork(1)?; + self.plan_launch(|p| p.mmvq(layer, Projection::GdnGate, rows))?; + self.capture.side_end(1) + } + fn geometry(&self) -> OriginalVerifyGeometry { + self.resources.base.journal.geometry() + } + fn plan(&self) -> PlanLayout { + let g = self.geometry(); + PlanLayout::new(g.max_t * g.k) + } + /// Byte offset of one group's device plan copy inside the "plan" span. + fn plan_group_offset(&self, group: usize) -> usize { + group * self.plan().device_stride() * 4 + } + fn journal(&self) -> &OriginalVerifyGdnJournal<'a, 'ctx> { + &self.resources.base.journal + } + fn submit(&mut self, commands: Vec) -> Result<()> { + self.resources.base.journal.submit(self.capture, commands) + } + /// Record planned launches of any sealed asset on the capture stream, in order. + fn launch(&mut self, launches: Vec) -> Result<()> { + self.resources.base.journal.submit_launches(self.capture, launches) + } + /// The pure planner over this graph's arena, policy and weight bindings. + fn planner(&self) -> Result> { + let cfg = self + .resources + .gr_cfg + .ok_or(Error::InvalidDriverValue("Original verifier window: resources were not prepared before capture"))?; + Ok(Planner::new(&self.resources.base.journal, self.geometry(), self.policy, cfg, &*self.resources)) + } + /// Plan with the planner, then record the launches. + fn plan_launch(&mut self, plan: impl FnOnce(&Planner<'_>) -> Result>) -> Result<()> { + let launches = { + let planner = self.planner()?; + plan(&planner)? + }; + self.launch(launches) + } + /// Address of a word inside the group's device plan block (`words` int32 units). + fn plan_word(&self, group: usize, word: usize) -> Result { + let layout = self.plan(); + if group >= self.groups || word >= layout.words { + return Err(Error::InvalidQwenShape); + } + self.journal().address("plan", self.plan_group_offset(group) + word * 4, 4) + } + fn mapped_flag(&self, index: usize) -> Result { + self.journal().physical.mapped_address(index, 0, 4) + } + fn wait_flag(&mut self, flag: usize, ring: u32) -> Result<()> { + let address = self.mapped_flag(flag)?; + self.submit(vec![command( + "verify_wait_flag_ge_kernel", + [1, 1, 1], + [1, 1, 1], + vec![Arg::Address(address), Arg::I32(ring as i32)], + )?]) + } +} + +impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { + fn embed(&mut self) -> Result<()> { + let g = self.geometry(); + let t = self.t; + let tokens = handle(self.resources.embed.tokens_mut()?)?.qwen_address(); + let source = self.journal().address("tok", 0, t * 4)?; + // The embedding rows read their own staged token bank; the verifier's staged tokens are + // copied (device to device, in capture order) into it before the gather. + self.submit(vec![command( + "verify_copy_i32_from_mapped_kernel", + [1, 1, 1], + [128, 1, 1], + vec![Arg::Address(tokens), Arg::Address(source), Arg::I32(t as i32)], + )?])?; + self.resources.embed.capture(self.capture)?; + let embedded = handle(self.resources.embed.output_device()?)?.qwen_address(); + let residual = self.journal().address("R", 0, t * g.hc * g.n * 4)?; + self.submit(vec![command( + "verify_broadcast_streams_kernel", + [(g.n * g.hc).div_ceil(256) as u32, t as u32, 1], + [256, 1, 1], + vec![Arg::Address(embedded), Arg::Address(residual), Arg::I64(g.n as i64), Arg::I32(g.hc as i32)], + )?]) + } + fn stamp(&mut self, layer: usize, stage: usize) -> Result<()> { + self.resources.base.journal.capture_stamp(self.capture, layer, stage) + } + fn ple_layer1(&mut self, rows: Rows) -> Result<()> { + let per_row = { + let planner = self.planner()?; + planner.ple_layer1(rows)? + }; + // Each row's history snapshot (`copy_from_mapped(hist_snap_ + t*HS, ss.ple.hist, HS)`) follows that row. + for (row, launches) in per_row { + self.launch(launches)?; + self.resources.base.journal.capture_ple_snapshot(self.capture, row)?; + } + Ok(()) + } + fn hc_read(&mut self, layer: usize, half: HcHalf, apply: bool, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.hc_read(layer, half, apply, rows))?; + let frame = layer * 2 + usize::from(half == HcHalf::Ffn); + self.resources.base.journal.capture_ladder(self.capture, frame, rows.begin, rows.end) + } + fn quantize_q8_1(&mut self, _layer: usize, source: QuantSource, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.quantize_q8_1(source, rows)) + } + fn mmvq(&mut self, layer: usize, projection: Projection, rows: Rows) -> Result<()> { + if self.side_gdn() { + match projection { + // SIDE_MIXER: the gates and the gate projection of this GDN layer are issued here, beside the qkv projection and the conv + Projection::GdnQkv => self.issue_gdn_side(layer, rows)?, + // ... and are not issued again where the literal order has them + Projection::GdnGate => return Ok(()), + _ => {} + } + } + self.plan_launch(|p| p.mmvq(layer, projection, rows)) + } + fn gdn_conv(&mut self, layer: usize, rows: Rows) -> Result<()> { + self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::Conv, self.capture, layer, rows.begin, rows.end) + } + fn gdn_alpha_beta(&mut self, layer: usize, rows: Rows) -> Result<()> { + if self.side_gdn() { + return Ok(()); // issued on side stream 0 by `issue_gdn_side` + } + self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::AlphaBeta, self.capture, layer, rows.begin, rows.end) + } + fn gdn_recurrence(&mut self, layer: usize, rows: Rows) -> Result<()> { + if self.side_gdn() { + // the recurrence reads the gates and the gate projection: the capture stream joins both branches + self.capture.side_join(0)?; + self.capture.side_join(1)?; + } + self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::Recurrence, self.capture, layer, rows.begin, rows.end) + } + fn qsa_index_k(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { + self.plan_launch(|p| p.qsa_index_k(q, rows, batched)) + } + fn qsa_k_norm_rope(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { + self.plan_launch(|p| p.qsa_k_norm_rope(q, rows, batched)) + } + fn qsa_tail_snapshot(&mut self, layer: usize) -> Result<()> { + let base = &self.resources.base; + base.qsa.capture_tail_snapshot(&base.journal, self.capture, layer) + } + fn qsa_kv_append(&mut self, q: usize, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.qsa_kv_append(q, rows)) + } + fn qsa_indexer_append(&mut self, layer: usize, rows: Rows) -> Result<()> { + let base = &self.resources.base; + base.qsa.capture_append_rows(&base.journal, self.capture, layer, rows.begin, rows.end) + } + fn qsa_q_path(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { + self.plan_launch(|p| p.qsa_q_path(q, rows, batched)) + } + fn qsa_index_q_path(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { + self.plan_launch(|p| p.qsa_index_q_path(q, rows, batched)) + } + fn qsa_block_scores_topk(&mut self, q: usize, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.qsa_block_scores_topk(q, rows)) + } + fn qsa_kv_resolve(&mut self, q: usize, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.qsa_kv_resolve(q, rows)) + } + fn qsa_decode_attention(&mut self, q: usize, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.qsa_decode_attention(q, rows)) + } + fn qsa_gate(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { + self.plan_launch(|p| p.qsa_gate(q, rows, batched)) + } + fn router(&mut self, layer: usize, rows: Rows, batched: bool) -> Result<()> { + self.plan_launch(|p| p.router(layer, rows, batched)) + } + fn doorbell(&mut self, rows: Rows) -> Result<()> { + self.resources.base.journal.capture_doorbell(self.capture, rows.begin, rows.end) + } + fn shared_expert(&mut self, layer: usize, rows: Rows, dec_batch: bool) -> Result<()> { + self.plan_launch(|p| p.shared_expert(layer, rows, dec_batch)) + } + fn quantize_expert_input(&mut self, _layer: usize, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.quantize_expert_input(rows)) + } + fn wait_plan(&mut self, ring: u32, rows: Rows) -> Result<()> { + if chain::flags().glue { + // wait flag A and the plan block copy in one launch (chain_window.cu) + let layout = self.plan(); + let flag = self.mapped_flag(11)?; + let device = self.journal().address("plan", self.plan_group_offset(rows.group), layout.words * 4)?; + let mapped = self.journal().physical.mapped_address(14, rows.group * layout.mapped_stride() * 4, layout.words * 4)?; + return self.launch(vec![Launch::new( + &chain::CHAIN, + chain::E_WAIT_COPY_I32, + [1, 1, 1], + [704, 1, 1], + 0, + vec![A::P(flag), A::I32(ring as i32), A::P(device), A::P(mapped), A::I32(layout.words as i32)], + )?]); + } + self.wait_flag(11, ring)?; + // The pool's GPU plan, copied from mapped host memory into this group's device block. + let layout = self.plan(); + let device = self.journal().address("plan", self.plan_group_offset(rows.group), layout.words * 4)?; + let mapped = self.journal().physical.mapped_address(14, rows.group * layout.mapped_stride() * 4, layout.words * 4)?; + self.submit(vec![command( + "verify_copy_i32_from_mapped_kernel", + [1, 1, 1], + [128, 1, 1], + vec![Arg::Address(device), Arg::Address(mapped), Arg::I32(layout.words as i32)], + )?]) + } + fn expert_groups(&mut self, layer: usize, rows: Rows, tier: ExpertTier) -> Result<()> { + self.plan_launch(|p| p.expert_groups(layer, rows, tier)) + } + fn wait_copies(&mut self, ring: u32) -> Result<()> { + self.wait_flag(12, ring) + } + fn pcie_stage(&mut self, layer: usize, rows: Rows) -> Result<()> { + // verify.cpp `fetch_blobs` + `rebase_ptrs` over the port's three-span source: `ptr2[3 q + r]` holds the device + // alias of span r (gate, up, down) of PCIe group q (`publish_gpu_plan`, pcie mode 2); the copy fills staging + // slot q with gate|up|down exactly as the DMA path does, then `ptr2[q]` is pointed at the slot. + let g = self.geometry(); + let layout = self.plan(); + let [gate, up, down] = self.resources.experts.role_bytes(layer)?; + let stride = gate + up + down; + let per = staging_blobs_per_group(self.groups); + if stride > g.max_expert_blob || 3 * per > g.max_t * g.k { + return Err(Error::InvalidQwenShape); + } + let stage_offset = rows.group * per * g.max_expert_blob; + let stage = self.journal().address("staging", stage_offset, per * g.max_expert_blob)?; + let source = self.plan_word(rows.group, layout.ptr2)?; + let count = self.plan_word(rows.group, layout.counts + 2)?; + let words = |bytes: usize| A::I64((bytes / 16) as i64); + let (spec, entry, grid, block) = match moe::pcie_fast_kernel() { + Some((entry, grid, block)) => (&moe::PCIE_FAST, entry, grid, block), + None => (&moe::PCIE, "verify_fetch_spans_kernel", [48 * 8, 1, 1], [256, 1, 1]), + }; + self.launch(vec![Launch::new( + spec, + entry, + grid, + block, + 0, + vec![A::P(source), A::P(count), A::P(stage), words(gate), words(up), words(down)], + )?])?; + self.submit(vec![command( + "verify_rebase_ptrs_kernel", + [1, 1, 1], + [128, 1, 1], + vec![Arg::Address(source), Arg::Address(count), Arg::U64(stage), Arg::I64(stride as i64)], + )?]) + } + fn wait_cpu(&mut self, ring: u32) -> Result<()> { + self.wait_flag(10, ring) + } + fn copy_cpu_rows(&mut self, rows: Rows, only_cpu_hits: bool) -> Result<()> { + let g = self.geometry(); + let n = rows.len(); + let first = rows.begin * g.k * g.n * 4; + let bytes = n * g.k * g.n * 4; + let parts = self.journal().address("parts", first, bytes)?; + let mapped = self.journal().physical.mapped_address(13, first, bytes)?; + if only_cpu_hits && chain::flags().glue { + let layout = self.plan(); + let hit_rows = self.plan_word(rows.group, layout.dst)?; + let count = self.plan_word(rows.group, layout.counts + 1)?; + return self.launch(vec![Launch::new( + &chain::CHAIN, + chain::E_COPY_ROWS, + [(n * g.k) as u32, 1, 1], + [128, 1, 1], + 0, + vec![A::P(parts), A::P(mapped), A::I64((g.n / 4) as i64), A::P(hit_rows), A::P(count)], + )?]); + } + let command = if only_cpu_hits { + let layout = self.plan(); + command( + "verify_copy_rows_from_mapped_kernel", + [(n * g.k) as u32, 1, 1], + [128, 1, 1], + vec![ + Arg::Address(parts), + Arg::Address(mapped), + Arg::I64((g.n / 4) as i64), + Arg::Address(self.plan_word(rows.group, layout.dst)?), + Arg::Address(self.plan_word(rows.group, layout.counts + 1)?), + ], + )? + } else { + let n4 = bytes / 16; + command( + "verify_copy_from_mapped_kernel", + [n4.div_ceil(256).min(64) as u32, 1, 1], + [256, 1, 1], + vec![Arg::Address(parts), Arg::Address(mapped), Arg::I64(n4 as i64)], + )? + }; + self.submit(vec![command]) + } + fn hit_add(&mut self, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.hit_add(rows)) + } + fn combine(&mut self, _layer: usize, rows: Rows, batched: bool) -> Result<()> { + self.plan_launch(|p| p.combine(rows, batched)) + } + fn final_write(&mut self, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.final_write(rows)) + } + fn head(&mut self, rows: usize) -> Result<()> { + // Per token `lm_head_mix` into the head rows' `mixed` buffer, then the head owner's captured tail: + // quantize ALL T, native MMVQ ALL T, greedy argmax (`capture_head_greedy`). + let mixed = handle(self.resources.base.head.mixed_mut()?)?.qwen_address(); + self.plan_launch(|p| p.head_mix(mixed, rows))?; + self.resources.base.head.capture_head_greedy(self.capture) + } +} + +impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> { + /// Record the T-token window graph for `t` (split windows use two groups). + /// `resources` is this graph's own aggregate (its head rows hold `t` rows). + pub fn record_literal_window( + &mut self, + t: usize, + resources: OriginalVerifyWindowResources<'a, 'ctx>, + policy: WindowPolicy, + ) -> Result<()> { + policy.validate_selected()?; + if resources.rows() != t { + return Err(Error::InvalidQwenShape); + } + // the cluster top-k needs sm_90+ and a sealed module; anything else keeps the Original's qsa_topk_ref + let mut policy = policy; + if policy.qsa.cluster_topk { + let cc = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?; + policy.qsa.cluster_topk = cc >= 9 && qsa::CLUSTER.sealed().is_ok(); + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| eprintln!("leleka-serve qsa decode top-k: {} (compute capability {cc})", if policy.qsa.cluster_topk { "thread-block cluster" } else { "qsa_topk_ref (cluster refused)" })); + } + // the sm_120 decode switches (original_verify_window_sm120.rs): resolved from the card and the environment, once per recording + { + let major = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?; + let minor = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MINOR)?; + let want = sm120::Sm120Switches::from_env(major, minor); + policy.qsa.attn_daily = (policy.qsa.attn_daily || want.attn_daily) && sm120::ATTN_DAILY.sealed().is_ok(); + policy.gu_swiglu = (policy.gu_swiglu || want.gu_swiglu) && sm120::GU_SWIGLU.sealed().is_ok(); + policy.side_mixer = policy.side_mixer || want.side_mixer; + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| eprintln!("leleka-serve sm120 switches: attn_daily={} gu_swiglu={} side_mixer={} (compute capability {major}.{minor}, requested {want:?})", policy.qsa.attn_daily, policy.gu_swiglu, policy.side_mixer)); + } + let ple = resources.verifier_journal().has_ple(); + let roles = if policy.pcie_mode == 2 { + let mut roles = [[0usize; 3]; WINDOW_LAYERS]; + for (layer, r) in roles.iter_mut().enumerate() { + *r = resources.experts.role_bytes(layer)?; + } + Some(roles) + } else { + None + }; + self.set_pcie_mode(policy.pcie_mode, roles)?; + // Sealed modules load before capture begins (cuModuleLoadData is not a capturable call). + let mut resources = resources; + resources.prepare(&policy)?; + // SIDE_MIXER: this recording's capture creates the two side streams (a split window just leaves them unused) + crate::original_gpu_schedule::set_side_streams_wanted(policy.side_mixer); + let recorded = self.record_window(t, resources, |capture, resources, groups| { + // The recorder re-validates the shape; the groups come from `set_split`. + let mut ops = OriginalVerifyWindowOps { capture, resources, t, groups, policy }; + record_window(&mut ops, &policy, t, groups, ple) + }); + crate::original_gpu_schedule::set_side_streams_wanted(false); + recorded + } + /// Record every T = 1..=max_t window graph and the real accepted-prefix commit + /// graph, in Original's order, BEFORE the first `run`. `window(t)` supplies each + /// graph's aggregate. All-or-nothing: the first unbound producer or admission + /// failure returns its error and `run` stays refused (`commit` is absent). + pub fn record_all( + &mut self, + policy: WindowPolicy, + mut window: impl FnMut(usize) -> Result>, + commit: OriginalVerifyWindowResources<'a, 'ctx>, + ) -> Result<()> { + policy.validate_selected()?; + let max_t = self.bank()?.geometry().max_t; + for t in 1..=max_t { + self.record_literal_window(t, window(t)?, policy).map_err(|e| graph_oom_at(e, t))?; + } + // The K/V half of a verifier commit is host publication of the mapped journal; the commit + // graph itself is GDN layer replay + QSA tail restore + re-append (+ PLE history). + self.record_commit(commit, |_, _, _| Ok(())).map_err(|e| graph_oom_at(e, 0)) + } +} + +/// A graph instantiate that ran out of device memory, named by the graph that did not fit (`window` = its T, 0 = the commit graph). +/// Any other error, and an out-of-memory that came with a cleanup failure (`Multiple`), stays as it is. +pub(crate) fn graph_oom_at(error: Error, window: usize) -> Error { + if crate::original_gpu_schedule::is_graph_out_of_memory(&error) { Error::GraphOutOfMemory { window } } else { error } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_graph_out_of_memory_is_named_by_the_graph_that_did_not_fit_and_nothing_else_is() { + let oom = Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 2 }; + assert_eq!(graph_oom_at(oom.clone(), 5), Error::GraphOutOfMemory { window: 5 }); + assert_eq!(graph_oom_at(oom.clone(), 0), Error::GraphOutOfMemory { window: 0 }); + // the upload warm-up is not an instantiate, but it shares the code and is treated the same by the capture + assert_eq!( + graph_oom_at(Error::Driver { operation: "cuGraphUpload", code: 2 }, 3), + Error::GraphOutOfMemory { window: 3 } + ); + // another code, another call, and an out-of-memory that carries a cleanup failure all stay fatal as they were + for other in [ + Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 1 }, + Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 700 }, + Error::Driver { operation: "cuStreamEndCapture", code: 2 }, + Error::ContextPoisoned, + Error::InvalidQwenShape, + Error::Multiple { primary: Box::new(oom.clone()), secondary: Box::new(Error::ContextPoisoned) }, + ] { + assert_eq!(graph_oom_at(other.clone(), 4), other); + } + assert!(graph_oom_at(oom, 2).to_string().contains("T=2")); + assert!(Error::GraphOutOfMemory { window: 0 }.to_string().contains("commit")); + } + + #[test] + fn every_window_asset_is_sealed_and_a_corrupted_pin_is_reported_by_name() { + // Sealed with nvcc 13.2.86 on 2026-10-15, so nothing is unsealed and a window may be recorded. + assert_eq!(unsealed_window_assets(), Vec::<&str>::new()); + let all = all_window_assets(); + assert!(!all.is_empty()); + for spec in &all { + spec.assert_sealed_and_fail_closed(); + } + // The two NEW sources (grouped native experts, fast-math QSA gate) are real sealed PTX too. + for new in [&moe::EXPERTS, &qsa::GATE] { + assert!(all.iter().any(|a| std::ptr::eq(*a, new)), "{}", new.name); + } + // Fail-closed reporting is alive: a one-byte-corrupted copy, a wrong digest and a zero pin of a sealed asset + // are each reported by module key (once), and the untouched specs stay out of the list. + let corrupted = moe::EXPERTS.derived(crate::sealed_ptx::test_support::one_byte_corrupted(moe::EXPERTS.ptx), moe::EXPERTS.sha); + let wrong_digest = qsa::GATE.derived(qsa::GATE.ptx, [7; 32]); + let zero_pin = gr::assets()[0].derived(gr::assets()[0].ptx, [0; 32]); + assert_eq!( + unsealed_keys([corrupted, &qsa::GATE, wrong_digest, zero_pin, corrupted]), + [corrupted.key(), wrong_digest.key(), zero_pin.key()] + ); + assert!(unsealed_keys([&moe::EXPERTS, &qsa::GATE]).is_empty()); + } + + #[test] + fn every_window_asset_is_listed_once_and_names_a_distinct_module() { + let all = all_window_assets(); + let mut keys: Vec<&str> = all.iter().map(|a| a.key()).collect(); + let count = keys.len(); + keys.sort_unstable(); + keys.dedup(); + // specs of one PTX file share a key (entries are unioned by the loader); no key hides two different files + assert!(keys.len() <= count); + for key in &keys { + let mut pins = all.iter().filter(|a| a.key() == *key).map(|a| (a.sha, a.ptx.len())); + let first = pins.next().unwrap(); + assert!(pins.all(|p| p == first), "{key}: specs of one module disagree on the file"); + } + assert!(UNBOUND_PRODUCERS.is_empty()); + } + + #[test] + fn expert_layout_requires_whole_16_byte_blobs_within_the_staging_bound() { + assert!(OriginalVerifyExpertLayout::new([1 << 20; WINDOW_LAYERS], 4 << 20).is_ok()); + assert!(OriginalVerifyExpertLayout::new([1 << 20; WINDOW_LAYERS], 1 << 19).is_err()); + let mut odd = [1 << 20; WINDOW_LAYERS]; + odd[7] = (1 << 20) + 8; + assert!(OriginalVerifyExpertLayout::new(odd, 4 << 20).is_err()); + let mut zero = [1 << 20; WINDOW_LAYERS]; + zero[0] = 0; + assert!(OriginalVerifyExpertLayout::new(zero, 4 << 20).is_err()); + assert_eq!(OriginalVerifyExpertLayout::new([32; WINDOW_LAYERS], 64).unwrap().blob_bytes(47), Ok(32)); + assert!(OriginalVerifyExpertLayout::new([32; WINDOW_LAYERS], 64).unwrap().blob_bytes(48).is_err()); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs index f6f0fb67..e63d1f20 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs @@ -1,1219 +1,1219 @@ -//! Concrete `OriginalSpecEngine` / `OriginalDraftEngine` / `OriginalFirstDraftEngine` -//! for the Original serve loop. The engine owns only the literal protocol -//! discipline of generate.cpp's serve loop (window lifetime, commit-before-draft, -//! both checkpoint restorations, async commit event, adaptive work pairing, -//! one-shot MTP completion cached for the controller's seed/chain callbacks). All -//! numerics and every physical owner live behind `OriginalServePort`, whose -//! implementation must bind the genuine verifier window, session publication and -//! `OriginalMtpDrafter::draft_from_verifier` owners. No default port exists: -//! a missing owner is `Error::Unsupported`, never a synthesized result. -use super::contract::{Error,Result}; -use super::original_spec_controller::{NanGuard,OriginalSpecController,OriginalSpecEngine,SpecConfig,SpecError}; -use super::original_spec_draft::{DraftPick,OriginalDraftEngine,OriginalFirstDraftEngine}; -use super::original_spec_adaptive::AdaptiveConfig; -use super::original_spec_policy::MAX_T; -use std::rc::Rc; - -/// One completed one-shot MTP draft (all-T residual catch-up, ring/full seed and -/// chain), exactly the picks `MtpDrafter::draft` would produce. -#[derive(Clone,Debug,PartialEq)] -pub(crate) struct DraftCompletion { - pub(crate) ids:Vec,pub(crate) probabilities:Vec, - /// Cell of the seed (`p + accepted_row`); the chain continues at `first_cell + j`. - pub(crate) first_cell:i64,pub(crate) accepted_row:usize, -} -impl DraftCompletion { - fn validate(&self,vocabulary:u32,max_picks:usize,cell:i64,row:usize)->Result<()> { - let n=self.ids.len(); - if n==0||n>max_picks||n!=self.probabilities.len()||self.first_cell!=cell||self.accepted_row!=row {return Err(Error::IdentityMismatch);} - if self.ids.iter().any(|&v|v<0||v as u32>=vocabulary) {return Err(Error::InvalidToken);} - if self.probabilities.iter().any(|p|!p.is_finite()||!(0.0..=1.0).contains(p)) {return Err(Error::NonFinite);} - Ok(()) - } -} - -/// The genuine physical owners behind the serve loop. Every method that touches -/// the GPU or a session must complete (or fence) its real commands before -/// returning an error, and a failed restore must poison the owner it touched. -pub(crate) trait OriginalServePort { - /// A completed `Verifier::run` window retaining ALL T residual rows and head - /// rows (never a capture-only graph), plus the committed-prefix evidence. - type Window; - /// Seed for the CLI draft_first entry (current committed residual). - type Seed; - type TargetCheckpoint; - type DraftCheckpoint; - type Adaptive; - /// The committed target prefix is exactly `consumed + input` at `position`. - fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()>; - /// Reads session state: the engine has already waited the commit event. - 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 the literal per-row penalty histories (sampler counter is the cell, - /// preserved across rollback) and run the genuine verifier window. - fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result; - fn validate_window(&self,window:&Self::Window,position:i64,inputs:&[i32])->Result<()>; - fn window_outputs<'a>(&self,window:&'a Self::Window)->&'a[i32]; - /// Enqueue the asynchronous commit of the first `keep` input rows (replays the - /// accepted prefix, publishes QSA/PLE/GDN state). The completion event is - /// observed only by `wait_commit`. - fn commit_window(&mut self,window:&mut Self::Window,keep:usize)->Result<()>; - /// Wait the commit event and publish the session. Idempotent when nothing is pending. - fn wait_commit(&mut self)->Result<()>; - fn drain_window(&mut self,window:Self::Window)->Result<()>; - /// Take back the physical effects of a window nothing was committed for (it was drained, both checkpoints restored): afterwards - /// `run_window` can stage rows at the same position again. Nothing outstanding is not an error. The NaN guard's retry needs it. - fn discard_window(&mut self)->Result<()>; - fn begin_adaptation(&mut self,next_round:u64)->Result; - fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()>; - /// Stage the coupled draft sampler's history (`set_draft_history`). - fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()>; - /// Literal `draft_from_verifier`: needs the committed window (commit already - /// enqueued, event dependency honored by the owner) and all T real rows. - #[allow(clippy::too_many_arguments)] - fn draft_committed(&mut self,window:&Self::Window,position:i64,accepted_row:usize,outputs:&[i32], - max_drafts:usize,min_p:f32,coupled:bool)->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<()>; -} - -/// The window receipt handed to the controller. It owns the port's window and -/// the host copies the controller needs; only this engine can drain it. -pub(crate) struct ServedWindow { - window:W,owner:Rc<()>,serial:u64,position:i64,inputs:[i32;MAX_T],outputs:[i32;MAX_T],t:usize,committed:Option, -} -impl ServedWindow { - pub(crate) fn rows(&self)->usize {self.t} - pub(crate) fn committed_rows(&self)->Option {self.committed} -} - -enum DraftStage {Idle,Replayed{serial:u64},Seeded{completion:DraftCompletion,next:usize},} -enum FirstStage {Idle,Seeded{completion:DraftCompletion,next:usize,cell:i64},} - -pub(crate) struct OriginalServeEngine { - port:P,owner:Rc<()>,vocabulary:u32,max_t:usize,max_drafts:usize,min_p:f32, - /// The chain length of the NEXT draft stage (<= `max_drafts`, the cap); equal to the cap unless an adaptive plan lowers it. - plan_drafts:usize, - serial:u64,live_windows:usize,commit_pending:bool,adaptive_pending:bool, - history_staged:Option,draft:DraftStage,first:FirstStage,poisoned:bool, -} -impl OriginalServeEngine

{ - pub(crate) fn new(port:P,vocabulary:u32,max_t:usize,max_drafts:usize)->Result { - if vocabulary==0||vocabulary>262144||!(1..=MAX_T).contains(&max_t)||max_drafts>max_t-1 {return Err(Error::InvalidDimension);} - Ok(Self{port,owner:Rc::new(()),vocabulary,max_t,max_drafts,min_p:0.0,plan_drafts:max_drafts,serial:0,live_windows:0,commit_pending:false, - adaptive_pending:false,history_staged:None,draft:DraftStage::Idle,first:FirstStage::Idle,poisoned:false}) - } - /// The request's draft confidence floor; the controller uses the same value - /// when it stops the chain, and `drain_draft` cross-checks the two. - pub(crate) fn set_min_p(&mut self,min_p:f32)->Result<()> { - if !min_p.is_finite()||min_p<0.0 {return Err(Error::InvalidDimension);} - if self.live_windows!=0||self.commit_pending {return Err(Error::IdentityMismatch);} - self.min_p=min_p;Ok(()) - } - pub(crate) fn port(&self)->&P {&self.port} - pub(crate) fn port_mut(&mut self)->&mut P {&mut self.port} - pub(crate) fn is_poisoned(&self)->bool {self.poisoned} - pub(crate) fn commit_pending(&self)->bool {self.commit_pending} - pub(crate) fn into_port(self)->P {self.port} - fn usable(&self)->Result<()> {if self.poisoned {Err(Error::IdentityMismatch)} else {Ok(())}} - fn window_ok(&self,w:&ServedWindow)->Result<()> { - if !Rc::ptr_eq(&self.owner,&w.owner)||w.serial!=self.serial {return Err(Error::IdentityMismatch);}Ok(()) - } - /// Session reads (checkpoint, validate) require the previous commit's event. - fn settle_commit(&mut self)->Result<()> { - if self.commit_pending { - self.commit_pending=false; - if let Err(e)=self.port.wait_commit() {self.poisoned=true;return Err(e);} - }Ok(()) - } - fn after_restore(&mut self) { - self.draft=DraftStage::Idle;self.first=FirstStage::Idle;self.history_staged=None; - } - fn cached_pick(&self,completion:&DraftCompletion,index:usize)->DraftPick { - DraftPick{token:completion.ids[index],probability:completion.probabilities[index]} - } -} - -impl OriginalDraftEngine> for OriginalServeEngine

{ - fn replay_target_kv(&mut self,verified:&ServedWindow,p:i64,outputs:&[i32])->Result<()> { - self.usable()?;self.window_ok(verified)?; - // Literal order: commit is enqueued BEFORE any draft reads the branch. - if verified.committed.is_none()||!matches!(self.draft,DraftStage::Idle)||p!=verified.position - ||outputs!=&verified.outputs[..verified.t] {return Err(Error::IdentityMismatch);} - self.draft=DraftStage::Replayed{serial:verified.serial};Ok(()) - } - fn full_target_seed(&mut self,verified:&ServedWindow,row:usize,cell:i64,token:i32,coupled:bool)->Result { - self.usable()?;self.window_ok(verified)?; - let keep=verified.committed.ok_or(Error::IdentityMismatch)?; - match self.draft {DraftStage::Replayed{serial} if serial==verified.serial=>{},_=>return Err(Error::IdentityMismatch)} - if row+1!=keep||row>=verified.t||cell!=verified.position.checked_add(row as i64).ok_or(Error::Overflow)? - ||token!=verified.outputs[row] {return Err(Error::IdentityMismatch);} - // A coupled draft is sampled with the staged history of THIS window. - if coupled&&self.history_staged!=Some(verified.serial) {return Err(Error::IdentityMismatch);} - let max_picks=self.plan_drafts.max(1); - let completion=self.port.draft_committed(&verified.window,verified.position,row,&verified.outputs[..verified.t], - self.plan_drafts,self.min_p,coupled)?; - completion.validate(self.vocabulary,max_picks,cell,row)?; - let pick=self.cached_pick(&completion,0); - self.draft=DraftStage::Seeded{completion,next:1};Ok(pick) - } - fn full_chain_step(&mut self,cell:i64,j:usize,previous_token:i32,_coupled:bool)->Result { - self.usable()?; - let DraftStage::Seeded{completion,next}=&self.draft else {return Err(Error::IdentityMismatch)}; - if j!=*next||j>=completion.ids.len()||cell!=completion.first_cell.checked_add(j as i64).ok_or(Error::Overflow)? - ||previous_token!=completion.ids[j-1] {return Err(Error::IdentityMismatch);} - let pick=self.cached_pick(completion,j); - if let DraftStage::Seeded{next,..}=&mut self.draft {*next+=1;}Ok(pick) - } - fn stage_coupled_history(&mut self,consumed:&[i32],next:i32)->Result<()> { - self.usable()?; - if next<0||next as u32>=self.vocabulary||consumed.iter().any(|&v|v<0||v as u32>=self.vocabulary) {return Err(Error::InvalidToken);} - self.port.stage_draft_history(consumed,next)?; - // The sampled history belongs to the window just verified (serial stays - // valid until the next verify bumps it). - self.history_staged=Some(self.serial);Ok(()) - } - fn set_draft_plan(&mut self,max_drafts:usize,min_p:f32)->Result<()> { - self.usable()?; - if max_drafts==0||max_drafts>self.max_drafts||!min_p.is_finite()||min_p<0.0 {return Err(Error::InvalidDimension);} - if !matches!(self.draft,DraftStage::Idle) {return Err(Error::IdentityMismatch);} - self.plan_drafts=max_drafts;self.min_p=min_p;Ok(()) - } - fn drain_draft(&mut self)->Result<()> { - // Always drain the real owner; then cross-check the controller's chain - // length against the one-shot completion. - let drained=self.port.drain_draft(); - let stage=std::mem::replace(&mut self.draft,DraftStage::Idle); - if drained.is_err() {self.poisoned=true;} - drained?; - if let DraftStage::Seeded{completion,next}=stage { - let n=completion.ids.len(); - if next=self.plan_drafts.min(self.max_t-1); - if !stopped {return Err(Error::IdentityMismatch);} - } - } - Ok(()) - } -} - -impl OriginalSpecEngine for OriginalServeEngine

{ - type Verified=ServedWindow; - type TargetCheckpoint=P::TargetCheckpoint; - type DraftCheckpoint=P::DraftCheckpoint; - type AdaptiveWork=P::Adaptive; - fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> { - self.usable()?; - if self.commit_pending {return Err(Error::IdentityMismatch);} - self.port.validate_current(consumed,input,position) - } - fn checkpoint_target(&self)->Result { - self.usable()?; - // The controller checkpoints right after validate_current; the previous - // commit event must already have been waited (see `apply_pending`). - if self.commit_pending {return Err(Error::IdentityMismatch);} - self.port.checkpoint_target() - } - fn checkpoint_draft(&self)->Result { - self.usable()?;if self.commit_pending {return Err(Error::IdentityMismatch);} - self.port.checkpoint_draft() - } - fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()> { - // A rollback never depends on engine health: it fences, then restores. - let settled=if self.commit_pending {self.commit_pending=false;self.port.wait_commit()} else {Ok(())}; - let restored=self.port.restore_target(checkpoint); - self.after_restore(); - if settled.is_err()||restored.is_err() {self.poisoned=true;} - settled.and(restored) - } - fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()> { - let restored=self.port.restore_draft(checkpoint); - self.after_restore(); - if restored.is_err() {self.poisoned=true;} - restored - } - fn apply_pending(&mut self)->Result<()> { - self.usable()?; - // Round-start session reads (and the adaptive refill) need the prior commit. - self.settle_commit()?; - self.port.apply_pending() - } - fn verify(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { - self.usable()?; - if inputs.is_empty()||inputs.len()>self.max_t||self.live_windows!=0||self.commit_pending - ||!matches!(self.draft,DraftStage::Idle) {return Err(Error::IdentityMismatch);} - if inputs.iter().chain(consumed).any(|&v|v<0||v as u32>=self.vocabulary) {return Err(Error::InvalidToken);} - let window=self.port.run_window(position,inputs,consumed)?; - // From here a window exists: any refusal below still has to drain it. - let t=inputs.len(); - let admission=(||{ - self.port.validate_window(&window,position,inputs)?; - let out=self.port.window_outputs(&window); - if out.len()!=t {return Err(Error::IdentityMismatch);} - let mut copy=[0;MAX_T];copy[..t].copy_from_slice(out);Ok(copy) - })(); - let outputs=match admission {Ok(o)=>o,Err(e)=>{ - if self.port.drain_window(window).is_err() {self.poisoned=true;} - return Err(e); - }}; - self.serial=self.serial.checked_add(1).ok_or(Error::Overflow)?; - self.live_windows+=1;self.history_staged=None; - let mut copy_in=[0;MAX_T];copy_in[..t].copy_from_slice(inputs); - Ok(ServedWindow{window,owner:Rc::clone(&self.owner),serial:self.serial,position,inputs:copy_in,outputs,t,committed:None}) - } - fn validate_verified(&self,verified:&Self::Verified,position:i64,inputs:&[i32])->Result<()> { - self.usable()?;self.window_ok(verified)?; - if verified.position!=position||inputs!=&verified.inputs[..verified.t] {return Err(Error::IdentityMismatch);} - self.port.validate_window(&verified.window,position,inputs) - } - fn outputs<'a>(&self,verified:&'a Self::Verified)->&'a[i32] {&verified.outputs[..verified.t]} - fn commit_verified(&mut self,verified:&mut Self::Verified,input_rows:usize)->Result<()> { - self.usable()?;self.window_ok(verified)?; - if verified.committed.is_some()||self.commit_pending||input_rows==0||input_rows>verified.t {return Err(Error::IdentityMismatch);} - // Only the accepted prefix is publishable: row k+1's input must equal output k. - if (1..input_rows).any(|k|verified.inputs[k]!=verified.outputs[k-1]) {return Err(Error::IdentityMismatch);} - // The commit event is outstanding from the moment it is enqueued, even if - // the enqueue itself reports uncertainty. - self.commit_pending=true; - if let Err(e)=self.port.commit_window(&mut verified.window,input_rows) {self.poisoned=true;return Err(e);} - verified.committed=Some(input_rows);Ok(()) - } - fn discard_window(&mut self)->Result<()> { - // after the drain of the refused window, before the checkpoints' round starts again: no window may be alive, no commit outstanding - if self.live_windows!=0||self.commit_pending {return Err(Error::IdentityMismatch);} - let discarded=self.port.discard_window(); - if discarded.is_err() {self.poisoned=true;} - discarded - } - fn drain_verified(&mut self,verified:Self::Verified)->Result<()> { - if !Rc::ptr_eq(&self.owner,&verified.owner) {return Err(Error::IdentityMismatch);} - self.live_windows=self.live_windows.saturating_sub(1); - // The draft that depended on the commit event has finished by now: wait - // the event (publishing the session) and release the window's resources. - // Both are always attempted; the first failure is the one reported. - let settled=self.settle_commit(); - let drained=self.port.drain_window(verified.window); - if drained.is_err() {self.poisoned=true;} - settled.and(drained) - } - fn begin_adaptation(&mut self,next_round:u64)->Result { - self.usable()?;if self.adaptive_pending {return Err(Error::IdentityMismatch);} - let work=self.port.begin_adaptation(next_round)?;self.adaptive_pending=true;Ok(work) - } - fn join_adaptation(&mut self,work:Self::AdaptiveWork)->Result<()> { - self.adaptive_pending=false; - let joined=self.port.join_adaptation(work); - if joined.is_err() {self.poisoned=true;}joined - } - fn wait_commit(&mut self)->Result<()> { - if self.commit_pending {self.settle_commit()} else {Ok(())} - } -} - -/// Seed receipt for the CLI `draft_first` path; same one-shot caching. -impl OriginalFirstDraftEngine for OriginalServeEngine

{ - fn replay_first_seed_kv(&mut self,_seed:&P::Seed,t:usize,cell:i64,token:i32)->Result<()> { - self.usable()?; - if t!=self.max_t||cell<0||token<0||token as u32>=self.vocabulary||self.commit_pending - ||!matches!(self.first,FirstStage::Idle)||!matches!(self.draft,DraftStage::Idle)||self.live_windows!=0 { - return Err(Error::IdentityMismatch); - } - Ok(()) - } - fn full_first_seed(&mut self,seed:&P::Seed,cell:i64,token:i32,coupled:bool)->Result { - self.usable()?; - if !matches!(self.first,FirstStage::Idle) {return Err(Error::IdentityMismatch);} - let completion=self.port.draft_first(seed,self.max_t,cell,token,self.max_drafts,self.min_p,coupled)?; - completion.validate(self.vocabulary,self.max_drafts.max(1),cell,0)?; - let pick=self.cached_pick(&completion,0); - self.first=FirstStage::Seeded{completion,next:1,cell};Ok(pick) - } - fn first_chain_step(&mut self,cell:i64,j:usize,previous_token:i32,_coupled:bool)->Result { - self.usable()?; - let FirstStage::Seeded{completion,next,cell:first}=&self.first else {return Err(Error::IdentityMismatch)}; - if j!=*next||j>=completion.ids.len()||cell!=first.checked_add(j as i64).ok_or(Error::Overflow)? - ||previous_token!=completion.ids[j-1] {return Err(Error::IdentityMismatch);} - let pick=self.cached_pick(completion,j); - if let FirstStage::Seeded{next,..}=&mut self.first {*next+=1;}Ok(pick) - } - fn drain_first_seed(&mut self)->Result<()> { - let drained=self.port.drain_first();self.first=FirstStage::Idle; - if drained.is_err() {self.poisoned=true;}drained - } -} - - -/// Whether the adaptive speculative window is the default of the serve stack (docs/adaptive-spec.md). -pub(crate) const ADAPTIVE_DEFAULT:bool=true; - -/// Original `generate` serve settings for mode17: `--spec 4` verify width, prompt lookup on -/// (`--suffix-draft 3`), which makes the MTP keep 4-wide windows (`mtp_max_t = spec`) and the -/// verifier take windows up to `spec + 2` (`kVerifyMaxT` 8), coupled draft sampling per env. -#[derive(Clone,Copy,Debug,PartialEq)] -pub(crate) struct OriginalServeSettings { - pub(crate) max_t:usize,pub(crate) mtp_max_t:usize,pub(crate) max_context:i64,pub(crate) vocabulary:u32, - pub(crate) suffix_min_match:usize,pub(crate) coupled:bool, - /// `LELEKA_SPEC_ADAPTIVE`: the adaptive window policy (`original_spec_adaptive.rs`). - pub(crate) adaptive:Option, - /// Re-run a verify window with non-finite output from its round's checkpoint (`NanGuard`); off in mode17 itself. - pub(crate) nan_guard:NanGuard, - /// An arm's own `spec_min_p` for the requests it serves (`fixed4@0`), overriding the harness default; `None` = the harness's. - pub(crate) request_min_p:Option, -} -impl OriginalServeSettings { - pub(crate) fn mode17(max_context:i64,vocabulary:u32,coupled:bool)->Self { - const SPEC:usize=4;const SUFFIX:usize=3; - Self{max_t:(SPEC+2).min(MAX_T),mtp_max_t:SPEC,max_context,vocabulary,suffix_min_match:SUFFIX,coupled,adaptive:None,nan_guard:NanGuard::off(),request_min_p:None} - } - /// Mode17 with the operator's overrides from the environment (read once per stack): - /// `LELEKA_SPEC` (the Original's `--spec`: MTP window, verify windows up to `spec + 2`, at most 8), - /// `LELEKA_SPEC_MTP_MAX_T` (`--mtp-max-t`, 0 = spec), `LELEKA_SPEC_SUFFIX` (`--suffix-draft`, 0 = off), and - /// `LELEKA_SPEC_ADAPTIVE=on` (adaptive window; widest window `LELEKA_SPEC_ADAPTIVE_MAX_T`, default 8 rows, MTP chain up - /// to `max_t - 1` drafts). Unset = mode17 exactly. - pub(crate) fn from_environment(max_context:i64,vocabulary:u32,coupled:bool)->Self { - let num=|name:&str|std::env::var(name).ok().and_then(|v|v.trim().parse::().ok()); - let mut s=Self::mode17(max_context,vocabulary,coupled); - s.nan_guard=NanGuard::from_environment(); - if let Some(spec)=num("LELEKA_SPEC") { - let spec=spec.clamp(2,MAX_T);s.max_t=(spec+2).min(MAX_T);s.mtp_max_t=spec; - } - if let Some(m)=num("LELEKA_SPEC_MTP_MAX_T") {s.mtp_max_t=if m==0 {s.max_t.min(s.mtp_max_t)} else {m.min(s.max_t)};} - if let Some(n)=num("LELEKA_SPEC_SUFFIX") {s.suffix_min_match=n;} - let explicit=std::env::var("LELEKA_SPEC_ADAPTIVE").ok(); - if Self::adaptive_wanted(explicit.as_deref(),std::env::var_os("LELEKA_SPEC").is_some()) { - let max_t=num("LELEKA_SPEC_ADAPTIVE_MAX_T").unwrap_or(MAX_T).clamp(2,MAX_T); - s.max_t=max_t;s.mtp_max_t=max_t; - s.adaptive=Some(AdaptiveConfig::new(max_t,max_t-1).from_environment()); - } - s - } - /// Adaptive window or the fixed mode17 window: an explicit `LELEKA_SPEC_ADAPTIVE` (`on`/`1`/`yes` or `off`/`0`/`no`) decides; otherwise - /// a fixed `LELEKA_SPEC=N` means the fixed window and nothing set means [`ADAPTIVE_DEFAULT`]. - pub(crate) fn adaptive_wanted(explicit:Option<&str>,fixed_spec_set:bool)->bool { - match explicit { - Some("on"|"1"|"yes")=>true, - Some("off"|"0"|"no")=>false, - _=>!fixed_spec_set&&ADAPTIVE_DEFAULT, - } - } - /// `STRATA_SPEC_COUPLED`: set, non-empty and not "0" (read once by the operator, not per request). - pub(crate) fn coupled_from_environment()->bool { - std::env::var("STRATA_SPEC_COUPLED").is_ok_and(|v|!v.is_empty()&&v!="0") - } - /// `LELEKA_SPEC_ARMS=fixed3,fixed4,fixed6,adaptive`: named window policies one process can switch between per request (an - /// A/B inside one model load, same tier and caches). `fixedN` is the Original's `--spec N` (suffix 3), `adaptive` the - /// adaptive window; the verifier is built for the widest arm. Empty when unset. - pub(crate) fn arms_from_environment(max_context:i64,vocabulary:u32,coupled:bool)->Vec<(String,Self)> { - let Ok(list)=std::env::var("LELEKA_SPEC_ARMS") else {return Vec::new()}; - let base=Self::from_environment(max_context,vocabulary,coupled); - let mut arms=Vec::new(); - for entry in list.split(',').map(str::trim).filter(|l|!l.is_empty()) { - // `name@MIN_P` pins the arm's request floor; `+flag` suffixes (`adaptive@0+tail7`) are the replay harness's, the label keeps them - let main=entry.split_once('+').map_or(entry,|(m,_)|m); - let (label,min_p)=match main.split_once('@') { - Some((l,p))=>(l,p.parse::().ok()), - None=>(main,None), - }; - let mut s=base;s.adaptive=None;s.request_min_p=min_p; - if let Some(n)=label.strip_prefix("fixed").and_then(|n|n.parse::().ok()) { - let n=n.clamp(2,MAX_T);s.max_t=(n+2).min(MAX_T);s.mtp_max_t=n;s.suffix_min_match=3; - } else if label=="adaptive" { - s.max_t=MAX_T;s.mtp_max_t=MAX_T;s.suffix_min_match=3; - s.adaptive=Some(AdaptiveConfig::new(MAX_T,MAX_T-1).from_environment()); - } else {continue;} - arms.push((entry.to_owned(),s)); - } - arms - } - /// The same policy for a verifier that records windows only up to `cap` rows (a window graph did not fit in device memory): the - /// widest window, the MTP chain and the adaptive policy's bounds are cut to it, everything else is unchanged. - pub(crate) fn with_window_cap(mut self,cap:usize)->Self { - let cap=cap.clamp(1,MAX_T); - self.max_t=self.max_t.min(cap);self.mtp_max_t=self.mtp_max_t.min(self.max_t); - if let Some(a)=self.adaptive.as_mut() {a.max_t=a.max_t.min(self.max_t);a.max_drafts=a.max_drafts.min(a.max_t.saturating_sub(1));} - self - } - /// Draft cap the engine shares with the controller's `DraftPreparation`. - pub(crate) fn max_drafts(&self)->usize {self.mtp_max_t.min(self.max_t).saturating_sub(1)} - /// The width the MTP drafter is LOADED with: generate.cpp rewrites `o.spec` to the verify width (`min(spec+2, 8)`, line 1537) - /// before `mtp.load(..., o.spec, ...)` (line 2610), so the drafter accepts every window the verifier runs (suffix drafts go up to - /// `max_t`) while its own chain stays capped by `max_drafts()` (`set_max_drafts(S_mtp - 1)`). Loading it at `mtp_max_t` made every - /// window wider than that fail `draft` (`T > max_t_`) with InvalidQwenShape. - pub(crate) fn mtp_load_t(&self)->usize {self.max_t} - /// The one production call of `OriginalSpecController::new`. - pub(crate) fn controller(&self)->Result { - OriginalSpecController::new(SpecConfig::new(self.max_t,self.mtp_max_t,self.max_context,self.vocabulary, - self.suffix_min_match,self.coupled)?.with_adaptive(self.adaptive).with_nan_guard(self.nan_guard)) - } -} - -#[derive(Clone,Copy,Debug,Eq,PartialEq)] -pub(crate) enum ServeStop {Eos,Length,Context} -#[derive(Clone,Copy,Debug,Eq,PartialEq)] -pub(crate) struct ServeOutcome {pub(crate) stop:ServeStop,pub(crate) produced:usize,pub(crate) rounds:usize} - -/// generate.cpp's serve loop for one request: begin, then verify/commit, emit the committed -/// tokens, finish the round (draft + adaptive join + drain), repeat; `finish_request` waits the -/// last commit before anything reads the session. `emit` runs only AFTER the commit succeeded. -pub(crate) fn serve_request(controller:&mut OriginalSpecController,engine:&mut E, - prompt:&[i32],max_new:usize,min_p:f32,eos:&[i32],mut emit:impl FnMut(&[i32])->Result<()>, - mut cancel:impl FnMut()->bool,mut clock_ms:impl FnMut()->f64)->std::result::Result { - let begin_span=super::original_serve_profile::span("ctrl.begin_request"); - controller.begin_request(prompt,max_new,min_p,eos)?; - drop(begin_span); - let (mut produced,mut rounds,mut stop)=(0usize,0usize,None); - let looped=(||->std::result::Result<(),SpecError> { - while !controller.finished() { - let started=clock_ms(); - let vc_span=super::original_serve_profile::span("round.verify_commit"); - let Some(round)=controller.verify_commit(engine,&mut cancel)? else {break}; - drop(vc_span); - let emit_span=super::original_serve_profile::span("round.emit"); - let emitted=emit(round.tokens()); - drop(emit_span); - produced+=round.tokens().len();rounds+=1; - if round.stopped_on_eos() {stop=Some(ServeStop::Eos);} - // A failed emit still finishes the round (drain + join) before reporting. - let fr_span=super::original_serve_profile::span("round.finish"); - let finished=controller.finish_round(engine,round,||clock_ms()-started,&mut cancel); - drop(fr_span); - emitted?;finished?; - } - Ok(()) - })(); - if let Err(e)=looped { - // Close the request best-effort (waits the last commit) so the controller is reusable - // unless a restore/finish failure already marked it failed. - let _=controller.finish_request(engine);return Err(e); - } - controller.finish_request(engine)?; - let stop=stop.unwrap_or(if produced>=max_new {ServeStop::Length} else {ServeStop::Context}); - Ok(ServeOutcome{stop,produced,rounds}) -} - - -/// Bring-up diagnostic: logs every port call and its outcome. Remove together with the DBG lines. -pub(crate) struct TracePort

(pub P); -fn tr_port(name: &str, f: impl FnOnce() -> Result) -> Result { - let started = std::time::Instant::now(); - let r = f(); - if crate::bringup_trace_enabled() { - let state = match &r { Ok(_) => "ok".to_string(), Err(e) => format!("ERR {e:?}") }; - eprintln!("DBG[{:.0}s] port.{name} {:.3}ms -> {state}", crate::qwen_forward::original_serve_stack::dbg_el(), - started.elapsed().as_secs_f64() * 1e3); - } - r -} -impl OriginalServePort for TracePort

{ - type Window = P::Window; - type Seed = P::Seed; - type TargetCheckpoint = P::TargetCheckpoint; - type DraftCheckpoint = P::DraftCheckpoint; - type Adaptive = P::Adaptive; - fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()> { tr_port("validate_current", || self.0.validate_current(consumed, input, position)) } - fn checkpoint_target(&self) -> Result { tr_port("checkpoint_target", || self.0.checkpoint_target()) } - fn checkpoint_draft(&self) -> Result { tr_port("checkpoint_draft", || self.0.checkpoint_draft()) } - fn restore_target(&mut self, c: &Self::TargetCheckpoint) -> Result<()> { tr_port("restore_target", || self.0.restore_target(c)) } - fn restore_draft(&mut self, c: &Self::DraftCheckpoint) -> Result<()> { tr_port("restore_draft", || self.0.restore_draft(c)) } - fn apply_pending(&mut self) -> Result<()> { tr_port("apply_pending", || self.0.apply_pending()) } - fn run_window(&mut self, position: i64, inputs: &[i32], consumed: &[i32]) -> Result { - crate::bringup_trace!("DBG port.run_window position={position} inputs={inputs:?} consumed_len={}", consumed.len()); - tr_port("run_window", || self.0.run_window(position, inputs, consumed)) - } - fn validate_window(&self, window: &Self::Window, position: i64, inputs: &[i32]) -> Result<()> { tr_port("validate_window", || self.0.validate_window(window, position, inputs)) } - fn window_outputs<'a>(&self, window: &'a Self::Window) -> &'a [i32] { self.0.window_outputs(window) } - fn commit_window(&mut self, window: &mut Self::Window, keep: usize) -> Result<()> { tr_port("commit_window", || self.0.commit_window(window, keep)) } - fn wait_commit(&mut self) -> Result<()> { tr_port("wait_commit", || self.0.wait_commit()) } - fn drain_window(&mut self, window: Self::Window) -> Result<()> { tr_port("drain_window", || self.0.drain_window(window)) } - fn discard_window(&mut self) -> Result<()> { tr_port("discard_window", || self.0.discard_window()) } - fn begin_adaptation(&mut self, next_round: u64) -> Result { tr_port("begin_adaptation", || self.0.begin_adaptation(next_round)) } - fn join_adaptation(&mut self, work: Self::Adaptive) -> Result<()> { tr_port("join_adaptation", || self.0.join_adaptation(work)) } - fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()> { tr_port("stage_draft_history", || self.0.stage_draft_history(consumed, next)) } - #[allow(clippy::too_many_arguments)] - fn draft_committed(&mut self, window: &Self::Window, position: i64, accepted_row: usize, outputs: &[i32], max_drafts: usize, min_p: f32, coupled: bool) -> Result { - tr_port("draft_committed", || self.0.draft_committed(window, position, accepted_row, outputs, max_drafts, min_p, coupled)) - } - fn drain_draft(&mut self) -> Result<()> { tr_port("drain_draft", || self.0.drain_draft()) } - #[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 { - tr_port("draft_first", || self.0.draft_first(seed, t, cell, token, max_drafts, min_p, coupled)) - } - fn drain_first(&mut self) -> Result<()> { tr_port("drain_first", || self.0.drain_first()) } -} - -#[cfg(test)] -mod tests { - use super::*; - use super::super::original_spec_controller::{NanGuard,OriginalSpecController,SpecConfig,SpecError}; - use super::super::original_spec_draft::DraftPreparation; - use std::cell::RefCell; - - const VOCAB:u32=1000; - fn model(x:i32)->i32 {(x*5+1)%997} - - #[derive(Default)] - struct World { - /// committed target tokens (the session prefix), including the current input. - committed:Vec,events:Vec,commit_waits:usize, - fail:Option<&'static str>,fail_restore:Option<&'static str>, - /// tokens the "MTP" drafts: chain of the model, shifted by `skew` to force rejections - skew:i32,sampler_cell:i64, - /// the highest cell (+1) a verify window row or a draft touched - max_end:i64, - } - struct Win {inputs:Vec,outputs:Vec,position:i64} - struct Fake {w:Rc>,pending_commit:Option,pending_position:i64} - impl Fake { - fn new(prompt:&[i32])->(Self,Rc>) { - let w=Rc::new(RefCell::new(World{committed:prompt.to_vec(),..Default::default()})); - (Self{w:Rc::clone(&w),pending_commit:None,pending_position:0},w) - } - fn log(&self,s:impl Into) {self.w.borrow_mut().events.push(s.into());} - fn fails(&self,what:&str)->bool {self.w.borrow().fail==Some(what)} - } - impl OriginalServePort for Fake { - type Window=Win;type Seed=i32;type TargetCheckpoint=(Vec,i64);type DraftCheckpoint=i64;type Adaptive=u64; - fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> { - let w=self.w.borrow(); - if w.committed.len() as i64!=position+1||&w.committed[..consumed.len()]!=consumed||w.committed[position as usize]!=input {return Err(Error::IdentityMismatch);} - Ok(()) - } - fn checkpoint_target(&self)->Result { - if self.pending_commit.is_some() {return Err(Error::CudaExecution);} - let w=self.w.borrow();Ok((w.committed.clone(),w.sampler_cell)) - } - fn checkpoint_draft(&self)->Result {self.log("ckpt-draft");Ok(self.w.borrow().committed.len() as i64)} - fn restore_target(&mut self,c:&Self::TargetCheckpoint)->Result<()> { - self.log("restore-target"); - if self.w.borrow().fail_restore==Some("target") {return Err(Error::CudaExecution);} - let mut w=self.w.borrow_mut();w.committed=c.0.clone();w.sampler_cell=c.1;Ok(()) - } - fn restore_draft(&mut self,_:&i64)->Result<()> { - self.log("restore-draft"); - if self.w.borrow().fail_restore==Some("draft") {return Err(Error::CudaExecution);}Ok(()) - } - fn apply_pending(&mut self)->Result<()> {self.log("apply-pending");Ok(())} - fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { - self.log(format!("run t={} consumed={}",inputs.len(),consumed.len())); - if self.fails("run") {return Err(Error::CudaExecution);} - // the window must see the committed branch (async commit already published) - let outputs:Vec=inputs.iter().map(|&x|model(x)).collect(); - self.w.borrow_mut().sampler_cell=position+inputs.len() as i64; - {let mut w=self.w.borrow_mut();w.max_end=w.max_end.max(position+inputs.len() as i64);} - Ok(Win{inputs:inputs.to_vec(),outputs,position}) - } - fn validate_window(&self,w:&Win,position:i64,inputs:&[i32])->Result<()> { - if self.fails("validate") {return Err(Error::NonFinite);} - if w.position!=position||w.inputs!=inputs {return Err(Error::IdentityMismatch);}Ok(()) - } - fn window_outputs<'a>(&self,w:&'a Win)->&'a[i32] {if self.fails("short") {&w.outputs[..1]} else {&w.outputs}} - fn commit_window(&mut self,w:&mut Win,keep:usize)->Result<()> { - self.log(format!("commit keep={keep}")); - if self.fails("commit") {return Err(Error::CudaExecution);} - self.pending_commit=Some(keep);self.pending_position=w.position; - // the published prefix is visible only after wait_commit - Ok(()) - } - fn wait_commit(&mut self)->Result<()> { - if self.pending_commit.take().is_some() { - self.log("wait-commit");self.w.borrow_mut().commit_waits+=1; - if self.fails("wait") {return Err(Error::CudaExecution);} - } - Ok(()) - } - fn drain_window(&mut self,_:Win)->Result<()> {self.log("drain-window");if self.fails("drain") {Err(Error::CudaExecution)} else {Ok(())}} - fn discard_window(&mut self)->Result<()> {self.log("discard-window");if self.fails("discard") {Err(Error::CudaExecution)} else {Ok(())}} - fn begin_adaptation(&mut self,r:u64)->Result {self.log(format!("begin-adapt {r}"));if self.fails("begin") {Err(Error::CudaExecution)} else {Ok(r)}} - fn join_adaptation(&mut self,r:u64)->Result<()> {self.log(format!("join-adapt {r}"));if self.fails("join") {Err(Error::CudaExecution)} else {Ok(())}} - fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()> {self.log(format!("history {} {next}",consumed.len()));Ok(())} - fn draft_committed(&mut self,w:&Win,position:i64,a:usize,outputs:&[i32],max_drafts:usize,min_p:f32,_coupled:bool)->Result { - self.log(format!("draft a={a}")); - if self.fails("draft") {return Err(Error::CudaExecution);} - let skew=self.w.borrow().skew; - let mut ids=vec![(model(outputs[a])+skew).rem_euclid(997)];let mut probs=vec![0.9f32]; - while ids.len()=min_p { - let last=*ids.last().unwrap();ids.push(model(last));probs.push(0.9); - } - let _=w; - {let mut wd=self.w.borrow_mut();wd.max_end=wd.max_end.max(position+a as i64+ids.len() as i64);} - Ok(DraftCompletion{ids,probabilities:probs,first_cell:position+a as i64,accepted_row:a}) - } - fn drain_draft(&mut self)->Result<()> {self.log("drain-draft");Ok(())} - fn draft_first(&mut self,_:&i32,_t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,_c:bool)->Result { - self.log("draft-first"); - let mut ids=vec![model(token)];let mut probs=vec![0.9f32]; - while ids.len()=min_p {let l=*ids.last().unwrap();ids.push(model(l));probs.push(0.9);} - Ok(DraftCompletion{ids,probabilities:probs,first_cell:cell,accepted_row:0}) - } - fn drain_first(&mut self)->Result<()> {self.log("drain-first");Ok(())} - } - - fn engine(prompt:&[i32],max_t:usize)->(OriginalServeEngine,Rc>) { - let (f,w)=Fake::new(prompt); - (OriginalServeEngine::new(f,VOCAB,max_t,max_t-1).unwrap(),w) - } - fn events(w:&Rc>)->Vec {w.borrow().events.clone()} - fn idx(e:&[String],needle:&str)->usize {e.iter().position(|s|s.starts_with(needle)).unwrap_or_else(||panic!("missing {needle} in {e:?}"))} - fn prompt() -> Vec {vec![11,model(11),model(model(11))]} - - /// Drive one window by hand the way the controller does (verify, commit). - fn verify_commit(e:&mut OriginalServeEngine,p:i64,inputs:&[i32],consumed:&[i32],keep:usize)->ServedWindow { - e.apply_pending().unwrap(); - let mut v=e.verify(p,inputs,consumed).unwrap(); - e.commit_verified(&mut v,keep).unwrap();v - } - - #[test] - fn constructor_validates_dimensions() { - let (f,_)=Fake::new(&prompt()); - assert!(OriginalServeEngine::new(f,0,4,3).is_err()); - let (f,_)=Fake::new(&prompt()); - assert!(OriginalServeEngine::new(f,VOCAB,0,0).is_err()); - let (f,_)=Fake::new(&prompt()); - assert!(OriginalServeEngine::new(f,VOCAB,4,4).is_err()); - let (f,_)=Fake::new(&prompt()); - assert!(OriginalServeEngine::new(f,VOCAB,4,3).is_ok()); - } - - #[test] - fn verify_returns_all_t_outputs_and_requires_a_drained_window() { - let p=prompt();let (mut e,w)=engine(&p,4); - let consumed=&p[..2];let input=p[2]; - let mut v=e.verify(2,&[input],consumed).unwrap(); - assert_eq!(e.outputs(&v),&[model(input)]); - e.validate_verified(&v,2,&[input]).unwrap(); - assert_eq!(e.validate_verified(&v,3,&[input]),Err(Error::IdentityMismatch)); - assert_eq!(e.validate_verified(&v,2,&[input+1]),Err(Error::IdentityMismatch)); - // a second window while one is live is refused before anything runs - let runs=events(&w).iter().filter(|s|s.starts_with("run")).count(); - assert_eq!(e.verify(2,&[input],consumed).err(),Some(Error::IdentityMismatch)); - assert_eq!(events(&w).iter().filter(|s|s.starts_with("run")).count(),runs); - e.commit_verified(&mut v,1).unwrap(); - assert_eq!(v.committed_rows(),Some(1)); - e.drain_verified(v).unwrap(); - e.wait_commit().unwrap(); - } - - #[test] - fn out_of_range_tokens_never_reach_the_port() { - let p=prompt();let (mut e,w)=engine(&p,4); - assert_eq!(e.verify(2,&[VOCAB as i32],&p[..2]).err(),Some(Error::InvalidToken)); - assert_eq!(e.verify(2,&[5],&[-1]).err(),Some(Error::InvalidToken)); - assert!(!events(&w).iter().any(|s|s.starts_with("run"))); - assert_eq!(e.verify(2,&[],&p[..2]).err(),Some(Error::IdentityMismatch)); - assert_eq!(e.verify(2,&[1,2,3,4,5],&p[..2]).err(),Some(Error::IdentityMismatch)); - } - - #[test] - fn a_short_or_invalid_window_is_drained_not_leaked() { - let p=prompt();let (mut e,w)=engine(&p,4); - w.borrow_mut().fail=Some("short"); - assert_eq!(e.verify(2,&[p[2],model(p[2])],&p[..2]).err(),Some(Error::IdentityMismatch)); - assert!(events(&w).iter().any(|s|s=="drain-window")); - w.borrow_mut().fail=Some("validate"); - assert_eq!(e.verify(2,&[p[2]],&p[..2]).err(),Some(Error::NonFinite)); - w.borrow_mut().fail=None; - // nothing left live: a clean window works again - let v=e.verify(2,&[p[2]],&p[..2]).unwrap();e.drain_verified(v).unwrap(); - assert!(!e.is_poisoned()); - } - - #[test] - fn commit_checks_the_accepted_prefix_and_only_once() { - let p=prompt();let (mut e,_)=engine(&p,4); - let a=p[2];let good=model(a); - let mut v=e.verify(2,&[a,good,good+1],&p[..2]).unwrap(); - // row 2's input (good+1) != output 1 (model(good)) so keep=3 is not a legal prefix - assert_eq!(e.commit_verified(&mut v,3),Err(Error::IdentityMismatch)); - assert_eq!(e.commit_verified(&mut v,0),Err(Error::IdentityMismatch)); - assert_eq!(e.commit_verified(&mut v,4),Err(Error::IdentityMismatch)); - e.commit_verified(&mut v,2).unwrap(); - assert_eq!(e.commit_verified(&mut v,2),Err(Error::IdentityMismatch)); - e.drain_verified(v).unwrap();e.wait_commit().unwrap(); - } - - #[test] - fn commit_is_asynchronous_and_the_window_drain_waits_for_its_event() { - let p=prompt();let (mut e,w)=engine(&p,4); - let v=verify_commit(&mut e,2,&[p[2]],&p[..2],1); - assert!(e.commit_pending()); - // checkpoints and validation refuse to read the session mid-commit - assert_eq!(e.checkpoint_target().err(),Some(Error::IdentityMismatch)); - assert_eq!(e.checkpoint_draft().err(),Some(Error::IdentityMismatch)); - assert_eq!(e.validate_current(&p[..2],p[2],2),Err(Error::IdentityMismatch)); - assert_eq!(w.borrow().commit_waits,0); - // the draft (event-dependent) runs before the drain; the drain waits + publishes - e.drain_verified(v).unwrap(); - assert_eq!(w.borrow().commit_waits,1); - assert!(!e.commit_pending()); - let ev=events(&w); - assert!(idx(&ev,"wait-commit")(Vec,Vec) { - let p=prompt_long(); - let (f,w)=Fake::new(&p[..p.len()-1]); - // Fake's committed prefix tracks tokens through the current input - w.borrow_mut().committed=p.clone();w.borrow_mut().skew=skew; - let mut e=OriginalServeEngine::new(f,VOCAB,max_t,max_t-1).unwrap(); - let mut c=OriginalSpecController::new(SpecConfig::new(max_t,0,4096,VOCAB,0,false).unwrap()).unwrap(); - c.begin_request(&p,max_new,0.0,&[]).unwrap(); - e.set_min_p(0.0).unwrap(); - let mut out=Vec::new(); - while !c.finished() { - // the fake's committed list must follow what the controller commits - let round=match c.verify_commit(&mut e,||false) {Ok(Some(r))=>r,Ok(None)=>break,Err(err)=>panic!("{err:?}")}; - out.extend_from_slice(round.tokens()); - w.borrow_mut().committed.extend_from_slice(round.tokens()); - c.finish_round(&mut e,round,||1.0,||false).unwrap(); - } - c.finish_request(&mut e).unwrap(); - let ev=events(&w);(out,ev) - } - fn prompt_long()->Vec {let mut v=vec![11];for i in 1..40 {v.push(model(v[i-1]));}v} - - #[test] - fn controller_over_the_engine_emits_the_greedy_continuation() { - let (out,ev)=run_request(0,4,20); - let mut expect=Vec::new();let mut x=*prompt_long().last().unwrap(); - for _ in 0..out.len() {x=model(x);expect.push(x);} - assert_eq!(out,expect); - assert!(out.len()>=20); - // every verify was followed by a commit, a drain, and (while unfinished) a draft - assert!(ev.iter().filter(|s|s.starts_with("commit keep=")).count()>=4); - assert_eq!(ev.iter().filter(|s|s.starts_with("run ")).count(),ev.iter().filter(|s|s.starts_with("commit keep=")).count()); - assert_eq!(ev.iter().filter(|s|*s=="drain-window").count(),ev.iter().filter(|s|s.starts_with("run ")).count()); - } - - #[test] - fn controller_over_the_engine_survives_rejected_drafts() { - let (out,ev)=run_request(3,4,12); - let mut expect=Vec::new();let mut x=*prompt_long().last().unwrap(); - for _ in 0..out.len() {x=model(x);expect.push(x);} - assert_eq!(out,expect,"rejected drafts must never change the greedy text"); - assert!(ev.iter().any(|s|s=="commit keep=1")); - } - - #[test] - fn controller_both_restores_run_when_the_verifier_fails() { - let p=prompt_long(); - let (f,w)=Fake::new(&p); - let mut e=OriginalServeEngine::new(f,VOCAB,4,3).unwrap(); - let mut c=OriginalSpecController::new(SpecConfig::new(4,0,4096,VOCAB,0,false).unwrap()).unwrap(); - c.begin_request(&p,8,0.0,&[]).unwrap(); - w.borrow_mut().fail=Some("run"); - let err=c.verify_commit(&mut e,||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::CudaExecution)); - let ev=events(&w); - assert!(ev.iter().any(|s|s=="restore-target")&&ev.iter().any(|s|s=="restore-draft")); - assert!(!c.is_failed()); - } - - #[test] - fn preparation_drives_the_engine_through_after_verified() { - let p=prompt();let (mut e,_)=engine(&p,4); - let a=p[2]; - let mut v=e.verify(2,&[a],&p[..2]).unwrap(); - let outs=e.outputs(&v).to_vec();e.commit_verified(&mut v,1).unwrap(); - let prep=DraftPreparation::new(4,3,VOCAB).unwrap(); - let batch=prep.after_verified(&mut e,&v,2,0,&outs,&p[..3],&mut crate::qwen_forward::token_memo::PrefixMemo::new(),0.0,false).unwrap(); - assert_eq!(batch.produced(),3); - assert_eq!(batch.ids()[0],model(outs[0])); - e.drain_verified(v).unwrap(); - } - - #[test] - fn the_adaptive_window_is_selected_by_the_explicit_switch_then_by_a_fixed_spec_then_by_the_default() { - let w=OriginalServeSettings::adaptive_wanted; - assert!(w(Some("on"),false)&&w(Some("1"),true)&&w(Some("yes"),true)); - assert!(!w(Some("off"),false)&&!w(Some("0"),false)&&!w(Some("no"),false)); - assert_eq!(w(None,false),ADAPTIVE_DEFAULT); - assert!(!w(None,true),"a fixed LELEKA_SPEC keeps the fixed window"); - } - - #[test] - fn a_window_cap_narrows_every_bound_and_leaves_the_rest() { - let mut wide=OriginalServeSettings::mode17(4096,VOCAB,true); - wide.max_t=8;wide.mtp_max_t=8; - wide.adaptive=Some(AdaptiveConfig::new(8,7)); - for cap in 2..=8 { - let s=wide.with_window_cap(cap); - assert_eq!((s.max_t,s.mtp_max_t),(cap,cap),"cap {cap}"); - assert_eq!(s.max_drafts(),cap-1); - let a=s.adaptive.unwrap(); - assert_eq!((a.max_t,a.max_drafts),(cap,cap-1)); - // unchanged: everything that is not a width - assert_eq!((s.max_context,s.vocabulary,s.suffix_min_match,s.coupled),(wide.max_context,wide.vocabulary,wide.suffix_min_match,wide.coupled)); - assert_eq!(s.nan_guard,wide.nan_guard); - // the controller and the engine accept it - let c=s.controller().unwrap(); - assert!(c.finished()&&!c.is_failed()); - let (f,_)=Fake::new(&prompt_long()); - assert!(OriginalServeEngine::new(f,VOCAB,s.max_t,s.max_drafts()).is_ok(),"cap {cap}"); - } - // a cap above the settings changes nothing; a fixed window narrower than the cap keeps its own width - assert_eq!(wide.with_window_cap(8),wide); - let fixed=OriginalServeSettings::mode17(4096,VOCAB,false); - assert_eq!(fixed.with_window_cap(8),fixed); - let narrow=fixed.with_window_cap(3); - assert_eq!((narrow.max_t,narrow.mtp_max_t,narrow.max_drafts()),(3,3,2)); - assert!(narrow.adaptive.is_none()); - } - - #[test] - fn mode17_settings_follow_generate_defaults() { - let s=OriginalServeSettings::mode17(4096,VOCAB,false); - assert_eq!((s.max_t,s.mtp_max_t,s.suffix_min_match),(6,4,3)); - assert_eq!(s.max_drafts(),3); - // the drafter is loaded at the verify width (6), not at its own window width (4): suffix windows are 6 rows wide - assert_eq!(s.mtp_load_t(),6); - assert!(s.mtp_load_t()>=s.max_t&&s.max_drafts()bool,fail_emit_after:Option) - ->(std::result::Result,Vec,OriginalSpecController,OriginalServeEngine) { - let (r,out,c,e,_)=serve_in(p,max_new,eos,cancel,fail_emit_after,4096);(r,out,c,e) - } - fn serve_in(p:&[i32],max_new:usize,eos:&[i32],mut cancel:impl FnMut()->bool,fail_emit_after:Option,max_context:i64) - ->(std::result::Result,Vec,OriginalSpecController,OriginalServeEngine,Rc>) { - let (f,w)=Fake::new(p); - let s=OriginalServeSettings{max_t:4,mtp_max_t:0,max_context,vocabulary:VOCAB,suffix_min_match:0,coupled:false,adaptive:None,nan_guard:NanGuard::off(),request_min_p:None}; - let mut e=OriginalServeEngine::new(f,VOCAB,s.max_t,s.max_t-1).unwrap(); - let mut c=s.controller().unwrap(); - let mut out=Vec::new(); - let wc=Rc::clone(&w); - let r=serve_request(&mut c,&mut e,p,max_new,0.0,eos,|t|{ - if fail_emit_after.is_some_and(|n|out.len()>=n) {return Err(Error::InputRead);} - out.extend_from_slice(t);wc.borrow_mut().committed.extend_from_slice(t);Ok(()) - },&mut cancel,||0.0); - (r,out,c,e,w) - } - - /// Upstream 41cf05a0 `e85567b6`: through the real engine (plan, cap and cross-check of the chain), a request that runs to the - /// context's end never touches a cell past it, whatever the distance of the last windows to it. - #[test] - fn serve_request_to_the_context_end_stays_inside_the_cells_and_ends_as_context() { - let p=prompt_long(); - for k in 1..=9i64 { - let max_context=p.len() as i64-1+k; - let (r,out,c,e,w)=serve_in(&p,1000,&[],||false,None,max_context); - let r=r.unwrap_or_else(|err|panic!("k {k}: {err:?}")); - assert_eq!(r.stop,ServeStop::Context,"k {k}"); - assert_eq!(out.len() as i64,k,"k {k}: one token per row that fits"); - let mut x=*p.last().unwrap();for &t in &out {x=model(x);assert_eq!(t,x);} - assert!(w.borrow().max_end<=max_context,"k {k}: touched cell {} of {max_context}",w.borrow().max_end); - assert!(c.finished()&&!c.is_failed()&&!e.is_poisoned()&&!e.commit_pending(),"k {k}"); - } - } - - #[test] - fn serve_request_emits_the_greedy_text_and_reports_the_stop() { - let p=prompt_long(); - let (r,out,mut c,_e)=serve(&p,10,&[],||false,None); - let r=r.unwrap(); - assert_eq!(r.stop,ServeStop::Length); - assert!(r.produced>=10&&r.rounds>=1); - assert_eq!(out.len(),r.produced); - let mut x=*p.last().unwrap();for &t in &out {x=model(x);assert_eq!(t,x);} - // the controller is reusable for the next request - assert!(c.begin_request(&p,1,0.0,&[]).is_ok()); - } - - /// Upstream 41cf05a0 `aece46db`: a 1-token prompt (position 0 is the first verify input) speculates like any other. - #[test] - fn serve_request_with_a_one_token_prompt_speculates() { - let p=vec![11]; - let (r,out,_c,e)=serve(&p,30,&[],||false,None); - let r=r.unwrap(); - assert_eq!((r.stop,r.produced),(ServeStop::Length,out.len())); - assert!(out.len()>=30); - let mut x=11;for &t in &out {x=model(x);assert_eq!(t,x);} - assert!(r.rounds3},None); - assert_eq!(r.err(),Some(SpecError::Cancelled)); - assert!(c.finished(),"a cancelled request is closed"); - assert!(!e.commit_pending()); - } - - #[test] - fn serve_request_a_failed_emit_still_finishes_the_round_and_closes_the_request() { - let p=prompt_long(); - let (r,out,c,e)=serve(&p,50,&[],||false,Some(1)); - assert_eq!(r.err(),Some(SpecError::Forward(Error::InputRead))); - assert!(!out.is_empty()); - assert!(c.finished()&&!e.commit_pending()); - } -} +//! Concrete `OriginalSpecEngine` / `OriginalDraftEngine` / `OriginalFirstDraftEngine` +//! for the Original serve loop. The engine owns only the literal protocol +//! discipline of generate.cpp's serve loop (window lifetime, commit-before-draft, +//! both checkpoint restorations, async commit event, adaptive work pairing, +//! one-shot MTP completion cached for the controller's seed/chain callbacks). All +//! numerics and every physical owner live behind `OriginalServePort`, whose +//! implementation must bind the genuine verifier window, session publication and +//! `OriginalMtpDrafter::draft_from_verifier` owners. No default port exists: +//! a missing owner is `Error::Unsupported`, never a synthesized result. +use super::contract::{Error,Result}; +use super::original_spec_controller::{NanGuard,OriginalSpecController,OriginalSpecEngine,SpecConfig,SpecError}; +use super::original_spec_draft::{DraftPick,OriginalDraftEngine,OriginalFirstDraftEngine}; +use super::original_spec_adaptive::AdaptiveConfig; +use super::original_spec_policy::MAX_T; +use std::rc::Rc; + +/// One completed one-shot MTP draft (all-T residual catch-up, ring/full seed and +/// chain), exactly the picks `MtpDrafter::draft` would produce. +#[derive(Clone,Debug,PartialEq)] +pub(crate) struct DraftCompletion { + pub(crate) ids:Vec,pub(crate) probabilities:Vec, + /// Cell of the seed (`p + accepted_row`); the chain continues at `first_cell + j`. + pub(crate) first_cell:i64,pub(crate) accepted_row:usize, +} +impl DraftCompletion { + fn validate(&self,vocabulary:u32,max_picks:usize,cell:i64,row:usize)->Result<()> { + let n=self.ids.len(); + if n==0||n>max_picks||n!=self.probabilities.len()||self.first_cell!=cell||self.accepted_row!=row {return Err(Error::IdentityMismatch);} + if self.ids.iter().any(|&v|v<0||v as u32>=vocabulary) {return Err(Error::InvalidToken);} + if self.probabilities.iter().any(|p|!p.is_finite()||!(0.0..=1.0).contains(p)) {return Err(Error::NonFinite);} + Ok(()) + } +} + +/// The genuine physical owners behind the serve loop. Every method that touches +/// the GPU or a session must complete (or fence) its real commands before +/// returning an error, and a failed restore must poison the owner it touched. +pub(crate) trait OriginalServePort { + /// A completed `Verifier::run` window retaining ALL T residual rows and head + /// rows (never a capture-only graph), plus the committed-prefix evidence. + type Window; + /// Seed for the CLI draft_first entry (current committed residual). + type Seed; + type TargetCheckpoint; + type DraftCheckpoint; + type Adaptive; + /// The committed target prefix is exactly `consumed + input` at `position`. + fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()>; + /// Reads session state: the engine has already waited the commit event. + 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 the literal per-row penalty histories (sampler counter is the cell, + /// preserved across rollback) and run the genuine verifier window. + fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result; + fn validate_window(&self,window:&Self::Window,position:i64,inputs:&[i32])->Result<()>; + fn window_outputs<'a>(&self,window:&'a Self::Window)->&'a[i32]; + /// Enqueue the asynchronous commit of the first `keep` input rows (replays the + /// accepted prefix, publishes QSA/PLE/GDN state). The completion event is + /// observed only by `wait_commit`. + fn commit_window(&mut self,window:&mut Self::Window,keep:usize)->Result<()>; + /// Wait the commit event and publish the session. Idempotent when nothing is pending. + fn wait_commit(&mut self)->Result<()>; + fn drain_window(&mut self,window:Self::Window)->Result<()>; + /// Take back the physical effects of a window nothing was committed for (it was drained, both checkpoints restored): afterwards + /// `run_window` can stage rows at the same position again. Nothing outstanding is not an error. The NaN guard's retry needs it. + fn discard_window(&mut self)->Result<()>; + fn begin_adaptation(&mut self,next_round:u64)->Result; + fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()>; + /// Stage the coupled draft sampler's history (`set_draft_history`). + fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()>; + /// Literal `draft_from_verifier`: needs the committed window (commit already + /// enqueued, event dependency honored by the owner) and all T real rows. + #[allow(clippy::too_many_arguments)] + fn draft_committed(&mut self,window:&Self::Window,position:i64,accepted_row:usize,outputs:&[i32], + max_drafts:usize,min_p:f32,coupled:bool)->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<()>; +} + +/// The window receipt handed to the controller. It owns the port's window and +/// the host copies the controller needs; only this engine can drain it. +pub(crate) struct ServedWindow { + window:W,owner:Rc<()>,serial:u64,position:i64,inputs:[i32;MAX_T],outputs:[i32;MAX_T],t:usize,committed:Option, +} +impl ServedWindow { + pub(crate) fn rows(&self)->usize {self.t} + pub(crate) fn committed_rows(&self)->Option {self.committed} +} + +enum DraftStage {Idle,Replayed{serial:u64},Seeded{completion:DraftCompletion,next:usize},} +enum FirstStage {Idle,Seeded{completion:DraftCompletion,next:usize,cell:i64},} + +pub(crate) struct OriginalServeEngine { + port:P,owner:Rc<()>,vocabulary:u32,max_t:usize,max_drafts:usize,min_p:f32, + /// The chain length of the NEXT draft stage (<= `max_drafts`, the cap); equal to the cap unless an adaptive plan lowers it. + plan_drafts:usize, + serial:u64,live_windows:usize,commit_pending:bool,adaptive_pending:bool, + history_staged:Option,draft:DraftStage,first:FirstStage,poisoned:bool, +} +impl OriginalServeEngine

{ + pub(crate) fn new(port:P,vocabulary:u32,max_t:usize,max_drafts:usize)->Result { + if vocabulary==0||vocabulary>262144||!(1..=MAX_T).contains(&max_t)||max_drafts>max_t-1 {return Err(Error::InvalidDimension);} + Ok(Self{port,owner:Rc::new(()),vocabulary,max_t,max_drafts,min_p:0.0,plan_drafts:max_drafts,serial:0,live_windows:0,commit_pending:false, + adaptive_pending:false,history_staged:None,draft:DraftStage::Idle,first:FirstStage::Idle,poisoned:false}) + } + /// The request's draft confidence floor; the controller uses the same value + /// when it stops the chain, and `drain_draft` cross-checks the two. + pub(crate) fn set_min_p(&mut self,min_p:f32)->Result<()> { + if !min_p.is_finite()||min_p<0.0 {return Err(Error::InvalidDimension);} + if self.live_windows!=0||self.commit_pending {return Err(Error::IdentityMismatch);} + self.min_p=min_p;Ok(()) + } + pub(crate) fn port(&self)->&P {&self.port} + pub(crate) fn port_mut(&mut self)->&mut P {&mut self.port} + pub(crate) fn is_poisoned(&self)->bool {self.poisoned} + pub(crate) fn commit_pending(&self)->bool {self.commit_pending} + pub(crate) fn into_port(self)->P {self.port} + fn usable(&self)->Result<()> {if self.poisoned {Err(Error::IdentityMismatch)} else {Ok(())}} + fn window_ok(&self,w:&ServedWindow)->Result<()> { + if !Rc::ptr_eq(&self.owner,&w.owner)||w.serial!=self.serial {return Err(Error::IdentityMismatch);}Ok(()) + } + /// Session reads (checkpoint, validate) require the previous commit's event. + fn settle_commit(&mut self)->Result<()> { + if self.commit_pending { + self.commit_pending=false; + if let Err(e)=self.port.wait_commit() {self.poisoned=true;return Err(e);} + }Ok(()) + } + fn after_restore(&mut self) { + self.draft=DraftStage::Idle;self.first=FirstStage::Idle;self.history_staged=None; + } + fn cached_pick(&self,completion:&DraftCompletion,index:usize)->DraftPick { + DraftPick{token:completion.ids[index],probability:completion.probabilities[index]} + } +} + +impl OriginalDraftEngine> for OriginalServeEngine

{ + fn replay_target_kv(&mut self,verified:&ServedWindow,p:i64,outputs:&[i32])->Result<()> { + self.usable()?;self.window_ok(verified)?; + // Literal order: commit is enqueued BEFORE any draft reads the branch. + if verified.committed.is_none()||!matches!(self.draft,DraftStage::Idle)||p!=verified.position + ||outputs!=&verified.outputs[..verified.t] {return Err(Error::IdentityMismatch);} + self.draft=DraftStage::Replayed{serial:verified.serial};Ok(()) + } + fn full_target_seed(&mut self,verified:&ServedWindow,row:usize,cell:i64,token:i32,coupled:bool)->Result { + self.usable()?;self.window_ok(verified)?; + let keep=verified.committed.ok_or(Error::IdentityMismatch)?; + match self.draft {DraftStage::Replayed{serial} if serial==verified.serial=>{},_=>return Err(Error::IdentityMismatch)} + if row+1!=keep||row>=verified.t||cell!=verified.position.checked_add(row as i64).ok_or(Error::Overflow)? + ||token!=verified.outputs[row] {return Err(Error::IdentityMismatch);} + // A coupled draft is sampled with the staged history of THIS window. + if coupled&&self.history_staged!=Some(verified.serial) {return Err(Error::IdentityMismatch);} + let max_picks=self.plan_drafts.max(1); + let completion=self.port.draft_committed(&verified.window,verified.position,row,&verified.outputs[..verified.t], + self.plan_drafts,self.min_p,coupled)?; + completion.validate(self.vocabulary,max_picks,cell,row)?; + let pick=self.cached_pick(&completion,0); + self.draft=DraftStage::Seeded{completion,next:1};Ok(pick) + } + fn full_chain_step(&mut self,cell:i64,j:usize,previous_token:i32,_coupled:bool)->Result { + self.usable()?; + let DraftStage::Seeded{completion,next}=&self.draft else {return Err(Error::IdentityMismatch)}; + if j!=*next||j>=completion.ids.len()||cell!=completion.first_cell.checked_add(j as i64).ok_or(Error::Overflow)? + ||previous_token!=completion.ids[j-1] {return Err(Error::IdentityMismatch);} + let pick=self.cached_pick(completion,j); + if let DraftStage::Seeded{next,..}=&mut self.draft {*next+=1;}Ok(pick) + } + fn stage_coupled_history(&mut self,consumed:&[i32],next:i32)->Result<()> { + self.usable()?; + if next<0||next as u32>=self.vocabulary||consumed.iter().any(|&v|v<0||v as u32>=self.vocabulary) {return Err(Error::InvalidToken);} + self.port.stage_draft_history(consumed,next)?; + // The sampled history belongs to the window just verified (serial stays + // valid until the next verify bumps it). + self.history_staged=Some(self.serial);Ok(()) + } + fn set_draft_plan(&mut self,max_drafts:usize,min_p:f32)->Result<()> { + self.usable()?; + if max_drafts==0||max_drafts>self.max_drafts||!min_p.is_finite()||min_p<0.0 {return Err(Error::InvalidDimension);} + if !matches!(self.draft,DraftStage::Idle) {return Err(Error::IdentityMismatch);} + self.plan_drafts=max_drafts;self.min_p=min_p;Ok(()) + } + fn drain_draft(&mut self)->Result<()> { + // Always drain the real owner; then cross-check the controller's chain + // length against the one-shot completion. + let drained=self.port.drain_draft(); + let stage=std::mem::replace(&mut self.draft,DraftStage::Idle); + if drained.is_err() {self.poisoned=true;} + drained?; + if let DraftStage::Seeded{completion,next}=stage { + let n=completion.ids.len(); + if next=self.plan_drafts.min(self.max_t-1); + if !stopped {return Err(Error::IdentityMismatch);} + } + } + Ok(()) + } +} + +impl OriginalSpecEngine for OriginalServeEngine

{ + type Verified=ServedWindow; + type TargetCheckpoint=P::TargetCheckpoint; + type DraftCheckpoint=P::DraftCheckpoint; + type AdaptiveWork=P::Adaptive; + fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> { + self.usable()?; + if self.commit_pending {return Err(Error::IdentityMismatch);} + self.port.validate_current(consumed,input,position) + } + fn checkpoint_target(&self)->Result { + self.usable()?; + // The controller checkpoints right after validate_current; the previous + // commit event must already have been waited (see `apply_pending`). + if self.commit_pending {return Err(Error::IdentityMismatch);} + self.port.checkpoint_target() + } + fn checkpoint_draft(&self)->Result { + self.usable()?;if self.commit_pending {return Err(Error::IdentityMismatch);} + self.port.checkpoint_draft() + } + fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()> { + // A rollback never depends on engine health: it fences, then restores. + let settled=if self.commit_pending {self.commit_pending=false;self.port.wait_commit()} else {Ok(())}; + let restored=self.port.restore_target(checkpoint); + self.after_restore(); + if settled.is_err()||restored.is_err() {self.poisoned=true;} + settled.and(restored) + } + fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()> { + let restored=self.port.restore_draft(checkpoint); + self.after_restore(); + if restored.is_err() {self.poisoned=true;} + restored + } + fn apply_pending(&mut self)->Result<()> { + self.usable()?; + // Round-start session reads (and the adaptive refill) need the prior commit. + self.settle_commit()?; + self.port.apply_pending() + } + fn verify(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { + self.usable()?; + if inputs.is_empty()||inputs.len()>self.max_t||self.live_windows!=0||self.commit_pending + ||!matches!(self.draft,DraftStage::Idle) {return Err(Error::IdentityMismatch);} + if inputs.iter().chain(consumed).any(|&v|v<0||v as u32>=self.vocabulary) {return Err(Error::InvalidToken);} + let window=self.port.run_window(position,inputs,consumed)?; + // From here a window exists: any refusal below still has to drain it. + let t=inputs.len(); + let admission=(||{ + self.port.validate_window(&window,position,inputs)?; + let out=self.port.window_outputs(&window); + if out.len()!=t {return Err(Error::IdentityMismatch);} + let mut copy=[0;MAX_T];copy[..t].copy_from_slice(out);Ok(copy) + })(); + let outputs=match admission {Ok(o)=>o,Err(e)=>{ + if self.port.drain_window(window).is_err() {self.poisoned=true;} + return Err(e); + }}; + self.serial=self.serial.checked_add(1).ok_or(Error::Overflow)?; + self.live_windows+=1;self.history_staged=None; + let mut copy_in=[0;MAX_T];copy_in[..t].copy_from_slice(inputs); + Ok(ServedWindow{window,owner:Rc::clone(&self.owner),serial:self.serial,position,inputs:copy_in,outputs,t,committed:None}) + } + fn validate_verified(&self,verified:&Self::Verified,position:i64,inputs:&[i32])->Result<()> { + self.usable()?;self.window_ok(verified)?; + if verified.position!=position||inputs!=&verified.inputs[..verified.t] {return Err(Error::IdentityMismatch);} + self.port.validate_window(&verified.window,position,inputs) + } + fn outputs<'a>(&self,verified:&'a Self::Verified)->&'a[i32] {&verified.outputs[..verified.t]} + fn commit_verified(&mut self,verified:&mut Self::Verified,input_rows:usize)->Result<()> { + self.usable()?;self.window_ok(verified)?; + if verified.committed.is_some()||self.commit_pending||input_rows==0||input_rows>verified.t {return Err(Error::IdentityMismatch);} + // Only the accepted prefix is publishable: row k+1's input must equal output k. + if (1..input_rows).any(|k|verified.inputs[k]!=verified.outputs[k-1]) {return Err(Error::IdentityMismatch);} + // The commit event is outstanding from the moment it is enqueued, even if + // the enqueue itself reports uncertainty. + self.commit_pending=true; + if let Err(e)=self.port.commit_window(&mut verified.window,input_rows) {self.poisoned=true;return Err(e);} + verified.committed=Some(input_rows);Ok(()) + } + fn discard_window(&mut self)->Result<()> { + // after the drain of the refused window, before the checkpoints' round starts again: no window may be alive, no commit outstanding + if self.live_windows!=0||self.commit_pending {return Err(Error::IdentityMismatch);} + let discarded=self.port.discard_window(); + if discarded.is_err() {self.poisoned=true;} + discarded + } + fn drain_verified(&mut self,verified:Self::Verified)->Result<()> { + if !Rc::ptr_eq(&self.owner,&verified.owner) {return Err(Error::IdentityMismatch);} + self.live_windows=self.live_windows.saturating_sub(1); + // The draft that depended on the commit event has finished by now: wait + // the event (publishing the session) and release the window's resources. + // Both are always attempted; the first failure is the one reported. + let settled=self.settle_commit(); + let drained=self.port.drain_window(verified.window); + if drained.is_err() {self.poisoned=true;} + settled.and(drained) + } + fn begin_adaptation(&mut self,next_round:u64)->Result { + self.usable()?;if self.adaptive_pending {return Err(Error::IdentityMismatch);} + let work=self.port.begin_adaptation(next_round)?;self.adaptive_pending=true;Ok(work) + } + fn join_adaptation(&mut self,work:Self::AdaptiveWork)->Result<()> { + self.adaptive_pending=false; + let joined=self.port.join_adaptation(work); + if joined.is_err() {self.poisoned=true;}joined + } + fn wait_commit(&mut self)->Result<()> { + if self.commit_pending {self.settle_commit()} else {Ok(())} + } +} + +/// Seed receipt for the CLI `draft_first` path; same one-shot caching. +impl OriginalFirstDraftEngine for OriginalServeEngine

{ + fn replay_first_seed_kv(&mut self,_seed:&P::Seed,t:usize,cell:i64,token:i32)->Result<()> { + self.usable()?; + if t!=self.max_t||cell<0||token<0||token as u32>=self.vocabulary||self.commit_pending + ||!matches!(self.first,FirstStage::Idle)||!matches!(self.draft,DraftStage::Idle)||self.live_windows!=0 { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + fn full_first_seed(&mut self,seed:&P::Seed,cell:i64,token:i32,coupled:bool)->Result { + self.usable()?; + if !matches!(self.first,FirstStage::Idle) {return Err(Error::IdentityMismatch);} + let completion=self.port.draft_first(seed,self.max_t,cell,token,self.max_drafts,self.min_p,coupled)?; + completion.validate(self.vocabulary,self.max_drafts.max(1),cell,0)?; + let pick=self.cached_pick(&completion,0); + self.first=FirstStage::Seeded{completion,next:1,cell};Ok(pick) + } + fn first_chain_step(&mut self,cell:i64,j:usize,previous_token:i32,_coupled:bool)->Result { + self.usable()?; + let FirstStage::Seeded{completion,next,cell:first}=&self.first else {return Err(Error::IdentityMismatch)}; + if j!=*next||j>=completion.ids.len()||cell!=first.checked_add(j as i64).ok_or(Error::Overflow)? + ||previous_token!=completion.ids[j-1] {return Err(Error::IdentityMismatch);} + let pick=self.cached_pick(completion,j); + if let FirstStage::Seeded{next,..}=&mut self.first {*next+=1;}Ok(pick) + } + fn drain_first_seed(&mut self)->Result<()> { + let drained=self.port.drain_first();self.first=FirstStage::Idle; + if drained.is_err() {self.poisoned=true;}drained + } +} + + +/// Whether the adaptive speculative window is the default of the serve stack (docs/adaptive-spec.md). +pub(crate) const ADAPTIVE_DEFAULT:bool=true; + +/// Original `generate` serve settings for mode17: `--spec 4` verify width, prompt lookup on +/// (`--suffix-draft 3`), which makes the MTP keep 4-wide windows (`mtp_max_t = spec`) and the +/// verifier take windows up to `spec + 2` (`kVerifyMaxT` 8), coupled draft sampling per env. +#[derive(Clone,Copy,Debug,PartialEq)] +pub(crate) struct OriginalServeSettings { + pub(crate) max_t:usize,pub(crate) mtp_max_t:usize,pub(crate) max_context:i64,pub(crate) vocabulary:u32, + pub(crate) suffix_min_match:usize,pub(crate) coupled:bool, + /// `LELEKA_SPEC_ADAPTIVE`: the adaptive window policy (`original_spec_adaptive.rs`). + pub(crate) adaptive:Option, + /// Re-run a verify window with non-finite output from its round's checkpoint (`NanGuard`); off in mode17 itself. + pub(crate) nan_guard:NanGuard, + /// An arm's own `spec_min_p` for the requests it serves (`fixed4@0`), overriding the harness default; `None` = the harness's. + pub(crate) request_min_p:Option, +} +impl OriginalServeSettings { + pub(crate) fn mode17(max_context:i64,vocabulary:u32,coupled:bool)->Self { + const SPEC:usize=4;const SUFFIX:usize=3; + Self{max_t:(SPEC+2).min(MAX_T),mtp_max_t:SPEC,max_context,vocabulary,suffix_min_match:SUFFIX,coupled,adaptive:None,nan_guard:NanGuard::off(),request_min_p:None} + } + /// Mode17 with the operator's overrides from the environment (read once per stack): + /// `LELEKA_SPEC` (the Original's `--spec`: MTP window, verify windows up to `spec + 2`, at most 8), + /// `LELEKA_SPEC_MTP_MAX_T` (`--mtp-max-t`, 0 = spec), `LELEKA_SPEC_SUFFIX` (`--suffix-draft`, 0 = off), and + /// `LELEKA_SPEC_ADAPTIVE=on` (adaptive window; widest window `LELEKA_SPEC_ADAPTIVE_MAX_T`, default 8 rows, MTP chain up + /// to `max_t - 1` drafts). Unset = mode17 exactly. + pub(crate) fn from_environment(max_context:i64,vocabulary:u32,coupled:bool)->Self { + let num=|name:&str|std::env::var(name).ok().and_then(|v|v.trim().parse::().ok()); + let mut s=Self::mode17(max_context,vocabulary,coupled); + s.nan_guard=NanGuard::from_environment(); + if let Some(spec)=num("LELEKA_SPEC") { + let spec=spec.clamp(2,MAX_T);s.max_t=(spec+2).min(MAX_T);s.mtp_max_t=spec; + } + if let Some(m)=num("LELEKA_SPEC_MTP_MAX_T") {s.mtp_max_t=if m==0 {s.max_t.min(s.mtp_max_t)} else {m.min(s.max_t)};} + if let Some(n)=num("LELEKA_SPEC_SUFFIX") {s.suffix_min_match=n;} + let explicit=std::env::var("LELEKA_SPEC_ADAPTIVE").ok(); + if Self::adaptive_wanted(explicit.as_deref(),std::env::var_os("LELEKA_SPEC").is_some()) { + let max_t=num("LELEKA_SPEC_ADAPTIVE_MAX_T").unwrap_or(MAX_T).clamp(2,MAX_T); + s.max_t=max_t;s.mtp_max_t=max_t; + s.adaptive=Some(AdaptiveConfig::new(max_t,max_t-1).from_environment()); + } + s + } + /// Adaptive window or the fixed mode17 window: an explicit `LELEKA_SPEC_ADAPTIVE` (`on`/`1`/`yes` or `off`/`0`/`no`) decides; otherwise + /// a fixed `LELEKA_SPEC=N` means the fixed window and nothing set means [`ADAPTIVE_DEFAULT`]. + pub(crate) fn adaptive_wanted(explicit:Option<&str>,fixed_spec_set:bool)->bool { + match explicit { + Some("on"|"1"|"yes")=>true, + Some("off"|"0"|"no")=>false, + _=>!fixed_spec_set&&ADAPTIVE_DEFAULT, + } + } + /// `STRATA_SPEC_COUPLED`: set, non-empty and not "0" (read once by the operator, not per request). + pub(crate) fn coupled_from_environment()->bool { + std::env::var("STRATA_SPEC_COUPLED").is_ok_and(|v|!v.is_empty()&&v!="0") + } + /// `LELEKA_SPEC_ARMS=fixed3,fixed4,fixed6,adaptive`: named window policies one process can switch between per request (an + /// A/B inside one model load, same tier and caches). `fixedN` is the Original's `--spec N` (suffix 3), `adaptive` the + /// adaptive window; the verifier is built for the widest arm. Empty when unset. + pub(crate) fn arms_from_environment(max_context:i64,vocabulary:u32,coupled:bool)->Vec<(String,Self)> { + let Ok(list)=std::env::var("LELEKA_SPEC_ARMS") else {return Vec::new()}; + let base=Self::from_environment(max_context,vocabulary,coupled); + let mut arms=Vec::new(); + for entry in list.split(',').map(str::trim).filter(|l|!l.is_empty()) { + // `name@MIN_P` pins the arm's request floor; `+flag` suffixes (`adaptive@0+tail7`) are the replay harness's, the label keeps them + let main=entry.split_once('+').map_or(entry,|(m,_)|m); + let (label,min_p)=match main.split_once('@') { + Some((l,p))=>(l,p.parse::().ok()), + None=>(main,None), + }; + let mut s=base;s.adaptive=None;s.request_min_p=min_p; + if let Some(n)=label.strip_prefix("fixed").and_then(|n|n.parse::().ok()) { + let n=n.clamp(2,MAX_T);s.max_t=(n+2).min(MAX_T);s.mtp_max_t=n;s.suffix_min_match=3; + } else if label=="adaptive" { + s.max_t=MAX_T;s.mtp_max_t=MAX_T;s.suffix_min_match=3; + s.adaptive=Some(AdaptiveConfig::new(MAX_T,MAX_T-1).from_environment()); + } else {continue;} + arms.push((entry.to_owned(),s)); + } + arms + } + /// The same policy for a verifier that records windows only up to `cap` rows (a window graph did not fit in device memory): the + /// widest window, the MTP chain and the adaptive policy's bounds are cut to it, everything else is unchanged. + pub(crate) fn with_window_cap(mut self,cap:usize)->Self { + let cap=cap.clamp(1,MAX_T); + self.max_t=self.max_t.min(cap);self.mtp_max_t=self.mtp_max_t.min(self.max_t); + if let Some(a)=self.adaptive.as_mut() {a.max_t=a.max_t.min(self.max_t);a.max_drafts=a.max_drafts.min(a.max_t.saturating_sub(1));} + self + } + /// Draft cap the engine shares with the controller's `DraftPreparation`. + pub(crate) fn max_drafts(&self)->usize {self.mtp_max_t.min(self.max_t).saturating_sub(1)} + /// The width the MTP drafter is LOADED with: generate.cpp rewrites `o.spec` to the verify width (`min(spec+2, 8)`, line 1537) + /// before `mtp.load(..., o.spec, ...)` (line 2610), so the drafter accepts every window the verifier runs (suffix drafts go up to + /// `max_t`) while its own chain stays capped by `max_drafts()` (`set_max_drafts(S_mtp - 1)`). Loading it at `mtp_max_t` made every + /// window wider than that fail `draft` (`T > max_t_`) with InvalidQwenShape. + pub(crate) fn mtp_load_t(&self)->usize {self.max_t} + /// The one production call of `OriginalSpecController::new`. + pub(crate) fn controller(&self)->Result { + OriginalSpecController::new(SpecConfig::new(self.max_t,self.mtp_max_t,self.max_context,self.vocabulary, + self.suffix_min_match,self.coupled)?.with_adaptive(self.adaptive).with_nan_guard(self.nan_guard)) + } +} + +#[derive(Clone,Copy,Debug,Eq,PartialEq)] +pub(crate) enum ServeStop {Eos,Length,Context} +#[derive(Clone,Copy,Debug,Eq,PartialEq)] +pub(crate) struct ServeOutcome {pub(crate) stop:ServeStop,pub(crate) produced:usize,pub(crate) rounds:usize} + +/// generate.cpp's serve loop for one request: begin, then verify/commit, emit the committed +/// tokens, finish the round (draft + adaptive join + drain), repeat; `finish_request` waits the +/// last commit before anything reads the session. `emit` runs only AFTER the commit succeeded. +pub(crate) fn serve_request(controller:&mut OriginalSpecController,engine:&mut E, + prompt:&[i32],max_new:usize,min_p:f32,eos:&[i32],mut emit:impl FnMut(&[i32])->Result<()>, + mut cancel:impl FnMut()->bool,mut clock_ms:impl FnMut()->f64)->std::result::Result { + let begin_span=super::original_serve_profile::span("ctrl.begin_request"); + controller.begin_request(prompt,max_new,min_p,eos)?; + drop(begin_span); + let (mut produced,mut rounds,mut stop)=(0usize,0usize,None); + let looped=(||->std::result::Result<(),SpecError> { + while !controller.finished() { + let started=clock_ms(); + let vc_span=super::original_serve_profile::span("round.verify_commit"); + let Some(round)=controller.verify_commit(engine,&mut cancel)? else {break}; + drop(vc_span); + let emit_span=super::original_serve_profile::span("round.emit"); + let emitted=emit(round.tokens()); + drop(emit_span); + produced+=round.tokens().len();rounds+=1; + if round.stopped_on_eos() {stop=Some(ServeStop::Eos);} + // A failed emit still finishes the round (drain + join) before reporting. + let fr_span=super::original_serve_profile::span("round.finish"); + let finished=controller.finish_round(engine,round,||clock_ms()-started,&mut cancel); + drop(fr_span); + emitted?;finished?; + } + Ok(()) + })(); + if let Err(e)=looped { + // Close the request best-effort (waits the last commit) so the controller is reusable + // unless a restore/finish failure already marked it failed. + let _=controller.finish_request(engine);return Err(e); + } + controller.finish_request(engine)?; + let stop=stop.unwrap_or(if produced>=max_new {ServeStop::Length} else {ServeStop::Context}); + Ok(ServeOutcome{stop,produced,rounds}) +} + + +/// Bring-up diagnostic: logs every port call and its outcome. Remove together with the DBG lines. +pub(crate) struct TracePort

(pub P); +fn tr_port(name: &str, f: impl FnOnce() -> Result) -> Result { + let started = std::time::Instant::now(); + let r = f(); + if crate::bringup_trace_enabled() { + let state = match &r { Ok(_) => "ok".to_string(), Err(e) => format!("ERR {e:?}") }; + eprintln!("DBG[{:.0}s] port.{name} {:.3}ms -> {state}", crate::qwen_forward::original_serve_stack::dbg_el(), + started.elapsed().as_secs_f64() * 1e3); + } + r +} +impl OriginalServePort for TracePort

{ + type Window = P::Window; + type Seed = P::Seed; + type TargetCheckpoint = P::TargetCheckpoint; + type DraftCheckpoint = P::DraftCheckpoint; + type Adaptive = P::Adaptive; + fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()> { tr_port("validate_current", || self.0.validate_current(consumed, input, position)) } + fn checkpoint_target(&self) -> Result { tr_port("checkpoint_target", || self.0.checkpoint_target()) } + fn checkpoint_draft(&self) -> Result { tr_port("checkpoint_draft", || self.0.checkpoint_draft()) } + fn restore_target(&mut self, c: &Self::TargetCheckpoint) -> Result<()> { tr_port("restore_target", || self.0.restore_target(c)) } + fn restore_draft(&mut self, c: &Self::DraftCheckpoint) -> Result<()> { tr_port("restore_draft", || self.0.restore_draft(c)) } + fn apply_pending(&mut self) -> Result<()> { tr_port("apply_pending", || self.0.apply_pending()) } + fn run_window(&mut self, position: i64, inputs: &[i32], consumed: &[i32]) -> Result { + crate::bringup_trace!("DBG port.run_window position={position} inputs={inputs:?} consumed_len={}", consumed.len()); + tr_port("run_window", || self.0.run_window(position, inputs, consumed)) + } + fn validate_window(&self, window: &Self::Window, position: i64, inputs: &[i32]) -> Result<()> { tr_port("validate_window", || self.0.validate_window(window, position, inputs)) } + fn window_outputs<'a>(&self, window: &'a Self::Window) -> &'a [i32] { self.0.window_outputs(window) } + fn commit_window(&mut self, window: &mut Self::Window, keep: usize) -> Result<()> { tr_port("commit_window", || self.0.commit_window(window, keep)) } + fn wait_commit(&mut self) -> Result<()> { tr_port("wait_commit", || self.0.wait_commit()) } + fn drain_window(&mut self, window: Self::Window) -> Result<()> { tr_port("drain_window", || self.0.drain_window(window)) } + fn discard_window(&mut self) -> Result<()> { tr_port("discard_window", || self.0.discard_window()) } + fn begin_adaptation(&mut self, next_round: u64) -> Result { tr_port("begin_adaptation", || self.0.begin_adaptation(next_round)) } + fn join_adaptation(&mut self, work: Self::Adaptive) -> Result<()> { tr_port("join_adaptation", || self.0.join_adaptation(work)) } + fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()> { tr_port("stage_draft_history", || self.0.stage_draft_history(consumed, next)) } + #[allow(clippy::too_many_arguments)] + fn draft_committed(&mut self, window: &Self::Window, position: i64, accepted_row: usize, outputs: &[i32], max_drafts: usize, min_p: f32, coupled: bool) -> Result { + tr_port("draft_committed", || self.0.draft_committed(window, position, accepted_row, outputs, max_drafts, min_p, coupled)) + } + fn drain_draft(&mut self) -> Result<()> { tr_port("drain_draft", || self.0.drain_draft()) } + #[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 { + tr_port("draft_first", || self.0.draft_first(seed, t, cell, token, max_drafts, min_p, coupled)) + } + fn drain_first(&mut self) -> Result<()> { tr_port("drain_first", || self.0.drain_first()) } +} + +#[cfg(test)] +mod tests { + use super::*; + use super::super::original_spec_controller::{NanGuard,OriginalSpecController,SpecConfig,SpecError}; + use super::super::original_spec_draft::DraftPreparation; + use std::cell::RefCell; + + const VOCAB:u32=1000; + fn model(x:i32)->i32 {(x*5+1)%997} + + #[derive(Default)] + struct World { + /// committed target tokens (the session prefix), including the current input. + committed:Vec,events:Vec,commit_waits:usize, + fail:Option<&'static str>,fail_restore:Option<&'static str>, + /// tokens the "MTP" drafts: chain of the model, shifted by `skew` to force rejections + skew:i32,sampler_cell:i64, + /// the highest cell (+1) a verify window row or a draft touched + max_end:i64, + } + struct Win {inputs:Vec,outputs:Vec,position:i64} + struct Fake {w:Rc>,pending_commit:Option,pending_position:i64} + impl Fake { + fn new(prompt:&[i32])->(Self,Rc>) { + let w=Rc::new(RefCell::new(World{committed:prompt.to_vec(),..Default::default()})); + (Self{w:Rc::clone(&w),pending_commit:None,pending_position:0},w) + } + fn log(&self,s:impl Into) {self.w.borrow_mut().events.push(s.into());} + fn fails(&self,what:&str)->bool {self.w.borrow().fail==Some(what)} + } + impl OriginalServePort for Fake { + type Window=Win;type Seed=i32;type TargetCheckpoint=(Vec,i64);type DraftCheckpoint=i64;type Adaptive=u64; + fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> { + let w=self.w.borrow(); + if w.committed.len() as i64!=position+1||&w.committed[..consumed.len()]!=consumed||w.committed[position as usize]!=input {return Err(Error::IdentityMismatch);} + Ok(()) + } + fn checkpoint_target(&self)->Result { + if self.pending_commit.is_some() {return Err(Error::CudaExecution);} + let w=self.w.borrow();Ok((w.committed.clone(),w.sampler_cell)) + } + fn checkpoint_draft(&self)->Result {self.log("ckpt-draft");Ok(self.w.borrow().committed.len() as i64)} + fn restore_target(&mut self,c:&Self::TargetCheckpoint)->Result<()> { + self.log("restore-target"); + if self.w.borrow().fail_restore==Some("target") {return Err(Error::CudaExecution);} + let mut w=self.w.borrow_mut();w.committed=c.0.clone();w.sampler_cell=c.1;Ok(()) + } + fn restore_draft(&mut self,_:&i64)->Result<()> { + self.log("restore-draft"); + if self.w.borrow().fail_restore==Some("draft") {return Err(Error::CudaExecution);}Ok(()) + } + fn apply_pending(&mut self)->Result<()> {self.log("apply-pending");Ok(())} + fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { + self.log(format!("run t={} consumed={}",inputs.len(),consumed.len())); + if self.fails("run") {return Err(Error::CudaExecution);} + // the window must see the committed branch (async commit already published) + let outputs:Vec=inputs.iter().map(|&x|model(x)).collect(); + self.w.borrow_mut().sampler_cell=position+inputs.len() as i64; + {let mut w=self.w.borrow_mut();w.max_end=w.max_end.max(position+inputs.len() as i64);} + Ok(Win{inputs:inputs.to_vec(),outputs,position}) + } + fn validate_window(&self,w:&Win,position:i64,inputs:&[i32])->Result<()> { + if self.fails("validate") {return Err(Error::NonFinite);} + if w.position!=position||w.inputs!=inputs {return Err(Error::IdentityMismatch);}Ok(()) + } + fn window_outputs<'a>(&self,w:&'a Win)->&'a[i32] {if self.fails("short") {&w.outputs[..1]} else {&w.outputs}} + fn commit_window(&mut self,w:&mut Win,keep:usize)->Result<()> { + self.log(format!("commit keep={keep}")); + if self.fails("commit") {return Err(Error::CudaExecution);} + self.pending_commit=Some(keep);self.pending_position=w.position; + // the published prefix is visible only after wait_commit + Ok(()) + } + fn wait_commit(&mut self)->Result<()> { + if self.pending_commit.take().is_some() { + self.log("wait-commit");self.w.borrow_mut().commit_waits+=1; + if self.fails("wait") {return Err(Error::CudaExecution);} + } + Ok(()) + } + fn drain_window(&mut self,_:Win)->Result<()> {self.log("drain-window");if self.fails("drain") {Err(Error::CudaExecution)} else {Ok(())}} + fn discard_window(&mut self)->Result<()> {self.log("discard-window");if self.fails("discard") {Err(Error::CudaExecution)} else {Ok(())}} + fn begin_adaptation(&mut self,r:u64)->Result {self.log(format!("begin-adapt {r}"));if self.fails("begin") {Err(Error::CudaExecution)} else {Ok(r)}} + fn join_adaptation(&mut self,r:u64)->Result<()> {self.log(format!("join-adapt {r}"));if self.fails("join") {Err(Error::CudaExecution)} else {Ok(())}} + fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()> {self.log(format!("history {} {next}",consumed.len()));Ok(())} + fn draft_committed(&mut self,w:&Win,position:i64,a:usize,outputs:&[i32],max_drafts:usize,min_p:f32,_coupled:bool)->Result { + self.log(format!("draft a={a}")); + if self.fails("draft") {return Err(Error::CudaExecution);} + let skew=self.w.borrow().skew; + let mut ids=vec![(model(outputs[a])+skew).rem_euclid(997)];let mut probs=vec![0.9f32]; + while ids.len()=min_p { + let last=*ids.last().unwrap();ids.push(model(last));probs.push(0.9); + } + let _=w; + {let mut wd=self.w.borrow_mut();wd.max_end=wd.max_end.max(position+a as i64+ids.len() as i64);} + Ok(DraftCompletion{ids,probabilities:probs,first_cell:position+a as i64,accepted_row:a}) + } + fn drain_draft(&mut self)->Result<()> {self.log("drain-draft");Ok(())} + fn draft_first(&mut self,_:&i32,_t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,_c:bool)->Result { + self.log("draft-first"); + let mut ids=vec![model(token)];let mut probs=vec![0.9f32]; + while ids.len()=min_p {let l=*ids.last().unwrap();ids.push(model(l));probs.push(0.9);} + Ok(DraftCompletion{ids,probabilities:probs,first_cell:cell,accepted_row:0}) + } + fn drain_first(&mut self)->Result<()> {self.log("drain-first");Ok(())} + } + + fn engine(prompt:&[i32],max_t:usize)->(OriginalServeEngine,Rc>) { + let (f,w)=Fake::new(prompt); + (OriginalServeEngine::new(f,VOCAB,max_t,max_t-1).unwrap(),w) + } + fn events(w:&Rc>)->Vec {w.borrow().events.clone()} + fn idx(e:&[String],needle:&str)->usize {e.iter().position(|s|s.starts_with(needle)).unwrap_or_else(||panic!("missing {needle} in {e:?}"))} + fn prompt() -> Vec {vec![11,model(11),model(model(11))]} + + /// Drive one window by hand the way the controller does (verify, commit). + fn verify_commit(e:&mut OriginalServeEngine,p:i64,inputs:&[i32],consumed:&[i32],keep:usize)->ServedWindow { + e.apply_pending().unwrap(); + let mut v=e.verify(p,inputs,consumed).unwrap(); + e.commit_verified(&mut v,keep).unwrap();v + } + + #[test] + fn constructor_validates_dimensions() { + let (f,_)=Fake::new(&prompt()); + assert!(OriginalServeEngine::new(f,0,4,3).is_err()); + let (f,_)=Fake::new(&prompt()); + assert!(OriginalServeEngine::new(f,VOCAB,0,0).is_err()); + let (f,_)=Fake::new(&prompt()); + assert!(OriginalServeEngine::new(f,VOCAB,4,4).is_err()); + let (f,_)=Fake::new(&prompt()); + assert!(OriginalServeEngine::new(f,VOCAB,4,3).is_ok()); + } + + #[test] + fn verify_returns_all_t_outputs_and_requires_a_drained_window() { + let p=prompt();let (mut e,w)=engine(&p,4); + let consumed=&p[..2];let input=p[2]; + let mut v=e.verify(2,&[input],consumed).unwrap(); + assert_eq!(e.outputs(&v),&[model(input)]); + e.validate_verified(&v,2,&[input]).unwrap(); + assert_eq!(e.validate_verified(&v,3,&[input]),Err(Error::IdentityMismatch)); + assert_eq!(e.validate_verified(&v,2,&[input+1]),Err(Error::IdentityMismatch)); + // a second window while one is live is refused before anything runs + let runs=events(&w).iter().filter(|s|s.starts_with("run")).count(); + assert_eq!(e.verify(2,&[input],consumed).err(),Some(Error::IdentityMismatch)); + assert_eq!(events(&w).iter().filter(|s|s.starts_with("run")).count(),runs); + e.commit_verified(&mut v,1).unwrap(); + assert_eq!(v.committed_rows(),Some(1)); + e.drain_verified(v).unwrap(); + e.wait_commit().unwrap(); + } + + #[test] + fn out_of_range_tokens_never_reach_the_port() { + let p=prompt();let (mut e,w)=engine(&p,4); + assert_eq!(e.verify(2,&[VOCAB as i32],&p[..2]).err(),Some(Error::InvalidToken)); + assert_eq!(e.verify(2,&[5],&[-1]).err(),Some(Error::InvalidToken)); + assert!(!events(&w).iter().any(|s|s.starts_with("run"))); + assert_eq!(e.verify(2,&[],&p[..2]).err(),Some(Error::IdentityMismatch)); + assert_eq!(e.verify(2,&[1,2,3,4,5],&p[..2]).err(),Some(Error::IdentityMismatch)); + } + + #[test] + fn a_short_or_invalid_window_is_drained_not_leaked() { + let p=prompt();let (mut e,w)=engine(&p,4); + w.borrow_mut().fail=Some("short"); + assert_eq!(e.verify(2,&[p[2],model(p[2])],&p[..2]).err(),Some(Error::IdentityMismatch)); + assert!(events(&w).iter().any(|s|s=="drain-window")); + w.borrow_mut().fail=Some("validate"); + assert_eq!(e.verify(2,&[p[2]],&p[..2]).err(),Some(Error::NonFinite)); + w.borrow_mut().fail=None; + // nothing left live: a clean window works again + let v=e.verify(2,&[p[2]],&p[..2]).unwrap();e.drain_verified(v).unwrap(); + assert!(!e.is_poisoned()); + } + + #[test] + fn commit_checks_the_accepted_prefix_and_only_once() { + let p=prompt();let (mut e,_)=engine(&p,4); + let a=p[2];let good=model(a); + let mut v=e.verify(2,&[a,good,good+1],&p[..2]).unwrap(); + // row 2's input (good+1) != output 1 (model(good)) so keep=3 is not a legal prefix + assert_eq!(e.commit_verified(&mut v,3),Err(Error::IdentityMismatch)); + assert_eq!(e.commit_verified(&mut v,0),Err(Error::IdentityMismatch)); + assert_eq!(e.commit_verified(&mut v,4),Err(Error::IdentityMismatch)); + e.commit_verified(&mut v,2).unwrap(); + assert_eq!(e.commit_verified(&mut v,2),Err(Error::IdentityMismatch)); + e.drain_verified(v).unwrap();e.wait_commit().unwrap(); + } + + #[test] + fn commit_is_asynchronous_and_the_window_drain_waits_for_its_event() { + let p=prompt();let (mut e,w)=engine(&p,4); + let v=verify_commit(&mut e,2,&[p[2]],&p[..2],1); + assert!(e.commit_pending()); + // checkpoints and validation refuse to read the session mid-commit + assert_eq!(e.checkpoint_target().err(),Some(Error::IdentityMismatch)); + assert_eq!(e.checkpoint_draft().err(),Some(Error::IdentityMismatch)); + assert_eq!(e.validate_current(&p[..2],p[2],2),Err(Error::IdentityMismatch)); + assert_eq!(w.borrow().commit_waits,0); + // the draft (event-dependent) runs before the drain; the drain waits + publishes + e.drain_verified(v).unwrap(); + assert_eq!(w.borrow().commit_waits,1); + assert!(!e.commit_pending()); + let ev=events(&w); + assert!(idx(&ev,"wait-commit")(Vec,Vec) { + let p=prompt_long(); + let (f,w)=Fake::new(&p[..p.len()-1]); + // Fake's committed prefix tracks tokens through the current input + w.borrow_mut().committed=p.clone();w.borrow_mut().skew=skew; + let mut e=OriginalServeEngine::new(f,VOCAB,max_t,max_t-1).unwrap(); + let mut c=OriginalSpecController::new(SpecConfig::new(max_t,0,4096,VOCAB,0,false).unwrap()).unwrap(); + c.begin_request(&p,max_new,0.0,&[]).unwrap(); + e.set_min_p(0.0).unwrap(); + let mut out=Vec::new(); + while !c.finished() { + // the fake's committed list must follow what the controller commits + let round=match c.verify_commit(&mut e,||false) {Ok(Some(r))=>r,Ok(None)=>break,Err(err)=>panic!("{err:?}")}; + out.extend_from_slice(round.tokens()); + w.borrow_mut().committed.extend_from_slice(round.tokens()); + c.finish_round(&mut e,round,||1.0,||false).unwrap(); + } + c.finish_request(&mut e).unwrap(); + let ev=events(&w);(out,ev) + } + fn prompt_long()->Vec {let mut v=vec![11];for i in 1..40 {v.push(model(v[i-1]));}v} + + #[test] + fn controller_over_the_engine_emits_the_greedy_continuation() { + let (out,ev)=run_request(0,4,20); + let mut expect=Vec::new();let mut x=*prompt_long().last().unwrap(); + for _ in 0..out.len() {x=model(x);expect.push(x);} + assert_eq!(out,expect); + assert!(out.len()>=20); + // every verify was followed by a commit, a drain, and (while unfinished) a draft + assert!(ev.iter().filter(|s|s.starts_with("commit keep=")).count()>=4); + assert_eq!(ev.iter().filter(|s|s.starts_with("run ")).count(),ev.iter().filter(|s|s.starts_with("commit keep=")).count()); + assert_eq!(ev.iter().filter(|s|*s=="drain-window").count(),ev.iter().filter(|s|s.starts_with("run ")).count()); + } + + #[test] + fn controller_over_the_engine_survives_rejected_drafts() { + let (out,ev)=run_request(3,4,12); + let mut expect=Vec::new();let mut x=*prompt_long().last().unwrap(); + for _ in 0..out.len() {x=model(x);expect.push(x);} + assert_eq!(out,expect,"rejected drafts must never change the greedy text"); + assert!(ev.iter().any(|s|s=="commit keep=1")); + } + + #[test] + fn controller_both_restores_run_when_the_verifier_fails() { + let p=prompt_long(); + let (f,w)=Fake::new(&p); + let mut e=OriginalServeEngine::new(f,VOCAB,4,3).unwrap(); + let mut c=OriginalSpecController::new(SpecConfig::new(4,0,4096,VOCAB,0,false).unwrap()).unwrap(); + c.begin_request(&p,8,0.0,&[]).unwrap(); + w.borrow_mut().fail=Some("run"); + let err=c.verify_commit(&mut e,||false).err().unwrap(); + assert_eq!(err,SpecError::Forward(Error::CudaExecution)); + let ev=events(&w); + assert!(ev.iter().any(|s|s=="restore-target")&&ev.iter().any(|s|s=="restore-draft")); + assert!(!c.is_failed()); + } + + #[test] + fn preparation_drives_the_engine_through_after_verified() { + let p=prompt();let (mut e,_)=engine(&p,4); + let a=p[2]; + let mut v=e.verify(2,&[a],&p[..2]).unwrap(); + let outs=e.outputs(&v).to_vec();e.commit_verified(&mut v,1).unwrap(); + let prep=DraftPreparation::new(4,3,VOCAB).unwrap(); + let batch=prep.after_verified(&mut e,&v,2,0,&outs,&p[..3],&mut crate::qwen_forward::token_memo::PrefixMemo::new(),0.0,false).unwrap(); + assert_eq!(batch.produced(),3); + assert_eq!(batch.ids()[0],model(outs[0])); + e.drain_verified(v).unwrap(); + } + + #[test] + fn the_adaptive_window_is_selected_by_the_explicit_switch_then_by_a_fixed_spec_then_by_the_default() { + let w=OriginalServeSettings::adaptive_wanted; + assert!(w(Some("on"),false)&&w(Some("1"),true)&&w(Some("yes"),true)); + assert!(!w(Some("off"),false)&&!w(Some("0"),false)&&!w(Some("no"),false)); + assert_eq!(w(None,false),ADAPTIVE_DEFAULT); + assert!(!w(None,true),"a fixed LELEKA_SPEC keeps the fixed window"); + } + + #[test] + fn a_window_cap_narrows_every_bound_and_leaves_the_rest() { + let mut wide=OriginalServeSettings::mode17(4096,VOCAB,true); + wide.max_t=8;wide.mtp_max_t=8; + wide.adaptive=Some(AdaptiveConfig::new(8,7)); + for cap in 2..=8 { + let s=wide.with_window_cap(cap); + assert_eq!((s.max_t,s.mtp_max_t),(cap,cap),"cap {cap}"); + assert_eq!(s.max_drafts(),cap-1); + let a=s.adaptive.unwrap(); + assert_eq!((a.max_t,a.max_drafts),(cap,cap-1)); + // unchanged: everything that is not a width + assert_eq!((s.max_context,s.vocabulary,s.suffix_min_match,s.coupled),(wide.max_context,wide.vocabulary,wide.suffix_min_match,wide.coupled)); + assert_eq!(s.nan_guard,wide.nan_guard); + // the controller and the engine accept it + let c=s.controller().unwrap(); + assert!(c.finished()&&!c.is_failed()); + let (f,_)=Fake::new(&prompt_long()); + assert!(OriginalServeEngine::new(f,VOCAB,s.max_t,s.max_drafts()).is_ok(),"cap {cap}"); + } + // a cap above the settings changes nothing; a fixed window narrower than the cap keeps its own width + assert_eq!(wide.with_window_cap(8),wide); + let fixed=OriginalServeSettings::mode17(4096,VOCAB,false); + assert_eq!(fixed.with_window_cap(8),fixed); + let narrow=fixed.with_window_cap(3); + assert_eq!((narrow.max_t,narrow.mtp_max_t,narrow.max_drafts()),(3,3,2)); + assert!(narrow.adaptive.is_none()); + } + + #[test] + fn mode17_settings_follow_generate_defaults() { + let s=OriginalServeSettings::mode17(4096,VOCAB,false); + assert_eq!((s.max_t,s.mtp_max_t,s.suffix_min_match),(6,4,3)); + assert_eq!(s.max_drafts(),3); + // the drafter is loaded at the verify width (6), not at its own window width (4): suffix windows are 6 rows wide + assert_eq!(s.mtp_load_t(),6); + assert!(s.mtp_load_t()>=s.max_t&&s.max_drafts()bool,fail_emit_after:Option) + ->(std::result::Result,Vec,OriginalSpecController,OriginalServeEngine) { + let (r,out,c,e,_)=serve_in(p,max_new,eos,cancel,fail_emit_after,4096);(r,out,c,e) + } + fn serve_in(p:&[i32],max_new:usize,eos:&[i32],mut cancel:impl FnMut()->bool,fail_emit_after:Option,max_context:i64) + ->(std::result::Result,Vec,OriginalSpecController,OriginalServeEngine,Rc>) { + let (f,w)=Fake::new(p); + let s=OriginalServeSettings{max_t:4,mtp_max_t:0,max_context,vocabulary:VOCAB,suffix_min_match:0,coupled:false,adaptive:None,nan_guard:NanGuard::off(),request_min_p:None}; + let mut e=OriginalServeEngine::new(f,VOCAB,s.max_t,s.max_t-1).unwrap(); + let mut c=s.controller().unwrap(); + let mut out=Vec::new(); + let wc=Rc::clone(&w); + let r=serve_request(&mut c,&mut e,p,max_new,0.0,eos,|t|{ + if fail_emit_after.is_some_and(|n|out.len()>=n) {return Err(Error::InputRead);} + out.extend_from_slice(t);wc.borrow_mut().committed.extend_from_slice(t);Ok(()) + },&mut cancel,||0.0); + (r,out,c,e,w) + } + + /// Upstream 41cf05a0 `e85567b6`: through the real engine (plan, cap and cross-check of the chain), a request that runs to the + /// context's end never touches a cell past it, whatever the distance of the last windows to it. + #[test] + fn serve_request_to_the_context_end_stays_inside_the_cells_and_ends_as_context() { + let p=prompt_long(); + for k in 1..=9i64 { + let max_context=p.len() as i64-1+k; + let (r,out,c,e,w)=serve_in(&p,1000,&[],||false,None,max_context); + let r=r.unwrap_or_else(|err|panic!("k {k}: {err:?}")); + assert_eq!(r.stop,ServeStop::Context,"k {k}"); + assert_eq!(out.len() as i64,k,"k {k}: one token per row that fits"); + let mut x=*p.last().unwrap();for &t in &out {x=model(x);assert_eq!(t,x);} + assert!(w.borrow().max_end<=max_context,"k {k}: touched cell {} of {max_context}",w.borrow().max_end); + assert!(c.finished()&&!c.is_failed()&&!e.is_poisoned()&&!e.commit_pending(),"k {k}"); + } + } + + #[test] + fn serve_request_emits_the_greedy_text_and_reports_the_stop() { + let p=prompt_long(); + let (r,out,mut c,_e)=serve(&p,10,&[],||false,None); + let r=r.unwrap(); + assert_eq!(r.stop,ServeStop::Length); + assert!(r.produced>=10&&r.rounds>=1); + assert_eq!(out.len(),r.produced); + let mut x=*p.last().unwrap();for &t in &out {x=model(x);assert_eq!(t,x);} + // the controller is reusable for the next request + assert!(c.begin_request(&p,1,0.0,&[]).is_ok()); + } + + /// Upstream 41cf05a0 `aece46db`: a 1-token prompt (position 0 is the first verify input) speculates like any other. + #[test] + fn serve_request_with_a_one_token_prompt_speculates() { + let p=vec![11]; + let (r,out,_c,e)=serve(&p,30,&[],||false,None); + let r=r.unwrap(); + assert_eq!((r.stop,r.produced),(ServeStop::Length,out.len())); + assert!(out.len()>=30); + let mut x=11;for &t in &out {x=model(x);assert_eq!(t,x);} + assert!(r.rounds3},None); + assert_eq!(r.err(),Some(SpecError::Cancelled)); + assert!(c.finished(),"a cancelled request is closed"); + assert!(!e.commit_pending()); + } + + #[test] + fn serve_request_a_failed_emit_still_finishes_the_round_and_closes_the_request() { + let p=prompt_long(); + let (r,out,c,e)=serve(&p,50,&[],||false,Some(1)); + assert_eq!(r.err(),Some(SpecError::Forward(Error::InputRead))); + assert!(!out.is_empty()); + assert!(c.finished()&&!e.commit_pending()); + } +} 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 7014bf6e..9ab865bf 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs @@ -1,1590 +1,1590 @@ -//! 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, -} -/// VRAM the per-request verifier (bank, canonical GDN image, window graphs, commit graph) takes at the start of a decode phase, -/// after the expert cache: 1,077 MiB free before it, 563 after (5090, `DBG vram` lines of `runs/speedtrain-ab`). -pub(crate) const VERIFIER_ASSEMBLY_MIB: usize = 514; -/// The lowest free VRAM vanilla Strata 0.2.6 runs with at 256k (315 MiB after its window captures, `strata verify: capturing ...`): -/// the floor the reserve must keep for ours too, measured with the same context and graph pools. -pub(crate) const VANILLA_FREE_FLOOR_MIB: usize = 315; -impl ExpertTierConfig { - /// Free VRAM the reserves leave at the start of a decode phase, worst case (the cache's quota rounding only adds to it): the - /// reserves less the verifier assembly. Negative when the verifier cannot fit. - pub(crate) fn decode_headroom_mib(&self) -> isize { - (self.reserve_mib + self.decode_reserve_mib) as isize - VERIFIER_ASSEMBLY_MIB as isize - } - 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. 5090, 5 x 245k session (speedtrain-ab): with 300 the card - // never had less than 563 MiB free (vanilla runs down to 315), so 130 would be safe on the card (E: +87 slots), - // but the first slots-footprint A/B showed the Context BUDGET is a second ceiling the planner now respects - // (`usable_room`); 130 stays an opt-in (`LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130`) until its own arm measures it. - 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); - let decay = adapt_decay(std::env::var("LELEKA_ADAPT_DECAY").ok().as_deref()); - if let Some(line) = decay.1 { - eprintln!("leleka-serve {line}"); - } - (var("LELEKA_ADAPT_MIN_COUNT", 2.0), var("LELEKA_ADAPT_MARGIN", 1.5), decay.0) - }) -} - -/// Default of `LELEKA_ADAPT_DECAY` (generate.cpp's constant). -const ADAPT_DECAY_DEFAULT: f32 = 0.7; - -/// `LELEKA_ADAPT_DECAY` must lie in 0..=1 (upstream 4a7e373d): above 1 the usage counts grow without end (inf after a few hundred -/// adaptations) and the swap gains turn NaN, which breaks the swap sort; below 0 the counts flip sign. Anything else (out of range, -/// not a finite number) falls back to the default, with the line to log. Unset gives the default silently. -fn adapt_decay(raw: Option<&str>) -> (f32, Option) { - let Some(text) = raw else { return (ADAPT_DECAY_DEFAULT, None) }; - match text.trim().parse::() { - Ok(v) if v.is_finite() && (0.0..=1.0).contains(&v) => (v, None), - _ => ( - ADAPT_DECAY_DEFAULT, - Some(format!("LELEKA_ADAPT_DECAY={text:?} is outside 0..1; using {ADAPT_DECAY_DEFAULT}")), - ), - } -} - -/// 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, - }; - if config.slots < 0 && config.decode_headroom_mib() < VANILLA_FREE_FLOOR_MIB as isize { - eprintln!( - "leleka-serve: WARNING: the VRAM reserves ({} + {} MiB) leave {} MiB free at decode after the {} MiB verifier assembly, below the {} MiB vanilla Strata runs with; the first request may not fit", - config.reserve_mib, config.decode_reserve_mib, config.decode_headroom_mib(), VERIFIER_ASSEMBLY_MIB, VANILLA_FREE_FLOOR_MIB - ); - } - 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 { - use super::*; - - #[test] - fn adapt_decay_outside_zero_to_one_falls_back_to_the_default_with_a_line() { - // unset: the default, no line - assert_eq!(adapt_decay(None), (0.7, None)); - // inside 0..=1 (both ends included): taken as given - for (text, want) in [("0", 0.0), ("0.25", 0.25), (" 0.9 ", 0.9), ("1", 1.0), ("1.0", 1.0)] { - assert_eq!(adapt_decay(Some(text)), (want, None), "{text}"); - } - // above 1 (counts grow without end), below 0 (counts flip sign), not finite, not a number: default plus a line naming the knob - for text in ["1.0001", "2", "1e30", "-0.1", "-1", "inf", "-inf", "NaN", "", "fast"] { - let (value, line) = adapt_decay(Some(text)); - assert_eq!(value, 0.7, "{text}"); - assert!(line.is_some_and(|l| l.contains("LELEKA_ADAPT_DECAY")), "{text}"); - } - // the decayed usage of a value in range stays finite however many adaptations ran; one above 1 would not - let mut kept = 8.0_f32; - let mut grown = 8.0_f32; - for _ in 0..1000 { - kept *= adapt_decay(Some("0.9")).0; - grown *= 1.5; - } - assert!(kept.is_finite() && kept < 8.0); - assert!(grown.is_infinite()); - } - - #[test] - fn the_default_reserves_keep_more_free_vram_at_decode_than_vanilla_runs_with() { - let config = ExpertTierConfig::off(); - // 700 + 300 less the 514 MiB verifier assembly - assert_eq!(config.decode_headroom_mib(), 486); - assert!(config.decode_headroom_mib() >= VANILLA_FREE_FLOOR_MIB as isize); - // the opt-in 130 MiB is the vanilla floor to the MiB (700 + 130 - 514 = 316) - let tight = ExpertTierConfig { decode_reserve_mib: 130, ..ExpertTierConfig::off() }; - assert_eq!(tight.decode_headroom_mib(), 316); - assert!(tight.decode_headroom_mib() >= VANILLA_FREE_FLOOR_MIB as isize); - } - - #[test] - fn a_reserve_below_the_verifier_assembly_reports_a_negative_headroom() { - let config = ExpertTierConfig { reserve_mib: 100, decode_reserve_mib: 100, ..ExpertTierConfig::off() }; - assert_eq!(config.decode_headroom_mib(), 200 - VERIFIER_ASSEMBLY_MIB as isize); - assert!(config.decode_headroom_mib() < 0); - } - - #[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, +} +/// VRAM the per-request verifier (bank, canonical GDN image, window graphs, commit graph) takes at the start of a decode phase, +/// after the expert cache: 1,077 MiB free before it, 563 after (5090, `DBG vram` lines of `runs/speedtrain-ab`). +pub(crate) const VERIFIER_ASSEMBLY_MIB: usize = 514; +/// The lowest free VRAM vanilla Strata 0.2.6 runs with at 256k (315 MiB after its window captures, `strata verify: capturing ...`): +/// the floor the reserve must keep for ours too, measured with the same context and graph pools. +pub(crate) const VANILLA_FREE_FLOOR_MIB: usize = 315; +impl ExpertTierConfig { + /// Free VRAM the reserves leave at the start of a decode phase, worst case (the cache's quota rounding only adds to it): the + /// reserves less the verifier assembly. Negative when the verifier cannot fit. + pub(crate) fn decode_headroom_mib(&self) -> isize { + (self.reserve_mib + self.decode_reserve_mib) as isize - VERIFIER_ASSEMBLY_MIB as isize + } + 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. 5090, 5 x 245k session (speedtrain-ab): with 300 the card + // never had less than 563 MiB free (vanilla runs down to 315), so 130 would be safe on the card (E: +87 slots), + // but the first slots-footprint A/B showed the Context BUDGET is a second ceiling the planner now respects + // (`usable_room`); 130 stays an opt-in (`LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130`) until its own arm measures it. + 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); + let decay = adapt_decay(std::env::var("LELEKA_ADAPT_DECAY").ok().as_deref()); + if let Some(line) = decay.1 { + eprintln!("leleka-serve {line}"); + } + (var("LELEKA_ADAPT_MIN_COUNT", 2.0), var("LELEKA_ADAPT_MARGIN", 1.5), decay.0) + }) +} + +/// Default of `LELEKA_ADAPT_DECAY` (generate.cpp's constant). +const ADAPT_DECAY_DEFAULT: f32 = 0.7; + +/// `LELEKA_ADAPT_DECAY` must lie in 0..=1 (upstream 4a7e373d): above 1 the usage counts grow without end (inf after a few hundred +/// adaptations) and the swap gains turn NaN, which breaks the swap sort; below 0 the counts flip sign. Anything else (out of range, +/// not a finite number) falls back to the default, with the line to log. Unset gives the default silently. +fn adapt_decay(raw: Option<&str>) -> (f32, Option) { + let Some(text) = raw else { return (ADAPT_DECAY_DEFAULT, None) }; + match text.trim().parse::() { + Ok(v) if v.is_finite() && (0.0..=1.0).contains(&v) => (v, None), + _ => ( + ADAPT_DECAY_DEFAULT, + Some(format!("LELEKA_ADAPT_DECAY={text:?} is outside 0..1; using {ADAPT_DECAY_DEFAULT}")), + ), + } +} + +/// 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, + }; + if config.slots < 0 && config.decode_headroom_mib() < VANILLA_FREE_FLOOR_MIB as isize { + eprintln!( + "leleka-serve: WARNING: the VRAM reserves ({} + {} MiB) leave {} MiB free at decode after the {} MiB verifier assembly, below the {} MiB vanilla Strata runs with; the first request may not fit", + config.reserve_mib, config.decode_reserve_mib, config.decode_headroom_mib(), VERIFIER_ASSEMBLY_MIB, VANILLA_FREE_FLOOR_MIB + ); + } + 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 { + use super::*; + + #[test] + fn adapt_decay_outside_zero_to_one_falls_back_to_the_default_with_a_line() { + // unset: the default, no line + assert_eq!(adapt_decay(None), (0.7, None)); + // inside 0..=1 (both ends included): taken as given + for (text, want) in [("0", 0.0), ("0.25", 0.25), (" 0.9 ", 0.9), ("1", 1.0), ("1.0", 1.0)] { + assert_eq!(adapt_decay(Some(text)), (want, None), "{text}"); + } + // above 1 (counts grow without end), below 0 (counts flip sign), not finite, not a number: default plus a line naming the knob + for text in ["1.0001", "2", "1e30", "-0.1", "-1", "inf", "-inf", "NaN", "", "fast"] { + let (value, line) = adapt_decay(Some(text)); + assert_eq!(value, 0.7, "{text}"); + assert!(line.is_some_and(|l| l.contains("LELEKA_ADAPT_DECAY")), "{text}"); + } + // the decayed usage of a value in range stays finite however many adaptations ran; one above 1 would not + let mut kept = 8.0_f32; + let mut grown = 8.0_f32; + for _ in 0..1000 { + kept *= adapt_decay(Some("0.9")).0; + grown *= 1.5; + } + assert!(kept.is_finite() && kept < 8.0); + assert!(grown.is_infinite()); + } + + #[test] + fn the_default_reserves_keep_more_free_vram_at_decode_than_vanilla_runs_with() { + let config = ExpertTierConfig::off(); + // 700 + 300 less the 514 MiB verifier assembly + assert_eq!(config.decode_headroom_mib(), 486); + assert!(config.decode_headroom_mib() >= VANILLA_FREE_FLOOR_MIB as isize); + // the opt-in 130 MiB is the vanilla floor to the MiB (700 + 130 - 514 = 316) + let tight = ExpertTierConfig { decode_reserve_mib: 130, ..ExpertTierConfig::off() }; + assert_eq!(tight.decode_headroom_mib(), 316); + assert!(tight.decode_headroom_mib() >= VANILLA_FREE_FLOOR_MIB as isize); + } + + #[test] + fn a_reserve_below_the_verifier_assembly_reports_a_negative_headroom() { + let config = ExpertTierConfig { reserve_mib: 100, decode_reserve_mib: 100, ..ExpertTierConfig::off() }; + assert_eq!(config.decode_headroom_mib(), 200 - VERIFIER_ASSEMBLY_MIB as isize); + assert!(config.decode_headroom_mib() < 0); + } + + #[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_stack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs index af5c7fe7..5907fc94 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs @@ -1,2038 +1,2038 @@ -//! 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, assemble_with_window_fallback, disassemble, seed_ple_history, AssembleFailure, 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"); - // The native head + embedding come first: with LELEKA_PROMPT_EMBED_ALIAS=1 the prompt path's token table aliases the mapped host copy - // of the native embedding instead of a second copy in VRAM (the two are the same GGUF tensor). - let output = staged!("native head + embedding", context, OriginalNativeOutput::load(binding, context, NativeHeadDispatch::default(), true).map_err(at("OriginalNativeOutput::load"))?); - let embedding = staged!("embedding table", context, if OriginalPromptEmbedding::alias_enabled() { - OriginalPromptEmbedding::alias_native(binding, context, output.embedding(binding).map_err(at("OriginalNativeOutput::embedding"))?).map_err(at("OriginalPromptEmbedding::alias_native"))? - } else { - OriginalPromptEmbedding::load(binding, context).map_err(at("OriginalPromptEmbedding::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()); - // the prompt path's token table may alias the native embedding's mapped copy: it goes first - note(embedding.close()); - note(output.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, - parked, - 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(()) - }; - // A window or commit graph that does not fit in device memory costs the widest windows, not the request or the engine - // (upstream a8c1d4b7): the assembly is repeated with the windows that fit. The owners come back from each failure. - let mut owners_slot = Some(owners); - let (used_max_t, assembled) = assemble_with_window_fallback( - *verifier_max_t, - |max_t| { - let Some(owners) = owners_slot.take() else { - return Err((AssembleFailure { failure: Error::IdentityMismatch.into(), owners: None, window_cap: None }, None)); - }; - assemble( - binding, &weights, context, &*output, &base, owners, ple_history, rope, blobs, max_t, *max_cells, pcie_mode, - &mut queue_refill, - ) - .map_err(|mut lost| { - let cap = lost.window_cap.filter(|&cap| cap < max_t); - if cap.is_some() { - owners_slot = lost.owners.take(); - } - (lost, cap) - }) - }, - |failed, next| { - operator_text(&format!( - "decode window graphs: out of device memory recording windows up to T={failed}; retrying with windows up to T={next}" - )) - }, - ); - 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)); - } - }; - if used_max_t < *verifier_max_t { - // The card holds windows only up to `used_max_t`: every policy of the stack follows, for this and the later requests (the - // controllers restart; what they learned about the wider windows no longer applies). - operator_text(&format!( - "decode window graphs: windows limited to T<={used_max_t} (were T<={}): the policy, its arms and the MTP draft cap follow", - *verifier_max_t - )); - *verifier_max_t = used_max_t; - let narrowed = (|| -> Result<()> { - *settings = settings.with_window_cap(used_max_t); - *controller = settings.controller()?; - for (_, arm, arm_controller) in parked.iter_mut() { - *arm = arm.with_window_cap(used_max_t); - *arm_controller = arm.controller()?; - } - executor.set_mtp_max_drafts(binding, i32::try_from(settings.max_drafts()).map_err(|_| Error::Overflow)?) - })(); - if let Err(error) = narrowed { - let _ = disassemble(resources).map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); - broken.get_or_insert(error); - return Err(SpecError::Forward(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. - // the card at the end of the decode phase, graph pools and all windows captured: the real low-water mark of a request - vram_note(context, "decode end before disassemble"); - 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) { - // LELEKA_VRAM_LEDGER=1: the device allocations that appeared since the previous note, per call site (nothing when off) - leleka_cuda_driver::vram_ledger::report(label); - if profile::enabled() { - if let Ok((free, total)) = context.memory_info() { - // the low-water mark of the card's free VRAM over every note of this process: the number the reserve must cover - static LOWEST_FREE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(usize::MAX); - let lowest = LOWEST_FREE.fetch_min(free, std::sync::atomic::Ordering::Relaxed).min(free); - eprintln!("DBG vram {label}: free {} MiB of {} MiB (lowest note so far {} MiB)", free >> 20, total >> 20, lowest >> 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, assemble_with_window_fallback, disassemble, seed_ple_history, AssembleFailure, 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"); + // The native head + embedding come first: with LELEKA_PROMPT_EMBED_ALIAS=1 the prompt path's token table aliases the mapped host copy + // of the native embedding instead of a second copy in VRAM (the two are the same GGUF tensor). + let output = staged!("native head + embedding", context, OriginalNativeOutput::load(binding, context, NativeHeadDispatch::default(), true).map_err(at("OriginalNativeOutput::load"))?); + let embedding = staged!("embedding table", context, if OriginalPromptEmbedding::alias_enabled() { + OriginalPromptEmbedding::alias_native(binding, context, output.embedding(binding).map_err(at("OriginalNativeOutput::embedding"))?).map_err(at("OriginalPromptEmbedding::alias_native"))? + } else { + OriginalPromptEmbedding::load(binding, context).map_err(at("OriginalPromptEmbedding::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()); + // the prompt path's token table may alias the native embedding's mapped copy: it goes first + note(embedding.close()); + note(output.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, + parked, + 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(()) + }; + // A window or commit graph that does not fit in device memory costs the widest windows, not the request or the engine + // (upstream a8c1d4b7): the assembly is repeated with the windows that fit. The owners come back from each failure. + let mut owners_slot = Some(owners); + let (used_max_t, assembled) = assemble_with_window_fallback( + *verifier_max_t, + |max_t| { + let Some(owners) = owners_slot.take() else { + return Err((AssembleFailure { failure: Error::IdentityMismatch.into(), owners: None, window_cap: None }, None)); + }; + assemble( + binding, &weights, context, &*output, &base, owners, ple_history, rope, blobs, max_t, *max_cells, pcie_mode, + &mut queue_refill, + ) + .map_err(|mut lost| { + let cap = lost.window_cap.filter(|&cap| cap < max_t); + if cap.is_some() { + owners_slot = lost.owners.take(); + } + (lost, cap) + }) + }, + |failed, next| { + operator_text(&format!( + "decode window graphs: out of device memory recording windows up to T={failed}; retrying with windows up to T={next}" + )) + }, + ); + 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)); + } + }; + if used_max_t < *verifier_max_t { + // The card holds windows only up to `used_max_t`: every policy of the stack follows, for this and the later requests (the + // controllers restart; what they learned about the wider windows no longer applies). + operator_text(&format!( + "decode window graphs: windows limited to T<={used_max_t} (were T<={}): the policy, its arms and the MTP draft cap follow", + *verifier_max_t + )); + *verifier_max_t = used_max_t; + let narrowed = (|| -> Result<()> { + *settings = settings.with_window_cap(used_max_t); + *controller = settings.controller()?; + for (_, arm, arm_controller) in parked.iter_mut() { + *arm = arm.with_window_cap(used_max_t); + *arm_controller = arm.controller()?; + } + executor.set_mtp_max_drafts(binding, i32::try_from(settings.max_drafts()).map_err(|_| Error::Overflow)?) + })(); + if let Err(error) = narrowed { + let _ = disassemble(resources).map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); + broken.get_or_insert(error); + return Err(SpecError::Forward(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. + // the card at the end of the decode phase, graph pools and all windows captured: the real low-water mark of a request + vram_note(context, "decode end before disassemble"); + 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) { + // LELEKA_VRAM_LEDGER=1: the device allocations that appeared since the previous note, per call site (nothing when off) + leleka_cuda_driver::vram_ledger::report(label); + if profile::enabled() { + if let Ok((free, total)) = context.memory_info() { + // the low-water mark of the card's free VRAM over every note of this process: the number the reserve must cover + static LOWEST_FREE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(usize::MAX); + let lowest = LOWEST_FREE.fetch_min(free, std::sync::atomic::Ordering::Relaxed).min(free); + eprintln!("DBG vram {label}: free {} MiB of {} MiB (lowest note so far {} MiB)", free >> 20, total >> 20, lowest >> 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/crates/leleka-runtime/src/qwen_forward/original_serve_verifier.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_verifier.rs index 57f5d731..18141f0c 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_verifier.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_verifier.rs @@ -1,476 +1,476 @@ -//! Assembly and teardown of the native Original verifier for one decode phase. -//! -//! The verifier owns, for the whole phase, a canonical GDN image seeded from the session's published -//! recurrent priors, the PLE history seeded from the session's PLE prior, and the twelve resident QSA -//! index images and mapped K/V journals handed over from the prompt executor. It records the T = 1..=max_t -//! window graphs and the accepted-prefix commit graph over those owners (`record_all`) and is then ready to -//! `run`. Teardown closes the graphs, which releases every aggregate's reference to the QSA journal, and -//! returns the physical QSA owners so the executor can take them back at the session's lineage. -//! -//! Any producer the driver cannot capture yet fails `record_all` with its name -//! (`UNBOUND_PRODUCERS`); that refusal surfaces here untouched, never as a substituted arithmetic. -use super::{ - contract::{Error, Result, Stage}, - dense_weight_cache::DenseWeightCache, - gdn::GdnPrior, - moe_weight_cache::{MoeWeightCache, SharedKeys}, - original_serve_config::{ExpertBlobSizes, RopeConstants, verify_geometry}, - output_native::OriginalNativeOutput, - session::original_verified::OriginalVerifiedBase, -}; -use crate::model_binding::qwen4exp_input::{BoundLayerKind, ModelBinding}; -use leleka_cuda_driver::{ - Context, DeviceBuffer, OriginalQsaMappedJournal, OriginalQsaResidentIndex, OriginalVerifier, OriginalVerifyExpertFormats, - OriginalVerifyQsaJournal, OriginalVerifyResources, OriginalVerifyWindowPolicy, OriginalVerifyWindowResources, -}; -use std::rc::Rc; - -const PLE_HISTORY_VALUES: usize = 9 * 10240; -pub(in crate::qwen_forward) const PLE_HISTORY_BYTES: usize = PLE_HISTORY_VALUES * 4; - -/// Default of `LELEKA_QSA_CLUSTER` (the cluster top-k of the decode window; flipped after its gates, docs/upstream-port-plan.md row 2.5). -const QSA_CLUSTER_DEFAULT: bool = true; - -/// A refusal with the driver's own words when it has them (an unbound producer, an unsealed asset). -#[derive(Clone, Debug, Eq, PartialEq)] -pub(crate) struct ServeFailure { - pub(crate) error: Error, - pub(crate) detail: Option, -} -impl From for ServeFailure { - fn from(error: Error) -> Self { - Self { error, detail: None } - } -} -impl From for ServeFailure { - fn from(driver: leleka_cuda_driver::Error) -> Self { - let error = driver_error(&driver); - let detail = match &driver { - leleka_cuda_driver::Error::InvalidDriverValue(message) => Some((*message).to_owned()), - leleka_cuda_driver::Error::UnsupportedQwenOperation => { - Some("a compiled asset is unsealed or the operation is not supported by this build".to_owned()) - } - leleka_cuda_driver::Error::GraphOutOfMemory { .. } => Some(driver.to_string()), - _ => None, - }; - Self { error, detail } - } -} -impl ServeFailure { - /// `class=... detail=...` for the operator diagnostic line (the detail text is a fixed driver string). - pub(crate) fn describe(&self) -> String { - match &self.detail { - Some(detail) => format!("{:?}: {detail}", self.error), - None => format!("{:?}", self.error), - } - } -} -/// The runtime error class of a driver error (the same mapping every Original owner uses). -pub(in crate::qwen_forward) fn driver_error(error: &leleka_cuda_driver::Error) -> Error { - use leleka_cuda_driver::Error as D; - match error { - D::NonFiniteMmqOutput(_) => Error::NonFinite, - D::BudgetExceeded | D::HostAllocation => Error::InputAllocation, - D::ContextMismatch | D::UnexpectedContext => Error::IdentityMismatch, - D::InvalidQwenShape | D::InvalidSize | D::InvalidProjectionShape => Error::InvalidDimension, - D::UnsupportedQwenOperation => Error::Unsupported(Stage::Session), - D::InvalidDriverValue(_) => Error::Unsupported(Stage::Executor), - _ => Error::CudaExecution, - } -} - -type QsaOwners<'ctx> = [Option<(OriginalQsaResidentIndex<'ctx>, OriginalQsaMappedJournal<'ctx>)>; 48]; - -/// The verifier plus the one extra reference to the QSA journal that lets the owners be recovered. -pub(in crate::qwen_forward) struct DecodeResources<'a, 'ctx> { - pub(in crate::qwen_forward) verifier: OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>>, - pub(in crate::qwen_forward) qsa: Rc>, - /// Model layer index of journal layer `i` (the owners were handed over in ascending slot order). - pub(in crate::qwen_forward) slots: [usize; 12], -} - -/// Why an assembly failed and whether the physical QSA owners survived it. -pub(in crate::qwen_forward) struct AssembleFailure<'ctx> { - pub(in crate::qwen_forward) failure: ServeFailure, - /// The owners, when they could be recovered; `None` means the stack must be rebuilt. - pub(in crate::qwen_forward) owners: Option>, - /// Set when a window or commit graph did not fit in device memory (the context is intact): the widest window T that is still - /// worth recording (`window_cap_after`), so the assembly can be repeated with `max_t` = this. `None` for every other failure. - pub(in crate::qwen_forward) window_cap: Option, -} -impl<'ctx> AssembleFailure<'ctx> { - fn lost(failure: impl Into) -> Self { - Self { failure: failure.into(), owners: None, window_cap: None } - } -} - -/// The narrowest verify window worth running: a width of one is plain decoding, so a fallback below it is no fallback. -pub(in crate::qwen_forward) const MIN_FALLBACK_WINDOW: usize = 2; - -/// After a graph instantiate that ran out of device memory while `max_t` windows were being recorded: the widest window width to -/// record instead, or `None` when the error is anything else or nothing wide enough is left. The graph that did not fit and every -/// wider one are given up; windows below it were recorded, so they fit (the commit graph, `window` = 0, costs the widest window). -pub(in crate::qwen_forward) fn window_cap_after(error: &leleka_cuda_driver::Error, max_t: usize) -> Option { - let leleka_cuda_driver::Error::GraphOutOfMemory { window } = error else { return None }; - let failed = if *window == 0 { max_t } else { (*window).min(max_t) }; - let cap = failed - 1; - (cap >= MIN_FALLBACK_WINDOW).then_some(cap) -} - -/// Repeat an assembly with narrower windows while it fails only because a window graph did not fit in device memory. -/// `attempt(max_t)` returns the assembly or the failure with the cap `window_cap_after` named (`None` = not retryable); every -/// retry is strictly narrower, so this ends. `note(failed, next)` reports each step. Returns the `max_t` of the last attempt with -/// its outcome. -pub(in crate::qwen_forward) fn assemble_with_window_fallback( - max_t: usize, - mut attempt: impl FnMut(usize) -> std::result::Result)>, - mut note: impl FnMut(usize, usize), -) -> (usize, std::result::Result) { - let mut current = max_t; - loop { - match attempt(current) { - Ok(done) => return (current, Ok(done)), - Err((_, Some(next))) if next < current && next >= MIN_FALLBACK_WINDOW => { - note(current, next); - current = next; - } - Err((error, _)) => return (current, Err(error)), - } - } -} - -/// The GDN priors of the thirty-six recurrent layers in layer order, as the canonical image takes them. -fn gdn_layer_priors<'p>(binding: &ModelBinding, base: &'p OriginalVerifiedBase<'_>) -> Result> { - let mut priors = Vec::new(); - priors.try_reserve_exact(36).map_err(|_| Error::InputAllocation)?; - for layer in binding.ordered_layers() { - if layer.kind() == BoundLayerKind::Gdn { - priors.push(base.gdn[layer.index() as usize].as_ref().ok_or(Error::IdentityMismatch)?); - } - } - if priors.len() != 36 { - return Err(Error::IdentityMismatch); - } - Ok(priors) -} - -/// Upload the session's PLE prior into the device history image the commit graph keeps current. -pub(in crate::qwen_forward) fn seed_ple_history<'ctx>( - base: &OriginalVerifiedBase<'_>, - ple_history: &mut DeviceBuffer<'ctx>, -) -> std::result::Result<(), ServeFailure> { - let ple = base.ple.as_ref().ok_or(Error::IdentityMismatch)?; - if ple.history().len() != PLE_HISTORY_VALUES || ple_history.len() != PLE_HISTORY_BYTES { - return Err(Error::InvalidDimension.into()); - } - let mut bytes = Vec::new(); - bytes.try_reserve_exact(PLE_HISTORY_BYTES).map_err(|_| Error::InputAllocation)?; - for value in ple.history() { - bytes.extend_from_slice(&value.to_le_bytes()); - } - ple_history.copy_from(&bytes)?; - Ok(()) -} - -/// The PLE history image as the commit graph left it (after the last committed window). -pub(in crate::qwen_forward) fn read_ple_history(ple_history: &DeviceBuffer<'_>) -> Result> { - if ple_history.len() != PLE_HISTORY_BYTES { - return Err(Error::InvalidDimension); - } - let bytes = ple_history.copy_to_owned(PLE_HISTORY_BYTES).map_err(|e| driver_error(&e))?; - let mut values = Vec::new(); - values.try_reserve_exact(PLE_HISTORY_VALUES).map_err(|_| Error::InputAllocation)?; - values.extend(bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b))); - Ok(values.into_boxed_slice()) -} - -/// The model weights the window graphs read in place for the whole phase, all borrowed from the caches that -/// own them: projections, hyper-connection / PLE and QSA operands from the dense cache, router and shared -/// experts from the MoE cache, and the PLE scratch the stack owns. -pub(in crate::qwen_forward) struct VerifyWeights<'a, 'ctx> { - pub(in crate::qwen_forward) dense: &'a DenseWeightCache<'ctx>, - pub(in crate::qwen_forward) moe: &'a MoeWeightCache<'ctx>, - pub(in crate::qwen_forward) shared: &'a SharedKeys, - pub(in crate::qwen_forward) formats: &'a OriginalVerifyExpertFormats, - pub(in crate::qwen_forward) ple_scratch: &'a DeviceBuffer<'ctx>, -} - -/// Build the canonical GDN image from the GDN priors, the QSA journal over the handed-over owners, and -/// record every window graph and the commit graph. `ple_history` must already hold the seeded image -/// (`seed_ple_history`) and outlive the phase; the caller keeps its own shared reference to read it back. -#[allow(clippy::too_many_arguments)] -pub(in crate::qwen_forward) fn assemble<'a, 'ctx>( - binding: &ModelBinding, - weights: &VerifyWeights<'a, 'ctx>, - context: &'ctx Context<'ctx>, - output: &OriginalNativeOutput<'ctx>, - base: &OriginalVerifiedBase<'ctx>, - mut owners: QsaOwners<'ctx>, - ple_history: &'a DeviceBuffer<'ctx>, - rope: &RopeConstants, - blobs: &ExpertBlobSizes, - max_t: usize, - max_cells: usize, - pcie_mode: u8, - after_prepare: &mut dyn FnMut() -> std::result::Result<(), Error>, -) -> std::result::Result, AssembleFailure<'ctx>> { - let dense = weights.dense; - // The window graphs bind each layer's streamed-KV resolver. The prompt path initialises it lazily on its - // first append, so a ONE-token prompt on a fresh stack reaches the capture with none: initialise it here - // (never through `reset`, which would change the epoch and orphan every prefix the session holds). - if let Err(failure) = ensure_resolvers(binding, dense, context, &mut owners) { - return Err(AssembleFailure { failure, owners: Some(owners), window_cap: None }); - } - // Everything that can be refused WITHOUT consuming the owners is checked first. - let p = super::original_serve_profile::span("assemble.prepare"); - let prepare = (|| -> std::result::Result<_, ServeFailure> { - let geometry = verify_geometry(max_t, max_cells, blobs)?; - blobs.layout()?; - let priors = gdn_layer_priors(binding, base)?; - let states: [&[f32]; 36] = std::array::from_fn(|i| priors[i].values()); - let histories: [&[f32]; 36] = std::array::from_fn(|i| priors[i].history()); - let canonical = context.original_verify_canonical_gdn(states, histories)?; - // PLE history: the seeded device image the commit graph keeps current. - if base.ple.is_none() || ple_history.len() != PLE_HISTORY_BYTES { - return Err(Error::InvalidDimension.into()); - } - let gamma = dense.original_verify_qsa_gamma(binding)?; - Ok((geometry, canonical, gamma)) - })(); - drop(p); - let (geometry, mut canonical, gamma) = match prepare { - Ok(parts) => parts, - Err(failure) => return Err(AssembleFailure { failure, owners: Some(owners), window_cap: None }), - }; - // The caller's work that wants the intake uploads done and the graph capture still ahead (the lent-slot refill copies). - if let Err(error) = after_prepare() { - drop(canonical); - return Err(AssembleFailure { failure: error.into(), owners: Some(owners), window_cap: None }); - } - // ---- from here the owners move into the journal - let mut slots = Vec::new(); - let mut indices = Vec::new(); - let mut mapped = Vec::new(); - for (slot, owner) in owners.into_iter().enumerate() { - if let Some((index, kv)) = owner { - slots.push(slot); - indices.push(index); - mapped.push(kv); - } - } - let slots: [usize; 12] = slots.try_into().map_err(|_| AssembleFailure::lost(Error::IdentityMismatch))?; - let indices: [OriginalQsaResidentIndex<'ctx>; 12] = - indices.try_into().map_err(|_| AssembleFailure::lost(Error::IdentityMismatch))?; - let mapped: [OriginalQsaMappedJournal<'ctx>; 12] = - mapped.try_into().map_err(|_| AssembleFailure::lost(Error::IdentityMismatch))?; - let p = super::original_serve_profile::span("assemble.qsa_journal"); - let qsa = OriginalVerifyQsaJournal::new(context, indices, mapped, gamma, rope.verify_rope()) - .map_err(AssembleFailure::lost)?; - drop(p); - let mut window_cap = None; - let recorded = (|| -> std::result::Result<_, ServeFailure> { - let p = super::original_serve_profile::span("assemble.verifier_new"); - let mut verifier = OriginalVerifier::<'ctx, OriginalVerifyWindowResources<'a, 'ctx>>::new(context, geometry)?; - drop(p); - let p = super::original_serve_profile::span("assemble.aggregates"); - let built = (|| -> std::result::Result<(Vec>>, OriginalVerifyWindowResources<'a, 'ctx>), ServeFailure> { - let mut windows = Vec::new(); - windows.try_reserve_exact(max_t).map_err(|_| Error::InputAllocation)?; - let mut aggregate = |t: usize| -> std::result::Result, ServeFailure> { - let gdn_weights = dense.original_verify_gdn_weights(binding)?; - let journal = verifier.bank()?.gdn_journal(&mut canonical, gdn_weights, Some(ple_history))?; - let head = output.rows(binding, t)?; - let resources = OriginalVerifyResources::new(context, journal, Rc::clone(&qsa), head)?; - let embed = output.embedding(binding)?.rows(t)?; - let window = OriginalVerifyWindowResources::new(context, resources, embed, blobs.layout()?, t)? - .with_projections(dense.original_verify_projections(binding, &geometry)?)? - .with_gr(dense.original_verify_gr(binding, weights.ple_scratch, ple_history)?)? - .with_qsa(dense.original_verify_qsa(binding, &geometry)?)? - .with_moe(weights.moe.original_verify_moe(binding, dense, &geometry, weights.shared, weights.formats.clone())?)?; - Ok(window) - }; - for t in 1..=max_t { - windows.push(Some(aggregate(t)?)); - } - let commit = aggregate(max_t)?; - Ok((windows, commit)) - })(); - drop(p); - let (mut windows, commit) = match built { - Ok(parts) => parts, - Err(failure) => { - let _ = verifier.close(); - return Err(failure); - } - }; - let _ = leleka_cuda_driver::original_capture_timing::take(); - let _p = super::original_serve_profile::span("assemble.record_all"); - // `Verifier::set_pcie_mode`: the copy kernel stages the PCIe share inside the graph (2), or DMA (0). - let mut policy = OriginalVerifyWindowPolicy::mode17(); - policy.pcie_mode = pcie_mode; - // docs/upstream-port-plan.md row 2.5: the decode top-k as a thread-block cluster (same ids as qsa_topk_ref; sm_90+, the driver - // turns it off again on an older card). `LELEKA_QSA_CLUSTER=1` / `0`; unset: QSA_CLUSTER_DEFAULT. - policy.qsa.cluster_topk = leleka_cuda_driver::qsa_cluster_requested(QSA_CLUSTER_DEFAULT); - let recorded = verifier.record_all( - policy, - |t| windows.get_mut(t - 1).and_then(Option::take).ok_or(leleka_cuda_driver::Error::InvalidQwenShape), - commit, - ); - let (capture_ms, instantiate_ms, modules_ms) = leleka_cuda_driver::original_capture_timing::take(); - super::original_serve_profile::add("record.capture", capture_ms); - super::original_serve_profile::add("record.instantiate", instantiate_ms); - super::original_serve_profile::add("record.modules", modules_ms); - if let Err(error) = recorded { - // dropping the unused aggregates and closing the verifier releases every journal reference - drop(windows); - let _ = verifier.close(); - window_cap = window_cap_after(&error, max_t); - return Err(error.into()); - } - Ok(verifier) - })(); - drop(canonical); - match recorded { - Ok(verifier) => Ok(DecodeResources { verifier, qsa, slots }), - Err(failure) => { - // every aggregate is gone: the journal can give the owners back - let owners = recover(qsa, slots); - // a retry needs the owners back - let window_cap = window_cap.filter(|_| owners.is_some()); - Err(AssembleFailure { failure, owners, window_cap }) - } - } -} - -/// `OriginalQsaMappedJournal::ensure_resolver` on every handed-over layer (a no-op for a layer the prompt -/// already appended to). -fn ensure_resolvers<'ctx>( - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, - context: &'ctx Context<'ctx>, - owners: &mut QsaOwners<'ctx>, -) -> std::result::Result<(), ServeFailure> { - if owners.iter().flatten().all(|(_, kv)| kv.resolver_ready()) { - return Ok(()); - } - let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; - for (_, kv) in owners.iter_mut().flatten() { - kv.ensure_resolver(&mut workspace)?; - } - Ok(()) -} - -/// Close the verifier (drains both streams, drops every graph and aggregate) and take the physical QSA -/// owners back from the journal. -pub(in crate::qwen_forward) fn disassemble<'a, 'ctx>( - resources: DecodeResources<'a, 'ctx>, -) -> std::result::Result, ServeFailure> { - let DecodeResources { verifier, qsa, slots } = resources; - let closed = verifier.close(); - let recovered = recover(qsa, slots); - match (closed, recovered) { - (Ok(()), Some(owners)) => Ok(owners), - (Err(error), _) => Err(error.into()), - (Ok(()), None) => Err(Error::IdentityMismatch.into()), - } -} - -fn recover<'a, 'ctx>(qsa: Rc>, slots: [usize; 12]) -> Option> { - let (indices, mapped) = OriginalVerifyQsaJournal::into_owners(qsa).ok()?; - let mut owners: QsaOwners<'ctx> = std::array::from_fn(|_| None); - for ((slot, index), kv) in slots.into_iter().zip(indices).zip(mapped) { - *owners.get_mut(slot)? = Some((index, kv)); - } - Some(owners) -} - -#[cfg(test)] -mod tests { - use super::*; - use leleka_cuda_driver::Error as D; - - #[test] - fn a_graph_out_of_memory_names_the_widest_window_worth_recording() { - // window T=6 of 8 did not fit: 1..=5 were recorded and fit - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 6 }, 8), Some(5)); - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 3 }, 8), Some(2)); - // the commit graph (window 0) is recorded after every window: the widest window goes - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 8), Some(7)); - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 4), Some(3)); - // nothing wide enough is left (a width of one is no speculation), and a window past max_t is clamped - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 2 }, 8), None); - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 1 }, 8), None); - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 2), None); - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 9 }, 4), Some(3)); - // every other failure, including a plain out-of-memory the driver did not classify, is not retried - for other in [D::HostAllocation, D::ContextPoisoned, D::InvalidQwenShape, D::Driver { operation: "cuGraphInstantiateWithFlags", code: 2 }] { - assert_eq!(window_cap_after(&other, 8), None, "{other:?}"); - } - assert!(ServeFailure::from(D::GraphOutOfMemory { window: 6 }).describe().contains("T=6")); - } - - #[test] - fn the_assembly_is_repeated_with_narrower_windows_until_one_fits() { - // 8 and 6 do not fit, 5 does - let mut tried = Vec::new(); - let mut notes = Vec::new(); - let (used, outcome) = assemble_with_window_fallback( - 8, - |t| { - tried.push(t); - match t { - 8 => Err(("oom at 8", window_cap_after(&D::GraphOutOfMemory { window: 7 }, t))), - 6 => Err(("oom at 6", window_cap_after(&D::GraphOutOfMemory { window: 0 }, t))), - t => Ok(t * 10), - } - }, - |failed, next| notes.push((failed, next)), - ); - assert_eq!((used, outcome), (5, Ok(50))); - assert_eq!(tried, [8, 6, 5]); - assert_eq!(notes, [(8, 6), (6, 5)]); - // it fits at once: one attempt, nothing noted - let mut calls = 0; - let (used, outcome) = assemble_with_window_fallback::<_, &str>(8, |t| { calls += 1; Ok(t) }, |_, _| panic!("no retry")); - assert_eq!((used, outcome, calls), (8, Ok(8), 1)); - } - - #[test] - fn the_fallback_stops_at_the_floor_on_any_other_failure_and_never_loops() { - // nothing fits down to the floor: the last failure comes back, with the width it was tried at - let (used, outcome) = assemble_with_window_fallback::<(), _>( - 8, - |t| Err((format!("oom at {t}"), window_cap_after(&D::GraphOutOfMemory { window: t }, t))), - |_, _| {}, - ); - assert_eq!((used, outcome), (2, Err("oom at 2".to_string()))); - // a failure that is not an out-of-memory is returned at once, with no retry - let mut calls = 0; - let (used, outcome) = assemble_with_window_fallback::<(), _>(8, |_| { calls += 1; Err(("broken", None)) }, |_, _| panic!("no retry")); - assert_eq!((used, outcome, calls), (8, Err("broken"), 1)); - // a cap that does not narrow the window (a bug somewhere) is not followed - let (used, outcome) = assemble_with_window_fallback::<(), _>(4, |_| Err(("same", Some(4))), |_, _| panic!("no retry")); - assert_eq!((used, outcome), (4, Err("same"))); - } - - #[test] - fn driver_refusals_keep_their_words_and_a_stable_class() { - let unbound = leleka_cuda_driver::Error::InvalidDriverValue("Original verifier producer unbound: router"); - let failure = ServeFailure::from(unbound); - assert_eq!(failure.error, Error::Unsupported(Stage::Executor)); - assert_eq!(failure.detail.as_deref(), Some("Original verifier producer unbound: router")); - assert!(failure.describe().contains("router")); - let sealed = ServeFailure::from(leleka_cuda_driver::Error::UnsupportedQwenOperation); - assert_eq!(sealed.error, Error::Unsupported(Stage::Session)); - assert!(sealed.detail.as_deref().is_some_and(|d| d.contains("unsealed"))); - let plain = ServeFailure::from(leleka_cuda_driver::Error::ContextMismatch); - assert_eq!((plain.error, plain.detail), (Error::IdentityMismatch, None)); - assert_eq!(ServeFailure::from(Error::NonFinite).describe(), "NonFinite"); - } - - #[test] - fn the_ple_history_image_is_nine_slots_of_the_channel_width() { - assert_eq!(PLE_HISTORY_VALUES, 92_160); - assert_eq!(PLE_HISTORY_BYTES, 368_640); - } -} +//! Assembly and teardown of the native Original verifier for one decode phase. +//! +//! The verifier owns, for the whole phase, a canonical GDN image seeded from the session's published +//! recurrent priors, the PLE history seeded from the session's PLE prior, and the twelve resident QSA +//! index images and mapped K/V journals handed over from the prompt executor. It records the T = 1..=max_t +//! window graphs and the accepted-prefix commit graph over those owners (`record_all`) and is then ready to +//! `run`. Teardown closes the graphs, which releases every aggregate's reference to the QSA journal, and +//! returns the physical QSA owners so the executor can take them back at the session's lineage. +//! +//! Any producer the driver cannot capture yet fails `record_all` with its name +//! (`UNBOUND_PRODUCERS`); that refusal surfaces here untouched, never as a substituted arithmetic. +use super::{ + contract::{Error, Result, Stage}, + dense_weight_cache::DenseWeightCache, + gdn::GdnPrior, + moe_weight_cache::{MoeWeightCache, SharedKeys}, + original_serve_config::{ExpertBlobSizes, RopeConstants, verify_geometry}, + output_native::OriginalNativeOutput, + session::original_verified::OriginalVerifiedBase, +}; +use crate::model_binding::qwen4exp_input::{BoundLayerKind, ModelBinding}; +use leleka_cuda_driver::{ + Context, DeviceBuffer, OriginalQsaMappedJournal, OriginalQsaResidentIndex, OriginalVerifier, OriginalVerifyExpertFormats, + OriginalVerifyQsaJournal, OriginalVerifyResources, OriginalVerifyWindowPolicy, OriginalVerifyWindowResources, +}; +use std::rc::Rc; + +const PLE_HISTORY_VALUES: usize = 9 * 10240; +pub(in crate::qwen_forward) const PLE_HISTORY_BYTES: usize = PLE_HISTORY_VALUES * 4; + +/// Default of `LELEKA_QSA_CLUSTER` (the cluster top-k of the decode window; flipped after its gates, docs/upstream-port-plan.md row 2.5). +const QSA_CLUSTER_DEFAULT: bool = true; + +/// A refusal with the driver's own words when it has them (an unbound producer, an unsealed asset). +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct ServeFailure { + pub(crate) error: Error, + pub(crate) detail: Option, +} +impl From for ServeFailure { + fn from(error: Error) -> Self { + Self { error, detail: None } + } +} +impl From for ServeFailure { + fn from(driver: leleka_cuda_driver::Error) -> Self { + let error = driver_error(&driver); + let detail = match &driver { + leleka_cuda_driver::Error::InvalidDriverValue(message) => Some((*message).to_owned()), + leleka_cuda_driver::Error::UnsupportedQwenOperation => { + Some("a compiled asset is unsealed or the operation is not supported by this build".to_owned()) + } + leleka_cuda_driver::Error::GraphOutOfMemory { .. } => Some(driver.to_string()), + _ => None, + }; + Self { error, detail } + } +} +impl ServeFailure { + /// `class=... detail=...` for the operator diagnostic line (the detail text is a fixed driver string). + pub(crate) fn describe(&self) -> String { + match &self.detail { + Some(detail) => format!("{:?}: {detail}", self.error), + None => format!("{:?}", self.error), + } + } +} +/// The runtime error class of a driver error (the same mapping every Original owner uses). +pub(in crate::qwen_forward) fn driver_error(error: &leleka_cuda_driver::Error) -> Error { + use leleka_cuda_driver::Error as D; + match error { + D::NonFiniteMmqOutput(_) => Error::NonFinite, + D::BudgetExceeded | D::HostAllocation => Error::InputAllocation, + D::ContextMismatch | D::UnexpectedContext => Error::IdentityMismatch, + D::InvalidQwenShape | D::InvalidSize | D::InvalidProjectionShape => Error::InvalidDimension, + D::UnsupportedQwenOperation => Error::Unsupported(Stage::Session), + D::InvalidDriverValue(_) => Error::Unsupported(Stage::Executor), + _ => Error::CudaExecution, + } +} + +type QsaOwners<'ctx> = [Option<(OriginalQsaResidentIndex<'ctx>, OriginalQsaMappedJournal<'ctx>)>; 48]; + +/// The verifier plus the one extra reference to the QSA journal that lets the owners be recovered. +pub(in crate::qwen_forward) struct DecodeResources<'a, 'ctx> { + pub(in crate::qwen_forward) verifier: OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>>, + pub(in crate::qwen_forward) qsa: Rc>, + /// Model layer index of journal layer `i` (the owners were handed over in ascending slot order). + pub(in crate::qwen_forward) slots: [usize; 12], +} + +/// Why an assembly failed and whether the physical QSA owners survived it. +pub(in crate::qwen_forward) struct AssembleFailure<'ctx> { + pub(in crate::qwen_forward) failure: ServeFailure, + /// The owners, when they could be recovered; `None` means the stack must be rebuilt. + pub(in crate::qwen_forward) owners: Option>, + /// Set when a window or commit graph did not fit in device memory (the context is intact): the widest window T that is still + /// worth recording (`window_cap_after`), so the assembly can be repeated with `max_t` = this. `None` for every other failure. + pub(in crate::qwen_forward) window_cap: Option, +} +impl<'ctx> AssembleFailure<'ctx> { + fn lost(failure: impl Into) -> Self { + Self { failure: failure.into(), owners: None, window_cap: None } + } +} + +/// The narrowest verify window worth running: a width of one is plain decoding, so a fallback below it is no fallback. +pub(in crate::qwen_forward) const MIN_FALLBACK_WINDOW: usize = 2; + +/// After a graph instantiate that ran out of device memory while `max_t` windows were being recorded: the widest window width to +/// record instead, or `None` when the error is anything else or nothing wide enough is left. The graph that did not fit and every +/// wider one are given up; windows below it were recorded, so they fit (the commit graph, `window` = 0, costs the widest window). +pub(in crate::qwen_forward) fn window_cap_after(error: &leleka_cuda_driver::Error, max_t: usize) -> Option { + let leleka_cuda_driver::Error::GraphOutOfMemory { window } = error else { return None }; + let failed = if *window == 0 { max_t } else { (*window).min(max_t) }; + let cap = failed - 1; + (cap >= MIN_FALLBACK_WINDOW).then_some(cap) +} + +/// Repeat an assembly with narrower windows while it fails only because a window graph did not fit in device memory. +/// `attempt(max_t)` returns the assembly or the failure with the cap `window_cap_after` named (`None` = not retryable); every +/// retry is strictly narrower, so this ends. `note(failed, next)` reports each step. Returns the `max_t` of the last attempt with +/// its outcome. +pub(in crate::qwen_forward) fn assemble_with_window_fallback( + max_t: usize, + mut attempt: impl FnMut(usize) -> std::result::Result)>, + mut note: impl FnMut(usize, usize), +) -> (usize, std::result::Result) { + let mut current = max_t; + loop { + match attempt(current) { + Ok(done) => return (current, Ok(done)), + Err((_, Some(next))) if next < current && next >= MIN_FALLBACK_WINDOW => { + note(current, next); + current = next; + } + Err((error, _)) => return (current, Err(error)), + } + } +} + +/// The GDN priors of the thirty-six recurrent layers in layer order, as the canonical image takes them. +fn gdn_layer_priors<'p>(binding: &ModelBinding, base: &'p OriginalVerifiedBase<'_>) -> Result> { + let mut priors = Vec::new(); + priors.try_reserve_exact(36).map_err(|_| Error::InputAllocation)?; + for layer in binding.ordered_layers() { + if layer.kind() == BoundLayerKind::Gdn { + priors.push(base.gdn[layer.index() as usize].as_ref().ok_or(Error::IdentityMismatch)?); + } + } + if priors.len() != 36 { + return Err(Error::IdentityMismatch); + } + Ok(priors) +} + +/// Upload the session's PLE prior into the device history image the commit graph keeps current. +pub(in crate::qwen_forward) fn seed_ple_history<'ctx>( + base: &OriginalVerifiedBase<'_>, + ple_history: &mut DeviceBuffer<'ctx>, +) -> std::result::Result<(), ServeFailure> { + let ple = base.ple.as_ref().ok_or(Error::IdentityMismatch)?; + if ple.history().len() != PLE_HISTORY_VALUES || ple_history.len() != PLE_HISTORY_BYTES { + return Err(Error::InvalidDimension.into()); + } + let mut bytes = Vec::new(); + bytes.try_reserve_exact(PLE_HISTORY_BYTES).map_err(|_| Error::InputAllocation)?; + for value in ple.history() { + bytes.extend_from_slice(&value.to_le_bytes()); + } + ple_history.copy_from(&bytes)?; + Ok(()) +} + +/// The PLE history image as the commit graph left it (after the last committed window). +pub(in crate::qwen_forward) fn read_ple_history(ple_history: &DeviceBuffer<'_>) -> Result> { + if ple_history.len() != PLE_HISTORY_BYTES { + return Err(Error::InvalidDimension); + } + let bytes = ple_history.copy_to_owned(PLE_HISTORY_BYTES).map_err(|e| driver_error(&e))?; + let mut values = Vec::new(); + values.try_reserve_exact(PLE_HISTORY_VALUES).map_err(|_| Error::InputAllocation)?; + values.extend(bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b))); + Ok(values.into_boxed_slice()) +} + +/// The model weights the window graphs read in place for the whole phase, all borrowed from the caches that +/// own them: projections, hyper-connection / PLE and QSA operands from the dense cache, router and shared +/// experts from the MoE cache, and the PLE scratch the stack owns. +pub(in crate::qwen_forward) struct VerifyWeights<'a, 'ctx> { + pub(in crate::qwen_forward) dense: &'a DenseWeightCache<'ctx>, + pub(in crate::qwen_forward) moe: &'a MoeWeightCache<'ctx>, + pub(in crate::qwen_forward) shared: &'a SharedKeys, + pub(in crate::qwen_forward) formats: &'a OriginalVerifyExpertFormats, + pub(in crate::qwen_forward) ple_scratch: &'a DeviceBuffer<'ctx>, +} + +/// Build the canonical GDN image from the GDN priors, the QSA journal over the handed-over owners, and +/// record every window graph and the commit graph. `ple_history` must already hold the seeded image +/// (`seed_ple_history`) and outlive the phase; the caller keeps its own shared reference to read it back. +#[allow(clippy::too_many_arguments)] +pub(in crate::qwen_forward) fn assemble<'a, 'ctx>( + binding: &ModelBinding, + weights: &VerifyWeights<'a, 'ctx>, + context: &'ctx Context<'ctx>, + output: &OriginalNativeOutput<'ctx>, + base: &OriginalVerifiedBase<'ctx>, + mut owners: QsaOwners<'ctx>, + ple_history: &'a DeviceBuffer<'ctx>, + rope: &RopeConstants, + blobs: &ExpertBlobSizes, + max_t: usize, + max_cells: usize, + pcie_mode: u8, + after_prepare: &mut dyn FnMut() -> std::result::Result<(), Error>, +) -> std::result::Result, AssembleFailure<'ctx>> { + let dense = weights.dense; + // The window graphs bind each layer's streamed-KV resolver. The prompt path initialises it lazily on its + // first append, so a ONE-token prompt on a fresh stack reaches the capture with none: initialise it here + // (never through `reset`, which would change the epoch and orphan every prefix the session holds). + if let Err(failure) = ensure_resolvers(binding, dense, context, &mut owners) { + return Err(AssembleFailure { failure, owners: Some(owners), window_cap: None }); + } + // Everything that can be refused WITHOUT consuming the owners is checked first. + let p = super::original_serve_profile::span("assemble.prepare"); + let prepare = (|| -> std::result::Result<_, ServeFailure> { + let geometry = verify_geometry(max_t, max_cells, blobs)?; + blobs.layout()?; + let priors = gdn_layer_priors(binding, base)?; + let states: [&[f32]; 36] = std::array::from_fn(|i| priors[i].values()); + let histories: [&[f32]; 36] = std::array::from_fn(|i| priors[i].history()); + let canonical = context.original_verify_canonical_gdn(states, histories)?; + // PLE history: the seeded device image the commit graph keeps current. + if base.ple.is_none() || ple_history.len() != PLE_HISTORY_BYTES { + return Err(Error::InvalidDimension.into()); + } + let gamma = dense.original_verify_qsa_gamma(binding)?; + Ok((geometry, canonical, gamma)) + })(); + drop(p); + let (geometry, mut canonical, gamma) = match prepare { + Ok(parts) => parts, + Err(failure) => return Err(AssembleFailure { failure, owners: Some(owners), window_cap: None }), + }; + // The caller's work that wants the intake uploads done and the graph capture still ahead (the lent-slot refill copies). + if let Err(error) = after_prepare() { + drop(canonical); + return Err(AssembleFailure { failure: error.into(), owners: Some(owners), window_cap: None }); + } + // ---- from here the owners move into the journal + let mut slots = Vec::new(); + let mut indices = Vec::new(); + let mut mapped = Vec::new(); + for (slot, owner) in owners.into_iter().enumerate() { + if let Some((index, kv)) = owner { + slots.push(slot); + indices.push(index); + mapped.push(kv); + } + } + let slots: [usize; 12] = slots.try_into().map_err(|_| AssembleFailure::lost(Error::IdentityMismatch))?; + let indices: [OriginalQsaResidentIndex<'ctx>; 12] = + indices.try_into().map_err(|_| AssembleFailure::lost(Error::IdentityMismatch))?; + let mapped: [OriginalQsaMappedJournal<'ctx>; 12] = + mapped.try_into().map_err(|_| AssembleFailure::lost(Error::IdentityMismatch))?; + let p = super::original_serve_profile::span("assemble.qsa_journal"); + let qsa = OriginalVerifyQsaJournal::new(context, indices, mapped, gamma, rope.verify_rope()) + .map_err(AssembleFailure::lost)?; + drop(p); + let mut window_cap = None; + let recorded = (|| -> std::result::Result<_, ServeFailure> { + let p = super::original_serve_profile::span("assemble.verifier_new"); + let mut verifier = OriginalVerifier::<'ctx, OriginalVerifyWindowResources<'a, 'ctx>>::new(context, geometry)?; + drop(p); + let p = super::original_serve_profile::span("assemble.aggregates"); + let built = (|| -> std::result::Result<(Vec>>, OriginalVerifyWindowResources<'a, 'ctx>), ServeFailure> { + let mut windows = Vec::new(); + windows.try_reserve_exact(max_t).map_err(|_| Error::InputAllocation)?; + let mut aggregate = |t: usize| -> std::result::Result, ServeFailure> { + let gdn_weights = dense.original_verify_gdn_weights(binding)?; + let journal = verifier.bank()?.gdn_journal(&mut canonical, gdn_weights, Some(ple_history))?; + let head = output.rows(binding, t)?; + let resources = OriginalVerifyResources::new(context, journal, Rc::clone(&qsa), head)?; + let embed = output.embedding(binding)?.rows(t)?; + let window = OriginalVerifyWindowResources::new(context, resources, embed, blobs.layout()?, t)? + .with_projections(dense.original_verify_projections(binding, &geometry)?)? + .with_gr(dense.original_verify_gr(binding, weights.ple_scratch, ple_history)?)? + .with_qsa(dense.original_verify_qsa(binding, &geometry)?)? + .with_moe(weights.moe.original_verify_moe(binding, dense, &geometry, weights.shared, weights.formats.clone())?)?; + Ok(window) + }; + for t in 1..=max_t { + windows.push(Some(aggregate(t)?)); + } + let commit = aggregate(max_t)?; + Ok((windows, commit)) + })(); + drop(p); + let (mut windows, commit) = match built { + Ok(parts) => parts, + Err(failure) => { + let _ = verifier.close(); + return Err(failure); + } + }; + let _ = leleka_cuda_driver::original_capture_timing::take(); + let _p = super::original_serve_profile::span("assemble.record_all"); + // `Verifier::set_pcie_mode`: the copy kernel stages the PCIe share inside the graph (2), or DMA (0). + let mut policy = OriginalVerifyWindowPolicy::mode17(); + policy.pcie_mode = pcie_mode; + // docs/upstream-port-plan.md row 2.5: the decode top-k as a thread-block cluster (same ids as qsa_topk_ref; sm_90+, the driver + // turns it off again on an older card). `LELEKA_QSA_CLUSTER=1` / `0`; unset: QSA_CLUSTER_DEFAULT. + policy.qsa.cluster_topk = leleka_cuda_driver::qsa_cluster_requested(QSA_CLUSTER_DEFAULT); + let recorded = verifier.record_all( + policy, + |t| windows.get_mut(t - 1).and_then(Option::take).ok_or(leleka_cuda_driver::Error::InvalidQwenShape), + commit, + ); + let (capture_ms, instantiate_ms, modules_ms) = leleka_cuda_driver::original_capture_timing::take(); + super::original_serve_profile::add("record.capture", capture_ms); + super::original_serve_profile::add("record.instantiate", instantiate_ms); + super::original_serve_profile::add("record.modules", modules_ms); + if let Err(error) = recorded { + // dropping the unused aggregates and closing the verifier releases every journal reference + drop(windows); + let _ = verifier.close(); + window_cap = window_cap_after(&error, max_t); + return Err(error.into()); + } + Ok(verifier) + })(); + drop(canonical); + match recorded { + Ok(verifier) => Ok(DecodeResources { verifier, qsa, slots }), + Err(failure) => { + // every aggregate is gone: the journal can give the owners back + let owners = recover(qsa, slots); + // a retry needs the owners back + let window_cap = window_cap.filter(|_| owners.is_some()); + Err(AssembleFailure { failure, owners, window_cap }) + } + } +} + +/// `OriginalQsaMappedJournal::ensure_resolver` on every handed-over layer (a no-op for a layer the prompt +/// already appended to). +fn ensure_resolvers<'ctx>( + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + context: &'ctx Context<'ctx>, + owners: &mut QsaOwners<'ctx>, +) -> std::result::Result<(), ServeFailure> { + if owners.iter().flatten().all(|(_, kv)| kv.resolver_ready()) { + return Ok(()); + } + let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + for (_, kv) in owners.iter_mut().flatten() { + kv.ensure_resolver(&mut workspace)?; + } + Ok(()) +} + +/// Close the verifier (drains both streams, drops every graph and aggregate) and take the physical QSA +/// owners back from the journal. +pub(in crate::qwen_forward) fn disassemble<'a, 'ctx>( + resources: DecodeResources<'a, 'ctx>, +) -> std::result::Result, ServeFailure> { + let DecodeResources { verifier, qsa, slots } = resources; + let closed = verifier.close(); + let recovered = recover(qsa, slots); + match (closed, recovered) { + (Ok(()), Some(owners)) => Ok(owners), + (Err(error), _) => Err(error.into()), + (Ok(()), None) => Err(Error::IdentityMismatch.into()), + } +} + +fn recover<'a, 'ctx>(qsa: Rc>, slots: [usize; 12]) -> Option> { + let (indices, mapped) = OriginalVerifyQsaJournal::into_owners(qsa).ok()?; + let mut owners: QsaOwners<'ctx> = std::array::from_fn(|_| None); + for ((slot, index), kv) in slots.into_iter().zip(indices).zip(mapped) { + *owners.get_mut(slot)? = Some((index, kv)); + } + Some(owners) +} + +#[cfg(test)] +mod tests { + use super::*; + use leleka_cuda_driver::Error as D; + + #[test] + fn a_graph_out_of_memory_names_the_widest_window_worth_recording() { + // window T=6 of 8 did not fit: 1..=5 were recorded and fit + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 6 }, 8), Some(5)); + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 3 }, 8), Some(2)); + // the commit graph (window 0) is recorded after every window: the widest window goes + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 8), Some(7)); + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 4), Some(3)); + // nothing wide enough is left (a width of one is no speculation), and a window past max_t is clamped + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 2 }, 8), None); + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 1 }, 8), None); + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 2), None); + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 9 }, 4), Some(3)); + // every other failure, including a plain out-of-memory the driver did not classify, is not retried + for other in [D::HostAllocation, D::ContextPoisoned, D::InvalidQwenShape, D::Driver { operation: "cuGraphInstantiateWithFlags", code: 2 }] { + assert_eq!(window_cap_after(&other, 8), None, "{other:?}"); + } + assert!(ServeFailure::from(D::GraphOutOfMemory { window: 6 }).describe().contains("T=6")); + } + + #[test] + fn the_assembly_is_repeated_with_narrower_windows_until_one_fits() { + // 8 and 6 do not fit, 5 does + let mut tried = Vec::new(); + let mut notes = Vec::new(); + let (used, outcome) = assemble_with_window_fallback( + 8, + |t| { + tried.push(t); + match t { + 8 => Err(("oom at 8", window_cap_after(&D::GraphOutOfMemory { window: 7 }, t))), + 6 => Err(("oom at 6", window_cap_after(&D::GraphOutOfMemory { window: 0 }, t))), + t => Ok(t * 10), + } + }, + |failed, next| notes.push((failed, next)), + ); + assert_eq!((used, outcome), (5, Ok(50))); + assert_eq!(tried, [8, 6, 5]); + assert_eq!(notes, [(8, 6), (6, 5)]); + // it fits at once: one attempt, nothing noted + let mut calls = 0; + let (used, outcome) = assemble_with_window_fallback::<_, &str>(8, |t| { calls += 1; Ok(t) }, |_, _| panic!("no retry")); + assert_eq!((used, outcome, calls), (8, Ok(8), 1)); + } + + #[test] + fn the_fallback_stops_at_the_floor_on_any_other_failure_and_never_loops() { + // nothing fits down to the floor: the last failure comes back, with the width it was tried at + let (used, outcome) = assemble_with_window_fallback::<(), _>( + 8, + |t| Err((format!("oom at {t}"), window_cap_after(&D::GraphOutOfMemory { window: t }, t))), + |_, _| {}, + ); + assert_eq!((used, outcome), (2, Err("oom at 2".to_string()))); + // a failure that is not an out-of-memory is returned at once, with no retry + let mut calls = 0; + let (used, outcome) = assemble_with_window_fallback::<(), _>(8, |_| { calls += 1; Err(("broken", None)) }, |_, _| panic!("no retry")); + assert_eq!((used, outcome, calls), (8, Err("broken"), 1)); + // a cap that does not narrow the window (a bug somewhere) is not followed + let (used, outcome) = assemble_with_window_fallback::<(), _>(4, |_| Err(("same", Some(4))), |_, _| panic!("no retry")); + assert_eq!((used, outcome), (4, Err("same"))); + } + + #[test] + fn driver_refusals_keep_their_words_and_a_stable_class() { + let unbound = leleka_cuda_driver::Error::InvalidDriverValue("Original verifier producer unbound: router"); + let failure = ServeFailure::from(unbound); + assert_eq!(failure.error, Error::Unsupported(Stage::Executor)); + assert_eq!(failure.detail.as_deref(), Some("Original verifier producer unbound: router")); + assert!(failure.describe().contains("router")); + let sealed = ServeFailure::from(leleka_cuda_driver::Error::UnsupportedQwenOperation); + assert_eq!(sealed.error, Error::Unsupported(Stage::Session)); + assert!(sealed.detail.as_deref().is_some_and(|d| d.contains("unsealed"))); + let plain = ServeFailure::from(leleka_cuda_driver::Error::ContextMismatch); + assert_eq!((plain.error, plain.detail), (Error::IdentityMismatch, None)); + assert_eq!(ServeFailure::from(Error::NonFinite).describe(), "NonFinite"); + } + + #[test] + fn the_ple_history_image_is_nine_slots_of_the_channel_width() { + assert_eq!(PLE_HISTORY_VALUES, 92_160); + assert_eq!(PLE_HISTORY_BYTES, 368_640); + } +} diff --git a/crates/model-format/src/ple_reader.rs b/crates/model-format/src/ple_reader.rs index 59e57f9d..82e2c6d1 100644 --- a/crates/model-format/src/ple_reader.rs +++ b/crates/model-format/src/ple_reader.rs @@ -1,890 +1,890 @@ -//! Asynchronous row reader for the per-layer n-gram (PLE) table, port of -//! `ngram/ple_reader.{hpp,cpp}` over `std` positional reads. -//! -//! The table is 320,001,536 rows of 90 bytes (IQ4_NL, 26.8 GiB) and never -//! lives in RAM. A token needs 16 rows on 16 different pages, all derived from -//! the token itself, so the only time to hide the reads is the embedding plus -//! layer 0; hence the split API: -//! -//! ```text -//! let ticket = reader.issue(&rows); // as soon as the token id is known -//! ... // embedding, layer 0 -//! let bytes = reader.collect(ticket)?; // before layer 1 reads the rows -//! ``` -//! -//! `issue` also serves prefill: pass all `16 x N` rows of a chunk. Rows are -//! served from the row cache when possible, the rest are grouped by 4 KiB page -//! (rows sharing a page share one read; a row straddling a page boundary reads -//! two pages), the reads are sorted by offset so a chunk reads the SSD in -//! near-sequential order, and a pool of I/O threads keeps at most -//! `max_inflight` of them outstanding. -//! -//! The row cache is not the table. It keeps rows this process already fetched -//! (8-way set associative, round-robin inside a set, bounded by construction; -//! capacity 0 disables it). -//! -//! Safety properties kept from the original: an out-of-range row reads as zero -//! bytes (the mmap path's behaviour); a short read inside the table, a failed -//! read or a source whose size changed is an error that sticks to the reader -//! (every later `collect` fails). Unsafe code is forbidden workspace-wide, so -//! reads go through [`PageSource`] (`pread` via `std`), and O_DIRECT, when -//! wanted, is the source's business: the reader always reads 4 KiB-aligned -//! offsets and lengths into 4 KiB-aligned buffers, as an unbuffered file -//! requires. - -use std::collections::{HashMap, VecDeque}; -use std::fmt; -use std::fs::File; -use std::io; -use std::sync::{Arc, Condvar, Mutex, MutexGuard}; -use std::thread::{self, JoinHandle}; -use std::time::{Duration, Instant}; - -/// An IQ4_NL row; `open` takes the table's own row size. -pub const ROW_BYTES: usize = 90; -pub const PAGE: usize = 4096; -const WAYS: usize = 8; -const EMPTY: u32 = 0xFFFF_FFFF; -const LATENCY_RING: usize = 65536; -const DEFAULT_IO_THREADS: usize = 16; - -/// A positional-read file. Reads may be short only at end of file. -pub trait PageSource: Send + Sync + 'static { - fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result; - /// Current length of the underlying file, for the size-unchanged check. - fn len(&self) -> io::Result; - fn is_empty(&self) -> io::Result { - Ok(self.len()? == 0) - } -} - -impl PageSource for File { - fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result { - #[cfg(unix)] - { - std::os::unix::fs::FileExt::read_at(self, buf, offset) - } - #[cfg(windows)] - { - std::os::windows::fs::FileExt::seek_read(self, buf, offset) - } - #[cfg(not(any(unix, windows)))] - { - let _ = (buf, offset); - Err(io::Error::new( - io::ErrorKind::Unsupported, - "positional reads unavailable", - )) - } - } - - fn len(&self) -> io::Result { - Ok(self.metadata()?.len()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PleError(pub String); - -impl fmt::Display for PleError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.0) - } -} -impl std::error::Error for PleError {} - -fn err(message: impl Into) -> Result { - Err(PleError(format!("PleReader: {}", message.into()))) -} - -#[derive(Clone, Debug)] -pub struct PleReaderConfig { - /// Byte offset of row 0 in the file. - pub table_offset: u64, - pub n_rows: u64, - /// One row's size in the file (90 IQ4_NL, 160 FP8), at most one page. - pub row_bytes: usize, - /// Reads outstanding at once, 1..=1024. - pub max_inflight: usize, - /// Row cache capacity in rows (rounded down to whole 8-row sets); 0 disables. - pub cache_rows: u64, - /// I/O threads; `None` picks `min(max_inflight, 16)`, `Some(0)` runs every - /// read on the thread that calls `collect` (no workers, no keep-alive). - pub io_threads: Option, - /// Required length of the source; a different length at `collect` is an error. - pub expected_len: Option, -} - -impl PleReaderConfig { - pub fn new(table_offset: u64, n_rows: u64) -> Self { - Self { - table_offset, - n_rows, - row_bytes: ROW_BYTES, - max_inflight: 64, - cache_rows: 0, - io_threads: None, - expected_len: None, - } - } -} - -#[derive(Clone, Debug, Default)] -pub struct ReaderStats { - /// Rows asked for. - pub requests: u64, - /// Rows served from the row cache. - pub cache_hits: u64, - /// Rows that shared a page already being read in the same ticket. - pub dedup_rows: u64, - /// SSD read requests issued. - pub reads: u64, - /// Bytes read from the SSD. - pub bytes: u64, - /// Time `collect` spent blocked, microseconds. - pub wait_us: f64, - /// Sum of per-read latencies (issue to completion), microseconds. - pub read_us_sum: f64, - /// Reads delayed by fault injection. - pub late_injected: u64, - /// Pages read only to keep the SSD awake (not in `reads`, `bytes` or latencies). - pub keepalive_reads: u64, - /// The slowest of them, microseconds. - pub keepalive_us_max: f64, - /// Last <= 65,536 read latencies, for percentiles. - pub read_us: Vec, -} - -impl ReaderStats { - pub fn percentile(&self, q: f64) -> f64 { - if self.read_us.is_empty() { - return 0.0; - } - let mut v = self.read_us.clone(); - let k = ((q * (v.len() - 1) as f64 + 0.5) as usize).min(v.len() - 1); - v.select_nth_unstable_by(k, f32::total_cmp); - f64::from(v[k]) - } -} - -/// Set-associative row cache: 8 ways per set, round-robin replacement inside a -/// set. Bounded by construction. -#[derive(Debug, Default)] -pub struct RowCache { - sets: u64, - rb: usize, - keys: Vec, - data: Vec, - next: Vec, - used: u64, -} - -impl RowCache { - pub fn new(rows: u64, row_bytes: usize) -> Self { - let sets = rows / WAYS as u64; - let slots = (sets as usize) * WAYS; - Self { - sets, - rb: row_bytes, - keys: vec![EMPTY; slots], - data: vec![0; slots * row_bytes], - next: vec![0; sets as usize], - used: 0, - } - } - - fn mix(row: u32) -> u64 { - let x = u64::from(row).wrapping_mul(0x9E37_79B9_7F4A_7C15); - x ^ (x >> 29) - } - - pub fn capacity(&self) -> u64 { - self.sets * WAYS as u64 - } - - pub fn len(&self) -> u64 { - self.used - } - - pub fn is_empty(&self) -> bool { - self.used == 0 - } - - pub fn find(&self, row: u32) -> Option<&[u8]> { - if self.sets == 0 { - return None; - } - let s = (Self::mix(row) % self.sets) as usize; - (0..WAYS) - .find(|&w| self.keys[s * WAYS + w] == row) - .map(|w| { - let at = (s * WAYS + w) * self.rb; - &self.data[at..at + self.rb] - }) - } - - pub fn insert(&mut self, row: u32, bytes: &[u8]) { - if self.sets == 0 || self.find(row).is_some() { - return; - } - debug_assert_eq!(bytes.len(), self.rb); - let s = (Self::mix(row) % self.sets) as usize; - let w = usize::from(self.next[s]); - self.next[s] = ((w + 1) % WAYS) as u8; - if self.keys[s * WAYS + w] == EMPTY { - self.used += 1; - } - self.keys[s * WAYS + w] = row; - let at = (s * WAYS + w) * self.rb; - self.data[at..at + self.rb].copy_from_slice(bytes); - } -} - -/// One row inside a read. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Use { - pub row: u32, - /// Byte offset of the row inside the read buffer. - pub in_page: usize, - /// Row slot in the ticket's output. - pub slot: usize, -} - -/// One read: an aligned file offset and one or two pages. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PlannedRead { - pub offset: u64, - pub length: usize, - pub uses: Vec, -} - -/// Plan the reads of a ticket exactly as `PleReader::issue` does: cache hits -/// and out-of-range rows are resolved into `out` immediately, the rest are -/// grouped by first page (a later row on the page may widen the read to two -/// pages) and sorted by offset. -pub fn plan_reads( - rows: &[u32], - cfg: &PleReaderConfig, - cache: &RowCache, - out: &mut [u8], - stats: &mut ReaderStats, -) -> Vec { - let rb = cfg.row_bytes; - let mut by_page: HashMap = HashMap::new(); - let mut jobs: Vec = Vec::new(); - for (i, &row) in rows.iter().enumerate() { - let dst = &mut out[i * rb..(i + 1) * rb]; - stats.requests += 1; - if u64::from(row) >= cfg.n_rows { - dst.fill(0); - continue; - } - if let Some(hit) = cache.find(row) { - dst.copy_from_slice(hit); - stats.cache_hits += 1; - continue; - } - let at = cfg.table_offset + u64::from(row) * rb as u64; - let first = at / PAGE as u64 * PAGE as u64; - let length = ((at + rb as u64 - 1) / PAGE as u64 * PAGE as u64 - first) as usize + PAGE; - let used = Use { - row, - in_page: (at - first) as usize, - slot: i, - }; - if let Some(&j) = by_page.get(&first) { - jobs[j].length = jobs[j].length.max(length); - jobs[j].uses.push(used); - stats.dedup_rows += 1; - } else { - by_page.insert(first, jobs.len()); - jobs.push(PlannedRead { - offset: first, - length, - uses: vec![used], - }); - } - } - // Sorted by offset: prefill chunks then read the SSD in near-sequential order. - jobs.sort_by_key(|job| job.offset); - jobs -} - -struct Job { - read: PlannedRead, - ticket: u32, - keepalive: bool, -} - -struct TicketState { - pending: usize, - out: Vec, -} - -#[derive(Default)] -struct KeepAlive { - period: Duration, - window: Duration, - last_issue: Option, - last_read: Option, - rng: u64, -} - -struct State { - queue: VecDeque, - tickets: HashMap, - next_ticket: u32, - cache: RowCache, - stats: ReaderStats, - ring_pos: usize, - delay: Duration, - error: Option, - stop: bool, - inflight: usize, - keep: KeepAlive, -} - -struct Shared { - source: Arc, - cfg: PleReaderConfig, - inline: bool, - state: Mutex, - work: Condvar, - done: Condvar, - keep_cv: Condvar, -} - -fn lock(m: &Mutex) -> MutexGuard<'_, State> { - // A panicking worker must not wedge the reader: the data is still coherent - // (every mutation is completed before the lock is released) and the error - // path reports failures through `State::error`. - m.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) -} - -/// Heap buffer whose usable window starts on a 4 KiB boundary, for unbuffered sources. -struct AlignedBuf { - raw: Vec, - start: usize, - len: usize, -} - -impl AlignedBuf { - fn new(len: usize) -> Self { - let raw = vec![0u8; len + PAGE]; - let start = (PAGE - raw.as_ptr() as usize % PAGE) % PAGE; - Self { raw, start, len } - } - fn window(&mut self, len: usize) -> &mut [u8] { - &mut self.raw[self.start..self.start + len.min(self.len)] - } -} - -/// Whether `source` serves one page-aligned page read at the page holding -/// `offset`, through a 4 KiB-aligned buffer. Used to accept an unbuffered -/// (O_DIRECT) handle only once it demonstrably works on this filesystem. -pub fn probe_aligned_read(source: &dyn PageSource, offset: u64) -> bool { - let mut buf = AlignedBuf::new(PAGE); - let page = offset / PAGE as u64 * PAGE as u64; - matches!(read_full_at(source, buf.window(PAGE), page), Ok(n) if n > 0) -} - -fn read_full_at(source: &dyn PageSource, buf: &mut [u8], offset: u64) -> io::Result { - let mut total = 0; - while total < buf.len() { - match source.read_at(&mut buf[total..], offset + total as u64) { - Ok(0) => break, - Ok(n) => total += n, - Err(e) if e.kind() == io::ErrorKind::Interrupted => {} - Err(e) => return Err(e), - } - } - Ok(total) -} - -impl State { - fn record_latency(&mut self, us: f64) { - self.stats.read_us_sum += us; - if self.stats.read_us.len() < LATENCY_RING { - self.stats.read_us.push(us as f32); - } else { - self.stats.read_us[self.ring_pos % LATENCY_RING] = us as f32; - self.ring_pos += 1; - } - } - - /// A job that will never run: its ticket no longer waits for it. - fn cancel_queued(&mut self) { - let queued: Vec = self.queue.drain(..).collect(); - for job in queued { - self.release(job.ticket); - } - } - - fn release(&mut self, ticket: u32) { - if let Some(t) = self.tickets.get_mut(&ticket) { - t.pending = t.pending.saturating_sub(1); - } - } - - fn fail(&mut self, message: &str) { - if self.error.is_none() { - self.error = Some(PleError(format!("PleReader: {message}"))); - } - self.cancel_queued(); - } - - /// When the next keep-alive read is due, or `None` when none is: it is off, - /// the reader failed, or no rows were asked for within the window (the SSD - /// may then sleep; the next `issue` re-arms it). - fn keepalive_due(&self, now: Instant) -> Option { - let k = &self.keep; - let issued = k.last_issue?; - if k.period.is_zero() || self.error.is_some() || now.duration_since(issued) > k.window { - return None; - } - Some(k.last_read.unwrap_or(issued) + k.period) - } -} - -impl Shared { - /// Run one job: the read happens outside the lock. - fn run(&self, job: Job, issued: Instant, delay: Duration) { - let mut buf = AlignedBuf::new(2 * PAGE); - let length = job.read.length; - // A source that panics is a failed read like any other: the worker survives, the reader fails and every ticket is released. - // Unwinding past this point would end the worker with the job's ticket still pending, and its `collect` would wait for ever. - let read = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - read_full_at(self.source.as_ref(), buf.window(length), job.read.offset) - })) - .unwrap_or_else(|_| Err(io::Error::other("the page source panicked"))); - let mut late = false; - if !delay.is_zero() { - let spent = issued.elapsed(); - if spent < delay { - late = true; - thread::sleep(delay - spent); - } - } - let mut st = lock(&self.state); - st.inflight -= 1; - if late { - st.stats.late_injected += 1; - } - let elapsed_us = issued.elapsed().as_secs_f64() * 1e6; - if job.keepalive { - // A failed keep-alive turns the keep-alive off, not the reader. - match read { - Ok(_) => { - st.stats.keepalive_reads += 1; - st.stats.keepalive_us_max = st.stats.keepalive_us_max.max(elapsed_us); - } - Err(_) => st.keep.period = Duration::ZERO, - } - drop(st); - self.work.notify_all(); - self.done.notify_all(); - return; - } - match read { - Err(e) => { - st.fail(&format!("a table read failed ({e})")); - st.release(job.ticket); - } - Ok(bytes) => { - st.record_latency(elapsed_us); - st.stats.bytes += bytes as u64; - let rb = self.cfg.row_bytes; - if job.read.uses.iter().any(|u| u.in_page + rb > bytes) { - st.fail("short read inside the table"); - st.release(job.ticket); - } else { - let data = buf.window(length); - for u in &job.read.uses { - let row = &data[u.in_page..u.in_page + rb]; - if let Some(t) = st.tickets.get_mut(&job.ticket) { - t.out[u.slot * rb..(u.slot + 1) * rb].copy_from_slice(row); - } - st.cache.insert(u.row, row); - } - st.release(job.ticket); - } - } - } - drop(st); - self.work.notify_all(); - self.done.notify_all(); - } - - /// Take the next job (marking it in flight) or `None` when there is none. - fn start(&self, st: &mut State) -> Option<(Job, Instant, Duration)> { - let job = st.queue.pop_front()?; - let now = Instant::now(); - st.inflight += 1; - st.keep.last_read = Some(now); - if !job.keepalive { - st.stats.reads += 1; - } - Some((job, now, st.delay)) - } - - fn worker(self: &Arc) { - loop { - let started = { - let mut st = lock(&self.state); - loop { - if st.stop && st.queue.is_empty() { - return; - } - if let Some(started) = self.start(&mut st) { - break started; - } - st = self.work.wait(st).unwrap_or_else(|p| p.into_inner()); - } - }; - self.run(started.0, started.1, started.2); - } - } - - fn keepalive_worker(self: &Arc) { - let mut st = lock(&self.state); - while !st.stop { - let now = Instant::now(); - match st.keepalive_due(now) { - None => st = self.keep_cv.wait(st).unwrap_or_else(|p| p.into_inner()), - Some(due) if now >= due => { - if st.queue.is_empty() && st.inflight == 0 { - // One page of the table, a different one each time, so the - // SSD really reads (not its controller's buffer). - st.keep.rng ^= st.keep.rng << 13; - st.keep.rng ^= st.keep.rng >> 7; - st.keep.rng ^= st.keep.rng << 17; - let first = self.cfg.table_offset / PAGE as u64; - let end = (self.cfg.table_offset - + self.cfg.n_rows * self.cfg.row_bytes as u64) - / PAGE as u64; - let page = first - + if end > first { - st.keep.rng % (end - first) - } else { - 0 - }; - st.queue.push_back(Job { - read: PlannedRead { - offset: page * PAGE as u64, - length: PAGE, - uses: Vec::new(), - }, - ticket: 0, - keepalive: true, - }); - self.work.notify_one(); - } - // Re-evaluate after the period (or when woken). - let wait = st.keep.period.max(Duration::from_millis(1)); - st = self - .keep_cv - .wait_timeout(st, wait) - .unwrap_or_else(|p| p.into_inner()) - .0; - } - Some(due) => { - let wait = (due - now).max(Duration::from_millis(1)); - st = self - .keep_cv - .wait_timeout(st, wait) - .unwrap_or_else(|p| p.into_inner()) - .0; - } - } - } - } -} - -/// Handle to a ticket issued by [`PleReader::issue`]. Dropping it without -/// collecting abandons the rows (reads in flight still warm the cache). -pub struct Ticket { - id: u32, - shared: Arc, -} - -impl Drop for Ticket { - fn drop(&mut self) { - lock(&self.shared.state).tickets.remove(&self.id); - } -} - -pub struct PleReader { - shared: Arc, - workers: Vec>, - keepalive: Option>, -} - -impl PleReader { - /// `source` is the table's file. The table must fit exactly in it from - /// `table_offset` (the caller's GGUF parse checks that; the length is - /// checked here too). - pub fn open(source: Arc, cfg: PleReaderConfig) -> Result { - if cfg.max_inflight == 0 || cfg.max_inflight > 1024 { - return err("max_inflight must be 1..1024"); - } - if cfg.row_bytes == 0 || cfg.row_bytes > PAGE { - return err("row_bytes must be 1..4096"); - } - if cfg.n_rows > u64::from(EMPTY) { - return err("the row count exceeds the 32-bit row index"); - } - let table_end = cfg - .n_rows - .checked_mul(cfg.row_bytes as u64) - .and_then(|bytes| bytes.checked_add(cfg.table_offset)); - let len = source - .len() - .map_err(|e| PleError(format!("PleReader: cannot size the table file ({e})")))?; - if table_end.is_none_or(|end| end > len) { - return err("the table extends past the end of the file"); - } - if cfg.expected_len.is_some_and(|expected| expected != len) { - return err("the table file changed size after verification"); - } - let threads = match cfg.io_threads { - None => cfg.max_inflight.min(DEFAULT_IO_THREADS), - Some(n) => n.min(cfg.max_inflight), - }; - let seed = 0x9E37_79B9_7F4A_7C15 - ^ std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(1, |d| d.as_micros() as u64); - let state = State { - queue: VecDeque::new(), - tickets: HashMap::new(), - next_ticket: 1, - cache: RowCache::new(cfg.cache_rows, cfg.row_bytes), - stats: ReaderStats::default(), - ring_pos: 0, - delay: Duration::ZERO, - error: None, - stop: false, - inflight: 0, - keep: KeepAlive { - rng: if seed == 0 { 1 } else { seed }, - ..KeepAlive::default() - }, - }; - let shared = Arc::new(Shared { - source, - inline: threads == 0, - cfg, - state: Mutex::new(state), - work: Condvar::new(), - done: Condvar::new(), - keep_cv: Condvar::new(), - }); - let mut reader = Self { - shared: Arc::clone(&shared), - workers: Vec::new(), - keepalive: None, - }; - for index in 0..threads { - let worker = Arc::clone(&shared); - let spawned = thread::Builder::new() - .name(format!("ple-reader-{index}")) - .spawn(move || worker.worker()); - match spawned { - Ok(handle) => reader.workers.push(handle), - Err(e) => return err(format!("cannot create I/O worker: {e}")), - } - } - Ok(reader) - } - - pub fn row_bytes(&self) -> usize { - self.shared.cfg.row_bytes - } - - pub fn rows(&self) -> u64 { - self.shared.cfg.n_rows - } - - /// Start fetching `rows`; row `i`'s raw bytes land at `row_bytes * i` of - /// the buffer `collect` returns. Out-of-range rows produce zero bytes. - pub fn issue(&self, rows: &[u32]) -> Ticket { - let shared = &self.shared; - let rb = shared.cfg.row_bytes; - let mut st = lock(&shared.state); - let id = st.next_ticket; - st.next_ticket = st.next_ticket.wrapping_add(1).max(1); - let now = Instant::now(); - let rearm = !st.keep.period.is_zero() - && st - .keep - .last_issue - .is_none_or(|last| now.duration_since(last) > st.keep.window); - st.keep.last_issue = Some(now); - let mut out = vec![0u8; rows.len() * rb]; - let State { cache, stats, .. } = &mut *st; - let reads = plan_reads(rows, &shared.cfg, cache, &mut out, stats); - let mut pending = reads.len(); - if st.error.is_some() { - pending = 0; // the reader failed: `collect` reports it, nothing is queued - } else { - for read in reads { - st.queue.push_back(Job { - read, - ticket: id, - keepalive: false, - }); - } - } - st.tickets.insert(id, TicketState { pending, out }); - drop(st); - if pending > 0 { - shared.work.notify_all(); - } - if rearm || pending > 0 { - shared.keep_cv.notify_all(); - } - Ticket { - id, - shared: Arc::clone(shared), - } - } - - /// Block until every row of the ticket is in the returned buffer. - pub fn collect(&self, ticket: Ticket) -> Result, PleError> { - let shared = &self.shared; - if !Arc::ptr_eq(&ticket.shared, shared) { - return err("ticket from another reader"); - } - let start = Instant::now(); - let mut st = lock(&shared.state); - if !st.tickets.contains_key(&ticket.id) { - return err("unknown ticket"); - } - loop { - let pending = st.tickets.get(&ticket.id).map_or(0, |t| t.pending); - if pending == 0 { - break; - } - if shared.inline { - // No workers: this thread performs the reads itself. - if let Some((job, issued, delay)) = shared.start(&mut st) { - drop(st); - shared.run(job, issued, delay); - st = lock(&shared.state); - continue; - } - } - st = shared.done.wait(st).unwrap_or_else(|p| p.into_inner()); - } - if let Some(e) = st.error.clone() { - return Err(e); - } - st.stats.wait_us += start.elapsed().as_secs_f64() * 1e6; - let out = st.tickets.remove(&ticket.id).map(|t| t.out); - drop(st); - // The same-FD size observation the verified GGUF reader makes around its streams. - if let Some(expected) = shared.cfg.expected_len { - match shared.source.len() { - Ok(len) if len == expected => {} - _ => { - let mut st = lock(&shared.state); - st.fail("the table file changed size after verification"); - return Err(st - .error - .clone() - .unwrap_or_else(|| PleError("PleReader: size check failed".into()))); - } - } - } - out.ok_or_else(|| PleError("PleReader: unknown ticket".into())) - } - - /// `issue` then `collect`. - pub fn read_rows(&self, rows: &[u32]) -> Result, PleError> { - self.collect(self.issue(rows)) - } - - /// Keep the SSD awake while the table is in use (worker mode only; call - /// after `open`): when no read has gone out for `period`, one page of the - /// table is read, until `window` after the last `issue`. A keep-alive read - /// that fails turns it off. A zero period turns it off. - pub fn set_keepalive(&mut self, period: Duration, window: Duration) { - let threaded = !self.shared.inline; - { - let mut st = lock(&self.shared.state); - st.keep.period = if threaded { period } else { Duration::ZERO }; - st.keep.window = window; - } - if threaded && !period.is_zero() && self.keepalive.is_none() { - let worker = Arc::clone(&self.shared); - if let Ok(handle) = thread::Builder::new() - .name("ple-reader-keepalive".into()) - .spawn(move || worker.keepalive_worker()) - { - self.keepalive = Some(handle); - } - } - self.shared.keep_cv.notify_all(); - } - - /// Fault injection for tests and for the plan's P2 exit check: every read - /// completes no earlier than `delay` after it was issued. Zero disables. - pub fn set_injected_delay(&self, delay: Duration) { - lock(&self.shared.state).delay = delay; - } - - /// A consistent copy of the counters. - pub fn snapshot(&self) -> ReaderStats { - lock(&self.shared.state).stats.clone() - } - - pub fn reset_stats(&self) { - let mut st = lock(&self.shared.state); - st.stats = ReaderStats::default(); - st.ring_pos = 0; - } - - pub fn cache_capacity(&self) -> u64 { - lock(&self.shared.state).cache.capacity() - } - - pub fn cache_size(&self) -> u64 { - lock(&self.shared.state).cache.len() - } - - /// Stop the workers (unsubmitted work is dropped, reads in flight finish). - pub fn close(&mut self) { - { - let mut st = lock(&self.shared.state); - st.stop = true; - st.cancel_queued(); - } - self.shared.work.notify_all(); - self.shared.keep_cv.notify_all(); - self.shared.done.notify_all(); - for handle in self.workers.drain(..) { - let _ = handle.join(); - } - if let Some(handle) = self.keepalive.take() { - let _ = handle.join(); - } - } -} - -impl fmt::Debug for PleReader { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("PleReader") - .field("rows", &self.shared.cfg.n_rows) - .field("workers", &self.workers.len()) - .finish() - } -} - -impl Drop for PleReader { - fn drop(&mut self) { - self.close(); - } -} - -#[cfg(test)] -mod tests; +//! Asynchronous row reader for the per-layer n-gram (PLE) table, port of +//! `ngram/ple_reader.{hpp,cpp}` over `std` positional reads. +//! +//! The table is 320,001,536 rows of 90 bytes (IQ4_NL, 26.8 GiB) and never +//! lives in RAM. A token needs 16 rows on 16 different pages, all derived from +//! the token itself, so the only time to hide the reads is the embedding plus +//! layer 0; hence the split API: +//! +//! ```text +//! let ticket = reader.issue(&rows); // as soon as the token id is known +//! ... // embedding, layer 0 +//! let bytes = reader.collect(ticket)?; // before layer 1 reads the rows +//! ``` +//! +//! `issue` also serves prefill: pass all `16 x N` rows of a chunk. Rows are +//! served from the row cache when possible, the rest are grouped by 4 KiB page +//! (rows sharing a page share one read; a row straddling a page boundary reads +//! two pages), the reads are sorted by offset so a chunk reads the SSD in +//! near-sequential order, and a pool of I/O threads keeps at most +//! `max_inflight` of them outstanding. +//! +//! The row cache is not the table. It keeps rows this process already fetched +//! (8-way set associative, round-robin inside a set, bounded by construction; +//! capacity 0 disables it). +//! +//! Safety properties kept from the original: an out-of-range row reads as zero +//! bytes (the mmap path's behaviour); a short read inside the table, a failed +//! read or a source whose size changed is an error that sticks to the reader +//! (every later `collect` fails). Unsafe code is forbidden workspace-wide, so +//! reads go through [`PageSource`] (`pread` via `std`), and O_DIRECT, when +//! wanted, is the source's business: the reader always reads 4 KiB-aligned +//! offsets and lengths into 4 KiB-aligned buffers, as an unbuffered file +//! requires. + +use std::collections::{HashMap, VecDeque}; +use std::fmt; +use std::fs::File; +use std::io; +use std::sync::{Arc, Condvar, Mutex, MutexGuard}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +/// An IQ4_NL row; `open` takes the table's own row size. +pub const ROW_BYTES: usize = 90; +pub const PAGE: usize = 4096; +const WAYS: usize = 8; +const EMPTY: u32 = 0xFFFF_FFFF; +const LATENCY_RING: usize = 65536; +const DEFAULT_IO_THREADS: usize = 16; + +/// A positional-read file. Reads may be short only at end of file. +pub trait PageSource: Send + Sync + 'static { + fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result; + /// Current length of the underlying file, for the size-unchanged check. + fn len(&self) -> io::Result; + fn is_empty(&self) -> io::Result { + Ok(self.len()? == 0) + } +} + +impl PageSource for File { + fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result { + #[cfg(unix)] + { + std::os::unix::fs::FileExt::read_at(self, buf, offset) + } + #[cfg(windows)] + { + std::os::windows::fs::FileExt::seek_read(self, buf, offset) + } + #[cfg(not(any(unix, windows)))] + { + let _ = (buf, offset); + Err(io::Error::new( + io::ErrorKind::Unsupported, + "positional reads unavailable", + )) + } + } + + fn len(&self) -> io::Result { + Ok(self.metadata()?.len()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PleError(pub String); + +impl fmt::Display for PleError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} +impl std::error::Error for PleError {} + +fn err(message: impl Into) -> Result { + Err(PleError(format!("PleReader: {}", message.into()))) +} + +#[derive(Clone, Debug)] +pub struct PleReaderConfig { + /// Byte offset of row 0 in the file. + pub table_offset: u64, + pub n_rows: u64, + /// One row's size in the file (90 IQ4_NL, 160 FP8), at most one page. + pub row_bytes: usize, + /// Reads outstanding at once, 1..=1024. + pub max_inflight: usize, + /// Row cache capacity in rows (rounded down to whole 8-row sets); 0 disables. + pub cache_rows: u64, + /// I/O threads; `None` picks `min(max_inflight, 16)`, `Some(0)` runs every + /// read on the thread that calls `collect` (no workers, no keep-alive). + pub io_threads: Option, + /// Required length of the source; a different length at `collect` is an error. + pub expected_len: Option, +} + +impl PleReaderConfig { + pub fn new(table_offset: u64, n_rows: u64) -> Self { + Self { + table_offset, + n_rows, + row_bytes: ROW_BYTES, + max_inflight: 64, + cache_rows: 0, + io_threads: None, + expected_len: None, + } + } +} + +#[derive(Clone, Debug, Default)] +pub struct ReaderStats { + /// Rows asked for. + pub requests: u64, + /// Rows served from the row cache. + pub cache_hits: u64, + /// Rows that shared a page already being read in the same ticket. + pub dedup_rows: u64, + /// SSD read requests issued. + pub reads: u64, + /// Bytes read from the SSD. + pub bytes: u64, + /// Time `collect` spent blocked, microseconds. + pub wait_us: f64, + /// Sum of per-read latencies (issue to completion), microseconds. + pub read_us_sum: f64, + /// Reads delayed by fault injection. + pub late_injected: u64, + /// Pages read only to keep the SSD awake (not in `reads`, `bytes` or latencies). + pub keepalive_reads: u64, + /// The slowest of them, microseconds. + pub keepalive_us_max: f64, + /// Last <= 65,536 read latencies, for percentiles. + pub read_us: Vec, +} + +impl ReaderStats { + pub fn percentile(&self, q: f64) -> f64 { + if self.read_us.is_empty() { + return 0.0; + } + let mut v = self.read_us.clone(); + let k = ((q * (v.len() - 1) as f64 + 0.5) as usize).min(v.len() - 1); + v.select_nth_unstable_by(k, f32::total_cmp); + f64::from(v[k]) + } +} + +/// Set-associative row cache: 8 ways per set, round-robin replacement inside a +/// set. Bounded by construction. +#[derive(Debug, Default)] +pub struct RowCache { + sets: u64, + rb: usize, + keys: Vec, + data: Vec, + next: Vec, + used: u64, +} + +impl RowCache { + pub fn new(rows: u64, row_bytes: usize) -> Self { + let sets = rows / WAYS as u64; + let slots = (sets as usize) * WAYS; + Self { + sets, + rb: row_bytes, + keys: vec![EMPTY; slots], + data: vec![0; slots * row_bytes], + next: vec![0; sets as usize], + used: 0, + } + } + + fn mix(row: u32) -> u64 { + let x = u64::from(row).wrapping_mul(0x9E37_79B9_7F4A_7C15); + x ^ (x >> 29) + } + + pub fn capacity(&self) -> u64 { + self.sets * WAYS as u64 + } + + pub fn len(&self) -> u64 { + self.used + } + + pub fn is_empty(&self) -> bool { + self.used == 0 + } + + pub fn find(&self, row: u32) -> Option<&[u8]> { + if self.sets == 0 { + return None; + } + let s = (Self::mix(row) % self.sets) as usize; + (0..WAYS) + .find(|&w| self.keys[s * WAYS + w] == row) + .map(|w| { + let at = (s * WAYS + w) * self.rb; + &self.data[at..at + self.rb] + }) + } + + pub fn insert(&mut self, row: u32, bytes: &[u8]) { + if self.sets == 0 || self.find(row).is_some() { + return; + } + debug_assert_eq!(bytes.len(), self.rb); + let s = (Self::mix(row) % self.sets) as usize; + let w = usize::from(self.next[s]); + self.next[s] = ((w + 1) % WAYS) as u8; + if self.keys[s * WAYS + w] == EMPTY { + self.used += 1; + } + self.keys[s * WAYS + w] = row; + let at = (s * WAYS + w) * self.rb; + self.data[at..at + self.rb].copy_from_slice(bytes); + } +} + +/// One row inside a read. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Use { + pub row: u32, + /// Byte offset of the row inside the read buffer. + pub in_page: usize, + /// Row slot in the ticket's output. + pub slot: usize, +} + +/// One read: an aligned file offset and one or two pages. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PlannedRead { + pub offset: u64, + pub length: usize, + pub uses: Vec, +} + +/// Plan the reads of a ticket exactly as `PleReader::issue` does: cache hits +/// and out-of-range rows are resolved into `out` immediately, the rest are +/// grouped by first page (a later row on the page may widen the read to two +/// pages) and sorted by offset. +pub fn plan_reads( + rows: &[u32], + cfg: &PleReaderConfig, + cache: &RowCache, + out: &mut [u8], + stats: &mut ReaderStats, +) -> Vec { + let rb = cfg.row_bytes; + let mut by_page: HashMap = HashMap::new(); + let mut jobs: Vec = Vec::new(); + for (i, &row) in rows.iter().enumerate() { + let dst = &mut out[i * rb..(i + 1) * rb]; + stats.requests += 1; + if u64::from(row) >= cfg.n_rows { + dst.fill(0); + continue; + } + if let Some(hit) = cache.find(row) { + dst.copy_from_slice(hit); + stats.cache_hits += 1; + continue; + } + let at = cfg.table_offset + u64::from(row) * rb as u64; + let first = at / PAGE as u64 * PAGE as u64; + let length = ((at + rb as u64 - 1) / PAGE as u64 * PAGE as u64 - first) as usize + PAGE; + let used = Use { + row, + in_page: (at - first) as usize, + slot: i, + }; + if let Some(&j) = by_page.get(&first) { + jobs[j].length = jobs[j].length.max(length); + jobs[j].uses.push(used); + stats.dedup_rows += 1; + } else { + by_page.insert(first, jobs.len()); + jobs.push(PlannedRead { + offset: first, + length, + uses: vec![used], + }); + } + } + // Sorted by offset: prefill chunks then read the SSD in near-sequential order. + jobs.sort_by_key(|job| job.offset); + jobs +} + +struct Job { + read: PlannedRead, + ticket: u32, + keepalive: bool, +} + +struct TicketState { + pending: usize, + out: Vec, +} + +#[derive(Default)] +struct KeepAlive { + period: Duration, + window: Duration, + last_issue: Option, + last_read: Option, + rng: u64, +} + +struct State { + queue: VecDeque, + tickets: HashMap, + next_ticket: u32, + cache: RowCache, + stats: ReaderStats, + ring_pos: usize, + delay: Duration, + error: Option, + stop: bool, + inflight: usize, + keep: KeepAlive, +} + +struct Shared { + source: Arc, + cfg: PleReaderConfig, + inline: bool, + state: Mutex, + work: Condvar, + done: Condvar, + keep_cv: Condvar, +} + +fn lock(m: &Mutex) -> MutexGuard<'_, State> { + // A panicking worker must not wedge the reader: the data is still coherent + // (every mutation is completed before the lock is released) and the error + // path reports failures through `State::error`. + m.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +/// Heap buffer whose usable window starts on a 4 KiB boundary, for unbuffered sources. +struct AlignedBuf { + raw: Vec, + start: usize, + len: usize, +} + +impl AlignedBuf { + fn new(len: usize) -> Self { + let raw = vec![0u8; len + PAGE]; + let start = (PAGE - raw.as_ptr() as usize % PAGE) % PAGE; + Self { raw, start, len } + } + fn window(&mut self, len: usize) -> &mut [u8] { + &mut self.raw[self.start..self.start + len.min(self.len)] + } +} + +/// Whether `source` serves one page-aligned page read at the page holding +/// `offset`, through a 4 KiB-aligned buffer. Used to accept an unbuffered +/// (O_DIRECT) handle only once it demonstrably works on this filesystem. +pub fn probe_aligned_read(source: &dyn PageSource, offset: u64) -> bool { + let mut buf = AlignedBuf::new(PAGE); + let page = offset / PAGE as u64 * PAGE as u64; + matches!(read_full_at(source, buf.window(PAGE), page), Ok(n) if n > 0) +} + +fn read_full_at(source: &dyn PageSource, buf: &mut [u8], offset: u64) -> io::Result { + let mut total = 0; + while total < buf.len() { + match source.read_at(&mut buf[total..], offset + total as u64) { + Ok(0) => break, + Ok(n) => total += n, + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) => return Err(e), + } + } + Ok(total) +} + +impl State { + fn record_latency(&mut self, us: f64) { + self.stats.read_us_sum += us; + if self.stats.read_us.len() < LATENCY_RING { + self.stats.read_us.push(us as f32); + } else { + self.stats.read_us[self.ring_pos % LATENCY_RING] = us as f32; + self.ring_pos += 1; + } + } + + /// A job that will never run: its ticket no longer waits for it. + fn cancel_queued(&mut self) { + let queued: Vec = self.queue.drain(..).collect(); + for job in queued { + self.release(job.ticket); + } + } + + fn release(&mut self, ticket: u32) { + if let Some(t) = self.tickets.get_mut(&ticket) { + t.pending = t.pending.saturating_sub(1); + } + } + + fn fail(&mut self, message: &str) { + if self.error.is_none() { + self.error = Some(PleError(format!("PleReader: {message}"))); + } + self.cancel_queued(); + } + + /// When the next keep-alive read is due, or `None` when none is: it is off, + /// the reader failed, or no rows were asked for within the window (the SSD + /// may then sleep; the next `issue` re-arms it). + fn keepalive_due(&self, now: Instant) -> Option { + let k = &self.keep; + let issued = k.last_issue?; + if k.period.is_zero() || self.error.is_some() || now.duration_since(issued) > k.window { + return None; + } + Some(k.last_read.unwrap_or(issued) + k.period) + } +} + +impl Shared { + /// Run one job: the read happens outside the lock. + fn run(&self, job: Job, issued: Instant, delay: Duration) { + let mut buf = AlignedBuf::new(2 * PAGE); + let length = job.read.length; + // A source that panics is a failed read like any other: the worker survives, the reader fails and every ticket is released. + // Unwinding past this point would end the worker with the job's ticket still pending, and its `collect` would wait for ever. + let read = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + read_full_at(self.source.as_ref(), buf.window(length), job.read.offset) + })) + .unwrap_or_else(|_| Err(io::Error::other("the page source panicked"))); + let mut late = false; + if !delay.is_zero() { + let spent = issued.elapsed(); + if spent < delay { + late = true; + thread::sleep(delay - spent); + } + } + let mut st = lock(&self.state); + st.inflight -= 1; + if late { + st.stats.late_injected += 1; + } + let elapsed_us = issued.elapsed().as_secs_f64() * 1e6; + if job.keepalive { + // A failed keep-alive turns the keep-alive off, not the reader. + match read { + Ok(_) => { + st.stats.keepalive_reads += 1; + st.stats.keepalive_us_max = st.stats.keepalive_us_max.max(elapsed_us); + } + Err(_) => st.keep.period = Duration::ZERO, + } + drop(st); + self.work.notify_all(); + self.done.notify_all(); + return; + } + match read { + Err(e) => { + st.fail(&format!("a table read failed ({e})")); + st.release(job.ticket); + } + Ok(bytes) => { + st.record_latency(elapsed_us); + st.stats.bytes += bytes as u64; + let rb = self.cfg.row_bytes; + if job.read.uses.iter().any(|u| u.in_page + rb > bytes) { + st.fail("short read inside the table"); + st.release(job.ticket); + } else { + let data = buf.window(length); + for u in &job.read.uses { + let row = &data[u.in_page..u.in_page + rb]; + if let Some(t) = st.tickets.get_mut(&job.ticket) { + t.out[u.slot * rb..(u.slot + 1) * rb].copy_from_slice(row); + } + st.cache.insert(u.row, row); + } + st.release(job.ticket); + } + } + } + drop(st); + self.work.notify_all(); + self.done.notify_all(); + } + + /// Take the next job (marking it in flight) or `None` when there is none. + fn start(&self, st: &mut State) -> Option<(Job, Instant, Duration)> { + let job = st.queue.pop_front()?; + let now = Instant::now(); + st.inflight += 1; + st.keep.last_read = Some(now); + if !job.keepalive { + st.stats.reads += 1; + } + Some((job, now, st.delay)) + } + + fn worker(self: &Arc) { + loop { + let started = { + let mut st = lock(&self.state); + loop { + if st.stop && st.queue.is_empty() { + return; + } + if let Some(started) = self.start(&mut st) { + break started; + } + st = self.work.wait(st).unwrap_or_else(|p| p.into_inner()); + } + }; + self.run(started.0, started.1, started.2); + } + } + + fn keepalive_worker(self: &Arc) { + let mut st = lock(&self.state); + while !st.stop { + let now = Instant::now(); + match st.keepalive_due(now) { + None => st = self.keep_cv.wait(st).unwrap_or_else(|p| p.into_inner()), + Some(due) if now >= due => { + if st.queue.is_empty() && st.inflight == 0 { + // One page of the table, a different one each time, so the + // SSD really reads (not its controller's buffer). + st.keep.rng ^= st.keep.rng << 13; + st.keep.rng ^= st.keep.rng >> 7; + st.keep.rng ^= st.keep.rng << 17; + let first = self.cfg.table_offset / PAGE as u64; + let end = (self.cfg.table_offset + + self.cfg.n_rows * self.cfg.row_bytes as u64) + / PAGE as u64; + let page = first + + if end > first { + st.keep.rng % (end - first) + } else { + 0 + }; + st.queue.push_back(Job { + read: PlannedRead { + offset: page * PAGE as u64, + length: PAGE, + uses: Vec::new(), + }, + ticket: 0, + keepalive: true, + }); + self.work.notify_one(); + } + // Re-evaluate after the period (or when woken). + let wait = st.keep.period.max(Duration::from_millis(1)); + st = self + .keep_cv + .wait_timeout(st, wait) + .unwrap_or_else(|p| p.into_inner()) + .0; + } + Some(due) => { + let wait = (due - now).max(Duration::from_millis(1)); + st = self + .keep_cv + .wait_timeout(st, wait) + .unwrap_or_else(|p| p.into_inner()) + .0; + } + } + } + } +} + +/// Handle to a ticket issued by [`PleReader::issue`]. Dropping it without +/// collecting abandons the rows (reads in flight still warm the cache). +pub struct Ticket { + id: u32, + shared: Arc, +} + +impl Drop for Ticket { + fn drop(&mut self) { + lock(&self.shared.state).tickets.remove(&self.id); + } +} + +pub struct PleReader { + shared: Arc, + workers: Vec>, + keepalive: Option>, +} + +impl PleReader { + /// `source` is the table's file. The table must fit exactly in it from + /// `table_offset` (the caller's GGUF parse checks that; the length is + /// checked here too). + pub fn open(source: Arc, cfg: PleReaderConfig) -> Result { + if cfg.max_inflight == 0 || cfg.max_inflight > 1024 { + return err("max_inflight must be 1..1024"); + } + if cfg.row_bytes == 0 || cfg.row_bytes > PAGE { + return err("row_bytes must be 1..4096"); + } + if cfg.n_rows > u64::from(EMPTY) { + return err("the row count exceeds the 32-bit row index"); + } + let table_end = cfg + .n_rows + .checked_mul(cfg.row_bytes as u64) + .and_then(|bytes| bytes.checked_add(cfg.table_offset)); + let len = source + .len() + .map_err(|e| PleError(format!("PleReader: cannot size the table file ({e})")))?; + if table_end.is_none_or(|end| end > len) { + return err("the table extends past the end of the file"); + } + if cfg.expected_len.is_some_and(|expected| expected != len) { + return err("the table file changed size after verification"); + } + let threads = match cfg.io_threads { + None => cfg.max_inflight.min(DEFAULT_IO_THREADS), + Some(n) => n.min(cfg.max_inflight), + }; + let seed = 0x9E37_79B9_7F4A_7C15 + ^ std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(1, |d| d.as_micros() as u64); + let state = State { + queue: VecDeque::new(), + tickets: HashMap::new(), + next_ticket: 1, + cache: RowCache::new(cfg.cache_rows, cfg.row_bytes), + stats: ReaderStats::default(), + ring_pos: 0, + delay: Duration::ZERO, + error: None, + stop: false, + inflight: 0, + keep: KeepAlive { + rng: if seed == 0 { 1 } else { seed }, + ..KeepAlive::default() + }, + }; + let shared = Arc::new(Shared { + source, + inline: threads == 0, + cfg, + state: Mutex::new(state), + work: Condvar::new(), + done: Condvar::new(), + keep_cv: Condvar::new(), + }); + let mut reader = Self { + shared: Arc::clone(&shared), + workers: Vec::new(), + keepalive: None, + }; + for index in 0..threads { + let worker = Arc::clone(&shared); + let spawned = thread::Builder::new() + .name(format!("ple-reader-{index}")) + .spawn(move || worker.worker()); + match spawned { + Ok(handle) => reader.workers.push(handle), + Err(e) => return err(format!("cannot create I/O worker: {e}")), + } + } + Ok(reader) + } + + pub fn row_bytes(&self) -> usize { + self.shared.cfg.row_bytes + } + + pub fn rows(&self) -> u64 { + self.shared.cfg.n_rows + } + + /// Start fetching `rows`; row `i`'s raw bytes land at `row_bytes * i` of + /// the buffer `collect` returns. Out-of-range rows produce zero bytes. + pub fn issue(&self, rows: &[u32]) -> Ticket { + let shared = &self.shared; + let rb = shared.cfg.row_bytes; + let mut st = lock(&shared.state); + let id = st.next_ticket; + st.next_ticket = st.next_ticket.wrapping_add(1).max(1); + let now = Instant::now(); + let rearm = !st.keep.period.is_zero() + && st + .keep + .last_issue + .is_none_or(|last| now.duration_since(last) > st.keep.window); + st.keep.last_issue = Some(now); + let mut out = vec![0u8; rows.len() * rb]; + let State { cache, stats, .. } = &mut *st; + let reads = plan_reads(rows, &shared.cfg, cache, &mut out, stats); + let mut pending = reads.len(); + if st.error.is_some() { + pending = 0; // the reader failed: `collect` reports it, nothing is queued + } else { + for read in reads { + st.queue.push_back(Job { + read, + ticket: id, + keepalive: false, + }); + } + } + st.tickets.insert(id, TicketState { pending, out }); + drop(st); + if pending > 0 { + shared.work.notify_all(); + } + if rearm || pending > 0 { + shared.keep_cv.notify_all(); + } + Ticket { + id, + shared: Arc::clone(shared), + } + } + + /// Block until every row of the ticket is in the returned buffer. + pub fn collect(&self, ticket: Ticket) -> Result, PleError> { + let shared = &self.shared; + if !Arc::ptr_eq(&ticket.shared, shared) { + return err("ticket from another reader"); + } + let start = Instant::now(); + let mut st = lock(&shared.state); + if !st.tickets.contains_key(&ticket.id) { + return err("unknown ticket"); + } + loop { + let pending = st.tickets.get(&ticket.id).map_or(0, |t| t.pending); + if pending == 0 { + break; + } + if shared.inline { + // No workers: this thread performs the reads itself. + if let Some((job, issued, delay)) = shared.start(&mut st) { + drop(st); + shared.run(job, issued, delay); + st = lock(&shared.state); + continue; + } + } + st = shared.done.wait(st).unwrap_or_else(|p| p.into_inner()); + } + if let Some(e) = st.error.clone() { + return Err(e); + } + st.stats.wait_us += start.elapsed().as_secs_f64() * 1e6; + let out = st.tickets.remove(&ticket.id).map(|t| t.out); + drop(st); + // The same-FD size observation the verified GGUF reader makes around its streams. + if let Some(expected) = shared.cfg.expected_len { + match shared.source.len() { + Ok(len) if len == expected => {} + _ => { + let mut st = lock(&shared.state); + st.fail("the table file changed size after verification"); + return Err(st + .error + .clone() + .unwrap_or_else(|| PleError("PleReader: size check failed".into()))); + } + } + } + out.ok_or_else(|| PleError("PleReader: unknown ticket".into())) + } + + /// `issue` then `collect`. + pub fn read_rows(&self, rows: &[u32]) -> Result, PleError> { + self.collect(self.issue(rows)) + } + + /// Keep the SSD awake while the table is in use (worker mode only; call + /// after `open`): when no read has gone out for `period`, one page of the + /// table is read, until `window` after the last `issue`. A keep-alive read + /// that fails turns it off. A zero period turns it off. + pub fn set_keepalive(&mut self, period: Duration, window: Duration) { + let threaded = !self.shared.inline; + { + let mut st = lock(&self.shared.state); + st.keep.period = if threaded { period } else { Duration::ZERO }; + st.keep.window = window; + } + if threaded && !period.is_zero() && self.keepalive.is_none() { + let worker = Arc::clone(&self.shared); + if let Ok(handle) = thread::Builder::new() + .name("ple-reader-keepalive".into()) + .spawn(move || worker.keepalive_worker()) + { + self.keepalive = Some(handle); + } + } + self.shared.keep_cv.notify_all(); + } + + /// Fault injection for tests and for the plan's P2 exit check: every read + /// completes no earlier than `delay` after it was issued. Zero disables. + pub fn set_injected_delay(&self, delay: Duration) { + lock(&self.shared.state).delay = delay; + } + + /// A consistent copy of the counters. + pub fn snapshot(&self) -> ReaderStats { + lock(&self.shared.state).stats.clone() + } + + pub fn reset_stats(&self) { + let mut st = lock(&self.shared.state); + st.stats = ReaderStats::default(); + st.ring_pos = 0; + } + + pub fn cache_capacity(&self) -> u64 { + lock(&self.shared.state).cache.capacity() + } + + pub fn cache_size(&self) -> u64 { + lock(&self.shared.state).cache.len() + } + + /// Stop the workers (unsubmitted work is dropped, reads in flight finish). + pub fn close(&mut self) { + { + let mut st = lock(&self.shared.state); + st.stop = true; + st.cancel_queued(); + } + self.shared.work.notify_all(); + self.shared.keep_cv.notify_all(); + self.shared.done.notify_all(); + for handle in self.workers.drain(..) { + let _ = handle.join(); + } + if let Some(handle) = self.keepalive.take() { + let _ = handle.join(); + } + } +} + +impl fmt::Debug for PleReader { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("PleReader") + .field("rows", &self.shared.cfg.n_rows) + .field("workers", &self.workers.len()) + .finish() + } +} + +impl Drop for PleReader { + fn drop(&mut self) { + self.close(); + } +} + +#[cfg(test)] +mod tests; diff --git a/scripts/gpu-bringup/bringup_lib.py b/scripts/gpu-bringup/bringup_lib.py index c6d3a604..6eb4fcbe 100644 --- a/scripts/gpu-bringup/bringup_lib.py +++ b/scripts/gpu-bringup/bringup_lib.py @@ -1,675 +1,675 @@ -"""Shared helpers for the GPU bring-up toolkit (plan loading, PTX checks, hashing). - -Pure standard library, Python >= 3.9. Nothing here touches a GPU, the network or nvcc. -""" -from __future__ import annotations - -import hashlib -import json -import re -from dataclasses import dataclass, field -from pathlib import Path -from typing import Dict, List, Optional, Tuple - -HERE = Path(__file__).resolve().parent -REPO = HERE.parents[1] - -MAX_PTX_BYTES = 16 * 1024 * 1024 -TOOLKIT_LOCK = "deploy/cuda-toolkit.lock.json" -EXTRA_PLAN = "scripts/gpu-bringup/extra-seal-plan.json" -ROPE_DOC = "docs/rope-and-memory-plan.md" -ABI_SOURCE = "crates/context/src/ptx_abi.rs" - -# -I set of scripts/build-original-verify-ptx.sh (repo-root relative). -STANDARD_INCLUDES = [ - "engine/strata/include", - "engine/strata/third_party/ggml", - "crates/cuda-driver/src/third_party/llamacpp/ggml-cuda", - "crates/cuda-driver/src/third_party/llamacpp/ggml-include", - "crates/cuda-driver/src/third_party/llamacpp/ggml-src", -] - -# Encoding of the stored .ptx file, as the Rust consumer reads it. -# include_bytes file = raw PTX + exactly one terminal NUL (include_bytes!) -# concat_include_str file = raw PTX, no NUL (concat!(include_str!(..), "\0")) -ENCODINGS = ("include_bytes", "concat_include_str") - -# Rust consumer tables for plan entries that do not carry rust_fields_to_fill themselves. -# (Window plan "new_sources" name the AssetSpec only in prose.) -WINDOW_PIN_TARGETS = { - "original_verify_window_moe_experts": {"original_verify_window_moe.rs": ["EXPERTS.sha"]}, - "original_verify_window_qsa_gate": {"original_verify_window_qsa.rs": ["GATE.sha"]}, -} - - -class PlanError(ValueError): - pass - - -def sha256_hex(data: bytes) -> str: - return hashlib.sha256(data).hexdigest() - - -def sha256_digest(data: bytes) -> bytes: - return hashlib.sha256(data).digest() - - -# ----------------------------------------------------------------------------------------------- model - - -@dataclass -class Asset: - id: str # ptx basename without ".ptx" - cu: str # repo-relative - ptx: str # repo-relative installation path - flags: List[str] - includes: List[str] = field(default_factory=list) - cu_pin: Optional[dict] = None # {"sha256", "bytes"}; None = no pin in the plan (recorded only) - entries: List[str] = field(default_factory=list) - entry_prefix_counts: Dict[str, int] = field(default_factory=dict) - entries_derived: bool = False - encoding: str = "include_bytes" - pin_fields: Dict[str, List[str]] = field(default_factory=dict) # consumer file name -> field specs - plan: str = "" - group: str = "" - policy: str = "" - params: Dict[str, int] = field(default_factory=dict) # entry -> expected .param count - repin_expect: Dict[str, int] = field(default_factory=dict) # repo file -> expected decimal-pin hits - deferred: Optional[str] = None - optional: bool = False - atomic_group: Optional[str] = None # all members must be sealed together - notes: List[str] = field(default_factory=list) - seal_fields: bool = False # the plan entry carries seal_sha256/seal_length slots to fill - entries_from_symbols: bool = False # entry names live in crates/cuda-driver/src/mtp_original_full_symbols.rs - flag_overrides: List[str] = field(default_factory=list) # operator overrides applied (recorded in the manifest) - - @property - def ptx_name(self) -> str: - return Path(self.ptx).name - - -# ------------------------------------------------------------------------------------------ plan files - - -def _group_from_plan_name(name: str) -> str: - stem = Path(name).stem - stem = stem.replace("cuda-seal-plan-additions", "additions").replace("cuda-seal-plan", "plan") - return stem.replace("additions-", "") - - -def split_nvcc_flags(tokens: List[str]) -> Tuple[List[str], List[str]]: - """Separate -I

tokens (and '-I dir' pairs) from the other flags; order is preserved per list.""" - flags: List[str] = [] - includes: List[str] = [] - i = 0 - while i < len(tokens): - t = tokens[i] - if t == "-I" and i + 1 < len(tokens): - includes.append(tokens[i + 1]) - i += 2 - continue - if t.startswith("-I") and len(t) > 2: - includes.append(t[2:]) - else: - flags.append(t) - i += 1 - return flags, includes - - -def _clean_pin(pin) -> Optional[dict]: - if pin is None: - return None - if not isinstance(pin, dict) or "sha256" not in pin: - raise PlanError(f"bad cu_pin {pin!r}") - return {"sha256": str(pin["sha256"]).lower(), "bytes": pin.get("bytes")} - - -def asset_from_assets_entry(entry: dict, plan: str, group: str) -> Asset: - for key in ("cu", "ptx", "flags"): - if key not in entry: - raise PlanError(f"{plan}: asset without '{key}': {entry.get('cu') or entry}") - enc = entry.get("encoding", "include_bytes") - if enc == "mixed": - # stra169 'mixed' (gdn_native_batch + qsa_native_batch): the file is read through concat_include_str. - enc = "concat_include_str" - if enc not in ENCODINGS: - raise PlanError(f"{plan}: unknown encoding {enc!r} for {entry['cu']}") - flags, includes = split_nvcc_flags(list(entry["flags"])) - a = Asset( - id=Path(entry["ptx"]).stem, - cu=entry["cu"], - ptx=entry["ptx"], - flags=flags, - includes=includes, - cu_pin=_clean_pin(entry.get("cu_pin")), - entries=list(entry.get("entries") or entry.get("exports") or []), - entry_prefix_counts=dict(entry.get("entry_prefix_counts") or {}), - encoding=enc, - pin_fields={k: list(v) for k, v in (entry.get("rust_fields_to_fill") or {}).items()}, - plan=plan, - group=entry.get("group", group), - policy=entry.get("policy", ""), - params={k: int(v) for k, v in (entry.get("params") or {}).items()}, - deferred=entry.get("deferred"), - optional=bool(entry.get("optional", False)), - atomic_group=entry.get("atomic_group"), - seal_fields="seal_sha256" in entry and "seal_length" in entry, - entries_from_symbols=bool(entry.get("entries_from_symbols", False)), - repin_expect={k: int(v) for k, v in (entry.get("repin_expect") or {}).items()}, - ) - if "include_profile" in entry: - if entry["include_profile"] != "standard": - raise PlanError(f"{plan}: unknown include_profile {entry['include_profile']!r}") - a.includes = list(STANDARD_INCLUDES) + a.includes - if entry.get("note"): - a.notes.append(str(entry["note"])) - return a - - -def asset_from_window_source(entry: dict, plan: str, group: str) -> Asset: - for key in ("source", "ptx", "nvcc"): - if key not in entry: - raise PlanError(f"{plan}: new_sources item without '{key}'") - flags, includes = split_nvcc_flags(list(entry["nvcc"])) - ident = Path(entry["ptx"]).stem - if ident not in WINDOW_PIN_TARGETS: - raise PlanError(f"{plan}: no pin target registered for window asset {ident!r} (bringup_lib.WINDOW_PIN_TARGETS)") - a = Asset( - id=ident, - cu=entry["source"], - ptx=entry["ptx"], - flags=flags, - includes=includes, - cu_pin=None, # the window plan does not pin the new sources; the compile manifest does - entries=list(entry.get("exports") or []), - encoding="include_bytes", # "append exactly ONE terminal NUL byte" - pin_fields={k: list(v) for k, v in WINDOW_PIN_TARGETS[ident].items()}, - plan=plan, - group=group, - policy=str(entry.get("nvcc_note") or entry.get("derived_from") or ""), - ) - for key in ("notes", "install"): - if entry.get(key): - a.notes.append(str(entry[key])) - return a - - -def load_plan_file(path: Path) -> List[Asset]: - try: - data = json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError) as error: - raise PlanError(f"{path}: {error}") from error - group = _group_from_plan_name(path.name) - out: List[Asset] = [] - known = False - if "assets" in data: - known = True - out += [asset_from_assets_entry(a, path.name, group) for a in data["assets"]] - if "new_sources" in data: - known = True - out += [asset_from_window_source(a, path.name, group) for a in data["new_sources"]] - if not known: - raise PlanError(f"{path.name}: neither 'assets' nor 'new_sources' present; unrecognised plan format") - return out - - -def window_sealed_bound(root: Path) -> List[dict]: - """sealed_assets_bound of the window plan: committed PTX the producers pin by sha256 (not to be rebuilt).""" - path = root / "docs/cuda-seal-plan-additions-window.json" - if not path.is_file(): - return [] - return list(json.loads(path.read_text(encoding="utf-8")).get("sealed_assets_bound", [])) - - -# ----------------------------------------------------------------------------------- rope doc / ABI - - -def parse_rope_doc(text: str) -> Tuple[List[str], List[str], List[str]]: - """Return (nvcc flags, include dirs repo-relative, source basenames) from the Regeneration section.""" - m = re.search(r"```sh\s*\n(nvcc .*?)```", text, re.S) - if not m: - raise PlanError("rope doc: no ```sh nvcc block found") - block = m.group(1).replace("\\\n", " ") - toks = block.split() - if toks[0] != "nvcc": - raise PlanError("rope doc: block does not start with nvcc") - toks = toks[1:] - # the trailing ".cu -o ....ptx" part is a template - cut = [i for i, t in enumerate(toks) if "" in t] - if not cut: - raise PlanError("rope doc: no placeholder in the nvcc block") - toks = toks[: cut[0]] - flags, includes = split_nvcc_flags(toks) - rel = [] - for inc in includes: - if not inc.startswith("$R/"): - raise PlanError(f"rope doc: include {inc!r} is not under $R") - rel.append(inc[3:]) - sm = re.search(r"for `` in ((?:`[^`]+`(?:,\s*)?)+)", text) - if not sm: - raise PlanError("rope doc: no 'for `` in ...' list") - sources = re.findall(r"`([^`]+)`", sm.group(1)) - if not sources: - raise PlanError("rope doc: empty source list") - return flags, rel, sources - - -def parse_abi_tuples(text: str) -> Dict[str, Dict[str, Tuple[int, int]]]: - """('file.ptx', 'entry', frozen, extra) tuples of ptx_abi.rs -> {file: {entry: (frozen, extra)}}.""" - out: Dict[str, Dict[str, Tuple[int, int]]] = {} - for f, e, a, b in re.findall(r'\(\s*"([\w.\-]+\.ptx)"\s*,\s*"(\w+)"\s*,\s*(\d+)\s*,\s*(\d+)\s*\)', text): - out.setdefault(f, {})[e] = (int(a), int(b)) - return out - - -ROPE_VARIANTS = ("precise", "preserve") -# Sources that the Original compiles with --use_fast_math (engine/strata/CMakeLists.txt native_* list); the -# committed PTX of these two contain .ftz instructions, i.e. they were built fast-math (stra169 plan). -ROPE_FASTMATH_SOURCES = ("qsa_prompt_indexer", "qsa_decode_postops") -# decimal-pin hits expected in the Rust tree for the committed digests (found by scanning, see seal_pins) -ROPE_REPIN_EXPECT = { - "qsa_prompt_indexer": {}, - "qsa_prompt_postops": {"crates/cuda-driver/src/original_verify_window_qsa.rs": 1}, - "qsa_decode_postops": {"crates/cuda-driver/src/original_verify_window_qsa.rs": 1}, - "qsa_prompt_resolver": {"crates/cuda-driver/src/original_verify_window_qsa.rs": 1}, -} -# hex pins in the window plan (sealed_assets_bound) -ROPE_HEX_DOC = "docs/cuda-seal-plan-additions-window.json" - - -def rope_assets(root: Path, variant: str) -> List[Asset]: - """The four QSA PTX that docs/rope-and-memory-plan.md says must be regenerated. - - variant 'precise' : the doc's flags verbatim (--fmad=true --ftz=false) for all four. - variant 'preserve' : same, except qsa_prompt_indexer / qsa_decode_postops keep --use_fast_math (how the - committed PTX were built; the Original compiles native_qsa_indexer/native_rope fast-math). - """ - if variant not in ROPE_VARIANTS: - raise PlanError(f"rope variant must be one of {ROPE_VARIANTS}") - doc = root / ROPE_DOC - abi = root / ABI_SOURCE - flags, includes, sources = parse_rope_doc(doc.read_text(encoding="utf-8")) - tuples = parse_abi_tuples(abi.read_text(encoding="utf-8")) - out: List[Asset] = [] - for src in sources: - f = list(flags) - if variant == "preserve" and src in ROPE_FASTMATH_SOURCES: - f = [t for t in f if t not in ("--fmad=true", "--ftz=false")] + ["--use_fast_math"] - cu = f"crates/cuda-driver/src/{src}.cu" - ptx = f"crates/cuda-driver/src/{src}.ptx" - entries = tuples.get(f"{src}.ptx", {}) - a = Asset( - id=src, - cu=cu, - ptx=ptx, - flags=f, - includes=list(includes), - cu_pin=None, - entries=sorted(entries), - encoding="include_bytes", - plan=ROPE_DOC, - group="rope", - policy=f"rope regeneration, variant {variant}", - params={e: fr + ex for e, (fr, ex) in entries.items()}, - repin_expect=dict(ROPE_REPIN_EXPECT.get(src, {})), - atomic_group="rope", - ) - out.append(a) - return out - - -# ------------------------------------------------------------------------------------- all assets - - -def load_all_assets(root: Path, rope_variant: Optional[str]) -> Tuple[List[Asset], List[str]]: - """Every docs/cuda-seal-plan*.json, the extra plan and (if rope_variant) the rope doc list. - - Returns (assets, warnings). Duplicate asset ids across plans are an error.""" - assets: List[Asset] = [] - warnings: List[str] = [] - plans = sorted((root / "docs").glob("cuda-seal-plan*.json")) - if not plans: - raise PlanError(f"no docs/cuda-seal-plan*.json under {root}") - for p in plans: - assets += load_plan_file(p) - extra = root / EXTRA_PLAN - if extra.is_file(): - assets += load_plan_file(extra) - if rope_variant: - assets += rope_assets(root, rope_variant) - seen: Dict[str, str] = {} - for a in assets: - if a.id in seen: - raise PlanError(f"asset {a.id!r} appears in both {seen[a.id]} and {a.plan}") - seen[a.id] = a.plan - return assets, warnings - - -# ------------------------------------------------------------------------------ source / pin checks - - -def check_cu_pin(root: Path, asset: Asset) -> Tuple[str, str]: - """('ok'|'unpinned'|'stale'|'missing', detail). Reads the .cu from root.""" - path = root / asset.cu - if not path.is_file(): - return "missing", f"{asset.cu} does not exist" - data = path.read_bytes() - if asset.cu_pin is None: - return "unpinned", sha256_hex(data) - got, want = sha256_hex(data), asset.cu_pin["sha256"] - if got != want: - return "stale", f"{asset.cu}: sha256 {got[:16]}.. != plan pin {want[:16]}.. (source edited since the plan)" - want_bytes = asset.cu_pin.get("bytes") - if want_bytes is not None and want_bytes != len(data): - return "stale", f"{asset.cu}: {len(data)} bytes != plan pin {want_bytes}" - return "ok", got - - -_INCLUDE_RE = re.compile(r'^\s*#\s*include\s+"([^"]+)"', re.M) - - -def resolve_includes(root: Path, asset: Asset) -> List[str]: - """Quoted #include targets of the .cu (recursively) that resolve nowhere; [] if all resolve.""" - dirs = [root / d for d in asset.includes] - missing: List[str] = [] - seen = set() - - def visit(path: Path) -> None: - if path in seen: - return - seen.add(path) - text = path.read_text(encoding="utf-8", errors="replace") - for inc in _INCLUDE_RE.findall(text): - for base in [path.parent] + dirs: - cand = base / inc - if cand.is_file(): - visit(cand.resolve()) - break - else: - missing.append(f"{inc} (from {path.name})") - - src = root / asset.cu - if src.is_file(): - visit(src.resolve()) - return missing - - -def policy_conflicts(asset: Asset) -> List[str]: - """Lint the fast-math policy notes against the flags (see window plan 'nvcc_note').""" - msgs = [] - flags = set(asset.flags) - fast = "--use_fast_math" in flags or "-use_fast_math" in flags - if fast and ({"--ftz=false", "--prec-div=true", "--prec-sqrt=true"} & flags): - msgs.append("--use_fast_math together with --ftz=false/--prec-div=true/--prec-sqrt=true contradicts itself") - p = asset.policy.lower() - # "not in the CMake fast-math list" / "no fast-math" are negations, not claims of fast-math - p = re.sub(r"\b(?:not in|no|without)\s+(?:the\s+)?(?:cmake\s+)?(?:--use_)?fast-?math(?:\s+list)?", "", p) - says_precise = "precise" in p - says_fast = bool(re.search(r"fast-?math", p)) and not says_precise - if says_precise and fast: - msgs.append("policy says precise but flags contain --use_fast_math") - if says_fast and not fast: - msgs.append("policy says fast-math but flags lack --use_fast_math") - return msgs - - -# ----------------------------------------------------------------------------------------- PTX utils - -_ENTRY_RE = re.compile(r"^\s*(?:\.visible\s+|\.weak\s+|\.extern\s+)?\.entry\s+([^\s(]+)", re.M) - - -def ptx_entries(text: str) -> List[str]: - return _ENTRY_RE.findall(text) - - -def entry_param_count(text: str, entry: str) -> Optional[int]: - """Mirror of leleka-context ptx_abi::entry_param_count.""" - needle = f".entry {entry}(" - i = text.find(needle) - if i < 0: - return None - start = i + len(needle) - end = text.find(")", start) - if end < 0: - return None - return text[start:end].count(".param") - - -# CUDA 13.2.0 and 13.2.1 (nvcc 13.2.51) miscompile some sm_120 kernels (IQ2_S / IQ3_S products wrong, relative error 0.5-1.0; -# upstream docs/TROUBLESHOOTING.md, #892, #968); 13.2.2 (nvcc 13.2.86) is right. Their PTX names the build in its header. -BAD_NVCC_BUILDS = ("13.2.0", "13.2.1", "13.2.51") -_NVCC_HEADER = re.compile(r"Cuda compilation tools, release [0-9.]+, V([0-9]+\.[0-9]+\.[0-9]+)") - - -def nvcc_build_of(ptx_head: str) -> Optional[str]: - """The `V..` that the header of a PTX names, or None when it names none.""" - m = _NVCC_HEADER.search(ptx_head[:4096]) - return m.group(1) if m else None - - -def validate_ptx(raw: bytes, asset: Asset, allow_fake: bool = False) -> List[str]: - """Problems with a freshly produced raw (NUL-free) PTX body; [] if acceptable.""" - bad: List[str] = [] - if not 0 < len(raw) <= MAX_PTX_BYTES: - return [f"size {len(raw)} outside 1..{MAX_PTX_BYTES}"] - if b"\0" in raw: - bad.append("contains a NUL byte") - if not raw.isascii(): - bad.append("not ASCII") - if bad: - return bad - text = raw.decode("ascii") - if ".version" not in text: - bad.append("no .version directive") - if ".target sm_120" not in text: - bad.append("no '.target sm_120'") - for marker in ("UNSEALED", "PLACEHOLDER"): - if marker in text: - bad.append(f"contains the {marker} marker") - if not allow_fake and "FAKE-NVCC" in text: - bad.append("fake-nvcc output") - build = nvcc_build_of(text) - if build in BAD_NVCC_BUILDS: - bad.append(f"built by nvcc V{build}, which miscompiles some sm_120 kernels (CUDA 13.2.0/13.2.1); use 13.2.2 (V13.2.86)") - found = ptx_entries(text) - foundset = set(found) - missing = [e for e in asset.entries if e not in foundset] - if missing: - shown = ", ".join(missing[:8]) + (" ..." if len(missing) > 8 else "") - bad.append(f"missing {len(missing)} exported .entry: {shown}") - for prefix, count in asset.entry_prefix_counts.items(): - n = sum(1 for e in foundset if e.startswith(prefix)) - if n != count: - bad.append(f"{n} entries start with {prefix!r}, expected {count}") - for entry, want in asset.params.items(): - got = entry_param_count(text, entry) - if got != want: - bad.append(f"entry {entry} has {got} params, expected {want}") - return bad - - -def stored_bytes(raw: bytes, encoding: str) -> bytes: - if encoding == "include_bytes": - return raw + b"\0" - if encoding == "concat_include_str": - return raw - raise PlanError(f"unknown encoding {encoding!r}") - - -def raw_from_stored(data: bytes) -> bytes: - """The hashed PTX body of an installed file (strip at most one terminal NUL).""" - return data[:-1] if data.endswith(b"\0") else data - - -def committed_fastmath_evidence(root: Path, asset: Asset) -> Optional[int]: - """Number of '.ftz' occurrences in the currently committed PTX (None if the file is absent/placeholder).""" - p = root / asset.ptx - if not p.is_file(): - return None - text = p.read_bytes().decode("latin-1") - if "UNSEALED" in text or "PLACEHOLDER" in text: - return None - return text.count(".ftz") - - -# --------------------------------------------------------------------------------- placeholder scan - - -def scan_placeholders(root: Path) -> List[str]: - """Repo-relative paths of every crates/cuda-driver/src/*.ptx that is an unsealed placeholder.""" - out = [] - for p in sorted((root / "crates/cuda-driver/src").glob("*.ptx")): - head = p.read_bytes()[:4096].decode("latin-1") - if "UNSEALED" in head or "PLACEHOLDER" in head: - out.append(str(p.relative_to(root))) - return out - - -_NONE_ASSET_RE = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?const\s+(\w+)\s*:\s*Option<&\[u8\]>\s*=\s*None;", re.M) - - -def scan_none_assets(root: Path) -> List[Tuple[str, str]]: - """const X: Option<&[u8]> = None; -- fail-closed assets that need *wiring*, not just a seal.""" - out = [] - for p in sorted((root / "crates").rglob("*.rs")): - text = p.read_text(encoding="utf-8", errors="replace") - for name in _NONE_ASSET_RE.findall(text): - out.append((str(p.relative_to(root)), name)) - return out - - -def toolkit_expected_version(root: Path) -> Optional[str]: - p = root / TOOLKIT_LOCK - if not p.is_file(): - return None - for c in json.loads(p.read_text(encoding="utf-8")).get("components", []): - if c.get("component") == "cuda_nvcc": - return c.get("version") - return None - - -# ------------------------------------------------------------------------------- entry derivation - -_KERNEL_RE = re.compile( - r'extern\s+"C"\s+__global__\s+(?:__launch_bounds__\([^)]*\)\s*)?void\s+(?:__launch_bounds__\([^)]*\)\s*)?([A-Za-z_]\w*)\s*\(' -) - - -def derive_entries(root: Path, asset: Asset) -> List[str]: - """extern "C" __global__ names in the .cu (as the stra169 seal script derived them). - - Macro parameters (all-uppercase names) and compiler keywords are dropped; this is a lower bound, so a - derived list only proves 'these exist', never that nothing else is expected.""" - src = root / asset.cu - names = _KERNEL_RE.findall(src.read_text(encoding="utf-8", errors="replace")) - keep = [] - for n in names: - if n.startswith("__") or n.isupper() or n in keep: - continue - keep.append(n) - return keep - - -def fill_derived_entries(root: Path, asset: Asset) -> None: - if asset.deferred or asset.entries or asset.entry_prefix_counts: - return - asset.entries = derive_entries(root, asset) - asset.entries_derived = True - - -SYMBOLS_FILE = "crates/cuda-driver/src/mtp_original_full_symbols.rs" - - -def symbols_entries(root: Path, ptx_name: str) -> List[str]: - """Entry names the Rust side loads from `ptx_name` (mtp_original_full_symbols.rs table).""" - text = (root / SYMBOLS_FILE).read_text(encoding="utf-8") - m = re.search(r'include_bytes!\("' + re.escape(ptx_name) + r'"\)\s*,\s*&\[([^\]]*)\]', text) - if not m: - raise PlanError(f"{ptx_name}: no entry table in {SYMBOLS_FILE}") - names = re.findall(r'c"([^"]+)"', m.group(1)) - if not names: - raise PlanError(f"{ptx_name}: empty entry table in {SYMBOLS_FILE}") - return names - - -def fill_derived_entries(root: Path, asset: Asset) -> None: # noqa: F811 - supersedes the earlier definition - if asset.deferred or asset.entries or asset.entry_prefix_counts: - return - if asset.entries_from_symbols: - asset.entries = symbols_entries(root, asset.ptx_name) - return - asset.entries = derive_entries(root, asset) - asset.entries_derived = True - - -def apply_flag_overrides(assets: List[Asset], specs: List[str]) -> None: - """Operator flag overrides, `ID:+FLAG` (add) / `ID:-FLAG` (remove); recorded on the asset. - - The policy note is replaced because the plan's own note no longer describes the build; the fast-math lint - still rejects contradictory flag sets (--use_fast_math with --ftz=false/--prec-div=true/--prec-sqrt=true).""" - by_id = {a.id: a for a in assets} - for spec in specs: - m = re.fullmatch(r"([\w.\-]+):([+-])(-.+)", spec) - if not m: - raise PlanError(f"bad --flag-override {spec!r}; expected ID:+--flag or ID:---flag") - a = by_id.get(m.group(1)) - if a is None: - raise PlanError(f"--flag-override: unknown asset {m.group(1)!r}") - flag = m.group(3) - if m.group(2) == "+": - if flag not in a.flags: - a.flags.append(flag) - else: - if flag not in a.flags: - raise PlanError(f"--flag-override {spec}: {a.id} does not have {flag}") - a.flags.remove(flag) - a.flag_overrides.append(spec) - a.policy = "operator flag override" - - -# ---------------------------------------------------------------------------------- PTX ISA / driver - -# PTX ISA version -> minimum NVIDIA driver able to JIT it. 8.7 is CUDA 12.8 (R570); 9.0 is CUDA 13.0 (R580, -# GA 580.65.06, deploy/README.md). An unknown version is an error: extend this table, do not guess. -# 9.1/9.2: CUDA 13.1/13.2 minimum Linux drivers per the CUDA release notes (to be confirmed by a real module load on the host). -ISA_MIN_DRIVER = {"7.0": "450.80", "8.0": "525.60", "8.7": "570.26", "9.0": "580.65.06", "9.1": "590.44.01", "9.2": "595.45.04"} - - -def ptx_isa_version(data: bytes) -> Optional[str]: - m = re.search(rb"(?m)^\.version\s+(\d+\.\d+)", data[:8192]) - return m.group(1).decode() if m else None - - -def isa_inventory(root: Path) -> Dict[str, List[str]]: - """{ISA version: [ptx names]} over the real (non-placeholder) PTX in crates/cuda-driver/src.""" - out: Dict[str, List[str]] = {} - for p in sorted((root / "crates/cuda-driver/src").glob("*.ptx")): - data = p.read_bytes() - if b"UNSEALED" in data[:4096] or b"PLACEHOLDER" in data[:4096]: - continue - v = ptx_isa_version(data) - if v: - out.setdefault(v, []).append(p.name) - return out - - -def version_tuple(v: str) -> Tuple[int, ...]: - return tuple(int(x) for x in re.findall(r"\d+", v)) - - -def min_driver_for(isa_versions) -> Tuple[str, str]: - """(highest ISA, minimum driver) for a set of ISA versions.""" - versions = sorted(set(isa_versions), key=version_tuple) - if not versions: - raise PlanError("no PTX ISA versions given") - for v in versions: - if v not in ISA_MIN_DRIVER: - raise PlanError(f"unknown PTX ISA version {v}: add it to ISA_MIN_DRIVER with its minimum driver") - top = max(versions, key=lambda v: version_tuple(ISA_MIN_DRIVER[v])) - return top, ISA_MIN_DRIVER[top] - - -def driver_ok(driver: str, isa_versions) -> Tuple[bool, str]: - top, need = min_driver_for(isa_versions) - ok = version_tuple(driver) >= version_tuple(need) - return ok, (f"driver {driver} {'supports' if ok else 'is too old for'} PTX ISA {top} (needs >= {need})") +"""Shared helpers for the GPU bring-up toolkit (plan loading, PTX checks, hashing). + +Pure standard library, Python >= 3.9. Nothing here touches a GPU, the network or nvcc. +""" +from __future__ import annotations + +import hashlib +import json +import re +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +HERE = Path(__file__).resolve().parent +REPO = HERE.parents[1] + +MAX_PTX_BYTES = 16 * 1024 * 1024 +TOOLKIT_LOCK = "deploy/cuda-toolkit.lock.json" +EXTRA_PLAN = "scripts/gpu-bringup/extra-seal-plan.json" +ROPE_DOC = "docs/rope-and-memory-plan.md" +ABI_SOURCE = "crates/context/src/ptx_abi.rs" + +# -I set of scripts/build-original-verify-ptx.sh (repo-root relative). +STANDARD_INCLUDES = [ + "engine/strata/include", + "engine/strata/third_party/ggml", + "crates/cuda-driver/src/third_party/llamacpp/ggml-cuda", + "crates/cuda-driver/src/third_party/llamacpp/ggml-include", + "crates/cuda-driver/src/third_party/llamacpp/ggml-src", +] + +# Encoding of the stored .ptx file, as the Rust consumer reads it. +# include_bytes file = raw PTX + exactly one terminal NUL (include_bytes!) +# concat_include_str file = raw PTX, no NUL (concat!(include_str!(..), "\0")) +ENCODINGS = ("include_bytes", "concat_include_str") + +# Rust consumer tables for plan entries that do not carry rust_fields_to_fill themselves. +# (Window plan "new_sources" name the AssetSpec only in prose.) +WINDOW_PIN_TARGETS = { + "original_verify_window_moe_experts": {"original_verify_window_moe.rs": ["EXPERTS.sha"]}, + "original_verify_window_qsa_gate": {"original_verify_window_qsa.rs": ["GATE.sha"]}, +} + + +class PlanError(ValueError): + pass + + +def sha256_hex(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def sha256_digest(data: bytes) -> bytes: + return hashlib.sha256(data).digest() + + +# ----------------------------------------------------------------------------------------------- model + + +@dataclass +class Asset: + id: str # ptx basename without ".ptx" + cu: str # repo-relative + ptx: str # repo-relative installation path + flags: List[str] + includes: List[str] = field(default_factory=list) + cu_pin: Optional[dict] = None # {"sha256", "bytes"}; None = no pin in the plan (recorded only) + entries: List[str] = field(default_factory=list) + entry_prefix_counts: Dict[str, int] = field(default_factory=dict) + entries_derived: bool = False + encoding: str = "include_bytes" + pin_fields: Dict[str, List[str]] = field(default_factory=dict) # consumer file name -> field specs + plan: str = "" + group: str = "" + policy: str = "" + params: Dict[str, int] = field(default_factory=dict) # entry -> expected .param count + repin_expect: Dict[str, int] = field(default_factory=dict) # repo file -> expected decimal-pin hits + deferred: Optional[str] = None + optional: bool = False + atomic_group: Optional[str] = None # all members must be sealed together + notes: List[str] = field(default_factory=list) + seal_fields: bool = False # the plan entry carries seal_sha256/seal_length slots to fill + entries_from_symbols: bool = False # entry names live in crates/cuda-driver/src/mtp_original_full_symbols.rs + flag_overrides: List[str] = field(default_factory=list) # operator overrides applied (recorded in the manifest) + + @property + def ptx_name(self) -> str: + return Path(self.ptx).name + + +# ------------------------------------------------------------------------------------------ plan files + + +def _group_from_plan_name(name: str) -> str: + stem = Path(name).stem + stem = stem.replace("cuda-seal-plan-additions", "additions").replace("cuda-seal-plan", "plan") + return stem.replace("additions-", "") + + +def split_nvcc_flags(tokens: List[str]) -> Tuple[List[str], List[str]]: + """Separate -I tokens (and '-I dir' pairs) from the other flags; order is preserved per list.""" + flags: List[str] = [] + includes: List[str] = [] + i = 0 + while i < len(tokens): + t = tokens[i] + if t == "-I" and i + 1 < len(tokens): + includes.append(tokens[i + 1]) + i += 2 + continue + if t.startswith("-I") and len(t) > 2: + includes.append(t[2:]) + else: + flags.append(t) + i += 1 + return flags, includes + + +def _clean_pin(pin) -> Optional[dict]: + if pin is None: + return None + if not isinstance(pin, dict) or "sha256" not in pin: + raise PlanError(f"bad cu_pin {pin!r}") + return {"sha256": str(pin["sha256"]).lower(), "bytes": pin.get("bytes")} + + +def asset_from_assets_entry(entry: dict, plan: str, group: str) -> Asset: + for key in ("cu", "ptx", "flags"): + if key not in entry: + raise PlanError(f"{plan}: asset without '{key}': {entry.get('cu') or entry}") + enc = entry.get("encoding", "include_bytes") + if enc == "mixed": + # stra169 'mixed' (gdn_native_batch + qsa_native_batch): the file is read through concat_include_str. + enc = "concat_include_str" + if enc not in ENCODINGS: + raise PlanError(f"{plan}: unknown encoding {enc!r} for {entry['cu']}") + flags, includes = split_nvcc_flags(list(entry["flags"])) + a = Asset( + id=Path(entry["ptx"]).stem, + cu=entry["cu"], + ptx=entry["ptx"], + flags=flags, + includes=includes, + cu_pin=_clean_pin(entry.get("cu_pin")), + entries=list(entry.get("entries") or entry.get("exports") or []), + entry_prefix_counts=dict(entry.get("entry_prefix_counts") or {}), + encoding=enc, + pin_fields={k: list(v) for k, v in (entry.get("rust_fields_to_fill") or {}).items()}, + plan=plan, + group=entry.get("group", group), + policy=entry.get("policy", ""), + params={k: int(v) for k, v in (entry.get("params") or {}).items()}, + deferred=entry.get("deferred"), + optional=bool(entry.get("optional", False)), + atomic_group=entry.get("atomic_group"), + seal_fields="seal_sha256" in entry and "seal_length" in entry, + entries_from_symbols=bool(entry.get("entries_from_symbols", False)), + repin_expect={k: int(v) for k, v in (entry.get("repin_expect") or {}).items()}, + ) + if "include_profile" in entry: + if entry["include_profile"] != "standard": + raise PlanError(f"{plan}: unknown include_profile {entry['include_profile']!r}") + a.includes = list(STANDARD_INCLUDES) + a.includes + if entry.get("note"): + a.notes.append(str(entry["note"])) + return a + + +def asset_from_window_source(entry: dict, plan: str, group: str) -> Asset: + for key in ("source", "ptx", "nvcc"): + if key not in entry: + raise PlanError(f"{plan}: new_sources item without '{key}'") + flags, includes = split_nvcc_flags(list(entry["nvcc"])) + ident = Path(entry["ptx"]).stem + if ident not in WINDOW_PIN_TARGETS: + raise PlanError(f"{plan}: no pin target registered for window asset {ident!r} (bringup_lib.WINDOW_PIN_TARGETS)") + a = Asset( + id=ident, + cu=entry["source"], + ptx=entry["ptx"], + flags=flags, + includes=includes, + cu_pin=None, # the window plan does not pin the new sources; the compile manifest does + entries=list(entry.get("exports") or []), + encoding="include_bytes", # "append exactly ONE terminal NUL byte" + pin_fields={k: list(v) for k, v in WINDOW_PIN_TARGETS[ident].items()}, + plan=plan, + group=group, + policy=str(entry.get("nvcc_note") or entry.get("derived_from") or ""), + ) + for key in ("notes", "install"): + if entry.get(key): + a.notes.append(str(entry[key])) + return a + + +def load_plan_file(path: Path) -> List[Asset]: + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as error: + raise PlanError(f"{path}: {error}") from error + group = _group_from_plan_name(path.name) + out: List[Asset] = [] + known = False + if "assets" in data: + known = True + out += [asset_from_assets_entry(a, path.name, group) for a in data["assets"]] + if "new_sources" in data: + known = True + out += [asset_from_window_source(a, path.name, group) for a in data["new_sources"]] + if not known: + raise PlanError(f"{path.name}: neither 'assets' nor 'new_sources' present; unrecognised plan format") + return out + + +def window_sealed_bound(root: Path) -> List[dict]: + """sealed_assets_bound of the window plan: committed PTX the producers pin by sha256 (not to be rebuilt).""" + path = root / "docs/cuda-seal-plan-additions-window.json" + if not path.is_file(): + return [] + return list(json.loads(path.read_text(encoding="utf-8")).get("sealed_assets_bound", [])) + + +# ----------------------------------------------------------------------------------- rope doc / ABI + + +def parse_rope_doc(text: str) -> Tuple[List[str], List[str], List[str]]: + """Return (nvcc flags, include dirs repo-relative, source basenames) from the Regeneration section.""" + m = re.search(r"```sh\s*\n(nvcc .*?)```", text, re.S) + if not m: + raise PlanError("rope doc: no ```sh nvcc block found") + block = m.group(1).replace("\\\n", " ") + toks = block.split() + if toks[0] != "nvcc": + raise PlanError("rope doc: block does not start with nvcc") + toks = toks[1:] + # the trailing ".cu -o ....ptx" part is a template + cut = [i for i, t in enumerate(toks) if "" in t] + if not cut: + raise PlanError("rope doc: no placeholder in the nvcc block") + toks = toks[: cut[0]] + flags, includes = split_nvcc_flags(toks) + rel = [] + for inc in includes: + if not inc.startswith("$R/"): + raise PlanError(f"rope doc: include {inc!r} is not under $R") + rel.append(inc[3:]) + sm = re.search(r"for `` in ((?:`[^`]+`(?:,\s*)?)+)", text) + if not sm: + raise PlanError("rope doc: no 'for `` in ...' list") + sources = re.findall(r"`([^`]+)`", sm.group(1)) + if not sources: + raise PlanError("rope doc: empty source list") + return flags, rel, sources + + +def parse_abi_tuples(text: str) -> Dict[str, Dict[str, Tuple[int, int]]]: + """('file.ptx', 'entry', frozen, extra) tuples of ptx_abi.rs -> {file: {entry: (frozen, extra)}}.""" + out: Dict[str, Dict[str, Tuple[int, int]]] = {} + for f, e, a, b in re.findall(r'\(\s*"([\w.\-]+\.ptx)"\s*,\s*"(\w+)"\s*,\s*(\d+)\s*,\s*(\d+)\s*\)', text): + out.setdefault(f, {})[e] = (int(a), int(b)) + return out + + +ROPE_VARIANTS = ("precise", "preserve") +# Sources that the Original compiles with --use_fast_math (engine/strata/CMakeLists.txt native_* list); the +# committed PTX of these two contain .ftz instructions, i.e. they were built fast-math (stra169 plan). +ROPE_FASTMATH_SOURCES = ("qsa_prompt_indexer", "qsa_decode_postops") +# decimal-pin hits expected in the Rust tree for the committed digests (found by scanning, see seal_pins) +ROPE_REPIN_EXPECT = { + "qsa_prompt_indexer": {}, + "qsa_prompt_postops": {"crates/cuda-driver/src/original_verify_window_qsa.rs": 1}, + "qsa_decode_postops": {"crates/cuda-driver/src/original_verify_window_qsa.rs": 1}, + "qsa_prompt_resolver": {"crates/cuda-driver/src/original_verify_window_qsa.rs": 1}, +} +# hex pins in the window plan (sealed_assets_bound) +ROPE_HEX_DOC = "docs/cuda-seal-plan-additions-window.json" + + +def rope_assets(root: Path, variant: str) -> List[Asset]: + """The four QSA PTX that docs/rope-and-memory-plan.md says must be regenerated. + + variant 'precise' : the doc's flags verbatim (--fmad=true --ftz=false) for all four. + variant 'preserve' : same, except qsa_prompt_indexer / qsa_decode_postops keep --use_fast_math (how the + committed PTX were built; the Original compiles native_qsa_indexer/native_rope fast-math). + """ + if variant not in ROPE_VARIANTS: + raise PlanError(f"rope variant must be one of {ROPE_VARIANTS}") + doc = root / ROPE_DOC + abi = root / ABI_SOURCE + flags, includes, sources = parse_rope_doc(doc.read_text(encoding="utf-8")) + tuples = parse_abi_tuples(abi.read_text(encoding="utf-8")) + out: List[Asset] = [] + for src in sources: + f = list(flags) + if variant == "preserve" and src in ROPE_FASTMATH_SOURCES: + f = [t for t in f if t not in ("--fmad=true", "--ftz=false")] + ["--use_fast_math"] + cu = f"crates/cuda-driver/src/{src}.cu" + ptx = f"crates/cuda-driver/src/{src}.ptx" + entries = tuples.get(f"{src}.ptx", {}) + a = Asset( + id=src, + cu=cu, + ptx=ptx, + flags=f, + includes=list(includes), + cu_pin=None, + entries=sorted(entries), + encoding="include_bytes", + plan=ROPE_DOC, + group="rope", + policy=f"rope regeneration, variant {variant}", + params={e: fr + ex for e, (fr, ex) in entries.items()}, + repin_expect=dict(ROPE_REPIN_EXPECT.get(src, {})), + atomic_group="rope", + ) + out.append(a) + return out + + +# ------------------------------------------------------------------------------------- all assets + + +def load_all_assets(root: Path, rope_variant: Optional[str]) -> Tuple[List[Asset], List[str]]: + """Every docs/cuda-seal-plan*.json, the extra plan and (if rope_variant) the rope doc list. + + Returns (assets, warnings). Duplicate asset ids across plans are an error.""" + assets: List[Asset] = [] + warnings: List[str] = [] + plans = sorted((root / "docs").glob("cuda-seal-plan*.json")) + if not plans: + raise PlanError(f"no docs/cuda-seal-plan*.json under {root}") + for p in plans: + assets += load_plan_file(p) + extra = root / EXTRA_PLAN + if extra.is_file(): + assets += load_plan_file(extra) + if rope_variant: + assets += rope_assets(root, rope_variant) + seen: Dict[str, str] = {} + for a in assets: + if a.id in seen: + raise PlanError(f"asset {a.id!r} appears in both {seen[a.id]} and {a.plan}") + seen[a.id] = a.plan + return assets, warnings + + +# ------------------------------------------------------------------------------ source / pin checks + + +def check_cu_pin(root: Path, asset: Asset) -> Tuple[str, str]: + """('ok'|'unpinned'|'stale'|'missing', detail). Reads the .cu from root.""" + path = root / asset.cu + if not path.is_file(): + return "missing", f"{asset.cu} does not exist" + data = path.read_bytes() + if asset.cu_pin is None: + return "unpinned", sha256_hex(data) + got, want = sha256_hex(data), asset.cu_pin["sha256"] + if got != want: + return "stale", f"{asset.cu}: sha256 {got[:16]}.. != plan pin {want[:16]}.. (source edited since the plan)" + want_bytes = asset.cu_pin.get("bytes") + if want_bytes is not None and want_bytes != len(data): + return "stale", f"{asset.cu}: {len(data)} bytes != plan pin {want_bytes}" + return "ok", got + + +_INCLUDE_RE = re.compile(r'^\s*#\s*include\s+"([^"]+)"', re.M) + + +def resolve_includes(root: Path, asset: Asset) -> List[str]: + """Quoted #include targets of the .cu (recursively) that resolve nowhere; [] if all resolve.""" + dirs = [root / d for d in asset.includes] + missing: List[str] = [] + seen = set() + + def visit(path: Path) -> None: + if path in seen: + return + seen.add(path) + text = path.read_text(encoding="utf-8", errors="replace") + for inc in _INCLUDE_RE.findall(text): + for base in [path.parent] + dirs: + cand = base / inc + if cand.is_file(): + visit(cand.resolve()) + break + else: + missing.append(f"{inc} (from {path.name})") + + src = root / asset.cu + if src.is_file(): + visit(src.resolve()) + return missing + + +def policy_conflicts(asset: Asset) -> List[str]: + """Lint the fast-math policy notes against the flags (see window plan 'nvcc_note').""" + msgs = [] + flags = set(asset.flags) + fast = "--use_fast_math" in flags or "-use_fast_math" in flags + if fast and ({"--ftz=false", "--prec-div=true", "--prec-sqrt=true"} & flags): + msgs.append("--use_fast_math together with --ftz=false/--prec-div=true/--prec-sqrt=true contradicts itself") + p = asset.policy.lower() + # "not in the CMake fast-math list" / "no fast-math" are negations, not claims of fast-math + p = re.sub(r"\b(?:not in|no|without)\s+(?:the\s+)?(?:cmake\s+)?(?:--use_)?fast-?math(?:\s+list)?", "", p) + says_precise = "precise" in p + says_fast = bool(re.search(r"fast-?math", p)) and not says_precise + if says_precise and fast: + msgs.append("policy says precise but flags contain --use_fast_math") + if says_fast and not fast: + msgs.append("policy says fast-math but flags lack --use_fast_math") + return msgs + + +# ----------------------------------------------------------------------------------------- PTX utils + +_ENTRY_RE = re.compile(r"^\s*(?:\.visible\s+|\.weak\s+|\.extern\s+)?\.entry\s+([^\s(]+)", re.M) + + +def ptx_entries(text: str) -> List[str]: + return _ENTRY_RE.findall(text) + + +def entry_param_count(text: str, entry: str) -> Optional[int]: + """Mirror of leleka-context ptx_abi::entry_param_count.""" + needle = f".entry {entry}(" + i = text.find(needle) + if i < 0: + return None + start = i + len(needle) + end = text.find(")", start) + if end < 0: + return None + return text[start:end].count(".param") + + +# CUDA 13.2.0 and 13.2.1 (nvcc 13.2.51) miscompile some sm_120 kernels (IQ2_S / IQ3_S products wrong, relative error 0.5-1.0; +# upstream docs/TROUBLESHOOTING.md, #892, #968); 13.2.2 (nvcc 13.2.86) is right. Their PTX names the build in its header. +BAD_NVCC_BUILDS = ("13.2.0", "13.2.1", "13.2.51") +_NVCC_HEADER = re.compile(r"Cuda compilation tools, release [0-9.]+, V([0-9]+\.[0-9]+\.[0-9]+)") + + +def nvcc_build_of(ptx_head: str) -> Optional[str]: + """The `V..` that the header of a PTX names, or None when it names none.""" + m = _NVCC_HEADER.search(ptx_head[:4096]) + return m.group(1) if m else None + + +def validate_ptx(raw: bytes, asset: Asset, allow_fake: bool = False) -> List[str]: + """Problems with a freshly produced raw (NUL-free) PTX body; [] if acceptable.""" + bad: List[str] = [] + if not 0 < len(raw) <= MAX_PTX_BYTES: + return [f"size {len(raw)} outside 1..{MAX_PTX_BYTES}"] + if b"\0" in raw: + bad.append("contains a NUL byte") + if not raw.isascii(): + bad.append("not ASCII") + if bad: + return bad + text = raw.decode("ascii") + if ".version" not in text: + bad.append("no .version directive") + if ".target sm_120" not in text: + bad.append("no '.target sm_120'") + for marker in ("UNSEALED", "PLACEHOLDER"): + if marker in text: + bad.append(f"contains the {marker} marker") + if not allow_fake and "FAKE-NVCC" in text: + bad.append("fake-nvcc output") + build = nvcc_build_of(text) + if build in BAD_NVCC_BUILDS: + bad.append(f"built by nvcc V{build}, which miscompiles some sm_120 kernels (CUDA 13.2.0/13.2.1); use 13.2.2 (V13.2.86)") + found = ptx_entries(text) + foundset = set(found) + missing = [e for e in asset.entries if e not in foundset] + if missing: + shown = ", ".join(missing[:8]) + (" ..." if len(missing) > 8 else "") + bad.append(f"missing {len(missing)} exported .entry: {shown}") + for prefix, count in asset.entry_prefix_counts.items(): + n = sum(1 for e in foundset if e.startswith(prefix)) + if n != count: + bad.append(f"{n} entries start with {prefix!r}, expected {count}") + for entry, want in asset.params.items(): + got = entry_param_count(text, entry) + if got != want: + bad.append(f"entry {entry} has {got} params, expected {want}") + return bad + + +def stored_bytes(raw: bytes, encoding: str) -> bytes: + if encoding == "include_bytes": + return raw + b"\0" + if encoding == "concat_include_str": + return raw + raise PlanError(f"unknown encoding {encoding!r}") + + +def raw_from_stored(data: bytes) -> bytes: + """The hashed PTX body of an installed file (strip at most one terminal NUL).""" + return data[:-1] if data.endswith(b"\0") else data + + +def committed_fastmath_evidence(root: Path, asset: Asset) -> Optional[int]: + """Number of '.ftz' occurrences in the currently committed PTX (None if the file is absent/placeholder).""" + p = root / asset.ptx + if not p.is_file(): + return None + text = p.read_bytes().decode("latin-1") + if "UNSEALED" in text or "PLACEHOLDER" in text: + return None + return text.count(".ftz") + + +# --------------------------------------------------------------------------------- placeholder scan + + +def scan_placeholders(root: Path) -> List[str]: + """Repo-relative paths of every crates/cuda-driver/src/*.ptx that is an unsealed placeholder.""" + out = [] + for p in sorted((root / "crates/cuda-driver/src").glob("*.ptx")): + head = p.read_bytes()[:4096].decode("latin-1") + if "UNSEALED" in head or "PLACEHOLDER" in head: + out.append(str(p.relative_to(root))) + return out + + +_NONE_ASSET_RE = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?const\s+(\w+)\s*:\s*Option<&\[u8\]>\s*=\s*None;", re.M) + + +def scan_none_assets(root: Path) -> List[Tuple[str, str]]: + """const X: Option<&[u8]> = None; -- fail-closed assets that need *wiring*, not just a seal.""" + out = [] + for p in sorted((root / "crates").rglob("*.rs")): + text = p.read_text(encoding="utf-8", errors="replace") + for name in _NONE_ASSET_RE.findall(text): + out.append((str(p.relative_to(root)), name)) + return out + + +def toolkit_expected_version(root: Path) -> Optional[str]: + p = root / TOOLKIT_LOCK + if not p.is_file(): + return None + for c in json.loads(p.read_text(encoding="utf-8")).get("components", []): + if c.get("component") == "cuda_nvcc": + return c.get("version") + return None + + +# ------------------------------------------------------------------------------- entry derivation + +_KERNEL_RE = re.compile( + r'extern\s+"C"\s+__global__\s+(?:__launch_bounds__\([^)]*\)\s*)?void\s+(?:__launch_bounds__\([^)]*\)\s*)?([A-Za-z_]\w*)\s*\(' +) + + +def derive_entries(root: Path, asset: Asset) -> List[str]: + """extern "C" __global__ names in the .cu (as the stra169 seal script derived them). + + Macro parameters (all-uppercase names) and compiler keywords are dropped; this is a lower bound, so a + derived list only proves 'these exist', never that nothing else is expected.""" + src = root / asset.cu + names = _KERNEL_RE.findall(src.read_text(encoding="utf-8", errors="replace")) + keep = [] + for n in names: + if n.startswith("__") or n.isupper() or n in keep: + continue + keep.append(n) + return keep + + +def fill_derived_entries(root: Path, asset: Asset) -> None: + if asset.deferred or asset.entries or asset.entry_prefix_counts: + return + asset.entries = derive_entries(root, asset) + asset.entries_derived = True + + +SYMBOLS_FILE = "crates/cuda-driver/src/mtp_original_full_symbols.rs" + + +def symbols_entries(root: Path, ptx_name: str) -> List[str]: + """Entry names the Rust side loads from `ptx_name` (mtp_original_full_symbols.rs table).""" + text = (root / SYMBOLS_FILE).read_text(encoding="utf-8") + m = re.search(r'include_bytes!\("' + re.escape(ptx_name) + r'"\)\s*,\s*&\[([^\]]*)\]', text) + if not m: + raise PlanError(f"{ptx_name}: no entry table in {SYMBOLS_FILE}") + names = re.findall(r'c"([^"]+)"', m.group(1)) + if not names: + raise PlanError(f"{ptx_name}: empty entry table in {SYMBOLS_FILE}") + return names + + +def fill_derived_entries(root: Path, asset: Asset) -> None: # noqa: F811 - supersedes the earlier definition + if asset.deferred or asset.entries or asset.entry_prefix_counts: + return + if asset.entries_from_symbols: + asset.entries = symbols_entries(root, asset.ptx_name) + return + asset.entries = derive_entries(root, asset) + asset.entries_derived = True + + +def apply_flag_overrides(assets: List[Asset], specs: List[str]) -> None: + """Operator flag overrides, `ID:+FLAG` (add) / `ID:-FLAG` (remove); recorded on the asset. + + The policy note is replaced because the plan's own note no longer describes the build; the fast-math lint + still rejects contradictory flag sets (--use_fast_math with --ftz=false/--prec-div=true/--prec-sqrt=true).""" + by_id = {a.id: a for a in assets} + for spec in specs: + m = re.fullmatch(r"([\w.\-]+):([+-])(-.+)", spec) + if not m: + raise PlanError(f"bad --flag-override {spec!r}; expected ID:+--flag or ID:---flag") + a = by_id.get(m.group(1)) + if a is None: + raise PlanError(f"--flag-override: unknown asset {m.group(1)!r}") + flag = m.group(3) + if m.group(2) == "+": + if flag not in a.flags: + a.flags.append(flag) + else: + if flag not in a.flags: + raise PlanError(f"--flag-override {spec}: {a.id} does not have {flag}") + a.flags.remove(flag) + a.flag_overrides.append(spec) + a.policy = "operator flag override" + + +# ---------------------------------------------------------------------------------- PTX ISA / driver + +# PTX ISA version -> minimum NVIDIA driver able to JIT it. 8.7 is CUDA 12.8 (R570); 9.0 is CUDA 13.0 (R580, +# GA 580.65.06, deploy/README.md). An unknown version is an error: extend this table, do not guess. +# 9.1/9.2: CUDA 13.1/13.2 minimum Linux drivers per the CUDA release notes (to be confirmed by a real module load on the host). +ISA_MIN_DRIVER = {"7.0": "450.80", "8.0": "525.60", "8.7": "570.26", "9.0": "580.65.06", "9.1": "590.44.01", "9.2": "595.45.04"} + + +def ptx_isa_version(data: bytes) -> Optional[str]: + m = re.search(rb"(?m)^\.version\s+(\d+\.\d+)", data[:8192]) + return m.group(1).decode() if m else None + + +def isa_inventory(root: Path) -> Dict[str, List[str]]: + """{ISA version: [ptx names]} over the real (non-placeholder) PTX in crates/cuda-driver/src.""" + out: Dict[str, List[str]] = {} + for p in sorted((root / "crates/cuda-driver/src").glob("*.ptx")): + data = p.read_bytes() + if b"UNSEALED" in data[:4096] or b"PLACEHOLDER" in data[:4096]: + continue + v = ptx_isa_version(data) + if v: + out.setdefault(v, []).append(p.name) + return out + + +def version_tuple(v: str) -> Tuple[int, ...]: + return tuple(int(x) for x in re.findall(r"\d+", v)) + + +def min_driver_for(isa_versions) -> Tuple[str, str]: + """(highest ISA, minimum driver) for a set of ISA versions.""" + versions = sorted(set(isa_versions), key=version_tuple) + if not versions: + raise PlanError("no PTX ISA versions given") + for v in versions: + if v not in ISA_MIN_DRIVER: + raise PlanError(f"unknown PTX ISA version {v}: add it to ISA_MIN_DRIVER with its minimum driver") + top = max(versions, key=lambda v: version_tuple(ISA_MIN_DRIVER[v])) + return top, ISA_MIN_DRIVER[top] + + +def driver_ok(driver: str, isa_versions) -> Tuple[bool, str]: + top, need = min_driver_for(isa_versions) + ok = version_tuple(driver) >= version_tuple(need) + return ok, (f"driver {driver} {'supports' if ok else 'is too old for'} PTX ISA {top} (needs >= {need})") diff --git a/scripts/gpu-bringup/tests/test_gpu_bringup.py b/scripts/gpu-bringup/tests/test_gpu_bringup.py index a2c1507e..9266ff02 100644 --- a/scripts/gpu-bringup/tests/test_gpu_bringup.py +++ b/scripts/gpu-bringup/tests/test_gpu_bringup.py @@ -1,989 +1,989 @@ -#!/usr/bin/env python3 -"""Unit tests for the GPU bring-up toolkit. Plain unittest: `python3 scripts/gpu-bringup/tests/test_gpu_bringup.py` -(pytest also collects it). No GPU, nvcc or network is used; compile tests run scripts/gpu-bringup/fake-nvcc.""" -import contextlib -import hashlib -import io -import json -import os -import re -import shutil -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path - -HERE = Path(__file__).resolve().parent -sys.path.insert(0, str(HERE.parent)) -import bringup_lib as L # noqa: E402 -import compile_assets as C # noqa: E402 -import rustpins as R # noqa: E402 -import seal_pins as S # noqa: E402 -import smoke_inventory as SI # noqa: E402 - -REPO = L.REPO -V = R.PinValues(raw_len=1234, ptx_sha256=hashlib.sha256(b"ptx").digest(), source_sha256=hashlib.sha256(b"cu").digest()) - - -def sh(b: bytes) -> str: - return hashlib.sha256(b).hexdigest() - - -# --------------------------------------------------------------------------------------- plan parsing -class PlanParsing(unittest.TestCase): - def test_every_checked_in_plan_loads_and_cu_pins_are_current(self): - assets, _ = L.load_all_assets(REPO, "precise") - self.assertGreaterEqual(len(assets), 24) - for a in assets: - status, detail = L.check_cu_pin(REPO, a) - self.assertIn(status, ("ok", "unpinned"), detail) - - def test_groups_cover_all_three_plan_formats_and_rope(self): - assets, _ = L.load_all_assets(REPO, "preserve") - groups = {a.group for a in assets} - self.assertTrue({"additions", "experimental", "window", "rope", "kar"} <= groups) - - def test_window_new_sources_become_assets_with_pin_targets(self): - assets, _ = L.load_all_assets(REPO, None) - moe = next(a for a in assets if a.id == "original_verify_window_moe_experts") - self.assertEqual(moe.pin_fields, {"original_verify_window_moe.rs": ["EXPERTS.sha"]}) - self.assertIn("-Iengine/strata/include", [f"-I{d}" for d in moe.includes]) - self.assertNotIn("-Iengine/strata/include", moe.flags) - self.assertEqual(len(moe.entries), 16) - self.assertEqual(moe.encoding, "include_bytes") - gate = next(a for a in assets if a.id == "original_verify_window_qsa_gate") - self.assertIn("--use_fast_math", gate.flags) - self.assertNotIn("--ftz=false", gate.flags) - - def test_experimental_plan_is_raw_encoding_with_six_pin_slots(self): - assets, _ = L.load_all_assets(REPO, None) - exp = [a for a in assets if a.group == "experimental"] - self.assertEqual(len(exp), 6) - self.assertTrue(all(a.encoding == "concat_include_str" for a in exp)) - self.assertEqual(sorted(f for a in exp for v in a.pin_fields.values() for f in v), - sorted(f"PINS[{i}].{k}" for i in range(6) for k in ("source_sha256", "ptx_sha256"))) - - def test_unrecognised_plan_format_is_an_error(self): - with tempfile.TemporaryDirectory() as d: - p = Path(d) / "cuda-seal-plan-x.json" - p.write_text(json.dumps({"schema": 1, "stuff": []})) - with self.assertRaises(L.PlanError): - L.load_plan_file(p) - - def test_duplicate_ids_across_plans_are_an_error(self): - with tempfile.TemporaryDirectory() as d: - root = Path(d) - (root / "docs").mkdir() - entry = {"cu": "a.cu", "ptx": "x/a.ptx", "flags": ["-ptx"]} - for n in ("a", "b"): - (root / "docs" / f"cuda-seal-plan-{n}.json").write_text(json.dumps({"assets": [entry]})) - with self.assertRaises(L.PlanError): - L.load_all_assets(root, None) - - def test_rope_list_and_abi_are_read_from_the_docs_not_hardcoded(self): - flags, incs, sources = L.parse_rope_doc((REPO / L.ROPE_DOC).read_text()) - self.assertEqual(sources, ["qsa_prompt_indexer", "qsa_prompt_postops", "qsa_decode_postops", "qsa_prompt_resolver"]) - self.assertEqual(flags, ["--ptx", "-std=c++17", "-O3", "-arch=sm_120", "--fmad=true", "--ftz=false"]) - self.assertEqual(incs, L.STANDARD_INCLUDES) - abi = L.parse_abi_tuples((REPO / L.ABI_SOURCE).read_text()) - self.assertEqual(abi["qsa_prompt_resolver.ptx"], {"leleka_qsa_stream_reset": (7, 2), "leleka_qsa_resolve": (10, 1)}) - self.assertEqual(abi["qsa_prompt_indexer.ptx"]["qsa_append_blocks"], (13, 5)) - - def test_rope_variants_differ_only_for_the_two_fast_math_sources(self): - precise = {a.id: a for a in L.rope_assets(REPO, "precise")} - keep = {a.id: a for a in L.rope_assets(REPO, "preserve")} - for name in precise: - if name in L.ROPE_FASTMATH_SOURCES: - self.assertIn("--use_fast_math", keep[name].flags) - self.assertNotIn("--ftz=false", keep[name].flags) - self.assertIn("--ftz=false", precise[name].flags) - else: - self.assertEqual(precise[name].flags, keep[name].flags) - self.assertEqual(precise["qsa_prompt_indexer"].params["qsa_append_first"], 11) - with self.assertRaises(L.PlanError): - L.rope_assets(REPO, "bogus") - - def test_committed_rope_ptx_were_built_fast_math_for_the_two_sources(self): - # evidence behind decision D1 in docs/gpu-bringup.md - keep = {a.id: a for a in L.rope_assets(REPO, "preserve")} - self.assertGreater(L.committed_fastmath_evidence(REPO, keep["qsa_prompt_indexer"]), 0) - self.assertGreater(L.committed_fastmath_evidence(REPO, keep["qsa_decode_postops"]), 0) - self.assertEqual(L.committed_fastmath_evidence(REPO, keep["qsa_prompt_resolver"]), 0) - - -# ---------------------------------------------------------------------------------------- pin logic -class CuPinLogic(unittest.TestCase): - def setUp(self): - self.d = tempfile.TemporaryDirectory() - self.root = Path(self.d.name) - (self.root / "k.cu").write_bytes(b"__global__ void k(){}\n") - - def tearDown(self): - self.d.cleanup() - - def asset(self, pin): - return L.Asset(id="k", cu="k.cu", ptx="k.ptx", flags=["-ptx"], cu_pin=pin) - - def test_ok_stale_bytes_unpinned_missing(self): - data = (self.root / "k.cu").read_bytes() - good = {"sha256": sh(data), "bytes": len(data)} - self.assertEqual(L.check_cu_pin(self.root, self.asset(good))[0], "ok") - self.assertEqual(L.check_cu_pin(self.root, self.asset({"sha256": "0" * 64, "bytes": len(data)}))[0], "stale") - self.assertEqual(L.check_cu_pin(self.root, self.asset({"sha256": sh(data), "bytes": 1}))[0], "stale") - self.assertEqual(L.check_cu_pin(self.root, self.asset(None))[0], "unpinned") - a = self.asset(None) - a.cu = "nope.cu" - self.assertEqual(L.check_cu_pin(self.root, a)[0], "missing") - - def test_include_resolution(self): - (self.root / "inc").mkdir() - (self.root / "inc" / "h.hpp").write_text('#include "deep.hpp"\n') - (self.root / "inc" / "deep.hpp").write_text("\n") - (self.root / "k.cu").write_text('#include "h.hpp"\n#include "gone.hpp"\n#include \n') - a = self.asset(None) - a.includes = ["inc"] - self.assertEqual(L.resolve_includes(self.root, a), ["gone.hpp (from k.cu)"]) - - -class PolicyLint(unittest.TestCase): - def mk(self, flags, policy): - return L.Asset(id="x", cu="x.cu", ptx="x.ptx", flags=flags, policy=policy) - - def test_cases(self): - self.assertEqual(L.policy_conflicts(self.mk(["--use_fast_math"], "Original native_qsa fastmath")), []) - self.assertEqual(L.policy_conflicts(self.mk([], "Original device.cu; not in the CMake fast-math list")), []) - self.assertEqual(L.policy_conflicts(self.mk([], "precise (not in CMake fast-math list)")), []) - self.assertTrue(L.policy_conflicts(self.mk(["--use_fast_math"], "precise"))) - self.assertTrue(L.policy_conflicts(self.mk([], "fast-math"))) - self.assertTrue(L.policy_conflicts(self.mk(["--use_fast_math", "--ftz=false"], ""))) - - def test_checked_in_plans_have_no_conflicts(self): - assets, _ = L.load_all_assets(REPO, "preserve") - self.assertEqual([(a.id, L.policy_conflicts(a)) for a in assets if L.policy_conflicts(a)], []) - - -class PtxValidation(unittest.TestCase): - def ptx(self, entries=("k",), extra=""): - body = ".version 8.7\n.target sm_120\n.address_size 64\n" - for e in entries: - body += f".visible .entry {e}(\n\t.param .u64 {e}_param_0,\n\t.param .u32 {e}_param_1\n)\n{{\n\tret;\n}}\n" - return (body + extra).encode() - - def asset(self, **kw): - return L.Asset(id="x", cu="x.cu", ptx="x.ptx", flags=[], entries=["k"], **kw) - - def test_accepts_good(self): - self.assertEqual(L.validate_ptx(self.ptx(), self.asset()), []) - - def test_rejections(self): - a = self.asset() - self.assertTrue(L.validate_ptx(b"", a)) - self.assertTrue(any("NUL" in m for m in L.validate_ptx(self.ptx() + b"\0", a))) - self.assertTrue(any("ASCII" in m for m in L.validate_ptx(self.ptx() + "é".encode(), a))) - self.assertTrue(any("sm_120" in m for m in L.validate_ptx(self.ptx().replace(b"sm_120", b"sm_90"), a))) - self.assertTrue(any("UNSEALED" in m for m in L.validate_ptx(self.ptx(extra="// UNSEALED\n"), a))) - self.assertTrue(any("missing" in m for m in L.validate_ptx(self.ptx(("other",)), a))) - self.assertTrue(any("fake" in m for m in L.validate_ptx(self.ptx(extra="// FAKE-NVCC\n"), a))) - self.assertEqual(L.validate_ptx(self.ptx(extra="// FAKE-NVCC\n"), a, allow_fake=True), []) - - def test_refuses_ptx_built_by_nvcc_13_2_0_or_13_2_1(self): - a = self.asset() - header = "// Cuda compilation tools, release 13.2, V{}" + chr(10) - for build in ("13.2.0", "13.2.1", "13.2.51"): - problems = L.validate_ptx(self.ptx(extra=header.format(build)), a) - self.assertTrue(any(build in m and "miscompiles" in m for m in problems), (build, problems)) - # the pinned and the older toolchains, and a header-less body (fake-nvcc output), stay acceptable - for build in ("13.2.86", "13.2.2", "13.0.88", "12.8.93", "13.2.10", "13.2.100"): - self.assertEqual(L.validate_ptx(self.ptx(extra=header.format(build)), a), [], build) - self.assertEqual(L.validate_ptx(self.ptx(), a), []) - - def test_every_sealed_ptx_in_the_tree_names_a_good_nvcc(self): - seen = 0 - for path in sorted((REPO / "crates").rglob("*.ptx")): - if "target" in path.parts: - continue - build = L.nvcc_build_of(path.read_bytes()[:4096].decode("latin-1")) - seen += build is not None - self.assertNotIn(build, L.BAD_NVCC_BUILDS, str(path)) - self.assertGreater(seen, 100) - - def test_entry_regex_like_the_reference_seal_script(self): - text = ".visible .entry a(\n)\n.weak .entry b(\n)\n .entry c(\n)\n// .entry d(\n" - self.assertEqual(L.ptx_entries(text), ["a", "b", "c"]) - - def test_param_counts_and_prefix_counts(self): - a = self.asset(params={"k": 2}) - self.assertEqual(L.validate_ptx(self.ptx(), a), []) - a.params = {"k": 3} - self.assertTrue(any("params" in m for m in L.validate_ptx(self.ptx(), a))) - b = L.Asset(id="m", cu="m.cu", ptx="m.ptx", flags=[], entry_prefix_counts={"_Z9mul": 2}) - self.assertEqual(L.validate_ptx(self.ptx(("_Z9mul_a", "_Z9mul_b")), b), []) - self.assertTrue(L.validate_ptx(self.ptx(("_Z9mul_a",)), b)) - - def test_encodings(self): - self.assertEqual(L.stored_bytes(b"abc", "include_bytes"), b"abc\0") - self.assertEqual(L.stored_bytes(b"abc", "concat_include_str"), b"abc") - self.assertEqual(L.raw_from_stored(b"abc\0"), b"abc") - self.assertEqual(L.raw_from_stored(b"abc"), b"abc") - with self.assertRaises(L.PlanError): - L.stored_bytes(b"x", "weird") - - def test_derive_entries_drops_macro_names(self): - with tempfile.TemporaryDirectory() as d: - root = Path(d) - (root / "k.cu").write_text('extern "C" __global__ void NAME(int x){}\nextern "C" __global__ void real_k(int x){}\n' - 'extern "C" __global__ __launch_bounds__(256) void other_k(int x){}\n') - a = L.Asset(id="k", cu="k.cu", ptx="k.ptx", flags=[]) - self.assertEqual(L.derive_entries(root, a), ["real_k", "other_k"]) - - -# ------------------------------------------------------------------------------------ rust pin forms -PINS_REPEAT = """\ -/// doc -pub const PINS: [PtxPin; 3] = [PtxPin { - source_sha256: [0; 32], - ptx_sha256: [0; 32], -}; 3]; -""" -OTHER = "const A: usize = 0;\n" - - -class RustPinForms(unittest.TestCase): - def test_ptxpin_array_repeat_form_expands_and_reads_back(self): - t = R.apply_field(PINS_REPEAT, "PINS[1].ptx_sha256", V) - self.assertTrue(R.read_field(t, "PINS[1].ptx_sha256", V)) - self.assertEqual(R.read_ptxpin(t, "PINS", 0, "ptx_sha256"), bytes(32)) - self.assertEqual(R.read_ptxpin(t, "PINS", 2, "source_sha256"), bytes(32)) - t = R.apply_field(t, "PINS[1].source_sha256", V) - self.assertEqual(R.read_ptxpin(t, "PINS", 1, "source_sha256"), V.source_sha256) - self.assertEqual(t.count("PtxPin {"), 3) - with self.assertRaises(R.PinError): - R.apply_field(t, "PINS[3].ptx_sha256", V) - - def test_ptxpin_single_struct(self): - src = "pub const P: PtxPin = PtxPin {\n source_sha256: [0; 32],\n ptx_sha256: [0; 32],\n};\n" - t = R.apply_field(R.apply_field(src, "P.source_sha256", V), "P.ptx_sha256", V) - self.assertTrue(R.read_field(t, "P.source_sha256", V) and R.read_field(t, "P.ptx_sha256", V)) - for line in t.splitlines(): - self.assertLessEqual(len(line), 100) - - def test_asset_spec_sha(self): - src = 'static E: AssetSpec = AssetSpec {\n name: "x.ptx",\n ptx: include_bytes!("x.ptx"),\n sha: [0; 32],\n entries: &[],\n};\n' - t = R.apply_field(src, "E.sha", V) - self.assertTrue(R.read_field(t, "E.sha", V)) - self.assertEqual(t.count("sha:"), 1) - self.assertIn('name: "x.ptx"', t) - # already sealed with the unspaced style used in the window files keeps its style - again = R.apply_field(t.replace(", ", ","), "E.sha", V) - self.assertNotIn(", ", again.split("sha:")[1].split("]")[0]) - - def test_option_tuple_array_len_includes_the_nul(self): - src = "const SEALED: [Option<(usize, [u8; 32])>; 3] = [None, None, None];\n" - t = R.apply_field(src, "SEALED[2]", V) - self.assertEqual(R.read_pin_array(t, "SEALED", 2), (V.raw_len + 1, V.ptx_sha256)) - self.assertIsNone(R.read_pin_array(t, "SEALED", 0)) - t = R.apply_field(t, "SEALED[0]", V) - self.assertEqual(R.read_pin_array(t, "SEALED", 0)[0], 1235) - - def test_plain_const_types(self): - for decl, spec, want in [ - ("const L: usize = 0;", "L", 1234), - ("const L: Option = None;", "L", 1234), - ("const D: [u8; 32] = [0; 32];", "D", V.ptx_sha256), - ("const D: Option<[u8; 32]> = None;", "D", V.ptx_sha256), - ("const T: Option<(usize, [u8; 32])> = None;", "T", (1235, V.ptx_sha256)), - ]: - t = R.apply_field(decl + "\n", spec, V) - self.assertEqual(R.read_plain(t, spec), want, decl) - self.assertTrue(R.read_field(t, spec, V)) - - def test_option_slice_assets_are_refused_not_guessed(self): - with self.assertRaises(R.PinError): - R.apply_field("const ASSET: Option<&[u8]> = None;\n", "ASSET", V) - - def test_exactly_one_declaration_or_refuse(self): - two = OTHER + "mod t {\n const A: usize = 0;\n}\n" - with self.assertRaises(R.PinError): - R.apply_field(two, "A", V) - with self.assertRaises(R.PinError): - R.apply_field(OTHER, "MISSING", V) - with self.assertRaises(R.PinError): - R.apply_field(OTHER, "A.bogus", V) - - def test_strings_and_comments_do_not_confuse_the_scanner(self): - src = 'const X: usize = 0; // trailing; semicolon\nconst S: &str = "a;b";\nconst PINS: [PtxPin; 1] = [PtxPin { source_sha256: [0; 32], ptx_sha256: [0; 32] }; 1];\n' - t = R.apply_field(src, "X", V) - self.assertIn("const X: usize = 1234;", t) - self.assertIn('"a;b"', t) - - def test_real_repo_declarations_patch_and_read_back(self): - src = REPO / "crates/cuda-driver/src" - cases = [ - ("experimental.rs", [f"PINS[{i}].{k}" for i in range(6) for k in ("source_sha256", "ptx_sha256")]), - ("kar_decode_levels.rs", ["KAR_DECODE_LEVELS_PIN.source_sha256", "KAR_DECODE_LEVELS_PIN.ptx_sha256"]), - ("original_verify_window_moe.rs", ["EXPERTS.sha"]), - ("original_verify_window_qsa.rs", ["GATE.sha"]), - ("mmq_original_group.rs", ["SEALED[0]", "SEALED[1]", "SEALED[2]"]), - ] - for name, specs in cases: - t = (src / name).read_text() - for s in specs: - t = R.apply_field(t, s, V) - for s in specs: - self.assertTrue(R.read_field(t, s, V), (name, s)) - - def test_already_sealed_consumers_are_recognised_as_resealable(self): - t = (REPO / "crates/cuda-driver/src/gdn_fused_t1.rs").read_text() - t2 = R.apply_field(R.apply_field(t, "FUSED_PTX_LEN", V), "FUSED_PTX_SHA256", V) - self.assertEqual(R.read_plain(t2, "FUSED_PTX_LEN"), 1234) - self.assertNotEqual(t, t2) - - def test_repin_decimal_inline_and_wrapped(self): - old = hashlib.sha256(b"old").digest() - new = V.ptx_sha256 - inline = "x: [" + ",".join(map(str, old)) + "],\n" - out, n = R.repin_decimal(inline, old, new) - self.assertEqual(n, 1) - self.assertEqual(out, "x: [" + ",".join(map(str, new)) + "],\n") - wrapped = " sha: " + R.render_digest(old, " ", wrapped=True) + ",\n" - out, n = R.repin_decimal(wrapped, old, new) - self.assertEqual(n, 1) - self.assertEqual(R.find_decimal_pins(out, new).__len__(), 1) - self.assertEqual(R.repin_decimal("nothing", old, new), ("nothing", 0)) - - def test_placeholder_test_finder(self): - t = '#[test]\nfn a_placeholder_check() {\n assert_eq!(P.sha, [0; 32]);\n}\n#[test]\nfn fine() {\n assert!(true);\n}\n' - self.assertEqual(R.placeholder_tests(t), ["a_placeholder_check"]) - - -# --------------------------------------------------------------- end-to-end on a miniature repository -def mini_repo(root: Path, cu_pin=True): - src = root / "crates/cuda-driver/src" - src.mkdir(parents=True) - (root / "docs").mkdir() - (root / "deploy").mkdir() - (root / "deploy/cuda-toolkit.lock.json").write_text(json.dumps({"components": [{"component": "cuda_nvcc", "version": "13.2.86"}]})) - cu = 'extern "C" __global__ void leleka_a(int x){}\nextern "C" __global__ void leleka_b(int x){}\n' - (src / "a.cu").write_text(cu) - (src / "b.cu").write_text(cu.replace("leleka_a", "leleka_c").replace("leleka_b", "leleka_d")) - (src / "a.ptx").write_text("// UNSEALED placeholder\n") - (src / "b.ptx").write_text("// UNSEALED placeholder\n") - pin_a = {"sha256": sh(cu.encode()), "bytes": len(cu)} if cu_pin else {"sha256": "0" * 64, "bytes": 1} - plan = {"schema": 1, "assets": [ - {"cu": "crates/cuda-driver/src/a.cu", "cu_pin": pin_a, "ptx": "crates/cuda-driver/src/a.ptx", - "flags": ["-ptx", "-O3", "-arch=sm_120"], "policy": "precise", "entries": ["leleka_a", "leleka_b"], - "encoding": "include_bytes", "rust_fields_to_fill": {"cons.rs": ["A_LEN", "A_SHA"]}}, - {"cu": "crates/cuda-driver/src/b.cu", "ptx": "crates/cuda-driver/src/b.ptx", "flags": ["-ptx", "--use_fast_math"], - "policy": "fastmath", "encoding": "concat_include_str", - "rust_fields_to_fill": {"cons.rs": ["B_PIN.source_sha256", "B_PIN.ptx_sha256"]}}, - ]} - (root / "docs/cuda-seal-plan-mini.json").write_text(json.dumps(plan)) - (src / "cons.rs").write_text( - "const A_LEN: usize = 0;\nconst A_SHA: [u8; 32] = [0; 32];\n" - "pub const B_PIN: PtxPin = PtxPin {\n source_sha256: [0; 32],\n ptx_sha256: [0; 32],\n};\n") - - -def run_quiet(fn, *a): - out, err = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = fn(*a) - return code, out.getvalue(), err.getvalue() - - -class EndToEnd(unittest.TestCase): - def setUp(self): - self.d = tempfile.TemporaryDirectory() - self.root = Path(self.d.name) / "repo" - self.out = Path(self.d.name) / "ptx" - mini_repo(self.root) - - def tearDown(self): - self.d.cleanup() - - def compile(self, *extra): - return run_quiet(C.main, ["--root", str(self.root), "--fake-nvcc", "--no-rope", "--out", str(self.out), *extra]) - - def test_dry_run_prints_commands_and_runs_nothing(self): - code, out, _ = run_quiet(C.main, ["--root", str(self.root), "--dry-run", "--no-rope"]) - self.assertEqual(code, 0) - self.assertIn("nvcc -ptx -O3 -arch=sm_120 crates/cuda-driver/src/a.cu -o", out) - self.assertIn("--use_fast_math crates/cuda-driver/src/b.cu", out) - self.assertFalse(self.out.exists()) - - def test_rope_flags_are_mandatory_when_rope_is_selected(self): - code, _, err = run_quiet(C.main, ["--root", str(REPO), "--dry-run"]) - self.assertEqual(code, 2) - self.assertIn("--rope-flags", err) - - def test_fake_compile_writes_ptx_and_manifest(self): - code, _, _ = self.compile() - self.assertEqual(code, 0) - m = json.loads((self.out / "build-manifest.json").read_text()) - self.assertTrue(m["fake"]) - self.assertEqual([a["id"] for a in m["assets"]], ["a", "b"]) - self.assertTrue(all(a["status"] == "ok" and a["cu_sha256"] for a in m["assets"])) - text = (self.out / "a.ptx").read_text() - self.assertIn(".entry leleka_a(", text) - self.assertIn("FAKE-NVCC", text) - self.assertEqual(code, 0) - # a second run into the same directory is refused - self.assertEqual(self.compile()[0], 2) - - def test_stale_cu_pin_is_refused_before_nvcc_runs(self): - shutil.rmtree(self.root) - mini_repo(self.root, cu_pin=False) - code, out, _ = self.compile() - self.assertEqual(code, 1) - self.assertIn("refusing", out) - m = json.loads((self.out / "build-manifest.json").read_text()) - bad = next(a for a in m["assets"] if a["id"] == "a") - self.assertEqual(bad["status"], "failed") - self.assertNotIn("command", bad) - self.assertEqual(next(a for a in m["assets"] if a["id"] == "b")["status"], "ok") - self.assertFalse((self.out / "a.ptx").exists()) - - def test_missing_export_fails_validation_and_keeps_a_rejected_copy(self): - import os - os.environ["FAKE_NVCC_ENTRIES"] = "leleka_a" # the "compiler" forgets leleka_b - try: - code, out, _ = self.compile() - finally: - del os.environ["FAKE_NVCC_ENTRIES"] - self.assertEqual(code, 1) - self.assertIn("leleka_b", out) - self.assertTrue((self.out / "a.ptx.rejected").exists()) - - def test_nvcc_failure_is_reported_and_other_assets_continue(self): - import os - os.environ["FAKE_NVCC_FAIL"] = "a.cu" - try: - code, out, _ = self.compile() - finally: - del os.environ["FAKE_NVCC_FAIL"] - self.assertEqual(code, 1) - self.assertIn("nvcc exit 2", out) - self.assertTrue((self.out / "b.ptx").exists()) - - def test_seal_dry_run_then_write(self): - self.assertEqual(self.compile()[0], 0) - base = ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--rustfmt", "never"] - code, out, _ = run_quiet(S.main, base) - self.assertEqual(code, 0) - man = json.loads(out) - self.assertEqual(man["mode"], "dry-run") - self.assertEqual((self.root / "crates/cuda-driver/src/a.ptx").read_text(), "// UNSEALED placeholder\n") - code, out, _ = run_quiet(S.main, base + ["--write"]) - self.assertEqual(code, 0) - man = json.loads(out) - a = next(x for x in man["assets"] if x["id"] == "a") - b = next(x for x in man["assets"] if x["id"] == "b") - ptx_a = (self.root / "crates/cuda-driver/src/a.ptx").read_bytes() - ptx_b = (self.root / "crates/cuda-driver/src/b.ptx").read_bytes() - self.assertTrue(ptx_a.endswith(b"\0") and ptx_a.count(b"\0") == 1) # include_bytes - self.assertFalse(ptx_b.endswith(b"\0")) # concat_include_str - self.assertEqual(a["raw_sha256"], sh(ptx_a[:-1])) - self.assertEqual(b["raw_sha256"], sh(ptx_b)) - cons = (self.root / "crates/cuda-driver/src/cons.rs").read_text() - self.assertTrue(R.read_field(cons, "A_LEN", R.PinValues(len(ptx_a) - 1, hashlib.sha256(ptx_a[:-1]).digest(), b""))) - self.assertEqual(R.read_plain(cons, "A_LEN"), len(ptx_a) - 1) - self.assertEqual(R.read_ptxpin(cons, "B_PIN", None, "ptx_sha256"), hashlib.sha256(ptx_b).digest()) - cu_b = (self.root / "crates/cuda-driver/src/b.cu").read_bytes() - self.assertEqual(R.read_ptxpin(cons, "B_PIN", None, "source_sha256"), hashlib.sha256(cu_b).digest()) - self.assertEqual(sorted(man["touched_files"]), ["crates/cuda-driver/src/a.ptx", "crates/cuda-driver/src/b.ptx", - "crates/cuda-driver/src/cons.rs"]) - self.assertEqual(man["unsealed_placeholders_remaining"], []) - - def test_fake_output_is_refused_in_the_real_checkout_and_without_the_flag(self): - self.assertEqual(self.compile()[0], 0) - code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root)]) - self.assertEqual(code, 1) - self.assertIn("fake-nvcc", err) - code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--allow-fake"]) # root = this checkout - self.assertEqual(code, 1) - self.assertIn("scratch", err) - - def test_cu_changed_after_compile_is_refused(self): - self.assertEqual(self.compile()[0], 0) - (self.root / "crates/cuda-driver/src/b.cu").write_text('extern "C" __global__ void leleka_c(int x){} // edited\n') - code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake"]) - self.assertEqual(code, 1) - self.assertIn("changed after it was compiled", err) - - def test_stale_plan_pin_at_seal_time_is_refused(self): - self.assertEqual(self.compile()[0], 0) - plan = json.loads((self.root / "docs/cuda-seal-plan-mini.json").read_text()) - plan["assets"][0]["cu_pin"]["sha256"] = "1" * 64 - (self.root / "docs/cuda-seal-plan-mini.json").write_text(json.dumps(plan)) - code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake"]) - self.assertEqual(code, 1) - self.assertIn("stale source", err) - - def test_tampered_ptx_is_refused(self): - self.assertEqual(self.compile()[0], 0) - with open(self.out / "a.ptx", "a") as f: - f.write("// tampered\n") - code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake"]) - self.assertEqual(code, 1) - self.assertIn("does not match the manifest", err) - - def test_a_pin_field_that_matches_two_declarations_refuses_and_writes_nothing(self): - self.assertEqual(self.compile()[0], 0) - cons = self.root / "crates/cuda-driver/src/cons.rs" - cons.write_text(cons.read_text() + "mod t {\n const A_LEN: usize = 0;\n}\n") - before = cons.read_text() - code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--write"]) - self.assertEqual(code, 1) - self.assertIn("exactly one declaration", err) - self.assertEqual(cons.read_text(), before) - self.assertEqual((self.root / "crates/cuda-driver/src/a.ptx").read_text(), "// UNSEALED placeholder\n") - - def test_idempotent_reseal_of_identical_output(self): - self.assertEqual(self.compile()[0], 0) - base = ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--rustfmt", "never", "--write"] - self.assertEqual(run_quiet(S.main, base)[0], 0) - snap = (self.root / "crates/cuda-driver/src/cons.rs").read_text() - self.assertEqual(run_quiet(S.main, base)[0], 0) - self.assertEqual((self.root / "crates/cuda-driver/src/cons.rs").read_text(), snap) - - def test_flag_override_is_recorded_and_checked_by_the_sealer(self): - code, out, _ = self.compile("--flag-override", "b:-clearly-not-there") - self.assertEqual(code, 2) - shutil.rmtree(self.out, ignore_errors=True) - code, out, err = self.compile("--flag-override", "a:+--use_fast_math") - self.assertEqual(code, 0, out + err) - m = json.loads((self.out / "build-manifest.json").read_text()) - self.assertEqual(m["flag_overrides"], ["a:+--use_fast_math"]) - rec = next(r for r in m["assets"] if r["id"] == "a") - self.assertIn("--use_fast_math", rec["flags"]) - self.assertEqual(rec["flag_overrides"], ["a:+--use_fast_math"]) - base = ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--rustfmt", "never"] - self.assertEqual(run_quiet(S.main, base)[0], 0) # the sealer re-applies the recorded overrides - man = json.loads((self.out / "build-manifest.json").read_text()) - man["flag_overrides"] = [] - (self.out / "build-manifest.json").write_text(json.dumps(man)) - code, _, err = run_quiet(S.main, base) - self.assertEqual(code, 1) - self.assertIn("compiled with flags", err) - - def test_contradictory_override_is_stopped_by_the_lint(self): - code, out, _ = self.compile("--flag-override", "b:+--ftz=false") - self.assertEqual(code, 1) - self.assertIn("contradicts itself", out) - - def test_atomic_groups_must_move_together(self): - plan = json.loads((self.root / "docs/cuda-seal-plan-mini.json").read_text()) - for a in plan["assets"]: - a["atomic_group"] = "g" - (self.root / "docs/cuda-seal-plan-mini.json").write_text(json.dumps(plan)) - self.assertEqual(self.compile()[0], 0) - code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--only", "a"]) - self.assertEqual(code, 1) - self.assertIn("atomic group", err) - - -class RealTreeFakeSeal(unittest.TestCase): - """The whole checked-in plan set against a scratch copy: every field of every plan must patch and read back.""" - - def test_full_fake_pipeline_on_a_scratch_copy(self): - with tempfile.TemporaryDirectory() as d: - scratch = Path(d) / "tree" - ignore = shutil.ignore_patterns(".git", "target", "*.gguf") - for sub in ("crates", "docs", "deploy", "engine/strata/include", "engine/strata/third_party", "scripts/gpu-bringup"): - shutil.copytree(REPO / sub, scratch / sub, ignore=ignore) - out = Path(d) / "ptx" - code, _, err = run_quiet(C.main, ["--root", str(scratch), "--fake-nvcc", "--out", str(out), "--rope-flags", "preserve", - "--include-optional"]) - self.assertEqual(code, 0, err) - code, text, err = run_quiet(S.main, ["--ptx-dir", str(out), "--root", str(scratch), "--allow-fake", "--write", - "--rustfmt", "never"]) - self.assertEqual(code, 0, err) - man = json.loads(text) - self.assertEqual(len(man["assets"]), 33) - self.assertEqual(man["min_driver_required"], "580.65.06") - # the six fast-math reseals were re-pinned where the old digests lived, and the PLE length slot updated - by = {a["id"]: a for a in man["assets"]} - resealed = [a for a in man["assets"] if a["group"] == "reseal-fastmath"] - self.assertEqual(len(resealed), 6) - self.assertTrue(all("--use_fast_math" in a["flags"] and "--ftz=false" not in a["flags"] for a in resealed)) - self.assertEqual(sum(r["replacements"] for a in resealed for r in a["repins"] if r.get("kind") == "decimal"), 7) - ple = by["ple_native_batch"] - queue = (scratch / "crates/cuda-driver/src/ple_batch_queue.rs").read_text() - self.assertEqual(R.read_plain(queue, "PTX_BYTES"), ple["raw_bytes"]) - self.assertEqual(R.read_plain(queue, "PTX_SHA256"), bytes.fromhex(ple["raw_sha256"])) - gr = (scratch / "crates/cuda-driver/src/original_verify_window_gr.rs").read_text() - self.assertEqual(len(R.find_decimal_pins(gr, bytes.fromhex(ple["raw_sha256"]))), 1) - # idempotent on the second run of identical output - code, _, err = run_quiet(S.main, ["--ptx-dir", str(out), "--root", str(scratch), "--allow-fake", "--write", - "--rustfmt", "never"]) - self.assertEqual(code, 0, err) - abi = (scratch / L.ABI_SOURCE).read_text() - self.assertIn("state == AbiState::Extended,", abi) - - -# ---------------------------------------------------------------------------------- smoke inventory -class SmokeInventory(unittest.TestCase): - def test_every_real_ignore_attribute_is_found_and_comments_are_not(self): - smokes = SI.scan(REPO) - raw = 0 - for p in (REPO / "crates").rglob("*.rs"): - if "target" in p.parts: - continue - raw += len(re.findall(r"(?m)^[ \t]*#\[ignore", p.read_text(errors="replace"))) - self.assertEqual(len(smokes), raw) - self.assertGreaterEqual(len(smokes), 100) - self.assertFalse([s for s in smokes if s.file.endswith(("experimental.rs", "kar_decode_levels.rs"))]) - - def test_gates_values_and_classes_on_known_tests(self): - by = {s.name: s for s in SI.scan(REPO)} - win = by["sealed_window_assets_load_on_the_device_and_export_every_named_entry"] - self.assertEqual(win.gates, {"LELEKA_VERIFY_WINDOW_GPU": "yes"}) - self.assertEqual(win.klass, "device") - basic = by["installed_driver_fixed_kernels"] - self.assertEqual(basic.gates, {"LELEKA_CUDA_REAL_GPU": "1"}) - self.assertEqual(by["installed_driver_q5_numeric_refusals"].klass, "device") - self.assertEqual(by["installed_driver_q5_native_parity"].klass, "assets") - self.assertEqual(by["isolated_q5_protocol_matrix"].klass, "mock") - self.assertEqual(by["pinned_artifact_two_tokens_finish_all_layers_and_commit_state"].klass - if "pinned_artifact_two_tokens_finish_all_layers_and_commit_state" in by else "assets", "assets") - self.assertEqual(by["actual_expert215_native_resident_gu_and_same_source_down_diagnostic"].klass, "assets") - self.assertEqual(by["experimental_gpu_fwht256_matches_cpu"].gates, {}) - - def test_every_smoke_lands_in_a_declared_group_and_dependencies_precede(self): - data = SI.load_groups() - smokes = SI.scan(REPO) - SI.assign(smokes, data) - declared = {g["name"] for g in data["groups"]} | {data["asset_group"], data["mock_group"]} - self.assertEqual({s.group for s in smokes} - declared, set()) - self.assertEqual([s for s in smokes if s.group == data["fallback_group"]], [], "new smokes need a home in smoke-groups.json") - self.assertEqual(SI.unique_filters(smokes), []) - order = SI.select_order(data, None, [], False) - for g in data["groups"]: - for d in g["depends_on"]: - self.assertLess(order.index(d), order.index(g["name"])) - - def test_selection_pulls_in_dependencies_and_guards_assets(self): - data = SI.load_groups() - self.assertEqual(SI.select_order(data, ["runtime-gr"], [], False), ["driver-basic", "transport", "gr", "runtime-gr"]) - with self.assertRaises(SystemExit): - SI.select_order(data, ["model-assets"], [], False) - self.assertNotIn("model-assets", SI.select_order(data, None, [], False)) - self.assertIn("model-assets", SI.select_order(data, None, [], True)) - - def test_doc_table_is_current(self): - doc = REPO / "docs/gpu-bringup.md" - if not doc.exists(): - self.skipTest("docs/gpu-bringup.md not written yet") - smokes = SI.scan(REPO) - SI.assign(smokes, SI.load_groups()) - text = doc.read_text() - start, end = text.index(SI.TABLE_START) + len(SI.TABLE_START), text.index(SI.TABLE_END) - self.assertEqual(text[start:end].strip("\n"), SI.emit_table(smokes, markdown=True), - "run: python3 scripts/gpu-bringup/smoke_inventory.py --update-doc docs/gpu-bringup.md") - - def test_synthetic_tree(self): - with tempfile.TemporaryDirectory() as d: - src = Path(d) / "crates/cuda-driver/src" - src.mkdir(parents=True) - lines = [ - 'const ENABLE: &str = "LELEKA_X_GPU";', - '/// docs mention #[ignore] and "LELEKA_NOT_A_GATE"', - '#[test]', '#[ignore = "Root-only"]', 'fn a_smoke() {', - ' assert_eq!(std::env::var(ENABLE).as_deref(), Ok("yes"));', '}', - '#[test]', '#[ignore]', 'fn a_smoke_longer() {', - ' let _ = std::env::var("LELEKA_Y_SHARD0");', - ' assert_eq!(std::env::var("LELEKA_Y_RUN_Z").as_deref(), Ok("1"));', '}', - ] - (src / "x_gpu.rs").write_text("\n".join(lines) + "\n") - smokes = SI.scan(Path(d)) - self.assertEqual([s.name for s in smokes], ["a_smoke", "a_smoke_longer"]) - self.assertEqual(smokes[0].gates, {"LELEKA_X_GPU": "yes"}) - self.assertEqual(smokes[1].gates, {"LELEKA_Y_RUN_Z": "1"}) - self.assertEqual(smokes[1].klass, "assets") - self.assertEqual(smokes[0].expected, 2) # the cargo filter "a_smoke" also matches a_smoke_longer - - -STUB_CARGO = """#!/usr/bin/env bash -name="${@: -1}" -echo "running 1 test" -if [[ ",${STUB_FAIL:-}," == *",$name,"* ]]; then echo "test $name ... FAILED"; echo "test result: FAILED. 0 passed; 1 failed; 0 ignored"; exit 101; fi -if [[ ",${STUB_ZERO:-}," == *",$name,"* ]]; then echo "test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 90 filtered out"; exit 0; fi -echo "test $name ... ok"; echo "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 90 filtered out" -""" -STUB_SMI = """#!/usr/bin/env bash -case "$*" in - *query-gpu=driver_version\\ *) echo "${STUB_DRIVER:-595.91.07}" ;; - *query-compute-apps*) [[ -n "${STUB_BUSY:-}" ]] && echo "4242, strata, 1000 MiB" ;; - *memory.free*) echo "${STUB_FREE:-32000}" ;; - *query-gpu*) echo "2026/10/14 20:00:00.000, NVIDIA GeForce RTX 5090, 595.91, 100 MiB, 32607 MiB, 40, 30.0 W, 210 MHz, 405 MHz, 0 %" ;; - *) echo "nvidia-smi -q (stub)" ;; -esac -""" - - -class RunSmokesScript(unittest.TestCase): - script = HERE.parent / "run_gpu_smokes.sh" - - def setUp(self): - self.d = tempfile.TemporaryDirectory() - self.bin = Path(self.d.name) / "bin" - self.bin.mkdir() - for name, body in (("cargo", STUB_CARGO), ("nvidia-smi", STUB_SMI)): - (self.bin / name).write_text(body) - (self.bin / name).chmod(0o755) - self.run_dir = Path(self.d.name) / "run" - - def tearDown(self): - self.d.cleanup() - - def run_script(self, *args, **env): - e = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", SMOKES_ALLOW_NON_LINUX="1", **env) - return subprocess.run([str(self.script), *args], capture_output=True, text=True, env=e, cwd=str(REPO)) - - def results(self): - rows = [l.split("\t") for l in (self.run_dir / "results.tsv").read_text().splitlines()[1:]] - return {r[2]: r[3] for r in rows} - - def status(self, g): - return (self.run_dir / "status" / g).read_text().strip() - - def test_plan_mode_prints_commands_and_does_not_need_a_gpu(self): - p = self.run_script("--plan", "--groups", "seal-loads") - self.assertEqual(p.returncode, 0, p.stderr) - self.assertIn("LELEKA_VERIFY_WINDOW_GPU=yes cargo test --locked -p leleka-cuda-driver --features cuda-driver --lib", p.stdout) - self.assertIn("# dependency order: driver-basic seal-loads", p.stdout) - - def test_all_pass(self): - p = self.run_script("--run", "--run-dir", str(self.run_dir)) - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - self.assertEqual(set(self.results().values()), {"PASS"}) - self.assertTrue((self.run_dir / "nvidia-smi.before.txt").exists() and (self.run_dir / "nvidia-smi.after.txt").exists()) - self.assertIn("# group gr start", (self.run_dir / "gpu-timeline.csv").read_text()) - self.assertNotIn("model-assets", p.stdout) # never started by default - - def test_failure_stops_its_group_skips_dependents_and_continues_independent_groups(self): - p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_FAIL="fixed_down_pack_matches_original_upload_and_refuses_before_copy") - self.assertEqual(p.returncode, 1) - r = self.results() - self.assertTrue(r["fixed_down_pack_matches_original_upload_and_refuses_before_copy"].startswith("FAIL")) - self.assertTrue(r["complete_selected_matrices_match_legacy_64_row_bits"].startswith("PASS")) # before it in the group - self.assertTrue(r["prepared_routed_gate_up_reuses_exact_native_q8_and_refuses_invalid_owners"].startswith("NOT-RUN")) - self.assertEqual(self.status("transport"), "FAIL") - self.assertEqual(self.status("gr"), "SKIPPED-DEP") - self.assertEqual(self.status("runtime-gr"), "SKIPPED-DEP") - self.assertEqual(self.status("seal-loads"), "PASS") # independent of transport - self.assertEqual(self.status("new-pins"), "PASS") - - def test_a_filter_that_matches_nothing_is_a_failure(self): - p = self.run_script("--run", "--run-dir", str(self.run_dir), "--groups", "driver-basic", STUB_ZERO="installed_driver_fixed_kernels") - self.assertEqual(p.returncode, 1) - self.assertIn("filter matched nothing", self.results()["installed_driver_fixed_kernels"]) - - def test_first_group_failure_skips_everything_after(self): - p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_FAIL="installed_driver_fixed_kernels") - self.assertEqual(p.returncode, 1) - self.assertEqual(self.status("driver-basic"), "FAIL") - self.assertEqual({self.status(g) for g in ("seal-loads", "new-pins", "transport", "gr")}, {"SKIPPED-DEP"}) - - def test_old_driver_is_refused_because_the_tree_holds_ptx_isa_9_0(self): - p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_DRIVER="575.28") - self.assertEqual(p.returncode, 3) - self.assertIn("ISA 9.0", p.stdout) - self.assertIn("too old", p.stdout) - self.assertFalse(self.run_dir.exists()) - - def test_busy_gpu_and_low_vram_are_refused_without_touching_anything(self): - p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_BUSY="1") - self.assertEqual(p.returncode, 3) - self.assertIn("other processes hold the GPU", p.stderr) - self.assertFalse(self.run_dir.exists()) - p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_FREE="100") - self.assertEqual(p.returncode, 3) - - def test_model_assets_need_the_flag_and_the_caller_supplied_env(self): - p = self.run_script("--run", "--run-dir", str(self.run_dir), "--groups", "model-assets") - self.assertNotEqual(p.returncode, 0) - self.assertFalse(self.run_dir.exists()) - p = self.run_script("--run", "--run-dir", str(self.run_dir), "--groups", "model-assets", "--allow-model-runs") - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - self.assertIn("skipped", p.stdout) - self.assertTrue(all(v.startswith("SKIPPED") for v in self.results().values())) - - def test_existing_run_dir_is_never_reused(self): - self.run_dir.mkdir() - p = self.run_script("--run", "--run-dir", str(self.run_dir)) - self.assertEqual(p.returncode, 2) - - -STUB_SSH = """#!/usr/bin/env bash -# records the remote command (and stdin size) instead of connecting anywhere -shift_args=() -for a in "$@"; do case "$a" in -o) skip=1 ;; *) if [[ "${skip:-}" == 1 ]]; then skip=0; else shift_args+=("$a"); fi ;; esac; done -host="${shift_args[0]}"; remote="${shift_args[*]:1}" -printf '%s\t%s\n' "$host" "$remote" >> "$STUB_LOG" -case "$remote" in - test\\ -e*SEALED-MANIFEST.json) [[ -n "${STUB_SEALED:-}" ]] ;; - cat\\ *SEALED-MANIFEST.json) cat "$STUB_MANIFEST" ;; - test\\ -d*) exit 1 ;; - "bash -s") cat > "$STUB_LOG.script"; echo "BUILD OK" ;; - cat\\ \\>*) cat > /dev/null ;; - *) ;; -esac -""" -STUB_RSYNC = """#!/usr/bin/env bash -printf '%s\n' "$*" >> "$STUB_LOG.rsync" -for a in "$@"; do case "$a" in --files-from=*) cp "${a#--files-from=}" "$STUB_LOG.filesfrom" ;; esac; done -""" - - -class DriverIsaChecks(unittest.TestCase): - def test_table_and_checks(self): - self.assertEqual(L.min_driver_for(["8.7", "9.0"]), ("9.0", "580.65.06")) - self.assertEqual(L.driver_ok("595.91.07", ["8.7", "9.0"])[0], True) - self.assertEqual(L.driver_ok("580.65.06", ["9.0"])[0], True) - self.assertEqual(L.driver_ok("580.65.05", ["9.0"])[0], False) - self.assertEqual(L.driver_ok("570.26", ["8.7"])[0], True) - with self.assertRaises(L.PlanError): - L.min_driver_for(["9.9"]) - - def test_the_tree_really_mixes_8_7_and_9_0(self): - inv = L.isa_inventory(REPO) - self.assertIn("8.7", inv) - self.assertIn("9.0", inv) - - def test_cli_exit_codes(self): - code, out, _ = run_quiet(C.main, ["--isa-inventory", "--driver-check", "--driver-version", "575.0"]) - self.assertEqual(code, 1) - self.assertIn("too old", out) - self.assertEqual(run_quiet(C.main, ["--isa-inventory", "--driver-check", "--driver-version", "595.91.07"])[0], 0) - - -class RemoteSyncScript(unittest.TestCase): - """remote_sync.sh against stub ssh/rsync: argument construction and the safety refusals, no network.""" - - def setUp(self): - self.d = tempfile.TemporaryDirectory() - root = Path(self.d.name) - self.repo = root / "repo" - (self.repo / "scripts/gpu-bringup").mkdir(parents=True) - shutil.copy(HERE.parent / "remote_sync.sh", self.repo / "scripts/gpu-bringup/remote_sync.sh") - (self.repo / "tracked.txt").write_text("x\n") - env = dict(os.environ, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@t", GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@t") - for cmd in (["init", "-q"], ["add", "-A"], ["commit", "-q", "-m", "x"]): - subprocess.run(["git", "-C", str(self.repo), *cmd], check=True, env=env, capture_output=True) - self.bin = root / "bin" - self.bin.mkdir() - for name, body in (("ssh", STUB_SSH), ("rsync", STUB_RSYNC)): - (self.bin / name).write_text(body) - (self.bin / name).chmod(0o755) - self.log = root / "stub.log" - self.manifest = root / "manifest.json" - self.manifest.write_text(json.dumps({"created_utc": "t", "mode": "write", "touched_files": ["crates/a.ptx", "docs/x.json"]})) - - def tearDown(self): - self.d.cleanup() - - def run_sync(self, *args, **env): - e = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", STUB_LOG=str(self.log), STUB_MANIFEST=str(self.manifest), **env) - return subprocess.run([str(self.repo / "scripts/gpu-bringup/remote_sync.sh"), *args, "--host", "h", "--remote-dir", "~/work/x"], - capture_output=True, text=True, env=e) - - def rsync_calls(self): - p = Path(str(self.log) + ".rsync") - return p.read_text().splitlines() if p.exists() else [] - - def test_dry_run_sync_uses_rsync_n_with_the_excludes_and_never_deletes(self): - p = self.run_sync("sync", "--dry-run") - self.assertEqual(p.returncode, 0, p.stderr) - (call,) = self.rsync_calls() - for needle in (" -n", "--exclude .git", "--exclude target", "--exclude *.gguf", "--max-size=200m", "h:~/work/x/"): - self.assertIn(needle, call) - self.assertNotIn("--delete", call) - self.assertFalse((Path(str(self.log) + ".script")).exists()) - - def test_real_sync_records_the_head_and_creates_only_the_dedicated_dir(self): - p = self.run_sync("sync") - self.assertEqual(p.returncode, 0, p.stderr) - log = self.log.read_text() - self.assertIn("mkdir -p work/x", log) - self.assertIn(".synced-from-head", log) - - def test_unpulled_sealed_files_block_a_second_sync(self): - p = self.run_sync("sync", STUB_SEALED="1") - self.assertEqual(p.returncode, 1) - self.assertIn("pull-sealed", p.stderr) - self.assertEqual(self.rsync_calls(), []) - p = self.run_sync("sync", "--force-overwrite-sealed", STUB_SEALED="1") - self.assertEqual(p.returncode, 0, p.stderr) - - def test_dirty_tracked_tree_is_refused_unless_allowed(self): - (self.repo / "tracked.txt").write_text("changed\n") - p = self.run_sync("sync", "--dry-run") - self.assertEqual(p.returncode, 1) - self.assertIn("commit first", p.stderr) - self.assertEqual(self.run_sync("sync", "--dry-run", "--allow-dirty").returncode, 0) - - def test_remote_dir_must_be_a_dedicated_dir_below_home(self): - for bad in ("/", "~", "~/", "/etc/x", "~/../x", "/home/para", "~/a b", "~/a;b", "~/$(x)"): - e = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", STUB_LOG=str(self.log)) - p = subprocess.run([str(self.repo / "scripts/gpu-bringup/remote_sync.sh"), "sync", "--dry-run", "--host", "h", "--remote-dir", bad], - capture_output=True, text=True, env=e) - self.assertEqual(p.returncode, 2, (bad, p.stderr)) - - def test_build_script_has_the_three_binaries_and_the_no_run_test_builds(self): - p = self.run_sync("build", "--jobs", "4") - self.assertEqual(p.returncode, 0, p.stderr) - script = Path(str(self.log) + ".script").read_text() - self.assertIn("cargo build --release --locked -j 4 -p strata-desktop-core --bin leleka-cli --bin leleka-daemon --bin leleka-inference", script) - self.assertIn("cargo test --no-run --locked -j 4 -p leleka-cuda-driver --features cuda-driver", script) - self.assertIn("-p leleka-runtime", script) - self.assertIn("nice -n 10", script) - self.assertIn("cargo fetch --locked", script) - self.assertNotIn("cargo run", script) - - def test_pull_sealed_transfers_exactly_the_manifest_files(self): - p = self.run_sync("pull-sealed") - self.assertEqual(p.returncode, 0, p.stderr) - self.assertEqual(Path(str(self.log) + ".filesfrom").read_text().split(), ["crates/a.ptx", "docs/x.json"]) - self.manifest.write_text(json.dumps({"created_utc": "t", "touched_files": ["../../etc/passwd"]})) - p = self.run_sync("pull-sealed") - self.assertNotEqual(p.returncode, 0) - self.assertIn("unsafe path", p.stderr) - - -class FakeToolkitThroughTheRealPath(unittest.TestCase): - """--toolkit: provenance must equal the lock; the version check runs; a mismatching nvcc is refused.""" - - def make_tk(self, root: Path, lock_override=None, version="13.2.86"): - tk = root / "tk" - (tk / "bin").mkdir(parents=True) - nvcc = tk / "bin" / "nvcc" - nvcc.write_text("#!/usr/bin/env bash\nif [[ \"$1\" == --version ]]; then echo 'Cuda compilation tools, release 13.0, V%s'; exit 0; fi\n" - "exec %s \"$@\"\n" % (version, HERE.parent / "fake-nvcc")) - nvcc.chmod(0o755) - lock = json.loads((REPO / L.TOOLKIT_LOCK).read_text()) - (tk / "TOOLKIT-PROVENANCE.json").write_text(json.dumps({"lock": lock_override or lock})) - return tk - - def test_toolkit_path_with_matching_provenance_and_version(self): - with tempfile.TemporaryDirectory() as d: - tk = self.make_tk(Path(d)) - code, out, err = run_quiet(C.main, ["--toolkit", str(tk), "--out", str(Path(d) / "o"), "--rope-flags", "preserve", "--only", "device_poison"]) - self.assertEqual(code, 1, out + err) # real path: fake-nvcc output carries the FAKE marker and is rejected - self.assertIn("fake-nvcc output", out) - - def test_wrong_provenance_and_wrong_version_are_refused(self): - with tempfile.TemporaryDirectory() as d: - tk = self.make_tk(Path(d), lock_override={"release": "other"}) - with self.assertRaises(L.PlanError): - C.locate_nvcc(type("A", (), {"fake_nvcc": False, "nvcc": None, "toolkit": str(tk), "allow_unprovenanced": False})(), REPO) - with tempfile.TemporaryDirectory() as d: - tk = self.make_tk(Path(d), version="13.2.2") - code, _, err = run_quiet(C.main, ["--toolkit", str(tk), "--out", str(Path(d) / "o"), "--rope-flags", "preserve", "--only", "device_poison"]) - self.assertEqual(code, 2) - self.assertIn("13.2.2", err) - self.assertIn("13.2.86", err) - - -if __name__ == "__main__": - unittest.main(verbosity=1) +#!/usr/bin/env python3 +"""Unit tests for the GPU bring-up toolkit. Plain unittest: `python3 scripts/gpu-bringup/tests/test_gpu_bringup.py` +(pytest also collects it). No GPU, nvcc or network is used; compile tests run scripts/gpu-bringup/fake-nvcc.""" +import contextlib +import hashlib +import io +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent)) +import bringup_lib as L # noqa: E402 +import compile_assets as C # noqa: E402 +import rustpins as R # noqa: E402 +import seal_pins as S # noqa: E402 +import smoke_inventory as SI # noqa: E402 + +REPO = L.REPO +V = R.PinValues(raw_len=1234, ptx_sha256=hashlib.sha256(b"ptx").digest(), source_sha256=hashlib.sha256(b"cu").digest()) + + +def sh(b: bytes) -> str: + return hashlib.sha256(b).hexdigest() + + +# --------------------------------------------------------------------------------------- plan parsing +class PlanParsing(unittest.TestCase): + def test_every_checked_in_plan_loads_and_cu_pins_are_current(self): + assets, _ = L.load_all_assets(REPO, "precise") + self.assertGreaterEqual(len(assets), 24) + for a in assets: + status, detail = L.check_cu_pin(REPO, a) + self.assertIn(status, ("ok", "unpinned"), detail) + + def test_groups_cover_all_three_plan_formats_and_rope(self): + assets, _ = L.load_all_assets(REPO, "preserve") + groups = {a.group for a in assets} + self.assertTrue({"additions", "experimental", "window", "rope", "kar"} <= groups) + + def test_window_new_sources_become_assets_with_pin_targets(self): + assets, _ = L.load_all_assets(REPO, None) + moe = next(a for a in assets if a.id == "original_verify_window_moe_experts") + self.assertEqual(moe.pin_fields, {"original_verify_window_moe.rs": ["EXPERTS.sha"]}) + self.assertIn("-Iengine/strata/include", [f"-I{d}" for d in moe.includes]) + self.assertNotIn("-Iengine/strata/include", moe.flags) + self.assertEqual(len(moe.entries), 16) + self.assertEqual(moe.encoding, "include_bytes") + gate = next(a for a in assets if a.id == "original_verify_window_qsa_gate") + self.assertIn("--use_fast_math", gate.flags) + self.assertNotIn("--ftz=false", gate.flags) + + def test_experimental_plan_is_raw_encoding_with_six_pin_slots(self): + assets, _ = L.load_all_assets(REPO, None) + exp = [a for a in assets if a.group == "experimental"] + self.assertEqual(len(exp), 6) + self.assertTrue(all(a.encoding == "concat_include_str" for a in exp)) + self.assertEqual(sorted(f for a in exp for v in a.pin_fields.values() for f in v), + sorted(f"PINS[{i}].{k}" for i in range(6) for k in ("source_sha256", "ptx_sha256"))) + + def test_unrecognised_plan_format_is_an_error(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "cuda-seal-plan-x.json" + p.write_text(json.dumps({"schema": 1, "stuff": []})) + with self.assertRaises(L.PlanError): + L.load_plan_file(p) + + def test_duplicate_ids_across_plans_are_an_error(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d) + (root / "docs").mkdir() + entry = {"cu": "a.cu", "ptx": "x/a.ptx", "flags": ["-ptx"]} + for n in ("a", "b"): + (root / "docs" / f"cuda-seal-plan-{n}.json").write_text(json.dumps({"assets": [entry]})) + with self.assertRaises(L.PlanError): + L.load_all_assets(root, None) + + def test_rope_list_and_abi_are_read_from_the_docs_not_hardcoded(self): + flags, incs, sources = L.parse_rope_doc((REPO / L.ROPE_DOC).read_text()) + self.assertEqual(sources, ["qsa_prompt_indexer", "qsa_prompt_postops", "qsa_decode_postops", "qsa_prompt_resolver"]) + self.assertEqual(flags, ["--ptx", "-std=c++17", "-O3", "-arch=sm_120", "--fmad=true", "--ftz=false"]) + self.assertEqual(incs, L.STANDARD_INCLUDES) + abi = L.parse_abi_tuples((REPO / L.ABI_SOURCE).read_text()) + self.assertEqual(abi["qsa_prompt_resolver.ptx"], {"leleka_qsa_stream_reset": (7, 2), "leleka_qsa_resolve": (10, 1)}) + self.assertEqual(abi["qsa_prompt_indexer.ptx"]["qsa_append_blocks"], (13, 5)) + + def test_rope_variants_differ_only_for_the_two_fast_math_sources(self): + precise = {a.id: a for a in L.rope_assets(REPO, "precise")} + keep = {a.id: a for a in L.rope_assets(REPO, "preserve")} + for name in precise: + if name in L.ROPE_FASTMATH_SOURCES: + self.assertIn("--use_fast_math", keep[name].flags) + self.assertNotIn("--ftz=false", keep[name].flags) + self.assertIn("--ftz=false", precise[name].flags) + else: + self.assertEqual(precise[name].flags, keep[name].flags) + self.assertEqual(precise["qsa_prompt_indexer"].params["qsa_append_first"], 11) + with self.assertRaises(L.PlanError): + L.rope_assets(REPO, "bogus") + + def test_committed_rope_ptx_were_built_fast_math_for_the_two_sources(self): + # evidence behind decision D1 in docs/gpu-bringup.md + keep = {a.id: a for a in L.rope_assets(REPO, "preserve")} + self.assertGreater(L.committed_fastmath_evidence(REPO, keep["qsa_prompt_indexer"]), 0) + self.assertGreater(L.committed_fastmath_evidence(REPO, keep["qsa_decode_postops"]), 0) + self.assertEqual(L.committed_fastmath_evidence(REPO, keep["qsa_prompt_resolver"]), 0) + + +# ---------------------------------------------------------------------------------------- pin logic +class CuPinLogic(unittest.TestCase): + def setUp(self): + self.d = tempfile.TemporaryDirectory() + self.root = Path(self.d.name) + (self.root / "k.cu").write_bytes(b"__global__ void k(){}\n") + + def tearDown(self): + self.d.cleanup() + + def asset(self, pin): + return L.Asset(id="k", cu="k.cu", ptx="k.ptx", flags=["-ptx"], cu_pin=pin) + + def test_ok_stale_bytes_unpinned_missing(self): + data = (self.root / "k.cu").read_bytes() + good = {"sha256": sh(data), "bytes": len(data)} + self.assertEqual(L.check_cu_pin(self.root, self.asset(good))[0], "ok") + self.assertEqual(L.check_cu_pin(self.root, self.asset({"sha256": "0" * 64, "bytes": len(data)}))[0], "stale") + self.assertEqual(L.check_cu_pin(self.root, self.asset({"sha256": sh(data), "bytes": 1}))[0], "stale") + self.assertEqual(L.check_cu_pin(self.root, self.asset(None))[0], "unpinned") + a = self.asset(None) + a.cu = "nope.cu" + self.assertEqual(L.check_cu_pin(self.root, a)[0], "missing") + + def test_include_resolution(self): + (self.root / "inc").mkdir() + (self.root / "inc" / "h.hpp").write_text('#include "deep.hpp"\n') + (self.root / "inc" / "deep.hpp").write_text("\n") + (self.root / "k.cu").write_text('#include "h.hpp"\n#include "gone.hpp"\n#include \n') + a = self.asset(None) + a.includes = ["inc"] + self.assertEqual(L.resolve_includes(self.root, a), ["gone.hpp (from k.cu)"]) + + +class PolicyLint(unittest.TestCase): + def mk(self, flags, policy): + return L.Asset(id="x", cu="x.cu", ptx="x.ptx", flags=flags, policy=policy) + + def test_cases(self): + self.assertEqual(L.policy_conflicts(self.mk(["--use_fast_math"], "Original native_qsa fastmath")), []) + self.assertEqual(L.policy_conflicts(self.mk([], "Original device.cu; not in the CMake fast-math list")), []) + self.assertEqual(L.policy_conflicts(self.mk([], "precise (not in CMake fast-math list)")), []) + self.assertTrue(L.policy_conflicts(self.mk(["--use_fast_math"], "precise"))) + self.assertTrue(L.policy_conflicts(self.mk([], "fast-math"))) + self.assertTrue(L.policy_conflicts(self.mk(["--use_fast_math", "--ftz=false"], ""))) + + def test_checked_in_plans_have_no_conflicts(self): + assets, _ = L.load_all_assets(REPO, "preserve") + self.assertEqual([(a.id, L.policy_conflicts(a)) for a in assets if L.policy_conflicts(a)], []) + + +class PtxValidation(unittest.TestCase): + def ptx(self, entries=("k",), extra=""): + body = ".version 8.7\n.target sm_120\n.address_size 64\n" + for e in entries: + body += f".visible .entry {e}(\n\t.param .u64 {e}_param_0,\n\t.param .u32 {e}_param_1\n)\n{{\n\tret;\n}}\n" + return (body + extra).encode() + + def asset(self, **kw): + return L.Asset(id="x", cu="x.cu", ptx="x.ptx", flags=[], entries=["k"], **kw) + + def test_accepts_good(self): + self.assertEqual(L.validate_ptx(self.ptx(), self.asset()), []) + + def test_rejections(self): + a = self.asset() + self.assertTrue(L.validate_ptx(b"", a)) + self.assertTrue(any("NUL" in m for m in L.validate_ptx(self.ptx() + b"\0", a))) + self.assertTrue(any("ASCII" in m for m in L.validate_ptx(self.ptx() + "é".encode(), a))) + self.assertTrue(any("sm_120" in m for m in L.validate_ptx(self.ptx().replace(b"sm_120", b"sm_90"), a))) + self.assertTrue(any("UNSEALED" in m for m in L.validate_ptx(self.ptx(extra="// UNSEALED\n"), a))) + self.assertTrue(any("missing" in m for m in L.validate_ptx(self.ptx(("other",)), a))) + self.assertTrue(any("fake" in m for m in L.validate_ptx(self.ptx(extra="// FAKE-NVCC\n"), a))) + self.assertEqual(L.validate_ptx(self.ptx(extra="// FAKE-NVCC\n"), a, allow_fake=True), []) + + def test_refuses_ptx_built_by_nvcc_13_2_0_or_13_2_1(self): + a = self.asset() + header = "// Cuda compilation tools, release 13.2, V{}" + chr(10) + for build in ("13.2.0", "13.2.1", "13.2.51"): + problems = L.validate_ptx(self.ptx(extra=header.format(build)), a) + self.assertTrue(any(build in m and "miscompiles" in m for m in problems), (build, problems)) + # the pinned and the older toolchains, and a header-less body (fake-nvcc output), stay acceptable + for build in ("13.2.86", "13.2.2", "13.0.88", "12.8.93", "13.2.10", "13.2.100"): + self.assertEqual(L.validate_ptx(self.ptx(extra=header.format(build)), a), [], build) + self.assertEqual(L.validate_ptx(self.ptx(), a), []) + + def test_every_sealed_ptx_in_the_tree_names_a_good_nvcc(self): + seen = 0 + for path in sorted((REPO / "crates").rglob("*.ptx")): + if "target" in path.parts: + continue + build = L.nvcc_build_of(path.read_bytes()[:4096].decode("latin-1")) + seen += build is not None + self.assertNotIn(build, L.BAD_NVCC_BUILDS, str(path)) + self.assertGreater(seen, 100) + + def test_entry_regex_like_the_reference_seal_script(self): + text = ".visible .entry a(\n)\n.weak .entry b(\n)\n .entry c(\n)\n// .entry d(\n" + self.assertEqual(L.ptx_entries(text), ["a", "b", "c"]) + + def test_param_counts_and_prefix_counts(self): + a = self.asset(params={"k": 2}) + self.assertEqual(L.validate_ptx(self.ptx(), a), []) + a.params = {"k": 3} + self.assertTrue(any("params" in m for m in L.validate_ptx(self.ptx(), a))) + b = L.Asset(id="m", cu="m.cu", ptx="m.ptx", flags=[], entry_prefix_counts={"_Z9mul": 2}) + self.assertEqual(L.validate_ptx(self.ptx(("_Z9mul_a", "_Z9mul_b")), b), []) + self.assertTrue(L.validate_ptx(self.ptx(("_Z9mul_a",)), b)) + + def test_encodings(self): + self.assertEqual(L.stored_bytes(b"abc", "include_bytes"), b"abc\0") + self.assertEqual(L.stored_bytes(b"abc", "concat_include_str"), b"abc") + self.assertEqual(L.raw_from_stored(b"abc\0"), b"abc") + self.assertEqual(L.raw_from_stored(b"abc"), b"abc") + with self.assertRaises(L.PlanError): + L.stored_bytes(b"x", "weird") + + def test_derive_entries_drops_macro_names(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d) + (root / "k.cu").write_text('extern "C" __global__ void NAME(int x){}\nextern "C" __global__ void real_k(int x){}\n' + 'extern "C" __global__ __launch_bounds__(256) void other_k(int x){}\n') + a = L.Asset(id="k", cu="k.cu", ptx="k.ptx", flags=[]) + self.assertEqual(L.derive_entries(root, a), ["real_k", "other_k"]) + + +# ------------------------------------------------------------------------------------ rust pin forms +PINS_REPEAT = """\ +/// doc +pub const PINS: [PtxPin; 3] = [PtxPin { + source_sha256: [0; 32], + ptx_sha256: [0; 32], +}; 3]; +""" +OTHER = "const A: usize = 0;\n" + + +class RustPinForms(unittest.TestCase): + def test_ptxpin_array_repeat_form_expands_and_reads_back(self): + t = R.apply_field(PINS_REPEAT, "PINS[1].ptx_sha256", V) + self.assertTrue(R.read_field(t, "PINS[1].ptx_sha256", V)) + self.assertEqual(R.read_ptxpin(t, "PINS", 0, "ptx_sha256"), bytes(32)) + self.assertEqual(R.read_ptxpin(t, "PINS", 2, "source_sha256"), bytes(32)) + t = R.apply_field(t, "PINS[1].source_sha256", V) + self.assertEqual(R.read_ptxpin(t, "PINS", 1, "source_sha256"), V.source_sha256) + self.assertEqual(t.count("PtxPin {"), 3) + with self.assertRaises(R.PinError): + R.apply_field(t, "PINS[3].ptx_sha256", V) + + def test_ptxpin_single_struct(self): + src = "pub const P: PtxPin = PtxPin {\n source_sha256: [0; 32],\n ptx_sha256: [0; 32],\n};\n" + t = R.apply_field(R.apply_field(src, "P.source_sha256", V), "P.ptx_sha256", V) + self.assertTrue(R.read_field(t, "P.source_sha256", V) and R.read_field(t, "P.ptx_sha256", V)) + for line in t.splitlines(): + self.assertLessEqual(len(line), 100) + + def test_asset_spec_sha(self): + src = 'static E: AssetSpec = AssetSpec {\n name: "x.ptx",\n ptx: include_bytes!("x.ptx"),\n sha: [0; 32],\n entries: &[],\n};\n' + t = R.apply_field(src, "E.sha", V) + self.assertTrue(R.read_field(t, "E.sha", V)) + self.assertEqual(t.count("sha:"), 1) + self.assertIn('name: "x.ptx"', t) + # already sealed with the unspaced style used in the window files keeps its style + again = R.apply_field(t.replace(", ", ","), "E.sha", V) + self.assertNotIn(", ", again.split("sha:")[1].split("]")[0]) + + def test_option_tuple_array_len_includes_the_nul(self): + src = "const SEALED: [Option<(usize, [u8; 32])>; 3] = [None, None, None];\n" + t = R.apply_field(src, "SEALED[2]", V) + self.assertEqual(R.read_pin_array(t, "SEALED", 2), (V.raw_len + 1, V.ptx_sha256)) + self.assertIsNone(R.read_pin_array(t, "SEALED", 0)) + t = R.apply_field(t, "SEALED[0]", V) + self.assertEqual(R.read_pin_array(t, "SEALED", 0)[0], 1235) + + def test_plain_const_types(self): + for decl, spec, want in [ + ("const L: usize = 0;", "L", 1234), + ("const L: Option = None;", "L", 1234), + ("const D: [u8; 32] = [0; 32];", "D", V.ptx_sha256), + ("const D: Option<[u8; 32]> = None;", "D", V.ptx_sha256), + ("const T: Option<(usize, [u8; 32])> = None;", "T", (1235, V.ptx_sha256)), + ]: + t = R.apply_field(decl + "\n", spec, V) + self.assertEqual(R.read_plain(t, spec), want, decl) + self.assertTrue(R.read_field(t, spec, V)) + + def test_option_slice_assets_are_refused_not_guessed(self): + with self.assertRaises(R.PinError): + R.apply_field("const ASSET: Option<&[u8]> = None;\n", "ASSET", V) + + def test_exactly_one_declaration_or_refuse(self): + two = OTHER + "mod t {\n const A: usize = 0;\n}\n" + with self.assertRaises(R.PinError): + R.apply_field(two, "A", V) + with self.assertRaises(R.PinError): + R.apply_field(OTHER, "MISSING", V) + with self.assertRaises(R.PinError): + R.apply_field(OTHER, "A.bogus", V) + + def test_strings_and_comments_do_not_confuse_the_scanner(self): + src = 'const X: usize = 0; // trailing; semicolon\nconst S: &str = "a;b";\nconst PINS: [PtxPin; 1] = [PtxPin { source_sha256: [0; 32], ptx_sha256: [0; 32] }; 1];\n' + t = R.apply_field(src, "X", V) + self.assertIn("const X: usize = 1234;", t) + self.assertIn('"a;b"', t) + + def test_real_repo_declarations_patch_and_read_back(self): + src = REPO / "crates/cuda-driver/src" + cases = [ + ("experimental.rs", [f"PINS[{i}].{k}" for i in range(6) for k in ("source_sha256", "ptx_sha256")]), + ("kar_decode_levels.rs", ["KAR_DECODE_LEVELS_PIN.source_sha256", "KAR_DECODE_LEVELS_PIN.ptx_sha256"]), + ("original_verify_window_moe.rs", ["EXPERTS.sha"]), + ("original_verify_window_qsa.rs", ["GATE.sha"]), + ("mmq_original_group.rs", ["SEALED[0]", "SEALED[1]", "SEALED[2]"]), + ] + for name, specs in cases: + t = (src / name).read_text() + for s in specs: + t = R.apply_field(t, s, V) + for s in specs: + self.assertTrue(R.read_field(t, s, V), (name, s)) + + def test_already_sealed_consumers_are_recognised_as_resealable(self): + t = (REPO / "crates/cuda-driver/src/gdn_fused_t1.rs").read_text() + t2 = R.apply_field(R.apply_field(t, "FUSED_PTX_LEN", V), "FUSED_PTX_SHA256", V) + self.assertEqual(R.read_plain(t2, "FUSED_PTX_LEN"), 1234) + self.assertNotEqual(t, t2) + + def test_repin_decimal_inline_and_wrapped(self): + old = hashlib.sha256(b"old").digest() + new = V.ptx_sha256 + inline = "x: [" + ",".join(map(str, old)) + "],\n" + out, n = R.repin_decimal(inline, old, new) + self.assertEqual(n, 1) + self.assertEqual(out, "x: [" + ",".join(map(str, new)) + "],\n") + wrapped = " sha: " + R.render_digest(old, " ", wrapped=True) + ",\n" + out, n = R.repin_decimal(wrapped, old, new) + self.assertEqual(n, 1) + self.assertEqual(R.find_decimal_pins(out, new).__len__(), 1) + self.assertEqual(R.repin_decimal("nothing", old, new), ("nothing", 0)) + + def test_placeholder_test_finder(self): + t = '#[test]\nfn a_placeholder_check() {\n assert_eq!(P.sha, [0; 32]);\n}\n#[test]\nfn fine() {\n assert!(true);\n}\n' + self.assertEqual(R.placeholder_tests(t), ["a_placeholder_check"]) + + +# --------------------------------------------------------------- end-to-end on a miniature repository +def mini_repo(root: Path, cu_pin=True): + src = root / "crates/cuda-driver/src" + src.mkdir(parents=True) + (root / "docs").mkdir() + (root / "deploy").mkdir() + (root / "deploy/cuda-toolkit.lock.json").write_text(json.dumps({"components": [{"component": "cuda_nvcc", "version": "13.2.86"}]})) + cu = 'extern "C" __global__ void leleka_a(int x){}\nextern "C" __global__ void leleka_b(int x){}\n' + (src / "a.cu").write_text(cu) + (src / "b.cu").write_text(cu.replace("leleka_a", "leleka_c").replace("leleka_b", "leleka_d")) + (src / "a.ptx").write_text("// UNSEALED placeholder\n") + (src / "b.ptx").write_text("// UNSEALED placeholder\n") + pin_a = {"sha256": sh(cu.encode()), "bytes": len(cu)} if cu_pin else {"sha256": "0" * 64, "bytes": 1} + plan = {"schema": 1, "assets": [ + {"cu": "crates/cuda-driver/src/a.cu", "cu_pin": pin_a, "ptx": "crates/cuda-driver/src/a.ptx", + "flags": ["-ptx", "-O3", "-arch=sm_120"], "policy": "precise", "entries": ["leleka_a", "leleka_b"], + "encoding": "include_bytes", "rust_fields_to_fill": {"cons.rs": ["A_LEN", "A_SHA"]}}, + {"cu": "crates/cuda-driver/src/b.cu", "ptx": "crates/cuda-driver/src/b.ptx", "flags": ["-ptx", "--use_fast_math"], + "policy": "fastmath", "encoding": "concat_include_str", + "rust_fields_to_fill": {"cons.rs": ["B_PIN.source_sha256", "B_PIN.ptx_sha256"]}}, + ]} + (root / "docs/cuda-seal-plan-mini.json").write_text(json.dumps(plan)) + (src / "cons.rs").write_text( + "const A_LEN: usize = 0;\nconst A_SHA: [u8; 32] = [0; 32];\n" + "pub const B_PIN: PtxPin = PtxPin {\n source_sha256: [0; 32],\n ptx_sha256: [0; 32],\n};\n") + + +def run_quiet(fn, *a): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = fn(*a) + return code, out.getvalue(), err.getvalue() + + +class EndToEnd(unittest.TestCase): + def setUp(self): + self.d = tempfile.TemporaryDirectory() + self.root = Path(self.d.name) / "repo" + self.out = Path(self.d.name) / "ptx" + mini_repo(self.root) + + def tearDown(self): + self.d.cleanup() + + def compile(self, *extra): + return run_quiet(C.main, ["--root", str(self.root), "--fake-nvcc", "--no-rope", "--out", str(self.out), *extra]) + + def test_dry_run_prints_commands_and_runs_nothing(self): + code, out, _ = run_quiet(C.main, ["--root", str(self.root), "--dry-run", "--no-rope"]) + self.assertEqual(code, 0) + self.assertIn("nvcc -ptx -O3 -arch=sm_120 crates/cuda-driver/src/a.cu -o", out) + self.assertIn("--use_fast_math crates/cuda-driver/src/b.cu", out) + self.assertFalse(self.out.exists()) + + def test_rope_flags_are_mandatory_when_rope_is_selected(self): + code, _, err = run_quiet(C.main, ["--root", str(REPO), "--dry-run"]) + self.assertEqual(code, 2) + self.assertIn("--rope-flags", err) + + def test_fake_compile_writes_ptx_and_manifest(self): + code, _, _ = self.compile() + self.assertEqual(code, 0) + m = json.loads((self.out / "build-manifest.json").read_text()) + self.assertTrue(m["fake"]) + self.assertEqual([a["id"] for a in m["assets"]], ["a", "b"]) + self.assertTrue(all(a["status"] == "ok" and a["cu_sha256"] for a in m["assets"])) + text = (self.out / "a.ptx").read_text() + self.assertIn(".entry leleka_a(", text) + self.assertIn("FAKE-NVCC", text) + self.assertEqual(code, 0) + # a second run into the same directory is refused + self.assertEqual(self.compile()[0], 2) + + def test_stale_cu_pin_is_refused_before_nvcc_runs(self): + shutil.rmtree(self.root) + mini_repo(self.root, cu_pin=False) + code, out, _ = self.compile() + self.assertEqual(code, 1) + self.assertIn("refusing", out) + m = json.loads((self.out / "build-manifest.json").read_text()) + bad = next(a for a in m["assets"] if a["id"] == "a") + self.assertEqual(bad["status"], "failed") + self.assertNotIn("command", bad) + self.assertEqual(next(a for a in m["assets"] if a["id"] == "b")["status"], "ok") + self.assertFalse((self.out / "a.ptx").exists()) + + def test_missing_export_fails_validation_and_keeps_a_rejected_copy(self): + import os + os.environ["FAKE_NVCC_ENTRIES"] = "leleka_a" # the "compiler" forgets leleka_b + try: + code, out, _ = self.compile() + finally: + del os.environ["FAKE_NVCC_ENTRIES"] + self.assertEqual(code, 1) + self.assertIn("leleka_b", out) + self.assertTrue((self.out / "a.ptx.rejected").exists()) + + def test_nvcc_failure_is_reported_and_other_assets_continue(self): + import os + os.environ["FAKE_NVCC_FAIL"] = "a.cu" + try: + code, out, _ = self.compile() + finally: + del os.environ["FAKE_NVCC_FAIL"] + self.assertEqual(code, 1) + self.assertIn("nvcc exit 2", out) + self.assertTrue((self.out / "b.ptx").exists()) + + def test_seal_dry_run_then_write(self): + self.assertEqual(self.compile()[0], 0) + base = ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--rustfmt", "never"] + code, out, _ = run_quiet(S.main, base) + self.assertEqual(code, 0) + man = json.loads(out) + self.assertEqual(man["mode"], "dry-run") + self.assertEqual((self.root / "crates/cuda-driver/src/a.ptx").read_text(), "// UNSEALED placeholder\n") + code, out, _ = run_quiet(S.main, base + ["--write"]) + self.assertEqual(code, 0) + man = json.loads(out) + a = next(x for x in man["assets"] if x["id"] == "a") + b = next(x for x in man["assets"] if x["id"] == "b") + ptx_a = (self.root / "crates/cuda-driver/src/a.ptx").read_bytes() + ptx_b = (self.root / "crates/cuda-driver/src/b.ptx").read_bytes() + self.assertTrue(ptx_a.endswith(b"\0") and ptx_a.count(b"\0") == 1) # include_bytes + self.assertFalse(ptx_b.endswith(b"\0")) # concat_include_str + self.assertEqual(a["raw_sha256"], sh(ptx_a[:-1])) + self.assertEqual(b["raw_sha256"], sh(ptx_b)) + cons = (self.root / "crates/cuda-driver/src/cons.rs").read_text() + self.assertTrue(R.read_field(cons, "A_LEN", R.PinValues(len(ptx_a) - 1, hashlib.sha256(ptx_a[:-1]).digest(), b""))) + self.assertEqual(R.read_plain(cons, "A_LEN"), len(ptx_a) - 1) + self.assertEqual(R.read_ptxpin(cons, "B_PIN", None, "ptx_sha256"), hashlib.sha256(ptx_b).digest()) + cu_b = (self.root / "crates/cuda-driver/src/b.cu").read_bytes() + self.assertEqual(R.read_ptxpin(cons, "B_PIN", None, "source_sha256"), hashlib.sha256(cu_b).digest()) + self.assertEqual(sorted(man["touched_files"]), ["crates/cuda-driver/src/a.ptx", "crates/cuda-driver/src/b.ptx", + "crates/cuda-driver/src/cons.rs"]) + self.assertEqual(man["unsealed_placeholders_remaining"], []) + + def test_fake_output_is_refused_in_the_real_checkout_and_without_the_flag(self): + self.assertEqual(self.compile()[0], 0) + code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root)]) + self.assertEqual(code, 1) + self.assertIn("fake-nvcc", err) + code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--allow-fake"]) # root = this checkout + self.assertEqual(code, 1) + self.assertIn("scratch", err) + + def test_cu_changed_after_compile_is_refused(self): + self.assertEqual(self.compile()[0], 0) + (self.root / "crates/cuda-driver/src/b.cu").write_text('extern "C" __global__ void leleka_c(int x){} // edited\n') + code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake"]) + self.assertEqual(code, 1) + self.assertIn("changed after it was compiled", err) + + def test_stale_plan_pin_at_seal_time_is_refused(self): + self.assertEqual(self.compile()[0], 0) + plan = json.loads((self.root / "docs/cuda-seal-plan-mini.json").read_text()) + plan["assets"][0]["cu_pin"]["sha256"] = "1" * 64 + (self.root / "docs/cuda-seal-plan-mini.json").write_text(json.dumps(plan)) + code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake"]) + self.assertEqual(code, 1) + self.assertIn("stale source", err) + + def test_tampered_ptx_is_refused(self): + self.assertEqual(self.compile()[0], 0) + with open(self.out / "a.ptx", "a") as f: + f.write("// tampered\n") + code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake"]) + self.assertEqual(code, 1) + self.assertIn("does not match the manifest", err) + + def test_a_pin_field_that_matches_two_declarations_refuses_and_writes_nothing(self): + self.assertEqual(self.compile()[0], 0) + cons = self.root / "crates/cuda-driver/src/cons.rs" + cons.write_text(cons.read_text() + "mod t {\n const A_LEN: usize = 0;\n}\n") + before = cons.read_text() + code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--write"]) + self.assertEqual(code, 1) + self.assertIn("exactly one declaration", err) + self.assertEqual(cons.read_text(), before) + self.assertEqual((self.root / "crates/cuda-driver/src/a.ptx").read_text(), "// UNSEALED placeholder\n") + + def test_idempotent_reseal_of_identical_output(self): + self.assertEqual(self.compile()[0], 0) + base = ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--rustfmt", "never", "--write"] + self.assertEqual(run_quiet(S.main, base)[0], 0) + snap = (self.root / "crates/cuda-driver/src/cons.rs").read_text() + self.assertEqual(run_quiet(S.main, base)[0], 0) + self.assertEqual((self.root / "crates/cuda-driver/src/cons.rs").read_text(), snap) + + def test_flag_override_is_recorded_and_checked_by_the_sealer(self): + code, out, _ = self.compile("--flag-override", "b:-clearly-not-there") + self.assertEqual(code, 2) + shutil.rmtree(self.out, ignore_errors=True) + code, out, err = self.compile("--flag-override", "a:+--use_fast_math") + self.assertEqual(code, 0, out + err) + m = json.loads((self.out / "build-manifest.json").read_text()) + self.assertEqual(m["flag_overrides"], ["a:+--use_fast_math"]) + rec = next(r for r in m["assets"] if r["id"] == "a") + self.assertIn("--use_fast_math", rec["flags"]) + self.assertEqual(rec["flag_overrides"], ["a:+--use_fast_math"]) + base = ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--rustfmt", "never"] + self.assertEqual(run_quiet(S.main, base)[0], 0) # the sealer re-applies the recorded overrides + man = json.loads((self.out / "build-manifest.json").read_text()) + man["flag_overrides"] = [] + (self.out / "build-manifest.json").write_text(json.dumps(man)) + code, _, err = run_quiet(S.main, base) + self.assertEqual(code, 1) + self.assertIn("compiled with flags", err) + + def test_contradictory_override_is_stopped_by_the_lint(self): + code, out, _ = self.compile("--flag-override", "b:+--ftz=false") + self.assertEqual(code, 1) + self.assertIn("contradicts itself", out) + + def test_atomic_groups_must_move_together(self): + plan = json.loads((self.root / "docs/cuda-seal-plan-mini.json").read_text()) + for a in plan["assets"]: + a["atomic_group"] = "g" + (self.root / "docs/cuda-seal-plan-mini.json").write_text(json.dumps(plan)) + self.assertEqual(self.compile()[0], 0) + code, _, err = run_quiet(S.main, ["--ptx-dir", str(self.out), "--root", str(self.root), "--allow-fake", "--only", "a"]) + self.assertEqual(code, 1) + self.assertIn("atomic group", err) + + +class RealTreeFakeSeal(unittest.TestCase): + """The whole checked-in plan set against a scratch copy: every field of every plan must patch and read back.""" + + def test_full_fake_pipeline_on_a_scratch_copy(self): + with tempfile.TemporaryDirectory() as d: + scratch = Path(d) / "tree" + ignore = shutil.ignore_patterns(".git", "target", "*.gguf") + for sub in ("crates", "docs", "deploy", "engine/strata/include", "engine/strata/third_party", "scripts/gpu-bringup"): + shutil.copytree(REPO / sub, scratch / sub, ignore=ignore) + out = Path(d) / "ptx" + code, _, err = run_quiet(C.main, ["--root", str(scratch), "--fake-nvcc", "--out", str(out), "--rope-flags", "preserve", + "--include-optional"]) + self.assertEqual(code, 0, err) + code, text, err = run_quiet(S.main, ["--ptx-dir", str(out), "--root", str(scratch), "--allow-fake", "--write", + "--rustfmt", "never"]) + self.assertEqual(code, 0, err) + man = json.loads(text) + self.assertEqual(len(man["assets"]), 33) + self.assertEqual(man["min_driver_required"], "580.65.06") + # the six fast-math reseals were re-pinned where the old digests lived, and the PLE length slot updated + by = {a["id"]: a for a in man["assets"]} + resealed = [a for a in man["assets"] if a["group"] == "reseal-fastmath"] + self.assertEqual(len(resealed), 6) + self.assertTrue(all("--use_fast_math" in a["flags"] and "--ftz=false" not in a["flags"] for a in resealed)) + self.assertEqual(sum(r["replacements"] for a in resealed for r in a["repins"] if r.get("kind") == "decimal"), 7) + ple = by["ple_native_batch"] + queue = (scratch / "crates/cuda-driver/src/ple_batch_queue.rs").read_text() + self.assertEqual(R.read_plain(queue, "PTX_BYTES"), ple["raw_bytes"]) + self.assertEqual(R.read_plain(queue, "PTX_SHA256"), bytes.fromhex(ple["raw_sha256"])) + gr = (scratch / "crates/cuda-driver/src/original_verify_window_gr.rs").read_text() + self.assertEqual(len(R.find_decimal_pins(gr, bytes.fromhex(ple["raw_sha256"]))), 1) + # idempotent on the second run of identical output + code, _, err = run_quiet(S.main, ["--ptx-dir", str(out), "--root", str(scratch), "--allow-fake", "--write", + "--rustfmt", "never"]) + self.assertEqual(code, 0, err) + abi = (scratch / L.ABI_SOURCE).read_text() + self.assertIn("state == AbiState::Extended,", abi) + + +# ---------------------------------------------------------------------------------- smoke inventory +class SmokeInventory(unittest.TestCase): + def test_every_real_ignore_attribute_is_found_and_comments_are_not(self): + smokes = SI.scan(REPO) + raw = 0 + for p in (REPO / "crates").rglob("*.rs"): + if "target" in p.parts: + continue + raw += len(re.findall(r"(?m)^[ \t]*#\[ignore", p.read_text(errors="replace"))) + self.assertEqual(len(smokes), raw) + self.assertGreaterEqual(len(smokes), 100) + self.assertFalse([s for s in smokes if s.file.endswith(("experimental.rs", "kar_decode_levels.rs"))]) + + def test_gates_values_and_classes_on_known_tests(self): + by = {s.name: s for s in SI.scan(REPO)} + win = by["sealed_window_assets_load_on_the_device_and_export_every_named_entry"] + self.assertEqual(win.gates, {"LELEKA_VERIFY_WINDOW_GPU": "yes"}) + self.assertEqual(win.klass, "device") + basic = by["installed_driver_fixed_kernels"] + self.assertEqual(basic.gates, {"LELEKA_CUDA_REAL_GPU": "1"}) + self.assertEqual(by["installed_driver_q5_numeric_refusals"].klass, "device") + self.assertEqual(by["installed_driver_q5_native_parity"].klass, "assets") + self.assertEqual(by["isolated_q5_protocol_matrix"].klass, "mock") + self.assertEqual(by["pinned_artifact_two_tokens_finish_all_layers_and_commit_state"].klass + if "pinned_artifact_two_tokens_finish_all_layers_and_commit_state" in by else "assets", "assets") + self.assertEqual(by["actual_expert215_native_resident_gu_and_same_source_down_diagnostic"].klass, "assets") + self.assertEqual(by["experimental_gpu_fwht256_matches_cpu"].gates, {}) + + def test_every_smoke_lands_in_a_declared_group_and_dependencies_precede(self): + data = SI.load_groups() + smokes = SI.scan(REPO) + SI.assign(smokes, data) + declared = {g["name"] for g in data["groups"]} | {data["asset_group"], data["mock_group"]} + self.assertEqual({s.group for s in smokes} - declared, set()) + self.assertEqual([s for s in smokes if s.group == data["fallback_group"]], [], "new smokes need a home in smoke-groups.json") + self.assertEqual(SI.unique_filters(smokes), []) + order = SI.select_order(data, None, [], False) + for g in data["groups"]: + for d in g["depends_on"]: + self.assertLess(order.index(d), order.index(g["name"])) + + def test_selection_pulls_in_dependencies_and_guards_assets(self): + data = SI.load_groups() + self.assertEqual(SI.select_order(data, ["runtime-gr"], [], False), ["driver-basic", "transport", "gr", "runtime-gr"]) + with self.assertRaises(SystemExit): + SI.select_order(data, ["model-assets"], [], False) + self.assertNotIn("model-assets", SI.select_order(data, None, [], False)) + self.assertIn("model-assets", SI.select_order(data, None, [], True)) + + def test_doc_table_is_current(self): + doc = REPO / "docs/gpu-bringup.md" + if not doc.exists(): + self.skipTest("docs/gpu-bringup.md not written yet") + smokes = SI.scan(REPO) + SI.assign(smokes, SI.load_groups()) + text = doc.read_text() + start, end = text.index(SI.TABLE_START) + len(SI.TABLE_START), text.index(SI.TABLE_END) + self.assertEqual(text[start:end].strip("\n"), SI.emit_table(smokes, markdown=True), + "run: python3 scripts/gpu-bringup/smoke_inventory.py --update-doc docs/gpu-bringup.md") + + def test_synthetic_tree(self): + with tempfile.TemporaryDirectory() as d: + src = Path(d) / "crates/cuda-driver/src" + src.mkdir(parents=True) + lines = [ + 'const ENABLE: &str = "LELEKA_X_GPU";', + '/// docs mention #[ignore] and "LELEKA_NOT_A_GATE"', + '#[test]', '#[ignore = "Root-only"]', 'fn a_smoke() {', + ' assert_eq!(std::env::var(ENABLE).as_deref(), Ok("yes"));', '}', + '#[test]', '#[ignore]', 'fn a_smoke_longer() {', + ' let _ = std::env::var("LELEKA_Y_SHARD0");', + ' assert_eq!(std::env::var("LELEKA_Y_RUN_Z").as_deref(), Ok("1"));', '}', + ] + (src / "x_gpu.rs").write_text("\n".join(lines) + "\n") + smokes = SI.scan(Path(d)) + self.assertEqual([s.name for s in smokes], ["a_smoke", "a_smoke_longer"]) + self.assertEqual(smokes[0].gates, {"LELEKA_X_GPU": "yes"}) + self.assertEqual(smokes[1].gates, {"LELEKA_Y_RUN_Z": "1"}) + self.assertEqual(smokes[1].klass, "assets") + self.assertEqual(smokes[0].expected, 2) # the cargo filter "a_smoke" also matches a_smoke_longer + + +STUB_CARGO = """#!/usr/bin/env bash +name="${@: -1}" +echo "running 1 test" +if [[ ",${STUB_FAIL:-}," == *",$name,"* ]]; then echo "test $name ... FAILED"; echo "test result: FAILED. 0 passed; 1 failed; 0 ignored"; exit 101; fi +if [[ ",${STUB_ZERO:-}," == *",$name,"* ]]; then echo "test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 90 filtered out"; exit 0; fi +echo "test $name ... ok"; echo "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 90 filtered out" +""" +STUB_SMI = """#!/usr/bin/env bash +case "$*" in + *query-gpu=driver_version\\ *) echo "${STUB_DRIVER:-595.91.07}" ;; + *query-compute-apps*) [[ -n "${STUB_BUSY:-}" ]] && echo "4242, strata, 1000 MiB" ;; + *memory.free*) echo "${STUB_FREE:-32000}" ;; + *query-gpu*) echo "2026/10/14 20:00:00.000, NVIDIA GeForce RTX 5090, 595.91, 100 MiB, 32607 MiB, 40, 30.0 W, 210 MHz, 405 MHz, 0 %" ;; + *) echo "nvidia-smi -q (stub)" ;; +esac +""" + + +class RunSmokesScript(unittest.TestCase): + script = HERE.parent / "run_gpu_smokes.sh" + + def setUp(self): + self.d = tempfile.TemporaryDirectory() + self.bin = Path(self.d.name) / "bin" + self.bin.mkdir() + for name, body in (("cargo", STUB_CARGO), ("nvidia-smi", STUB_SMI)): + (self.bin / name).write_text(body) + (self.bin / name).chmod(0o755) + self.run_dir = Path(self.d.name) / "run" + + def tearDown(self): + self.d.cleanup() + + def run_script(self, *args, **env): + e = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", SMOKES_ALLOW_NON_LINUX="1", **env) + return subprocess.run([str(self.script), *args], capture_output=True, text=True, env=e, cwd=str(REPO)) + + def results(self): + rows = [l.split("\t") for l in (self.run_dir / "results.tsv").read_text().splitlines()[1:]] + return {r[2]: r[3] for r in rows} + + def status(self, g): + return (self.run_dir / "status" / g).read_text().strip() + + def test_plan_mode_prints_commands_and_does_not_need_a_gpu(self): + p = self.run_script("--plan", "--groups", "seal-loads") + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("LELEKA_VERIFY_WINDOW_GPU=yes cargo test --locked -p leleka-cuda-driver --features cuda-driver --lib", p.stdout) + self.assertIn("# dependency order: driver-basic seal-loads", p.stdout) + + def test_all_pass(self): + p = self.run_script("--run", "--run-dir", str(self.run_dir)) + self.assertEqual(p.returncode, 0, p.stdout + p.stderr) + self.assertEqual(set(self.results().values()), {"PASS"}) + self.assertTrue((self.run_dir / "nvidia-smi.before.txt").exists() and (self.run_dir / "nvidia-smi.after.txt").exists()) + self.assertIn("# group gr start", (self.run_dir / "gpu-timeline.csv").read_text()) + self.assertNotIn("model-assets", p.stdout) # never started by default + + def test_failure_stops_its_group_skips_dependents_and_continues_independent_groups(self): + p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_FAIL="fixed_down_pack_matches_original_upload_and_refuses_before_copy") + self.assertEqual(p.returncode, 1) + r = self.results() + self.assertTrue(r["fixed_down_pack_matches_original_upload_and_refuses_before_copy"].startswith("FAIL")) + self.assertTrue(r["complete_selected_matrices_match_legacy_64_row_bits"].startswith("PASS")) # before it in the group + self.assertTrue(r["prepared_routed_gate_up_reuses_exact_native_q8_and_refuses_invalid_owners"].startswith("NOT-RUN")) + self.assertEqual(self.status("transport"), "FAIL") + self.assertEqual(self.status("gr"), "SKIPPED-DEP") + self.assertEqual(self.status("runtime-gr"), "SKIPPED-DEP") + self.assertEqual(self.status("seal-loads"), "PASS") # independent of transport + self.assertEqual(self.status("new-pins"), "PASS") + + def test_a_filter_that_matches_nothing_is_a_failure(self): + p = self.run_script("--run", "--run-dir", str(self.run_dir), "--groups", "driver-basic", STUB_ZERO="installed_driver_fixed_kernels") + self.assertEqual(p.returncode, 1) + self.assertIn("filter matched nothing", self.results()["installed_driver_fixed_kernels"]) + + def test_first_group_failure_skips_everything_after(self): + p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_FAIL="installed_driver_fixed_kernels") + self.assertEqual(p.returncode, 1) + self.assertEqual(self.status("driver-basic"), "FAIL") + self.assertEqual({self.status(g) for g in ("seal-loads", "new-pins", "transport", "gr")}, {"SKIPPED-DEP"}) + + def test_old_driver_is_refused_because_the_tree_holds_ptx_isa_9_0(self): + p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_DRIVER="575.28") + self.assertEqual(p.returncode, 3) + self.assertIn("ISA 9.0", p.stdout) + self.assertIn("too old", p.stdout) + self.assertFalse(self.run_dir.exists()) + + def test_busy_gpu_and_low_vram_are_refused_without_touching_anything(self): + p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_BUSY="1") + self.assertEqual(p.returncode, 3) + self.assertIn("other processes hold the GPU", p.stderr) + self.assertFalse(self.run_dir.exists()) + p = self.run_script("--run", "--run-dir", str(self.run_dir), STUB_FREE="100") + self.assertEqual(p.returncode, 3) + + def test_model_assets_need_the_flag_and_the_caller_supplied_env(self): + p = self.run_script("--run", "--run-dir", str(self.run_dir), "--groups", "model-assets") + self.assertNotEqual(p.returncode, 0) + self.assertFalse(self.run_dir.exists()) + p = self.run_script("--run", "--run-dir", str(self.run_dir), "--groups", "model-assets", "--allow-model-runs") + self.assertEqual(p.returncode, 0, p.stdout + p.stderr) + self.assertIn("skipped", p.stdout) + self.assertTrue(all(v.startswith("SKIPPED") for v in self.results().values())) + + def test_existing_run_dir_is_never_reused(self): + self.run_dir.mkdir() + p = self.run_script("--run", "--run-dir", str(self.run_dir)) + self.assertEqual(p.returncode, 2) + + +STUB_SSH = """#!/usr/bin/env bash +# records the remote command (and stdin size) instead of connecting anywhere +shift_args=() +for a in "$@"; do case "$a" in -o) skip=1 ;; *) if [[ "${skip:-}" == 1 ]]; then skip=0; else shift_args+=("$a"); fi ;; esac; done +host="${shift_args[0]}"; remote="${shift_args[*]:1}" +printf '%s\t%s\n' "$host" "$remote" >> "$STUB_LOG" +case "$remote" in + test\\ -e*SEALED-MANIFEST.json) [[ -n "${STUB_SEALED:-}" ]] ;; + cat\\ *SEALED-MANIFEST.json) cat "$STUB_MANIFEST" ;; + test\\ -d*) exit 1 ;; + "bash -s") cat > "$STUB_LOG.script"; echo "BUILD OK" ;; + cat\\ \\>*) cat > /dev/null ;; + *) ;; +esac +""" +STUB_RSYNC = """#!/usr/bin/env bash +printf '%s\n' "$*" >> "$STUB_LOG.rsync" +for a in "$@"; do case "$a" in --files-from=*) cp "${a#--files-from=}" "$STUB_LOG.filesfrom" ;; esac; done +""" + + +class DriverIsaChecks(unittest.TestCase): + def test_table_and_checks(self): + self.assertEqual(L.min_driver_for(["8.7", "9.0"]), ("9.0", "580.65.06")) + self.assertEqual(L.driver_ok("595.91.07", ["8.7", "9.0"])[0], True) + self.assertEqual(L.driver_ok("580.65.06", ["9.0"])[0], True) + self.assertEqual(L.driver_ok("580.65.05", ["9.0"])[0], False) + self.assertEqual(L.driver_ok("570.26", ["8.7"])[0], True) + with self.assertRaises(L.PlanError): + L.min_driver_for(["9.9"]) + + def test_the_tree_really_mixes_8_7_and_9_0(self): + inv = L.isa_inventory(REPO) + self.assertIn("8.7", inv) + self.assertIn("9.0", inv) + + def test_cli_exit_codes(self): + code, out, _ = run_quiet(C.main, ["--isa-inventory", "--driver-check", "--driver-version", "575.0"]) + self.assertEqual(code, 1) + self.assertIn("too old", out) + self.assertEqual(run_quiet(C.main, ["--isa-inventory", "--driver-check", "--driver-version", "595.91.07"])[0], 0) + + +class RemoteSyncScript(unittest.TestCase): + """remote_sync.sh against stub ssh/rsync: argument construction and the safety refusals, no network.""" + + def setUp(self): + self.d = tempfile.TemporaryDirectory() + root = Path(self.d.name) + self.repo = root / "repo" + (self.repo / "scripts/gpu-bringup").mkdir(parents=True) + shutil.copy(HERE.parent / "remote_sync.sh", self.repo / "scripts/gpu-bringup/remote_sync.sh") + (self.repo / "tracked.txt").write_text("x\n") + env = dict(os.environ, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@t", GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@t") + for cmd in (["init", "-q"], ["add", "-A"], ["commit", "-q", "-m", "x"]): + subprocess.run(["git", "-C", str(self.repo), *cmd], check=True, env=env, capture_output=True) + self.bin = root / "bin" + self.bin.mkdir() + for name, body in (("ssh", STUB_SSH), ("rsync", STUB_RSYNC)): + (self.bin / name).write_text(body) + (self.bin / name).chmod(0o755) + self.log = root / "stub.log" + self.manifest = root / "manifest.json" + self.manifest.write_text(json.dumps({"created_utc": "t", "mode": "write", "touched_files": ["crates/a.ptx", "docs/x.json"]})) + + def tearDown(self): + self.d.cleanup() + + def run_sync(self, *args, **env): + e = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", STUB_LOG=str(self.log), STUB_MANIFEST=str(self.manifest), **env) + return subprocess.run([str(self.repo / "scripts/gpu-bringup/remote_sync.sh"), *args, "--host", "h", "--remote-dir", "~/work/x"], + capture_output=True, text=True, env=e) + + def rsync_calls(self): + p = Path(str(self.log) + ".rsync") + return p.read_text().splitlines() if p.exists() else [] + + def test_dry_run_sync_uses_rsync_n_with_the_excludes_and_never_deletes(self): + p = self.run_sync("sync", "--dry-run") + self.assertEqual(p.returncode, 0, p.stderr) + (call,) = self.rsync_calls() + for needle in (" -n", "--exclude .git", "--exclude target", "--exclude *.gguf", "--max-size=200m", "h:~/work/x/"): + self.assertIn(needle, call) + self.assertNotIn("--delete", call) + self.assertFalse((Path(str(self.log) + ".script")).exists()) + + def test_real_sync_records_the_head_and_creates_only_the_dedicated_dir(self): + p = self.run_sync("sync") + self.assertEqual(p.returncode, 0, p.stderr) + log = self.log.read_text() + self.assertIn("mkdir -p work/x", log) + self.assertIn(".synced-from-head", log) + + def test_unpulled_sealed_files_block_a_second_sync(self): + p = self.run_sync("sync", STUB_SEALED="1") + self.assertEqual(p.returncode, 1) + self.assertIn("pull-sealed", p.stderr) + self.assertEqual(self.rsync_calls(), []) + p = self.run_sync("sync", "--force-overwrite-sealed", STUB_SEALED="1") + self.assertEqual(p.returncode, 0, p.stderr) + + def test_dirty_tracked_tree_is_refused_unless_allowed(self): + (self.repo / "tracked.txt").write_text("changed\n") + p = self.run_sync("sync", "--dry-run") + self.assertEqual(p.returncode, 1) + self.assertIn("commit first", p.stderr) + self.assertEqual(self.run_sync("sync", "--dry-run", "--allow-dirty").returncode, 0) + + def test_remote_dir_must_be_a_dedicated_dir_below_home(self): + for bad in ("/", "~", "~/", "/etc/x", "~/../x", "/home/para", "~/a b", "~/a;b", "~/$(x)"): + e = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", STUB_LOG=str(self.log)) + p = subprocess.run([str(self.repo / "scripts/gpu-bringup/remote_sync.sh"), "sync", "--dry-run", "--host", "h", "--remote-dir", bad], + capture_output=True, text=True, env=e) + self.assertEqual(p.returncode, 2, (bad, p.stderr)) + + def test_build_script_has_the_three_binaries_and_the_no_run_test_builds(self): + p = self.run_sync("build", "--jobs", "4") + self.assertEqual(p.returncode, 0, p.stderr) + script = Path(str(self.log) + ".script").read_text() + self.assertIn("cargo build --release --locked -j 4 -p strata-desktop-core --bin leleka-cli --bin leleka-daemon --bin leleka-inference", script) + self.assertIn("cargo test --no-run --locked -j 4 -p leleka-cuda-driver --features cuda-driver", script) + self.assertIn("-p leleka-runtime", script) + self.assertIn("nice -n 10", script) + self.assertIn("cargo fetch --locked", script) + self.assertNotIn("cargo run", script) + + def test_pull_sealed_transfers_exactly_the_manifest_files(self): + p = self.run_sync("pull-sealed") + self.assertEqual(p.returncode, 0, p.stderr) + self.assertEqual(Path(str(self.log) + ".filesfrom").read_text().split(), ["crates/a.ptx", "docs/x.json"]) + self.manifest.write_text(json.dumps({"created_utc": "t", "touched_files": ["../../etc/passwd"]})) + p = self.run_sync("pull-sealed") + self.assertNotEqual(p.returncode, 0) + self.assertIn("unsafe path", p.stderr) + + +class FakeToolkitThroughTheRealPath(unittest.TestCase): + """--toolkit: provenance must equal the lock; the version check runs; a mismatching nvcc is refused.""" + + def make_tk(self, root: Path, lock_override=None, version="13.2.86"): + tk = root / "tk" + (tk / "bin").mkdir(parents=True) + nvcc = tk / "bin" / "nvcc" + nvcc.write_text("#!/usr/bin/env bash\nif [[ \"$1\" == --version ]]; then echo 'Cuda compilation tools, release 13.0, V%s'; exit 0; fi\n" + "exec %s \"$@\"\n" % (version, HERE.parent / "fake-nvcc")) + nvcc.chmod(0o755) + lock = json.loads((REPO / L.TOOLKIT_LOCK).read_text()) + (tk / "TOOLKIT-PROVENANCE.json").write_text(json.dumps({"lock": lock_override or lock})) + return tk + + def test_toolkit_path_with_matching_provenance_and_version(self): + with tempfile.TemporaryDirectory() as d: + tk = self.make_tk(Path(d)) + code, out, err = run_quiet(C.main, ["--toolkit", str(tk), "--out", str(Path(d) / "o"), "--rope-flags", "preserve", "--only", "device_poison"]) + self.assertEqual(code, 1, out + err) # real path: fake-nvcc output carries the FAKE marker and is rejected + self.assertIn("fake-nvcc output", out) + + def test_wrong_provenance_and_wrong_version_are_refused(self): + with tempfile.TemporaryDirectory() as d: + tk = self.make_tk(Path(d), lock_override={"release": "other"}) + with self.assertRaises(L.PlanError): + C.locate_nvcc(type("A", (), {"fake_nvcc": False, "nvcc": None, "toolkit": str(tk), "allow_unprovenanced": False})(), REPO) + with tempfile.TemporaryDirectory() as d: + tk = self.make_tk(Path(d), version="13.2.2") + code, _, err = run_quiet(C.main, ["--toolkit", str(tk), "--out", str(Path(d) / "o"), "--rope-flags", "preserve", "--only", "device_poison"]) + self.assertEqual(code, 2) + self.assertIn("13.2.2", err) + self.assertIn("13.2.86", err) + + +if __name__ == "__main__": + unittest.main(verbosity=1)