From 08e2c787616af7c1ecb41efe522a08ff16bfe9b8 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 24 Oct 2026 19:58:28 +0200 Subject: [PATCH] runtime telemetry: GPU load/VRAM (NVML), RAM, CPU cores, prefill/decode tok/s, cache hits, context leleka-memory::telemetry (sampler + per-request records) -> Backend::telemetry_report -> Snapshot.telemetry_json (gRPC) -> control plane /v1/status machine -> leleka status. Co-Authored-By: Claude Sonnet 5.5 --- control-plane/src/backend_worker.rs | 2 + control-plane/src/memory_view.rs | 23 + control-plane/src/server_api.rs | 13 +- crates/backend-api/src/lib.rs | 6 + crates/cuda-driver/src/lib.rs | 6839 +++++++++-------- crates/cuda-driver/src/nvml.rs | 167 + crates/deploy/src/app.rs | 1184 +-- crates/deploy/src/steps.rs | 11 + crates/leleka-memory/src/lib.rs | 47 +- crates/leleka-memory/src/telemetry.rs | 498 ++ crates/leleka-runtime/src/backend.rs | 10 + .../src/backend_original_serve.rs | 36 +- crates/runtime-client/proto/runtime.proto | 2 + crates/runtime-client/src/backend.rs | 11 + crates/runtime-client/src/client.rs | 2 + crates/runtime-client/tests/grpc_backend.rs | 1 + desktop-core/src/runtime_rpc.rs | 11 +- 17 files changed, 4870 insertions(+), 3993 deletions(-) create mode 100644 crates/cuda-driver/src/nvml.rs create mode 100644 crates/leleka-memory/src/telemetry.rs diff --git a/control-plane/src/backend_worker.rs b/control-plane/src/backend_worker.rs index 3fbe8a09..c09212af 100644 --- a/control-plane/src/backend_worker.rs +++ b/control-plane/src/backend_worker.rs @@ -379,6 +379,8 @@ async fn refresh_prefix_view(engine: &Engine, config: &BackendWorkerConfig) { if let Some(view) = &config.memory_view { let report = on_engine(engine, |backend| backend.memory_report()).await.ok().flatten(); view.set(report); + let telemetry = on_engine(engine, |backend| backend.telemetry_report()).await.ok().flatten(); + view.set_telemetry(telemetry); } } diff --git a/control-plane/src/memory_view.rs b/control-plane/src/memory_view.rs index a85b54fd..9bdcaf6f 100644 --- a/control-plane/src/memory_view.rs +++ b/control-plane/src/memory_view.rs @@ -32,6 +32,8 @@ pub struct Closed { #[derive(Default)] pub struct MemoryView { latest: RwLock>, + /// The engine's telemetry document (`Backend::telemetry_report`) and when it was copied. + telemetry: RwLock>, gated: AtomicU64, } @@ -44,6 +46,27 @@ impl MemoryView { } } + /// Replace the stored telemetry document (`None`: the engine reports none, or is unreachable). + pub fn set_telemetry(&self, document: Option) { + let value = document.and_then(|text| serde_json::from_str::(&text).ok()).filter(Value::is_object); + if let Ok(mut latest) = self.telemetry.write() { + *latest = value.map(|value| (value, Instant::now())); + } + } + + /// For `GET /v1/status` `machine`: the engine's telemetry with its age; a document older than [`FRESH_FOR`] is `null`. + pub fn telemetry_status(&self) -> Value { + let Ok(latest) = self.telemetry.read() else { return Value::Null }; + match latest.as_ref() { + Some((value, at)) if at.elapsed() <= FRESH_FOR => { + let mut value = value.clone(); + value["age_ms"] = json!(at.elapsed().as_millis() as u64); + value + } + _ => Value::Null, + } + } + /// For `GET /v1/status`: the report with its age and this process's gate counter; `null` when there is none. pub fn status(&self) -> Value { let Ok(latest) = self.latest.read() else { return Value::Null }; diff --git a/control-plane/src/server_api.rs b/control-plane/src/server_api.rs index e9676f1b..e9d16cbe 100644 --- a/control-plane/src/server_api.rs +++ b/control-plane/src/server_api.rs @@ -341,7 +341,7 @@ async fn status_value(state: &AppState) -> Value { "activity": {"requests": worker.metrics.started, "in_flight": usize::from(busy) + queued, "last_request_at": last_at}, "last_timings": timings, - "machine": {"at": now_s(), "gpu": null, "ram": null}, + "machine": machine_view(&state.memory), "memory": state.memory.status(), }); // Present only when a prefix cache exists: the Python server's status has no such key (golden http_surface). @@ -570,3 +570,14 @@ pub async fn mcp_status(State(state): State) -> Response { }; reply(StatusCode::OK, body) } + +/// `machine` of `GET /v1/status`: the engine's telemetry (GPU load and VRAM, RAM, CPU cores, throughput, cache hits, context) +/// when it reports any; the legacy `{at, gpu, ram}` shape with nulls otherwise. +fn machine_view(memory: &crate::memory_view::MemoryView) -> Value { + let mut view = memory.telemetry_status(); + if !view.is_object() { + return json!({"at": now_s(), "gpu": null, "ram": null}); + } + view["at"] = json!(now_s()); + view +} diff --git a/crates/backend-api/src/lib.rs b/crates/backend-api/src/lib.rs index 275e8e61..3ca4a0f9 100644 --- a/crates/backend-api/src/lib.rs +++ b/crates/backend-api/src/lib.rs @@ -276,6 +276,12 @@ pub trait Backend: Send { fn memory_report(&self) -> Option { None } + /// JSON telemetry of the backend for the operator (`leleka status`): GPU load and VRAM, host RAM, CPU cores in use, prefill and + /// decode tokens per second, prefix-cache hits and the context in use. `None`: this backend reports none (the default). + /// Cheap and non-blocking by contract (the text was rendered by the backend's sampler thread). + fn telemetry_report(&self) -> Option { + None + } } #[derive(Clone, Debug, Eq, PartialEq)] diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index b0077567..ac9fb480 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -1,3419 +1,3420 @@ -//! 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)] - - -/// 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; - -use std::{cell::{Cell, RefCell}, fmt, marker::PhantomData, rc::Rc}; - -#[allow(unsafe_code)] -mod ffi; -pub mod compute_drain; -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", - target_os = "linux", - target_pointer_width = "64" -))] -pub use original_mtp_actor::{OriginalMtpActor, OriginalMtpLoadEvidence, OriginalMtpLoadMeter}; -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - target_pointer_width = "64" -))] -mod original_mtp_draft_head; -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - 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", - target_os = "linux", - target_pointer_width = "64" -))] -pub mod experimental_gpu; -#[cfg(all( - test, - feature = "cuda-driver", - target_os = "linux", - 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", - target_os = "linux", - target_pointer_width = "64" -))] -pub mod closed_kernels_gpu; -#[cfg(all( - test, - feature = "cuda-driver", - target_os = "linux", - target_arch = "x86_64" -))] -#[path = "closed_kernels_gpu_smoke.rs"] -mod closed_kernels_gpu_smoke; -#[cfg(all(test, feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))] -mod original_prefill_schedule_crosscheck; -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - target_pointer_width = "64" -))] -pub mod kar_decode_levels_gpu; -#[cfg(all( - test, - feature = "cuda-driver", - target_os = "linux", - target_arch = "x86_64" -))] -#[path = "kar_decode_levels_gpu_smoke.rs"] -mod kar_decode_levels_gpu_smoke; - -/// 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())?; - Ok(DeviceBuffer { - context: self, - handle: Some(handle), - bytes, - _thread: PhantomData, - }) - } - /// 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>, -} -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 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, target_os = "linux", target_arch = "x86_64"))] -#[path = "moe_down_pack_gpu.rs"] -mod moe_down_pack_gpu_tests; - -#[cfg(all(test, target_os = "linux", 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", target_os = "linux", 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", target_os = "linux", 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, - }; - 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(target_os = "linux", 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", - target_os = "linux", - 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(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))] -pub mod q6_layer_preview; - -#[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))] -pub use qwen_dispatch::batch_gr_preview::GrBatchModule; - -#[cfg(all( - test, - feature = "cuda-driver", - target_os = "linux", - 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(target_os = "linux", 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(target_os = "linux", 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(target_os = "linux", 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(target_os = "linux", 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(target_os = "linux", target_arch = "x86_64"))] -mod gdn_batch_gemm; -#[cfg(all(target_os = "linux", target_arch = "x86_64"))] -pub use gdn_batch_gemm::NativeGdnGemm; - -#[cfg(all(target_os = "linux", target_arch = "x86_64"))] -mod qsa_native_batch; -#[cfg(all(target_os = "linux", 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(target_os = "linux", target_arch = "x86_64"))] -#[allow(unsafe_code)] -mod qsa_index_ffi; -#[cfg(all(target_os = "linux", target_arch = "x86_64"))] -mod qsa_prompt_index; -#[cfg(all(target_os = "linux", 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(target_os = "linux", target_arch = "x86_64"))] -mod qsa_native_decode; -#[cfg(all(target_os = "linux", target_arch = "x86_64"))] -mod qsa_prompt_attention; -#[cfg(all(target_os = "linux", target_arch = "x86_64"))] -#[allow(unsafe_code)] -mod qsa_prompt_attention_ffi; -#[cfg(all(target_os = "linux", target_arch = "x86_64"))] -#[allow(unsafe_code)] -mod qsa_prompt_host_ffi; -#[cfg(all(target_os = "linux", target_arch = "x86_64"))] -mod qsa_prompt_kv; -#[cfg(all(target_os = "linux", target_arch = "x86_64"))] -mod qsa_prompt_resolver; -pub use qsa_prompt_resolver::KvStreamCounters; -#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] -mod kv_stream_gpu; -#[cfg(all(target_os = "linux", target_arch = "x86_64"))] -pub use qsa_native_decode::{QSA_NATIVE_DECODE_BYTES, QsaNativeDecode, QsaNativeDecodeCompletion}; -#[cfg(all(target_os = "linux", target_arch = "x86_64"))] -pub use qsa_prompt_attention::{ - QSA_PROMPT_ATTENTION_BYTES, QsaAttentionInputs, QsaPromptAttention, - QsaPromptAttentionCompletion, -}; -#[cfg(all(target_os = "linux", 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(target_os = "linux", target_arch = "x86_64"))] -pub use qsa_native_decode::OriginalQsaResidentDecodeCompletion; -#[cfg(all(target_os = "linux", target_arch = "x86_64"))] -pub use qsa_prompt_attention::OriginalQsaResidentAttention; -#[cfg(all(target_os = "linux", target_arch = "x86_64"))] -pub use qsa_prompt_index::{ - OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex, - OriginalQsaResidentPromptDevice, OriginalQsaResidentScalarIndex, - OriginalQsaResidentScalarSelection, OriginalQsaResidentSelection, -}; -#[cfg(all(target_os = "linux", target_arch = "x86_64"))] -pub use qsa_prompt_kv::{ - OriginalQsaMappedAppend, OriginalQsaMappedJournal, OriginalQsaMappedPrefix, - OriginalQsaResidentTransport, -}; -#[cfg(all(target_os = "linux", 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; -#[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; -pub use native_prompt_device::{ - OriginalDeviceBlock, OriginalDeviceGrRead, OriginalDeviceNormedResidual, - OriginalDeviceResidual, OriginalPleHistory, OriginalPromptDevice, PromptInputStage, -}; - -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - 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", - target_os = "linux", - target_pointer_width = "64" -))] -pub use mtp_dense_kv::{ - CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, - OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, - OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpStepOutput, -}; - -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - target_pointer_width = "64" -))] -mod original_expert_stager; -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - target_pointer_width = "64" -))] -pub use original_expert_stager::{ - OriginalExpertStager, OriginalFileExpertBlob, OriginalStagerBatch, OriginalStagerCompleted, - OriginalStagerJob, OriginalStagerOptions, OriginalStreamAll, OriginalStreamAllCompleted, - OriginalStreamAllForward, OriginalStreamAllOptions, -}; - -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - target_pointer_width = "64" -))] -mod native_parity; -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - target_pointer_width = "64" -))] -#[allow(unsafe_code)] -mod native_parity_ffi; -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - 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", - target_os = "linux", - target_pointer_width = "64" -))] -pub use mtp_dense_kv::{ - OriginalMtpGrVariant, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, - OriginalMtpScalarPrefill, -}; -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - 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", - target_os = "linux", - target_pointer_width = "64" -))] -mod native_head; -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - 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", - target_os = "linux", - target_pointer_width = "64" -))] -mod original_file_expert_source; -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - target_pointer_width = "64" -))] -pub use original_file_expert_source::{ - OriginalFileExpertSource, OriginalFileSourceBlob, OriginalFileSourceCounters, - OriginalResidentOptions, OriginalSourceSwap, -}; - -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - target_pointer_width = "64" -))] -pub(crate) mod original_verify; -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - 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", - target_os = "linux", - 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", - target_os = "linux", - 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", - target_os = "linux", - target_pointer_width = "64" -))] -pub use qsa_prompt_index::{OriginalVerifyQsaJournal, OriginalVerifyRope}; -#[cfg(all( - feature = "cuda-driver", - feature = "expert-tier-probe", - target_os = "linux", - 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", - target_os = "linux", - target_pointer_width = "64" -))] -mod original_serve_assets; -#[cfg(all( - feature = "cuda-driver", - target_os = "linux", - 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", - target_os = "linux", - 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)] + + +/// 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; + +use std::{cell::{Cell, RefCell}, fmt, marker::PhantomData, rc::Rc}; + +#[allow(unsafe_code)] +mod ffi; +pub mod compute_drain; +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", + target_os = "linux", + target_pointer_width = "64" +))] +pub use original_mtp_actor::{OriginalMtpActor, OriginalMtpLoadEvidence, OriginalMtpLoadMeter}; +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + target_pointer_width = "64" +))] +mod original_mtp_draft_head; +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + 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", + target_os = "linux", + target_pointer_width = "64" +))] +pub mod experimental_gpu; +#[cfg(all( + test, + feature = "cuda-driver", + target_os = "linux", + 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", + target_os = "linux", + target_pointer_width = "64" +))] +pub mod closed_kernels_gpu; +#[cfg(all( + test, + feature = "cuda-driver", + target_os = "linux", + target_arch = "x86_64" +))] +#[path = "closed_kernels_gpu_smoke.rs"] +mod closed_kernels_gpu_smoke; +#[cfg(all(test, feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))] +mod original_prefill_schedule_crosscheck; +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + target_pointer_width = "64" +))] +pub mod kar_decode_levels_gpu; +#[cfg(all( + test, + feature = "cuda-driver", + target_os = "linux", + target_arch = "x86_64" +))] +#[path = "kar_decode_levels_gpu_smoke.rs"] +mod kar_decode_levels_gpu_smoke; + +/// 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())?; + Ok(DeviceBuffer { + context: self, + handle: Some(handle), + bytes, + _thread: PhantomData, + }) + } + /// 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>, +} +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 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, target_os = "linux", target_arch = "x86_64"))] +#[path = "moe_down_pack_gpu.rs"] +mod moe_down_pack_gpu_tests; + +#[cfg(all(test, target_os = "linux", 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", target_os = "linux", 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", target_os = "linux", 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, + }; + 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(target_os = "linux", 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", + target_os = "linux", + 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(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))] +pub mod q6_layer_preview; + +#[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))] +pub use qwen_dispatch::batch_gr_preview::GrBatchModule; + +#[cfg(all( + test, + feature = "cuda-driver", + target_os = "linux", + 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(target_os = "linux", 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(target_os = "linux", 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(target_os = "linux", 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(target_os = "linux", 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(target_os = "linux", target_arch = "x86_64"))] +mod gdn_batch_gemm; +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +pub use gdn_batch_gemm::NativeGdnGemm; + +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +mod qsa_native_batch; +#[cfg(all(target_os = "linux", 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(target_os = "linux", target_arch = "x86_64"))] +#[allow(unsafe_code)] +mod qsa_index_ffi; +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +mod qsa_prompt_index; +#[cfg(all(target_os = "linux", 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(target_os = "linux", target_arch = "x86_64"))] +mod qsa_native_decode; +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +mod qsa_prompt_attention; +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +#[allow(unsafe_code)] +mod qsa_prompt_attention_ffi; +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +#[allow(unsafe_code)] +mod qsa_prompt_host_ffi; +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +mod qsa_prompt_kv; +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +mod qsa_prompt_resolver; +pub use qsa_prompt_resolver::KvStreamCounters; +#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] +mod kv_stream_gpu; +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +pub use qsa_native_decode::{QSA_NATIVE_DECODE_BYTES, QsaNativeDecode, QsaNativeDecodeCompletion}; +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +pub use qsa_prompt_attention::{ + QSA_PROMPT_ATTENTION_BYTES, QsaAttentionInputs, QsaPromptAttention, + QsaPromptAttentionCompletion, +}; +#[cfg(all(target_os = "linux", 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(target_os = "linux", target_arch = "x86_64"))] +pub use qsa_native_decode::OriginalQsaResidentDecodeCompletion; +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +pub use qsa_prompt_attention::OriginalQsaResidentAttention; +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +pub use qsa_prompt_index::{ + OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex, + OriginalQsaResidentPromptDevice, OriginalQsaResidentScalarIndex, + OriginalQsaResidentScalarSelection, OriginalQsaResidentSelection, +}; +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +pub use qsa_prompt_kv::{ + OriginalQsaMappedAppend, OriginalQsaMappedJournal, OriginalQsaMappedPrefix, + OriginalQsaResidentTransport, +}; +#[cfg(all(target_os = "linux", 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; +#[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; +pub use native_prompt_device::{ + OriginalDeviceBlock, OriginalDeviceGrRead, OriginalDeviceNormedResidual, + OriginalDeviceResidual, OriginalPleHistory, OriginalPromptDevice, PromptInputStage, +}; + +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + 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", + target_os = "linux", + target_pointer_width = "64" +))] +pub use mtp_dense_kv::{ + CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, + OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, + OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpStepOutput, +}; + +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + target_pointer_width = "64" +))] +mod original_expert_stager; +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + target_pointer_width = "64" +))] +pub use original_expert_stager::{ + OriginalExpertStager, OriginalFileExpertBlob, OriginalStagerBatch, OriginalStagerCompleted, + OriginalStagerJob, OriginalStagerOptions, OriginalStreamAll, OriginalStreamAllCompleted, + OriginalStreamAllForward, OriginalStreamAllOptions, +}; + +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + target_pointer_width = "64" +))] +mod native_parity; +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + target_pointer_width = "64" +))] +#[allow(unsafe_code)] +mod native_parity_ffi; +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + 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", + target_os = "linux", + target_pointer_width = "64" +))] +pub use mtp_dense_kv::{ + OriginalMtpGrVariant, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, + OriginalMtpScalarPrefill, +}; +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + 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", + target_os = "linux", + target_pointer_width = "64" +))] +mod native_head; +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + 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", + target_os = "linux", + target_pointer_width = "64" +))] +mod original_file_expert_source; +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + target_pointer_width = "64" +))] +pub use original_file_expert_source::{ + OriginalFileExpertSource, OriginalFileSourceBlob, OriginalFileSourceCounters, + OriginalResidentOptions, OriginalSourceSwap, +}; + +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + target_pointer_width = "64" +))] +pub(crate) mod original_verify; +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + 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", + target_os = "linux", + 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", + target_os = "linux", + 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", + target_os = "linux", + target_pointer_width = "64" +))] +pub use qsa_prompt_index::{OriginalVerifyQsaJournal, OriginalVerifyRope}; +#[cfg(all( + feature = "cuda-driver", + feature = "expert-tier-probe", + target_os = "linux", + 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", + target_os = "linux", + target_pointer_width = "64" +))] +mod original_serve_assets; +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + 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", + target_os = "linux", + target_pointer_width = "64" +))] +mod original_serve_access; diff --git a/crates/cuda-driver/src/nvml.rs b/crates/cuda-driver/src/nvml.rs new file mode 100644 index 00000000..ccc98210 --- /dev/null +++ b/crates/cuda-driver/src/nvml.rs @@ -0,0 +1,167 @@ +//! GPU load for the operator (`leleka status`): utilisation, VRAM, power and clock through NVML, loaded with `dlopen` +//! so a host without the library simply reports nothing. Read-only queries; nothing here touches a CUDA context. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct NvmlSample { + pub index: u32, + pub util_pct: u32, + pub mem_util_pct: u32, + pub vram_used_mib: u64, + pub vram_total_mib: u64, + pub power_w: Option, + pub sm_clock_mhz: Option, +} + +/// A reusable handle to NVML's device `index`; `None` when the library, the symbols or the device are missing. +pub struct Nvml(imp::Handle); + +impl Nvml { + pub fn open(index: u32) -> Option { + imp::Handle::open(index).map(Nvml) + } + pub fn sample(&self) -> Option { + self.0.sample() + } +} + +#[cfg(all(target_os = "linux", target_pointer_width = "64"))] +#[allow(unsafe_code)] +mod imp { + use super::NvmlSample; + use libc::{c_int, c_uint, c_void}; + + type Init = unsafe extern "C" fn() -> c_int; + type GetHandle = unsafe extern "C" fn(c_uint, *mut *mut c_void) -> c_int; + #[repr(C)] + #[derive(Default)] + struct Utilization { + gpu: c_uint, + memory: c_uint, + } + #[repr(C)] + #[derive(Default)] + struct MemoryInfo { + total: u64, + free: u64, + used: u64, + } + type GetUtilization = unsafe extern "C" fn(*mut c_void, *mut Utilization) -> c_int; + type GetMemory = unsafe extern "C" fn(*mut c_void, *mut MemoryInfo) -> c_int; + type GetPower = unsafe extern "C" fn(*mut c_void, *mut c_uint) -> c_int; + type GetClock = unsafe extern "C" fn(*mut c_void, c_uint, *mut c_uint) -> c_int; + const NVML_CLOCK_SM: c_uint = 1; + + pub(super) struct Handle { + library: *mut c_void, + device: *mut c_void, + index: u32, + utilization: GetUtilization, + memory: GetMemory, + power: Option, + clock: Option, + } + + // SAFETY: NVML's query functions are thread-safe after nvmlInit; the handle is plain data and the library stays loaded. + unsafe impl Send for Handle {} + unsafe impl Sync for Handle {} + + fn symbol(library: *mut c_void, name: &std::ffi::CStr) -> Option<*mut c_void> { + // SAFETY: a live dlopen handle and a static C name. + let address = unsafe { libc::dlsym(library, name.as_ptr()) }; + (!address.is_null()).then_some(address) + } + + impl Handle { + pub(super) fn open(index: u32) -> Option { + // SAFETY: fixed library names and flags. + let library = unsafe { + let first = libc::dlopen(c"libnvidia-ml.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL); + if first.is_null() { + libc::dlopen(c"libnvidia-ml.so".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) + } else { + first + } + }; + if library.is_null() { + return None; + } + let built = (|| { + // SAFETY: each transmute names the documented NVML C signature of the symbol it loads. + unsafe { + let init: Init = std::mem::transmute(symbol(library, c"nvmlInit_v2")?); + let get_handle: GetHandle = std::mem::transmute(symbol(library, c"nvmlDeviceGetHandleByIndex_v2")?); + let utilization: GetUtilization = std::mem::transmute(symbol(library, c"nvmlDeviceGetUtilizationRates")?); + let memory: GetMemory = std::mem::transmute(symbol(library, c"nvmlDeviceGetMemoryInfo")?); + let power = symbol(library, c"nvmlDeviceGetPowerUsage").map(|p| std::mem::transmute::<*mut c_void, GetPower>(p)); + let clock = symbol(library, c"nvmlDeviceGetClockInfo").map(|p| std::mem::transmute::<*mut c_void, GetClock>(p)); + if init() != 0 { + return None; + } + let mut device: *mut c_void = std::ptr::null_mut(); + if get_handle(index, &mut device) != 0 || device.is_null() { + return None; + } + Some(Handle { library, device, index, utilization, memory, power, clock }) + } + })(); + if built.is_none() { + // SAFETY: the reference this call opened. + unsafe { + libc::dlclose(library); + } + } + built + } + + pub(super) fn sample(&self) -> Option { + let mut utilization = Utilization::default(); + let mut memory = MemoryInfo::default(); + // SAFETY: valid device handle, correctly sized out-parameters. + let (ok_util, ok_mem) = unsafe { ((self.utilization)(self.device, &mut utilization) == 0, (self.memory)(self.device, &mut memory) == 0) }; + if !ok_util && !ok_mem { + return None; + } + let power_w = self.power.and_then(|f| { + let mut milliwatts: c_uint = 0; + // SAFETY: as above. + (unsafe { f(self.device, &mut milliwatts) } == 0).then(|| f64::from(milliwatts) / 1000.0) + }); + let sm_clock_mhz = self.clock.and_then(|f| { + let mut mhz: c_uint = 0; + // SAFETY: as above. + (unsafe { f(self.device, NVML_CLOCK_SM, &mut mhz) } == 0).then_some(mhz) + }); + Some(NvmlSample { + index: self.index, + util_pct: utilization.gpu, + mem_util_pct: utilization.memory, + vram_used_mib: memory.used >> 20, + vram_total_mib: memory.total >> 20, + power_w, + sm_clock_mhz, + }) + } + } + + impl Drop for Handle { + fn drop(&mut self) { + // SAFETY: the reference `open` took; NVML stays initialised for the process, which is harmless. + unsafe { + libc::dlclose(self.library); + } + } + } +} + +#[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] +mod imp { + use super::NvmlSample; + pub(super) struct Handle; + impl Handle { + pub(super) fn open(_index: u32) -> Option { + None + } + pub(super) fn sample(&self) -> Option { + None + } + } +} diff --git a/crates/deploy/src/app.rs b/crates/deploy/src/app.rs index f7d87d19..1883c309 100644 --- a/crates/deploy/src/app.rs +++ b/crates/deploy/src/app.rs @@ -1,545 +1,639 @@ -//! Command implementations behind `main`: `up`, `preflight`, `status`, `down`, `profiles`. -use crate::{ - cli::{Command, Environment, USAGE, UpOptions, parse}, - plan::{Context, Mode, Step, StepState, UnitScopeTag, gather, plan_steps, render_plan}, - preflight::Report, - profile::{BUILTIN, Profile}, - steps::{self, gather_fs, say}, - supervisor, -}; -use serde_json::{Value, json}; -use std::path::PathBuf; - -pub fn env_var(name: &str) -> Option { - std::env::var(name).ok().filter(|v| !v.is_empty()) -} - -fn is_root() -> bool { - #[cfg(target_os = "linux")] - { - rustix::process::geteuid().is_root() - } - #[cfg(not(target_os = "linux"))] - { - false - } -} - -pub async fn main_with(args: Vec) -> i32 { - let var = env_var; - let environment = Environment { - root: is_root(), - home: std::env::var_os("HOME").map(PathBuf::from), - var: &var, - }; - let command = match parse(&args, &environment) { - Ok(command) => command, - Err(message) => { - eprintln!("leleka: {message}"); - return 2; - } - }; - match command { - Command::Help => { - print!("{USAGE}"); - 0 - } - Command::Version => { - println!("leleka {}", env!("CARGO_PKG_VERSION")); - 0 - } - Command::Profiles(None) => { - for (name, _) in BUILTIN { - let profile = Profile::builtin(name).expect("built-in"); - println!("{name}\n {}", profile.description); - } - 0 - } - Command::Profiles(Some(name)) => match Profile::builtin(&name) { - Some(profile) => { - print!("{}", crate::config::to_file_text(&profile)); - 0 - } - None => { - eprintln!("leleka: unknown profile {name:?}"); - 2 - } - }, - Command::Preflight(opts) => preflight(opts).await, - Command::Up(opts) => up(opts).await, - Command::Status(opts) => status(opts).await, - Command::Down(opts) => down(opts).await, - Command::Verify(opts) => verify(opts).await, - Command::Run { config, kar_fd } => { - supervisor::run(supervisor::Options { config, kar_fd }).await - } - Command::ExecInherit(rest) => match crate::sealed::exec_inherit(&rest) { - Ok(never) => match never {}, - Err(message) => { - eprintln!("leleka exec-inherit: {message}"); - 2 - } - }, - } -} - -fn print_report(report: &Report) { - eprint!("{}", report.render()); -} - -fn json_plan(ctx: &Context, steps: &[Step]) -> Value { - json!({ - "mode": ctx.mode, - "profile": ctx.config.as_ref().map(|c| c.profile.name.clone()), - "preflight": ctx.report, - "steps": steps, - "engine_command": ctx.config.as_ref().map(|c| { - let mut args = vec![ctx.paths.bin("leleka-inference").display().to_string()]; - args.extend(c.engine_args(c.kar_arg())); - args - }), - }) -} - -async fn preflight(opts: UpOptions) -> i32 { - let ctx = gather(&opts, &env_var); - match (&ctx.profile, &ctx.report) { - (Err(message), _) => { - eprintln!("leleka: {message}"); - 1 - } - (Ok(_), Some(report)) => { - if opts.json { - println!( - "{}", - serde_json::to_string_pretty(report).expect("serializable") - ); - } else { - print_report(report); - } - i32::from(report.failed()) - } - _ => 1, - } -} - -pub async fn up(opts: UpOptions) -> i32 { - let ctx = gather(&opts, &env_var); - if let Err(message) = &ctx.profile { - eprintln!("leleka: {message}"); - return 1; - } - let report = ctx - .report - .as_ref() - .expect("report exists when the profile does"); - print_report(report); - if let Some(resources) = &ctx.needs.resources { - eprint!("{}", resources.render(&ctx.facts)); - } - let fs = gather_fs(&ctx).await; - let steps = plan_steps(&ctx, &fs); - let blocked = steps - .iter() - .any(|s| matches!(s.state, StepState::Blocked(_)) && s.id != "preflight"); - if opts.dry_run { - if opts.json { - println!( - "{}", - serde_json::to_string_pretty(&json_plan(&ctx, &steps)).expect("serializable") - ); - } else { - print!("{}", render_plan(&ctx, &steps)); - println!( - "mode: {}; nothing was changed (--dry-run)", - ctx.mode.label() - ); - } - return i32::from(report.failed() || blocked); - } - if report.failed() { - eprintln!( - "leleka: preflight failed; nothing was changed. Fix the FAIL lines above and rerun the same command." - ); - return 1; - } - eprint!("{}", render_plan(&ctx, &steps)); - match run_up(&ctx, &steps).await { - Ok(code) => code, - Err(message) => { - eprintln!("leleka: {message}"); - eprintln!( - "leleka: the run is resumable: fix the cause and rerun the same command (finished steps are skipped)." - ); - 1 - } - } -} - -pub async fn run_up(ctx: &Context, steps: &[Step]) -> Result { - let changes = steps::prepare(ctx, steps).await?; - let config = steps::config_of(ctx)?; - match ctx.mode { - Mode::None => { - say(&format!( - "prepared. Start it with: {} run --config {}", - ctx.paths.bin("leleka").display(), - ctx.paths.run_config().display() - )); - Ok(0) - } - Mode::Systemd(scope) => { - #[cfg(unix)] - if scope == UnitScopeTag::System { - steps::ensure_service_user(ctx).await?; - steps::hand_over_to_service_user(ctx)?; - } - let changed = steps::install_unit(ctx, scope).await?; - steps::start_unit(ctx, scope, changed || changes.needs_restart()).await?; - steps::wait_ready(ctx, Some(scope)).await?; - summary(ctx, config); - Ok(0) - } - Mode::Foreground => { - if let Some(fd) = ctx.opts.kar_fd { - crate::sealed::check_inherited_archive(fd, crate::profile::ARCHIVE_BYTES)?; - } - if steps::probe_ready(ctx).await { - say("a supervisor for this state directory is already ready"); - summary(ctx, config); - return Ok(0); - } - if crate::plan::service_running(&ctx.paths) { - return Err(format!( - "another supervisor is running for {} (not ready yet); wait for it or stop it first", - ctx.opts.dirs.state.display() - )); - } - let options = supervisor::Options { - config: ctx.paths.run_config(), - kar_fd: ctx.opts.kar_fd, - }; - let run = supervisor::run(options); - tokio::pin!(run); - let mut printed = false; - loop { - tokio::select! { - code = &mut run => return Ok(code), - ready = steps::wait_ready(ctx, None), if !printed => { - printed = true; - match ready { - Ok(()) => summary(ctx, config), - Err(message) => say(&message), - } - } - } - } - } - } -} - -pub fn summary_json(ctx: &Context, config: &crate::config::RunConfig) -> Value { - let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu); - json!({ - "ready": true, - "endpoint": format!("http://{}", ctx.opts.ports.api), - "model": config.model_id, - "model_digest": config.model_digest, - "api_key_file": ctx.paths.api_key().display().to_string(), - "gpu": gpu.map(|g| json!({"index": g.index, "name": g.name, "sm": g.sm, "vram_total_mib": g.vram_total_mib, "driver": g.driver})), - "profile": config.profile.name, - "gpu_budget_bytes": config.profile.gpu_budget_bytes, - "context_tokens": config.profile.context_tokens, - "kar_source": config.profile.kar_source.as_str(), - "ram_total_bytes": ctx.facts.memory.total, - "ram_available_at_start_bytes": ctx.facts.memory.available, - "service": ctx.mode.label(), - "logs": ctx.paths.logs().display().to_string(), - "state": ctx.opts.dirs.state.display().to_string(), - "assets": ctx.opts.dirs.assets.display().to_string(), - }) -} - -pub fn summary(ctx: &Context, config: &crate::config::RunConfig) { - let gib = |bytes: u64| format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64); - if ctx.opts.json { - println!( - "{}", - serde_json::to_string_pretty(&summary_json(ctx, config)).expect("serializable") - ); - return; - } - let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu); - let key_file = ctx.paths.api_key().display().to_string(); - let mut text = String::from("\nLeleka is ready.\n"); - text.push_str(&format!( - " endpoint http://{} (loopback only; reach it from elsewhere through an SSH tunnel)\n", - ctx.opts.ports.api - )); - text.push_str(&format!( - " model {} {}\n", - config.model_id, config.model_digest - )); - text.push_str(&format!( - " api key in {key_file} (send it as `Authorization: Bearer ...`)\n" - )); - if let Some(gpu) = gpu { - text.push_str(&format!( - " gpu {} (GPU {}, sm_{}, {} MiB, driver {})\n", - gpu.name, - gpu.index, - gpu.sm.map_or("?".into(), |s| s.to_string()), - gpu.vram_total_mib, - gpu.driver - )); - } - text.push_str(&format!( - " profile {}: VRAM budget {}, context {} tokens, KAR archive as {}\n", - config.profile.name, - gib(config.profile.gpu_budget_bytes), - config.profile.context_tokens, - match config.profile.kar_source { - crate::profile::KarSource::Memfd => format!( - "a sealed memfd ({} of RAM held for the life of the service)", - gib(crate::profile::ARCHIVE_BYTES) - ), - crate::profile::KarSource::File => "a read-only file (page cache only)".to_owned(), - } - )); - text.push_str(&format!( - " host RAM {} total, {} available before start\n", - gib(ctx.facts.memory.total), - gib(ctx.facts.memory.available) - )); - text.push_str(&format!(" service {}\n", ctx.mode.label())); - if ctx.mode == Mode::Systemd(UnitScopeTag::User) { - text.push_str(" a user unit runs while you have a session; `loginctl enable-linger $USER` starts it at boot -"); - } - text.push_str(&format!( - " logs {} (leleka.log, engine.log, gateway.log, api.log)\n", - ctx.paths.logs().display() - )); - text.push_str(&format!( - " try curl -s -H \"Authorization: Bearer $(cat {key_file})\" -H 'content-type: application/json' \\\n -d '{{\"model\":\"{}\",\"input\":\"hello\",\"max_output_tokens\":32}}' http://{}/v1/responses\n", - config.model_id, ctx.opts.ports.api - )); - eprintln!("{text}"); -} - -/// Which systemd unit of this deployment exists (system first), judged by the unit file. -fn installed_scope(paths: &crate::layout::Paths) -> Option { - let home = std::env::var_os("HOME").map(PathBuf::from); - [UnitScopeTag::System, UnitScopeTag::User] - .into_iter() - .find(|scope| { - crate::units::unit_path(scope.scope(), home.as_deref(), paths.unit_name()) - .is_ok_and(|path| path.is_file()) - }) -} - -/// Cheap by design (the container health check runs it every 30 s): no GPU probe, no hashing. -async fn status(opts: UpOptions) -> i32 { - let paths = opts.dirs.paths(); - let api = crate::config::RunConfig::read(&paths.run_config()) - .map(|config| config.ports.api) - .unwrap_or_else(|_| opts.ports.api.clone()); - let status: Option = std::fs::read_to_string(paths.status_file()) - .ok() - .and_then(|t| serde_json::from_str(&t).ok()); - let ready = steps::probe_ready_at(&paths, &api).await; - let unit = match installed_scope(&paths) { - Some(scope) => { - let mut command = tokio::process::Command::new("systemctl"); - if scope == UnitScopeTag::User { - command.arg("--user"); - } - command.args(["is-active", paths.unit_name()]); - command - .output() - .await - .ok() - .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()) - } - None => None, - }; - if opts.json { - println!( - "{}", - serde_json::to_string_pretty( - &json!({"ready": ready, "unit": unit, "supervisor": status}) - ) - .expect("serializable") - ); - } else { - println!("ready: {ready}"); - if let Some(unit) = unit { - println!("systemd unit {}: {unit}", paths.unit_name()); - } - match status { - Some(s) => println!( - "supervisor: phase {} (pid {}), engine restarts {}, updated {} - {}", - s["phase"].as_str().unwrap_or("?"), - s["supervisor_pid"], - s["engine_restarts"], - s["updated_unix"] - .as_u64() - .map(supervisor::format_utc) - .unwrap_or_default(), - s["message"].as_str().unwrap_or("") - ), - None => println!( - "supervisor: no status file in {} (never started?)", - paths.run_dir().display() - ), - } - } - i32::from(!ready) -} - -/// `leleka verify`: full hashing of both shards and the archive, in parallel, against the pinned digests; renews the -/// stamps (`STATE/stamps/engine`) that let the next start skip the hashing. Nothing is loaded and no GPU is touched. -async fn verify(opts: UpOptions) -> i32 { - use crate::{config::RUNTIME_TOKEN_ENV, facts::parse_env_file, profile::KarSource}; - use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps, sha256_of_file}; - let paths = opts.dirs.paths(); - let config = match crate::config::RunConfig::read(&paths.run_config()) { - Ok(config) => config, - Err(message) => { - eprintln!("leleka: {message}"); - return 2; - } - }; - let stamp_dir = paths.engine_stamps(); - if let Err(error) = std::fs::create_dir_all(&stamp_dir) { - eprintln!("leleka: cannot create {}: {error}", stamp_dir.display()); - return 1; - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let _ = std::fs::set_permissions(&stamp_dir, std::fs::Permissions::from_mode(0o700)); - } - let env = std::fs::read_to_string(paths.env_file()) - .map(|text| parse_env_file(&text)) - .unwrap_or_default(); - let Some(token) = env.get(RUNTIME_TOKEN_ENV).cloned() else { - eprintln!( - "leleka: {} has no {RUNTIME_TOKEN_ENV}; run `leleka up`", - paths.env_file().display() - ); - return 2; - }; - let started = std::time::Instant::now(); - say( - "hashing both shards (and the archive, when it is a file) in full, in parallel; this renews the stamps", - ); - let engine = tokio::process::Command::new(paths.bin("leleka-inference")) - .args(config.verify_args(true)) - .env(RUNTIME_TOKEN_ENV, token) - .env_remove("HF_TOKEN") - .stdin(std::process::Stdio::null()) - .status(); - // A sealed-memfd profile cannot hand the engine the file (it must be read-only and owned); the archive file is - // hashed here instead, against the pinned digest, and stamped for the supervisor (kind `kar-source`). - let archive = tokio::task::spawn_blocking({ - let kar = paths.kar(); - let memfd = config.profile.kar_source == KarSource::Memfd; - let stamps = VerifyStamps::new(stamp_dir.clone(), true); - move || -> Result, String> { - if !memfd { - return Ok(None); - } - let begun = std::time::Instant::now(); - let file = std::fs::File::open(&kar) - .map_err(|e| format!("cannot open {}: {e}", kar.display()))?; - let before = file.metadata().ok().and_then(|m| FileIdentity::of(&m)); - let digest = - sha256_of_file(&file).map_err(|e| format!("cannot read {}: {e}", kar.display()))?; - if digest != crate::profile::archive_sha256() { - return Err(format!( - "{} does not match the pinned archive digest", - kar.display() - )); - } - let after = file.metadata().ok().and_then(|m| FileIdentity::of(&m)); - if let (Some(before), true) = (before, before == after) { - stamps - .record("kar-source", &crate::profile::archive_sha256(), &before) - .map_err(|e| format!("cannot record the archive stamp: {e}"))?; - } - Ok(Some(begun.elapsed().as_secs_f64())) - } - }); - let (engine, archive) = tokio::join!(engine, archive); - let mut code = 0; - match engine { - Ok(status) if status.success() => {} - Ok(status) => { - eprintln!( - "leleka: the engine's verification failed ({status}); a file does not match its pinned digest" - ); - code = 1; - } - Err(error) => { - eprintln!( - "leleka: cannot run {}: {error}", - paths.bin("leleka-inference").display() - ); - code = 1; - } - } - match archive { - Ok(Ok(Some(seconds))) => say(&format!( - "archive file matches the pinned SHA-256 ({seconds:.1}s); stamped" - )), - Ok(Ok(None)) => {} - Ok(Err(message)) => { - eprintln!("leleka: {message}"); - code = 1; - } - Err(error) => { - eprintln!("leleka: archive verification failed to run: {error}"); - code = 1; - } - } - say(&format!( - "verification {} in {:.1}s", - if code == 0 { "passed" } else { "FAILED" }, - started.elapsed().as_secs_f32() - )); - code -} - -async fn down(opts: UpOptions) -> i32 { - let paths = opts.dirs.paths(); - match installed_scope(&paths) { - Some(scope) => { - let mut command = tokio::process::Command::new("systemctl"); - if scope == UnitScopeTag::User { - command.arg("--user"); - } - match command.args(["stop", paths.unit_name()]).status().await { - Ok(status) if status.success() => { - eprintln!("leleka: stopped {}", paths.unit_name()); - 0 - } - Ok(status) => { - eprintln!("leleka: systemctl stop failed ({status})"); - 1 - } - Err(error) => { - eprintln!("leleka: cannot run systemctl: {error}"); - 1 - } - } - } - None => { - eprintln!( - "leleka: no systemd unit is installed for this deployment; a foreground service stops with Ctrl-C (SIGINT/SIGTERM drain the API, then stop the gateway and the engine)" - ); - 0 - } - } -} +//! Command implementations behind `main`: `up`, `preflight`, `status`, `down`, `profiles`. +use crate::{ + cli::{Command, Environment, USAGE, UpOptions, parse}, + plan::{Context, Mode, Step, StepState, UnitScopeTag, gather, plan_steps, render_plan}, + preflight::Report, + profile::{BUILTIN, Profile}, + steps::{self, gather_fs, say}, + supervisor, +}; +use serde_json::{Value, json}; +use std::path::PathBuf; + +pub fn env_var(name: &str) -> Option { + std::env::var(name).ok().filter(|v| !v.is_empty()) +} + +fn is_root() -> bool { + #[cfg(target_os = "linux")] + { + rustix::process::geteuid().is_root() + } + #[cfg(not(target_os = "linux"))] + { + false + } +} + +pub async fn main_with(args: Vec) -> i32 { + let var = env_var; + let environment = Environment { + root: is_root(), + home: std::env::var_os("HOME").map(PathBuf::from), + var: &var, + }; + let command = match parse(&args, &environment) { + Ok(command) => command, + Err(message) => { + eprintln!("leleka: {message}"); + return 2; + } + }; + match command { + Command::Help => { + print!("{USAGE}"); + 0 + } + Command::Version => { + println!("leleka {}", env!("CARGO_PKG_VERSION")); + 0 + } + Command::Profiles(None) => { + for (name, _) in BUILTIN { + let profile = Profile::builtin(name).expect("built-in"); + println!("{name}\n {}", profile.description); + } + 0 + } + Command::Profiles(Some(name)) => match Profile::builtin(&name) { + Some(profile) => { + print!("{}", crate::config::to_file_text(&profile)); + 0 + } + None => { + eprintln!("leleka: unknown profile {name:?}"); + 2 + } + }, + Command::Preflight(opts) => preflight(opts).await, + Command::Up(opts) => up(opts).await, + Command::Status(opts) => status(opts).await, + Command::Down(opts) => down(opts).await, + Command::Verify(opts) => verify(opts).await, + Command::Run { config, kar_fd } => { + supervisor::run(supervisor::Options { config, kar_fd }).await + } + Command::ExecInherit(rest) => match crate::sealed::exec_inherit(&rest) { + Ok(never) => match never {}, + Err(message) => { + eprintln!("leleka exec-inherit: {message}"); + 2 + } + }, + } +} + +fn print_report(report: &Report) { + eprint!("{}", report.render()); +} + +fn json_plan(ctx: &Context, steps: &[Step]) -> Value { + json!({ + "mode": ctx.mode, + "profile": ctx.config.as_ref().map(|c| c.profile.name.clone()), + "preflight": ctx.report, + "steps": steps, + "engine_command": ctx.config.as_ref().map(|c| { + let mut args = vec![ctx.paths.bin("leleka-inference").display().to_string()]; + args.extend(c.engine_args(c.kar_arg())); + args + }), + }) +} + +async fn preflight(opts: UpOptions) -> i32 { + let ctx = gather(&opts, &env_var); + match (&ctx.profile, &ctx.report) { + (Err(message), _) => { + eprintln!("leleka: {message}"); + 1 + } + (Ok(_), Some(report)) => { + if opts.json { + println!( + "{}", + serde_json::to_string_pretty(report).expect("serializable") + ); + } else { + print_report(report); + } + i32::from(report.failed()) + } + _ => 1, + } +} + +pub async fn up(opts: UpOptions) -> i32 { + let ctx = gather(&opts, &env_var); + if let Err(message) = &ctx.profile { + eprintln!("leleka: {message}"); + return 1; + } + let report = ctx + .report + .as_ref() + .expect("report exists when the profile does"); + print_report(report); + if let Some(resources) = &ctx.needs.resources { + eprint!("{}", resources.render(&ctx.facts)); + } + let fs = gather_fs(&ctx).await; + let steps = plan_steps(&ctx, &fs); + let blocked = steps + .iter() + .any(|s| matches!(s.state, StepState::Blocked(_)) && s.id != "preflight"); + if opts.dry_run { + if opts.json { + println!( + "{}", + serde_json::to_string_pretty(&json_plan(&ctx, &steps)).expect("serializable") + ); + } else { + print!("{}", render_plan(&ctx, &steps)); + println!( + "mode: {}; nothing was changed (--dry-run)", + ctx.mode.label() + ); + } + return i32::from(report.failed() || blocked); + } + if report.failed() { + eprintln!( + "leleka: preflight failed; nothing was changed. Fix the FAIL lines above and rerun the same command." + ); + return 1; + } + eprint!("{}", render_plan(&ctx, &steps)); + match run_up(&ctx, &steps).await { + Ok(code) => code, + Err(message) => { + eprintln!("leleka: {message}"); + eprintln!( + "leleka: the run is resumable: fix the cause and rerun the same command (finished steps are skipped)." + ); + 1 + } + } +} + +pub async fn run_up(ctx: &Context, steps: &[Step]) -> Result { + let changes = steps::prepare(ctx, steps).await?; + let config = steps::config_of(ctx)?; + match ctx.mode { + Mode::None => { + say(&format!( + "prepared. Start it with: {} run --config {}", + ctx.paths.bin("leleka").display(), + ctx.paths.run_config().display() + )); + Ok(0) + } + Mode::Systemd(scope) => { + #[cfg(unix)] + if scope == UnitScopeTag::System { + steps::ensure_service_user(ctx).await?; + steps::hand_over_to_service_user(ctx)?; + } + let changed = steps::install_unit(ctx, scope).await?; + steps::start_unit(ctx, scope, changed || changes.needs_restart()).await?; + steps::wait_ready(ctx, Some(scope)).await?; + summary(ctx, config); + Ok(0) + } + Mode::Foreground => { + if let Some(fd) = ctx.opts.kar_fd { + crate::sealed::check_inherited_archive(fd, crate::profile::ARCHIVE_BYTES)?; + } + if steps::probe_ready(ctx).await { + say("a supervisor for this state directory is already ready"); + summary(ctx, config); + return Ok(0); + } + if crate::plan::service_running(&ctx.paths) { + return Err(format!( + "another supervisor is running for {} (not ready yet); wait for it or stop it first", + ctx.opts.dirs.state.display() + )); + } + let options = supervisor::Options { + config: ctx.paths.run_config(), + kar_fd: ctx.opts.kar_fd, + }; + let run = supervisor::run(options); + tokio::pin!(run); + let mut printed = false; + loop { + tokio::select! { + code = &mut run => return Ok(code), + ready = steps::wait_ready(ctx, None), if !printed => { + printed = true; + match ready { + Ok(()) => summary(ctx, config), + Err(message) => say(&message), + } + } + } + } + } + } +} + +pub fn summary_json(ctx: &Context, config: &crate::config::RunConfig) -> Value { + let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu); + json!({ + "ready": true, + "endpoint": format!("http://{}", ctx.opts.ports.api), + "model": config.model_id, + "model_digest": config.model_digest, + "api_key_file": ctx.paths.api_key().display().to_string(), + "gpu": gpu.map(|g| json!({"index": g.index, "name": g.name, "sm": g.sm, "vram_total_mib": g.vram_total_mib, "driver": g.driver})), + "profile": config.profile.name, + "gpu_budget_bytes": config.profile.gpu_budget_bytes, + "context_tokens": config.profile.context_tokens, + "kar_source": config.profile.kar_source.as_str(), + "ram_total_bytes": ctx.facts.memory.total, + "ram_available_at_start_bytes": ctx.facts.memory.available, + "service": ctx.mode.label(), + "logs": ctx.paths.logs().display().to_string(), + "state": ctx.opts.dirs.state.display().to_string(), + "assets": ctx.opts.dirs.assets.display().to_string(), + }) +} + +pub fn summary(ctx: &Context, config: &crate::config::RunConfig) { + let gib = |bytes: u64| format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64); + if ctx.opts.json { + println!( + "{}", + serde_json::to_string_pretty(&summary_json(ctx, config)).expect("serializable") + ); + return; + } + let gpu = ctx.facts.gpus.iter().find(|g| g.index == ctx.opts.gpu); + let key_file = ctx.paths.api_key().display().to_string(); + let mut text = String::from("\nLeleka is ready.\n"); + text.push_str(&format!( + " endpoint http://{} (loopback only; reach it from elsewhere through an SSH tunnel)\n", + ctx.opts.ports.api + )); + text.push_str(&format!( + " model {} {}\n", + config.model_id, config.model_digest + )); + text.push_str(&format!( + " api key in {key_file} (send it as `Authorization: Bearer ...`)\n" + )); + if let Some(gpu) = gpu { + text.push_str(&format!( + " gpu {} (GPU {}, sm_{}, {} MiB, driver {})\n", + gpu.name, + gpu.index, + gpu.sm.map_or("?".into(), |s| s.to_string()), + gpu.vram_total_mib, + gpu.driver + )); + } + text.push_str(&format!( + " profile {}: VRAM budget {}, context {} tokens, KAR archive as {}\n", + config.profile.name, + gib(config.profile.gpu_budget_bytes), + config.profile.context_tokens, + match config.profile.kar_source { + crate::profile::KarSource::Memfd => format!( + "a sealed memfd ({} of RAM held for the life of the service)", + gib(crate::profile::ARCHIVE_BYTES) + ), + crate::profile::KarSource::File => "a read-only file (page cache only)".to_owned(), + } + )); + text.push_str(&format!( + " host RAM {} total, {} available before start\n", + gib(ctx.facts.memory.total), + gib(ctx.facts.memory.available) + )); + text.push_str(&format!(" service {}\n", ctx.mode.label())); + if ctx.mode == Mode::Systemd(UnitScopeTag::User) { + text.push_str(" a user unit runs while you have a session; `loginctl enable-linger $USER` starts it at boot +"); + } + text.push_str(&format!( + " logs {} (leleka.log, engine.log, gateway.log, api.log)\n", + ctx.paths.logs().display() + )); + text.push_str(&format!( + " try curl -s -H \"Authorization: Bearer $(cat {key_file})\" -H 'content-type: application/json' \\\n -d '{{\"model\":\"{}\",\"input\":\"hello\",\"max_output_tokens\":32}}' http://{}/v1/responses\n", + config.model_id, ctx.opts.ports.api + )); + eprintln!("{text}"); +} + +/// Which systemd unit of this deployment exists (system first), judged by the unit file. +fn installed_scope(paths: &crate::layout::Paths) -> Option { + let home = std::env::var_os("HOME").map(PathBuf::from); + [UnitScopeTag::System, UnitScopeTag::User] + .into_iter() + .find(|scope| { + crate::units::unit_path(scope.scope(), home.as_deref(), paths.unit_name()) + .is_ok_and(|path| path.is_file()) + }) +} + +/// Cheap by design (the container health check runs it every 30 s): no GPU probe, no hashing. +async fn status(opts: UpOptions) -> i32 { + let paths = opts.dirs.paths(); + let api = crate::config::RunConfig::read(&paths.run_config()) + .map(|config| config.ports.api) + .unwrap_or_else(|_| opts.ports.api.clone()); + let status: Option = std::fs::read_to_string(paths.status_file()) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()); + let ready = steps::probe_ready_at(&paths, &api).await; + let gateway = if ready { steps::fetch_status(&paths, &api).await } else { None }; + let machine = gateway.as_ref().map(|g| g["machine"].clone()).filter(Value::is_object); + let unit = match installed_scope(&paths) { + Some(scope) => { + let mut command = tokio::process::Command::new("systemctl"); + if scope == UnitScopeTag::User { + command.arg("--user"); + } + command.args(["is-active", paths.unit_name()]); + command + .output() + .await + .ok() + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()) + } + None => None, + }; + if opts.json { + println!( + "{}", + serde_json::to_string_pretty( + &json!({"ready": ready, "unit": unit, "supervisor": status, "machine": machine, + "prefix_cache": gateway.as_ref().map(|g| g["prefix_cache"].clone())}) + ) + .expect("serializable") + ); + } else { + println!("ready: {ready}"); + if let Some(unit) = unit { + println!("systemd unit {}: {unit}", paths.unit_name()); + } + match status { + Some(s) => println!( + "supervisor: phase {} (pid {}), engine restarts {}, updated {} + {}", + s["phase"].as_str().unwrap_or("?"), + s["supervisor_pid"], + s["engine_restarts"], + s["updated_unix"] + .as_u64() + .map(supervisor::format_utc) + .unwrap_or_default(), + s["message"].as_str().unwrap_or("") + ), + None => println!( + "supervisor: no status file in {} (never started?)", + paths.run_dir().display() + ), + } + if let Some(machine) = &machine { + print!("{}", render_machine(machine)); + } else if ready { + println!("engine load: the engine reports no telemetry yet"); + } + } + i32::from(!ready) +} + +/// The human view of the engine telemetry document (`machine` of `/v1/status`): GPU, CPU, RAM, throughput, cache, context. +pub fn render_machine(machine: &Value) -> String { + let gib = |mib: &Value| mib.as_f64().map_or("?".to_owned(), |m| format!("{:.1}", m / 1024.0)); + let num = |value: &Value| value.as_f64().map_or("-".to_owned(), |v| format!("{v:.0}")); + let pct = |value: &Value| value.as_f64().map_or("-".to_owned(), |v| format!("{:.0}%", v * 100.0)); + let mut out = format!("engine load ({}):\n", machine["phase"].as_str().unwrap_or("?")); + let gpu = &machine["gpu"]; + if gpu.is_object() { + out.push_str(&format!( + " gpu {}% busy (memory bus {}%), VRAM {} of {} GiB{}{}\n", + gpu["util_pct"], gpu["mem_util_pct"], gib(&gpu["vram_used_mib"]), gib(&gpu["vram_total_mib"]), + gpu["power_w"].as_f64().map_or(String::new(), |w| format!(", {w:.0} W")), + gpu["sm_clock_mhz"].as_u64().map_or(String::new(), |m| format!(", {m} MHz")), + )); + } + let cpu = &machine["cpu"]; + if cpu.is_object() { + out.push_str(&format!( + " cpu {} of {} cores busy in the engine (whole system {}%)\n", + cpu["process_busy_cores"], cpu["cores"], cpu["system_busy_pct"] + )); + } + let ram = &machine["ram"]; + if ram.is_object() { + out.push_str(&format!( + " ram {} of {} GiB available, engine {} GiB resident ({} GiB pinned), swap in use {} GiB\n", + gib(&ram["available_mib"]), gib(&ram["total_mib"]), gib(&ram["process_rss_mib"]), gib(&ram["process_pinned_mib"]), gib(&ram["swap_used_mib"]) + )); + } + let rates = &machine["throughput"]; + out.push_str(&format!( + " prefill {} tok/s last, {} average, {} lifetime\n", + num(&rates["prefill_tok_s_last"]), num(&rates["prefill_tok_s_avg"]), num(&rates["prefill_tok_s_lifetime"]) + )); + out.push_str(&format!( + " decode {} tok/s last, {} average, {} lifetime{}\n", + num(&rates["decode_tok_s_last"]), num(&rates["decode_tok_s_avg"]), num(&rates["decode_tok_s_lifetime"]), + rates["decode_tok_s_live"].as_f64().map_or(String::new(), |v| format!(", {v:.0} now")) + )); + let cache = &machine["cache"]; + out.push_str(&format!( + " cache {} of requests hit, {} of prompt tokens reused (last request {} of {})\n", + pct(&cache["hit_ratio"]), pct(&cache["token_hit_ratio"]), cache["last_reused_tokens"], cache["last_prompt_tokens"] + )); + let context = &machine["context"]; + out.push_str(&format!( + " context {} of {} tokens{}\n", + context["live_tokens"], context["max_tokens"], + context["used_pct"].as_f64().map_or(String::new(), |p| format!(" ({p:.1}%)")) + )); + out +} + +/// `leleka verify`: full hashing of both shards and the archive, in parallel, against the pinned digests; renews the +/// stamps (`STATE/stamps/engine`) that let the next start skip the hashing. Nothing is loaded and no GPU is touched. +async fn verify(opts: UpOptions) -> i32 { + use crate::{config::RUNTIME_TOKEN_ENV, facts::parse_env_file, profile::KarSource}; + use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps, sha256_of_file}; + let paths = opts.dirs.paths(); + let config = match crate::config::RunConfig::read(&paths.run_config()) { + Ok(config) => config, + Err(message) => { + eprintln!("leleka: {message}"); + return 2; + } + }; + let stamp_dir = paths.engine_stamps(); + if let Err(error) = std::fs::create_dir_all(&stamp_dir) { + eprintln!("leleka: cannot create {}: {error}", stamp_dir.display()); + return 1; + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&stamp_dir, std::fs::Permissions::from_mode(0o700)); + } + let env = std::fs::read_to_string(paths.env_file()) + .map(|text| parse_env_file(&text)) + .unwrap_or_default(); + let Some(token) = env.get(RUNTIME_TOKEN_ENV).cloned() else { + eprintln!( + "leleka: {} has no {RUNTIME_TOKEN_ENV}; run `leleka up`", + paths.env_file().display() + ); + return 2; + }; + let started = std::time::Instant::now(); + say( + "hashing both shards (and the archive, when it is a file) in full, in parallel; this renews the stamps", + ); + let engine = tokio::process::Command::new(paths.bin("leleka-inference")) + .args(config.verify_args(true)) + .env(RUNTIME_TOKEN_ENV, token) + .env_remove("HF_TOKEN") + .stdin(std::process::Stdio::null()) + .status(); + // A sealed-memfd profile cannot hand the engine the file (it must be read-only and owned); the archive file is + // hashed here instead, against the pinned digest, and stamped for the supervisor (kind `kar-source`). + let archive = tokio::task::spawn_blocking({ + let kar = paths.kar(); + let memfd = config.profile.kar_source == KarSource::Memfd; + let stamps = VerifyStamps::new(stamp_dir.clone(), true); + move || -> Result, String> { + if !memfd { + return Ok(None); + } + let begun = std::time::Instant::now(); + let file = std::fs::File::open(&kar) + .map_err(|e| format!("cannot open {}: {e}", kar.display()))?; + let before = file.metadata().ok().and_then(|m| FileIdentity::of(&m)); + let digest = + sha256_of_file(&file).map_err(|e| format!("cannot read {}: {e}", kar.display()))?; + if digest != crate::profile::archive_sha256() { + return Err(format!( + "{} does not match the pinned archive digest", + kar.display() + )); + } + let after = file.metadata().ok().and_then(|m| FileIdentity::of(&m)); + if let (Some(before), true) = (before, before == after) { + stamps + .record("kar-source", &crate::profile::archive_sha256(), &before) + .map_err(|e| format!("cannot record the archive stamp: {e}"))?; + } + Ok(Some(begun.elapsed().as_secs_f64())) + } + }); + let (engine, archive) = tokio::join!(engine, archive); + let mut code = 0; + match engine { + Ok(status) if status.success() => {} + Ok(status) => { + eprintln!( + "leleka: the engine's verification failed ({status}); a file does not match its pinned digest" + ); + code = 1; + } + Err(error) => { + eprintln!( + "leleka: cannot run {}: {error}", + paths.bin("leleka-inference").display() + ); + code = 1; + } + } + match archive { + Ok(Ok(Some(seconds))) => say(&format!( + "archive file matches the pinned SHA-256 ({seconds:.1}s); stamped" + )), + Ok(Ok(None)) => {} + Ok(Err(message)) => { + eprintln!("leleka: {message}"); + code = 1; + } + Err(error) => { + eprintln!("leleka: archive verification failed to run: {error}"); + code = 1; + } + } + say(&format!( + "verification {} in {:.1}s", + if code == 0 { "passed" } else { "FAILED" }, + started.elapsed().as_secs_f32() + )); + code +} + +async fn down(opts: UpOptions) -> i32 { + let paths = opts.dirs.paths(); + match installed_scope(&paths) { + Some(scope) => { + let mut command = tokio::process::Command::new("systemctl"); + if scope == UnitScopeTag::User { + command.arg("--user"); + } + match command.args(["stop", paths.unit_name()]).status().await { + Ok(status) if status.success() => { + eprintln!("leleka: stopped {}", paths.unit_name()); + 0 + } + Ok(status) => { + eprintln!("leleka: systemctl stop failed ({status})"); + 1 + } + Err(error) => { + eprintln!("leleka: cannot run systemctl: {error}"); + 1 + } + } + } + None => { + eprintln!( + "leleka: no systemd unit is installed for this deployment; a foreground service stops with Ctrl-C (SIGINT/SIGTERM drain the API, then stop the gateway and the engine)" + ); + 0 + } + } +} + +#[cfg(test)] +mod machine_tests { + use super::render_machine; + use serde_json::json; + + #[test] + fn the_machine_view_names_every_figure_the_operator_asked_for() { + let text = render_machine(&json!({ + "phase": "decode", + "gpu": {"util_pct": 91, "mem_util_pct": 40, "vram_used_mib": 30000, "vram_total_mib": 32607, "power_w": 480.0, "sm_clock_mhz": 2900}, + "cpu": {"cores": 32, "process_busy_cores": 7.4, "system_busy_pct": 31.0}, + "ram": {"total_mib": 122880, "available_mib": 70000, "process_rss_mib": 55000, "process_pinned_mib": 3000, "swap_used_mib": 0}, + "throughput": {"prefill_tok_s_last": 5050.0, "prefill_tok_s_avg": 5010.0, "prefill_tok_s_lifetime": 5030.0, + "decode_tok_s_last": 131.0, "decode_tok_s_avg": 129.0, "decode_tok_s_lifetime": 128.5, "decode_tok_s_live": 135.2}, + "cache": {"hit_ratio": 0.87, "token_hit_ratio": 0.91, "last_reused_tokens": 175104, "last_prompt_tokens": 179968}, + "context": {"live_tokens": 179968, "max_tokens": 262144, "used_pct": 68.65} + })); + for needle in ["engine load (decode)", "91% busy", "VRAM 29.3 of 31.8 GiB", "480 W", "7.4 of 32 cores", "prefill 5050 tok/s", "decode 131 tok/s", "135 now", "87% of requests", "91% of prompt", "179968 of 262144 tokens (68.7%)"] { + assert!(text.contains(needle), "{needle}\ +{text}"); + } + } + + #[test] + fn missing_blocks_are_left_out_not_invented() { + let text = render_machine(&json!({"phase": "idle", "gpu": null, "cpu": null, "ram": null, + "throughput": {}, "cache": {}, "context": {"live_tokens": 0, "max_tokens": 8192}})); + assert!(!text.contains(" gpu ") && !text.contains(" cpu ") && !text.contains(" ram "), "{text}"); + assert!(text.contains("prefill - tok/s")); + } +} + diff --git a/crates/deploy/src/steps.rs b/crates/deploy/src/steps.rs index d38424f8..6839c2df 100644 --- a/crates/deploy/src/steps.rs +++ b/crates/deploy/src/steps.rs @@ -273,6 +273,17 @@ pub async fn probe_ready_at(paths: &Paths, api: &str) -> bool { matches!(http::get(address, "/ready", Some(key.trim_end()), Duration::from_secs(3)).await, Ok(r) if r.status == 200) } +/// `GET /v1/status` with the key of `paths`: the gateway's status document (`machine` carries the engine telemetry). +pub async fn fetch_status(paths: &Paths, api: &str) -> Option { + let key = std::fs::read_to_string(paths.api_key()).ok()?; + let address = crate::config::probe_address(api)?; + let response = http::get(address, "/v1/status", Some(key.trim_end()), Duration::from_secs(3)).await.ok()?; + if response.status != 200 { + return None; + } + serde_json::from_str(&response.body).ok() +} + pub fn unit_text(ctx: &Context, scope: UnitScopeTag) -> Result<(PathBuf, String), String> { let home = std::env::var_os("HOME").map(PathBuf::from); let text = units::render( diff --git a/crates/leleka-memory/src/lib.rs b/crates/leleka-memory/src/lib.rs index 380571d2..fe4adbd0 100644 --- a/crates/leleka-memory/src/lib.rs +++ b/crates/leleka-memory/src/lib.rs @@ -1,23 +1,24 @@ -//! Memory safety for the Leleka runtime: an allocation inventory, a startup budget that refuses what cannot fit and -//! sizes the caches from what is left, a runtime pressure monitor that sheds load in a fixed order instead of letting the -//! OOM killer or a swap storm decide, a residency guard for the sealed KAR memfd, and the census used by the soak tests. -//! -//! Model-free and CUDA-free by design: the runtime feeds it numbers (what it will allocate, what the device reports) and -//! acts on its decisions (evict, refuse, lock). See `docs/memory-safety.md`. - -pub mod census; -pub mod governor; -pub mod heap; -pub mod host; -pub mod inventory; -pub mod ledger; -pub mod lock; -pub mod plan; -pub mod pressure; -pub mod procfs; - -pub use governor::{Admission, Governor, GovernorConfig, LockReport, Refuse, RequestShape, SamplerGuard, ShedDirective, published_report}; -pub use host::{FakeProc, HostFacts, ProcSource, RealProc}; -pub use inventory::{Entry, Inventory, Space, When}; -pub use plan::{CacheWish, FixedItem, GIB, KarForm, MIB, Plan, PlanInput, Policy, Refusal, VramFacts, VramPlan, check_vram}; -pub use pressure::Level; +//! Memory safety for the Leleka runtime: an allocation inventory, a startup budget that refuses what cannot fit and +//! sizes the caches from what is left, a runtime pressure monitor that sheds load in a fixed order instead of letting the +//! OOM killer or a swap storm decide, a residency guard for the sealed KAR memfd, and the census used by the soak tests. +//! +//! Model-free and CUDA-free by design: the runtime feeds it numbers (what it will allocate, what the device reports) and +//! acts on its decisions (evict, refuse, lock). See `docs/memory-safety.md`. + +pub mod census; +pub mod governor; +pub mod heap; +pub mod host; +pub mod inventory; +pub mod ledger; +pub mod lock; +pub mod plan; +pub mod pressure; +pub mod procfs; +pub mod telemetry; + +pub use governor::{Admission, Governor, GovernorConfig, LockReport, Refuse, RequestShape, SamplerGuard, ShedDirective, published_report}; +pub use host::{FakeProc, HostFacts, ProcSource, RealProc}; +pub use inventory::{Entry, Inventory, Space, When}; +pub use plan::{CacheWish, FixedItem, GIB, KarForm, MIB, Plan, PlanInput, Policy, Refusal, VramFacts, VramPlan, check_vram}; +pub use pressure::Level; diff --git a/crates/leleka-memory/src/telemetry.rs b/crates/leleka-memory/src/telemetry.rs new file mode 100644 index 00000000..46267e05 --- /dev/null +++ b/crates/leleka-memory/src/telemetry.rs @@ -0,0 +1,498 @@ +//! Runtime telemetry: what the operator watches while the engine serves. GPU load and VRAM (through a probe the +//! runtime supplies), host RAM and the process footprint, CPU cores in use, prefill and decode throughput, prefix-cache +//! hits and the context in use. Rendered as one JSON document (`published_telemetry`) that rides the runtime snapshot +//! (`Snapshot.telemetry_json`) to the gateway, `/v1/status` and `leleka status`. +//! +//! The serve loop calls the `record_*` functions (a mutex-guarded struct, no allocation); one sampler thread reads +//! `/proc` once a second and publishes. Everything that parses or computes is a pure function over fixtures. +use crate::{ + host::{ProcSource, RealProc}, + procfs, +}; +use serde::Serialize; +use std::{ + sync::{ + Arc, Mutex, MutexGuard, + atomic::{AtomicBool, Ordering}, + }, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, +}; + +/// Linux reports process CPU time in clock ticks of `USER_HZ`, which is 100 on every supported architecture. +const USER_HZ: f64 = 100.0; +/// Weight of the newest request in the running average of the throughput. +const EMA_ALPHA: f64 = 0.3; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)] +pub struct GpuSample { + pub index: u32, + /// Percent of the last sample period in which any kernel ran (NVML `utilization.gpu`). + pub util_pct: u32, + /// Percent of the period the memory interface was reading or writing (NVML `utilization.memory`). + pub mem_util_pct: u32, + pub vram_used_mib: u64, + pub vram_total_mib: u64, + pub power_w: Option, + pub sm_clock_mhz: Option, +} + +type GpuProbe = Box Option + Send + Sync>; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Phase { + #[default] + Idle, + Prefill, + Decode, +} + +#[derive(Debug, Default)] +struct State { + phase: Phase, + started: Option, + first_token: Option, + produced_now: u64, + /// Lifetime counters. + requests: u64, + cache_hit_requests: u64, + prompt_tokens: u64, + reused_tokens: u64, + produced_tokens: u64, + prefill_tokens: u64, + prefill_ms: f64, + decode_tokens: u64, + decode_ms: f64, + /// Last finished request. + last_prompt_tokens: u64, + last_reused_tokens: u64, + last_prefill_tok_s: Option, + last_decode_tok_s: Option, + prefill_ema: Option, + decode_ema: Option, + context_live: u64, + context_max: u64, +} + +static STATE: Mutex> = Mutex::new(None); +static PUBLISHED: Mutex> = Mutex::new(None); + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|p| p.into_inner()) +} + +fn with_state(f: impl FnOnce(&mut State)) { + f(lock(&STATE).get_or_insert_with(State::default)); +} + +/// The last document the sampler published (JSON text). +pub fn published_telemetry() -> Option { + lock(&PUBLISHED).clone() +} + +/// The context window the engine serves (tokens); constant for a loaded model. +pub fn set_context_max(tokens: u64) { + with_state(|s| s.context_max = tokens); +} + +/// A request entered the engine: `prompt_tokens` to prefill, of which the cache supplies `reused_tokens`. +pub fn request_started(prompt_tokens: u64, reused_tokens: u64) { + with_state(|s| { + s.phase = Phase::Prefill; + s.started = Some(Instant::now()); + s.first_token = None; + s.produced_now = 0; + s.context_live = prompt_tokens; + s.last_prompt_tokens = prompt_tokens; + s.last_reused_tokens = reused_tokens; + }); +} + +/// Tokens were delivered: the first delivery ends the prefill phase. +pub fn tokens_delivered(count: u64) { + with_state(|s| { + if s.first_token.is_none() { + s.first_token = Some(Instant::now()); + s.phase = Phase::Decode; + } + s.produced_now += count; + s.context_live += count; + }); +} + +/// A request ended without numbers worth folding in (cancelled or failed): the engine is idle again. +pub fn request_aborted() { + with_state(|s| { + s.phase = Phase::Idle; + s.started = None; + s.first_token = None; + }); +} + +/// A request finished (any outcome that produced numbers): fold it into the lifetime figures. +pub fn request_finished(prompt_tokens: u64, reused_tokens: u64, produced: u64, prompt_ms: f64, decode_ms: f64) { + with_state(|s| { + s.phase = Phase::Idle; + s.started = None; + s.first_token = None; + s.requests += 1; + s.prompt_tokens += prompt_tokens; + s.reused_tokens += reused_tokens; + s.produced_tokens += produced; + if reused_tokens > 0 { + s.cache_hit_requests += 1; + } + s.last_prompt_tokens = prompt_tokens; + s.last_reused_tokens = reused_tokens; + s.context_live = prompt_tokens + produced; + let prefilled = prompt_tokens.saturating_sub(reused_tokens); + if prefilled > 0 && prompt_ms > 0.0 { + let rate = prefilled as f64 * 1e3 / prompt_ms; + s.prefill_tokens += prefilled; + s.prefill_ms += prompt_ms; + s.last_prefill_tok_s = Some(rate); + s.prefill_ema = Some(ema(s.prefill_ema, rate)); + } + if produced > 0 && decode_ms > 0.0 { + let rate = produced as f64 * 1e3 / decode_ms; + s.decode_tokens += produced; + s.decode_ms += decode_ms; + s.last_decode_tok_s = Some(rate); + s.decode_ema = Some(ema(s.decode_ema, rate)); + } + }); +} + +fn ema(previous: Option, value: f64) -> f64 { + previous.map_or(value, |p| p + EMA_ALPHA * (value - p)) +} + +fn round1(value: f64) -> f64 { + (value * 10.0).round() / 10.0 +} + +/// Process and system CPU time read at one instant. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct CpuReading { + /// utime + stime of this process, in clock ticks. + pub process_ticks: u64, + /// Sum of all non-idle and all system ticks (`/proc/stat` first line). + pub system_busy: u64, + pub system_total: u64, +} + +/// `/proc/self/stat`: utime and stime are fields 14 and 15 (counted after the parenthesised command name). +pub fn parse_self_stat_ticks(text: &str) -> Option { + let rest = text.rsplit_once(')')?.1; + let fields: Vec<&str> = rest.split_ascii_whitespace().collect(); + // after ")" the fields start at 3 (state); utime is 14, stime 15 + let utime: u64 = fields.get(11)?.parse().ok()?; + let stime: u64 = fields.get(12)?.parse().ok()?; + Some(utime + stime) +} + +/// `/proc/stat` first line: (busy, total) ticks over all CPUs. +pub fn parse_stat_cpu(text: &str) -> Option<(u64, u64)> { + let line = text.lines().next()?; + let mut parts = line.split_ascii_whitespace(); + if parts.next()? != "cpu" { + return None; + } + let values: Vec = parts.filter_map(|v| v.parse().ok()).collect(); + if values.len() < 4 { + return None; + } + let idle = values[3] + values.get(4).copied().unwrap_or(0); + let total: u64 = values.iter().take(8).sum(); + Some((total.saturating_sub(idle), total)) +} + +pub fn read_cpu(src: &dyn ProcSource) -> Option { + let process_ticks = parse_self_stat_ticks(&src.read("/proc/self/stat").ok()?)?; + let (system_busy, system_total) = parse_stat_cpu(&src.read("/proc/stat").ok()?)?; + Some(CpuReading { process_ticks, system_busy, system_total }) +} + +/// Cores worth of CPU this process used between two readings, and the whole system's busy percentage. +pub fn cpu_usage(before: &CpuReading, after: &CpuReading, wall: Duration) -> (f64, f64) { + let seconds = wall.as_secs_f64().max(1e-6); + let process = after.process_ticks.saturating_sub(before.process_ticks) as f64 / USER_HZ / seconds; + let total = after.system_total.saturating_sub(before.system_total); + let busy = after.system_busy.saturating_sub(before.system_busy); + let system = if total == 0 { 0.0 } else { 100.0 * busy as f64 / total as f64 }; + (process, system) +} + +#[derive(Debug, Serialize)] +struct Ram { + total_mib: u64, + available_mib: u64, + process_rss_mib: u64, + process_pinned_mib: u64, + swap_used_mib: u64, +} + +#[derive(Debug, Serialize)] +struct Cpu { + cores: u32, + process_busy_cores: f64, + system_busy_pct: f64, +} + +#[derive(Debug, Serialize)] +struct Rates { + prefill_tok_s_last: Option, + prefill_tok_s_avg: Option, + prefill_tok_s_lifetime: Option, + decode_tok_s_last: Option, + decode_tok_s_avg: Option, + decode_tok_s_lifetime: Option, + /// While a request is decoding: tokens delivered so far over the time since its first token. + decode_tok_s_live: Option, +} + +#[derive(Debug, Serialize)] +struct Cache { + requests: u64, + hit_requests: u64, + hit_ratio: Option, + prompt_tokens: u64, + reused_tokens: u64, + token_hit_ratio: Option, + last_prompt_tokens: u64, + last_reused_tokens: u64, +} + +#[derive(Debug, Serialize)] +struct Context { + live_tokens: u64, + max_tokens: u64, + used_pct: Option, +} + +#[derive(Debug, Serialize)] +struct Document { + version: u32, + ts_ms: u64, + uptime_s: u64, + phase: Phase, + gpu: Option, + ram: Option, + cpu: Option, + throughput: Rates, + cache: Cache, + context: Context, +} + +fn ratio(part: u64, whole: u64) -> Option { + (whole > 0).then(|| (part as f64 / whole as f64 * 1e4).round() / 1e4) +} + +fn lifetime_rate(tokens: u64, ms: f64) -> Option { + (ms > 0.0).then(|| round1(tokens as f64 * 1e3 / ms)) +} + +/// Everything the sampler measured this tick. +pub struct Measured { + pub now_ms: u64, + pub uptime_s: u64, + pub gpu: Option, + pub meminfo: procfs::MemInfo, + pub status: procfs::ProcStatus, + pub cores: u32, + pub cpu: Option<(f64, f64)>, +} + +fn render(state: &State, measured: &Measured) -> String { + let mib = |bytes: Option| bytes.map_or(0, |b| b >> 20); + let ram = measured.meminfo.mem_total.map(|total| Ram { + total_mib: total >> 20, + available_mib: mib(measured.meminfo.mem_available), + process_rss_mib: mib(measured.status.vm_rss), + process_pinned_mib: mib(measured.status.vm_pin), + swap_used_mib: measured.meminfo.swap_total.unwrap_or(0).saturating_sub(measured.meminfo.swap_free.unwrap_or(0)) >> 20, + }); + let live_rate = match (state.phase, state.first_token) { + (Phase::Decode, Some(first)) if state.produced_now > 1 => { + let secs = first.elapsed().as_secs_f64(); + (secs > 0.05).then(|| round1(state.produced_now as f64 / secs)) + } + _ => None, + }; + let document = Document { + version: 1, + ts_ms: measured.now_ms, + uptime_s: measured.uptime_s, + phase: state.phase, + gpu: measured.gpu, + ram, + cpu: measured.cpu.map(|(process, system)| Cpu { + cores: measured.cores, + process_busy_cores: round1(process), + system_busy_pct: round1(system), + }), + throughput: Rates { + prefill_tok_s_last: state.last_prefill_tok_s.map(round1), + prefill_tok_s_avg: state.prefill_ema.map(round1), + prefill_tok_s_lifetime: lifetime_rate(state.prefill_tokens, state.prefill_ms), + decode_tok_s_last: state.last_decode_tok_s.map(round1), + decode_tok_s_avg: state.decode_ema.map(round1), + decode_tok_s_lifetime: lifetime_rate(state.decode_tokens, state.decode_ms), + decode_tok_s_live: live_rate, + }, + cache: Cache { + requests: state.requests, + hit_requests: state.cache_hit_requests, + hit_ratio: ratio(state.cache_hit_requests, state.requests), + prompt_tokens: state.prompt_tokens, + reused_tokens: state.reused_tokens, + token_hit_ratio: ratio(state.reused_tokens, state.prompt_tokens), + last_prompt_tokens: state.last_prompt_tokens, + last_reused_tokens: state.last_reused_tokens, + }, + context: Context { + live_tokens: state.context_live, + max_tokens: state.context_max, + used_pct: ratio(state.context_live, state.context_max).map(|r| (r * 1e4).round() / 1e2), + }, + }; + serde_json::to_string(&document).unwrap_or_default() +} + +/// Render the current document from the recorded state and one measurement (public for tests and for a one-shot read). +pub fn render_now(measured: &Measured) -> String { + let guard = lock(&STATE); + match guard.as_ref() { + Some(state) => render(state, measured), + None => render(&State::default(), measured), + } +} + +pub struct Sampler { + stop: Arc, +} + +impl Sampler { + pub fn stop(&self) { + self.stop.store(true, Ordering::Release); + } +} + +impl Drop for Sampler { + fn drop(&mut self) { + self.stop(); + } +} + +/// Start the once-a-second sampler over the real `/proc`. `gpu_probe` reads the device (NVML); `None` reports no GPU block. +pub fn start(gpu_probe: Option, period: Duration) -> Sampler { + let stop = Arc::new(AtomicBool::new(false)); + let flag = stop.clone(); + let spawned = std::thread::Builder::new().name("leleka-telemetry".into()).spawn(move || { + let src = RealProc; + let began = Instant::now(); + let cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32); + let mut previous = read_cpu(&src).map(|reading| (reading, Instant::now())); + while !flag.load(Ordering::Acquire) { + std::thread::sleep(period); + let now = Instant::now(); + let reading = read_cpu(&src); + let cpu = match (&previous, &reading) { + (Some((before, at)), Some(after)) => Some(cpu_usage(before, after, now.duration_since(*at))), + _ => None, + }; + if let Some(reading) = reading { + previous = Some((reading, now)); + } + let measured = Measured { + now_ms: SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64), + uptime_s: began.elapsed().as_secs(), + gpu: gpu_probe.as_ref().and_then(|probe| probe()), + meminfo: procfs::parse_meminfo(&src.read("/proc/meminfo").unwrap_or_default()), + status: procfs::parse_status(&src.read("/proc/self/status").unwrap_or_default()), + cores, + cpu, + }; + let text = render_now(&measured); + *lock(&PUBLISHED) = Some(text); + } + }); + if spawned.is_err() { + stop.store(true, Ordering::Release); + } + Sampler { stop } +} + +#[cfg(test)] +mod tests { + use super::*; + + static SERIAL: Mutex<()> = Mutex::new(()); + + fn measured() -> Measured { + Measured { + now_ms: 1, + uptime_s: 5, + gpu: Some(GpuSample { index: 0, util_pct: 91, mem_util_pct: 40, vram_used_mib: 30000, vram_total_mib: 32607, power_w: Some(480.0), sm_clock_mhz: Some(2900) }), + meminfo: procfs::parse_meminfo("MemTotal: 125829120 kB\nMemAvailable: 70000000 kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n"), + status: procfs::parse_status("VmRSS:\t55000000 kB\nVmPin:\t3000000 kB\n"), + cores: 32, + cpu: Some((7.4, 31.0)), + } + } + + #[test] + fn self_stat_survives_a_command_name_with_spaces_and_parentheses() { + let line = "123 (a b) c) S 1 2 3 4 5 6 7 8 9 10 250 50 0 0 20 0 1 0"; + assert_eq!(parse_self_stat_ticks(line), Some(300)); + assert_eq!(parse_self_stat_ticks("garbage"), None); + } + + #[test] + fn system_cpu_counts_idle_and_iowait_as_not_busy() { + let (busy, total) = parse_stat_cpu("cpu 100 0 50 800 50 0 0 0 0 0\ncpu0 1 2 3 4\n").unwrap(); + assert_eq!((busy, total), (150, 1000)); + let before = CpuReading { process_ticks: 1000, system_busy: 0, system_total: 0 }; + let after = CpuReading { process_ticks: 1740, system_busy: 150, system_total: 1000 }; + let (process, system) = cpu_usage(&before, &after, Duration::from_secs(1)); + assert!((process - 7.4).abs() < 1e-9 && (system - 15.0).abs() < 1e-9, "{process} {system}"); + } + + #[test] + fn requests_fold_into_rates_cache_and_context() { + let _serial = lock(&SERIAL); + *lock(&STATE) = None; + set_context_max(262_144); + request_started(100_000, 80_000); + tokens_delivered(4); + request_finished(100_000, 80_000, 400, 4_000.0, 4_000.0); + request_started(101_000, 0); + request_finished(101_000, 0, 200, 20_000.0, 2_000.0); + let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); + assert_eq!(doc["phase"], "idle"); + assert_eq!(doc["cache"]["requests"], 2); + assert_eq!(doc["cache"]["hit_requests"], 1); + assert_eq!(doc["cache"]["hit_ratio"], 0.5); + // 100000+101000 prompt tokens, 80000 reused + assert_eq!(doc["cache"]["token_hit_ratio"], 0.398); + // prefill: 20000 tokens in 4000 ms = 5000/s, then 101000 in 20000 ms = 5050/s + assert_eq!(doc["throughput"]["prefill_tok_s_last"], 5050.0); + assert_eq!(doc["throughput"]["decode_tok_s_last"], 100.0); + assert_eq!(doc["throughput"]["decode_tok_s_lifetime"], 100.0); + assert_eq!(doc["context"]["live_tokens"], 101_200); + assert_eq!(doc["context"]["max_tokens"], 262_144); + assert_eq!(doc["gpu"]["util_pct"], 91); + assert_eq!(doc["ram"]["total_mib"], 122_880); + assert_eq!(doc["cpu"]["process_busy_cores"], 7.4); + } + + #[test] + fn an_empty_state_renders_nulls_not_zeros_for_unmeasured_rates() { + let _serial = lock(&SERIAL); + *lock(&STATE) = None; + let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); + assert!(doc["throughput"]["decode_tok_s_last"].is_null()); + assert!(doc["cache"]["hit_ratio"].is_null()); + assert!(doc["context"]["used_pct"].is_null()); + } +} diff --git a/crates/leleka-runtime/src/backend.rs b/crates/leleka-runtime/src/backend.rs index 282cf7ba..1d8b5540 100644 --- a/crates/leleka-runtime/src/backend.rs +++ b/crates/leleka-runtime/src/backend.rs @@ -845,6 +845,12 @@ impl Backend for Proxy { } leleka_memory::published_report() } + fn telemetry_report(&self) -> Option { + if self.shared.shutdown.load(Ordering::Acquire) { + return None; + } + leleka_memory::telemetry::published_telemetry() + } fn load( &mut self, model: ModelDescriptor, @@ -1435,6 +1441,7 @@ fn serve_load( } let driver = Driver::load() .map_err(|_| load_failure(LoadPhase::Driver, unavailable("CUDA driver unavailable")))?; + GPU_ORDINAL.store(config.gpu_device_ordinal, Ordering::Relaxed); let device = driver .device(config.gpu_device_ordinal as i32) .map_err(|_| load_failure(LoadPhase::Device, unavailable("CUDA device unavailable")))?; @@ -2500,6 +2507,9 @@ fn validate_request(request: &GenerationRequest) -> Result<(), BackendError> { /// Validated sampling plan of a request: `None` keeps the ordinary greedy path /// (temperature 0 and no penalty), `Some` carries the Original `SamplerParams` for /// the host sampler. `entropy` seeds requests that carry no seed (Original `seed = 0`). +/// The CUDA ordinal of the loaded device, for the telemetry sampler (NVML indexes the same physical order). +pub(crate) static GPU_ORDINAL: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + fn request_sampler( request: &GenerationRequest, entropy: u64, diff --git a/crates/leleka-runtime/src/backend_original_serve.rs b/crates/leleka-runtime/src/backend_original_serve.rs index 2f4bf7cf..fa27e5cf 100644 --- a/crates/leleka-runtime/src/backend_original_serve.rs +++ b/crates/leleka-runtime/src/backend_original_serve.rs @@ -461,9 +461,11 @@ mod runner { let mut captured: Option = None; let mut timed_out = false; let mut generated_ids: Vec = Vec::new(); + leleka_memory::telemetry::request_started(prompt.len() as u64, 0); let result = { let mut emit = |tokens: &[i32]| -> Result<(), ForwardError> { generated_ids.extend_from_slice(tokens); + leleka_memory::telemetry::tokens_delivered(tokens.len() as u64); let mut deliver = |token: i32| -> Result<(), GenerationFailure> { count += 1; if stop_tokens.contains(&token) { @@ -496,21 +498,31 @@ mod runner { stack.serve(&serve_request, &mut emit, &mut cancel_probe) }; if let Some(failure) = captured.take() { + leleka_memory::telemetry::request_aborted(); return Err(failure); } if timed_out { + leleka_memory::telemetry::request_aborted(); return Err(unavailable("generation deadline exceeded").into()); } let outcome = match result { Ok(outcome) => outcome, - Err(ServeError::Cancelled) => return Err(GenerationFailure::Cancelled), - Err(ServeError::Refused(admission)) => return Err(admission_error(admission).into()), + Err(ServeError::Cancelled) => { + leleka_memory::telemetry::request_aborted(); + return Err(GenerationFailure::Cancelled); + } + Err(ServeError::Refused(admission)) => { + leleka_memory::telemetry::request_aborted(); + return Err(admission_error(admission).into()); + } Err(ServeError::Failed(error)) => { + leleka_memory::telemetry::request_aborted(); use std::io::Write; let _ = writeln!(std::io::stderr().lock(), "leleka-serve request failed: class={error:?}"); return Err(unavailable("Original serve request failed").into()); } Err(ServeError::Broken(error)) => { + leleka_memory::telemetry::request_aborted(); use std::io::Write; let _ = writeln!(std::io::stderr().lock(), "leleka-serve stack lost an owner: class={error:?}"); return Err(unavailable("Original serve stack lost a physical owner").into()); @@ -533,6 +545,8 @@ mod runner { output_tokens: count, reused_input_tokens: stack.reused_tokens() as u64, }; + let (prompt_ms, decode_ms) = stack.last_timing(); + leleka_memory::telemetry::request_finished(usage.input_tokens, usage.reused_input_tokens, usage.output_tokens, prompt_ms, decode_ms); emit_event(sink, &cancelled, GenerationEvent::Usage(usage.clone()))?; { use std::io::Write; @@ -597,6 +611,24 @@ mod runner { })?; publish_prefix_summary(&stack, shared); crate::load_clock::lap("serve_stack_open_total"); + // operator telemetry: GPU/RAM/CPU once a second, throughput and cache hits recorded per request + leleka_memory::telemetry::set_context_max(u64::from(context_tokens)); + let _telemetry = leleka_memory::telemetry::start( + leleka_cuda_driver::nvml::Nvml::open(crate::backend::GPU_ORDINAL.load(Ordering::Relaxed)).map(|nvml| { + Box::new(move || { + nvml.sample().map(|s| leleka_memory::telemetry::GpuSample { + index: s.index, + util_pct: s.util_pct, + mem_util_pct: s.mem_util_pct, + vram_used_mib: s.vram_used_mib, + vram_total_mib: s.vram_total_mib, + power_w: s.power_w, + sm_clock_mhz: s.sm_clock_mhz, + }) + }) as Box Option + Send + Sync> + }), + Duration::from_secs(1), + ); let mut stack = Some(stack); if shared.shutdown.load(Ordering::Acquire) { if let Some(stack) = stack.take() { diff --git a/crates/runtime-client/proto/runtime.proto b/crates/runtime-client/proto/runtime.proto index 7c1267a6..e766e19c 100644 --- a/crates/runtime-client/proto/runtime.proto +++ b/crates/runtime-client/proto/runtime.proto @@ -59,6 +59,8 @@ message Snapshot { string prefix_cache_json = 11; // JSON report of the runtime's memory governor (docs/memory-safety.md): pressure level, Retry-After, plan, inventory, counters. Empty when it has none. string memory_json = 12; + // JSON telemetry of the runtime for the operator (leleka-memory telemetry): GPU load and VRAM, host RAM, CPU cores in use, prefill and decode tokens/s, prefix-cache hits, context in use. Empty when it has none. + string telemetry_json = 13; } message LoadRequest { string operation_id = 1; string expected_epoch = 2; ModelDescriptor model = 3; LoadConfig config = 4; } message UnloadRequest { string operation_id = 1; string expected_epoch = 2; string handle = 3; } diff --git a/crates/runtime-client/src/backend.rs b/crates/runtime-client/src/backend.rs index ec04cadd..4a06997b 100644 --- a/crates/runtime-client/src/backend.rs +++ b/crates/runtime-client/src/backend.rs @@ -38,6 +38,8 @@ pub struct GrpcBackend { prefix_summary: Mutex>, /// The runtime's memory-governor report from the last probe (`Backend::memory_report`). memory_report: Mutex>, + /// The runtime's telemetry document from the last probe (`Backend::telemetry_report`). + telemetry_report: Mutex>, } #[derive(Clone)] @@ -96,6 +98,7 @@ impl GrpcBackend { active: Arc::new(Mutex::new(None)), prefix_summary: Mutex::new(None), memory_report: Mutex::new(None), + telemetry_report: Mutex::new(None), } } @@ -149,6 +152,9 @@ impl api::Backend for GrpcBackend { // memory pressure matters before and without a loaded model: no epoch/ready condition, only a non-empty report *cell = probe.as_ref().filter(|snapshot| !snapshot.memory_json.is_empty()).map(|snapshot| snapshot.memory_json.clone()); } + if let Ok(mut cell) = self.telemetry_report.lock() { + *cell = probe.as_ref().filter(|snapshot| !snapshot.telemetry_json.is_empty()).map(|snapshot| snapshot.telemetry_json.clone()); + } if let Ok(mut cell) = self.prefix_summary.lock() { *cell = probe .as_ref() @@ -189,6 +195,11 @@ impl api::Backend for GrpcBackend { self.memory_report.lock().ok().and_then(|cell| cell.clone()) } + /// The runtime's telemetry document as of the last `capabilities` probe; `None` when unreachable or it has none. + fn telemetry_report(&self) -> Option { + self.telemetry_report.lock().ok().and_then(|cell| cell.clone()) + } + fn load( &mut self, model: api::ModelDescriptor, diff --git a/crates/runtime-client/src/client.rs b/crates/runtime-client/src/client.rs index 41780a8e..cc101d1e 100644 --- a/crates/runtime-client/src/client.rs +++ b/crates/runtime-client/src/client.rs @@ -348,6 +348,7 @@ mod tests { active_request_id: String::new(), prefix_cache_json: String::new(), memory_json: String::new(), + telemetry_json: String::new(), }; assert!(validate_snapshot(&snapshot).is_ok()); snapshot @@ -387,6 +388,7 @@ mod tests { active_request_id: String::new(), prefix_cache_json: String::new(), memory_json: String::new(), + telemetry_json: String::new(), } } } diff --git a/crates/runtime-client/tests/grpc_backend.rs b/crates/runtime-client/tests/grpc_backend.rs index ca86510b..ff4c04b5 100644 --- a/crates/runtime-client/tests/grpc_backend.rs +++ b/crates/runtime-client/tests/grpc_backend.rs @@ -117,6 +117,7 @@ impl Fake { active_request_id: String::new(), prefix_cache_json: String::new(), memory_json: String::new(), + telemetry_json: String::new(), } } diff --git a/desktop-core/src/runtime_rpc.rs b/desktop-core/src/runtime_rpc.rs index 5396dc6e..b94b2e65 100644 --- a/desktop-core/src/runtime_rpc.rs +++ b/desktop-core/src/runtime_rpc.rs @@ -57,6 +57,8 @@ struct State { prefix_cache_json: String, /// The backend's memory-governor report as of the last observation (`Backend::memory_report`). memory_json: String, + /// The backend's telemetry document as of the last observation (`Backend::telemetry_report`). + telemetry_json: String, } struct Operation { digest: [u8; 32], @@ -137,6 +139,7 @@ fn snapshot(state: &State) -> proto::Snapshot { active_request_id: state.active.clone().unwrap_or_default(), prefix_cache_json: if state.stopping { String::new() } else { state.prefix_cache_json.clone() }, memory_json: if state.stopping { String::new() } else { state.memory_json.clone() }, + telemetry_json: if state.stopping { String::new() } else { state.telemetry_json.clone() }, } } fn publish(inner: &Inner, state: &mut State) { @@ -175,6 +178,7 @@ impl RuntimeServer { stopping: false, prefix_cache_json: String::new(), memory_json: String::new(), + telemetry_json: String::new(), }), changes, controls: Arc::new(Semaphore::new(16)), @@ -746,15 +750,16 @@ fn close_admission(inner: &Inner) { } fn refresh_capabilities(inner: &Inner) { // Observations must not wait behind a load/acceptance acknowledgement. - let (capabilities, summary, memory) = match inner.backend.try_lock() { - Ok(backend) => (backend.capabilities(), backend.prefix_cache_summary(), backend.memory_report()), + let (capabilities, summary, memory, telemetry) = match inner.backend.try_lock() { + Ok(backend) => (backend.capabilities(), backend.prefix_cache_summary(), backend.memory_report(), backend.telemetry_report()), Err(std::sync::TryLockError::WouldBlock) => return, - Err(std::sync::TryLockError::Poisoned(_)) => (api::BackendCapabilities::default(), None, None), + Err(std::sync::TryLockError::Poisoned(_)) => (api::BackendCapabilities::default(), None, None, None), }; if let Ok(mut state) = inner.state.lock() { // the summary changes with every request; watchers are told about it only through a snapshot they ask for state.prefix_cache_json = summary.unwrap_or_default(); state.memory_json = memory.unwrap_or_default(); + state.telemetry_json = telemetry.unwrap_or_default(); let capabilities = if state.loaded.is_some() { capabilities } else {