leleka-memory::telemetry (sampler + per-request records) -> Backend::telemetry_report -> Snapshot.telemetry_json (gRPC) -> control plane /v1/status machine -> leleka status. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
3421 lines
131 KiB
Rust
3421 lines
131 KiB
Rust
//! 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<bool> = 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<Error>,
|
||
secondary: Box<Error>,
|
||
},
|
||
}
|
||
|
||
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<T> = std::result::Result<T, Error>;
|
||
|
||
/// 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<T>(primary: Result<T>, secondary: Result<()>) -> Result<T> {
|
||
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<ffi::Api>,
|
||
version: i32,
|
||
}
|
||
impl Driver {
|
||
/// Resolve the entire fixed ABI before initializing CUDA.
|
||
pub fn load() -> Result<Self> {
|
||
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<Device<'_>> {
|
||
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<Context<'driver>> {
|
||
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<bool>` that prints the stack of the first `set(true)` when LELEKA_TRACE_POISON is set.
|
||
pub(crate) struct PoisonCell(Cell<bool>);
|
||
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<ffi::ContextHandle>,
|
||
/// 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<usize>,
|
||
poisoned: PoisonCell,
|
||
vector_add_kernel: Cell<Option<FixedKernel>>,
|
||
matvec_kernel: Cell<Option<FixedKernel>>,
|
||
q5_k_kernel: Cell<Option<FixedPairKernels>>,
|
||
q6_k_kernel: Cell<Option<FixedPairKernels>>,
|
||
common_quantizer: Cell<Option<FixedKernel>>,
|
||
grouped_iq3: Cell<Option<FixedKernel>>,
|
||
grouped_iq2: Cell<Option<FixedKernel>>,
|
||
grouped_iq3_s: Cell<Option<FixedKernel>>,
|
||
grouped_iq4_xs: Cell<Option<FixedKernel>>,
|
||
grouped_iq3_s_nc4: Cell<Option<FixedKernel>>,
|
||
grouped_iq4_xs_nc4: Cell<Option<FixedKernel>>,
|
||
grouped_swiglu: Cell<Option<FixedKernel>>,
|
||
grouped_down_iq4: Cell<Option<FixedKernel>>,
|
||
grouped_down_q2: Cell<Option<FixedKernel>>,
|
||
gr_read_guard_kernel: Cell<Option<FixedKernel>>,
|
||
projection_kernels: [Cell<Option<ProjectionKernels>>; 8],
|
||
qwen_kernels: qwen_dispatch::Cache,
|
||
kar_levels: Cell<Option<kar_decode_levels::KarLevelsKernels>>,
|
||
experimental: [Cell<Option<experimental::LoadedProgram>>; 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, Rc<original_verify::abi::Module>, 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<Vec<(ffi::BufferHandle, usize)>>,
|
||
}
|
||
#[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<DeviceBuffer<'context>>,
|
||
}
|
||
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<ffi::FunctionHandle>,
|
||
routed: Option<ffi::FunctionHandle>,
|
||
}
|
||
impl ProjectionKind {
|
||
fn layout(self) -> (usize, usize, usize, Option<usize>) {
|
||
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<Self>, Option<Self>) {
|
||
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<ProjectionShape> {
|
||
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<usize>| -> Result<usize> {
|
||
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<Q5KShape> {
|
||
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<usize> {
|
||
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<Q6KShape> {
|
||
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<usize> {
|
||
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<MatvecShape> {
|
||
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<usize>| -> Result<usize> {
|
||
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<ffi::BufferHandle>,
|
||
vector: Option<ffi::BufferHandle>,
|
||
output: Option<ffi::BufferHandle>,
|
||
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<CurrentGuard<'_, '_>> {
|
||
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<DeviceBuffer<'_>> {
|
||
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::<usize>()
|
||
};
|
||
static LIMIT: std::sync::OnceLock<usize> = 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::<usize>().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<T>(
|
||
&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<RoutedGateUpQ8<'context>> {
|
||
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<T>(
|
||
&self,
|
||
operation: Result<T>,
|
||
scratch: DeviceBuffer<'_>,
|
||
status: DeviceBuffer<'_>,
|
||
) -> Result<T> {
|
||
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<Option<FixedKernel>> {
|
||
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<FixedKernel> {
|
||
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<Option<FixedPairKernels>>,
|
||
module_op: FixedOperation,
|
||
quantize_op: FixedOperation,
|
||
project_op: FixedOperation,
|
||
) -> Result<FixedPairKernels> {
|
||
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<FixedPairKernels> {
|
||
self.fixed_pair(
|
||
&self.q5_k_kernel,
|
||
FixedOperation::Q5K,
|
||
FixedOperation::Q5KQuantize,
|
||
FixedOperation::Q5KProject,
|
||
)
|
||
}
|
||
fn q6_kernels(&self) -> Result<FixedPairKernels> {
|
||
self.fixed_pair(
|
||
&self.q6_k_kernel,
|
||
FixedOperation::Q6K,
|
||
FixedOperation::Q6KQuantize,
|
||
FixedOperation::Q6KProject,
|
||
)
|
||
}
|
||
fn unload_pair(&self, cache: &Cell<Option<FixedPairKernels>>) -> 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<ffi::BufferHandle>,
|
||
bytes: usize,
|
||
_thread: PhantomData<Rc<()>>,
|
||
}
|
||
impl DeviceBuffer<'_> {
|
||
pub fn len(&self) -> usize {
|
||
self.bytes
|
||
}
|
||
pub fn is_empty(&self) -> bool {
|
||
false
|
||
}
|
||
fn staging(&self, actual: usize) -> Result<Vec<u8>> {
|
||
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<u8>) -> 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<DeviceBuffer>`).
|
||
/// 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<Vec<u8>> {
|
||
let staging = self.staging(expected_bytes)?;
|
||
self.copy_staged(staging, true)
|
||
}
|
||
fn copy_staged(&self, mut staging: Vec<u8>, to_host: bool) -> Result<Vec<u8>> {
|
||
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::<u32>()
|
||
.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;
|