diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index ac9fb480..7e62f476 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -1,3420 +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; -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; +//! 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/deploy/src/cli.rs b/crates/deploy/src/cli.rs index 9e1db091..05967e2f 100644 --- a/crates/deploy/src/cli.rs +++ b/crates/deploy/src/cli.rs @@ -1,528 +1,528 @@ -//! Command-line parsing for `leleka`. No framework: a flag table per command, `--flag value` or `--flag=value`. -use crate::{config::Ports, layout::Dirs}; -use std::{collections::BTreeMap, path::PathBuf}; - -pub const USAGE: &str = "\ -leleka - one-command deployment of the Leleka runtime - -USAGE - leleka up [OPTIONS] preflight, fetch+verify the model, build the KAR archive, install, start, wait for ready - leleka preflight [OPTIONS] only the host checks (exit 1 when one fails) - leleka run --config FILE the foreground supervisor that systemd starts (engine + gateway + API) - leleka status [OPTIONS] service state and readiness - leleka down [OPTIONS] stop the systemd service - leleka verify [OPTIONS] hash both shards and the archive in full (in parallel), check the pinned digests, renew the - verification stamps that let a restart skip the hashing (needs a prepared state) - leleka profiles [show NAME] list the memory profiles, or print one as JSON - leleka version - -UP / PREFLIGHT OPTIONS - --dry-run print the plan and the preflight, change nothing - --json machine-readable plan / summary on stdout - --profile auto|NAME|FILE memory profile (default auto: chosen from the GPU) - --gpu N CUDA device ordinal (default 0) - --assets DIR model volume: shards, KAR archive, MTP pack, tokenizer [$LELEKA_ASSETS] - --state-dir DIR configs, tokens, logs, status [$LELEKA_STATE] - --prefix DIR install prefix (bin/, lib/cublas/) [$LELEKA_PREFIX] - --bin-src DIR where to take the six binaries from (default: the directory of this binary) - --mode auto|system|user|foreground|none - --foreground same as --mode foreground (WSL without systemd, containers, terminals) - --api-port N API port (default 8081) - --api-bind IP API listen address (default 127.0.0.1; 0.0.0.0 only inside a container whose port - is published to 127.0.0.1 or tunnelled; the key is the only protection, no TLS) - --engine-port N engine gRPC port (default 18766) - --daemon-port N gateway port (default 18080) - --preset dedicated|workstation dedicated (default) takes the whole host; workstation leaves cores, RAM and VRAM - for Docker, agents and the IDE (env LELEKA_PRESET) - --gpu-budget-gib N override the profile's GPU memory budget - --context-tokens N override the profile's context ceiling - --no-fetch never download or build; require the model files to exist - --reverify ignore the verification stamps and hash everything again - --trust-archive accept an existing archive of the pinned length + its provenance file without the - strict re-derivation (hours-scale); the engine still checks its SHA-256 and every - CRC against the pinned digest at each load - --mtp-pack PATH import the MTP pack (directory or .tar/.tar.gz of data/mtp-rt) into the assets - --cublas-dir DIR use this CUDA 12 cuBLAS directory instead of searching / downloading - --no-install-cublas fail instead of downloading cuBLAS 12.9.1.4 - --timeout-s N wait this long for readiness (default 3600) - --kar-fd N an already sealed KAR memfd inherited from the parent process: not copied again, - its RAM is not required (foreground / --mode none only) - --service-user NAME system unit only: account the service runs as (default leleka, created if missing) - -ENVIRONMENT - HF_TOKEN optional Hugging Face token for the model download (sent only to huggingface.co) -"; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum ModeChoice { - Auto, - System, - User, - Foreground, - None, -} - -#[derive(Clone, Debug)] -pub struct UpOptions { - pub dry_run: bool, - pub json: bool, - pub profile: Option, - pub gpu: u32, - pub dirs: Dirs, - pub bin_src: Option, - pub mode: ModeChoice, - /// Resource preset (`--preset`, `LELEKA_PRESET`): how much of the host the engine may take. - pub preset: crate::resources::Preset, - pub ports: Ports, - pub gpu_budget_gib: Option, - pub context_tokens: Option, - pub fetch: bool, - pub reverify: bool, - /// Accept an existing archive of the pinned length without the strict F32 re-derivation. - pub trust_archive: bool, - pub mtp_pack: Option, - pub cublas_dir: Option, - pub install_cublas: bool, - pub timeout_s: u64, - /// System unit only: the account the service runs as (created when missing). Default `leleka`. - pub service_user: Option, - /// An already sealed archive descriptor inherited from the parent (foreground / prepare-only runs). - pub kar_fd: Option, -} - -#[derive(Debug)] -pub enum Command { - Up(UpOptions), - Preflight(UpOptions), - Run { - config: PathBuf, - kar_fd: Option, - }, - ExecInherit(Vec), - Status(UpOptions), - Down(UpOptions), - Verify(UpOptions), - Profiles(Option), - Version, - Help, -} - -type Flags = BTreeMap>; - -const UP_FLAGS: &[(&str, bool)] = &[ - ("--dry-run", false), - ("--json", false), - ("--profile", true), - ("--gpu", true), - ("--assets", true), - ("--state-dir", true), - ("--prefix", true), - ("--bin-src", true), - ("--mode", true), - ("--preset", true), - ("--foreground", false), - ("--api-port", true), - ("--api-bind", true), - ("--engine-port", true), - ("--daemon-port", true), - ("--gpu-budget-gib", true), - ("--context-tokens", true), - ("--no-fetch", false), - ("--reverify", false), - ("--trust-archive", false), - ("--mtp-pack", true), - ("--cublas-dir", true), - ("--no-install-cublas", false), - ("--timeout-s", true), - ("--service-user", true), - ("--kar-fd", true), -]; - -fn parse_flags(args: &[String], table: &[(&str, bool)]) -> Result { - let mut flags = Flags::new(); - let mut index = 0; - while index < args.len() { - let arg = &args[index]; - let (name, inline) = match arg.split_once('=') { - Some((name, value)) if name.starts_with("--") => (name, Some(value.to_owned())), - _ => (arg.as_str(), None), - }; - let Some((_, takes_value)) = table.iter().find(|(flag, _)| *flag == name) else { - return Err(format!("unknown option {name:?}; see `leleka --help`")); - }; - let value = if *takes_value { - match inline { - Some(value) => Some(value), - None => { - index += 1; - Some( - args.get(index) - .ok_or_else(|| format!("{name} needs a value"))? - .clone(), - ) - } - } - } else if inline.is_some() { - return Err(format!("{name} takes no value")); - } else { - None - }; - if flags.insert(name.to_owned(), value).is_some() { - return Err(format!("{name} given twice")); - } - index += 1; - } - Ok(flags) -} - -fn number(flags: &Flags, name: &str, default: T) -> Result { - match flags.get(name) { - None => Ok(default), - Some(value) => value - .as_deref() - .unwrap_or("") - .parse() - .map_err(|_| format!("{name} needs a number")), - } -} - -/// `--api-bind IP`: where the public API listens. Loopback unless asked; the engine and the gateway always -/// stay on loopback. A non-loopback bind is for containers (publish the port to 127.0.0.1 on the host). -fn api_bind(flags: &Flags) -> Result { - match text(flags, "--api-bind") { - None => Ok("127.0.0.1".into()), - Some(ip) => match ip.parse::() { - Ok(std::net::IpAddr::V4(v4)) => Ok(v4.to_string()), - Ok(std::net::IpAddr::V6(_)) => Err("--api-bind takes an IPv4 address".into()), - Err(_) => Err(format!("--api-bind needs an IP address, not {ip:?}")), - }, - } -} - -fn ranged( - flags: &Flags, - name: &str, - range: std::ops::RangeInclusive, -) -> Result, String> { - if !flags.contains_key(name) { - return Ok(None); - } - let value: T = number(flags, name, *range.start())?; - if !range.contains(&value) { - return Err(format!("{name} must be {}..{}", range.start(), range.end())); - } - Ok(Some(value)) -} - -fn text<'a>(flags: &'a Flags, name: &str) -> Option<&'a str> { - flags.get(name).and_then(|v| v.as_deref()) -} - -fn port(flags: &Flags, name: &str, default: u16) -> Result { - let value: u16 = number(flags, name, default)?; - if value < 1024 { - return Err(format!("{name} must be 1024..65535")); - } - Ok(value) -} - -/// Environment access is injected so that parsing is testable. -pub struct Environment<'a> { - pub root: bool, - pub home: Option, - pub var: &'a dyn Fn(&str) -> Option, -} - -fn up_options(args: &[String], env: &Environment) -> Result { - let flags = parse_flags(args, UP_FLAGS)?; - let defaults = Dirs::defaults(env.root, env.home.as_deref(), env.var); - let abs = |name: &str, fallback: PathBuf| -> Result { - let path = text(&flags, name).map(PathBuf::from).unwrap_or(fallback); - if !path.is_absolute() { - return Err(format!( - "{name} must be an absolute path (got {})", - path.display() - )); - } - Ok(path) - }; - let dirs = Dirs { - prefix: abs("--prefix", defaults.prefix)?, - state: abs("--state-dir", defaults.state)?, - assets: abs("--assets", defaults.assets)?, - }; - let mode = if flags.contains_key("--foreground") { - if flags.contains_key("--mode") { - return Err("use either --foreground or --mode".into()); - } - ModeChoice::Foreground - } else { - match text(&flags, "--mode").unwrap_or("auto") { - "auto" => ModeChoice::Auto, - "system" => ModeChoice::System, - "user" => ModeChoice::User, - "foreground" => ModeChoice::Foreground, - "none" => ModeChoice::None, - other => { - return Err(format!( - "--mode must be auto, system, user, foreground or none, not {other:?}" - )); - } - } - }; - let kar_fd = match flags.get("--kar-fd") { - None => None, - Some(_) => { - let fd: u32 = number(&flags, "--kar-fd", 0u32)?; - if !(3..=1_048_576).contains(&fd) { - return Err( - "--kar-fd must be an inherited descriptor number of 3 or higher".into(), - ); - } - if matches!(mode, ModeChoice::System | ModeChoice::User) { - return Err("--kar-fd belongs to a process that holds the descriptor; use it with --foreground or --mode none, not with a systemd unit".into()); - } - Some(fd) - } - }; - if mode == ModeChoice::System && !env.root { - return Err("--mode system needs root (use sudo), or --mode user / --foreground".into()); - } - let ports = Ports { - api: format!( - "{}:{}", - api_bind(&flags)?, - port(&flags, "--api-port", 8081)? - ), - engine: format!("127.0.0.1:{}", port(&flags, "--engine-port", 18766)?), - daemon: format!("127.0.0.1:{}", port(&flags, "--daemon-port", 18080)?), - }; - let distinct = [&ports.api, &ports.engine, &ports.daemon]; - if distinct[0] == distinct[1] || distinct[0] == distinct[2] || distinct[1] == distinct[2] { - return Err("the API, engine and gateway ports must differ".into()); - } - let cublas_dir = text(&flags, "--cublas-dir").map(PathBuf::from); - if let Some(dir) = &cublas_dir - && !dir.is_absolute() - { - return Err("--cublas-dir must be an absolute path".into()); - } - Ok(UpOptions { - dry_run: flags.contains_key("--dry-run"), - json: flags.contains_key("--json"), - profile: text(&flags, "--profile").map(str::to_owned), - gpu: number(&flags, "--gpu", 0u32)?, - dirs, - bin_src: text(&flags, "--bin-src").map(PathBuf::from), - mode, - preset: match text(&flags, "--preset") { - Some(value) => crate::resources::Preset::parse(value)?, - None => match (env.var)("LELEKA_PRESET") { - Some(value) if !value.is_empty() => crate::resources::Preset::parse(&value)?, - _ => crate::resources::Preset::Dedicated, - }, - }, - ports, - gpu_budget_gib: ranged(&flags, "--gpu-budget-gib", 1u64..=1024)?, - context_tokens: ranged(&flags, "--context-tokens", 1u32..=262_144)?, - service_user: text(&flags, "--service-user").map(str::to_owned), - kar_fd, - fetch: !flags.contains_key("--no-fetch"), - reverify: flags.contains_key("--reverify"), - trust_archive: flags.contains_key("--trust-archive"), - mtp_pack: text(&flags, "--mtp-pack").map(PathBuf::from), - cublas_dir, - install_cublas: !flags.contains_key("--no-install-cublas"), - timeout_s: { - let value: u64 = number(&flags, "--timeout-s", 3600)?; - if !(1..=86_400).contains(&value) { - return Err("--timeout-s must be 1..86400".into()); - } - value - }, - }) -} - -pub fn parse(args: &[String], env: &Environment) -> Result { - let Some((command, rest)) = args.split_first() else { - return Ok(Command::Help); - }; - match command.as_str() { - "-h" | "--help" | "help" => Ok(Command::Help), - "version" | "--version" | "-V" => Ok(Command::Version), - "up" => up_options(rest, env).map(Command::Up), - "preflight" => up_options(rest, env).map(Command::Preflight), - "status" => up_options(rest, env).map(Command::Status), - "down" => up_options(rest, env).map(Command::Down), - "verify" => up_options(rest, env).map(Command::Verify), - "profiles" => match rest { - [] => Ok(Command::Profiles(None)), - [show, name] if show == "show" => Ok(Command::Profiles(Some(name.clone()))), - _ => Err("usage: leleka profiles [show NAME]".into()), - }, - "run" => { - let flags = parse_flags(rest, &[("--config", true), ("--kar-fd", true)])?; - let config = text(&flags, "--config").ok_or("leleka run needs --config FILE")?; - Ok(Command::Run { - config: PathBuf::from(config), - kar_fd: flags - .get("--kar-fd") - .map(|_| number(&flags, "--kar-fd", 0u32)) - .transpose()?, - }) - } - "exec-inherit" => Ok(Command::ExecInherit(rest.to_vec())), - other => Err(format!("unknown command {other:?}; see `leleka --help`")), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn strings(items: &[&str]) -> Vec { - items.iter().map(|s| s.to_string()).collect() - } - - fn parse_as(root: bool, args: &[&str]) -> Result { - let var = |_: &str| None; - parse( - &strings(args), - &Environment { - root, - home: Some("/home/para".into()), - var: &var, - }, - ) - } - - #[test] - fn up_defaults_for_a_user() { - let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { - panic!() - }; - assert_eq!( - options.dirs.assets, - PathBuf::from("/home/para/.local/share/leleka/assets") - ); - assert_eq!(options.ports.api, "127.0.0.1:8081"); - assert!(options.fetch && options.install_cublas && !options.dry_run); - assert_eq!(options.mode, ModeChoice::Auto); - assert_eq!(options.timeout_s, 3600); - } - - #[test] - fn flags_accept_both_forms_and_reject_mistakes() { - let Command::Up(options) = parse_as( - false, - &[ - "up", - "--assets=/data/l", - "--gpu", - "1", - "--foreground", - "--dry-run", - "--json", - "--no-fetch", - "--api-port=9000", - ], - ) - .unwrap() else { - panic!() - }; - assert_eq!(options.dirs.assets, PathBuf::from("/data/l")); - assert_eq!( - ( - options.gpu, - options.mode, - options.dry_run, - options.json, - options.fetch - ), - (1, ModeChoice::Foreground, true, true, false) - ); - assert_eq!(options.ports.api, "127.0.0.1:9000"); - for bad in [ - &["up", "--nope"][..], - &["up", "--gpu"], - &["up", "--dry-run", "--dry-run"], - &["up", "--dry-run=1"], - &["up", "--assets", "relative/dir"], - &["up", "--api-port", "80"], - &["up", "--api-port", "9000", "--engine-port", "9000"], - &["up", "--mode", "weird"], - &["up", "--foreground", "--mode", "user"], - &["up", "--gpu-budget-gib", "0"], - &["up", "--context-tokens", "999999"], - &["up", "--timeout-s", "0"], - ] { - assert!(parse_as(false, bad).is_err(), "{bad:?} should fail"); - } - } - - #[test] - fn the_resource_preset_comes_from_the_flag_then_the_environment() { - use crate::resources::Preset; - let preset = |args: &[&str]| match parse_as(false, args) { - Ok(Command::Up(options)) => Ok(options.preset), - Ok(_) => unreachable!(), - Err(message) => Err(message), - }; - assert_eq!(preset(&["up"]), Ok(Preset::Dedicated)); - assert_eq!(preset(&["up", "--preset", "workstation"]), Ok(Preset::Workstation)); - assert!(preset(&["up", "--preset", "shared"]).unwrap_err().contains("unknown preset")); - } - - #[test] - fn api_bind_is_explicit_and_only_for_the_api() { - let Command::Up(options) = parse_as(false, &["up", "--api-bind", "0.0.0.0"]).unwrap() - else { - panic!() - }; - assert_eq!(options.ports.api, "0.0.0.0:8081"); - assert_eq!(options.ports.engine, "127.0.0.1:18766"); - assert!(parse_as(false, &["up", "--api-bind", "localhost"]).is_err()); - assert!(parse_as(false, &["up", "--api-bind", "::"]).is_err()); - } - - #[test] - fn system_mode_needs_root() { - assert!( - parse_as(false, &["up", "--mode", "system"]) - .unwrap_err() - .contains("root") - ); - assert!(parse_as(true, &["up", "--mode", "system"]).is_ok()); - let Command::Up(options) = parse_as(true, &["up"]).unwrap() else { - panic!() - }; - assert_eq!(options.dirs.prefix, PathBuf::from("/opt/leleka")); - } - - #[test] - fn other_commands() { - assert!(matches!(parse_as(false, &[]).unwrap(), Command::Help)); - assert!(matches!( - parse_as(false, &["profiles"]).unwrap(), - Command::Profiles(None) - )); - assert!(matches!( - parse_as(false, &["profiles", "show", "rtx5090-32g"]).unwrap(), - Command::Profiles(Some(_)) - )); - let Command::Run { config, kar_fd } = parse_as( - false, - &["run", "--config", "/s/leleka.json", "--kar-fd", "3"], - ) - .unwrap() else { - panic!() - }; - assert_eq!((config, kar_fd), (PathBuf::from("/s/leleka.json"), Some(3))); - assert!(parse_as(false, &["run"]).is_err()); - assert!(parse_as(false, &["frobnicate"]).is_err()); - assert!(matches!( - parse_as(false, &["exec-inherit", "--", "x"]).unwrap(), - Command::ExecInherit(_) - )); - } -} +//! Command-line parsing for `leleka`. No framework: a flag table per command, `--flag value` or `--flag=value`. +use crate::{config::Ports, layout::Dirs}; +use std::{collections::BTreeMap, path::PathBuf}; + +pub const USAGE: &str = "\ +leleka - one-command deployment of the Leleka runtime + +USAGE + leleka up [OPTIONS] preflight, fetch+verify the model, build the KAR archive, install, start, wait for ready + leleka preflight [OPTIONS] only the host checks (exit 1 when one fails) + leleka run --config FILE the foreground supervisor that systemd starts (engine + gateway + API) + leleka status [OPTIONS] service state and readiness + leleka down [OPTIONS] stop the systemd service + leleka verify [OPTIONS] hash both shards and the archive in full (in parallel), check the pinned digests, renew the + verification stamps that let a restart skip the hashing (needs a prepared state) + leleka profiles [show NAME] list the memory profiles, or print one as JSON + leleka version + +UP / PREFLIGHT OPTIONS + --dry-run print the plan and the preflight, change nothing + --json machine-readable plan / summary on stdout + --profile auto|NAME|FILE memory profile (default auto: chosen from the GPU) + --gpu N CUDA device ordinal (default 0) + --assets DIR model volume: shards, KAR archive, MTP pack, tokenizer [$LELEKA_ASSETS] + --state-dir DIR configs, tokens, logs, status [$LELEKA_STATE] + --prefix DIR install prefix (bin/, lib/cublas/) [$LELEKA_PREFIX] + --bin-src DIR where to take the six binaries from (default: the directory of this binary) + --mode auto|system|user|foreground|none + --foreground same as --mode foreground (WSL without systemd, containers, terminals) + --api-port N API port (default 8081) + --api-bind IP API listen address (default 127.0.0.1; 0.0.0.0 only inside a container whose port + is published to 127.0.0.1 or tunnelled; the key is the only protection, no TLS) + --engine-port N engine gRPC port (default 18766) + --daemon-port N gateway port (default 18080) + --preset dedicated|workstation dedicated (default) takes the whole host; workstation leaves cores, RAM and VRAM + for Docker, agents and the IDE (env LELEKA_PRESET) + --gpu-budget-gib N override the profile's GPU memory budget + --context-tokens N override the profile's context ceiling + --no-fetch never download or build; require the model files to exist + --reverify ignore the verification stamps and hash everything again + --trust-archive accept an existing archive of the pinned length + its provenance file without the + strict re-derivation (hours-scale); the engine still checks its SHA-256 and every + CRC against the pinned digest at each load + --mtp-pack PATH import the MTP pack (directory or .tar/.tar.gz of data/mtp-rt) into the assets + --cublas-dir DIR use this CUDA 12 cuBLAS directory instead of searching / downloading + --no-install-cublas fail instead of downloading cuBLAS 12.9.1.4 + --timeout-s N wait this long for readiness (default 3600) + --kar-fd N an already sealed KAR memfd inherited from the parent process: not copied again, + its RAM is not required (foreground / --mode none only) + --service-user NAME system unit only: account the service runs as (default leleka, created if missing) + +ENVIRONMENT + HF_TOKEN optional Hugging Face token for the model download (sent only to huggingface.co) +"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ModeChoice { + Auto, + System, + User, + Foreground, + None, +} + +#[derive(Clone, Debug)] +pub struct UpOptions { + pub dry_run: bool, + pub json: bool, + pub profile: Option, + pub gpu: u32, + pub dirs: Dirs, + pub bin_src: Option, + pub mode: ModeChoice, + /// Resource preset (`--preset`, `LELEKA_PRESET`): how much of the host the engine may take. + pub preset: crate::resources::Preset, + pub ports: Ports, + pub gpu_budget_gib: Option, + pub context_tokens: Option, + pub fetch: bool, + pub reverify: bool, + /// Accept an existing archive of the pinned length without the strict F32 re-derivation. + pub trust_archive: bool, + pub mtp_pack: Option, + pub cublas_dir: Option, + pub install_cublas: bool, + pub timeout_s: u64, + /// System unit only: the account the service runs as (created when missing). Default `leleka`. + pub service_user: Option, + /// An already sealed archive descriptor inherited from the parent (foreground / prepare-only runs). + pub kar_fd: Option, +} + +#[derive(Debug)] +pub enum Command { + Up(UpOptions), + Preflight(UpOptions), + Run { + config: PathBuf, + kar_fd: Option, + }, + ExecInherit(Vec), + Status(UpOptions), + Down(UpOptions), + Verify(UpOptions), + Profiles(Option), + Version, + Help, +} + +type Flags = BTreeMap>; + +const UP_FLAGS: &[(&str, bool)] = &[ + ("--dry-run", false), + ("--json", false), + ("--profile", true), + ("--gpu", true), + ("--assets", true), + ("--state-dir", true), + ("--prefix", true), + ("--bin-src", true), + ("--mode", true), + ("--preset", true), + ("--foreground", false), + ("--api-port", true), + ("--api-bind", true), + ("--engine-port", true), + ("--daemon-port", true), + ("--gpu-budget-gib", true), + ("--context-tokens", true), + ("--no-fetch", false), + ("--reverify", false), + ("--trust-archive", false), + ("--mtp-pack", true), + ("--cublas-dir", true), + ("--no-install-cublas", false), + ("--timeout-s", true), + ("--service-user", true), + ("--kar-fd", true), +]; + +fn parse_flags(args: &[String], table: &[(&str, bool)]) -> Result { + let mut flags = Flags::new(); + let mut index = 0; + while index < args.len() { + let arg = &args[index]; + let (name, inline) = match arg.split_once('=') { + Some((name, value)) if name.starts_with("--") => (name, Some(value.to_owned())), + _ => (arg.as_str(), None), + }; + let Some((_, takes_value)) = table.iter().find(|(flag, _)| *flag == name) else { + return Err(format!("unknown option {name:?}; see `leleka --help`")); + }; + let value = if *takes_value { + match inline { + Some(value) => Some(value), + None => { + index += 1; + Some( + args.get(index) + .ok_or_else(|| format!("{name} needs a value"))? + .clone(), + ) + } + } + } else if inline.is_some() { + return Err(format!("{name} takes no value")); + } else { + None + }; + if flags.insert(name.to_owned(), value).is_some() { + return Err(format!("{name} given twice")); + } + index += 1; + } + Ok(flags) +} + +fn number(flags: &Flags, name: &str, default: T) -> Result { + match flags.get(name) { + None => Ok(default), + Some(value) => value + .as_deref() + .unwrap_or("") + .parse() + .map_err(|_| format!("{name} needs a number")), + } +} + +/// `--api-bind IP`: where the public API listens. Loopback unless asked; the engine and the gateway always +/// stay on loopback. A non-loopback bind is for containers (publish the port to 127.0.0.1 on the host). +fn api_bind(flags: &Flags) -> Result { + match text(flags, "--api-bind") { + None => Ok("127.0.0.1".into()), + Some(ip) => match ip.parse::() { + Ok(std::net::IpAddr::V4(v4)) => Ok(v4.to_string()), + Ok(std::net::IpAddr::V6(_)) => Err("--api-bind takes an IPv4 address".into()), + Err(_) => Err(format!("--api-bind needs an IP address, not {ip:?}")), + }, + } +} + +fn ranged( + flags: &Flags, + name: &str, + range: std::ops::RangeInclusive, +) -> Result, String> { + if !flags.contains_key(name) { + return Ok(None); + } + let value: T = number(flags, name, *range.start())?; + if !range.contains(&value) { + return Err(format!("{name} must be {}..{}", range.start(), range.end())); + } + Ok(Some(value)) +} + +fn text<'a>(flags: &'a Flags, name: &str) -> Option<&'a str> { + flags.get(name).and_then(|v| v.as_deref()) +} + +fn port(flags: &Flags, name: &str, default: u16) -> Result { + let value: u16 = number(flags, name, default)?; + if value < 1024 { + return Err(format!("{name} must be 1024..65535")); + } + Ok(value) +} + +/// Environment access is injected so that parsing is testable. +pub struct Environment<'a> { + pub root: bool, + pub home: Option, + pub var: &'a dyn Fn(&str) -> Option, +} + +fn up_options(args: &[String], env: &Environment) -> Result { + let flags = parse_flags(args, UP_FLAGS)?; + let defaults = Dirs::defaults(env.root, env.home.as_deref(), env.var); + let abs = |name: &str, fallback: PathBuf| -> Result { + let path = text(&flags, name).map(PathBuf::from).unwrap_or(fallback); + if !path.is_absolute() { + return Err(format!( + "{name} must be an absolute path (got {})", + path.display() + )); + } + Ok(path) + }; + let dirs = Dirs { + prefix: abs("--prefix", defaults.prefix)?, + state: abs("--state-dir", defaults.state)?, + assets: abs("--assets", defaults.assets)?, + }; + let mode = if flags.contains_key("--foreground") { + if flags.contains_key("--mode") { + return Err("use either --foreground or --mode".into()); + } + ModeChoice::Foreground + } else { + match text(&flags, "--mode").unwrap_or("auto") { + "auto" => ModeChoice::Auto, + "system" => ModeChoice::System, + "user" => ModeChoice::User, + "foreground" => ModeChoice::Foreground, + "none" => ModeChoice::None, + other => { + return Err(format!( + "--mode must be auto, system, user, foreground or none, not {other:?}" + )); + } + } + }; + let kar_fd = match flags.get("--kar-fd") { + None => None, + Some(_) => { + let fd: u32 = number(&flags, "--kar-fd", 0u32)?; + if !(3..=1_048_576).contains(&fd) { + return Err( + "--kar-fd must be an inherited descriptor number of 3 or higher".into(), + ); + } + if matches!(mode, ModeChoice::System | ModeChoice::User) { + return Err("--kar-fd belongs to a process that holds the descriptor; use it with --foreground or --mode none, not with a systemd unit".into()); + } + Some(fd) + } + }; + if mode == ModeChoice::System && !env.root { + return Err("--mode system needs root (use sudo), or --mode user / --foreground".into()); + } + let ports = Ports { + api: format!( + "{}:{}", + api_bind(&flags)?, + port(&flags, "--api-port", 8081)? + ), + engine: format!("127.0.0.1:{}", port(&flags, "--engine-port", 18766)?), + daemon: format!("127.0.0.1:{}", port(&flags, "--daemon-port", 18080)?), + }; + let distinct = [&ports.api, &ports.engine, &ports.daemon]; + if distinct[0] == distinct[1] || distinct[0] == distinct[2] || distinct[1] == distinct[2] { + return Err("the API, engine and gateway ports must differ".into()); + } + let cublas_dir = text(&flags, "--cublas-dir").map(PathBuf::from); + if let Some(dir) = &cublas_dir + && !dir.is_absolute() + { + return Err("--cublas-dir must be an absolute path".into()); + } + Ok(UpOptions { + dry_run: flags.contains_key("--dry-run"), + json: flags.contains_key("--json"), + profile: text(&flags, "--profile").map(str::to_owned), + gpu: number(&flags, "--gpu", 0u32)?, + dirs, + bin_src: text(&flags, "--bin-src").map(PathBuf::from), + mode, + preset: match text(&flags, "--preset") { + Some(value) => crate::resources::Preset::parse(value)?, + None => match (env.var)("LELEKA_PRESET") { + Some(value) if !value.is_empty() => crate::resources::Preset::parse(&value)?, + _ => crate::resources::Preset::Dedicated, + }, + }, + ports, + gpu_budget_gib: ranged(&flags, "--gpu-budget-gib", 1u64..=1024)?, + context_tokens: ranged(&flags, "--context-tokens", 1u32..=262_144)?, + service_user: text(&flags, "--service-user").map(str::to_owned), + kar_fd, + fetch: !flags.contains_key("--no-fetch"), + reverify: flags.contains_key("--reverify"), + trust_archive: flags.contains_key("--trust-archive"), + mtp_pack: text(&flags, "--mtp-pack").map(PathBuf::from), + cublas_dir, + install_cublas: !flags.contains_key("--no-install-cublas"), + timeout_s: { + let value: u64 = number(&flags, "--timeout-s", 3600)?; + if !(1..=86_400).contains(&value) { + return Err("--timeout-s must be 1..86400".into()); + } + value + }, + }) +} + +pub fn parse(args: &[String], env: &Environment) -> Result { + let Some((command, rest)) = args.split_first() else { + return Ok(Command::Help); + }; + match command.as_str() { + "-h" | "--help" | "help" => Ok(Command::Help), + "version" | "--version" | "-V" => Ok(Command::Version), + "up" => up_options(rest, env).map(Command::Up), + "preflight" => up_options(rest, env).map(Command::Preflight), + "status" => up_options(rest, env).map(Command::Status), + "down" => up_options(rest, env).map(Command::Down), + "verify" => up_options(rest, env).map(Command::Verify), + "profiles" => match rest { + [] => Ok(Command::Profiles(None)), + [show, name] if show == "show" => Ok(Command::Profiles(Some(name.clone()))), + _ => Err("usage: leleka profiles [show NAME]".into()), + }, + "run" => { + let flags = parse_flags(rest, &[("--config", true), ("--kar-fd", true)])?; + let config = text(&flags, "--config").ok_or("leleka run needs --config FILE")?; + Ok(Command::Run { + config: PathBuf::from(config), + kar_fd: flags + .get("--kar-fd") + .map(|_| number(&flags, "--kar-fd", 0u32)) + .transpose()?, + }) + } + "exec-inherit" => Ok(Command::ExecInherit(rest.to_vec())), + other => Err(format!("unknown command {other:?}; see `leleka --help`")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn strings(items: &[&str]) -> Vec { + items.iter().map(|s| s.to_string()).collect() + } + + fn parse_as(root: bool, args: &[&str]) -> Result { + let var = |_: &str| None; + parse( + &strings(args), + &Environment { + root, + home: Some("/home/para".into()), + var: &var, + }, + ) + } + + #[test] + fn up_defaults_for_a_user() { + let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { + panic!() + }; + assert_eq!( + options.dirs.assets, + PathBuf::from("/home/para/.local/share/leleka/assets") + ); + assert_eq!(options.ports.api, "127.0.0.1:8081"); + assert!(options.fetch && options.install_cublas && !options.dry_run); + assert_eq!(options.mode, ModeChoice::Auto); + assert_eq!(options.timeout_s, 3600); + } + + #[test] + fn flags_accept_both_forms_and_reject_mistakes() { + let Command::Up(options) = parse_as( + false, + &[ + "up", + "--assets=/data/l", + "--gpu", + "1", + "--foreground", + "--dry-run", + "--json", + "--no-fetch", + "--api-port=9000", + ], + ) + .unwrap() else { + panic!() + }; + assert_eq!(options.dirs.assets, PathBuf::from("/data/l")); + assert_eq!( + ( + options.gpu, + options.mode, + options.dry_run, + options.json, + options.fetch + ), + (1, ModeChoice::Foreground, true, true, false) + ); + assert_eq!(options.ports.api, "127.0.0.1:9000"); + for bad in [ + &["up", "--nope"][..], + &["up", "--gpu"], + &["up", "--dry-run", "--dry-run"], + &["up", "--dry-run=1"], + &["up", "--assets", "relative/dir"], + &["up", "--api-port", "80"], + &["up", "--api-port", "9000", "--engine-port", "9000"], + &["up", "--mode", "weird"], + &["up", "--foreground", "--mode", "user"], + &["up", "--gpu-budget-gib", "0"], + &["up", "--context-tokens", "999999"], + &["up", "--timeout-s", "0"], + ] { + assert!(parse_as(false, bad).is_err(), "{bad:?} should fail"); + } + } + + #[test] + fn the_resource_preset_comes_from_the_flag_then_the_environment() { + use crate::resources::Preset; + let preset = |args: &[&str]| match parse_as(false, args) { + Ok(Command::Up(options)) => Ok(options.preset), + Ok(_) => unreachable!(), + Err(message) => Err(message), + }; + assert_eq!(preset(&["up"]), Ok(Preset::Dedicated)); + assert_eq!(preset(&["up", "--preset", "workstation"]), Ok(Preset::Workstation)); + assert!(preset(&["up", "--preset", "shared"]).unwrap_err().contains("unknown preset")); + } + + #[test] + fn api_bind_is_explicit_and_only_for_the_api() { + let Command::Up(options) = parse_as(false, &["up", "--api-bind", "0.0.0.0"]).unwrap() + else { + panic!() + }; + assert_eq!(options.ports.api, "0.0.0.0:8081"); + assert_eq!(options.ports.engine, "127.0.0.1:18766"); + assert!(parse_as(false, &["up", "--api-bind", "localhost"]).is_err()); + assert!(parse_as(false, &["up", "--api-bind", "::"]).is_err()); + } + + #[test] + fn system_mode_needs_root() { + assert!( + parse_as(false, &["up", "--mode", "system"]) + .unwrap_err() + .contains("root") + ); + assert!(parse_as(true, &["up", "--mode", "system"]).is_ok()); + let Command::Up(options) = parse_as(true, &["up"]).unwrap() else { + panic!() + }; + assert_eq!(options.dirs.prefix, PathBuf::from("/opt/leleka")); + } + + #[test] + fn other_commands() { + assert!(matches!(parse_as(false, &[]).unwrap(), Command::Help)); + assert!(matches!( + parse_as(false, &["profiles"]).unwrap(), + Command::Profiles(None) + )); + assert!(matches!( + parse_as(false, &["profiles", "show", "rtx5090-32g"]).unwrap(), + Command::Profiles(Some(_)) + )); + let Command::Run { config, kar_fd } = parse_as( + false, + &["run", "--config", "/s/leleka.json", "--kar-fd", "3"], + ) + .unwrap() else { + panic!() + }; + assert_eq!((config, kar_fd), (PathBuf::from("/s/leleka.json"), Some(3))); + assert!(parse_as(false, &["run"]).is_err()); + assert!(parse_as(false, &["frobnicate"]).is_err()); + assert!(matches!( + parse_as(false, &["exec-inherit", "--", "x"]).unwrap(), + Command::ExecInherit(_) + )); + } +} diff --git a/crates/deploy/src/config.rs b/crates/deploy/src/config.rs index 55b326df..a899f309 100644 --- a/crates/deploy/src/config.rs +++ b/crates/deploy/src/config.rs @@ -1,561 +1,561 @@ -//! The run configuration written by `up` and read by `run`, and the generated configs of the child processes. -//! -//! `leleka.json` holds no secret. Tokens live in `runtime.env` (mode 0600) and reach the children only through -//! their environment, never through argv. -use crate::{ - layout::{Dirs, MODEL_DIGEST, MODEL_ID, MTP_PROFILE, Paths}, - profile::{KarSource, Profile}, -}; -use serde::{Deserialize, Serialize}; -use serde_json::{Value, json}; -use std::collections::BTreeMap; - -pub const SCHEMA_VERSION: u32 = 1; -pub const RUNTIME_TOKEN_ENV: &str = "LELEKA_RUNTIME_TOKEN"; -pub const GATEWAY_TOKEN_ENV: &str = "LELEKA_GATEWAY_TOKEN"; - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Ports { - pub api: String, - pub engine: String, - pub daemon: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RestartPolicy { - /// Engine restarts the supervisor performs before it gives up (each one re-reads the archive). - pub max_engine_restarts: u32, - /// An engine that stayed ready this long resets the restart counter. - pub stable_after_s: u64, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RunConfig { - pub schema_version: u32, - pub leleka_version: String, - pub model_id: String, - pub model_digest: String, - pub prefix: String, - pub state: String, - pub assets: String, - pub ports: Ports, - pub gpu: u32, - pub profile: Profile, - /// The resource preset `up` applied (the profile and `engine_env` already carry its numbers). - #[serde(default)] - pub preset: crate::resources::Preset, - /// Extra engine environment resolved by `up` (for example the expert-profile path when that file is valid). - #[serde(default)] - pub engine_env: BTreeMap, - pub load_timeout_s: u64, - pub shutdown_grace_s: u64, - pub restart: RestartPolicy, - /// Do not hash a shard or the archive again when it is unchanged since it last matched its pinned digest - /// (`docs/deploy.md`, "Fast restarts"). `leleka verify` hashes everything and renews the stamps. - #[serde(default = "default_true")] - pub verify_stamps: bool, -} - -fn default_true() -> bool { - true -} - -/// How the engine receives the archive on its command line. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum KarArg { - /// `--kar-archive-fd {FD}`: the shim substitutes the descriptor number. - Fd, - /// `--kar-archive-file PATH`. - File, -} - -impl RunConfig { - pub fn new( - dirs: &Dirs, - ports: Ports, - gpu: u32, - profile: Profile, - engine_env: BTreeMap, - ) -> Self { - RunConfig { - schema_version: SCHEMA_VERSION, - leleka_version: env!("CARGO_PKG_VERSION").to_owned(), - model_id: MODEL_ID.to_owned(), - model_digest: MODEL_DIGEST.to_owned(), - prefix: dirs.prefix.display().to_string(), - state: dirs.state.display().to_string(), - assets: dirs.assets.display().to_string(), - ports, - gpu, - profile, - preset: crate::resources::Preset::default(), - engine_env, - load_timeout_s: 1800, - shutdown_grace_s: 10, - restart: RestartPolicy { - max_engine_restarts: 2, - stable_after_s: 600, - }, - verify_stamps: true, - } - } - - pub fn dirs(&self) -> Dirs { - Dirs { - prefix: self.prefix.clone().into(), - state: self.state.clone().into(), - assets: self.assets.clone().into(), - } - } - - pub fn paths(&self) -> Paths { - self.dirs().paths() - } - - pub fn validate(&self) -> Result<(), String> { - if self.schema_version != SCHEMA_VERSION { - return Err(format!( - "leleka.json has schema_version {}, this binary understands {SCHEMA_VERSION}; rerun `leleka up`", - self.schema_version - )); - } - self.profile.validate()?; - for (name, address, must_be_loopback) in [ - ("api", &self.ports.api, false), - ("engine", &self.ports.engine, true), - ("daemon", &self.ports.daemon, true), - ] { - let parsed: std::net::SocketAddr = address - .parse() - .map_err(|_| format!("ports.{name} must be a literal ip:port"))?; - // Only the API may leave the loopback interface (containers); the engine and the gateway never. - if must_be_loopback && !parsed.ip().is_loopback() { - return Err(format!( - "ports.{name} must be a loopback address (use an SSH tunnel for remote access)" - )); - } - } - Ok(()) - } - - pub fn read(path: &std::path::Path) -> Result { - let bytes = std::fs::read(path).map_err(|error| { - format!( - "cannot read {}: {error}; run `leleka up` first", - path.display() - ) - })?; - let config: RunConfig = serde_json::from_slice(&bytes) - .map_err(|error| format!("invalid {}: {error}", path.display()))?; - config.validate()?; - Ok(config) - } - - /// Arguments of `leleka-inference`, in the order its parser requires (seven fixed pairs first, then the - /// operator-source tuples). `{FD}` stays literal for [`KarArg::Fd`]. - pub fn engine_args(&self, kar: KarArg) -> Vec { - let paths = self.paths(); - let profile = &self.profile; - let mut args: Vec = vec![ - "--listen".into(), - self.ports.engine.clone(), - "--token-env".into(), - RUNTIME_TOKEN_ENV.into(), - "--shard0".into(), - paths.shard(0).display().to_string(), - "--shard1".into(), - paths.shard(1).display().to_string(), - "--gpu".into(), - self.gpu.to_string(), - "--gpu-budget".into(), - profile.gpu_budget_bytes.to_string(), - "--context-tokens".into(), - profile.context_tokens.to_string(), - ]; - match kar { - KarArg::Fd => args.extend(["--kar-archive-fd".into(), "{FD}".into()]), - KarArg::File => args.extend([ - "--kar-archive-file".into(), - paths.kar().display().to_string(), - ]), - } - args.extend([ - "--kar-provenance".into(), - paths.kar_provenance().display().to_string(), - "--mtp-pack".into(), - paths.mtp_pack().display().to_string(), - "--mtp-staging".into(), - paths.mtp_staging().display().to_string(), - "--backend-mode".into(), - "original".into(), - "--expert-source".into(), - profile.expert_source.as_str().into(), - // The Original drafts over the MTP pack's draft vocabulary (draft_vocab.bin, 106k rows); without this the engine - // drafts over the full 248k-row head, about 0.2 ms more per draft step. - "--mtp-rt-dir".into(), - paths.mtp_pack().display().to_string(), - ]); - if let Some(value) = profile.prefill_capacity { - args.extend(["--original-prefill-capacity".into(), value.to_string()]); - } - if let Some(value) = &profile.kv { - args.extend(["--kv".into(), value.clone()]); - } - if let Some(value) = profile.kv_resident { - args.extend(["--kv-resident".into(), value.to_string()]); - } - if let Some(value) = profile.prompt_cache { - args.extend(["--prompt-cache".into(), value.to_string()]); - } - if let Some(value) = profile.spec_min_p { - args.extend(["--spec-min-p".into(), value.to_string()]); - } - args.extend(profile.memory.args()); - if self.verify_stamps { - args.extend([ - "--verify-stamps".into(), - paths.engine_stamps().display().to_string(), - ]); - } - args - } - - /// Arguments of `leleka-inference --verify-only --verify-rehash`: both shards hashed in full and the stamps renewed. - /// A file-backed archive is verified by the engine too; a sealed-memfd profile has no archive here (the - /// supervisor-side hash of the archive file is `leleka verify`'s other half). - pub fn verify_args(&self, rehash: bool) -> Vec { - let paths = self.paths(); - let mut args = self.engine_args(KarArg::File); - // Keep the seven fixed pairs, drop the archive, pack and backend switches the verification does not use. - args.truncate(14); - if self.profile.kar_source == KarSource::File { - args.extend([ - "--kar-archive-file".into(), - paths.kar().display().to_string(), - "--kar-provenance".into(), - paths.kar_provenance().display().to_string(), - ]); - } - args.push("--verify-only".into()); - if rehash { - args.push("--verify-rehash".into()); - } - args.extend([ - "--verify-stamps".into(), - paths.engine_stamps().display().to_string(), - ]); - args - } - - pub fn kar_arg(&self) -> KarArg { - match self.profile.kar_source { - KarSource::Memfd => KarArg::Fd, - KarSource::File => KarArg::File, - } - } - - /// The engine's extra environment: profile switches, then the `up`-resolved ones (which win). - pub fn engine_environment(&self) -> BTreeMap { - let mut env = self.profile.memory.env(); - env.extend(self.profile.engine_env.clone()); - env.extend(self.engine_env.clone()); - env - } - - pub fn daemon_json(&self) -> Value { - json!({ - "schema_version": 1, - "listen": self.ports.daemon, - "token_env": GATEWAY_TOKEN_ENV, - "runtimes": [{ - "id": self.model_id, - "address": self.ports.engine, - "token_env": RUNTIME_TOKEN_ENV, - "artifact_digest": self.model_digest, - }] - }) - } - - pub fn strata_json(&self) -> Value { - let paths = self.paths(); - json!({ - "bind": self.ports.api, - "api_key_file": paths.api_key().display().to_string(), - "model": self.model_id, - "shutdown_grace_s": self.shutdown_grace_s, - "runtime": { - "address": self.ports.engine, - "token_env": RUNTIME_TOKEN_ENV, - "tokenizer_dir": paths.tokenizer_dir().display().to_string(), - "model": { - "family": "qwen4exp", - "architecture": "qwen4exp", - "weight_format": "gguf:iq3_s", - "artifact_digest": self.model_digest, - }, - "mode": {"type": "mtp", "profile_id": MTP_PROFILE}, - "max_context": self.profile.context_tokens, - "max_output_tokens": 32768, - } - }) - } -} - -/// The address to probe for an `ip:port` the service binds: an unspecified address (0.0.0.0, ::) is probed on -/// the loopback interface. -pub fn probe_address(bind: &str) -> Option { - let address: std::net::SocketAddr = bind.parse().ok()?; - Some(if address.ip().is_unspecified() { - std::net::SocketAddr::from(([127, 0, 0, 1], address.port())) - } else { - address - }) -} - -/// Pretty JSON with a trailing newline, the byte form that is written and compared. -pub fn to_file_text(value: &impl Serialize) -> String { - let mut text = serde_json::to_string_pretty(value).expect("serializable"); - text.push('\n'); - text -} - -/// `n` random bytes from the kernel. Linux only (the deployment is). -pub fn random_bytes(n: usize) -> Result, String> { - use std::io::Read; - let mut bytes = vec![0u8; n]; - std::fs::File::open("/dev/urandom") - .and_then(|mut file| file.read_exact(&mut bytes)) - .map_err(|error| format!("cannot read /dev/urandom: {error}"))?; - Ok(bytes) -} - -/// A 48-character lower-case hex token (192 bits), inside the 32..4096 printable-ASCII rule of the runtime. -pub fn new_token() -> Result { - Ok(hex::encode(random_bytes(24)?)) -} - -/// Update `KEY=VALUE` lines of a systemd environment file in place, appending missing keys and keeping every -/// other line (including secrets) byte for byte. -pub fn merge_env(existing: &str, updates: &[(&str, String)]) -> String { - let mut lines: Vec = existing.lines().map(str::to_owned).collect(); - for (key, value) in updates { - let prefix = format!("{key}="); - let mut found = false; - for line in lines.iter_mut() { - if line.trim_start().starts_with(&prefix) { - *line = format!("{key}={value}"); - found = true; - break; - } - } - if !found { - lines.push(format!("{key}={value}")); - } - } - let mut text = lines.join("\n"); - text.push('\n'); - text -} - -/// The header comment of a freshly created `runtime.env`. -pub const ENV_HEADER: &str = "# Written by `leleka up`; mode 0600; never commit. Two independent secrets and the loader path."; - -#[cfg(test)] -mod tests { - use super::*; - - fn config(profile: &str) -> RunConfig { - let dirs = Dirs { - prefix: "/opt/leleka".into(), - state: "/var/lib/leleka/state".into(), - assets: "/data/leleka".into(), - }; - RunConfig::new( - &dirs, - Ports { - api: "127.0.0.1:8081".into(), - engine: "127.0.0.1:18766".into(), - daemon: "127.0.0.1:18080".into(), - }, - 0, - Profile::builtin(profile).unwrap(), - BTreeMap::new(), - ) - } - - #[test] - fn server_engine_command_matches_the_documented_one() { - let args = config("rtx5090-32g").engine_args(KarArg::Fd); - let text = args.join(" "); - // docs/rust-runtime-run.md, step 1. - assert!(text.starts_with("--listen 127.0.0.1:18766 --token-env LELEKA_RUNTIME_TOKEN --shard0 /data/leleka/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf"), "{text}"); - assert!(text.contains("--gpu 0 --gpu-budget 32212254720 --context-tokens 262144")); - assert!(text.contains("--kar-archive-fd {FD} --kar-provenance /data/leleka/qwen-iq3-s-l2-v4.kar.provenance.json")); - assert!(text.contains("--mtp-pack /data/leleka/data/mtp-rt --mtp-staging /var/lib/leleka/state/mtp-staging --backend-mode original --expert-source resident --mtp-rt-dir /data/leleka/data/mtp-rt")); - // The engine parser reads the first 14 arguments positionally. - assert_eq!(args[..14].len(), 14); - assert_eq!(args[12], "--context-tokens"); - } - - #[test] - fn verify_arguments_keep_the_seven_pairs_and_choose_the_archive_by_profile() { - let server = config("rtx5090-32g"); - let args = server.verify_args(false); - assert_eq!(&args[..14], &server.engine_args(KarArg::Fd)[..14]); - let text = args.join(" "); - assert!( - text.ends_with("--verify-only --verify-stamps /var/lib/leleka/state/stamps/engine"), - "{text}" - ); - assert!( - !text.contains("--kar-archive") && !text.contains("--backend-mode"), - "{text}" - ); - assert!( - server - .verify_args(true) - .contains(&"--verify-rehash".to_owned()) - ); - let laptop = config("rtx3080-16g").verify_args(true).join(" "); - assert!( - laptop - .contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar --kar-provenance"), - "{laptop}" - ); - } - - #[test] - fn stamps_are_in_the_engine_command_unless_switched_off() { - let mut c = config("rtx5090-32g"); - assert!( - c.engine_args(KarArg::Fd) - .join(" ") - .contains("--verify-stamps /var/lib/leleka/state/stamps/engine") - ); - c.verify_stamps = false; - assert!( - !c.engine_args(KarArg::Fd) - .join(" ") - .contains("--verify-stamps") - ); - } - - #[test] - fn laptop_uses_the_file_source_and_a_small_context() { - let config = config("rtx3080-16g"); - assert_eq!(config.kar_arg(), KarArg::File); - let text = config.engine_args(config.kar_arg()).join(" "); - assert!( - text.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar --kar-provenance") - ); - assert!(text.contains("--gpu-budget 16106127360 --context-tokens 8192")); - assert!(text.contains("--expert-source mapped")); - assert!(!text.contains("{FD}")); - } - - #[test] - fn generated_configs_are_consistent() { - let config = config("rtx5090-32g"); - let daemon = config.daemon_json(); - assert_eq!(daemon["runtimes"][0]["address"], "127.0.0.1:18766"); - assert_eq!(daemon["runtimes"][0]["artifact_digest"], MODEL_DIGEST); - let strata = config.strata_json(); - assert_eq!( - strata["runtime"]["address"], - daemon["runtimes"][0]["address"] - ); - assert_eq!( - strata["runtime"]["mode"]["profile_id"], - "qwen4exp-kar-ple-mtp-v1" - ); - assert_eq!( - strata["runtime"]["tokenizer_dir"], - "/data/leleka/tokenizer-assets/tokenizer" - ); - assert_eq!(strata["runtime"]["max_context"], 262144); - // No secret is ever part of a generated config. - let text = to_file_text(&strata) + &to_file_text(&daemon) + &to_file_text(&config); - assert!(!text.to_ascii_lowercase().contains("secret")); - } - - #[test] - fn validation_rejects_non_loopback_and_future_schemas() { - // Only the API may be bound beyond loopback (container use); the others never. - let mut open_api = config("rtx5090-32g"); - open_api.ports.api = "0.0.0.0:8081".into(); - assert!(open_api.validate().is_ok()); - assert_eq!( - probe_address("0.0.0.0:8081"), - Some("127.0.0.1:8081".parse().unwrap()) - ); - assert_eq!( - probe_address("127.0.0.1:1"), - Some("127.0.0.1:1".parse().unwrap()) - ); - assert_eq!(probe_address("nonsense"), None); - let mut bad = config("rtx5090-32g"); - bad.ports.engine = "0.0.0.0:18766".into(); - assert!(bad.validate().unwrap_err().contains("loopback")); - let mut bad = config("rtx5090-32g"); - bad.schema_version = 9; - assert!(bad.validate().unwrap_err().contains("schema_version")); - assert!(config("rtx3080-16g").validate().is_ok()); - } - - #[test] - fn round_trip_through_json() { - let original = config("rtx3080-16g"); - let text = to_file_text(&original); - let back: RunConfig = serde_json::from_str(&text).unwrap(); - assert_eq!(back, original); - } - - #[test] - fn env_merge_keeps_secrets_and_updates_the_loader_path() { - let existing = "# c\nLELEKA_RUNTIME_TOKEN=aaaa\nLD_LIBRARY_PATH=/old\nOTHER=1\n"; - let merged = merge_env( - existing, - &[ - ("LD_LIBRARY_PATH", "/new".into()), - ("LELEKA_GATEWAY_TOKEN", "bbbb".into()), - ], - ); - assert_eq!( - merged, - "# c\nLELEKA_RUNTIME_TOKEN=aaaa\nLD_LIBRARY_PATH=/new\nOTHER=1\nLELEKA_GATEWAY_TOKEN=bbbb\n" - ); - assert_eq!( - merge_env(&merged, &[("LD_LIBRARY_PATH", "/new".into())]), - merged - ); - } - - #[cfg(target_os = "linux")] - #[test] - fn tokens_are_printable_distinct_and_long_enough() { - let (a, b) = (new_token().unwrap(), new_token().unwrap()); - assert_ne!(a, b); - assert!((32..=4096).contains(&a.len()) && a.bytes().all(|c| (0x21..=0x7e).contains(&c))); - } - - #[test] - fn expert_environment_wins_over_the_profile() { - let mut config = config("rtx3080-16g"); - config - .profile - .engine_env - .insert("LELEKA_ORIGINAL_SERVE_PCIE_FRAC".into(), "0.1".into()); - config - .engine_env - .insert("LELEKA_ORIGINAL_SERVE_PCIE_FRAC".into(), "0.2".into()); - config - .engine_env - .insert("LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS".into(), "auto".into()); - let env = config.engine_environment(); - assert_eq!(env["LELEKA_ORIGINAL_SERVE_PCIE_FRAC"], "0.2"); - assert_eq!(env["LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS"], "auto"); - } -} +//! The run configuration written by `up` and read by `run`, and the generated configs of the child processes. +//! +//! `leleka.json` holds no secret. Tokens live in `runtime.env` (mode 0600) and reach the children only through +//! their environment, never through argv. +use crate::{ + layout::{Dirs, MODEL_DIGEST, MODEL_ID, MTP_PROFILE, Paths}, + profile::{KarSource, Profile}, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; + +pub const SCHEMA_VERSION: u32 = 1; +pub const RUNTIME_TOKEN_ENV: &str = "LELEKA_RUNTIME_TOKEN"; +pub const GATEWAY_TOKEN_ENV: &str = "LELEKA_GATEWAY_TOKEN"; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Ports { + pub api: String, + pub engine: String, + pub daemon: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RestartPolicy { + /// Engine restarts the supervisor performs before it gives up (each one re-reads the archive). + pub max_engine_restarts: u32, + /// An engine that stayed ready this long resets the restart counter. + pub stable_after_s: u64, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RunConfig { + pub schema_version: u32, + pub leleka_version: String, + pub model_id: String, + pub model_digest: String, + pub prefix: String, + pub state: String, + pub assets: String, + pub ports: Ports, + pub gpu: u32, + pub profile: Profile, + /// The resource preset `up` applied (the profile and `engine_env` already carry its numbers). + #[serde(default)] + pub preset: crate::resources::Preset, + /// Extra engine environment resolved by `up` (for example the expert-profile path when that file is valid). + #[serde(default)] + pub engine_env: BTreeMap, + pub load_timeout_s: u64, + pub shutdown_grace_s: u64, + pub restart: RestartPolicy, + /// Do not hash a shard or the archive again when it is unchanged since it last matched its pinned digest + /// (`docs/deploy.md`, "Fast restarts"). `leleka verify` hashes everything and renews the stamps. + #[serde(default = "default_true")] + pub verify_stamps: bool, +} + +fn default_true() -> bool { + true +} + +/// How the engine receives the archive on its command line. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KarArg { + /// `--kar-archive-fd {FD}`: the shim substitutes the descriptor number. + Fd, + /// `--kar-archive-file PATH`. + File, +} + +impl RunConfig { + pub fn new( + dirs: &Dirs, + ports: Ports, + gpu: u32, + profile: Profile, + engine_env: BTreeMap, + ) -> Self { + RunConfig { + schema_version: SCHEMA_VERSION, + leleka_version: env!("CARGO_PKG_VERSION").to_owned(), + model_id: MODEL_ID.to_owned(), + model_digest: MODEL_DIGEST.to_owned(), + prefix: dirs.prefix.display().to_string(), + state: dirs.state.display().to_string(), + assets: dirs.assets.display().to_string(), + ports, + gpu, + profile, + preset: crate::resources::Preset::default(), + engine_env, + load_timeout_s: 1800, + shutdown_grace_s: 10, + restart: RestartPolicy { + max_engine_restarts: 2, + stable_after_s: 600, + }, + verify_stamps: true, + } + } + + pub fn dirs(&self) -> Dirs { + Dirs { + prefix: self.prefix.clone().into(), + state: self.state.clone().into(), + assets: self.assets.clone().into(), + } + } + + pub fn paths(&self) -> Paths { + self.dirs().paths() + } + + pub fn validate(&self) -> Result<(), String> { + if self.schema_version != SCHEMA_VERSION { + return Err(format!( + "leleka.json has schema_version {}, this binary understands {SCHEMA_VERSION}; rerun `leleka up`", + self.schema_version + )); + } + self.profile.validate()?; + for (name, address, must_be_loopback) in [ + ("api", &self.ports.api, false), + ("engine", &self.ports.engine, true), + ("daemon", &self.ports.daemon, true), + ] { + let parsed: std::net::SocketAddr = address + .parse() + .map_err(|_| format!("ports.{name} must be a literal ip:port"))?; + // Only the API may leave the loopback interface (containers); the engine and the gateway never. + if must_be_loopback && !parsed.ip().is_loopback() { + return Err(format!( + "ports.{name} must be a loopback address (use an SSH tunnel for remote access)" + )); + } + } + Ok(()) + } + + pub fn read(path: &std::path::Path) -> Result { + let bytes = std::fs::read(path).map_err(|error| { + format!( + "cannot read {}: {error}; run `leleka up` first", + path.display() + ) + })?; + let config: RunConfig = serde_json::from_slice(&bytes) + .map_err(|error| format!("invalid {}: {error}", path.display()))?; + config.validate()?; + Ok(config) + } + + /// Arguments of `leleka-inference`, in the order its parser requires (seven fixed pairs first, then the + /// operator-source tuples). `{FD}` stays literal for [`KarArg::Fd`]. + pub fn engine_args(&self, kar: KarArg) -> Vec { + let paths = self.paths(); + let profile = &self.profile; + let mut args: Vec = vec![ + "--listen".into(), + self.ports.engine.clone(), + "--token-env".into(), + RUNTIME_TOKEN_ENV.into(), + "--shard0".into(), + paths.shard(0).display().to_string(), + "--shard1".into(), + paths.shard(1).display().to_string(), + "--gpu".into(), + self.gpu.to_string(), + "--gpu-budget".into(), + profile.gpu_budget_bytes.to_string(), + "--context-tokens".into(), + profile.context_tokens.to_string(), + ]; + match kar { + KarArg::Fd => args.extend(["--kar-archive-fd".into(), "{FD}".into()]), + KarArg::File => args.extend([ + "--kar-archive-file".into(), + paths.kar().display().to_string(), + ]), + } + args.extend([ + "--kar-provenance".into(), + paths.kar_provenance().display().to_string(), + "--mtp-pack".into(), + paths.mtp_pack().display().to_string(), + "--mtp-staging".into(), + paths.mtp_staging().display().to_string(), + "--backend-mode".into(), + "original".into(), + "--expert-source".into(), + profile.expert_source.as_str().into(), + // The Original drafts over the MTP pack's draft vocabulary (draft_vocab.bin, 106k rows); without this the engine + // drafts over the full 248k-row head, about 0.2 ms more per draft step. + "--mtp-rt-dir".into(), + paths.mtp_pack().display().to_string(), + ]); + if let Some(value) = profile.prefill_capacity { + args.extend(["--original-prefill-capacity".into(), value.to_string()]); + } + if let Some(value) = &profile.kv { + args.extend(["--kv".into(), value.clone()]); + } + if let Some(value) = profile.kv_resident { + args.extend(["--kv-resident".into(), value.to_string()]); + } + if let Some(value) = profile.prompt_cache { + args.extend(["--prompt-cache".into(), value.to_string()]); + } + if let Some(value) = profile.spec_min_p { + args.extend(["--spec-min-p".into(), value.to_string()]); + } + args.extend(profile.memory.args()); + if self.verify_stamps { + args.extend([ + "--verify-stamps".into(), + paths.engine_stamps().display().to_string(), + ]); + } + args + } + + /// Arguments of `leleka-inference --verify-only --verify-rehash`: both shards hashed in full and the stamps renewed. + /// A file-backed archive is verified by the engine too; a sealed-memfd profile has no archive here (the + /// supervisor-side hash of the archive file is `leleka verify`'s other half). + pub fn verify_args(&self, rehash: bool) -> Vec { + let paths = self.paths(); + let mut args = self.engine_args(KarArg::File); + // Keep the seven fixed pairs, drop the archive, pack and backend switches the verification does not use. + args.truncate(14); + if self.profile.kar_source == KarSource::File { + args.extend([ + "--kar-archive-file".into(), + paths.kar().display().to_string(), + "--kar-provenance".into(), + paths.kar_provenance().display().to_string(), + ]); + } + args.push("--verify-only".into()); + if rehash { + args.push("--verify-rehash".into()); + } + args.extend([ + "--verify-stamps".into(), + paths.engine_stamps().display().to_string(), + ]); + args + } + + pub fn kar_arg(&self) -> KarArg { + match self.profile.kar_source { + KarSource::Memfd => KarArg::Fd, + KarSource::File => KarArg::File, + } + } + + /// The engine's extra environment: profile switches, then the `up`-resolved ones (which win). + pub fn engine_environment(&self) -> BTreeMap { + let mut env = self.profile.memory.env(); + env.extend(self.profile.engine_env.clone()); + env.extend(self.engine_env.clone()); + env + } + + pub fn daemon_json(&self) -> Value { + json!({ + "schema_version": 1, + "listen": self.ports.daemon, + "token_env": GATEWAY_TOKEN_ENV, + "runtimes": [{ + "id": self.model_id, + "address": self.ports.engine, + "token_env": RUNTIME_TOKEN_ENV, + "artifact_digest": self.model_digest, + }] + }) + } + + pub fn strata_json(&self) -> Value { + let paths = self.paths(); + json!({ + "bind": self.ports.api, + "api_key_file": paths.api_key().display().to_string(), + "model": self.model_id, + "shutdown_grace_s": self.shutdown_grace_s, + "runtime": { + "address": self.ports.engine, + "token_env": RUNTIME_TOKEN_ENV, + "tokenizer_dir": paths.tokenizer_dir().display().to_string(), + "model": { + "family": "qwen4exp", + "architecture": "qwen4exp", + "weight_format": "gguf:iq3_s", + "artifact_digest": self.model_digest, + }, + "mode": {"type": "mtp", "profile_id": MTP_PROFILE}, + "max_context": self.profile.context_tokens, + "max_output_tokens": 32768, + } + }) + } +} + +/// The address to probe for an `ip:port` the service binds: an unspecified address (0.0.0.0, ::) is probed on +/// the loopback interface. +pub fn probe_address(bind: &str) -> Option { + let address: std::net::SocketAddr = bind.parse().ok()?; + Some(if address.ip().is_unspecified() { + std::net::SocketAddr::from(([127, 0, 0, 1], address.port())) + } else { + address + }) +} + +/// Pretty JSON with a trailing newline, the byte form that is written and compared. +pub fn to_file_text(value: &impl Serialize) -> String { + let mut text = serde_json::to_string_pretty(value).expect("serializable"); + text.push('\n'); + text +} + +/// `n` random bytes from the kernel. Linux only (the deployment is). +pub fn random_bytes(n: usize) -> Result, String> { + use std::io::Read; + let mut bytes = vec![0u8; n]; + std::fs::File::open("/dev/urandom") + .and_then(|mut file| file.read_exact(&mut bytes)) + .map_err(|error| format!("cannot read /dev/urandom: {error}"))?; + Ok(bytes) +} + +/// A 48-character lower-case hex token (192 bits), inside the 32..4096 printable-ASCII rule of the runtime. +pub fn new_token() -> Result { + Ok(hex::encode(random_bytes(24)?)) +} + +/// Update `KEY=VALUE` lines of a systemd environment file in place, appending missing keys and keeping every +/// other line (including secrets) byte for byte. +pub fn merge_env(existing: &str, updates: &[(&str, String)]) -> String { + let mut lines: Vec = existing.lines().map(str::to_owned).collect(); + for (key, value) in updates { + let prefix = format!("{key}="); + let mut found = false; + for line in lines.iter_mut() { + if line.trim_start().starts_with(&prefix) { + *line = format!("{key}={value}"); + found = true; + break; + } + } + if !found { + lines.push(format!("{key}={value}")); + } + } + let mut text = lines.join("\n"); + text.push('\n'); + text +} + +/// The header comment of a freshly created `runtime.env`. +pub const ENV_HEADER: &str = "# Written by `leleka up`; mode 0600; never commit. Two independent secrets and the loader path."; + +#[cfg(test)] +mod tests { + use super::*; + + fn config(profile: &str) -> RunConfig { + let dirs = Dirs { + prefix: "/opt/leleka".into(), + state: "/var/lib/leleka/state".into(), + assets: "/data/leleka".into(), + }; + RunConfig::new( + &dirs, + Ports { + api: "127.0.0.1:8081".into(), + engine: "127.0.0.1:18766".into(), + daemon: "127.0.0.1:18080".into(), + }, + 0, + Profile::builtin(profile).unwrap(), + BTreeMap::new(), + ) + } + + #[test] + fn server_engine_command_matches_the_documented_one() { + let args = config("rtx5090-32g").engine_args(KarArg::Fd); + let text = args.join(" "); + // docs/rust-runtime-run.md, step 1. + assert!(text.starts_with("--listen 127.0.0.1:18766 --token-env LELEKA_RUNTIME_TOKEN --shard0 /data/leleka/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf"), "{text}"); + assert!(text.contains("--gpu 0 --gpu-budget 32212254720 --context-tokens 262144")); + assert!(text.contains("--kar-archive-fd {FD} --kar-provenance /data/leleka/qwen-iq3-s-l2-v4.kar.provenance.json")); + assert!(text.contains("--mtp-pack /data/leleka/data/mtp-rt --mtp-staging /var/lib/leleka/state/mtp-staging --backend-mode original --expert-source resident --mtp-rt-dir /data/leleka/data/mtp-rt")); + // The engine parser reads the first 14 arguments positionally. + assert_eq!(args[..14].len(), 14); + assert_eq!(args[12], "--context-tokens"); + } + + #[test] + fn verify_arguments_keep_the_seven_pairs_and_choose_the_archive_by_profile() { + let server = config("rtx5090-32g"); + let args = server.verify_args(false); + assert_eq!(&args[..14], &server.engine_args(KarArg::Fd)[..14]); + let text = args.join(" "); + assert!( + text.ends_with("--verify-only --verify-stamps /var/lib/leleka/state/stamps/engine"), + "{text}" + ); + assert!( + !text.contains("--kar-archive") && !text.contains("--backend-mode"), + "{text}" + ); + assert!( + server + .verify_args(true) + .contains(&"--verify-rehash".to_owned()) + ); + let laptop = config("rtx3080-16g").verify_args(true).join(" "); + assert!( + laptop + .contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar --kar-provenance"), + "{laptop}" + ); + } + + #[test] + fn stamps_are_in_the_engine_command_unless_switched_off() { + let mut c = config("rtx5090-32g"); + assert!( + c.engine_args(KarArg::Fd) + .join(" ") + .contains("--verify-stamps /var/lib/leleka/state/stamps/engine") + ); + c.verify_stamps = false; + assert!( + !c.engine_args(KarArg::Fd) + .join(" ") + .contains("--verify-stamps") + ); + } + + #[test] + fn laptop_uses_the_file_source_and_a_small_context() { + let config = config("rtx3080-16g"); + assert_eq!(config.kar_arg(), KarArg::File); + let text = config.engine_args(config.kar_arg()).join(" "); + assert!( + text.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar --kar-provenance") + ); + assert!(text.contains("--gpu-budget 16106127360 --context-tokens 8192")); + assert!(text.contains("--expert-source mapped")); + assert!(!text.contains("{FD}")); + } + + #[test] + fn generated_configs_are_consistent() { + let config = config("rtx5090-32g"); + let daemon = config.daemon_json(); + assert_eq!(daemon["runtimes"][0]["address"], "127.0.0.1:18766"); + assert_eq!(daemon["runtimes"][0]["artifact_digest"], MODEL_DIGEST); + let strata = config.strata_json(); + assert_eq!( + strata["runtime"]["address"], + daemon["runtimes"][0]["address"] + ); + assert_eq!( + strata["runtime"]["mode"]["profile_id"], + "qwen4exp-kar-ple-mtp-v1" + ); + assert_eq!( + strata["runtime"]["tokenizer_dir"], + "/data/leleka/tokenizer-assets/tokenizer" + ); + assert_eq!(strata["runtime"]["max_context"], 262144); + // No secret is ever part of a generated config. + let text = to_file_text(&strata) + &to_file_text(&daemon) + &to_file_text(&config); + assert!(!text.to_ascii_lowercase().contains("secret")); + } + + #[test] + fn validation_rejects_non_loopback_and_future_schemas() { + // Only the API may be bound beyond loopback (container use); the others never. + let mut open_api = config("rtx5090-32g"); + open_api.ports.api = "0.0.0.0:8081".into(); + assert!(open_api.validate().is_ok()); + assert_eq!( + probe_address("0.0.0.0:8081"), + Some("127.0.0.1:8081".parse().unwrap()) + ); + assert_eq!( + probe_address("127.0.0.1:1"), + Some("127.0.0.1:1".parse().unwrap()) + ); + assert_eq!(probe_address("nonsense"), None); + let mut bad = config("rtx5090-32g"); + bad.ports.engine = "0.0.0.0:18766".into(); + assert!(bad.validate().unwrap_err().contains("loopback")); + let mut bad = config("rtx5090-32g"); + bad.schema_version = 9; + assert!(bad.validate().unwrap_err().contains("schema_version")); + assert!(config("rtx3080-16g").validate().is_ok()); + } + + #[test] + fn round_trip_through_json() { + let original = config("rtx3080-16g"); + let text = to_file_text(&original); + let back: RunConfig = serde_json::from_str(&text).unwrap(); + assert_eq!(back, original); + } + + #[test] + fn env_merge_keeps_secrets_and_updates_the_loader_path() { + let existing = "# c\nLELEKA_RUNTIME_TOKEN=aaaa\nLD_LIBRARY_PATH=/old\nOTHER=1\n"; + let merged = merge_env( + existing, + &[ + ("LD_LIBRARY_PATH", "/new".into()), + ("LELEKA_GATEWAY_TOKEN", "bbbb".into()), + ], + ); + assert_eq!( + merged, + "# c\nLELEKA_RUNTIME_TOKEN=aaaa\nLD_LIBRARY_PATH=/new\nOTHER=1\nLELEKA_GATEWAY_TOKEN=bbbb\n" + ); + assert_eq!( + merge_env(&merged, &[("LD_LIBRARY_PATH", "/new".into())]), + merged + ); + } + + #[cfg(target_os = "linux")] + #[test] + fn tokens_are_printable_distinct_and_long_enough() { + let (a, b) = (new_token().unwrap(), new_token().unwrap()); + assert_ne!(a, b); + assert!((32..=4096).contains(&a.len()) && a.bytes().all(|c| (0x21..=0x7e).contains(&c))); + } + + #[test] + fn expert_environment_wins_over_the_profile() { + let mut config = config("rtx3080-16g"); + config + .profile + .engine_env + .insert("LELEKA_ORIGINAL_SERVE_PCIE_FRAC".into(), "0.1".into()); + config + .engine_env + .insert("LELEKA_ORIGINAL_SERVE_PCIE_FRAC".into(), "0.2".into()); + config + .engine_env + .insert("LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS".into(), "auto".into()); + let env = config.engine_environment(); + assert_eq!(env["LELEKA_ORIGINAL_SERVE_PCIE_FRAC"], "0.2"); + assert_eq!(env["LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS"], "auto"); + } +} diff --git a/crates/deploy/src/facts.rs b/crates/deploy/src/facts.rs index 5dbe21a7..789c2cef 100644 --- a/crates/deploy/src/facts.rs +++ b/crates/deploy/src/facts.rs @@ -1,513 +1,513 @@ -//! Host facts for the preflight: pure parsers (unit-tested on any OS) and a Linux probe that fills `Facts`. -//! -//! `Facts` is plain data so that `preflight::evaluate` can be tested with synthetic hosts. Nothing here creates -//! a CUDA context; the GPU is read through `nvidia-smi`. -use std::{ - collections::BTreeMap, - path::{Path, PathBuf}, -}; - -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct Gpu { - pub index: u32, - pub name: String, - pub driver: String, - pub vram_total_mib: u64, - pub vram_free_mib: u64, - /// Compute capability times ten (12.0 -> 120, 8.6 -> 86). - pub sm: Option, -} - -impl Gpu { - pub fn driver_major(&self) -> Option { - self.driver.split('.').next()?.parse().ok() - } -} - -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct Memory { - pub total: u64, - pub available: u64, - pub swap_total: u64, -} - -/// What `probe` reads about one directory the deployment will write to. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct DirFact { - pub path: PathBuf, - /// Free bytes of the file system that holds (or would hold) the directory. - pub free_bytes: Option, - /// File system type of the mount that holds it (`ext4`, `9p`, `drvfs`, ...). - pub fs_type: Option, -} - -#[derive(Clone, Debug, Default)] -pub struct Facts { - pub os: String, - pub arch: String, - pub root: bool, - pub nvidia_smi_found: bool, - pub nvidia_smi_error: Option, - pub gpus: Vec, - pub memory: Memory, - /// Logical CPUs this process may use (affinity and cgroup quota aware); 0 when unknown. - pub cpu_cores: u32, - /// `memory.max` of the cgroup this process runs in, when limited. - pub cgroup_memory_max: Option, - pub wsl: bool, - pub systemd_system: bool, - pub proc_fd: bool, - pub memfd_ok: bool, - pub libs: BTreeMap>, - pub tools: BTreeMap, - pub dirs: BTreeMap, - pub busy_ports: Vec, - pub binaries: BTreeMap, - pub hf_token_set: bool, -} - -impl Facts { - pub fn lib(&self, soname: &str) -> Option<&PathBuf> { - self.libs.get(soname).and_then(Option::as_ref) - } - pub fn tool(&self, name: &str) -> bool { - self.tools.get(name).copied().unwrap_or(false) - } -} - -/// `nvidia-smi --query-gpu=index,name,driver_version,memory.total,memory.free,compute_cap --format=csv,noheader,nounits`. -/// A missing or "[N/A]" compute capability falls back to a name table so older drivers still classify. -pub fn parse_nvidia_smi(csv: &str) -> Vec { - csv.lines() - .filter_map(|line| { - let fields: Vec<&str> = line.split(',').map(str::trim).collect(); - if fields.len() < 5 { - return None; - } - let index = fields[0].parse().ok()?; - let name = fields[1].to_owned(); - let sm = fields - .get(5) - .and_then(|cc| parse_compute_capability(cc)) - .or_else(|| sm_from_name(&name)); - Some(Gpu { - index, - driver: fields[2].to_owned(), - vram_total_mib: fields[3].parse().ok()?, - vram_free_mib: fields[4].parse().ok()?, - name, - sm, - }) - }) - .collect() -} - -pub fn parse_compute_capability(text: &str) -> Option { - let (major, minor) = text.trim().split_once('.')?; - let (major, minor): (u32, u32) = (major.parse().ok()?, minor.parse().ok()?); - (minor < 10).then_some(major * 10 + minor) -} - -fn sm_from_name(name: &str) -> Option { - const TABLE: [(&str, u32); 8] = [ - ("RTX 50", 120), - ("RTX 40", 89), - ("RTX 3090", 86), - ("RTX 30", 86), - ("RTX 20", 75), - ("A100", 80), - ("H100", 90), - ("L40", 89), - ]; - TABLE - .iter() - .find(|(needle, _)| name.contains(needle)) - .map(|(_, sm)| *sm) -} - -/// `/proc/meminfo` in bytes. `MemAvailable` is required; a kernel without it yields zeros (the caller fails closed). -pub fn parse_meminfo(text: &str) -> Memory { - let value = |key: &str| -> u64 { - text.lines() - .find_map(|line| line.strip_prefix(key)?.strip_prefix(':')) - .and_then(|rest| rest.split_whitespace().next()?.parse::().ok()) - .map_or(0, |kib| kib.saturating_mul(1024)) - }; - Memory { - total: value("MemTotal"), - available: value("MemAvailable"), - swap_total: value("SwapTotal"), - } -} - -/// WSL2 identifies itself in the kernel version string (`...-microsoft-standard-WSL2`). -pub fn is_wsl(proc_version: &str) -> bool { - let lower = proc_version.to_ascii_lowercase(); - lower.contains("microsoft") || lower.contains("wsl") -} - -/// `memory.max` content: a byte count, or `max` for unlimited. -pub fn parse_cgroup_max(text: &str) -> Option { - text.trim().parse().ok() -} - -/// File system type of the longest mount point that contains `path` (`/proc/mounts` format). -pub fn fs_type_for(mounts: &str, path: &Path) -> Option { - let mut best: Option<(usize, String)> = None; - for line in mounts.lines() { - let mut fields = line.split_whitespace(); - let (Some(_device), Some(mount), Some(kind)) = - (fields.next(), fields.next(), fields.next()) - else { - continue; - }; - let mount = mount.replace("\\040", " "); - let mount_path = Path::new(&mount); - if path.starts_with(mount_path) && best.as_ref().is_none_or(|(len, _)| mount.len() >= *len) - { - best = Some((mount.len(), kind.to_owned())); - } - } - best.map(|(_, kind)| kind) -} - -/// File system types that are a Windows drive or a network share seen from WSL: far too slow for mapped reads. -pub fn is_slow_foreign_fs(kind: &str) -> bool { - matches!( - kind, - "9p" | "drvfs" | "virtiofs" | "cifs" | "smb3" | "nfs" | "nfs4" | "fuse.sshfs" - ) -} - -/// First directory in `dirs` that holds a file called `soname`, or the `ldconfig -p` entry for it. -pub fn find_library(soname: &str, dirs: &[PathBuf], ldconfig: &str) -> Option { - for dir in dirs { - let candidate = dir.join(soname); - if candidate.exists() { - return Some(candidate); - } - } - ldconfig.lines().find_map(|line| { - let line = line.trim(); - let (name, rest) = line.split_once(" (")?; - if name.trim() != soname { - return None; - } - let path = rest.split_once("=>")?.1.trim(); - Some(PathBuf::from(path)) - }) -} - -/// Parse `KEY=VALUE` lines of an environment file (systemd `EnvironmentFile` subset: no export, `#` comments). -pub fn parse_env_file(text: &str) -> BTreeMap { - text.lines() - .filter_map(|line| { - let line = line.trim(); - if line.is_empty() || line.starts_with('#') { - return None; - } - let (key, value) = line.split_once('=')?; - let key = key.trim(); - if key.is_empty() || !key.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { - return None; - } - let value = value.trim(); - let value = value - .strip_prefix('"') - .and_then(|v| v.strip_suffix('"')) - .unwrap_or(value); - Some((key.to_owned(), value.to_owned())) - }) - .collect() -} - -/// What `probe` must look at beyond the machine itself. -#[derive(Clone, Debug, Default)] -pub struct ProbeRequest { - pub dirs: Vec<(String, PathBuf)>, - pub ports: Vec, - pub binary_dir: Option, - pub binaries: Vec, - pub extra_library_dirs: Vec, -} - -#[cfg(target_os = "linux")] -pub fn probe(request: &ProbeRequest) -> Facts { - linux::probe(request) -} - -#[cfg(not(target_os = "linux"))] -pub fn probe(_request: &ProbeRequest) -> Facts { - Facts { - os: std::env::consts::OS.to_owned(), - arch: std::env::consts::ARCH.to_owned(), - ..Facts::default() - } -} - -#[cfg(target_os = "linux")] -mod linux { - use super::*; - use std::{net::TcpListener, process::Command}; - - fn read(path: &str) -> String { - std::fs::read_to_string(path).unwrap_or_default() - } - - fn which(name: &str, extra: &[&str]) -> Option { - let path = std::env::var_os("PATH").unwrap_or_default(); - std::env::split_paths(&path) - .chain(extra.iter().map(PathBuf::from)) - .map(|dir| dir.join(name)) - .find(|candidate| candidate.is_file()) - } - - fn nearest_existing(path: &Path) -> PathBuf { - let mut current = path.to_path_buf(); - while !current.exists() { - if !current.pop() { - return PathBuf::from("/"); - } - } - current - } - - fn free_bytes(path: &Path) -> Option { - let stat = rustix::fs::statvfs(nearest_existing(path)).ok()?; - Some(stat.f_bavail.saturating_mul(stat.f_frsize)) - } - - fn memfd_works() -> bool { - use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, memfd_create}; - let Ok(fd) = memfd_create( - "leleka-preflight", - MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC, - ) else { - return false; - }; - fcntl_add_seals(&fd, SealFlags::SEAL).is_ok() - } - - pub fn probe(request: &ProbeRequest) -> Facts { - let mut facts = Facts { - os: std::env::consts::OS.to_owned(), - arch: std::env::consts::ARCH.to_owned(), - root: rustix::process::geteuid().is_root(), - hf_token_set: std::env::var_os("HF_TOKEN").is_some_and(|v| !v.is_empty()), - ..Facts::default() - }; - facts.wsl = is_wsl(&read("/proc/version")); - facts.memory = parse_meminfo(&read("/proc/meminfo")); - facts.cpu_cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32); - facts.cgroup_memory_max = parse_cgroup_max(&read("/sys/fs/cgroup/memory.max")); - facts.systemd_system = Path::new("/run/systemd/system").is_dir(); - facts.proc_fd = Path::new("/proc/self/fd").is_dir(); - facts.memfd_ok = memfd_works(); - - let smi = which( - "nvidia-smi", - &["/usr/lib/wsl/lib", "/usr/bin", "/usr/local/bin"], - ); - match smi { - None => { - facts.nvidia_smi_error = Some("nvidia-smi was not found in PATH".into()); - } - Some(smi) => { - facts.nvidia_smi_found = true; - match Command::new(smi) - .args([ - "--query-gpu=index,name,driver_version,memory.total,memory.free,compute_cap", - "--format=csv,noheader,nounits", - ]) - .output() - { - Ok(output) if output.status.success() => { - facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&output.stdout)); - } - Ok(output) => { - // compute_cap is unknown to old drivers: retry without it. - let retry = Command::new("nvidia-smi") - .args([ - "--query-gpu=index,name,driver_version,memory.total,memory.free", - "--format=csv,noheader,nounits", - ]) - .output(); - match retry { - Ok(second) if second.status.success() => { - facts.gpus = - parse_nvidia_smi(&String::from_utf8_lossy(&second.stdout)); - } - _ => { - let text = String::from_utf8_lossy(&output.stderr); - facts.nvidia_smi_error = - Some(text.lines().next().unwrap_or("nvidia-smi failed").to_owned()); - } - } - } - Err(error) => facts.nvidia_smi_error = Some(error.to_string()), - } - } - } - - let ldconfig = Command::new("ldconfig") - .arg("-p") - .output() - .map(|o| String::from_utf8_lossy(&o.stdout).into_owned()) - .unwrap_or_default(); - let mut library_dirs: Vec = request.extra_library_dirs.clone(); - if let Some(paths) = std::env::var_os("LD_LIBRARY_PATH") { - library_dirs - .extend(std::env::split_paths(&paths).filter(|p| !p.as_os_str().is_empty())); - } - for fixed in [ - "/usr/lib/wsl/lib", - "/usr/local/cuda/lib64", - "/usr/lib/x86_64-linux-gnu", - "/usr/lib64", - ] { - library_dirs.push(PathBuf::from(fixed)); - } - for soname in ["libcuda.so.1", "libcublas.so.12", "libcublasLt.so.12"] { - facts.libs.insert( - soname.to_owned(), - find_library(soname, &library_dirs, &ldconfig), - ); - } - - for tool in ["curl", "wget", "tar", "xz", "systemctl", "ldd"] { - facts.tools.insert( - tool.to_owned(), - which(tool, &["/usr/sbin", "/sbin"]).is_some(), - ); - } - - let mounts = read("/proc/mounts"); - for (key, path) in &request.dirs { - facts.dirs.insert( - key.clone(), - DirFact { - path: path.clone(), - free_bytes: free_bytes(path), - fs_type: fs_type_for(&mounts, &nearest_existing(path)), - }, - ); - } - for port in &request.ports { - if TcpListener::bind(("127.0.0.1", *port)).is_err() { - facts.busy_ports.push(*port); - } - } - if let Some(dir) = &request.binary_dir { - for name in &request.binaries { - facts - .binaries - .insert(name.clone(), is_executable(&dir.join(name))); - } - } - facts - } - - fn is_executable(path: &Path) -> bool { - use std::os::unix::fs::PermissionsExt; - path.metadata() - .is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn nvidia_smi_csv_for_server_and_laptop() { - let server = - parse_nvidia_smi("0, NVIDIA GeForce RTX 5090, 595.99.02, 32607, 32105, 12.0\n"); - assert_eq!(server.len(), 1); - assert_eq!(server[0].sm, Some(120)); - assert_eq!(server[0].driver_major(), Some(595)); - assert_eq!(server[0].vram_free_mib, 32105); - let laptop = - parse_nvidia_smi("0, NVIDIA GeForce RTX 3080 Laptop GPU, 617.42, 16384, 15234, 8.6\n"); - assert_eq!(laptop[0].sm, Some(86)); - assert_eq!(laptop[0].driver_major(), Some(617)); - } - - #[test] - fn missing_compute_capability_falls_back_to_the_name_table() { - let gpus = - parse_nvidia_smi("0, NVIDIA GeForce RTX 3080 Laptop GPU, 617.42, 16384, 15234\n"); - assert_eq!(gpus[0].sm, Some(86)); - let gpus = parse_nvidia_smi("0, NVIDIA GeForce RTX 5090, 595.99.02, 32607, 32105, [N/A]\n"); - assert_eq!(gpus[0].sm, Some(120)); - let gpus = parse_nvidia_smi("0, Mystery Board, 595.1, 8000, 8000, [N/A]\n"); - assert_eq!(gpus[0].sm, None); - assert!(parse_nvidia_smi("garbage\n\n").is_empty()); - } - - #[test] - fn meminfo_bytes() { - let memory = parse_meminfo( - "MemTotal: 24447308 kB\nMemFree: 1 kB\nMemAvailable: 22000000 kB\nSwapTotal: 2097152 kB\n", - ); - assert_eq!(memory.total, 24_447_308 * 1024); - assert_eq!(memory.available, 22_000_000 * 1024); - assert_eq!(memory.swap_total, 2_097_152 * 1024); - assert_eq!(parse_meminfo("nothing"), Memory::default()); - } - - #[test] - fn wsl_and_cgroup_detection() { - assert!(is_wsl( - "Linux version 5.15.167.4-microsoft-standard-WSL2 (root@x) (gcc)" - )); - assert!(!is_wsl( - "Linux version 7.0.0-38-generic (buildd@lcy02) (gcc)" - )); - assert_eq!(parse_cgroup_max("max\n"), None); - assert_eq!(parse_cgroup_max("68719476736\n"), Some(68_719_476_736)); - } - - #[test] - fn filesystem_type_uses_the_longest_mount_prefix() { - let mounts = - "/dev/sdc / ext4 rw 0 0\nC:\\134 /mnt/c 9p rw 0 0\n/dev/sdd /mnt/c/data ext4 rw 0 0\n"; - assert_eq!( - fs_type_for(mounts, Path::new("/mnt/c/Users/x")).as_deref(), - Some("9p") - ); - assert_eq!( - fs_type_for(mounts, Path::new("/mnt/c/data/models")).as_deref(), - Some("ext4") - ); - assert_eq!( - fs_type_for(mounts, Path::new("/home/x")).as_deref(), - Some("ext4") - ); - assert!(is_slow_foreign_fs("9p") && !is_slow_foreign_fs("ext4")); - } - - #[test] - fn library_lookup_prefers_directories_then_ldconfig() { - let ldconfig = "\tlibcublas.so.12 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libcublas.so.12\n\tlibcublasLt.so.13 (libc6,x86-64) => /usr/lib/libcublasLt.so.13\n"; - assert_eq!( - find_library("libcublas.so.12", &[], ldconfig), - Some(PathBuf::from("/usr/lib/x86_64-linux-gnu/libcublas.so.12")) - ); - assert_eq!(find_library("libcublasLt.so.12", &[], ldconfig), None); - } - - #[test] - fn env_file_parser_handles_comments_and_quotes() { - let env = parse_env_file( - "# c\nA=1\n B = \"two words\" \nbad key=3\nexport X=1\nLD_LIBRARY_PATH=/a:/b\n", - ); - assert_eq!(env.get("A").map(String::as_str), Some("1")); - assert_eq!(env.get("B").map(String::as_str), Some("two words")); - assert_eq!( - env.get("LD_LIBRARY_PATH").map(String::as_str), - Some("/a:/b") - ); - assert!(!env.contains_key("bad key")); - assert!(!env.contains_key("export X")); - } -} +//! Host facts for the preflight: pure parsers (unit-tested on any OS) and a Linux probe that fills `Facts`. +//! +//! `Facts` is plain data so that `preflight::evaluate` can be tested with synthetic hosts. Nothing here creates +//! a CUDA context; the GPU is read through `nvidia-smi`. +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, +}; + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Gpu { + pub index: u32, + pub name: String, + pub driver: String, + pub vram_total_mib: u64, + pub vram_free_mib: u64, + /// Compute capability times ten (12.0 -> 120, 8.6 -> 86). + pub sm: Option, +} + +impl Gpu { + pub fn driver_major(&self) -> Option { + self.driver.split('.').next()?.parse().ok() + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Memory { + pub total: u64, + pub available: u64, + pub swap_total: u64, +} + +/// What `probe` reads about one directory the deployment will write to. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DirFact { + pub path: PathBuf, + /// Free bytes of the file system that holds (or would hold) the directory. + pub free_bytes: Option, + /// File system type of the mount that holds it (`ext4`, `9p`, `drvfs`, ...). + pub fs_type: Option, +} + +#[derive(Clone, Debug, Default)] +pub struct Facts { + pub os: String, + pub arch: String, + pub root: bool, + pub nvidia_smi_found: bool, + pub nvidia_smi_error: Option, + pub gpus: Vec, + pub memory: Memory, + /// Logical CPUs this process may use (affinity and cgroup quota aware); 0 when unknown. + pub cpu_cores: u32, + /// `memory.max` of the cgroup this process runs in, when limited. + pub cgroup_memory_max: Option, + pub wsl: bool, + pub systemd_system: bool, + pub proc_fd: bool, + pub memfd_ok: bool, + pub libs: BTreeMap>, + pub tools: BTreeMap, + pub dirs: BTreeMap, + pub busy_ports: Vec, + pub binaries: BTreeMap, + pub hf_token_set: bool, +} + +impl Facts { + pub fn lib(&self, soname: &str) -> Option<&PathBuf> { + self.libs.get(soname).and_then(Option::as_ref) + } + pub fn tool(&self, name: &str) -> bool { + self.tools.get(name).copied().unwrap_or(false) + } +} + +/// `nvidia-smi --query-gpu=index,name,driver_version,memory.total,memory.free,compute_cap --format=csv,noheader,nounits`. +/// A missing or "[N/A]" compute capability falls back to a name table so older drivers still classify. +pub fn parse_nvidia_smi(csv: &str) -> Vec { + csv.lines() + .filter_map(|line| { + let fields: Vec<&str> = line.split(',').map(str::trim).collect(); + if fields.len() < 5 { + return None; + } + let index = fields[0].parse().ok()?; + let name = fields[1].to_owned(); + let sm = fields + .get(5) + .and_then(|cc| parse_compute_capability(cc)) + .or_else(|| sm_from_name(&name)); + Some(Gpu { + index, + driver: fields[2].to_owned(), + vram_total_mib: fields[3].parse().ok()?, + vram_free_mib: fields[4].parse().ok()?, + name, + sm, + }) + }) + .collect() +} + +pub fn parse_compute_capability(text: &str) -> Option { + let (major, minor) = text.trim().split_once('.')?; + let (major, minor): (u32, u32) = (major.parse().ok()?, minor.parse().ok()?); + (minor < 10).then_some(major * 10 + minor) +} + +fn sm_from_name(name: &str) -> Option { + const TABLE: [(&str, u32); 8] = [ + ("RTX 50", 120), + ("RTX 40", 89), + ("RTX 3090", 86), + ("RTX 30", 86), + ("RTX 20", 75), + ("A100", 80), + ("H100", 90), + ("L40", 89), + ]; + TABLE + .iter() + .find(|(needle, _)| name.contains(needle)) + .map(|(_, sm)| *sm) +} + +/// `/proc/meminfo` in bytes. `MemAvailable` is required; a kernel without it yields zeros (the caller fails closed). +pub fn parse_meminfo(text: &str) -> Memory { + let value = |key: &str| -> u64 { + text.lines() + .find_map(|line| line.strip_prefix(key)?.strip_prefix(':')) + .and_then(|rest| rest.split_whitespace().next()?.parse::().ok()) + .map_or(0, |kib| kib.saturating_mul(1024)) + }; + Memory { + total: value("MemTotal"), + available: value("MemAvailable"), + swap_total: value("SwapTotal"), + } +} + +/// WSL2 identifies itself in the kernel version string (`...-microsoft-standard-WSL2`). +pub fn is_wsl(proc_version: &str) -> bool { + let lower = proc_version.to_ascii_lowercase(); + lower.contains("microsoft") || lower.contains("wsl") +} + +/// `memory.max` content: a byte count, or `max` for unlimited. +pub fn parse_cgroup_max(text: &str) -> Option { + text.trim().parse().ok() +} + +/// File system type of the longest mount point that contains `path` (`/proc/mounts` format). +pub fn fs_type_for(mounts: &str, path: &Path) -> Option { + let mut best: Option<(usize, String)> = None; + for line in mounts.lines() { + let mut fields = line.split_whitespace(); + let (Some(_device), Some(mount), Some(kind)) = + (fields.next(), fields.next(), fields.next()) + else { + continue; + }; + let mount = mount.replace("\\040", " "); + let mount_path = Path::new(&mount); + if path.starts_with(mount_path) && best.as_ref().is_none_or(|(len, _)| mount.len() >= *len) + { + best = Some((mount.len(), kind.to_owned())); + } + } + best.map(|(_, kind)| kind) +} + +/// File system types that are a Windows drive or a network share seen from WSL: far too slow for mapped reads. +pub fn is_slow_foreign_fs(kind: &str) -> bool { + matches!( + kind, + "9p" | "drvfs" | "virtiofs" | "cifs" | "smb3" | "nfs" | "nfs4" | "fuse.sshfs" + ) +} + +/// First directory in `dirs` that holds a file called `soname`, or the `ldconfig -p` entry for it. +pub fn find_library(soname: &str, dirs: &[PathBuf], ldconfig: &str) -> Option { + for dir in dirs { + let candidate = dir.join(soname); + if candidate.exists() { + return Some(candidate); + } + } + ldconfig.lines().find_map(|line| { + let line = line.trim(); + let (name, rest) = line.split_once(" (")?; + if name.trim() != soname { + return None; + } + let path = rest.split_once("=>")?.1.trim(); + Some(PathBuf::from(path)) + }) +} + +/// Parse `KEY=VALUE` lines of an environment file (systemd `EnvironmentFile` subset: no export, `#` comments). +pub fn parse_env_file(text: &str) -> BTreeMap { + text.lines() + .filter_map(|line| { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + return None; + } + let (key, value) = line.split_once('=')?; + let key = key.trim(); + if key.is_empty() || !key.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { + return None; + } + let value = value.trim(); + let value = value + .strip_prefix('"') + .and_then(|v| v.strip_suffix('"')) + .unwrap_or(value); + Some((key.to_owned(), value.to_owned())) + }) + .collect() +} + +/// What `probe` must look at beyond the machine itself. +#[derive(Clone, Debug, Default)] +pub struct ProbeRequest { + pub dirs: Vec<(String, PathBuf)>, + pub ports: Vec, + pub binary_dir: Option, + pub binaries: Vec, + pub extra_library_dirs: Vec, +} + +#[cfg(target_os = "linux")] +pub fn probe(request: &ProbeRequest) -> Facts { + linux::probe(request) +} + +#[cfg(not(target_os = "linux"))] +pub fn probe(_request: &ProbeRequest) -> Facts { + Facts { + os: std::env::consts::OS.to_owned(), + arch: std::env::consts::ARCH.to_owned(), + ..Facts::default() + } +} + +#[cfg(target_os = "linux")] +mod linux { + use super::*; + use std::{net::TcpListener, process::Command}; + + fn read(path: &str) -> String { + std::fs::read_to_string(path).unwrap_or_default() + } + + fn which(name: &str, extra: &[&str]) -> Option { + let path = std::env::var_os("PATH").unwrap_or_default(); + std::env::split_paths(&path) + .chain(extra.iter().map(PathBuf::from)) + .map(|dir| dir.join(name)) + .find(|candidate| candidate.is_file()) + } + + fn nearest_existing(path: &Path) -> PathBuf { + let mut current = path.to_path_buf(); + while !current.exists() { + if !current.pop() { + return PathBuf::from("/"); + } + } + current + } + + fn free_bytes(path: &Path) -> Option { + let stat = rustix::fs::statvfs(nearest_existing(path)).ok()?; + Some(stat.f_bavail.saturating_mul(stat.f_frsize)) + } + + fn memfd_works() -> bool { + use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, memfd_create}; + let Ok(fd) = memfd_create( + "leleka-preflight", + MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC, + ) else { + return false; + }; + fcntl_add_seals(&fd, SealFlags::SEAL).is_ok() + } + + pub fn probe(request: &ProbeRequest) -> Facts { + let mut facts = Facts { + os: std::env::consts::OS.to_owned(), + arch: std::env::consts::ARCH.to_owned(), + root: rustix::process::geteuid().is_root(), + hf_token_set: std::env::var_os("HF_TOKEN").is_some_and(|v| !v.is_empty()), + ..Facts::default() + }; + facts.wsl = is_wsl(&read("/proc/version")); + facts.memory = parse_meminfo(&read("/proc/meminfo")); + facts.cpu_cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32); + facts.cgroup_memory_max = parse_cgroup_max(&read("/sys/fs/cgroup/memory.max")); + facts.systemd_system = Path::new("/run/systemd/system").is_dir(); + facts.proc_fd = Path::new("/proc/self/fd").is_dir(); + facts.memfd_ok = memfd_works(); + + let smi = which( + "nvidia-smi", + &["/usr/lib/wsl/lib", "/usr/bin", "/usr/local/bin"], + ); + match smi { + None => { + facts.nvidia_smi_error = Some("nvidia-smi was not found in PATH".into()); + } + Some(smi) => { + facts.nvidia_smi_found = true; + match Command::new(smi) + .args([ + "--query-gpu=index,name,driver_version,memory.total,memory.free,compute_cap", + "--format=csv,noheader,nounits", + ]) + .output() + { + Ok(output) if output.status.success() => { + facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&output.stdout)); + } + Ok(output) => { + // compute_cap is unknown to old drivers: retry without it. + let retry = Command::new("nvidia-smi") + .args([ + "--query-gpu=index,name,driver_version,memory.total,memory.free", + "--format=csv,noheader,nounits", + ]) + .output(); + match retry { + Ok(second) if second.status.success() => { + facts.gpus = + parse_nvidia_smi(&String::from_utf8_lossy(&second.stdout)); + } + _ => { + let text = String::from_utf8_lossy(&output.stderr); + facts.nvidia_smi_error = + Some(text.lines().next().unwrap_or("nvidia-smi failed").to_owned()); + } + } + } + Err(error) => facts.nvidia_smi_error = Some(error.to_string()), + } + } + } + + let ldconfig = Command::new("ldconfig") + .arg("-p") + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).into_owned()) + .unwrap_or_default(); + let mut library_dirs: Vec = request.extra_library_dirs.clone(); + if let Some(paths) = std::env::var_os("LD_LIBRARY_PATH") { + library_dirs + .extend(std::env::split_paths(&paths).filter(|p| !p.as_os_str().is_empty())); + } + for fixed in [ + "/usr/lib/wsl/lib", + "/usr/local/cuda/lib64", + "/usr/lib/x86_64-linux-gnu", + "/usr/lib64", + ] { + library_dirs.push(PathBuf::from(fixed)); + } + for soname in ["libcuda.so.1", "libcublas.so.12", "libcublasLt.so.12"] { + facts.libs.insert( + soname.to_owned(), + find_library(soname, &library_dirs, &ldconfig), + ); + } + + for tool in ["curl", "wget", "tar", "xz", "systemctl", "ldd"] { + facts.tools.insert( + tool.to_owned(), + which(tool, &["/usr/sbin", "/sbin"]).is_some(), + ); + } + + let mounts = read("/proc/mounts"); + for (key, path) in &request.dirs { + facts.dirs.insert( + key.clone(), + DirFact { + path: path.clone(), + free_bytes: free_bytes(path), + fs_type: fs_type_for(&mounts, &nearest_existing(path)), + }, + ); + } + for port in &request.ports { + if TcpListener::bind(("127.0.0.1", *port)).is_err() { + facts.busy_ports.push(*port); + } + } + if let Some(dir) = &request.binary_dir { + for name in &request.binaries { + facts + .binaries + .insert(name.clone(), is_executable(&dir.join(name))); + } + } + facts + } + + fn is_executable(path: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + path.metadata() + .is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nvidia_smi_csv_for_server_and_laptop() { + let server = + parse_nvidia_smi("0, NVIDIA GeForce RTX 5090, 595.99.02, 32607, 32105, 12.0\n"); + assert_eq!(server.len(), 1); + assert_eq!(server[0].sm, Some(120)); + assert_eq!(server[0].driver_major(), Some(595)); + assert_eq!(server[0].vram_free_mib, 32105); + let laptop = + parse_nvidia_smi("0, NVIDIA GeForce RTX 3080 Laptop GPU, 617.42, 16384, 15234, 8.6\n"); + assert_eq!(laptop[0].sm, Some(86)); + assert_eq!(laptop[0].driver_major(), Some(617)); + } + + #[test] + fn missing_compute_capability_falls_back_to_the_name_table() { + let gpus = + parse_nvidia_smi("0, NVIDIA GeForce RTX 3080 Laptop GPU, 617.42, 16384, 15234\n"); + assert_eq!(gpus[0].sm, Some(86)); + let gpus = parse_nvidia_smi("0, NVIDIA GeForce RTX 5090, 595.99.02, 32607, 32105, [N/A]\n"); + assert_eq!(gpus[0].sm, Some(120)); + let gpus = parse_nvidia_smi("0, Mystery Board, 595.1, 8000, 8000, [N/A]\n"); + assert_eq!(gpus[0].sm, None); + assert!(parse_nvidia_smi("garbage\n\n").is_empty()); + } + + #[test] + fn meminfo_bytes() { + let memory = parse_meminfo( + "MemTotal: 24447308 kB\nMemFree: 1 kB\nMemAvailable: 22000000 kB\nSwapTotal: 2097152 kB\n", + ); + assert_eq!(memory.total, 24_447_308 * 1024); + assert_eq!(memory.available, 22_000_000 * 1024); + assert_eq!(memory.swap_total, 2_097_152 * 1024); + assert_eq!(parse_meminfo("nothing"), Memory::default()); + } + + #[test] + fn wsl_and_cgroup_detection() { + assert!(is_wsl( + "Linux version 5.15.167.4-microsoft-standard-WSL2 (root@x) (gcc)" + )); + assert!(!is_wsl( + "Linux version 7.0.0-38-generic (buildd@lcy02) (gcc)" + )); + assert_eq!(parse_cgroup_max("max\n"), None); + assert_eq!(parse_cgroup_max("68719476736\n"), Some(68_719_476_736)); + } + + #[test] + fn filesystem_type_uses_the_longest_mount_prefix() { + let mounts = + "/dev/sdc / ext4 rw 0 0\nC:\\134 /mnt/c 9p rw 0 0\n/dev/sdd /mnt/c/data ext4 rw 0 0\n"; + assert_eq!( + fs_type_for(mounts, Path::new("/mnt/c/Users/x")).as_deref(), + Some("9p") + ); + assert_eq!( + fs_type_for(mounts, Path::new("/mnt/c/data/models")).as_deref(), + Some("ext4") + ); + assert_eq!( + fs_type_for(mounts, Path::new("/home/x")).as_deref(), + Some("ext4") + ); + assert!(is_slow_foreign_fs("9p") && !is_slow_foreign_fs("ext4")); + } + + #[test] + fn library_lookup_prefers_directories_then_ldconfig() { + let ldconfig = "\tlibcublas.so.12 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libcublas.so.12\n\tlibcublasLt.so.13 (libc6,x86-64) => /usr/lib/libcublasLt.so.13\n"; + assert_eq!( + find_library("libcublas.so.12", &[], ldconfig), + Some(PathBuf::from("/usr/lib/x86_64-linux-gnu/libcublas.so.12")) + ); + assert_eq!(find_library("libcublasLt.so.12", &[], ldconfig), None); + } + + #[test] + fn env_file_parser_handles_comments_and_quotes() { + let env = parse_env_file( + "# c\nA=1\n B = \"two words\" \nbad key=3\nexport X=1\nLD_LIBRARY_PATH=/a:/b\n", + ); + assert_eq!(env.get("A").map(String::as_str), Some("1")); + assert_eq!(env.get("B").map(String::as_str), Some("two words")); + assert_eq!( + env.get("LD_LIBRARY_PATH").map(String::as_str), + Some("/a:/b") + ); + assert!(!env.contains_key("bad key")); + assert!(!env.contains_key("export X")); + } +} diff --git a/crates/deploy/src/lib.rs b/crates/deploy/src/lib.rs index ac3fe73f..024b387c 100644 --- a/crates/deploy/src/lib.rs +++ b/crates/deploy/src/lib.rs @@ -1,20 +1,20 @@ -//! `leleka`: deploy and run the Leleka runtime (engine + gateway + API) with one command. -//! -//! No Python, no shell glue at run time: `leleka up` preflights the host, fetches and verifies the model, builds the -//! KAR archive, installs the binaries, writes the configuration, starts the service and waits for readiness; -//! `leleka run` is the supervisor that the systemd unit (or a terminal) executes. See `docs/deploy.md`. -pub mod app; -pub mod cli; -pub mod config; -pub mod facts; -pub mod http; -pub mod layout; -pub mod manifest; -pub mod plan; -pub mod preflight; -pub mod profile; -pub mod resources; -pub mod sealed; -pub mod steps; -pub mod supervisor; -pub mod units; +//! `leleka`: deploy and run the Leleka runtime (engine + gateway + API) with one command. +//! +//! No Python, no shell glue at run time: `leleka up` preflights the host, fetches and verifies the model, builds the +//! KAR archive, installs the binaries, writes the configuration, starts the service and waits for readiness; +//! `leleka run` is the supervisor that the systemd unit (or a terminal) executes. See `docs/deploy.md`. +pub mod app; +pub mod cli; +pub mod config; +pub mod facts; +pub mod http; +pub mod layout; +pub mod manifest; +pub mod plan; +pub mod preflight; +pub mod profile; +pub mod resources; +pub mod sealed; +pub mod steps; +pub mod supervisor; +pub mod units; diff --git a/crates/deploy/src/plan.rs b/crates/deploy/src/plan.rs index a5018360..d6d3f87a 100644 --- a/crates/deploy/src/plan.rs +++ b/crates/deploy/src/plan.rs @@ -1,1140 +1,1140 @@ -//! The deployment plan: what `up` would do, derived from what is already on the machine. -//! -//! `gather` reads the host (no writes, no hashing of model files, no network). `plan_steps` is pure over the -//! gathered state, so a fresh machine, a half-finished run and a finished deployment are all unit-tested. -//! `--dry-run` prints this plan; execution (`steps.rs`) walks the same list and runs only the `Todo` entries, -//! which is what makes a re-run idempotent and a crashed run resumable. -use crate::{ - cli::{ModeChoice, UpOptions}, - config::{KarArg, RunConfig}, - facts::{Facts, ProbeRequest, probe}, - layout::{BINARIES, MANIFEST, MTP_FILES, Paths, missing_asset_bytes}, - manifest::Manifest, - preflight::{ExpertProfileState, Needs, Report, evaluate}, - profile::{ARCHIVE_BYTES, KarSource, Profile, resolve}, - units::UnitScope, -}; -use serde::Serialize; -use std::{ - collections::BTreeMap, - path::{Path, PathBuf}, -}; - -pub const CUBLAS_VERSION: &str = "12.9.1.4"; -pub const CUBLAS_URL: &str = "https://developer.download.nvidia.com/compute/cuda/redist/libcublas/linux-x86_64/libcublas-linux-x86_64-12.9.1.4-archive.tar.xz"; -pub const CUBLAS_SHA256: &str = "546addc4a9d82b8f23aa9ba9274b6bc0429a63008a31c759884ac24880796057"; -pub const CUBLAS_BYTES: u64 = 933_611_504; -pub const EXPERT_PROFILE_SHA256: &str = - "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf"; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] -#[serde(rename_all = "lowercase")] -pub enum Mode { - Systemd(UnitScopeTag), - Foreground, - /// Prepare everything, start nothing. - None, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] -#[serde(rename_all = "lowercase")] -pub enum UnitScopeTag { - System, - User, -} - -impl UnitScopeTag { - pub fn scope(self) -> UnitScope { - match self { - UnitScopeTag::System => UnitScope::System, - UnitScopeTag::User => UnitScope::User, - } - } -} - -impl Mode { - pub fn label(self) -> &'static str { - match self { - Mode::Systemd(UnitScopeTag::System) => "systemd (system unit)", - Mode::Systemd(UnitScopeTag::User) => "systemd (user unit)", - Mode::Foreground => "foreground", - Mode::None => "prepare only", - } - } -} - -/// `--mode auto`: root with systemd gets a system unit, a user with a systemd user session a user unit, everything -/// else (WSL without systemd, containers) runs in the foreground. -pub fn resolve_mode(choice: ModeChoice, facts: &Facts, user_session: bool) -> Mode { - match choice { - ModeChoice::System => Mode::Systemd(UnitScopeTag::System), - ModeChoice::User => Mode::Systemd(UnitScopeTag::User), - ModeChoice::Foreground => Mode::Foreground, - ModeChoice::None => Mode::None, - ModeChoice::Auto => { - if facts.systemd_system && facts.tool("systemctl") { - if facts.root { - Mode::Systemd(UnitScopeTag::System) - } else if user_session { - Mode::Systemd(UnitScopeTag::User) - } else { - Mode::Foreground - } - } else { - Mode::Foreground - } - } - } -} - -#[derive(Debug)] -pub struct Context { - pub opts: UpOptions, - pub facts: Facts, - pub paths: Paths, - pub bin_src: PathBuf, - pub manifest: Option>, - pub profile: Result, - pub mode: Mode, - pub service_user: String, - pub config: Option, - pub report: Option, - pub needs: Needs, -} - -fn current_bin_dir() -> PathBuf { - std::env::current_exe() - .ok() - .and_then(|exe| exe.parent().map(Path::to_path_buf)) - .unwrap_or_else(|| PathBuf::from(".")) -} - -pub fn expert_profile_state(profile: &Profile, assets: &Path) -> Option { - let relative = profile.expert_profile.as_ref()?; - let path = assets.join(relative); - let Ok(bytes) = std::fs::read(&path) else { - return Some(ExpertProfileState::Absent); - }; - if bytes.len() > 16 << 20 { - return Some(ExpertProfileState::WrongDigest); - } - let expected = profile - .expert_profile_sha256 - .as_deref() - .unwrap_or(EXPERT_PROFILE_SHA256); - Some(if sha256_hex(&bytes) == expected { - ExpertProfileState::Valid - } else { - ExpertProfileState::WrongDigest - }) -} - -pub fn sha256_hex(bytes: &[u8]) -> String { - use sha2::{Digest, Sha256}; - hex::encode(Sha256::digest(bytes)) -} - -/// Is the supervisor of this state directory alive? (`run/status.json` names its pid.) -pub fn service_running(paths: &Paths) -> bool { - let Ok(text) = std::fs::read_to_string(paths.status_file()) else { - return false; - }; - let Ok(value) = serde_json::from_str::(&text) else { - return false; - }; - let pid = value.get("supervisor_pid").and_then(|v| v.as_u64()); - let phase = value.get("phase").and_then(|v| v.as_str()).unwrap_or(""); - matches!(pid, Some(pid) if Path::new(&format!("/proc/{pid}")).exists()) - && !matches!(phase, "stopped" | "failed") -} - -fn user_session_available(var: &dyn Fn(&str) -> Option) -> bool { - var("XDG_RUNTIME_DIR").is_some_and(|dir| Path::new(&dir).join("systemd").exists()) -} - -pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option) -> Context { - let paths = opts.dirs.paths(); - let bin_src = opts.bin_src.clone().unwrap_or_else(current_bin_dir); - let installed = paths.bin_dir(); - // Probe the source of the binaries, or the installed copy when the source has none (re-run after install). - let binary_dir = if BINARIES.iter().all(|b| bin_src.join(b).is_file()) { - bin_src.clone() - } else { - installed.clone() - }; - let mut extra_library_dirs: Vec = Vec::new(); - if let Some(dir) = &opts.cublas_dir { - extra_library_dirs.push(dir.clone()); - } else { - extra_library_dirs.push(paths.cublas_dir()); - } - let ports: Vec = [&opts.ports.api, &opts.ports.engine, &opts.ports.daemon] - .iter() - .filter_map(|p| p.rsplit(':').next()?.parse().ok()) - .collect(); - let request = ProbeRequest { - dirs: vec![ - ("assets".into(), opts.dirs.assets.clone()), - ("state".into(), opts.dirs.state.clone()), - ("prefix".into(), opts.dirs.prefix.clone()), - ], - ports, - binary_dir: Some(binary_dir.clone()), - binaries: BINARIES.iter().map(|b| b.to_string()).collect(), - extra_library_dirs, - }; - let facts = probe(&request); - let manifest = Manifest::find(&binary_dir); - let gpu = facts.gpus.iter().find(|g| g.index == opts.gpu); - let mut profile = resolve(opts.profile.as_deref(), gpu); - if let Ok(p) = &mut profile { - if let Some(gib) = opts.gpu_budget_gib { - p.gpu_budget_bytes = gib << 30; - } - if let Some(tokens) = opts.context_tokens { - p.context_tokens = tokens; - } - if let Err(message) = p.validate() { - profile = Err(message); - } - } - let choice = if opts.kar_fd.is_some() && opts.mode == ModeChoice::Auto { - ModeChoice::Foreground - } else { - opts.mode - }; - let mode = resolve_mode(choice, &facts, user_session_available(var)); - let service_user = if matches!(mode, Mode::Systemd(UnitScopeTag::System)) { - opts.service_user - .clone() - .unwrap_or_else(|| "leleka".to_owned()) - } else { - var("USER") - .or_else(|| var("LOGNAME")) - .unwrap_or_else(|| "root".to_owned()) - }; - let (shards, kar) = missing_asset_bytes(&paths); - let installed_same_dir = same_dir(&bin_src, &installed); - let mut needs = Needs { - gpu_index: opts.gpu, - assets_dir: opts.dirs.assets.clone(), - state_dir: opts.dirs.state.clone(), - prefix_dir: opts.dirs.prefix.clone(), - shard_bytes_missing: if opts.fetch { shards } else { 0 }, - kar_bytes_missing: if opts.fetch { kar } else { 0 }, - install_binaries: !installed_same_dir, - may_install_cublas: opts.install_cublas && opts.cublas_dir.is_none(), - cublas_download_bytes: CUBLAS_BYTES, - wants_systemd: matches!(mode, Mode::Systemd(_)), - service_ports: vec![ - ("api".into(), port_of(&opts.ports.api)), - ("engine".into(), port_of(&opts.ports.engine)), - ("gateway".into(), port_of(&opts.ports.daemon)), - ], - require_binaries: true, - binary_has_sm86: manifest - .as_ref() - .and_then(|m| m.as_ref().ok()) - .map(Manifest::has_sm86), - service_running: service_running(&paths), - kar_fd_inherited: opts.kar_fd.is_some(), - api_bind_open: crate::config::probe_address(&opts.ports.api) - .is_some_and(|a| !a.ip().is_loopback()), - expert_profile: None, - resources: None, - }; - let (config, report) = match &mut profile { - Ok(p) => { - needs.expert_profile = expert_profile_state(p, &opts.dirs.assets); - let mut engine_env = BTreeMap::new(); - let resources = crate::resources::compute(&facts, gpu, p, opts.preset); - crate::resources::apply(&resources, p, &mut engine_env, opts.gpu_budget_gib.is_some()); - needs.resources = Some(resources); - if needs.expert_profile == Some(ExpertProfileState::Valid) - && let Some(relative) = &p.expert_profile - { - engine_env.insert( - "LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS".to_owned(), - "auto".to_owned(), - ); - engine_env.insert( - "LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE".to_owned(), - opts.dirs.assets.join(relative).display().to_string(), - ); - } - let mut config = RunConfig::new( - &opts.dirs, - opts.ports.clone(), - opts.gpu, - p.clone(), - engine_env, - ); - config.preset = opts.preset; - let report = evaluate(&facts, p, &needs); - (Some(config), Some(report)) - } - Err(_) => (None, None), - }; - Context { - opts: opts.clone(), - facts, - paths, - bin_src, - manifest, - profile, - mode, - service_user, - config, - report, - needs, - } -} - -fn port_of(address: &str) -> u16 { - address - .rsplit(':') - .next() - .and_then(|p| p.parse().ok()) - .unwrap_or(0) -} - -fn same_dir(a: &Path, b: &Path) -> bool { - match (a.canonicalize(), b.canonicalize()) { - (Ok(a), Ok(b)) => a == b, - _ => a == b, - } -} - -/// What exists on disk now, reduced to the facts the plan needs. -#[derive(Clone, Debug, Default)] -pub struct FsState { - pub dirs_exist: bool, - pub binaries_current: bool, - pub binaries_source_ok: bool, - pub cublas_ready: bool, - pub secrets_present: bool, - pub shards_stamp_ok: bool, - pub kar_stamp_ok: bool, - /// The archive file has the pinned length and its provenance sidecar exists. - pub kar_present: bool, - pub mtp_present: bool, - pub tokenizer_present: bool, - pub configs_current: bool, - pub unit_current: bool, - pub service_ready: bool, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize)] -#[serde(tag = "state", content = "why", rename_all = "lowercase")] -pub enum StepState { - Done(String), - Todo(String), - Skip(String), - Blocked(String), -} - -impl StepState { - pub fn tag(&self) -> &'static str { - match self { - StepState::Done(_) => "done", - StepState::Todo(_) => "todo", - StepState::Skip(_) => "skip", - StepState::Blocked(_) => "BLOCKED", - } - } - pub fn why(&self) -> &str { - match self { - StepState::Done(s) - | StepState::Todo(s) - | StepState::Skip(s) - | StepState::Blocked(s) => s, - } - } -} - -#[derive(Clone, Debug, Serialize)] -pub struct Step { - pub id: &'static str, - pub title: String, - #[serde(flatten)] - pub state: StepState, - pub commands: Vec, -} - -fn step(id: &'static str, title: &str, state: StepState, commands: Vec) -> Step { - Step { - id, - title: title.to_owned(), - state, - commands, - } -} - -pub fn plan_steps(ctx: &Context, fs: &FsState) -> Vec { - let paths = &ctx.paths; - let opts = &ctx.opts; - let sn = paths.bin("strata-next").display().to_string(); - let manifest_name = MANIFEST; - let mut steps = Vec::new(); - - let pre_state = match &ctx.report { - Some(report) if report.failed() => StepState::Blocked(format!( - "{} check(s) failed", - report.count(crate::preflight::Level::Fail) - )), - Some(report) => StepState::Todo(format!( - "{} warning(s)", - report.count(crate::preflight::Level::Warn) - )), - None => StepState::Blocked(ctx.profile.as_ref().err().cloned().unwrap_or_default()), - }; - steps.push(step( - "preflight", - "host checks", - pre_state, - vec!["nvidia-smi, /proc/meminfo, statvfs, ldconfig, memfd_create".into()], - )); - - steps.push(step( - "layout", - "create directories", - if fs.dirs_exist { - StepState::Done("present".into()) - } else { - StepState::Todo("create state (0700), logs, run, stamps, assets".into()) - }, - vec![format!( - "mkdir -p {} {} {}", - opts.dirs.prefix.display(), - opts.dirs.state.display(), - opts.dirs.assets.display() - )], - )); - - steps.push(step( - "binaries", - "install the six runtime binaries", - if !fs.binaries_source_ok { - StepState::Blocked(format!( - "not all of {} are in {} or {}", - BINARIES.join(", "), - ctx.bin_src.display(), - paths.bin_dir().display() - )) - } else if fs.binaries_current { - StepState::Done(format!("{} is current", paths.bin_dir().display())) - } else { - StepState::Todo(format!( - "copy from {} (SHA-256 checked against MANIFEST.json when present)", - ctx.bin_src.display() - )) - }, - vec![format!( - "install {{{}}} -> {}", - BINARIES.join(","), - paths.bin_dir().display() - )], - )); - - let cublas_cmd = vec![ - format!("curl -fL -C - {CUBLAS_URL} (sha256 {CUBLAS_SHA256})"), - format!( - "tar -xJf libcublas-{CUBLAS_VERSION}.tar.xz -> {}", - paths.cublas_dir().display() - ), - ]; - steps.push(step( - "cublas", - "CUDA 12 cuBLAS for the PLE batch GEMM", - if fs.cublas_ready { - StepState::Done("libcublas.so.12 and libcublasLt.so.12 found".into()) - } else if opts.cublas_dir.is_some() { - StepState::Blocked( - "--cublas-dir does not contain libcublas.so.12 and libcublasLt.so.12".into(), - ) - } else if opts.install_cublas { - StepState::Todo(format!( - "download the pinned {CUBLAS_VERSION} redistributable ({} MiB)", - CUBLAS_BYTES >> 20 - )) - } else { - StepState::Blocked("missing and --no-install-cublas was given".into()) - }, - cublas_cmd, - )); - - steps.push(step( - "secrets", - "service tokens and API key", - if fs.secrets_present { - StepState::Done("runtime.env and api-key exist (never rotated)".into()) - } else { - StepState::Todo("generate two tokens (0600) and run `strata-next api-key init`".into()) - }, - vec![format!( - "{sn} api-key init --file {}", - paths.api_key().display() - )], - )); - - let trusted = opts.trust_archive && fs.kar_present; - let kar_state = if fs.kar_stamp_ok && !opts.reverify { - StepState::Done(format!("{} bytes, verified earlier", ARCHIVE_BYTES)) - } else if trusted { - StepState::Todo( - "accept the existing archive without the strict re-derivation (--trust-archive); the engine verifies its SHA-256 and every CRC at each load" - .into(), - ) - } else if !opts.fetch { - StepState::Blocked("--no-fetch given but the archive is missing or unverified".into()) - } else { - StepState::Todo( - "build the level-2 KAR archive (bounded memory, hours on a first run) or re-verify the existing one (strict, tens of minutes), then stamp it" - .into(), - ) - }; - let kar_runs_tool = matches!(kar_state, StepState::Todo(_)) && !trusted; - - let model_cmds = vec![ - format!( - "{sn} model fetch {manifest_name} --output {}", - paths.model_dir().display() - ), - format!( - "{sn} model verify {manifest_name} --output {}", - paths.model_dir().display() - ), - ]; - steps.push(step( - "model", - "fetch and verify the two IQ3_S GGUF shards", - if fs.shards_stamp_ok && !opts.reverify { - StepState::Done( - "verified earlier; sizes and mtimes unchanged (--reverify hashes again)".into(), - ) - } else if kar_runs_tool { - StepState::Todo( - "downloaded and verified inside the archive step (ensure-sharded-streamed fetches and verifies the shards first)" - .into(), - ) - } else if !opts.fetch { - if fs.shards_stamp_ok { - StepState::Todo("--no-fetch: verify only".into()) - } else { - StepState::Blocked( - "--no-fetch given but the shards are not verified yet; run without --no-fetch" - .into(), - ) - } - } else { - StepState::Todo(format!( - "{} still to download; resumable, SHA-256 of 83.6 GB", - gib_text(ctx.needs.shard_bytes_missing) - )) - }, - model_cmds, - )); - - let kar_cmd = vec![format!( - "{sn} model ensure-sharded-streamed {manifest_name} --source-dir {} --output {} --levels 2", - paths.model_dir().display(), - paths.kar().display() - )]; - steps.push(step( - "kar", - "KAR level-2 archive (+ provenance)", - kar_state, - kar_cmd, - )); - - steps.push(step( - "mtp-pack", - "MTP draft pack (data/mtp-rt)", - if let Some(src) = &opts.mtp_pack { - if fs.mtp_present { StepState::Done("present; --mtp-pack ignored".into()) } else { StepState::Todo(format!("import from {}", src.display())) } - } else if fs.mtp_present { - StepState::Done(format!("{} present", paths.mtp_pack().display())) - } else { - StepState::Blocked(format!("{} is missing and no --mtp-pack was given; the pack ({}) has no automated producer yet", paths.mtp_pack().display(), MTP_FILES.join(", "))) - }, - vec![format!("copy/unpack -> {}", paths.mtp_pack().display())], - )); - - steps.push(step( - "tokenizer", - "tokenizer assets for the API", - if fs.tokenizer_present { - StepState::Done("present".into()) - } else { - StepState::Todo("extract from shard 1".into()) - }, - vec![format!( - "{sn} model extract-tokenizer {} --output {}", - paths.shard(0).display(), - paths.tokenizer_root().display() - )], - )); - - steps.push(step( - "config", - "run configuration, gateway and API configs, environment file", - if fs.configs_current { - StepState::Done("up to date".into()) - } else { - StepState::Todo( - "write leleka.json, daemon.json, strata.json, profile.json, runtime.env".into(), - ) - }, - vec![format!( - "write {}/{{leleka,daemon,strata,profile}}.json runtime.env", - opts.dirs.state.display() - )], - )); - - match ctx.mode { - Mode::Systemd(scope) => { - steps.push(step( - "service", - "systemd unit", - if fs.unit_current { - StepState::Done("installed and enabled".into()) - } else { - StepState::Todo(format!( - "write {} unit, daemon-reload, enable", - if scope == UnitScopeTag::System { - "system" - } else { - "user" - } - )) - }, - vec![format!( - "systemctl {}enable {}", - if scope == UnitScopeTag::User { - "--user " - } else { - "" - }, - paths.unit_name() - )], - )); - steps.push(step( - "start", - "start the service", - if fs.service_ready { - StepState::Done("already ready".into()) - } else { - StepState::Todo( - "systemctl start (first start copies the archive and loads the model)" - .into(), - ) - }, - vec![format!( - "systemctl {}start {}", - if scope == UnitScopeTag::User { - "--user " - } else { - "" - }, - paths.unit_name() - )], - )); - } - Mode::Foreground => { - steps.push(step( - "service", - "systemd unit", - StepState::Skip("foreground mode".into()), - vec![], - )); - steps.push(step( - "start", - "run the supervisor in this terminal", - if fs.service_ready { - StepState::Done("a supervisor is already ready".into()) - } else { - StepState::Todo("leleka run (Ctrl-C drains and stops)".into()) - }, - vec![format!( - "{} run --config {}", - paths.bin("leleka").display(), - paths.run_config().display() - )], - )); - } - Mode::None => { - steps.push(step( - "service", - "systemd unit", - StepState::Skip("--mode none".into()), - vec![], - )); - steps.push(step( - "start", - "start the service", - StepState::Skip("--mode none".into()), - vec![], - )); - } - } - steps.push(step( - "ready", - "wait for readiness", - if matches!(ctx.mode, Mode::None) { - StepState::Skip("--mode none".into()) - } else if fs.service_ready { - StepState::Done("ready".into()) - } else { - StepState::Todo(format!( - "poll {} /ready for up to {} s", - opts.ports.api, opts.timeout_s - )) - }, - vec![format!("GET http://{}/ready", opts.ports.api)], - )); - steps -} - -fn gib_text(bytes: u64) -> String { - format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64) -} - -/// A human rendering of the plan, with the engine command the service will run. -pub fn render_plan(ctx: &Context, steps: &[Step]) -> String { - let mut out = String::new(); - out.push_str("plan:\n"); - for (index, step) in steps.iter().enumerate() { - out.push_str(&format!( - " {:>2}. [{:7}] {} - {}\n", - index + 1, - step.state.tag(), - step.title, - step.state.why() - )); - if matches!(step.state, StepState::Todo(_) | StepState::Blocked(_)) { - for command in &step.commands { - out.push_str(&format!(" $ {command}\n")); - } - } - } - if let Some(config) = &ctx.config { - let kar = match config.profile.kar_source { - KarSource::Memfd => KarArg::Fd, - KarSource::File => KarArg::File, - }; - out.push_str(&format!( - "engine command the service runs:\n {} {}\n", - ctx.paths.bin("leleka-inference").display(), - config.engine_args(kar).join(" ") - )); - out.push_str(&format!( - " (profile {}: budget {:.1} GiB, context {}, KAR {})\n", - config.profile.name, - config.profile.gpu_budget_bytes as f64 / (1u64 << 30) as f64, - config.profile.context_tokens, - config.profile.kar_source.as_str() - )); - let env = config.engine_environment(); - if !env.is_empty() { - out.push_str(&format!( - " engine environment: {}\n", - env.iter() - .map(|(k, v)| format!("{k}={v}")) - .collect::>() - .join(" ") - )); - } - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - cli::{Command, Environment, parse}, - facts::{Gpu, Memory}, - layout::Dirs, - }; - - fn options(extra: &[&str]) -> UpOptions { - let var = |_: &str| None; - let mut args: Vec = vec![ - "up".into(), - "--assets".into(), - "/data/leleka".into(), - "--state-dir".into(), - "/var/lib/leleka/state".into(), - "--prefix".into(), - "/opt/leleka".into(), - ]; - args.extend(extra.iter().map(|s| s.to_string())); - match parse( - &args, - &Environment { - root: true, - home: None, - var: &var, - }, - ) - .unwrap() - { - Command::Up(options) => options, - _ => unreachable!(), - } - } - - fn context(opts: UpOptions, mode: Mode, gpu_name: &str, sm: u32) -> Context { - let paths = opts.dirs.paths(); - let gpu = Gpu { - index: 0, - name: gpu_name.into(), - driver: "595.99.02".into(), - vram_total_mib: if sm == 120 { 32607 } else { 16384 }, - vram_free_mib: if sm == 120 { 32000 } else { 15500 }, - sm: Some(sm), - }; - let mut facts = Facts { - os: "linux".into(), - arch: "x86_64".into(), - gpus: vec![gpu.clone()], - memory: Memory { - total: 128 << 30, - available: 100 << 30, - swap_total: 0, - }, - root: true, - systemd_system: true, - proc_fd: true, - memfd_ok: true, - ..Facts::default() - }; - facts - .libs - .insert("libcublas.so.12".into(), Some("/x/libcublas.so.12".into())); - facts.libs.insert( - "libcublasLt.so.12".into(), - Some("/x/libcublasLt.so.12".into()), - ); - facts - .libs - .insert("libcuda.so.1".into(), Some("/x/libcuda.so.1".into())); - for tool in ["curl", "tar", "xz", "systemctl"] { - facts.tools.insert(tool.into(), true); - } - for name in BINARIES { - facts.binaries.insert(name.into(), true); - } - for key in ["assets", "state", "prefix"] { - facts.dirs.insert( - key.into(), - crate::facts::DirFact { - path: format!("/{key}").into(), - free_bytes: Some(2 << 40), - fs_type: Some("ext4".into()), - }, - ); - } - let profile = resolve(opts.profile.as_deref(), Some(&gpu)); - let needs = Needs { - shard_bytes_missing: 83_617_662_656, - kar_bytes_missing: ARCHIVE_BYTES * 12 / 10, - ..Needs::default() - }; - let config = profile.as_ref().ok().map(|p| { - RunConfig::new( - &opts.dirs, - opts.ports.clone(), - 0, - p.clone(), - BTreeMap::new(), - ) - }); - let report = profile.as_ref().ok().map(|p| evaluate(&facts, p, &needs)); - Context { - service_user: "leleka".into(), - bin_src: "/src/bin".into(), - manifest: None, - profile, - mode, - facts, - paths, - config, - report, - needs, - opts, - } - } - - fn state_of<'a>(steps: &'a [Step], id: &str) -> &'a StepState { - &steps.iter().find(|s| s.id == id).unwrap().state - } - - #[test] - fn fresh_server_plans_every_step() { - let ctx = context( - options(&[]), - Mode::Systemd(UnitScopeTag::System), - "NVIDIA GeForce RTX 5090", - 120, - ); - let steps = plan_steps( - &ctx, - &FsState { - binaries_source_ok: true, - mtp_present: true, - ..FsState::default() - }, - ); - for id in [ - "layout", - "binaries", - "secrets", - "model", - "kar", - "tokenizer", - "config", - "service", - "start", - "ready", - ] { - assert!( - matches!(state_of(&steps, id), StepState::Todo(_)), - "{id}: {:?}", - state_of(&steps, id) - ); - } - let text = render_plan(&ctx, &steps); - assert!(text.contains("model ensure-sharded-streamed qwen-iq3-s --source-dir /data/leleka/model --output /data/leleka/qwen-iq3-s-l2-v4.kar --levels 2"), "{text}"); - assert!(text.contains("--kar-archive-fd {FD}"), "{text}"); - } - - #[test] - fn finished_deployment_is_done_except_nothing_to_do() { - let ctx = context( - options(&[]), - Mode::Systemd(UnitScopeTag::System), - "NVIDIA GeForce RTX 5090", - 120, - ); - let fs = FsState { - dirs_exist: true, - binaries_current: true, - binaries_source_ok: true, - cublas_ready: true, - secrets_present: true, - shards_stamp_ok: true, - kar_stamp_ok: true, - kar_present: true, - mtp_present: true, - tokenizer_present: true, - configs_current: true, - unit_current: true, - service_ready: true, - }; - let steps = plan_steps(&ctx, &fs); - for step in &steps { - if step.id != "preflight" { - assert!( - matches!(step.state, StepState::Done(_)), - "{} is {:?}", - step.id, - step.state - ); - } - } - // The plan of a finished deployment prints no commands (nothing will run). - assert!(!render_plan(&ctx, &steps[1..]).contains("$ ")); - } - - #[test] - fn missing_pieces_block_with_the_reason() { - let ctx = context( - options(&["--no-fetch", "--no-install-cublas"]), - Mode::Foreground, - "NVIDIA GeForce RTX 5090", - 120, - ); - let steps = plan_steps(&ctx, &FsState::default()); - assert!(matches!( - state_of(&steps, "binaries"), - StepState::Blocked(_) - )); - assert!(matches!(state_of(&steps, "cublas"), StepState::Blocked(_))); - assert!(matches!(state_of(&steps, "model"), StepState::Blocked(_))); - assert!(matches!(state_of(&steps, "kar"), StepState::Blocked(_))); - let mtp = state_of(&steps, "mtp-pack"); - assert!( - matches!(mtp, StepState::Blocked(_)) && mtp.why().contains("no automated producer"), - "{mtp:?}" - ); - assert!(matches!(state_of(&steps, "service"), StepState::Skip(_))); - } - - #[test] - fn the_archive_step_covers_the_shards_and_trust_archive_does_not() { - let ctx = context( - options(&[]), - Mode::Foreground, - "NVIDIA GeForce RTX 5090", - 120, - ); - let steps = plan_steps( - &ctx, - &FsState { - binaries_source_ok: true, - ..FsState::default() - }, - ); - assert!( - state_of(&steps, "model") - .why() - .contains("inside the archive step") - ); - let trusted = context( - options(&["--trust-archive"]), - Mode::Foreground, - "NVIDIA GeForce RTX 5090", - 120, - ); - let steps = plan_steps( - &trusted, - &FsState { - binaries_source_ok: true, - kar_present: true, - ..FsState::default() - }, - ); - assert!( - !state_of(&steps, "model") - .why() - .contains("inside the archive step") - ); - assert!(state_of(&steps, "kar").why().contains("--trust-archive")); - // Trusting needs an archive to trust. - let steps = plan_steps( - &trusted, - &FsState { - binaries_source_ok: true, - ..FsState::default() - }, - ); - assert!(!state_of(&steps, "kar").why().contains("--trust-archive")); - } - - #[test] - fn mtp_pack_import_is_a_todo_when_given() { - let ctx = context( - options(&["--mtp-pack", "/tmp/mtp-rt.tar.gz"]), - Mode::None, - "NVIDIA GeForce RTX 5090", - 120, - ); - let steps = plan_steps( - &ctx, - &FsState { - binaries_source_ok: true, - ..FsState::default() - }, - ); - assert!(matches!(state_of(&steps, "mtp-pack"), StepState::Todo(_))); - assert!(matches!(state_of(&steps, "start"), StepState::Skip(_))); - } - - #[test] - fn reverify_replans_verified_assets() { - let ctx = context( - options(&["--reverify"]), - Mode::Foreground, - "NVIDIA GeForce RTX 5090", - 120, - ); - let steps = plan_steps( - &ctx, - &FsState { - shards_stamp_ok: true, - kar_stamp_ok: true, - binaries_source_ok: true, - ..FsState::default() - }, - ); - assert!( - matches!(state_of(&steps, "model"), StepState::Todo(_)) - && matches!(state_of(&steps, "kar"), StepState::Todo(_)) - ); - } - - #[test] - fn laptop_plan_uses_the_file_engine_command() { - let ctx = context( - options(&[]), - Mode::Foreground, - "NVIDIA GeForce RTX 3080 Laptop GPU", - 86, - ); - let steps = plan_steps(&ctx, &FsState::default()); - let text = render_plan(&ctx, &steps); - assert!( - text.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar") - && text.contains("--context-tokens 8192"), - "{text}" - ); - assert!(text.contains("rtx3080-16g")); - } - - #[test] - fn mode_resolution() { - let mut facts = Facts { - root: true, - systemd_system: true, - ..Facts::default() - }; - facts.tools.insert("systemctl".into(), true); - assert_eq!( - resolve_mode(ModeChoice::Auto, &facts, false), - Mode::Systemd(UnitScopeTag::System) - ); - facts.root = false; - assert_eq!( - resolve_mode(ModeChoice::Auto, &facts, true), - Mode::Systemd(UnitScopeTag::User) - ); - assert_eq!( - resolve_mode(ModeChoice::Auto, &facts, false), - Mode::Foreground - ); - facts.systemd_system = false; - assert_eq!( - resolve_mode(ModeChoice::Auto, &facts, true), - Mode::Foreground - ); - assert_eq!(resolve_mode(ModeChoice::None, &facts, true), Mode::None); - let _ = Dirs { - prefix: "/".into(), - state: "/".into(), - assets: "/".into(), - }; - } - - #[test] - fn expert_profile_needs_the_pinned_digest() { - let dir = std::env::temp_dir().join(format!("leleka-expert-{}", std::process::id())); - std::fs::create_dir_all(dir.join("data")).unwrap(); - let profile = Profile::builtin("rtx3080-16g").unwrap(); - assert_eq!( - expert_profile_state(&profile, &dir), - Some(ExpertProfileState::Absent) - ); - std::fs::write(dir.join("data/expert-profile.bin"), b"not the profile").unwrap(); - assert_eq!( - expert_profile_state(&profile, &dir), - Some(ExpertProfileState::WrongDigest) - ); - // the server profile names the same shipped routing profile (default digest) - assert_eq!( - expert_profile_state(&Profile::builtin("rtx5090-32g").unwrap(), &dir), - Some(ExpertProfileState::WrongDigest) - ); - std::fs::remove_dir_all(dir).unwrap(); - } -} +//! The deployment plan: what `up` would do, derived from what is already on the machine. +//! +//! `gather` reads the host (no writes, no hashing of model files, no network). `plan_steps` is pure over the +//! gathered state, so a fresh machine, a half-finished run and a finished deployment are all unit-tested. +//! `--dry-run` prints this plan; execution (`steps.rs`) walks the same list and runs only the `Todo` entries, +//! which is what makes a re-run idempotent and a crashed run resumable. +use crate::{ + cli::{ModeChoice, UpOptions}, + config::{KarArg, RunConfig}, + facts::{Facts, ProbeRequest, probe}, + layout::{BINARIES, MANIFEST, MTP_FILES, Paths, missing_asset_bytes}, + manifest::Manifest, + preflight::{ExpertProfileState, Needs, Report, evaluate}, + profile::{ARCHIVE_BYTES, KarSource, Profile, resolve}, + units::UnitScope, +}; +use serde::Serialize; +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, +}; + +pub const CUBLAS_VERSION: &str = "12.9.1.4"; +pub const CUBLAS_URL: &str = "https://developer.download.nvidia.com/compute/cuda/redist/libcublas/linux-x86_64/libcublas-linux-x86_64-12.9.1.4-archive.tar.xz"; +pub const CUBLAS_SHA256: &str = "546addc4a9d82b8f23aa9ba9274b6bc0429a63008a31c759884ac24880796057"; +pub const CUBLAS_BYTES: u64 = 933_611_504; +pub const EXPERT_PROFILE_SHA256: &str = + "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Mode { + Systemd(UnitScopeTag), + Foreground, + /// Prepare everything, start nothing. + None, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum UnitScopeTag { + System, + User, +} + +impl UnitScopeTag { + pub fn scope(self) -> UnitScope { + match self { + UnitScopeTag::System => UnitScope::System, + UnitScopeTag::User => UnitScope::User, + } + } +} + +impl Mode { + pub fn label(self) -> &'static str { + match self { + Mode::Systemd(UnitScopeTag::System) => "systemd (system unit)", + Mode::Systemd(UnitScopeTag::User) => "systemd (user unit)", + Mode::Foreground => "foreground", + Mode::None => "prepare only", + } + } +} + +/// `--mode auto`: root with systemd gets a system unit, a user with a systemd user session a user unit, everything +/// else (WSL without systemd, containers) runs in the foreground. +pub fn resolve_mode(choice: ModeChoice, facts: &Facts, user_session: bool) -> Mode { + match choice { + ModeChoice::System => Mode::Systemd(UnitScopeTag::System), + ModeChoice::User => Mode::Systemd(UnitScopeTag::User), + ModeChoice::Foreground => Mode::Foreground, + ModeChoice::None => Mode::None, + ModeChoice::Auto => { + if facts.systemd_system && facts.tool("systemctl") { + if facts.root { + Mode::Systemd(UnitScopeTag::System) + } else if user_session { + Mode::Systemd(UnitScopeTag::User) + } else { + Mode::Foreground + } + } else { + Mode::Foreground + } + } + } +} + +#[derive(Debug)] +pub struct Context { + pub opts: UpOptions, + pub facts: Facts, + pub paths: Paths, + pub bin_src: PathBuf, + pub manifest: Option>, + pub profile: Result, + pub mode: Mode, + pub service_user: String, + pub config: Option, + pub report: Option, + pub needs: Needs, +} + +fn current_bin_dir() -> PathBuf { + std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(Path::to_path_buf)) + .unwrap_or_else(|| PathBuf::from(".")) +} + +pub fn expert_profile_state(profile: &Profile, assets: &Path) -> Option { + let relative = profile.expert_profile.as_ref()?; + let path = assets.join(relative); + let Ok(bytes) = std::fs::read(&path) else { + return Some(ExpertProfileState::Absent); + }; + if bytes.len() > 16 << 20 { + return Some(ExpertProfileState::WrongDigest); + } + let expected = profile + .expert_profile_sha256 + .as_deref() + .unwrap_or(EXPERT_PROFILE_SHA256); + Some(if sha256_hex(&bytes) == expected { + ExpertProfileState::Valid + } else { + ExpertProfileState::WrongDigest + }) +} + +pub fn sha256_hex(bytes: &[u8]) -> String { + use sha2::{Digest, Sha256}; + hex::encode(Sha256::digest(bytes)) +} + +/// Is the supervisor of this state directory alive? (`run/status.json` names its pid.) +pub fn service_running(paths: &Paths) -> bool { + let Ok(text) = std::fs::read_to_string(paths.status_file()) else { + return false; + }; + let Ok(value) = serde_json::from_str::(&text) else { + return false; + }; + let pid = value.get("supervisor_pid").and_then(|v| v.as_u64()); + let phase = value.get("phase").and_then(|v| v.as_str()).unwrap_or(""); + matches!(pid, Some(pid) if Path::new(&format!("/proc/{pid}")).exists()) + && !matches!(phase, "stopped" | "failed") +} + +fn user_session_available(var: &dyn Fn(&str) -> Option) -> bool { + var("XDG_RUNTIME_DIR").is_some_and(|dir| Path::new(&dir).join("systemd").exists()) +} + +pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option) -> Context { + let paths = opts.dirs.paths(); + let bin_src = opts.bin_src.clone().unwrap_or_else(current_bin_dir); + let installed = paths.bin_dir(); + // Probe the source of the binaries, or the installed copy when the source has none (re-run after install). + let binary_dir = if BINARIES.iter().all(|b| bin_src.join(b).is_file()) { + bin_src.clone() + } else { + installed.clone() + }; + let mut extra_library_dirs: Vec = Vec::new(); + if let Some(dir) = &opts.cublas_dir { + extra_library_dirs.push(dir.clone()); + } else { + extra_library_dirs.push(paths.cublas_dir()); + } + let ports: Vec = [&opts.ports.api, &opts.ports.engine, &opts.ports.daemon] + .iter() + .filter_map(|p| p.rsplit(':').next()?.parse().ok()) + .collect(); + let request = ProbeRequest { + dirs: vec![ + ("assets".into(), opts.dirs.assets.clone()), + ("state".into(), opts.dirs.state.clone()), + ("prefix".into(), opts.dirs.prefix.clone()), + ], + ports, + binary_dir: Some(binary_dir.clone()), + binaries: BINARIES.iter().map(|b| b.to_string()).collect(), + extra_library_dirs, + }; + let facts = probe(&request); + let manifest = Manifest::find(&binary_dir); + let gpu = facts.gpus.iter().find(|g| g.index == opts.gpu); + let mut profile = resolve(opts.profile.as_deref(), gpu); + if let Ok(p) = &mut profile { + if let Some(gib) = opts.gpu_budget_gib { + p.gpu_budget_bytes = gib << 30; + } + if let Some(tokens) = opts.context_tokens { + p.context_tokens = tokens; + } + if let Err(message) = p.validate() { + profile = Err(message); + } + } + let choice = if opts.kar_fd.is_some() && opts.mode == ModeChoice::Auto { + ModeChoice::Foreground + } else { + opts.mode + }; + let mode = resolve_mode(choice, &facts, user_session_available(var)); + let service_user = if matches!(mode, Mode::Systemd(UnitScopeTag::System)) { + opts.service_user + .clone() + .unwrap_or_else(|| "leleka".to_owned()) + } else { + var("USER") + .or_else(|| var("LOGNAME")) + .unwrap_or_else(|| "root".to_owned()) + }; + let (shards, kar) = missing_asset_bytes(&paths); + let installed_same_dir = same_dir(&bin_src, &installed); + let mut needs = Needs { + gpu_index: opts.gpu, + assets_dir: opts.dirs.assets.clone(), + state_dir: opts.dirs.state.clone(), + prefix_dir: opts.dirs.prefix.clone(), + shard_bytes_missing: if opts.fetch { shards } else { 0 }, + kar_bytes_missing: if opts.fetch { kar } else { 0 }, + install_binaries: !installed_same_dir, + may_install_cublas: opts.install_cublas && opts.cublas_dir.is_none(), + cublas_download_bytes: CUBLAS_BYTES, + wants_systemd: matches!(mode, Mode::Systemd(_)), + service_ports: vec![ + ("api".into(), port_of(&opts.ports.api)), + ("engine".into(), port_of(&opts.ports.engine)), + ("gateway".into(), port_of(&opts.ports.daemon)), + ], + require_binaries: true, + binary_has_sm86: manifest + .as_ref() + .and_then(|m| m.as_ref().ok()) + .map(Manifest::has_sm86), + service_running: service_running(&paths), + kar_fd_inherited: opts.kar_fd.is_some(), + api_bind_open: crate::config::probe_address(&opts.ports.api) + .is_some_and(|a| !a.ip().is_loopback()), + expert_profile: None, + resources: None, + }; + let (config, report) = match &mut profile { + Ok(p) => { + needs.expert_profile = expert_profile_state(p, &opts.dirs.assets); + let mut engine_env = BTreeMap::new(); + let resources = crate::resources::compute(&facts, gpu, p, opts.preset); + crate::resources::apply(&resources, p, &mut engine_env, opts.gpu_budget_gib.is_some()); + needs.resources = Some(resources); + if needs.expert_profile == Some(ExpertProfileState::Valid) + && let Some(relative) = &p.expert_profile + { + engine_env.insert( + "LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS".to_owned(), + "auto".to_owned(), + ); + engine_env.insert( + "LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE".to_owned(), + opts.dirs.assets.join(relative).display().to_string(), + ); + } + let mut config = RunConfig::new( + &opts.dirs, + opts.ports.clone(), + opts.gpu, + p.clone(), + engine_env, + ); + config.preset = opts.preset; + let report = evaluate(&facts, p, &needs); + (Some(config), Some(report)) + } + Err(_) => (None, None), + }; + Context { + opts: opts.clone(), + facts, + paths, + bin_src, + manifest, + profile, + mode, + service_user, + config, + report, + needs, + } +} + +fn port_of(address: &str) -> u16 { + address + .rsplit(':') + .next() + .and_then(|p| p.parse().ok()) + .unwrap_or(0) +} + +fn same_dir(a: &Path, b: &Path) -> bool { + match (a.canonicalize(), b.canonicalize()) { + (Ok(a), Ok(b)) => a == b, + _ => a == b, + } +} + +/// What exists on disk now, reduced to the facts the plan needs. +#[derive(Clone, Debug, Default)] +pub struct FsState { + pub dirs_exist: bool, + pub binaries_current: bool, + pub binaries_source_ok: bool, + pub cublas_ready: bool, + pub secrets_present: bool, + pub shards_stamp_ok: bool, + pub kar_stamp_ok: bool, + /// The archive file has the pinned length and its provenance sidecar exists. + pub kar_present: bool, + pub mtp_present: bool, + pub tokenizer_present: bool, + pub configs_current: bool, + pub unit_current: bool, + pub service_ready: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(tag = "state", content = "why", rename_all = "lowercase")] +pub enum StepState { + Done(String), + Todo(String), + Skip(String), + Blocked(String), +} + +impl StepState { + pub fn tag(&self) -> &'static str { + match self { + StepState::Done(_) => "done", + StepState::Todo(_) => "todo", + StepState::Skip(_) => "skip", + StepState::Blocked(_) => "BLOCKED", + } + } + pub fn why(&self) -> &str { + match self { + StepState::Done(s) + | StepState::Todo(s) + | StepState::Skip(s) + | StepState::Blocked(s) => s, + } + } +} + +#[derive(Clone, Debug, Serialize)] +pub struct Step { + pub id: &'static str, + pub title: String, + #[serde(flatten)] + pub state: StepState, + pub commands: Vec, +} + +fn step(id: &'static str, title: &str, state: StepState, commands: Vec) -> Step { + Step { + id, + title: title.to_owned(), + state, + commands, + } +} + +pub fn plan_steps(ctx: &Context, fs: &FsState) -> Vec { + let paths = &ctx.paths; + let opts = &ctx.opts; + let sn = paths.bin("strata-next").display().to_string(); + let manifest_name = MANIFEST; + let mut steps = Vec::new(); + + let pre_state = match &ctx.report { + Some(report) if report.failed() => StepState::Blocked(format!( + "{} check(s) failed", + report.count(crate::preflight::Level::Fail) + )), + Some(report) => StepState::Todo(format!( + "{} warning(s)", + report.count(crate::preflight::Level::Warn) + )), + None => StepState::Blocked(ctx.profile.as_ref().err().cloned().unwrap_or_default()), + }; + steps.push(step( + "preflight", + "host checks", + pre_state, + vec!["nvidia-smi, /proc/meminfo, statvfs, ldconfig, memfd_create".into()], + )); + + steps.push(step( + "layout", + "create directories", + if fs.dirs_exist { + StepState::Done("present".into()) + } else { + StepState::Todo("create state (0700), logs, run, stamps, assets".into()) + }, + vec![format!( + "mkdir -p {} {} {}", + opts.dirs.prefix.display(), + opts.dirs.state.display(), + opts.dirs.assets.display() + )], + )); + + steps.push(step( + "binaries", + "install the six runtime binaries", + if !fs.binaries_source_ok { + StepState::Blocked(format!( + "not all of {} are in {} or {}", + BINARIES.join(", "), + ctx.bin_src.display(), + paths.bin_dir().display() + )) + } else if fs.binaries_current { + StepState::Done(format!("{} is current", paths.bin_dir().display())) + } else { + StepState::Todo(format!( + "copy from {} (SHA-256 checked against MANIFEST.json when present)", + ctx.bin_src.display() + )) + }, + vec![format!( + "install {{{}}} -> {}", + BINARIES.join(","), + paths.bin_dir().display() + )], + )); + + let cublas_cmd = vec![ + format!("curl -fL -C - {CUBLAS_URL} (sha256 {CUBLAS_SHA256})"), + format!( + "tar -xJf libcublas-{CUBLAS_VERSION}.tar.xz -> {}", + paths.cublas_dir().display() + ), + ]; + steps.push(step( + "cublas", + "CUDA 12 cuBLAS for the PLE batch GEMM", + if fs.cublas_ready { + StepState::Done("libcublas.so.12 and libcublasLt.so.12 found".into()) + } else if opts.cublas_dir.is_some() { + StepState::Blocked( + "--cublas-dir does not contain libcublas.so.12 and libcublasLt.so.12".into(), + ) + } else if opts.install_cublas { + StepState::Todo(format!( + "download the pinned {CUBLAS_VERSION} redistributable ({} MiB)", + CUBLAS_BYTES >> 20 + )) + } else { + StepState::Blocked("missing and --no-install-cublas was given".into()) + }, + cublas_cmd, + )); + + steps.push(step( + "secrets", + "service tokens and API key", + if fs.secrets_present { + StepState::Done("runtime.env and api-key exist (never rotated)".into()) + } else { + StepState::Todo("generate two tokens (0600) and run `strata-next api-key init`".into()) + }, + vec![format!( + "{sn} api-key init --file {}", + paths.api_key().display() + )], + )); + + let trusted = opts.trust_archive && fs.kar_present; + let kar_state = if fs.kar_stamp_ok && !opts.reverify { + StepState::Done(format!("{} bytes, verified earlier", ARCHIVE_BYTES)) + } else if trusted { + StepState::Todo( + "accept the existing archive without the strict re-derivation (--trust-archive); the engine verifies its SHA-256 and every CRC at each load" + .into(), + ) + } else if !opts.fetch { + StepState::Blocked("--no-fetch given but the archive is missing or unverified".into()) + } else { + StepState::Todo( + "build the level-2 KAR archive (bounded memory, hours on a first run) or re-verify the existing one (strict, tens of minutes), then stamp it" + .into(), + ) + }; + let kar_runs_tool = matches!(kar_state, StepState::Todo(_)) && !trusted; + + let model_cmds = vec![ + format!( + "{sn} model fetch {manifest_name} --output {}", + paths.model_dir().display() + ), + format!( + "{sn} model verify {manifest_name} --output {}", + paths.model_dir().display() + ), + ]; + steps.push(step( + "model", + "fetch and verify the two IQ3_S GGUF shards", + if fs.shards_stamp_ok && !opts.reverify { + StepState::Done( + "verified earlier; sizes and mtimes unchanged (--reverify hashes again)".into(), + ) + } else if kar_runs_tool { + StepState::Todo( + "downloaded and verified inside the archive step (ensure-sharded-streamed fetches and verifies the shards first)" + .into(), + ) + } else if !opts.fetch { + if fs.shards_stamp_ok { + StepState::Todo("--no-fetch: verify only".into()) + } else { + StepState::Blocked( + "--no-fetch given but the shards are not verified yet; run without --no-fetch" + .into(), + ) + } + } else { + StepState::Todo(format!( + "{} still to download; resumable, SHA-256 of 83.6 GB", + gib_text(ctx.needs.shard_bytes_missing) + )) + }, + model_cmds, + )); + + let kar_cmd = vec![format!( + "{sn} model ensure-sharded-streamed {manifest_name} --source-dir {} --output {} --levels 2", + paths.model_dir().display(), + paths.kar().display() + )]; + steps.push(step( + "kar", + "KAR level-2 archive (+ provenance)", + kar_state, + kar_cmd, + )); + + steps.push(step( + "mtp-pack", + "MTP draft pack (data/mtp-rt)", + if let Some(src) = &opts.mtp_pack { + if fs.mtp_present { StepState::Done("present; --mtp-pack ignored".into()) } else { StepState::Todo(format!("import from {}", src.display())) } + } else if fs.mtp_present { + StepState::Done(format!("{} present", paths.mtp_pack().display())) + } else { + StepState::Blocked(format!("{} is missing and no --mtp-pack was given; the pack ({}) has no automated producer yet", paths.mtp_pack().display(), MTP_FILES.join(", "))) + }, + vec![format!("copy/unpack -> {}", paths.mtp_pack().display())], + )); + + steps.push(step( + "tokenizer", + "tokenizer assets for the API", + if fs.tokenizer_present { + StepState::Done("present".into()) + } else { + StepState::Todo("extract from shard 1".into()) + }, + vec![format!( + "{sn} model extract-tokenizer {} --output {}", + paths.shard(0).display(), + paths.tokenizer_root().display() + )], + )); + + steps.push(step( + "config", + "run configuration, gateway and API configs, environment file", + if fs.configs_current { + StepState::Done("up to date".into()) + } else { + StepState::Todo( + "write leleka.json, daemon.json, strata.json, profile.json, runtime.env".into(), + ) + }, + vec![format!( + "write {}/{{leleka,daemon,strata,profile}}.json runtime.env", + opts.dirs.state.display() + )], + )); + + match ctx.mode { + Mode::Systemd(scope) => { + steps.push(step( + "service", + "systemd unit", + if fs.unit_current { + StepState::Done("installed and enabled".into()) + } else { + StepState::Todo(format!( + "write {} unit, daemon-reload, enable", + if scope == UnitScopeTag::System { + "system" + } else { + "user" + } + )) + }, + vec![format!( + "systemctl {}enable {}", + if scope == UnitScopeTag::User { + "--user " + } else { + "" + }, + paths.unit_name() + )], + )); + steps.push(step( + "start", + "start the service", + if fs.service_ready { + StepState::Done("already ready".into()) + } else { + StepState::Todo( + "systemctl start (first start copies the archive and loads the model)" + .into(), + ) + }, + vec![format!( + "systemctl {}start {}", + if scope == UnitScopeTag::User { + "--user " + } else { + "" + }, + paths.unit_name() + )], + )); + } + Mode::Foreground => { + steps.push(step( + "service", + "systemd unit", + StepState::Skip("foreground mode".into()), + vec![], + )); + steps.push(step( + "start", + "run the supervisor in this terminal", + if fs.service_ready { + StepState::Done("a supervisor is already ready".into()) + } else { + StepState::Todo("leleka run (Ctrl-C drains and stops)".into()) + }, + vec![format!( + "{} run --config {}", + paths.bin("leleka").display(), + paths.run_config().display() + )], + )); + } + Mode::None => { + steps.push(step( + "service", + "systemd unit", + StepState::Skip("--mode none".into()), + vec![], + )); + steps.push(step( + "start", + "start the service", + StepState::Skip("--mode none".into()), + vec![], + )); + } + } + steps.push(step( + "ready", + "wait for readiness", + if matches!(ctx.mode, Mode::None) { + StepState::Skip("--mode none".into()) + } else if fs.service_ready { + StepState::Done("ready".into()) + } else { + StepState::Todo(format!( + "poll {} /ready for up to {} s", + opts.ports.api, opts.timeout_s + )) + }, + vec![format!("GET http://{}/ready", opts.ports.api)], + )); + steps +} + +fn gib_text(bytes: u64) -> String { + format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64) +} + +/// A human rendering of the plan, with the engine command the service will run. +pub fn render_plan(ctx: &Context, steps: &[Step]) -> String { + let mut out = String::new(); + out.push_str("plan:\n"); + for (index, step) in steps.iter().enumerate() { + out.push_str(&format!( + " {:>2}. [{:7}] {} - {}\n", + index + 1, + step.state.tag(), + step.title, + step.state.why() + )); + if matches!(step.state, StepState::Todo(_) | StepState::Blocked(_)) { + for command in &step.commands { + out.push_str(&format!(" $ {command}\n")); + } + } + } + if let Some(config) = &ctx.config { + let kar = match config.profile.kar_source { + KarSource::Memfd => KarArg::Fd, + KarSource::File => KarArg::File, + }; + out.push_str(&format!( + "engine command the service runs:\n {} {}\n", + ctx.paths.bin("leleka-inference").display(), + config.engine_args(kar).join(" ") + )); + out.push_str(&format!( + " (profile {}: budget {:.1} GiB, context {}, KAR {})\n", + config.profile.name, + config.profile.gpu_budget_bytes as f64 / (1u64 << 30) as f64, + config.profile.context_tokens, + config.profile.kar_source.as_str() + )); + let env = config.engine_environment(); + if !env.is_empty() { + out.push_str(&format!( + " engine environment: {}\n", + env.iter() + .map(|(k, v)| format!("{k}={v}")) + .collect::>() + .join(" ") + )); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + cli::{Command, Environment, parse}, + facts::{Gpu, Memory}, + layout::Dirs, + }; + + fn options(extra: &[&str]) -> UpOptions { + let var = |_: &str| None; + let mut args: Vec = vec![ + "up".into(), + "--assets".into(), + "/data/leleka".into(), + "--state-dir".into(), + "/var/lib/leleka/state".into(), + "--prefix".into(), + "/opt/leleka".into(), + ]; + args.extend(extra.iter().map(|s| s.to_string())); + match parse( + &args, + &Environment { + root: true, + home: None, + var: &var, + }, + ) + .unwrap() + { + Command::Up(options) => options, + _ => unreachable!(), + } + } + + fn context(opts: UpOptions, mode: Mode, gpu_name: &str, sm: u32) -> Context { + let paths = opts.dirs.paths(); + let gpu = Gpu { + index: 0, + name: gpu_name.into(), + driver: "595.99.02".into(), + vram_total_mib: if sm == 120 { 32607 } else { 16384 }, + vram_free_mib: if sm == 120 { 32000 } else { 15500 }, + sm: Some(sm), + }; + let mut facts = Facts { + os: "linux".into(), + arch: "x86_64".into(), + gpus: vec![gpu.clone()], + memory: Memory { + total: 128 << 30, + available: 100 << 30, + swap_total: 0, + }, + root: true, + systemd_system: true, + proc_fd: true, + memfd_ok: true, + ..Facts::default() + }; + facts + .libs + .insert("libcublas.so.12".into(), Some("/x/libcublas.so.12".into())); + facts.libs.insert( + "libcublasLt.so.12".into(), + Some("/x/libcublasLt.so.12".into()), + ); + facts + .libs + .insert("libcuda.so.1".into(), Some("/x/libcuda.so.1".into())); + for tool in ["curl", "tar", "xz", "systemctl"] { + facts.tools.insert(tool.into(), true); + } + for name in BINARIES { + facts.binaries.insert(name.into(), true); + } + for key in ["assets", "state", "prefix"] { + facts.dirs.insert( + key.into(), + crate::facts::DirFact { + path: format!("/{key}").into(), + free_bytes: Some(2 << 40), + fs_type: Some("ext4".into()), + }, + ); + } + let profile = resolve(opts.profile.as_deref(), Some(&gpu)); + let needs = Needs { + shard_bytes_missing: 83_617_662_656, + kar_bytes_missing: ARCHIVE_BYTES * 12 / 10, + ..Needs::default() + }; + let config = profile.as_ref().ok().map(|p| { + RunConfig::new( + &opts.dirs, + opts.ports.clone(), + 0, + p.clone(), + BTreeMap::new(), + ) + }); + let report = profile.as_ref().ok().map(|p| evaluate(&facts, p, &needs)); + Context { + service_user: "leleka".into(), + bin_src: "/src/bin".into(), + manifest: None, + profile, + mode, + facts, + paths, + config, + report, + needs, + opts, + } + } + + fn state_of<'a>(steps: &'a [Step], id: &str) -> &'a StepState { + &steps.iter().find(|s| s.id == id).unwrap().state + } + + #[test] + fn fresh_server_plans_every_step() { + let ctx = context( + options(&[]), + Mode::Systemd(UnitScopeTag::System), + "NVIDIA GeForce RTX 5090", + 120, + ); + let steps = plan_steps( + &ctx, + &FsState { + binaries_source_ok: true, + mtp_present: true, + ..FsState::default() + }, + ); + for id in [ + "layout", + "binaries", + "secrets", + "model", + "kar", + "tokenizer", + "config", + "service", + "start", + "ready", + ] { + assert!( + matches!(state_of(&steps, id), StepState::Todo(_)), + "{id}: {:?}", + state_of(&steps, id) + ); + } + let text = render_plan(&ctx, &steps); + assert!(text.contains("model ensure-sharded-streamed qwen-iq3-s --source-dir /data/leleka/model --output /data/leleka/qwen-iq3-s-l2-v4.kar --levels 2"), "{text}"); + assert!(text.contains("--kar-archive-fd {FD}"), "{text}"); + } + + #[test] + fn finished_deployment_is_done_except_nothing_to_do() { + let ctx = context( + options(&[]), + Mode::Systemd(UnitScopeTag::System), + "NVIDIA GeForce RTX 5090", + 120, + ); + let fs = FsState { + dirs_exist: true, + binaries_current: true, + binaries_source_ok: true, + cublas_ready: true, + secrets_present: true, + shards_stamp_ok: true, + kar_stamp_ok: true, + kar_present: true, + mtp_present: true, + tokenizer_present: true, + configs_current: true, + unit_current: true, + service_ready: true, + }; + let steps = plan_steps(&ctx, &fs); + for step in &steps { + if step.id != "preflight" { + assert!( + matches!(step.state, StepState::Done(_)), + "{} is {:?}", + step.id, + step.state + ); + } + } + // The plan of a finished deployment prints no commands (nothing will run). + assert!(!render_plan(&ctx, &steps[1..]).contains("$ ")); + } + + #[test] + fn missing_pieces_block_with_the_reason() { + let ctx = context( + options(&["--no-fetch", "--no-install-cublas"]), + Mode::Foreground, + "NVIDIA GeForce RTX 5090", + 120, + ); + let steps = plan_steps(&ctx, &FsState::default()); + assert!(matches!( + state_of(&steps, "binaries"), + StepState::Blocked(_) + )); + assert!(matches!(state_of(&steps, "cublas"), StepState::Blocked(_))); + assert!(matches!(state_of(&steps, "model"), StepState::Blocked(_))); + assert!(matches!(state_of(&steps, "kar"), StepState::Blocked(_))); + let mtp = state_of(&steps, "mtp-pack"); + assert!( + matches!(mtp, StepState::Blocked(_)) && mtp.why().contains("no automated producer"), + "{mtp:?}" + ); + assert!(matches!(state_of(&steps, "service"), StepState::Skip(_))); + } + + #[test] + fn the_archive_step_covers_the_shards_and_trust_archive_does_not() { + let ctx = context( + options(&[]), + Mode::Foreground, + "NVIDIA GeForce RTX 5090", + 120, + ); + let steps = plan_steps( + &ctx, + &FsState { + binaries_source_ok: true, + ..FsState::default() + }, + ); + assert!( + state_of(&steps, "model") + .why() + .contains("inside the archive step") + ); + let trusted = context( + options(&["--trust-archive"]), + Mode::Foreground, + "NVIDIA GeForce RTX 5090", + 120, + ); + let steps = plan_steps( + &trusted, + &FsState { + binaries_source_ok: true, + kar_present: true, + ..FsState::default() + }, + ); + assert!( + !state_of(&steps, "model") + .why() + .contains("inside the archive step") + ); + assert!(state_of(&steps, "kar").why().contains("--trust-archive")); + // Trusting needs an archive to trust. + let steps = plan_steps( + &trusted, + &FsState { + binaries_source_ok: true, + ..FsState::default() + }, + ); + assert!(!state_of(&steps, "kar").why().contains("--trust-archive")); + } + + #[test] + fn mtp_pack_import_is_a_todo_when_given() { + let ctx = context( + options(&["--mtp-pack", "/tmp/mtp-rt.tar.gz"]), + Mode::None, + "NVIDIA GeForce RTX 5090", + 120, + ); + let steps = plan_steps( + &ctx, + &FsState { + binaries_source_ok: true, + ..FsState::default() + }, + ); + assert!(matches!(state_of(&steps, "mtp-pack"), StepState::Todo(_))); + assert!(matches!(state_of(&steps, "start"), StepState::Skip(_))); + } + + #[test] + fn reverify_replans_verified_assets() { + let ctx = context( + options(&["--reverify"]), + Mode::Foreground, + "NVIDIA GeForce RTX 5090", + 120, + ); + let steps = plan_steps( + &ctx, + &FsState { + shards_stamp_ok: true, + kar_stamp_ok: true, + binaries_source_ok: true, + ..FsState::default() + }, + ); + assert!( + matches!(state_of(&steps, "model"), StepState::Todo(_)) + && matches!(state_of(&steps, "kar"), StepState::Todo(_)) + ); + } + + #[test] + fn laptop_plan_uses_the_file_engine_command() { + let ctx = context( + options(&[]), + Mode::Foreground, + "NVIDIA GeForce RTX 3080 Laptop GPU", + 86, + ); + let steps = plan_steps(&ctx, &FsState::default()); + let text = render_plan(&ctx, &steps); + assert!( + text.contains("--kar-archive-file /data/leleka/qwen-iq3-s-l2-v4.kar") + && text.contains("--context-tokens 8192"), + "{text}" + ); + assert!(text.contains("rtx3080-16g")); + } + + #[test] + fn mode_resolution() { + let mut facts = Facts { + root: true, + systemd_system: true, + ..Facts::default() + }; + facts.tools.insert("systemctl".into(), true); + assert_eq!( + resolve_mode(ModeChoice::Auto, &facts, false), + Mode::Systemd(UnitScopeTag::System) + ); + facts.root = false; + assert_eq!( + resolve_mode(ModeChoice::Auto, &facts, true), + Mode::Systemd(UnitScopeTag::User) + ); + assert_eq!( + resolve_mode(ModeChoice::Auto, &facts, false), + Mode::Foreground + ); + facts.systemd_system = false; + assert_eq!( + resolve_mode(ModeChoice::Auto, &facts, true), + Mode::Foreground + ); + assert_eq!(resolve_mode(ModeChoice::None, &facts, true), Mode::None); + let _ = Dirs { + prefix: "/".into(), + state: "/".into(), + assets: "/".into(), + }; + } + + #[test] + fn expert_profile_needs_the_pinned_digest() { + let dir = std::env::temp_dir().join(format!("leleka-expert-{}", std::process::id())); + std::fs::create_dir_all(dir.join("data")).unwrap(); + let profile = Profile::builtin("rtx3080-16g").unwrap(); + assert_eq!( + expert_profile_state(&profile, &dir), + Some(ExpertProfileState::Absent) + ); + std::fs::write(dir.join("data/expert-profile.bin"), b"not the profile").unwrap(); + assert_eq!( + expert_profile_state(&profile, &dir), + Some(ExpertProfileState::WrongDigest) + ); + // the server profile names the same shipped routing profile (default digest) + assert_eq!( + expert_profile_state(&Profile::builtin("rtx5090-32g").unwrap(), &dir), + Some(ExpertProfileState::WrongDigest) + ); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/deploy/src/preflight.rs b/crates/deploy/src/preflight.rs index bc9a2b09..69e79fd3 100644 --- a/crates/deploy/src/preflight.rs +++ b/crates/deploy/src/preflight.rs @@ -1,1060 +1,1060 @@ -//! Preflight: turn `Facts` + `Profile` + what the plan needs into pass / warn / fail checks with a fix for each. -//! -//! Pure logic over data, so it is unit-tested with synthetic hosts (server, laptop under WSL2, driver too old, -//! no cuBLAS, full disk). `leleka up` refuses to start a step that changes anything while a check fails. -use crate::{ - facts::{Facts, Gpu, is_slow_foreign_fs}, - profile::{ARCHIVE_BYTES, KarSource, Profile}, -}; -use serde::Serialize; -use std::path::PathBuf; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] -#[serde(rename_all = "lowercase")] -pub enum Level { - Pass, - Warn, - Fail, -} - -#[derive(Clone, Debug, Serialize)] -pub struct Check { - pub id: &'static str, - pub level: Level, - pub title: String, - pub detail: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub fix: Option, -} - -#[derive(Clone, Debug, Serialize)] -pub struct Report { - pub profile: String, - pub checks: Vec, -} - -impl Report { - pub fn failed(&self) -> bool { - self.checks.iter().any(|c| c.level == Level::Fail) - } - pub fn count(&self, level: Level) -> usize { - self.checks.iter().filter(|c| c.level == level).count() - } - pub fn render(&self) -> String { - let mut out = format!("preflight (profile {}):\n", self.profile); - for check in &self.checks { - let tag = match check.level { - Level::Pass => "ok ", - Level::Warn => "WARN", - Level::Fail => "FAIL", - }; - out.push_str(&format!(" [{tag}] {}: {}\n", check.title, check.detail)); - if check.level != Level::Pass - && let Some(fix) = &check.fix - { - for line in fix.lines() { - out.push_str(&format!(" fix: {line}\n")); - } - } - } - out.push_str(&format!( - " {} failed, {} warnings, {} ok\n", - self.count(Level::Fail), - self.count(Level::Warn), - self.count(Level::Pass) - )); - out - } -} - -/// What the plan will do, as far as it matters for the checks. -#[derive(Clone, Debug, Default)] -pub struct Needs { - pub gpu_index: u32, - pub assets_dir: PathBuf, - pub state_dir: PathBuf, - pub prefix_dir: PathBuf, - /// Bytes of GGUF shards still to download / of KAR archive still to build (0 when present). - pub shard_bytes_missing: u64, - pub kar_bytes_missing: u64, - /// Install the binaries from `bin_src` into the prefix. - pub install_binaries: bool, - /// cuBLAS 12 will be downloaded when the host has none. - pub may_install_cublas: bool, - pub cublas_download_bytes: u64, - pub wants_systemd: bool, - pub service_ports: Vec<(String, u16)>, - pub require_binaries: bool, - /// The release manifest lists the `sm86` feature (companion PTX for cc 8.6 <= cc < 12.0), when known. - pub binary_has_sm86: Option, - /// Ports already owned by this deployment's own running service are not conflicts. - pub service_running: bool, - /// The public API is bound beyond the loopback interface (`--api-bind`). - pub api_bind_open: bool, - /// The sealed archive comes from the parent process (`--kar-fd`): the service does not copy it. - pub kar_fd_inherited: bool, - /// Expert profile present, and its digest is the pinned one (only meaningful for profiles that name one). - pub expert_profile: Option, - /// The resource preset's numbers (`resources.rs`); its shortfalls are reported as checks. - pub resources: Option, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum ExpertProfileState { - Absent, - Valid, - WrongDigest, -} - -const GIB: u64 = 1 << 30; - -fn gib(bytes: u64) -> String { - format!("{:.1} GiB", bytes as f64 / GIB as f64) -} - -fn check( - id: &'static str, - level: Level, - title: &str, - detail: String, - fix: Option, -) -> Check { - Check { - id, - level, - title: title.to_owned(), - detail, - fix, - } -} - -fn pass(id: &'static str, title: &str, detail: String) -> Check { - check(id, Level::Pass, title, detail, None) -} - -pub fn evaluate(facts: &Facts, profile: &Profile, needs: &Needs) -> Report { - let mut checks = Vec::new(); - - // 1. platform - if facts.os == "linux" && facts.arch == "x86_64" { - checks.push(pass("platform", "platform", "linux x86_64".into())); - } else { - checks.push(check( - "platform", - Level::Fail, - "platform", - format!( - "{}/{} is not supported; the CUDA runtime is Linux x86_64 only", - facts.os, facts.arch - ), - Some("run on a Linux x86_64 host, or inside WSL2 on Windows".into()), - )); - // Nothing else can be judged on another OS. - return Report { - profile: profile.name.clone(), - checks, - }; - } - - // 2. GPU, driver, architecture, VRAM - let gpu: Option<&Gpu> = facts.gpus.iter().find(|g| g.index == needs.gpu_index); - match gpu { - None => { - let reason = if !facts.nvidia_smi_found { - "nvidia-smi was not found".to_owned() - } else if let Some(error) = &facts.nvidia_smi_error { - format!("nvidia-smi failed: {error}") - } else { - format!( - "GPU {} is not present (found {} GPU(s))", - needs.gpu_index, - facts.gpus.len() - ) - }; - checks.push(check( - "gpu", - Level::Fail, - "NVIDIA GPU", - reason, - Some(if facts.wsl { - "WSL2: install the NVIDIA Windows driver (not a Linux driver inside WSL) and run `wsl --shutdown` once; nvidia-smi must work inside the distribution".into() - } else { - "install the NVIDIA driver (>= 595) and make sure `nvidia-smi` lists the GPU; choose another device with --gpu N".into() - }), - )); - } - Some(gpu) => { - checks.push(pass( - "gpu", - "NVIDIA GPU", - format!( - "{} (GPU {}, sm_{}, {} MiB, {} MiB free)", - gpu.name, - gpu.index, - gpu.sm.map_or("?".into(), |sm| sm.to_string()), - gpu.vram_total_mib, - gpu.vram_free_mib - ), - )); - // driver - match gpu.driver_major() { - Some(major) if major >= profile.min_driver_major => checks.push(pass( - "driver", - "driver version", - format!("{} (>= {})", gpu.driver, profile.min_driver_major), - )), - Some(_) => checks.push(check( - "driver", - Level::Fail, - "driver version", - format!( - "{} is older than {}; the sealed PTX needs ISA 9.2 (CUDA 13.2)", - gpu.driver, profile.min_driver_major - ), - Some(format!( - "update the NVIDIA driver to {} or newer ({})", - profile.min_driver_major, - if facts.wsl { - "the Windows driver on the host" - } else { - "e.g. the nvidia-driver-595 package" - } - )), - )), - None => checks.push(check( - "driver", - Level::Fail, - "driver version", - format!("cannot parse driver version {:?}", gpu.driver), - None, - )), - } - // architecture -> which sealed PTX serves this card - match gpu.sm { - Some(sm) if (120..130).contains(&sm) => checks.push(pass( - "arch", - "architecture", - format!("sm_{sm}: the sealed sm_120 PTX is used as is"), - )), - Some(sm) if (86..120).contains(&sm) => { - let (level, extra, fix) = match needs.binary_has_sm86 { - Some(true) => (Level::Pass, "binaries built with the sm86 feature".to_owned(), None), - Some(false) => ( - Level::Fail, - "these binaries were built WITHOUT the sm86 feature and cannot load on this card".to_owned(), - Some("use a release built with `--features sm86` (every release made by scripts/package-release.sh is)".into()), - ), - None => ( - Level::Warn, - "cannot tell whether the binaries carry the sm86 companions (no MANIFEST.json next to them)".to_owned(), - Some("run from an unpacked release tarball, or build with `--features sm86`".into()), - ), - }; - checks.push(check( - "arch", - level, - "architecture", - format!( - "sm_{sm}: sealed sm_86 companion PTX are selected at load; {extra}" - ), - fix, - )); - } - Some(sm) => checks.push(check( - "arch", - Level::Fail, - "architecture", - format!("sm_{sm} is below sm_86; no sealed PTX exists for it"), - Some("use an RTX 30-series or newer GPU".into()), - )), - None => checks.push(check( - "arch", - Level::Warn, - "architecture", - "compute capability unknown (old nvidia-smi); assuming the profile fits".into(), - Some("upgrade the driver so `nvidia-smi --query-gpu=compute_cap` works".into()), - )), - } - // VRAM - if gpu.vram_total_mib < profile.min_vram_total_mib { - checks.push(check( - "vram", - Level::Fail, - "GPU memory", - format!( - "{} MiB total is below the {} MiB the profile {} needs", - gpu.vram_total_mib, profile.min_vram_total_mib, profile.name - ), - Some("use a larger GPU or a smaller profile (--profile FILE)".into()), - )); - } else { - let budget_mib = profile.gpu_budget_bytes / (1 << 20); - let need_mib = profile.min_vram_free_mib.unwrap_or(budget_mib); - if gpu.vram_free_mib < need_mib { - checks.push(check( - "vram", - Level::Fail, - "GPU memory", - format!( - "{} MiB free but the engine needs {} MiB (budget {}); another process holds {} MiB", - gpu.vram_free_mib, - need_mib, - gib(profile.gpu_budget_bytes), - gpu.vram_total_mib.saturating_sub(gpu.vram_free_mib) - ), - Some("stop the other GPU users (`nvidia-smi` lists them), or lower the budget with --gpu-budget-gib N".into()), - )); - } else { - checks.push(pass( - "vram", - "GPU memory", - format!("{} MiB free, budget {} MiB", gpu.vram_free_mib, budget_mib), - )); - } - } - } - } - - // 2b. resource preset - if let Some(plan) = &needs.resources { - if plan.problems.is_empty() { - checks.push(pass( - "resources", - "resource preset", - format!( - "{}: {} CPU workers, VRAM budget {} MiB", - plan.preset.as_str(), - plan.cpu_workers.map_or("default".to_owned(), |w| w.to_string()), - plan.gpu_budget_bytes / (1 << 20) - ), - )); - } else { - for problem in &plan.problems { - checks.push(check( - "resources", - Level::Fail, - "resource preset", - problem.clone(), - Some("rerun with --preset dedicated, or free the resource named above".into()), - )); - } - } - for warning in &plan.warnings { - checks.push(check("resources", Level::Warn, "resource preset", warning.clone(), None)); - } - } - - // 3. RAM - let ram = &facts.memory; - // An inherited sealed archive is already counted in the parent's memory: only the engine's own need remains. - let min_available = if needs.kar_fd_inherited { - profile - .min_ram_available_bytes - .saturating_sub(ARCHIVE_BYTES) - .max(4 * GIB) - } else { - profile.min_ram_available_bytes - }; - if ram.available == 0 && ram.total == 0 { - checks.push(check( - "ram", - Level::Fail, - "memory", - "cannot read /proc/meminfo".into(), - Some("mount /proc".into()), - )); - } else { - let mut level = Level::Pass; - let mut problems = Vec::new(); - if ram.total < profile.min_ram_total_bytes { - level = Level::Fail; - problems.push(format!( - "{} total is below the {} the profile needs", - gib(ram.total), - gib(profile.min_ram_total_bytes) - )); - } - if ram.available < min_available { - level = Level::Fail; - problems.push(format!( - "{} available is below the {} needed to start (kar_source={})", - gib(ram.available), - gib(min_available), - profile.kar_source.as_str() - )); - } - if let Some(limit) = facts.cgroup_memory_max - && limit < min_available - { - level = Level::Fail; - problems.push(format!( - "the cgroup memory limit {} is below the {} needed", - gib(limit), - gib(min_available) - )); - } - let fix = if level == Level::Fail { - Some(if facts.wsl { - let want = profile.wsl_memory_gib.unwrap_or(32); - format!( - "WSL2 gives this VM only {} of RAM. In %UserProfile%\\.wslconfig put:\n[wsl2]\nmemory={want}GB\nswap=8GB\nthen run `wsl --shutdown` from Windows and start the distribution again", - gib(ram.total) - ) - } else if profile.kar_source == KarSource::Memfd { - "free memory (the sealed archive copy needs the whole archive in RAM), or use the file-backed profile --profile rtx3080-16g if the GPU fits it".into() - } else { - "free memory or add RAM".into() - }) - } else { - None - }; - if problems.is_empty() { - problems.push(format!( - "{} total, {} available", - gib(ram.total), - gib(ram.available) - )); - } - checks.push(check("ram", level, "memory", problems.join("; "), fix)); - } - - // 4. KAR source prerequisites - if profile.kar_source == KarSource::Memfd { - if facts.proc_fd && facts.memfd_ok { - checks.push(pass( - "memfd", - "sealed memfd", - "memfd_create with sealing works and /proc/self/fd is mounted".into(), - )); - } else { - checks.push(check( - "memfd", - Level::Fail, - "sealed memfd", - format!( - "{}{}", - if facts.proc_fd { "" } else { "/proc/self/fd is not mounted; " }, - if facts.memfd_ok { "" } else { "memfd_create with F_SEAL_* failed (kernel < 3.17 or a seccomp filter)" } - ), - Some("run on a host kernel with memfd sealing; in a container allow memfd_create (default Docker seccomp does) and mount /proc".into()), - )); - } - } else if facts.proc_fd { - checks.push(pass( - "memfd", - "KAR file mode", - "the archive is opened read-only from the model volume".into(), - )); - } else { - checks.push(check( - "memfd", - Level::Warn, - "KAR file mode", - "/proc/self/fd is not mounted".into(), - Some("mount /proc".into()), - )); - } - - // 5. cuBLAS 12 - let blas = facts.lib("libcublas.so.12"); - let blas_lt = facts.lib("libcublasLt.so.12"); - match (blas, blas_lt) { - (Some(path), Some(_)) => checks.push(pass( - "cublas", - "cuBLAS 12", - format!("libcublas.so.12 and libcublasLt.so.12 found ({})", path.display()), - )), - _ if needs.may_install_cublas => { - let mut missing = Vec::new(); - if blas.is_none() { - missing.push("libcublas.so.12"); - } - if blas_lt.is_none() { - missing.push("libcublasLt.so.12"); - } - let tools_ok = (facts.tool("curl") || facts.tool("wget")) && facts.tool("tar") && facts.tool("xz"); - checks.push(check( - "cublas", - if tools_ok { Level::Warn } else { Level::Fail }, - "cuBLAS 12", - format!( - "{} not found; the pinned NVIDIA redistributable (~{} MiB) will be downloaded into the prefix{}", - missing.join(", "), - needs.cublas_download_bytes / (1 << 20), - if tools_ok { "" } else { ", but curl/wget, tar and xz are required for that" } - ), - Some("apt install curl xz-utils (or pass --cublas-dir DIR with CUDA 12 cuBLAS), or --no-install-cublas to supply it yourself".into()), - )); - } - _ => checks.push(check( - "cublas", - Level::Fail, - "cuBLAS 12", - "libcublas.so.12 / libcublasLt.so.12 not found; leleka-inference loads them by name".into(), - Some("pass --cublas-dir DIR (CUDA 12 cuBLAS), drop --no-install-cublas to let `up` download the pinned 12.9.1.4 redistributable, or apt install libcublas12".into()), - )), - } - match facts.lib("libcuda.so.1") { - Some(path) => checks.push(pass("libcuda", "CUDA driver library", format!("{}", path.display()))), - None => checks.push(check( - "libcuda", - Level::Warn, - "CUDA driver library", - "libcuda.so.1 was not found by the library search (the engine dlopens it)".into(), - Some(if facts.wsl { - "WSL2 provides it in /usr/lib/wsl/lib; make sure that directory is not removed from the loader path".into() - } else { - "install the NVIDIA driver's libcuda (nvidia-utils / libnvidia-compute packages)".into() - }), - )), - } - - // 6. WSL specifics - if facts.wsl { - let slow: Vec = ["assets", "state", "prefix"] - .iter() - .filter_map(|key| facts.dirs.get(*key)) - .filter(|dir| dir.fs_type.as_deref().is_some_and(is_slow_foreign_fs)) - .map(|dir| { - format!( - "{} ({})", - dir.path.display(), - dir.fs_type.as_deref().unwrap_or("?") - ) - }) - .collect(); - if slow.is_empty() { - checks.push(pass( - "wsl", - "WSL2", - "model volume is on the Linux file system".into(), - )); - } else { - checks.push(check( - "wsl", - Level::Fail, - "WSL2 file system", - format!("{} is on a Windows/network mount; mapped and direct reads are far too slow there", slow.join(", ")), - Some("put --assets (and --state-dir) on the WSL ext4 disk, e.g. under ~/leleka, not under /mnt/c".into()), - )); - } - } - - // 7. disk space - let mut disk_problems = Vec::new(); - let mut disk_notes = Vec::new(); - let mut by_volume: Vec<(String, u64, u64)> = Vec::new(); // (label, need, free) - let assets_need = needs.shard_bytes_missing + needs.kar_bytes_missing + 2 * GIB; - let state_need = 2 * GIB; - let prefix_need = if needs.install_binaries || needs.may_install_cublas { - GIB + if needs.may_install_cublas && blas.is_none() { - 2 * GIB - } else { - 0 - } - } else { - 0 - }; - for (key, need) in [ - ("assets", assets_need), - ("state", state_need), - ("prefix", prefix_need), - ] { - if let Some(dir) = facts.dirs.get(key) { - match dir.free_bytes { - Some(free) => by_volume.push((format!("{key} {}", dir.path.display()), need, free)), - None => { - disk_notes.push(format!("cannot read free space of {}", dir.path.display())) - } - } - } - } - for (label, need, free) in &by_volume { - if free < need { - disk_problems.push(format!( - "{label}: {} free, {} needed", - gib(*free), - gib(*need) - )); - } - } - if disk_problems.is_empty() { - let summary: Vec = by_volume - .iter() - .map(|(label, need, free)| { - format!("{label}: {} free (need {})", gib(*free), gib(*need)) - }) - .collect(); - checks.push(pass( - "disk", - "disk space", - [summary, disk_notes].concat().join("; "), - )); - } else { - checks.push(check( - "disk", - Level::Fail, - "disk space", - disk_problems.join("; "), - Some(format!( - "the first run needs about {} on the model volume (shards {}, archive {}); point --assets at a larger volume. Nothing was downloaded yet", - gib(needs.shard_bytes_missing + needs.kar_bytes_missing), - gib(needs.shard_bytes_missing), - gib(needs.kar_bytes_missing.min(ARCHIVE_BYTES + ARCHIVE_BYTES / 5)) - )), - )); - } - - // 8. tools and service manager - if needs.wants_systemd { - if facts.systemd_system && facts.tool("systemctl") { - checks.push(pass( - "systemd", - "systemd", - "systemd is PID 1 and systemctl is available".into(), - )); - } else { - checks.push(check( - "systemd", - Level::Fail, - "systemd", - "systemd is not running as the service manager here".into(), - Some(if facts.wsl { - "WSL2: add `[boot]\\nsystemd=true` to /etc/wsl.conf and `wsl --shutdown`, or run with --foreground".into() - } else { - "use --foreground to run the service in this terminal".into() - }), - )); - } - } - - // 9. ports - let busy: Vec = needs - .service_ports - .iter() - .filter(|(_, port)| facts.busy_ports.contains(port)) - .map(|(name, port)| format!("{name} {port}")) - .collect(); - if busy.is_empty() { - checks.push(pass("ports", "loopback ports", "free".into())); - } else if needs.service_running { - checks.push(pass( - "ports", - "loopback ports", - format!("{} in use by the running Leleka service", busy.join(", ")), - )); - } else { - checks.push(check( - "ports", - Level::Fail, - "loopback ports", - format!("already in use: {}", busy.join(", ")), - Some("stop the other listener or pick other ports with --api-port / --engine-port / --daemon-port".into()), - )); - } - - if needs.api_bind_open { - checks.push(check( - "api-bind", - Level::Warn, - "API listen address", - "the API is bound beyond the loopback interface; the bearer key is its only protection and there is no TLS".into(), - Some("publish the port to 127.0.0.1 only (docker run -p 127.0.0.1:8081:8081) or put a TLS proxy / SSH tunnel in front".into()), - )); - } - - // 10. binaries - if needs.require_binaries { - let missing: Vec<&String> = facts - .binaries - .iter() - .filter(|(_, ok)| !**ok) - .map(|(name, _)| name) - .collect(); - if missing.is_empty() { - checks.push(pass( - "binaries", - "binaries", - "all six runtime binaries are present".into(), - )); - } else { - checks.push(check( - "binaries", - Level::Fail, - "binaries", - format!("missing or not executable: {}", missing.iter().map(|s| s.as_str()).collect::>().join(", ")), - Some("run `leleka up` from the unpacked release tarball (bin/), or pass --bin-src DIR".into()), - )); - } - } - - // 11. gated assets / credentials hints - if (needs.shard_bytes_missing > 0) && !facts.hf_token_set { - checks.push(check( - "hf-token", - Level::Warn, - "Hugging Face token", - "HF_TOKEN is not set; the pinned shard repository is fetched anonymously".into(), - Some("if the download answers 401/403, export HF_TOKEN=... (it is only sent to https://huggingface.co and never printed)".into()), - )); - } - match &needs.expert_profile { - Some(ExpertProfileState::Absent) if profile.expert_profile.is_some() => checks.push(check( - "expert-profile", - Level::Warn, - "VRAM expert tier", - format!("{} is not in the assets directory; the engine runs without the ranked VRAM expert tier (slower)", profile.expert_profile.as_deref().unwrap_or("")), - Some("copy the upstream data/expert-profile.bin (sha256 8f59b4aa...388975baf) there, then rerun".into()), - )), - Some(ExpertProfileState::WrongDigest) => checks.push(check( - "expert-profile", - Level::Warn, - "VRAM expert tier", - "the expert profile does not have the pinned SHA-256; it will not be used".into(), - None, - )), - _ => {} - } - - Report { - profile: profile.name.clone(), - checks, - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::facts::{DirFact, Memory}; - - fn server_facts() -> Facts { - let mut facts = Facts { - os: "linux".into(), - arch: "x86_64".into(), - nvidia_smi_found: true, - gpus: vec![Gpu { - index: 0, - name: "NVIDIA GeForce RTX 5090".into(), - driver: "595.99.02".into(), - vram_total_mib: 32607, - vram_free_mib: 32105, - sm: Some(120), - }], - memory: Memory { - total: 121 * GIB, - available: 118 * GIB, - swap_total: 0, - }, - systemd_system: true, - proc_fd: true, - memfd_ok: true, - ..Facts::default() - }; - facts.libs.insert( - "libcublas.so.12".into(), - Some("/opt/c/libcublas.so.12".into()), - ); - facts.libs.insert( - "libcublasLt.so.12".into(), - Some("/opt/c/libcublasLt.so.12".into()), - ); - facts.libs.insert( - "libcuda.so.1".into(), - Some("/usr/lib/x86_64-linux-gnu/libcuda.so.1".into()), - ); - for tool in ["curl", "tar", "xz", "systemctl"] { - facts.tools.insert(tool.into(), true); - } - for key in ["assets", "state", "prefix"] { - facts.dirs.insert( - key.into(), - DirFact { - path: format!("/data/{key}").into(), - free_bytes: Some(900 * GIB), - fs_type: Some("ext4".into()), - }, - ); - } - facts - } - - fn needs() -> Needs { - Needs { - assets_dir: "/data/assets".into(), - shard_bytes_missing: 83_617_662_656, - kar_bytes_missing: ARCHIVE_BYTES * 12 / 10, - install_binaries: true, - may_install_cublas: true, - cublas_download_bytes: 500 << 20, - wants_systemd: true, - service_ports: vec![("api".into(), 8081), ("engine".into(), 18766)], - ..Needs::default() - } - } - - fn level_of(report: &Report, id: &str) -> Level { - report - .checks - .iter() - .find(|c| c.id == id) - .unwrap_or_else(|| panic!("no check {id}")) - .level - } - - #[test] - fn healthy_server_passes_everything() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let report = evaluate(&server_facts(), &profile, &needs()); - assert!(!report.failed(), "{}", report.render()); - assert_eq!(level_of(&report, "arch"), Level::Pass); - assert_eq!(level_of(&report, "memfd"), Level::Pass); - } - - #[test] - fn old_driver_and_busy_gpu_fail_with_actionable_text() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.gpus[0].driver = "580.65.06".into(); - facts.gpus[0].vram_free_mib = 9000; - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "driver"), Level::Fail); - assert_eq!(level_of(&report, "vram"), Level::Fail); - let text = report.render(); - assert!(text.contains("580.65.06 is older than 595"), "{text}"); - assert!(text.contains("--gpu-budget-gib"), "{text}"); - } - - #[test] - fn no_gpu_names_the_wsl_remedy_under_wsl() { - let profile = Profile::builtin("rtx3080-16g").unwrap(); - let mut facts = server_facts(); - facts.gpus.clear(); - facts.nvidia_smi_found = false; - facts.wsl = true; - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "gpu"), Level::Fail); - assert!(report.render().contains("Windows driver")); - } - - #[test] - fn laptop_under_default_wsl_memory_gets_wslconfig_advice() { - let profile = Profile::builtin("rtx3080-16g").unwrap(); - let mut facts = server_facts(); - facts.wsl = true; - facts.gpus[0] = Gpu { - index: 0, - name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(), - driver: "617.42".into(), - vram_total_mib: 16384, - vram_free_mib: 15234, - sm: Some(86), - }; - facts.memory = Memory { - total: 12 * GIB, - available: 9 * GIB, - swap_total: 0, - }; - let mut n = needs(); - n.binary_has_sm86 = Some(true); - let report = evaluate(&facts, &profile, &n); - assert_eq!(level_of(&report, "ram"), Level::Fail); - let text = report.render(); - assert!( - text.contains(".wslconfig") - && text.contains("memory=32GB") - && text.contains("wsl --shutdown"), - "{text}" - ); - assert_eq!(level_of(&report, "arch"), Level::Pass); - // 24 GB as WSL2 gives by default passes. - facts.memory = Memory { - total: 24_447_308 * 1024, - available: 22 * GIB, - swap_total: 0, - }; - let report = evaluate(&facts, &profile, &n); - assert!(!report.failed(), "{}", report.render()); - } - - #[test] - fn sm86_card_needs_binaries_with_the_companion_feature() { - let profile = Profile::builtin("rtx3080-16g").unwrap(); - let mut facts = server_facts(); - facts.gpus[0].sm = Some(86); - facts.gpus[0].vram_total_mib = 16384; - facts.gpus[0].vram_free_mib = 15000; - let mut n = needs(); - n.binary_has_sm86 = Some(false); - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "arch"), - Level::Fail - ); - n.binary_has_sm86 = None; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "arch"), - Level::Warn - ); - } - - #[test] - fn model_volume_on_a_windows_mount_is_refused_under_wsl() { - let profile = Profile::builtin("rtx3080-16g").unwrap(); - let mut facts = server_facts(); - facts.wsl = true; - facts.dirs.get_mut("assets").unwrap().fs_type = Some("9p".into()); - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "wsl"), Level::Fail); - assert!(report.render().contains("/mnt/c")); - } - - #[test] - fn missing_cublas_is_fixable_unless_the_tools_are_missing_too() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.libs.insert("libcublas.so.12".into(), None); - facts.libs.insert("libcublasLt.so.12".into(), None); - assert_eq!( - level_of(&evaluate(&facts, &profile, &needs()), "cublas"), - Level::Warn - ); - facts.tools.insert("xz".into(), false); - assert_eq!( - level_of(&evaluate(&facts, &profile, &needs()), "cublas"), - Level::Fail - ); - let mut n = needs(); - n.may_install_cublas = false; - facts.tools.insert("xz".into(), true); - let report = evaluate(&facts, &profile, &n); - assert_eq!(level_of(&report, "cublas"), Level::Fail); - assert!(report.render().contains("--cublas-dir")); - } - - #[test] - fn low_disk_reports_the_volume_before_anything_is_downloaded() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.dirs.get_mut("assets").unwrap().free_bytes = Some(53 * GIB); - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "disk"), Level::Fail); - let text = report.render(); - assert!( - text.contains("assets /data/assets: 53.0 GiB free"), - "{text}" - ); - assert!(text.contains("Nothing was downloaded yet"), "{text}"); - // With the model already present the same volume is fine. - let mut n = needs(); - n.shard_bytes_missing = 0; - n.kar_bytes_missing = 0; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "disk"), - Level::Pass - ); - } - - #[test] - fn memory_is_judged_by_the_profile_kar_source() { - let server = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.memory = Memory { - total: 64 * GIB, - available: 40 * GIB, - swap_total: 0, - }; - let report = evaluate(&facts, &server, &needs()); - assert_eq!(level_of(&report, "ram"), Level::Fail); - assert!( - report - .render() - .contains("sealed archive copy needs the whole archive in RAM") - ); - facts.memory = Memory { - total: 128 * GIB, - available: 100 * GIB, - swap_total: 0, - }; - facts.cgroup_memory_max = Some(32 * GIB); - assert_eq!( - level_of(&evaluate(&facts, &server, &needs()), "ram"), - Level::Fail - ); - } - - #[test] - fn an_inherited_sealed_archive_is_not_counted_twice() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - // 70 GiB available: not enough to copy the archive and hold the 50 GB expert bank, enough when the - // parent already holds the sealed archive. - facts.memory = Memory { - total: 121 * GIB, - available: 70 * GIB, - swap_total: 0, - }; - assert_eq!( - level_of(&evaluate(&facts, &profile, &needs()), "ram"), - Level::Fail - ); - let mut n = needs(); - n.kar_fd_inherited = true; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "ram"), - Level::Pass - ); - facts.memory.available = 20 * GIB; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "ram"), - Level::Fail - ); - } - - #[test] - fn a_running_service_owns_its_ports_and_a_stranger_does_not() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.busy_ports = vec![8081]; - assert_eq!( - level_of(&evaluate(&facts, &profile, &needs()), "ports"), - Level::Fail - ); - let mut n = needs(); - n.service_running = true; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "ports"), - Level::Pass - ); - } - - #[test] - fn other_platforms_stop_at_the_first_check() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let facts = Facts { - os: "windows".into(), - arch: "x86_64".into(), - ..Facts::default() - }; - let report = evaluate(&facts, &profile, &needs()); - assert!(report.failed()); - assert_eq!(report.checks.len(), 1); - } - - #[test] - fn no_systemd_points_at_foreground_mode() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.systemd_system = false; - facts.wsl = true; - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "systemd"), Level::Fail); - assert!(report.render().contains("--foreground")); - let mut n = needs(); - n.wants_systemd = false; - assert!( - !evaluate(&facts, &profile, &n) - .checks - .iter() - .any(|c| c.id == "systemd") - ); - } -} +//! Preflight: turn `Facts` + `Profile` + what the plan needs into pass / warn / fail checks with a fix for each. +//! +//! Pure logic over data, so it is unit-tested with synthetic hosts (server, laptop under WSL2, driver too old, +//! no cuBLAS, full disk). `leleka up` refuses to start a step that changes anything while a check fails. +use crate::{ + facts::{Facts, Gpu, is_slow_foreign_fs}, + profile::{ARCHIVE_BYTES, KarSource, Profile}, +}; +use serde::Serialize; +use std::path::PathBuf; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Level { + Pass, + Warn, + Fail, +} + +#[derive(Clone, Debug, Serialize)] +pub struct Check { + pub id: &'static str, + pub level: Level, + pub title: String, + pub detail: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub fix: Option, +} + +#[derive(Clone, Debug, Serialize)] +pub struct Report { + pub profile: String, + pub checks: Vec, +} + +impl Report { + pub fn failed(&self) -> bool { + self.checks.iter().any(|c| c.level == Level::Fail) + } + pub fn count(&self, level: Level) -> usize { + self.checks.iter().filter(|c| c.level == level).count() + } + pub fn render(&self) -> String { + let mut out = format!("preflight (profile {}):\n", self.profile); + for check in &self.checks { + let tag = match check.level { + Level::Pass => "ok ", + Level::Warn => "WARN", + Level::Fail => "FAIL", + }; + out.push_str(&format!(" [{tag}] {}: {}\n", check.title, check.detail)); + if check.level != Level::Pass + && let Some(fix) = &check.fix + { + for line in fix.lines() { + out.push_str(&format!(" fix: {line}\n")); + } + } + } + out.push_str(&format!( + " {} failed, {} warnings, {} ok\n", + self.count(Level::Fail), + self.count(Level::Warn), + self.count(Level::Pass) + )); + out + } +} + +/// What the plan will do, as far as it matters for the checks. +#[derive(Clone, Debug, Default)] +pub struct Needs { + pub gpu_index: u32, + pub assets_dir: PathBuf, + pub state_dir: PathBuf, + pub prefix_dir: PathBuf, + /// Bytes of GGUF shards still to download / of KAR archive still to build (0 when present). + pub shard_bytes_missing: u64, + pub kar_bytes_missing: u64, + /// Install the binaries from `bin_src` into the prefix. + pub install_binaries: bool, + /// cuBLAS 12 will be downloaded when the host has none. + pub may_install_cublas: bool, + pub cublas_download_bytes: u64, + pub wants_systemd: bool, + pub service_ports: Vec<(String, u16)>, + pub require_binaries: bool, + /// The release manifest lists the `sm86` feature (companion PTX for cc 8.6 <= cc < 12.0), when known. + pub binary_has_sm86: Option, + /// Ports already owned by this deployment's own running service are not conflicts. + pub service_running: bool, + /// The public API is bound beyond the loopback interface (`--api-bind`). + pub api_bind_open: bool, + /// The sealed archive comes from the parent process (`--kar-fd`): the service does not copy it. + pub kar_fd_inherited: bool, + /// Expert profile present, and its digest is the pinned one (only meaningful for profiles that name one). + pub expert_profile: Option, + /// The resource preset's numbers (`resources.rs`); its shortfalls are reported as checks. + pub resources: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ExpertProfileState { + Absent, + Valid, + WrongDigest, +} + +const GIB: u64 = 1 << 30; + +fn gib(bytes: u64) -> String { + format!("{:.1} GiB", bytes as f64 / GIB as f64) +} + +fn check( + id: &'static str, + level: Level, + title: &str, + detail: String, + fix: Option, +) -> Check { + Check { + id, + level, + title: title.to_owned(), + detail, + fix, + } +} + +fn pass(id: &'static str, title: &str, detail: String) -> Check { + check(id, Level::Pass, title, detail, None) +} + +pub fn evaluate(facts: &Facts, profile: &Profile, needs: &Needs) -> Report { + let mut checks = Vec::new(); + + // 1. platform + if facts.os == "linux" && facts.arch == "x86_64" { + checks.push(pass("platform", "platform", "linux x86_64".into())); + } else { + checks.push(check( + "platform", + Level::Fail, + "platform", + format!( + "{}/{} is not supported; the CUDA runtime is Linux x86_64 only", + facts.os, facts.arch + ), + Some("run on a Linux x86_64 host, or inside WSL2 on Windows".into()), + )); + // Nothing else can be judged on another OS. + return Report { + profile: profile.name.clone(), + checks, + }; + } + + // 2. GPU, driver, architecture, VRAM + let gpu: Option<&Gpu> = facts.gpus.iter().find(|g| g.index == needs.gpu_index); + match gpu { + None => { + let reason = if !facts.nvidia_smi_found { + "nvidia-smi was not found".to_owned() + } else if let Some(error) = &facts.nvidia_smi_error { + format!("nvidia-smi failed: {error}") + } else { + format!( + "GPU {} is not present (found {} GPU(s))", + needs.gpu_index, + facts.gpus.len() + ) + }; + checks.push(check( + "gpu", + Level::Fail, + "NVIDIA GPU", + reason, + Some(if facts.wsl { + "WSL2: install the NVIDIA Windows driver (not a Linux driver inside WSL) and run `wsl --shutdown` once; nvidia-smi must work inside the distribution".into() + } else { + "install the NVIDIA driver (>= 595) and make sure `nvidia-smi` lists the GPU; choose another device with --gpu N".into() + }), + )); + } + Some(gpu) => { + checks.push(pass( + "gpu", + "NVIDIA GPU", + format!( + "{} (GPU {}, sm_{}, {} MiB, {} MiB free)", + gpu.name, + gpu.index, + gpu.sm.map_or("?".into(), |sm| sm.to_string()), + gpu.vram_total_mib, + gpu.vram_free_mib + ), + )); + // driver + match gpu.driver_major() { + Some(major) if major >= profile.min_driver_major => checks.push(pass( + "driver", + "driver version", + format!("{} (>= {})", gpu.driver, profile.min_driver_major), + )), + Some(_) => checks.push(check( + "driver", + Level::Fail, + "driver version", + format!( + "{} is older than {}; the sealed PTX needs ISA 9.2 (CUDA 13.2)", + gpu.driver, profile.min_driver_major + ), + Some(format!( + "update the NVIDIA driver to {} or newer ({})", + profile.min_driver_major, + if facts.wsl { + "the Windows driver on the host" + } else { + "e.g. the nvidia-driver-595 package" + } + )), + )), + None => checks.push(check( + "driver", + Level::Fail, + "driver version", + format!("cannot parse driver version {:?}", gpu.driver), + None, + )), + } + // architecture -> which sealed PTX serves this card + match gpu.sm { + Some(sm) if (120..130).contains(&sm) => checks.push(pass( + "arch", + "architecture", + format!("sm_{sm}: the sealed sm_120 PTX is used as is"), + )), + Some(sm) if (86..120).contains(&sm) => { + let (level, extra, fix) = match needs.binary_has_sm86 { + Some(true) => (Level::Pass, "binaries built with the sm86 feature".to_owned(), None), + Some(false) => ( + Level::Fail, + "these binaries were built WITHOUT the sm86 feature and cannot load on this card".to_owned(), + Some("use a release built with `--features sm86` (every release made by scripts/package-release.sh is)".into()), + ), + None => ( + Level::Warn, + "cannot tell whether the binaries carry the sm86 companions (no MANIFEST.json next to them)".to_owned(), + Some("run from an unpacked release tarball, or build with `--features sm86`".into()), + ), + }; + checks.push(check( + "arch", + level, + "architecture", + format!( + "sm_{sm}: sealed sm_86 companion PTX are selected at load; {extra}" + ), + fix, + )); + } + Some(sm) => checks.push(check( + "arch", + Level::Fail, + "architecture", + format!("sm_{sm} is below sm_86; no sealed PTX exists for it"), + Some("use an RTX 30-series or newer GPU".into()), + )), + None => checks.push(check( + "arch", + Level::Warn, + "architecture", + "compute capability unknown (old nvidia-smi); assuming the profile fits".into(), + Some("upgrade the driver so `nvidia-smi --query-gpu=compute_cap` works".into()), + )), + } + // VRAM + if gpu.vram_total_mib < profile.min_vram_total_mib { + checks.push(check( + "vram", + Level::Fail, + "GPU memory", + format!( + "{} MiB total is below the {} MiB the profile {} needs", + gpu.vram_total_mib, profile.min_vram_total_mib, profile.name + ), + Some("use a larger GPU or a smaller profile (--profile FILE)".into()), + )); + } else { + let budget_mib = profile.gpu_budget_bytes / (1 << 20); + let need_mib = profile.min_vram_free_mib.unwrap_or(budget_mib); + if gpu.vram_free_mib < need_mib { + checks.push(check( + "vram", + Level::Fail, + "GPU memory", + format!( + "{} MiB free but the engine needs {} MiB (budget {}); another process holds {} MiB", + gpu.vram_free_mib, + need_mib, + gib(profile.gpu_budget_bytes), + gpu.vram_total_mib.saturating_sub(gpu.vram_free_mib) + ), + Some("stop the other GPU users (`nvidia-smi` lists them), or lower the budget with --gpu-budget-gib N".into()), + )); + } else { + checks.push(pass( + "vram", + "GPU memory", + format!("{} MiB free, budget {} MiB", gpu.vram_free_mib, budget_mib), + )); + } + } + } + } + + // 2b. resource preset + if let Some(plan) = &needs.resources { + if plan.problems.is_empty() { + checks.push(pass( + "resources", + "resource preset", + format!( + "{}: {} CPU workers, VRAM budget {} MiB", + plan.preset.as_str(), + plan.cpu_workers.map_or("default".to_owned(), |w| w.to_string()), + plan.gpu_budget_bytes / (1 << 20) + ), + )); + } else { + for problem in &plan.problems { + checks.push(check( + "resources", + Level::Fail, + "resource preset", + problem.clone(), + Some("rerun with --preset dedicated, or free the resource named above".into()), + )); + } + } + for warning in &plan.warnings { + checks.push(check("resources", Level::Warn, "resource preset", warning.clone(), None)); + } + } + + // 3. RAM + let ram = &facts.memory; + // An inherited sealed archive is already counted in the parent's memory: only the engine's own need remains. + let min_available = if needs.kar_fd_inherited { + profile + .min_ram_available_bytes + .saturating_sub(ARCHIVE_BYTES) + .max(4 * GIB) + } else { + profile.min_ram_available_bytes + }; + if ram.available == 0 && ram.total == 0 { + checks.push(check( + "ram", + Level::Fail, + "memory", + "cannot read /proc/meminfo".into(), + Some("mount /proc".into()), + )); + } else { + let mut level = Level::Pass; + let mut problems = Vec::new(); + if ram.total < profile.min_ram_total_bytes { + level = Level::Fail; + problems.push(format!( + "{} total is below the {} the profile needs", + gib(ram.total), + gib(profile.min_ram_total_bytes) + )); + } + if ram.available < min_available { + level = Level::Fail; + problems.push(format!( + "{} available is below the {} needed to start (kar_source={})", + gib(ram.available), + gib(min_available), + profile.kar_source.as_str() + )); + } + if let Some(limit) = facts.cgroup_memory_max + && limit < min_available + { + level = Level::Fail; + problems.push(format!( + "the cgroup memory limit {} is below the {} needed", + gib(limit), + gib(min_available) + )); + } + let fix = if level == Level::Fail { + Some(if facts.wsl { + let want = profile.wsl_memory_gib.unwrap_or(32); + format!( + "WSL2 gives this VM only {} of RAM. In %UserProfile%\\.wslconfig put:\n[wsl2]\nmemory={want}GB\nswap=8GB\nthen run `wsl --shutdown` from Windows and start the distribution again", + gib(ram.total) + ) + } else if profile.kar_source == KarSource::Memfd { + "free memory (the sealed archive copy needs the whole archive in RAM), or use the file-backed profile --profile rtx3080-16g if the GPU fits it".into() + } else { + "free memory or add RAM".into() + }) + } else { + None + }; + if problems.is_empty() { + problems.push(format!( + "{} total, {} available", + gib(ram.total), + gib(ram.available) + )); + } + checks.push(check("ram", level, "memory", problems.join("; "), fix)); + } + + // 4. KAR source prerequisites + if profile.kar_source == KarSource::Memfd { + if facts.proc_fd && facts.memfd_ok { + checks.push(pass( + "memfd", + "sealed memfd", + "memfd_create with sealing works and /proc/self/fd is mounted".into(), + )); + } else { + checks.push(check( + "memfd", + Level::Fail, + "sealed memfd", + format!( + "{}{}", + if facts.proc_fd { "" } else { "/proc/self/fd is not mounted; " }, + if facts.memfd_ok { "" } else { "memfd_create with F_SEAL_* failed (kernel < 3.17 or a seccomp filter)" } + ), + Some("run on a host kernel with memfd sealing; in a container allow memfd_create (default Docker seccomp does) and mount /proc".into()), + )); + } + } else if facts.proc_fd { + checks.push(pass( + "memfd", + "KAR file mode", + "the archive is opened read-only from the model volume".into(), + )); + } else { + checks.push(check( + "memfd", + Level::Warn, + "KAR file mode", + "/proc/self/fd is not mounted".into(), + Some("mount /proc".into()), + )); + } + + // 5. cuBLAS 12 + let blas = facts.lib("libcublas.so.12"); + let blas_lt = facts.lib("libcublasLt.so.12"); + match (blas, blas_lt) { + (Some(path), Some(_)) => checks.push(pass( + "cublas", + "cuBLAS 12", + format!("libcublas.so.12 and libcublasLt.so.12 found ({})", path.display()), + )), + _ if needs.may_install_cublas => { + let mut missing = Vec::new(); + if blas.is_none() { + missing.push("libcublas.so.12"); + } + if blas_lt.is_none() { + missing.push("libcublasLt.so.12"); + } + let tools_ok = (facts.tool("curl") || facts.tool("wget")) && facts.tool("tar") && facts.tool("xz"); + checks.push(check( + "cublas", + if tools_ok { Level::Warn } else { Level::Fail }, + "cuBLAS 12", + format!( + "{} not found; the pinned NVIDIA redistributable (~{} MiB) will be downloaded into the prefix{}", + missing.join(", "), + needs.cublas_download_bytes / (1 << 20), + if tools_ok { "" } else { ", but curl/wget, tar and xz are required for that" } + ), + Some("apt install curl xz-utils (or pass --cublas-dir DIR with CUDA 12 cuBLAS), or --no-install-cublas to supply it yourself".into()), + )); + } + _ => checks.push(check( + "cublas", + Level::Fail, + "cuBLAS 12", + "libcublas.so.12 / libcublasLt.so.12 not found; leleka-inference loads them by name".into(), + Some("pass --cublas-dir DIR (CUDA 12 cuBLAS), drop --no-install-cublas to let `up` download the pinned 12.9.1.4 redistributable, or apt install libcublas12".into()), + )), + } + match facts.lib("libcuda.so.1") { + Some(path) => checks.push(pass("libcuda", "CUDA driver library", format!("{}", path.display()))), + None => checks.push(check( + "libcuda", + Level::Warn, + "CUDA driver library", + "libcuda.so.1 was not found by the library search (the engine dlopens it)".into(), + Some(if facts.wsl { + "WSL2 provides it in /usr/lib/wsl/lib; make sure that directory is not removed from the loader path".into() + } else { + "install the NVIDIA driver's libcuda (nvidia-utils / libnvidia-compute packages)".into() + }), + )), + } + + // 6. WSL specifics + if facts.wsl { + let slow: Vec = ["assets", "state", "prefix"] + .iter() + .filter_map(|key| facts.dirs.get(*key)) + .filter(|dir| dir.fs_type.as_deref().is_some_and(is_slow_foreign_fs)) + .map(|dir| { + format!( + "{} ({})", + dir.path.display(), + dir.fs_type.as_deref().unwrap_or("?") + ) + }) + .collect(); + if slow.is_empty() { + checks.push(pass( + "wsl", + "WSL2", + "model volume is on the Linux file system".into(), + )); + } else { + checks.push(check( + "wsl", + Level::Fail, + "WSL2 file system", + format!("{} is on a Windows/network mount; mapped and direct reads are far too slow there", slow.join(", ")), + Some("put --assets (and --state-dir) on the WSL ext4 disk, e.g. under ~/leleka, not under /mnt/c".into()), + )); + } + } + + // 7. disk space + let mut disk_problems = Vec::new(); + let mut disk_notes = Vec::new(); + let mut by_volume: Vec<(String, u64, u64)> = Vec::new(); // (label, need, free) + let assets_need = needs.shard_bytes_missing + needs.kar_bytes_missing + 2 * GIB; + let state_need = 2 * GIB; + let prefix_need = if needs.install_binaries || needs.may_install_cublas { + GIB + if needs.may_install_cublas && blas.is_none() { + 2 * GIB + } else { + 0 + } + } else { + 0 + }; + for (key, need) in [ + ("assets", assets_need), + ("state", state_need), + ("prefix", prefix_need), + ] { + if let Some(dir) = facts.dirs.get(key) { + match dir.free_bytes { + Some(free) => by_volume.push((format!("{key} {}", dir.path.display()), need, free)), + None => { + disk_notes.push(format!("cannot read free space of {}", dir.path.display())) + } + } + } + } + for (label, need, free) in &by_volume { + if free < need { + disk_problems.push(format!( + "{label}: {} free, {} needed", + gib(*free), + gib(*need) + )); + } + } + if disk_problems.is_empty() { + let summary: Vec = by_volume + .iter() + .map(|(label, need, free)| { + format!("{label}: {} free (need {})", gib(*free), gib(*need)) + }) + .collect(); + checks.push(pass( + "disk", + "disk space", + [summary, disk_notes].concat().join("; "), + )); + } else { + checks.push(check( + "disk", + Level::Fail, + "disk space", + disk_problems.join("; "), + Some(format!( + "the first run needs about {} on the model volume (shards {}, archive {}); point --assets at a larger volume. Nothing was downloaded yet", + gib(needs.shard_bytes_missing + needs.kar_bytes_missing), + gib(needs.shard_bytes_missing), + gib(needs.kar_bytes_missing.min(ARCHIVE_BYTES + ARCHIVE_BYTES / 5)) + )), + )); + } + + // 8. tools and service manager + if needs.wants_systemd { + if facts.systemd_system && facts.tool("systemctl") { + checks.push(pass( + "systemd", + "systemd", + "systemd is PID 1 and systemctl is available".into(), + )); + } else { + checks.push(check( + "systemd", + Level::Fail, + "systemd", + "systemd is not running as the service manager here".into(), + Some(if facts.wsl { + "WSL2: add `[boot]\\nsystemd=true` to /etc/wsl.conf and `wsl --shutdown`, or run with --foreground".into() + } else { + "use --foreground to run the service in this terminal".into() + }), + )); + } + } + + // 9. ports + let busy: Vec = needs + .service_ports + .iter() + .filter(|(_, port)| facts.busy_ports.contains(port)) + .map(|(name, port)| format!("{name} {port}")) + .collect(); + if busy.is_empty() { + checks.push(pass("ports", "loopback ports", "free".into())); + } else if needs.service_running { + checks.push(pass( + "ports", + "loopback ports", + format!("{} in use by the running Leleka service", busy.join(", ")), + )); + } else { + checks.push(check( + "ports", + Level::Fail, + "loopback ports", + format!("already in use: {}", busy.join(", ")), + Some("stop the other listener or pick other ports with --api-port / --engine-port / --daemon-port".into()), + )); + } + + if needs.api_bind_open { + checks.push(check( + "api-bind", + Level::Warn, + "API listen address", + "the API is bound beyond the loopback interface; the bearer key is its only protection and there is no TLS".into(), + Some("publish the port to 127.0.0.1 only (docker run -p 127.0.0.1:8081:8081) or put a TLS proxy / SSH tunnel in front".into()), + )); + } + + // 10. binaries + if needs.require_binaries { + let missing: Vec<&String> = facts + .binaries + .iter() + .filter(|(_, ok)| !**ok) + .map(|(name, _)| name) + .collect(); + if missing.is_empty() { + checks.push(pass( + "binaries", + "binaries", + "all six runtime binaries are present".into(), + )); + } else { + checks.push(check( + "binaries", + Level::Fail, + "binaries", + format!("missing or not executable: {}", missing.iter().map(|s| s.as_str()).collect::>().join(", ")), + Some("run `leleka up` from the unpacked release tarball (bin/), or pass --bin-src DIR".into()), + )); + } + } + + // 11. gated assets / credentials hints + if (needs.shard_bytes_missing > 0) && !facts.hf_token_set { + checks.push(check( + "hf-token", + Level::Warn, + "Hugging Face token", + "HF_TOKEN is not set; the pinned shard repository is fetched anonymously".into(), + Some("if the download answers 401/403, export HF_TOKEN=... (it is only sent to https://huggingface.co and never printed)".into()), + )); + } + match &needs.expert_profile { + Some(ExpertProfileState::Absent) if profile.expert_profile.is_some() => checks.push(check( + "expert-profile", + Level::Warn, + "VRAM expert tier", + format!("{} is not in the assets directory; the engine runs without the ranked VRAM expert tier (slower)", profile.expert_profile.as_deref().unwrap_or("")), + Some("copy the upstream data/expert-profile.bin (sha256 8f59b4aa...388975baf) there, then rerun".into()), + )), + Some(ExpertProfileState::WrongDigest) => checks.push(check( + "expert-profile", + Level::Warn, + "VRAM expert tier", + "the expert profile does not have the pinned SHA-256; it will not be used".into(), + None, + )), + _ => {} + } + + Report { + profile: profile.name.clone(), + checks, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::facts::{DirFact, Memory}; + + fn server_facts() -> Facts { + let mut facts = Facts { + os: "linux".into(), + arch: "x86_64".into(), + nvidia_smi_found: true, + gpus: vec![Gpu { + index: 0, + name: "NVIDIA GeForce RTX 5090".into(), + driver: "595.99.02".into(), + vram_total_mib: 32607, + vram_free_mib: 32105, + sm: Some(120), + }], + memory: Memory { + total: 121 * GIB, + available: 118 * GIB, + swap_total: 0, + }, + systemd_system: true, + proc_fd: true, + memfd_ok: true, + ..Facts::default() + }; + facts.libs.insert( + "libcublas.so.12".into(), + Some("/opt/c/libcublas.so.12".into()), + ); + facts.libs.insert( + "libcublasLt.so.12".into(), + Some("/opt/c/libcublasLt.so.12".into()), + ); + facts.libs.insert( + "libcuda.so.1".into(), + Some("/usr/lib/x86_64-linux-gnu/libcuda.so.1".into()), + ); + for tool in ["curl", "tar", "xz", "systemctl"] { + facts.tools.insert(tool.into(), true); + } + for key in ["assets", "state", "prefix"] { + facts.dirs.insert( + key.into(), + DirFact { + path: format!("/data/{key}").into(), + free_bytes: Some(900 * GIB), + fs_type: Some("ext4".into()), + }, + ); + } + facts + } + + fn needs() -> Needs { + Needs { + assets_dir: "/data/assets".into(), + shard_bytes_missing: 83_617_662_656, + kar_bytes_missing: ARCHIVE_BYTES * 12 / 10, + install_binaries: true, + may_install_cublas: true, + cublas_download_bytes: 500 << 20, + wants_systemd: true, + service_ports: vec![("api".into(), 8081), ("engine".into(), 18766)], + ..Needs::default() + } + } + + fn level_of(report: &Report, id: &str) -> Level { + report + .checks + .iter() + .find(|c| c.id == id) + .unwrap_or_else(|| panic!("no check {id}")) + .level + } + + #[test] + fn healthy_server_passes_everything() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let report = evaluate(&server_facts(), &profile, &needs()); + assert!(!report.failed(), "{}", report.render()); + assert_eq!(level_of(&report, "arch"), Level::Pass); + assert_eq!(level_of(&report, "memfd"), Level::Pass); + } + + #[test] + fn old_driver_and_busy_gpu_fail_with_actionable_text() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.gpus[0].driver = "580.65.06".into(); + facts.gpus[0].vram_free_mib = 9000; + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "driver"), Level::Fail); + assert_eq!(level_of(&report, "vram"), Level::Fail); + let text = report.render(); + assert!(text.contains("580.65.06 is older than 595"), "{text}"); + assert!(text.contains("--gpu-budget-gib"), "{text}"); + } + + #[test] + fn no_gpu_names_the_wsl_remedy_under_wsl() { + let profile = Profile::builtin("rtx3080-16g").unwrap(); + let mut facts = server_facts(); + facts.gpus.clear(); + facts.nvidia_smi_found = false; + facts.wsl = true; + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "gpu"), Level::Fail); + assert!(report.render().contains("Windows driver")); + } + + #[test] + fn laptop_under_default_wsl_memory_gets_wslconfig_advice() { + let profile = Profile::builtin("rtx3080-16g").unwrap(); + let mut facts = server_facts(); + facts.wsl = true; + facts.gpus[0] = Gpu { + index: 0, + name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(), + driver: "617.42".into(), + vram_total_mib: 16384, + vram_free_mib: 15234, + sm: Some(86), + }; + facts.memory = Memory { + total: 12 * GIB, + available: 9 * GIB, + swap_total: 0, + }; + let mut n = needs(); + n.binary_has_sm86 = Some(true); + let report = evaluate(&facts, &profile, &n); + assert_eq!(level_of(&report, "ram"), Level::Fail); + let text = report.render(); + assert!( + text.contains(".wslconfig") + && text.contains("memory=32GB") + && text.contains("wsl --shutdown"), + "{text}" + ); + assert_eq!(level_of(&report, "arch"), Level::Pass); + // 24 GB as WSL2 gives by default passes. + facts.memory = Memory { + total: 24_447_308 * 1024, + available: 22 * GIB, + swap_total: 0, + }; + let report = evaluate(&facts, &profile, &n); + assert!(!report.failed(), "{}", report.render()); + } + + #[test] + fn sm86_card_needs_binaries_with_the_companion_feature() { + let profile = Profile::builtin("rtx3080-16g").unwrap(); + let mut facts = server_facts(); + facts.gpus[0].sm = Some(86); + facts.gpus[0].vram_total_mib = 16384; + facts.gpus[0].vram_free_mib = 15000; + let mut n = needs(); + n.binary_has_sm86 = Some(false); + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "arch"), + Level::Fail + ); + n.binary_has_sm86 = None; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "arch"), + Level::Warn + ); + } + + #[test] + fn model_volume_on_a_windows_mount_is_refused_under_wsl() { + let profile = Profile::builtin("rtx3080-16g").unwrap(); + let mut facts = server_facts(); + facts.wsl = true; + facts.dirs.get_mut("assets").unwrap().fs_type = Some("9p".into()); + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "wsl"), Level::Fail); + assert!(report.render().contains("/mnt/c")); + } + + #[test] + fn missing_cublas_is_fixable_unless_the_tools_are_missing_too() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.libs.insert("libcublas.so.12".into(), None); + facts.libs.insert("libcublasLt.so.12".into(), None); + assert_eq!( + level_of(&evaluate(&facts, &profile, &needs()), "cublas"), + Level::Warn + ); + facts.tools.insert("xz".into(), false); + assert_eq!( + level_of(&evaluate(&facts, &profile, &needs()), "cublas"), + Level::Fail + ); + let mut n = needs(); + n.may_install_cublas = false; + facts.tools.insert("xz".into(), true); + let report = evaluate(&facts, &profile, &n); + assert_eq!(level_of(&report, "cublas"), Level::Fail); + assert!(report.render().contains("--cublas-dir")); + } + + #[test] + fn low_disk_reports_the_volume_before_anything_is_downloaded() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.dirs.get_mut("assets").unwrap().free_bytes = Some(53 * GIB); + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "disk"), Level::Fail); + let text = report.render(); + assert!( + text.contains("assets /data/assets: 53.0 GiB free"), + "{text}" + ); + assert!(text.contains("Nothing was downloaded yet"), "{text}"); + // With the model already present the same volume is fine. + let mut n = needs(); + n.shard_bytes_missing = 0; + n.kar_bytes_missing = 0; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "disk"), + Level::Pass + ); + } + + #[test] + fn memory_is_judged_by_the_profile_kar_source() { + let server = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.memory = Memory { + total: 64 * GIB, + available: 40 * GIB, + swap_total: 0, + }; + let report = evaluate(&facts, &server, &needs()); + assert_eq!(level_of(&report, "ram"), Level::Fail); + assert!( + report + .render() + .contains("sealed archive copy needs the whole archive in RAM") + ); + facts.memory = Memory { + total: 128 * GIB, + available: 100 * GIB, + swap_total: 0, + }; + facts.cgroup_memory_max = Some(32 * GIB); + assert_eq!( + level_of(&evaluate(&facts, &server, &needs()), "ram"), + Level::Fail + ); + } + + #[test] + fn an_inherited_sealed_archive_is_not_counted_twice() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + // 70 GiB available: not enough to copy the archive and hold the 50 GB expert bank, enough when the + // parent already holds the sealed archive. + facts.memory = Memory { + total: 121 * GIB, + available: 70 * GIB, + swap_total: 0, + }; + assert_eq!( + level_of(&evaluate(&facts, &profile, &needs()), "ram"), + Level::Fail + ); + let mut n = needs(); + n.kar_fd_inherited = true; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "ram"), + Level::Pass + ); + facts.memory.available = 20 * GIB; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "ram"), + Level::Fail + ); + } + + #[test] + fn a_running_service_owns_its_ports_and_a_stranger_does_not() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.busy_ports = vec![8081]; + assert_eq!( + level_of(&evaluate(&facts, &profile, &needs()), "ports"), + Level::Fail + ); + let mut n = needs(); + n.service_running = true; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "ports"), + Level::Pass + ); + } + + #[test] + fn other_platforms_stop_at_the_first_check() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let facts = Facts { + os: "windows".into(), + arch: "x86_64".into(), + ..Facts::default() + }; + let report = evaluate(&facts, &profile, &needs()); + assert!(report.failed()); + assert_eq!(report.checks.len(), 1); + } + + #[test] + fn no_systemd_points_at_foreground_mode() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.systemd_system = false; + facts.wsl = true; + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "systemd"), Level::Fail); + assert!(report.render().contains("--foreground")); + let mut n = needs(); + n.wants_systemd = false; + assert!( + !evaluate(&facts, &profile, &n) + .checks + .iter() + .any(|c| c.id == "systemd") + ); + } +} diff --git a/crates/deploy/src/resources.rs b/crates/deploy/src/resources.rs index 06394fab..edea8b05 100644 --- a/crates/deploy/src/resources.rs +++ b/crates/deploy/src/resources.rs @@ -1,377 +1,377 @@ -//! Resource presets: how much of the host `leleka up` lets the engine take (`docs/deploy.md`, "Resource presets"). -//! -//! * `dedicated` (default): the host belongs to the runtime. The profile's VRAM budget as it is, engine defaults for the -//! memory governor, CPU workers up to the useful maximum. -//! * `workstation`: Docker, agents and the IDE share the machine. At least 4 cores (8 on hosts with more than 16) stay -//! free of engine workers, the memory governor keeps 8-16 GiB of host RAM free (it sheds the prefix cache first), and -//! about 4 GiB of VRAM is left to the desktop; the expert tier is sized from what remains. -//! -//! `compute` is a pure function of the host facts and the profile; `apply` writes the result into the profile and the -//! engine environment. Explicit profile fields and command-line overrides always win over a preset. -use std::collections::BTreeMap; - -use serde::{Deserialize, Serialize}; - -use crate::{ - facts::{Facts, Gpu}, - profile::{ARCHIVE_BYTES, ExpertSource, KarSource, Profile}, -}; - -const GIB: u64 = 1 << 30; -const MIB: u64 = 1 << 20; -/// Decode is bound by host memory bandwidth: more CPU expert workers than this do not help (`docs/roofline.md`). -const MAX_USEFUL_WORKERS: u32 = 8; -/// VRAM the desktop/browser keeps in the workstation preset. -const WORKSTATION_VRAM_MARGIN_MIB: u64 = 4096; -/// Resident host memory of a memfd-backed engine besides the archive (tokenizer, pinned buffers, CUDA host state). -const ENGINE_EXTRA_BYTES: u64 = 3 * GIB; -/// Host memory the mapped form keeps for the engine itself, the tokenizer and the working set of the page cache. -const MAPPED_OVERHEAD_BYTES: u64 = 8 * GIB; -/// What the mapped form still needs available to start. -const MAPPED_MIN_AVAILABLE_BYTES: u64 = 10 * GIB; -pub const CPU_WORKERS_ENV: &str = "LELEKA_ORIGINAL_SERVE_CPU_WORKERS"; - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum Preset { - #[default] - Dedicated, - Workstation, -} - -impl Preset { - pub fn as_str(self) -> &'static str { - match self { - Preset::Dedicated => "dedicated", - Preset::Workstation => "workstation", - } - } - - pub fn parse(text: &str) -> Result { - match text { - "dedicated" => Ok(Preset::Dedicated), - "workstation" => Ok(Preset::Workstation), - other => Err(format!( - "unknown preset '{other}' (use dedicated or workstation)" - )), - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize)] -pub struct ResourcePlan { - pub preset: Preset, - pub cores: u32, - /// `None` when the core count is unknown: the engine keeps its own default. - pub cpu_workers: Option, - pub gpu_budget_bytes: u64, - /// The profile's `min_vram_free_mib`, lowered when the preset lowered the budget. - pub min_vram_free_mib: Option, - pub vram_free_after_mib: Option, - /// Host RAM the memory governor keeps available: (soft, hard) floors in MiB, `None` = engine defaults. - pub ram_floors_mib: Option<(u64, u64)>, - pub ram_expected_free_after_bytes: Option, - /// Host RAM cannot hold the sealed archive and the experts next to the free target: serve from SSD/HDD instead - /// (archive as a read-only file, experts memory-mapped, this many GiB of them page-locked). - pub mapped_resident_gib: Option, - /// Shortfalls that make the preset unachievable (the preflight fails on them). - pub problems: Vec, - pub warnings: Vec, -} - -fn gib_text(bytes: u64) -> String { - format!("{:.1} GiB", bytes as f64 / GIB as f64) -} - -/// RAM the workstation preset keeps free: 8 GiB on small hosts up to 16 GiB from 64 GiB of RAM. -pub fn workstation_ram_target(total: u64) -> u64 { - if total >= 64 * GIB { - 16 * GIB - } else if total >= 32 * GIB { - 12 * GIB - } else { - 8 * GIB - } -} - -pub fn compute(facts: &Facts, gpu: Option<&Gpu>, profile: &Profile, preset: Preset) -> ResourcePlan { - let mut plan = ResourcePlan { - preset, - cores: facts.cpu_cores, - cpu_workers: None, - gpu_budget_bytes: profile.gpu_budget_bytes, - min_vram_free_mib: profile.min_vram_free_mib, - vram_free_after_mib: None, - ram_floors_mib: None, - ram_expected_free_after_bytes: None, - mapped_resident_gib: None, - problems: Vec::new(), - warnings: Vec::new(), - }; - - // CPU - if facts.cpu_cores > 0 { - let cores = facts.cpu_cores; - let leave = match preset { - Preset::Dedicated => 2, - Preset::Workstation if cores <= 16 => 4, - Preset::Workstation => 8, - }; - plan.cpu_workers = Some(cores.saturating_sub(leave).clamp(1, MAX_USEFUL_WORKERS)); - if preset == Preset::Workstation && cores < leave + 1 { - plan.warnings.push(format!( - "only {cores} CPU cores: the workstation preset cannot leave {leave} of them free (1 worker)" - )); - } - } - - // VRAM - if let Some(gpu) = gpu { - let budget_mib = profile.gpu_budget_bytes / MIB; - if preset == Preset::Workstation { - let cap_mib = (gpu.vram_free_mib.saturating_sub(WORKSTATION_VRAM_MARGIN_MIB) / 1024) * 1024; - if cap_mib < budget_mib { - plan.gpu_budget_bytes = cap_mib * MIB; - let need = profile.min_vram_free_mib.unwrap_or(budget_mib).min(cap_mib); - plan.min_vram_free_mib = Some(need); - // Below half of the profile budget the expert tier and KV window shrink past what was measured. - if cap_mib * 2 < budget_mib { - plan.problems.push(format!( - "the workstation preset leaves {} MiB of VRAM free, which gives the engine {} MiB; the profile {} needs about {} MiB (free the GPU or use --preset dedicated)", - WORKSTATION_VRAM_MARGIN_MIB, cap_mib, profile.name, budget_mib - )); - } - } - } - let used = (plan.gpu_budget_bytes / MIB).max(plan.min_vram_free_mib.unwrap_or(0)); - plan.vram_free_after_mib = Some(gpu.vram_free_mib.saturating_sub(used)); - } - - // Host RAM - let ram = &facts.memory; - if ram.total > 0 { - let target = match preset { - Preset::Workstation => workstation_ram_target(ram.total), - Preset::Dedicated => profile.memory.soft_floor_mib.map_or(4 * GIB, |mib| mib * MIB), - }; - if preset == Preset::Workstation { - let soft = target / MIB; - plan.ram_floors_mib = Some((soft, soft / 2)); - } - if profile.kar_source == KarSource::Memfd { - let footprint = ARCHIVE_BYTES + ENGINE_EXTRA_BYTES; - let after = ram.available.saturating_sub(footprint); - if after >= target { - plan.ram_expected_free_after_bytes = Some(after); - } else { - // Not enough RAM for the pinned form: map the archive and the experts from disk instead of failing. - let resident = ram.available.saturating_sub(target + MAPPED_OVERHEAD_BYTES) / GIB; - let resident = resident.min(u64::from(u32::MAX)) as u32; - plan.mapped_resident_gib = Some(resident); - plan.ram_expected_free_after_bytes = Some(ram.available.saturating_sub(u64::from(resident) * GIB + MAPPED_OVERHEAD_BYTES)); - plan.warnings.push(format!( - "{} of host RAM available, the pinned form needs about {} plus {} free: the archive and the experts are served from disk (memory-mapped), {} GiB of experts stay page-locked; decode is slower than with everything in RAM", - gib_text(ram.available), - gib_text(footprint), - gib_text(target), - resident - )); - } - } - } - plan -} - -/// Write the plan into the profile and the engine environment. Values the profile or the command line already set win. -pub fn apply( - plan: &ResourcePlan, - profile: &mut Profile, - engine_env: &mut BTreeMap, - budget_overridden: bool, -) { - if !budget_overridden { - profile.gpu_budget_bytes = plan.gpu_budget_bytes; - profile.min_vram_free_mib = plan.min_vram_free_mib; - } - if let Some((soft, hard)) = plan.ram_floors_mib { - // The profile's floors are its dedicated-host values; the workstation preset only raises them. - let raised = |current: Option, wanted: u64| Some(current.map_or(wanted, |c| c.max(wanted))); - profile.memory.soft_floor_mib = raised(profile.memory.soft_floor_mib, soft); - profile.memory.hard_floor_mib = raised(profile.memory.hard_floor_mib, hard); - } - if let Some(resident) = plan.mapped_resident_gib { - profile.kar_source = KarSource::File; - profile.expert_source = ExpertSource::Mapped; - profile.memory.resident_budget_gib.get_or_insert(resident); - profile.memory.lock = Some("off".into()); - profile.memory.heal = Some(false); - profile.min_ram_total_bytes = profile.min_ram_total_bytes.min(16 * GIB); - profile.min_ram_available_bytes = profile.min_ram_available_bytes.min(MAPPED_MIN_AVAILABLE_BYTES); - } - if let Some(workers) = plan.cpu_workers - && !profile.engine_env.contains_key(CPU_WORKERS_ENV) - { - engine_env.insert(CPU_WORKERS_ENV.to_owned(), workers.to_string()); - } -} - -impl ResourcePlan { - /// The table `leleka up` prints: what the engine takes and what stays free. - pub fn render(&self, facts: &Facts) -> String { - let mut out = format!("resources ({} preset)\n", self.preset.as_str()); - if let Some(workers) = self.cpu_workers { - out.push_str(&format!( - " cpu {workers} expert workers of {} cores; ~{} cores stay free\n", - self.cores, - self.cores.saturating_sub(workers + 1) - )); - } - out.push_str(&format!( - " vram budget {}{}\n", - gib_text(self.gpu_budget_bytes), - self.vram_free_after_mib - .map_or(String::new(), |free| format!(", ~{} MiB stay free", free)) - )); - match (self.ram_floors_mib, self.ram_expected_free_after_bytes) { - (Some((soft, hard)), after) => out.push_str(&format!( - " host ram caches shed below {} MiB available, requests refused below {} MiB{}\n", - soft, - hard, - after.map_or(String::new(), |b| format!("; ~{} free after the start", gib_text(b))) - )), - (None, Some(after)) => out.push_str(&format!( - " host ram engine defaults; ~{} of {} free after the start\n", - gib_text(after), - gib_text(facts.memory.total) - )), - (None, None) => {} - } - for warning in &self.warnings { - out.push_str(&format!(" warning {warning}\n")); - } - out - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::facts::Memory; - - fn gpu(total: u64, free: u64) -> Gpu { - Gpu { index: 0, name: "gpu".into(), driver: "595.1".into(), vram_total_mib: total, vram_free_mib: free, sm: Some(120) } - } - - fn host(cores: u32, ram_gib: u64, avail_gib: u64) -> Facts { - Facts { - cpu_cores: cores, - memory: Memory { total: ram_gib * GIB, available: avail_gib * GIB, swap_total: 0 }, - ..Facts::default() - } - } - - fn server() -> Profile { - Profile::builtin("rtx5090-32g").unwrap() - } - fn laptop() -> Profile { - Profile::builtin("rtx3080-16g").unwrap() - } - - #[test] - fn dedicated_takes_the_profile_and_caps_workers_at_the_useful_maximum() { - let plan = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Dedicated); - assert_eq!(plan.cpu_workers, Some(8)); - assert_eq!(plan.gpu_budget_bytes, server().gpu_budget_bytes); - assert_eq!(plan.ram_floors_mib, None); - assert!(plan.problems.is_empty()); - } - - #[test] - fn workstation_leaves_cores_ram_and_vram_on_the_server() { - let plan = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Workstation); - assert_eq!(plan.cpu_workers, Some(8), "32 cores - 8 left free = 24, capped at 8"); - assert_eq!(plan.gpu_budget_bytes, 27 * GIB, "32100 MiB free - 4096 MiB, rounded down to GiB"); - assert_eq!(plan.ram_floors_mib, Some((16384, 8192))); - assert!(plan.problems.is_empty(), "{:?}", plan.problems); - let mut profile = server(); - let mut env = BTreeMap::new(); - apply(&plan, &mut profile, &mut env, false); - assert_eq!(profile.gpu_budget_bytes, 27 * GIB); - assert_eq!(profile.memory.soft_floor_mib, Some(16384)); - assert_eq!(profile.memory.hard_floor_mib, Some(8192)); - assert_eq!(env.get(CPU_WORKERS_ENV).map(String::as_str), Some("8")); - } - - #[test] - fn workstation_on_a_16_thread_laptop_leaves_four_cores_and_scales_the_ram_target() { - let plan = compute(&host(16, 24, 21), Some(&gpu(16384, 15500)), &laptop(), Preset::Workstation); - assert_eq!(plan.cpu_workers, Some(8)); - assert_eq!(plan.ram_floors_mib, Some((8192, 4096))); - assert_eq!(plan.gpu_budget_bytes, 11 * GIB); - assert!(plan.problems.is_empty(), "{:?}", plan.problems); - let small = compute(&host(8, 24, 21), Some(&gpu(16384, 15500)), &laptop(), Preset::Workstation); - assert_eq!(small.cpu_workers, Some(4)); - } - - #[test] - fn an_unachievable_workstation_vram_target_is_a_problem_not_a_silent_shrink() { - let plan = compute(&host(16, 24, 21), Some(&gpu(16384, 9000)), &laptop(), Preset::Workstation); - assert!(!plan.problems.is_empty()); - let dedicated = compute(&host(16, 24, 21), Some(&gpu(16384, 9000)), &laptop(), Preset::Dedicated); - assert!(dedicated.problems.is_empty()); - } - - #[test] - fn explicit_values_win_and_floors_are_only_raised() { - let plan = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Workstation); - let mut profile = server(); - profile.memory.soft_floor_mib = Some(30000); - profile.engine_env.insert(CPU_WORKERS_ENV.into(), "3".into()); - let mut env = BTreeMap::new(); - apply(&plan, &mut profile, &mut env, true); - assert_eq!(profile.gpu_budget_bytes, server().gpu_budget_bytes, "--gpu-budget-gib wins"); - assert_eq!(profile.memory.soft_floor_mib, Some(30000)); - assert_eq!(profile.memory.hard_floor_mib, Some(8192), "floors are only ever raised"); - assert!(env.is_empty()); - } - - #[test] - fn unknown_core_count_leaves_the_engine_default() { - let plan = compute(&host(0, 121, 100), None, &server(), Preset::Workstation); - assert_eq!(plan.cpu_workers, None); - } - - #[test] - fn not_enough_ram_for_the_pinned_form_switches_to_mapped_files_instead_of_failing() { - // 121 GiB host with 70 GiB available: 58 GiB of pinned archive leaves 12 GiB, below the 16 GiB workstation target - let plan = compute(&host(32, 121, 70), Some(&gpu(32607, 32100)), &server(), Preset::Workstation); - assert_eq!(plan.mapped_resident_gib, Some(46), "70 - 16 target - 8 overhead"); - assert_eq!(plan.warnings.len(), 1, "{:?}", plan.warnings); - assert!(plan.render(&host(32, 121, 70)).contains("served from disk")); - let mut profile = server(); - let mut env = BTreeMap::new(); - apply(&plan, &mut profile, &mut env, false); - assert_eq!(profile.kar_source, KarSource::File); - assert_eq!(profile.expert_source, ExpertSource::Mapped); - assert_eq!(profile.memory.resident_budget_gib, Some(46)); - assert_eq!(profile.memory.lock.as_deref(), Some("off")); - assert!(profile.min_ram_available_bytes <= 10 * GIB && profile.min_ram_total_bytes <= 16 * GIB); - profile.validate().unwrap(); - } - - #[test] - fn a_small_host_gets_zero_resident_experts_and_dedicated_switches_too() { - let plan = compute(&host(16, 24, 12), Some(&gpu(16384, 15500)), &server(), Preset::Dedicated); - assert_eq!(plan.mapped_resident_gib, Some(0), "12 GiB available is below the 4 GiB target plus 8 GiB overhead"); - let ample = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Workstation); - assert_eq!(ample.mapped_resident_gib, None); - assert!(ample.warnings.is_empty(), "{:?}", ample.warnings); - } - - #[test] - fn presets_parse_and_default_to_dedicated() { - assert_eq!(Preset::default(), Preset::Dedicated); - assert_eq!(Preset::parse("workstation").unwrap(), Preset::Workstation); - assert!(Preset::parse("x").is_err()); - } -} +//! Resource presets: how much of the host `leleka up` lets the engine take (`docs/deploy.md`, "Resource presets"). +//! +//! * `dedicated` (default): the host belongs to the runtime. The profile's VRAM budget as it is, engine defaults for the +//! memory governor, CPU workers up to the useful maximum. +//! * `workstation`: Docker, agents and the IDE share the machine. At least 4 cores (8 on hosts with more than 16) stay +//! free of engine workers, the memory governor keeps 8-16 GiB of host RAM free (it sheds the prefix cache first), and +//! about 4 GiB of VRAM is left to the desktop; the expert tier is sized from what remains. +//! +//! `compute` is a pure function of the host facts and the profile; `apply` writes the result into the profile and the +//! engine environment. Explicit profile fields and command-line overrides always win over a preset. +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::{ + facts::{Facts, Gpu}, + profile::{ARCHIVE_BYTES, ExpertSource, KarSource, Profile}, +}; + +const GIB: u64 = 1 << 30; +const MIB: u64 = 1 << 20; +/// Decode is bound by host memory bandwidth: more CPU expert workers than this do not help (`docs/roofline.md`). +const MAX_USEFUL_WORKERS: u32 = 8; +/// VRAM the desktop/browser keeps in the workstation preset. +const WORKSTATION_VRAM_MARGIN_MIB: u64 = 4096; +/// Resident host memory of a memfd-backed engine besides the archive (tokenizer, pinned buffers, CUDA host state). +const ENGINE_EXTRA_BYTES: u64 = 3 * GIB; +/// Host memory the mapped form keeps for the engine itself, the tokenizer and the working set of the page cache. +const MAPPED_OVERHEAD_BYTES: u64 = 8 * GIB; +/// What the mapped form still needs available to start. +const MAPPED_MIN_AVAILABLE_BYTES: u64 = 10 * GIB; +pub const CPU_WORKERS_ENV: &str = "LELEKA_ORIGINAL_SERVE_CPU_WORKERS"; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Preset { + #[default] + Dedicated, + Workstation, +} + +impl Preset { + pub fn as_str(self) -> &'static str { + match self { + Preset::Dedicated => "dedicated", + Preset::Workstation => "workstation", + } + } + + pub fn parse(text: &str) -> Result { + match text { + "dedicated" => Ok(Preset::Dedicated), + "workstation" => Ok(Preset::Workstation), + other => Err(format!( + "unknown preset '{other}' (use dedicated or workstation)" + )), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct ResourcePlan { + pub preset: Preset, + pub cores: u32, + /// `None` when the core count is unknown: the engine keeps its own default. + pub cpu_workers: Option, + pub gpu_budget_bytes: u64, + /// The profile's `min_vram_free_mib`, lowered when the preset lowered the budget. + pub min_vram_free_mib: Option, + pub vram_free_after_mib: Option, + /// Host RAM the memory governor keeps available: (soft, hard) floors in MiB, `None` = engine defaults. + pub ram_floors_mib: Option<(u64, u64)>, + pub ram_expected_free_after_bytes: Option, + /// Host RAM cannot hold the sealed archive and the experts next to the free target: serve from SSD/HDD instead + /// (archive as a read-only file, experts memory-mapped, this many GiB of them page-locked). + pub mapped_resident_gib: Option, + /// Shortfalls that make the preset unachievable (the preflight fails on them). + pub problems: Vec, + pub warnings: Vec, +} + +fn gib_text(bytes: u64) -> String { + format!("{:.1} GiB", bytes as f64 / GIB as f64) +} + +/// RAM the workstation preset keeps free: 8 GiB on small hosts up to 16 GiB from 64 GiB of RAM. +pub fn workstation_ram_target(total: u64) -> u64 { + if total >= 64 * GIB { + 16 * GIB + } else if total >= 32 * GIB { + 12 * GIB + } else { + 8 * GIB + } +} + +pub fn compute(facts: &Facts, gpu: Option<&Gpu>, profile: &Profile, preset: Preset) -> ResourcePlan { + let mut plan = ResourcePlan { + preset, + cores: facts.cpu_cores, + cpu_workers: None, + gpu_budget_bytes: profile.gpu_budget_bytes, + min_vram_free_mib: profile.min_vram_free_mib, + vram_free_after_mib: None, + ram_floors_mib: None, + ram_expected_free_after_bytes: None, + mapped_resident_gib: None, + problems: Vec::new(), + warnings: Vec::new(), + }; + + // CPU + if facts.cpu_cores > 0 { + let cores = facts.cpu_cores; + let leave = match preset { + Preset::Dedicated => 2, + Preset::Workstation if cores <= 16 => 4, + Preset::Workstation => 8, + }; + plan.cpu_workers = Some(cores.saturating_sub(leave).clamp(1, MAX_USEFUL_WORKERS)); + if preset == Preset::Workstation && cores < leave + 1 { + plan.warnings.push(format!( + "only {cores} CPU cores: the workstation preset cannot leave {leave} of them free (1 worker)" + )); + } + } + + // VRAM + if let Some(gpu) = gpu { + let budget_mib = profile.gpu_budget_bytes / MIB; + if preset == Preset::Workstation { + let cap_mib = (gpu.vram_free_mib.saturating_sub(WORKSTATION_VRAM_MARGIN_MIB) / 1024) * 1024; + if cap_mib < budget_mib { + plan.gpu_budget_bytes = cap_mib * MIB; + let need = profile.min_vram_free_mib.unwrap_or(budget_mib).min(cap_mib); + plan.min_vram_free_mib = Some(need); + // Below half of the profile budget the expert tier and KV window shrink past what was measured. + if cap_mib * 2 < budget_mib { + plan.problems.push(format!( + "the workstation preset leaves {} MiB of VRAM free, which gives the engine {} MiB; the profile {} needs about {} MiB (free the GPU or use --preset dedicated)", + WORKSTATION_VRAM_MARGIN_MIB, cap_mib, profile.name, budget_mib + )); + } + } + } + let used = (plan.gpu_budget_bytes / MIB).max(plan.min_vram_free_mib.unwrap_or(0)); + plan.vram_free_after_mib = Some(gpu.vram_free_mib.saturating_sub(used)); + } + + // Host RAM + let ram = &facts.memory; + if ram.total > 0 { + let target = match preset { + Preset::Workstation => workstation_ram_target(ram.total), + Preset::Dedicated => profile.memory.soft_floor_mib.map_or(4 * GIB, |mib| mib * MIB), + }; + if preset == Preset::Workstation { + let soft = target / MIB; + plan.ram_floors_mib = Some((soft, soft / 2)); + } + if profile.kar_source == KarSource::Memfd { + let footprint = ARCHIVE_BYTES + ENGINE_EXTRA_BYTES; + let after = ram.available.saturating_sub(footprint); + if after >= target { + plan.ram_expected_free_after_bytes = Some(after); + } else { + // Not enough RAM for the pinned form: map the archive and the experts from disk instead of failing. + let resident = ram.available.saturating_sub(target + MAPPED_OVERHEAD_BYTES) / GIB; + let resident = resident.min(u64::from(u32::MAX)) as u32; + plan.mapped_resident_gib = Some(resident); + plan.ram_expected_free_after_bytes = Some(ram.available.saturating_sub(u64::from(resident) * GIB + MAPPED_OVERHEAD_BYTES)); + plan.warnings.push(format!( + "{} of host RAM available, the pinned form needs about {} plus {} free: the archive and the experts are served from disk (memory-mapped), {} GiB of experts stay page-locked; decode is slower than with everything in RAM", + gib_text(ram.available), + gib_text(footprint), + gib_text(target), + resident + )); + } + } + } + plan +} + +/// Write the plan into the profile and the engine environment. Values the profile or the command line already set win. +pub fn apply( + plan: &ResourcePlan, + profile: &mut Profile, + engine_env: &mut BTreeMap, + budget_overridden: bool, +) { + if !budget_overridden { + profile.gpu_budget_bytes = plan.gpu_budget_bytes; + profile.min_vram_free_mib = plan.min_vram_free_mib; + } + if let Some((soft, hard)) = plan.ram_floors_mib { + // The profile's floors are its dedicated-host values; the workstation preset only raises them. + let raised = |current: Option, wanted: u64| Some(current.map_or(wanted, |c| c.max(wanted))); + profile.memory.soft_floor_mib = raised(profile.memory.soft_floor_mib, soft); + profile.memory.hard_floor_mib = raised(profile.memory.hard_floor_mib, hard); + } + if let Some(resident) = plan.mapped_resident_gib { + profile.kar_source = KarSource::File; + profile.expert_source = ExpertSource::Mapped; + profile.memory.resident_budget_gib.get_or_insert(resident); + profile.memory.lock = Some("off".into()); + profile.memory.heal = Some(false); + profile.min_ram_total_bytes = profile.min_ram_total_bytes.min(16 * GIB); + profile.min_ram_available_bytes = profile.min_ram_available_bytes.min(MAPPED_MIN_AVAILABLE_BYTES); + } + if let Some(workers) = plan.cpu_workers + && !profile.engine_env.contains_key(CPU_WORKERS_ENV) + { + engine_env.insert(CPU_WORKERS_ENV.to_owned(), workers.to_string()); + } +} + +impl ResourcePlan { + /// The table `leleka up` prints: what the engine takes and what stays free. + pub fn render(&self, facts: &Facts) -> String { + let mut out = format!("resources ({} preset)\n", self.preset.as_str()); + if let Some(workers) = self.cpu_workers { + out.push_str(&format!( + " cpu {workers} expert workers of {} cores; ~{} cores stay free\n", + self.cores, + self.cores.saturating_sub(workers + 1) + )); + } + out.push_str(&format!( + " vram budget {}{}\n", + gib_text(self.gpu_budget_bytes), + self.vram_free_after_mib + .map_or(String::new(), |free| format!(", ~{} MiB stay free", free)) + )); + match (self.ram_floors_mib, self.ram_expected_free_after_bytes) { + (Some((soft, hard)), after) => out.push_str(&format!( + " host ram caches shed below {} MiB available, requests refused below {} MiB{}\n", + soft, + hard, + after.map_or(String::new(), |b| format!("; ~{} free after the start", gib_text(b))) + )), + (None, Some(after)) => out.push_str(&format!( + " host ram engine defaults; ~{} of {} free after the start\n", + gib_text(after), + gib_text(facts.memory.total) + )), + (None, None) => {} + } + for warning in &self.warnings { + out.push_str(&format!(" warning {warning}\n")); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::facts::Memory; + + fn gpu(total: u64, free: u64) -> Gpu { + Gpu { index: 0, name: "gpu".into(), driver: "595.1".into(), vram_total_mib: total, vram_free_mib: free, sm: Some(120) } + } + + fn host(cores: u32, ram_gib: u64, avail_gib: u64) -> Facts { + Facts { + cpu_cores: cores, + memory: Memory { total: ram_gib * GIB, available: avail_gib * GIB, swap_total: 0 }, + ..Facts::default() + } + } + + fn server() -> Profile { + Profile::builtin("rtx5090-32g").unwrap() + } + fn laptop() -> Profile { + Profile::builtin("rtx3080-16g").unwrap() + } + + #[test] + fn dedicated_takes_the_profile_and_caps_workers_at_the_useful_maximum() { + let plan = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Dedicated); + assert_eq!(plan.cpu_workers, Some(8)); + assert_eq!(plan.gpu_budget_bytes, server().gpu_budget_bytes); + assert_eq!(plan.ram_floors_mib, None); + assert!(plan.problems.is_empty()); + } + + #[test] + fn workstation_leaves_cores_ram_and_vram_on_the_server() { + let plan = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Workstation); + assert_eq!(plan.cpu_workers, Some(8), "32 cores - 8 left free = 24, capped at 8"); + assert_eq!(plan.gpu_budget_bytes, 27 * GIB, "32100 MiB free - 4096 MiB, rounded down to GiB"); + assert_eq!(plan.ram_floors_mib, Some((16384, 8192))); + assert!(plan.problems.is_empty(), "{:?}", plan.problems); + let mut profile = server(); + let mut env = BTreeMap::new(); + apply(&plan, &mut profile, &mut env, false); + assert_eq!(profile.gpu_budget_bytes, 27 * GIB); + assert_eq!(profile.memory.soft_floor_mib, Some(16384)); + assert_eq!(profile.memory.hard_floor_mib, Some(8192)); + assert_eq!(env.get(CPU_WORKERS_ENV).map(String::as_str), Some("8")); + } + + #[test] + fn workstation_on_a_16_thread_laptop_leaves_four_cores_and_scales_the_ram_target() { + let plan = compute(&host(16, 24, 21), Some(&gpu(16384, 15500)), &laptop(), Preset::Workstation); + assert_eq!(plan.cpu_workers, Some(8)); + assert_eq!(plan.ram_floors_mib, Some((8192, 4096))); + assert_eq!(plan.gpu_budget_bytes, 11 * GIB); + assert!(plan.problems.is_empty(), "{:?}", plan.problems); + let small = compute(&host(8, 24, 21), Some(&gpu(16384, 15500)), &laptop(), Preset::Workstation); + assert_eq!(small.cpu_workers, Some(4)); + } + + #[test] + fn an_unachievable_workstation_vram_target_is_a_problem_not_a_silent_shrink() { + let plan = compute(&host(16, 24, 21), Some(&gpu(16384, 9000)), &laptop(), Preset::Workstation); + assert!(!plan.problems.is_empty()); + let dedicated = compute(&host(16, 24, 21), Some(&gpu(16384, 9000)), &laptop(), Preset::Dedicated); + assert!(dedicated.problems.is_empty()); + } + + #[test] + fn explicit_values_win_and_floors_are_only_raised() { + let plan = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Workstation); + let mut profile = server(); + profile.memory.soft_floor_mib = Some(30000); + profile.engine_env.insert(CPU_WORKERS_ENV.into(), "3".into()); + let mut env = BTreeMap::new(); + apply(&plan, &mut profile, &mut env, true); + assert_eq!(profile.gpu_budget_bytes, server().gpu_budget_bytes, "--gpu-budget-gib wins"); + assert_eq!(profile.memory.soft_floor_mib, Some(30000)); + assert_eq!(profile.memory.hard_floor_mib, Some(8192), "floors are only ever raised"); + assert!(env.is_empty()); + } + + #[test] + fn unknown_core_count_leaves_the_engine_default() { + let plan = compute(&host(0, 121, 100), None, &server(), Preset::Workstation); + assert_eq!(plan.cpu_workers, None); + } + + #[test] + fn not_enough_ram_for_the_pinned_form_switches_to_mapped_files_instead_of_failing() { + // 121 GiB host with 70 GiB available: 58 GiB of pinned archive leaves 12 GiB, below the 16 GiB workstation target + let plan = compute(&host(32, 121, 70), Some(&gpu(32607, 32100)), &server(), Preset::Workstation); + assert_eq!(plan.mapped_resident_gib, Some(46), "70 - 16 target - 8 overhead"); + assert_eq!(plan.warnings.len(), 1, "{:?}", plan.warnings); + assert!(plan.render(&host(32, 121, 70)).contains("served from disk")); + let mut profile = server(); + let mut env = BTreeMap::new(); + apply(&plan, &mut profile, &mut env, false); + assert_eq!(profile.kar_source, KarSource::File); + assert_eq!(profile.expert_source, ExpertSource::Mapped); + assert_eq!(profile.memory.resident_budget_gib, Some(46)); + assert_eq!(profile.memory.lock.as_deref(), Some("off")); + assert!(profile.min_ram_available_bytes <= 10 * GIB && profile.min_ram_total_bytes <= 16 * GIB); + profile.validate().unwrap(); + } + + #[test] + fn a_small_host_gets_zero_resident_experts_and_dedicated_switches_too() { + let plan = compute(&host(16, 24, 12), Some(&gpu(16384, 15500)), &server(), Preset::Dedicated); + assert_eq!(plan.mapped_resident_gib, Some(0), "12 GiB available is below the 4 GiB target plus 8 GiB overhead"); + let ample = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Workstation); + assert_eq!(ample.mapped_resident_gib, None); + assert!(ample.warnings.is_empty(), "{:?}", ample.warnings); + } + + #[test] + fn presets_parse_and_default_to_dedicated() { + assert_eq!(Preset::default(), Preset::Dedicated); + assert_eq!(Preset::parse("workstation").unwrap(), Preset::Workstation); + assert!(Preset::parse("x").is_err()); + } +} diff --git a/crates/leleka-memory/src/lib.rs b/crates/leleka-memory/src/lib.rs index fe4adbd0..47e929d7 100644 --- a/crates/leleka-memory/src/lib.rs +++ b/crates/leleka-memory/src/lib.rs @@ -1,24 +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 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; +//! 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;