From b5d5b24faa247a5e69a84754eb2d09fbb94f2e6b Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 30 Oct 2026 03:33:18 +0100 Subject: [PATCH] decode: a verifier graph that runs out of device memory costs the widest windows, not the engine cuGraphInstantiateWithFlags answering out of memory used to poison the whole CUDA context (every call after it failed, so the engine was lost; upstream a8c1d4b7 / 2a9a67c1). The refusal is not sticky and changes no state, so now: - the instantiate step does not poison the context on that one code (every other failure still does), the half-built graph is destroyed, and a line is logged; - a failed cuGraphUpload (a warm-up) is skipped with a line; - OriginalVerifier::record_all names the graph that did not fit (Error::GraphOutOfMemory { window }, 0 = commit graph); - the serve stack repeats the assembly with the windows that fit (assemble_with_window_fallback; owners come back from each failure), logs each step, and narrows the settings, controllers and MTP draft cap of every arm to the window it ended with, for the later requests too. No cap below T=2: a failure with nothing left is returned as before, but with the context intact. Test hook for a card with room: LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT=N fails the N-th window instantiation once. CPU tests: poison decision, error classification, cap computation, retry loop (terminates, stops at the floor, no retry on other errors), settings cap. Not verified on a GPU. Co-Authored-By: Claude Sonnet 5.5 --- crates/cuda-driver/src/lib.rs | 7002 +++++++++-------- .../cuda-driver/src/original_gpu_schedule.rs | 2418 +++--- .../src/original_verify_window_ops.rs | 1609 ++-- .../src/qwen_forward/original_serve_engine.rs | 2401 +++--- .../src/qwen_forward/original_serve_stack.rs | 4026 +++++----- .../qwen_forward/original_serve_verifier.rs | 844 +- 6 files changed, 9318 insertions(+), 8982 deletions(-) diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index 7a16fd87..d8258c51 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -1,3495 +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, - 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::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 6b54d997..bbc8796e 100644 --- a/crates/cuda-driver/src/original_gpu_schedule.rs +++ b/crates/cuda-driver/src/original_gpu_schedule.rs @@ -1,1160 +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(()) - } -} -fn call(c: &Context<'_>, api: &abi::Api, f: impl FnOnce(&abi::Api) -> Result) -> Result { - healthy(c)?; - let guard = c.enter().inspect_err(|_| poison(c))?; - let op = f(api); - let pop = guard.finish(); - if op.is_err() || pop.is_err() { - poison(c); - } - combine(op, pop) -} -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(), - ); - } - } - let instantiate = call(g.context, &g.api, |a| { - g.exec = Some(a.instantiate(graph)?); - 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); - 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]) - } -} +//! 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 3596dfd8..4cff784f 100644 --- a/crates/cuda-driver/src/original_verify_window_ops.rs +++ b/crates/cuda-driver/src/original_verify_window_ops.rs @@ -1,789 +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)?; - } - // 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(())) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[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 ecda2746..f6f0fb67 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs @@ -1,1182 +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 - } - /// 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 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_stack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs index c29ced2c..af5c7fe7 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs @@ -1,1988 +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, disassemble, seed_ple_history, DecodeResources, ServeFailure, VerifyWeights, PLE_HISTORY_BYTES}, - original_spec_controller::{OriginalSpecController, SpecError}, - output_native::{OriginalNativeOutput, OriginalNativePenaltyHistory}, - session::{ - original_prompt::{draft::OriginalDraftCheckpoint, OriginalPromptInput, OriginalSessionCheckpoint, ParkedBlock, ParkedSession}, - QwenSession, - }, -}; -use crate::backend::original_prompt::{PlanError, PromptOptions, PromptPath, PromptPlan}; -use crate::model_binding::qwen4exp_input::ModelBinding; -use leleka_context::memory_plan::KvFormat; -use leleka_cuda_driver::{ - Context, DeviceBuffer, NativeHeadDispatch, OriginalExpertCache, OriginalMtpFullPolicy, OriginalMtpScalarPolicy, - OriginalPrefillArena, OriginalVerifyExpertFormats, PLE_SCRATCH_BYTES, PrefillLayoutOptions, -}; -use std::{path::PathBuf, rc::Rc, time::Instant}; - -/// One timed, measured step of opening the stack: the load ledger records what it cost in host and device memory. -macro_rules! staged { - ($name:expr, $ctx:expr, $body:expr) => {{ - let __stage = crate::memory_governor::begin($name, Some($ctx)); - let __result = $body; - crate::memory_governor::end(__stage, Some($ctx)); - __result - }}; -} - -#[path = "original_serve_conversation.rs"] -mod conversation; -pub(crate) use conversation::{ConversationConfig, TURN_TOKEN}; -use conversation::{ResumeDevice, ServeConversation}; - -#[path = "original_serve_prefix.rs"] -mod prefix; -pub(crate) use prefix::{PrefixBudget, PrefixConfig, TailMode}; -use prefix::{ChunkOutcome, PrefixDevice, PrefixServe}; -use crate::prefix_cache::{ByteSize, PrefixMatch, PrefixSummary}; - -/// Stage marks of one request's time to first token (milliseconds since `serve` was entered). -#[derive(Clone, Copy, Debug)] -struct TtftMarks { - started: Option, - resumed: f64, - prefilled: f64, - assembled: f64, - first_round: f64, -} -impl Default for TtftMarks { - fn default() -> Self { - Self { started: None, resumed: f64::NAN, prefilled: f64::NAN, assembled: f64::NAN, first_round: f64::NAN } - } -} -impl TtftMarks { - fn start() -> Self { - Self { started: Some(Instant::now()), ..Self::default() } - } - fn since(&self) -> f64 { - self.started.map_or(f64::NAN, |at| at.elapsed().as_secs_f64() * 1e3) - } - fn as_array(&self) -> [f64; 4] { - [self.resumed, self.prefilled, self.assembled, self.first_round] - } -} - -/// The digest of the pinned model's first shard: part of the prefix cache's namespace. -const PINNED_MODEL: &str = "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"; - -/// Prompt-chunk capacities the Original prefill admits (`PromptPlan::new`), ascending. -pub(crate) const ADMITTED_CAPACITIES: [usize; 10] = [256, 512, 1024, 2048, 3072, 4096, 6144, 8192, 16384, 32768]; -/// The default chunk. The Original sizes it from the free expert-cache slots (`--prefill-auto`); with no GPU -/// expert tier there is no slot count to derive it from, so the operator picks it (the arena is a few GiB at -/// 8192) and a hardware run settles the default. -pub(crate) const DEFAULT_CAPACITY: usize = 2048; -/// `qsa_kv_resident_min()`: the shipped resident draft-K/V budget in cells. -const MTP_RESIDENT_CELLS: u64 = 20_480; -const CPU_WORKERS: i32 = 15; -const VOCABULARY: u32 = 248_320; - -/// Operator-visible choices of the stack. -#[derive(Clone, Debug)] -pub(crate) struct StackConfig { - pub(crate) capacity: usize, - /// The request ceiling (`--max-context`): at most the process serving cell count. - pub(crate) max_context: i64, - /// `--mtp DIR`: the Original-literal RT directory; `None` takes the digest-pinned pack of the binding. - pub(crate) rt_directory: Option, - pub(crate) coupled: bool, - pub(crate) cpu_workers: i32, - /// Read the verifier's GDN/PLE state back into the session at the end of every request (needed only by - /// a consumer that reuses the session; the default reset-per-request flow skips the 110 MB transfer). - pub(crate) settle_state: bool, - /// `--kv`: QSA K/V storage. Only `int8` (the production `--kv int8`) has sealed owners; fp16, q4_0 and - /// k8v4 are refused (docs/kv-streaming.md). - pub(crate) kv_format: KvFormat, - /// `--kv-resident N`: cells of each QSA layer kept in VRAM, the rest streamed from pinned host memory - /// (raised to 20480; 0 = the whole context). Default 32768, the window every earlier build used. - pub(crate) kv_resident: usize, - /// generate.cpp's conversation cache (`--prompt-cache` and friends); on by default with the Original's - /// settings (`--prompt-cache 6`). `None` reads every request from the empty prompt. - pub(crate) conversation: Option, - /// The cross-session prefix cache (`--prefix-cache-mib`, `docs/prefix-cache.md`). When it is on it REPLACES the - /// conversation cache: the prompt is read on a token grid and any request resumes from the deepest checkpoint - /// that is a prefix of its prompt, whichever session built it. `None` (the default) leaves the conversation - /// cache in charge. - pub(crate) prefix: Option, - /// The VRAM expert tier (`--expert-cache`, `--expert-cache-per-layer`, `--expert-profile`, `--pcie-frac`, - /// `--adapt-every/--adapt-swaps`). Off by default: every routed expert on the CPU pool. - pub(crate) expert_tier: ExpertTierConfig, - /// Smaller prompt loans for smaller chunks (`LELEKA_PREFILL_LOAN_TIERS=1`; off: every chunk borrows the full loan of `capacity`). - pub(crate) loan_tiers: bool, -} -impl StackConfig { - pub(crate) fn new(max_context: i64) -> Self { - Self { - capacity: DEFAULT_CAPACITY, - max_context, - rt_directory: None, - coupled: OriginalServeSettings::coupled_from_environment(), - // LELEKA_ORIGINAL_SERVE_CPU_WORKERS: experiment knob (the Original's default on this host is 15) - // LELEKA_CPU_POOL_PLAN=on: when the count is not set, the plan of `native-cpu-expert::pool_plan` (physical cores but the host's, hybrid and quota aware; - // docs/upstream-port-plan.md row 2.3) instead of the constant 15 (opt-in: the same 15 on the server's 16-core CPU, not measured on any other) - cpu_workers: std::env::var("LELEKA_ORIGINAL_SERVE_CPU_WORKERS").ok().and_then(|v| v.parse().ok()).filter(|n| (1..=64).contains(n)).unwrap_or_else(|| { - if std::env::var("LELEKA_CPU_POOL_PLAN").is_ok_and(|v| v == "on") { leleka_native_cpu_expert::pool_plan::default_workers() } else { CPU_WORKERS } - }), - settle_state: false, - kv_format: KvFormat::Int8, - kv_resident: leleka_cuda_driver::KV_RESIDENT_DEFAULT_CELLS, - conversation: Some(ConversationConfig::original()), - prefix: None, - expert_tier: ExpertTierConfig::off(), - loan_tiers: loan_tiers_enabled(), - } - } - /// The streamed KV of this configuration (`None` when the window is not servable). - pub(crate) fn kv_footprint(&self) -> Option { - leleka_cuda_driver::serving_context().geometry.kv_stream_footprint(self.kv_resident).ok() - } - pub(crate) fn validate(&self) -> Result<()> { - if self.kv_format != KvFormat::Int8 { - return Err(Error::Unsupported(super::contract::Stage::Session)); - } - if !ADMITTED_CAPACITIES.contains(&self.capacity) - || self.kv_footprint().is_none() - || self.capacity > 8192 - || self.max_context < 1 - || self.max_context as u64 > super::contract::serving_cells() - || !(1..=64).contains(&self.cpu_workers) - { - return Err(Error::InvalidDimension); - } - if let Some(conversation) = &self.conversation { - conversation.validate()?; - } - if let Some(prefix) = &self.prefix { - prefix.validate(self.capacity)?; - } - self.expert_tier.validate() - } -} - -/// Bytes the prompt path's buffers need at `options.capacity` (what a loan must cover). -fn prefill_bytes(options: PrefillLayoutOptions) -> Result { - let carve = options.carve().map_err(|e| super::original_serve_verifier::driver_error(&e))?; - Ok(carve.borrowed_bytes.max(carve.source_bytes_needed)) -} - -/// One rung of the loan ladder: the arena layout for chunks of at most `rows` rows and the slots it needs. -#[derive(Clone, Copy, Debug)] -struct LoanTier { - rows: usize, - layout: PrefillLayoutOptions, - slots: usize, -} - -/// Chunk sizes (rows) that get their own, smaller loan below the configured capacity. -const LOAN_TIER_ROWS: [usize; 2] = [512, 2048]; - -/// The smallest rung of the ladder that holds a chunk of `count` rows (`None`: the full loan). -fn tier_for(tiers: &[LoanTier], count: usize) -> Option<&LoanTier> { - tiers.iter().find(|t| count <= t.rows) -} - -/// `LELEKA_PREFILL_LOAN_TIERS=1` turns the ladder on. It is OFF by default until the real-model identity gate (job p34: the final residual R of -/// every chunk equal with and without the ladder) and the paired A/B (job p35) have run (docs/prefill-throughput.md). -fn loan_tiers_enabled() -> bool { - std::env::var("LELEKA_PREFILL_LOAN_TIERS").is_ok_and(|v| v == "1" || v == "on") -} - -/// One conversation checkpoint of the stack: the session's Original checkpoint and the draft ring's snapshot, -/// taken together at a published prompt-chunk boundary. -struct StackPoint<'ctx> { - session: OriginalSessionCheckpoint<'ctx>, - draft: OriginalDraftCheckpoint, -} - -/// A prefix-cache checkpoint of the stack: the session's recurrent state and the draft ring's snapshot at one grid point. -struct StackState { - session: ParkedSession, - draft: OriginalDraftCheckpoint, -} -impl ByteSize for StackState { - fn byte_size(&self) -> usize { - self.session.host_bytes() + self.draft.host_bytes() - } -} -/// The K/V cells and index rows of one block of the twelve resident QSA layers. -struct StackBlock(ParkedBlock); -impl ByteSize for StackBlock { - fn byte_size(&self) -> usize { - self.0.host_bytes() - } -} -/// Bytes of one cell across the twelve layers: INT8 K+V with scales (1056 B) and the pooled index key (128 B). -const PARKED_BYTES_PER_TOKEN: usize = 12 * (1056 + 128); -/// Expected size of a parked state before one was measured (GDN/PLE images, the draft ring, the index tails). -const PARKED_STATE_ESTIMATE: usize = 120 << 20; - -fn plan_error(error: PlanError) -> Error { - match error { - PlanError::InvalidInput => Error::InvalidDimension, - PlanError::Overflow => Error::Overflow, - } -} - -pub(crate) struct OriginalServeStack<'a, 'ctx> { - binding: &'a ModelBinding, - context: &'ctx Context<'ctx>, - config: StackConfig, - settings: OriginalServeSettings, - max_cells: usize, - rope: RopeConstants, - blobs: ExpertBlobSizes, - formats: OriginalVerifyExpertFormats, - full_policy: OriginalMtpFullPolicy, - scalar_policy: OriginalMtpScalarPolicy, - controller: OriginalSpecController, - /// Window policies other than the live one (`LELEKA_SPEC_ARMS`), parked with their controllers (each keeps its learned - /// state across requests), and the live one's label. The verifier is built for `verifier_max_t`, the widest arm. - parked: Vec<(String, OriginalServeSettings, OriginalSpecController)>, - arm_label: String, - arm_order: Vec, - verifier_max_t: usize, - /// Why the stack can serve no more (a lost physical owner); `None` while healthy. - broken: Option, - // The empty-prompt lineage taken at load: the reset target of every request. - empty_session: OriginalSessionCheckpoint<'ctx>, - empty_draft: OriginalDraftCheckpoint, - /// The conversation cache (checkpoints hold priors and snapshots of the owners below: dropped first). - conversation: Option>>, - /// The prefix cache (`StackConfig::prefix`); replaces `conversation` when set. - prefix: Option>, - /// The tokens the session holds at the end of a decode that left it settled with the draft ring in step (`TailMode::Reply`). - tail_consumed: Option>, - /// Prompt tokens the last request did not read again. - reused: usize, - /// Where the conversation cache placed the last request (`reused`, or the re-read checkpoint's length). - resume_point: usize, - // Owners, dependents first (fields drop in declaration order). - history: OriginalNativePenaltyHistory<'ctx>, - ple_history: DeviceBuffer<'ctx>, - ple_scratch: DeviceBuffer<'ctx>, - /// The prompt path's own buffers; `None` while it borrows the expert cache's last slots instead. - arena: Option>, - layout: PrefillLayoutOptions, - /// The VRAM expert tier (`None`: off), the slots the prompt path borrows per chunk, the adaptive counts - /// that survive requests. - expert_cache: Option>, - loan: Option, - /// Smaller loans for smaller chunks, ascending by rows (empty unless `LELEKA_PREFILL_LOAN_TIERS=1`: only `loan`): a chunk of at most - /// `rows` rows borrows `slots` slots instead of the full loan, so a request that reads a few hundred tokens refills a few - /// hundred slots, not the 1.9 GB of an 8192-row arena. - loan_tiers: Vec, - residency: ResidencyState, - /// The (layer, expert) pairs the tier held right after the profile fill (`reset_expert_tier`). - initial_owners: Vec>, - /// The last request's prompt-routing seed (`LELEKA_ORIGINAL_SERVE_SEED`), if one was made. - seed_report: Option, - /// The prompt counts of the last seed (kept for the `LELEKA_SEED_TRACE` coverage line). - seed_counts: Option>, - /// Lent-slot refill copies are queued and not yet waited (`LELEKA_REFILL_DEFER`): the decode phase waits before any - /// window reads the cache; every other user of the cache waits inside its own entry points. - refill_pending: bool, - /// The lent slots still have to be refilled: the decode phase queues the copies right after its host-side intake - /// uploads (so they overlap the graph capture instead of queueing small uploads behind 1.4 GB of DMA). - refill_due: bool, - /// Wall-clock milliseconds of the last request's prompt and decode phases (operator measurements). - timing: (f64, f64), - /// Milliseconds since the request entered `serve` at which each stage of the time to first token ended (`ttft_marks`). - marks: TtftMarks, - executor: OriginalPromptExecutor<'ctx>, - draft: super::session::original_prompt::draft::OriginalDraftSession<'ctx>, - session: QwenSession<'ctx>, - pool: CpuExpertPool<'a>, - kar: Option>, - moe: MoeWeightCache<'ctx>, - dense: DenseWeightCache<'ctx>, - output: OriginalNativeOutput<'ctx>, - embedding: OriginalPromptEmbedding<'ctx>, -} - -fn failure(error: Error) -> ServeFailure { - ServeFailure::from(error) -} - -/// Name the startup step in a refusal so a failed open says where it stopped. -fn at>(step: &'static str) -> impl FnOnce(E) -> ServeFailure { - move |error| { - let mut failure: ServeFailure = error.into(); - failure.detail = Some(match failure.detail.take() { - Some(detail) => format!("{step}: {detail}"), - None => format!("{step}: {:?}", failure.error), - }); - failure - } -} - -impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { - /// `generate.cpp` startup over the binding: embedding table, native head + embedding, dense weights at - /// the prompt capacity, the MoE arena cache, the target session, the prompt executor with the MTP - /// drafter, the prefill arena, and the per-request stages. `shared` is the session's reference to the - /// very context `context` borrows. - pub(crate) fn open( - binding: &'a ModelBinding, - context: &'ctx Context<'ctx>, - shared: Rc>, - config: StackConfig, - ) -> std::result::Result { - crate::bringup_trace!("DBG[{:.0}s] OriginalServeStack::open begin", dbg_el()); - config.validate().map_err(at("config.validate"))?; - // generate.cpp: qsa_set_kv_resident before any QSA state exists (every streamed owner sizes from it) - leleka_cuda_driver::configure_kv_resident(config.kv_resident).map_err(|_| ServeFailure { - error: Error::InvalidDimension, - detail: Some(format!("--kv-resident {}: the process already serves another resident KV window", config.kv_resident)), - })?; - if let Some(footprint) = config.kv_footprint() { - operator_note(&footprint.to_string()); - } - if !std::ptr::eq(context, &*shared) { - return Err(failure(Error::IdentityMismatch)); - } - if binding.layer_count() != 48 { - return Err(ServeFailure { error: Error::IdentityMismatch, detail: Some("the Original serve stack serves the 48-layer model only".to_owned()) }); - } - if !binding.has_mtp() { - return Err(ServeFailure { - error: Error::Unsupported(super::contract::Stage::Session), - detail: Some("the binding carries no MTP pack: the Original serve loop drafts with the MTP layer".to_owned()), - }); - } - let max_cells = usize::try_from(super::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?; - let mut settings = OriginalServeSettings::from_environment(config.max_context, VOCABULARY, config.coupled); - let mut arm_label = String::from("env"); - let arm_order: Vec = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled).into_iter().map(|(l, _)| l).collect(); - let mut parked = Vec::new(); - let arms = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled); - let verifier_max_t = arms.iter().map(|(_, s)| s.max_t).chain([settings.max_t]).max().unwrap_or(settings.max_t); - if let Some(((label, first), rest)) = arms.split_first() { - settings = *first; - arm_label = label.clone(); - for (label, s) in rest { - parked.push((label.clone(), *s, s.controller().map_err(at("settings.controller"))?)); - } - } - let controller = settings.controller().map_err(at("settings.controller"))?; - let rope = RopeConstants::from_serving_context(); - let blobs = ExpertBlobSizes::from_binding(binding).map_err(at("ExpertBlobSizes::from_binding"))?; - let formats = expert_formats(binding).map_err(at("expert_formats"))?; - let layout = prefill_layout_options(config.capacity, max_cells, &blobs); - - vram_note(context, "open begin"); - // 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, - arm_label, - verifier_max_t, - history, - ple_history, - ple_scratch, - executor, - draft, - session, - pool, - kar, - moe, - dense, - output, - broken, - conversation, - expert_cache, - residency, - refill_pending, - refill_due, - marks, - prefix, - tail_consumed, - .. - } = self; - let binding: &ModelBinding = *binding; - let context: &'ctx Context<'ctx> = *context; - if controller.is_failed() { - // a failed restore/finish poisoned the controller; its adaptive cadence is the only thing lost - *controller = settings.controller()?; - } - crate::bringup_trace!("DBG[{:.0}s] decode_phase start", dbg_el()); - let sampling = RequestSampling::new(request.params, request.path)?; - let n = request.prompt.len(); - let base = session.original_verified_base()?; - crate::bringup_trace!("DBG[{:.0}s] decode: base position {} (n-1 = {})", dbg_el(), base.position, n as u64 - 1); - if base.position != (n as u64 - 1) { - return Err(Error::IdentityMismatch.into()); - } - // generate.cpp `ver.set_pcie_mode`: only a window that can stage anything over PCIe records the copy kernel. - let pcie_mode = match (expert_cache.as_ref(), moe.original_expert_bank()) { - (Some(_), Some(bank)) if config.expert_tier.pcie_num_for(bank.pageable()) > 0 => { - config.expert_tier.pcie_mode.graph_mode(bank.pageable(), blobs.spans_tile_blobs()).ok_or(Error::Unsupported( - super::contract::Stage::Session, - ))? - } - _ => 0, - }; - let p = profile::span("decode.seed_ple"); - seed_ple_history(&base, ple_history).map_err(|f| SpecError::Forward(f.error))?; - drop(p); - // the window reads the shared experts of all 48 layers in place: load/refresh them together first - let p = profile::span("decode.shared"); - let shared = moe.ensure_original_verify_shared(binding)?; - drop(p); - crate::bringup_trace!("DBG[{:.0}s] decode: shared experts loaded", dbg_el()); - let owners = executor.take_qsa_owners()?; - let ple_history: &DeviceBuffer<'ctx> = &*ple_history; - let weights = VerifyWeights { dense: &*dense, moe: &*moe, shared: &shared, formats: &*formats, ple_scratch: &*ple_scratch }; - let p = profile::span("decode.assemble"); - // queued after assembly's own uploads (canonical GDN image), before the graph capture - let mut queue_refill = || -> Result<()> { - if !std::mem::take(&mut *refill_due) { - return Ok(()); - } - if let Some(cache) = expert_cache.as_mut() { - let _p = profile::span("prefill.refill"); - original_serve_residency::refill_lent(binding, &*moe, cache, &mut residency.spans, true)?; - *refill_pending = true; - } - Ok(()) - }; - let assembled = assemble( - binding, &weights, context, &*output, &base, owners, ple_history, rope, blobs, *verifier_max_t, *max_cells, - pcie_mode, &mut queue_refill, - ); - drop(p); - marks.assembled = marks.since(); - // the lent slots' refill copies (queued at the end of the prompt phase) have run behind the assembly: wait for them - // before a window or the tier's own bookkeeping touches the cache - if std::mem::take(refill_pending) { - if let Some(cache) = expert_cache.as_mut() { - if let Err(error) = original_serve_residency::settle_refill(cache) { - broken.get_or_insert(error); - if let Ok(resources) = assembled { - let _ = disassemble(resources).map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); - } - return Err(SpecError::Forward(error)); - } - } - } - vram_note(context, "decode after assemble"); - crate::bringup_trace!("DBG[{:.0}s] decode: assemble -> {}", dbg_el(), if assembled.is_ok() { "ok" } else { "ERR" }); - let resources = match assembled { - Ok(resources) => resources, - Err(lost) => { - operator_line("assemble", &lost.failure); - if let Some(owners) = lost.owners { - if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners) { - broken.get_or_insert(error); - } - } else { - broken.get_or_insert(Error::IdentityMismatch); - } - return Err(SpecError::Forward(lost.failure.error)); - } - }; - let DecodeResources { verifier, qsa, slots } = resources; - // the NaN guard's retry takes a refused window back from these (OriginalVerifier::discard_window) - qsa.set_window_snapshots(settings.nan_guard.retries > 0); - let committed = request.prompt[..n - 1].to_vec(); - // The window's expert tier: the GPU share first and the CPU pool on the rest, or the CPU pool alone. - let mut gpu_pool; - let pool: &mut dyn OriginalServePool<'ctx> = match (expert_cache.as_mut(), moe.original_expert_bank()) { - (Some(cache), Some(bank)) => { - let pcie_num = config.expert_tier.pcie_num_for(bank.pageable()); - let tail_rank = original_serve_residency::effective_tail_rank(&*cache); - let pcie_locked = if pcie_num > 0 && original_serve_residency::pcie_locked_only() { bank.locked_experts() } else { Vec::new() }; - gpu_pool = GpuExpertPool { - binding, - moe: &*moe, - cache, - bank, - cpu: &mut *pool, - state: &mut *residency, - pcie_num, - adapt_every: config.expert_tier.adapt_every, - adapt_swaps: config.expert_tier.adapt_swaps as usize, - tail_rank, - pcie_locked, - }; - &mut gpu_pool - } - (Some(_), None) => return Err(SpecError::Forward(Error::IdentityMismatch)), - (None, _) => &mut *pool, - }; - let owners = HostOwners { - binding, - dense: &*dense, - context, - session: &mut *session, - draft: &mut *draft, - executor: &mut *executor, - kar: kar.as_mut(), - history: &mut *history, - pool, - qsa: Rc::clone(&qsa), - slots, - ple_history, - policy: &*full_policy, - }; - let want_tail = config.prefix.as_ref().is_some_and(|p| p.tail == TailMode::Reply) && prefix.is_some(); - controller.set_final_draft(want_tail); - *tail_consumed = None; - let host = OriginalServeHost::new(owners, committed, config.max_context as u64, sampling); - let (served, verifier, outcome) = match host { - Err(error) => (Err(SpecError::Forward(error)), verifier, None), - Ok(host) => { - let port = super::original_serve_engine::TracePort(NativeServePort::new(verifier, host)); - let engine = OriginalServeEngine::new(port, VOCABULARY, settings.max_t, settings.max_drafts()); - match engine { - Err(error) => { - // `new` consumed the port on failure; the verifier is gone with it. Treated as lost below. - let _ = error; - broken.get_or_insert(Error::IdentityMismatch); - return Err(SpecError::Forward(Error::IdentityMismatch)); - } - Ok(mut engine) => { - crate::bringup_trace!("DBG[{:.0}s] decode: engine ready, serving", dbg_el()); - let started = Instant::now(); - let serve_span = profile::span("decode.serve"); - let result = engine.set_min_p(request.spec_min_p).map_err(SpecError::Forward).and_then(|()| { - serve_request( - controller, - &mut engine, - &request.prompt, - request.max_new, - request.spec_min_p, - &request.eos, - |tokens| { - if marks.first_round.is_nan() { - marks.first_round = marks.since(); - } - emit(tokens) - }, - &mut *cancel, - || started.elapsed().as_secs_f64() * 1e3, - ) - }); - drop(serve_span); - { - // the controller's round counters belong to this request in every window policy - let stats = controller.take_stats(); - if super::original_spec_controller::stats_enabled() { - eprintln!("DBG spec-stats arm={} {}", arm_label, stats.line()); - } - } - if let Err(e) = &result { crate::bringup_trace!("DBG[{:.0}s] serve_request err {e:?}", dbg_el()); } - let (mut verifier, mut host) = engine.into_port().0.into_parts(); - // STRATA_VERIFY_PROFILE=1: the GPU stage times of the request's windows (empty otherwise) - let gpu_profile = verifier.profile_report(); - if !gpu_profile.is_empty() { - eprintln!("DBG verify-profile:{gpu_profile}"); - } - // conversation cache: the session can be continued as is only when the draft ring - // stands at its position (then its recurrent state is settled to match) - let live = conversation.is_some() - && matches!(result, Ok(_) | Err(SpecError::Cancelled)) - && host.draft_in_step(); - // prefix cache, TailMode::Reply: the session settled and the ring in step (the final window was drafted) - let tail = want_tail && result.is_ok() && prefix.is_some() && host.draft_in_step(); - if want_tail && result.is_ok() && !tail { - operator_text("prefix tail: the draft ring is not at the session's position; no checkpoint at the end of this decode"); - } - if (result.is_ok() && config.settle_state) || live || tail { - match host.settle_state(&mut verifier) { - Ok(()) if live => { - if let Some(conversation) = conversation.as_mut() { - conversation.note_live(host.committed().to_vec()); - } - } - Ok(()) if tail => *tail_consumed = Some(host.committed().to_vec()), - Ok(()) => {} - Err(error) => { - broken.get_or_insert(error); - } - } - } - let outcome = host.finish(); - (result, verifier, Some(outcome)) - } - } - } - }; - // The MTP drafter's cached round programs and staged window are bound to THIS verifier's bank: release them before the - // bank closes (it is shared while they live) and so the next request captures against its own bank. - let p = profile::span("decode.release_mtp"); - let released = executor.mtp_release_verifier(binding); - drop(p); - if let Err(error) = released { - operator_line("release MTP verifier bindings", &failure(error)); - broken.get_or_insert(error); - } - // Close the verifier (drains both streams, drops the graphs) and take the physical owners back at - // the session's lineage; an abandoned window is rolled back there. - // 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 1c71acf4..57f5d731 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_verifier.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_verifier.rs @@ -1,368 +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()) - } - _ => 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>, -} -impl<'ctx> AssembleFailure<'ctx> { - fn lost(failure: impl Into) -> Self { - Self { failure: failure.into(), owners: None } - } -} - -/// 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) }); - } - // 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) }), - }; - // 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) }); - } - // ---- 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 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(); - 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); - Err(AssembleFailure { failure, owners }) - } - } -} - -/// `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::*; - - #[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); + } +}