STRA-338 S17: inline modules of the cuda-driver root and FFI files move to files, lib.rs and ffi/enabled.rs split by responsibility

lib.rs 3508 -> 938 lines, ffi.rs 1897 -> small, qwen_dispatch.rs 2003 and qwen_ffi.rs 1696 lose their inline test and installed-proof modules (scripts/dev/extract_modules.py, 5 self-tests; split_module.py --allow-root for lib.rs). Module paths, visibility and test ids are unchanged: 544 test ids before and after, cuda-driver tests 433 passed / 78 ignored before and after (Linux), host check clean. GPU identity and A/B follow with the combined batch 1+2 gate.
This commit is contained in:
Pavlo Ratushnyi
2026-11-05 22:28:30 +01:00
parent eecbfce60d
commit ecc774a530
34 changed files with 7342 additions and 7023 deletions
+4 -4
View File
@@ -24,10 +24,9 @@
"crates/cuda-driver/src/api.rs": 423,
"crates/cuda-driver/src/closed_kernels/tests.rs": 405,
"crates/cuda-driver/src/experimental.rs": 407,
"crates/cuda-driver/src/ffi.rs": 1897,
"crates/cuda-driver/src/gdn_native_batch.rs": 557,
"crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs": 618,
"crates/cuda-driver/src/lib.rs": 3508,
"crates/cuda-driver/src/lib.rs": 938,
"crates/cuda-driver/src/mmq_resident_gpu.rs": 517,
"crates/cuda-driver/src/moe_prefill_batch.rs": 476,
"crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs": 621,
@@ -44,8 +43,9 @@
"crates/cuda-driver/src/original_verify_window_qsa/tests.rs": 652,
"crates/cuda-driver/src/ple_batch_ffi.rs": 625,
"crates/cuda-driver/src/prefill_stage_gdn_gpu.rs": 420,
"crates/cuda-driver/src/qwen_dispatch.rs": 2003,
"crates/cuda-driver/src/qwen_ffi.rs": 1696,
"crates/cuda-driver/src/qwen_dispatch/tests.rs": 1455,
"crates/cuda-driver/src/qwen_ffi.rs": 876,
"crates/cuda-driver/src/qwen_ffi/tests.rs": 821,
"crates/cuda-driver/src/sm86_table.rs": 933,
"crates/cuda-driver/tests/mock_driver.rs": 1560,
"crates/cuda-driver/tests/original_serve_preflight_probe.rs": 784,
@@ -0,0 +1,235 @@
//! Moved out of the parent module by STRA-338: fn bringup_trace_enabled, impl PromptSyncTrace, impl Drop_for_PromptSyncTrace, impl Error, impl fmt_Display_for, impl std_error_Error ....
#[allow(unused_imports)]
use super::*;
/// 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())
}
impl PromptSyncTrace {
pub fn enter() -> Self {
#[cfg(windows)]
libc::cuda_trace_set_sync(true);
Self(())
}
}
impl Drop for PromptSyncTrace {
fn drop(&mut self) {
#[cfg(windows)]
libc::cuda_trace_set_sync(false);
}
}
impl Error {
pub(super) 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,
})
}
pub(super) fn validation_message(&self) -> Option<&'static str> {
Some(match self {
Self::ContextMismatch => "buffers must belong to this exact context",
Self::InvalidVectorShape => {
"vector shape must be nonempty f32 bytes with a bounded u32 count/grid"
}
Self::InvalidMatvecShape => {
"matvec requires exact nonempty bounded row-major f32 shapes"
}
Self::InvalidQ5KProjectionShape => {
"Q5_K projection requires exact bounded row-major single-column shapes"
}
Self::InvalidQ6KProjectionShape => {
"Q6_K projection requires exact bounded row-major single-column shapes"
}
Self::UnsupportedProjection => "projection format is not integrated",
Self::UnsupportedQwenOperation => "Qwen operation has no qualified fixed asset",
Self::InvalidQwenShape => {
"Qwen operation requires its exact pinned topology and byte layout"
}
Self::InvalidBf16ProjectionShape => {
"BF16 projection requires exact bounded rows and positive even columns"
}
Self::InvalidProjectionShape => {
"projection requires exact bounded packed single-column shapes"
}
Self::InvalidQ8Activation => "activation cannot be represented by native Q8_1",
Self::NonFiniteMmqOutput(_) => "MMQ produced a nonfinite stage output",
Self::OutputAliasesInput => "output must not alias an input",
Self::InvalidSize => "byte size must be nonzero and fit isize",
Self::BudgetExceeded => "allocation exceeds context byte budget",
_ => return None,
})
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(message) = self
.environment_message()
.or_else(|| self.validation_message())
{
return f.write_str(message);
}
match self {
Self::MissingSymbol(symbol) => write!(f, "missing CUDA Driver symbol {symbol}"),
Self::InvalidDriverValue(operation) => {
write!(f, "{operation} returned an invalid handle on success")
}
Self::Driver { operation, code } => {
write!(f, "{operation} failed with CUDA code {code}")
}
Self::ShapeMismatch { expected, actual } => {
write!(f, "byte shape mismatch: expected {expected}, got {actual}")
}
Self::GraphOutOfMemory { window: 0 } => {
write!(f, "the verifier commit graph did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)")
}
Self::GraphOutOfMemory { window } => {
write!(f, "the verifier window graph T={window} did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)")
}
Self::Multiple { primary, secondary } => {
write!(f, "{primary}; subsequent error: {secondary}")
}
_ => unreachable!("static errors have a message"),
}
}
}
impl std::error::Error for Error {}
pub(super) 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),
}),
}
}
pub(super) fn valid_size(bytes: usize) -> Result<()> {
if bytes == 0 || bytes > isize::MAX as usize {
Err(Error::InvalidSize)
} else {
Ok(())
}
}
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,
})
}
}
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()),
})
}
}
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);
}
}
impl RoutedGateUpQ8<'_> {
/// Consume the owner and report its one scratch release attempt.
pub fn close(mut self) -> Result<()> {
self.release()
}
pub(super) 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();
}
}
+341
View File
@@ -0,0 +1,341 @@
//! Moved out of the parent file by STRA-338 (same module path as before).
use super::*;
const KINDS: [ProjectionKind; 10] = [
ProjectionKind::Dense(DenseFormat::Q8_0),
ProjectionKind::Dense(DenseFormat::Q4_K),
ProjectionKind::Routed(RoutedFormat::IQ3_XXS),
ProjectionKind::Routed(RoutedFormat::IQ3_S),
ProjectionKind::Routed(RoutedFormat::IQ2_S),
ProjectionKind::Dense(DenseFormat::IQ4_NL),
ProjectionKind::Routed(RoutedFormat::IQ4_NL),
ProjectionKind::Dense(DenseFormat::IQ4_XS),
ProjectionKind::Routed(RoutedFormat::IQ4_XS),
ProjectionKind::Routed(RoutedFormat::Q2_0),
];
#[test]
fn common_checked_geometry_matches_frozen_native_layouts() {
for (kind, index) in KINDS.into_iter().zip([0, 1, 2, 3, 4, 5, 5, 6, 6, 7]) {
let shape = projection_shape(ProjectionSpec {
kind,
rows: 5,
columns: 256,
})
.unwrap();
assert_eq!(
shape.weight_bytes,
5 * (256 / family_expectations::LAYOUTS[index].0)
* family_expectations::LAYOUTS[index].1
);
assert_eq!(
(
shape.activation_bytes,
shape.output_bytes,
shape.scratch_bytes,
shape.temporary_bytes
),
(1024, 20, 288, 292)
);
}
for (n, bytes, grid) in family_expectations::TAILS {
let shape = projection_shape(ProjectionSpec {
kind: KINDS[0],
rows: 5,
columns: n,
})
.unwrap();
assert_eq!(
(shape.scratch_bytes, shape.quant_grid, shape.projection_grid),
(bytes, grid as u32, 2)
);
}
for (kind, limit) in [
(KINDS[0], 1024),
(KINDS[1], 2048),
(KINDS[5], 2048),
(KINDS[7], 4096),
] {
for (n, grid) in [(limit - 256, 2), (limit, 5), (limit + 256, 5)] {
assert_eq!(
projection_shape(ProjectionSpec {
kind,
rows: 5,
columns: n
})
.unwrap()
.projection_grid,
grid
);
}
}
for kind in [KINDS[2], KINDS[3], KINDS[4], KINDS[6], KINDS[8], KINDS[9]] {
assert_eq!(
projection_shape(ProjectionSpec {
kind,
rows: 5,
columns: 6144
})
.unwrap()
.projection_grid,
2
);
}
}
#[test]
fn common_invalid_shapes_have_fixed_errors() {
for kind in KINDS {
for (m, n) in [
(0, 256),
(1, 0),
(1, 31),
(1, 33),
(usize::MAX, 256),
(1, usize::MAX),
(i32::MAX as usize + 1, 256),
] {
assert_eq!(
projection_shape(ProjectionSpec {
kind,
rows: m,
columns: n
}),
Err(Error::InvalidProjectionShape)
);
}
}
assert_eq!(
projection_shape(ProjectionSpec {
kind: KINDS[1],
rows: 1,
columns: 32
}),
Err(Error::InvalidProjectionShape)
);
}
#[test]
fn q4_k_admission_bounds_every_padded_cta_byte_offset() {
// At N=256 the kernel launches four output rows per CTA and computes
// all four row-arm offsets before guarding the final partial CTA.
// The largest admitted padded row count therefore stays on a four
// row boundary and its post-loop signed offset fits i32.
const BLOCK_BYTES: usize = 144;
const ROWS_PER_CTA: usize = 4;
let max_block_index = i32::MAX as usize / BLOCK_BYTES;
// Include the common final +8-block PTX increment after the last
// iteration, then round the small-N four-row CTA down to its boundary.
let max_padded_rows =
((max_block_index.saturating_sub(7) / ROWS_PER_CTA) * ROWS_PER_CTA).max(ROWS_PER_CTA);
let at_limit_offset = (max_padded_rows + 7) * BLOCK_BYTES;
assert!(at_limit_offset <= i32::MAX as usize);
assert!(q4_k_native_indices_fit(max_padded_rows - ROWS_PER_CTA, 256));
assert!(q4_k_native_indices_fit(max_padded_rows, 256));
assert!(!q4_k_native_indices_fit(max_padded_rows + 1, 256));
assert!(
projection_shape(ProjectionSpec {
kind: ProjectionKind::Dense(DenseFormat::Q4_K),
rows: max_padded_rows,
columns: 256,
})
.is_ok()
);
// The large-N launch uses one CTA per row but still materializes
// row+1 through row+3 and the final offsets of all eight lane groups.
let blocks_per_row = 2048 / 256;
let max_large_n_rows = ((max_block_index - (blocks_per_row + 7)) / blocks_per_row) - 2;
assert!(q4_k_native_indices_fit(max_large_n_rows - 1, 2048));
assert!(q4_k_native_indices_fit(max_large_n_rows, 2048));
assert!(!q4_k_native_indices_fit(max_large_n_rows + 1, 2048));
assert!(
projection_shape(ProjectionSpec {
kind: ProjectionKind::Dense(DenseFormat::Q4_K),
rows: max_large_n_rows,
columns: 2048,
})
.is_ok()
);
assert_eq!(
projection_shape(ProjectionSpec {
kind: ProjectionKind::Dense(DenseFormat::Q4_K),
rows: max_large_n_rows + 1,
columns: 2048,
}),
Err(Error::InvalidProjectionShape)
);
// N=2304 has nine blocks: lane group 0 visits 0 and 8 then reaches
// 16, the maximum final index across groups 0..7.
let blocks_per_row: usize = 2304 / 256;
let final_loop_index = blocks_per_row + 7;
assert_eq!(final_loop_index, 16);
let max_nonwrapping_rows = ((max_block_index - final_loop_index) / blocks_per_row) - 2;
assert!(q4_k_native_indices_fit(max_nonwrapping_rows, 2304));
assert!(!q4_k_native_indices_fit(max_nonwrapping_rows + 1, 2304));
// For sixteen blocks, lane group 7 visits block 15 and increments to
// 23; checking only the block-zero loop would miss this signed offset.
let blocks_per_row: usize = 4096 / 256;
let final_loop_index = blocks_per_row + 7;
assert_eq!(final_loop_index, 23);
let max_nonwrapping_rows = ((max_block_index - final_loop_index) / blocks_per_row) - 2;
assert!(q4_k_native_indices_fit(max_nonwrapping_rows, 4096));
assert!(!q4_k_native_indices_fit(max_nonwrapping_rows + 1, 4096));
// The independent QA counterexample and its adjacent valid-row
// boundary are rejected before any context, cache, or allocation work.
for rows in [14_913_081, 14_913_082] {
assert!(!q4_k_native_indices_fit(rows, 256));
assert_eq!(
projection_shape(ProjectionSpec {
kind: ProjectionKind::Dense(DenseFormat::Q4_K),
rows,
columns: 256,
}),
Err(Error::InvalidProjectionShape)
);
}
// With one row, a large N may have a large total extent while every
// native signed packed-byte base remains representable. This case is
// structural only and deliberately allocates no host or device data.
let large_n = 256 * 3_000_000;
assert!(q4_k_native_indices_fit(1, large_n));
assert!(
projection_shape(ProjectionSpec {
kind: ProjectionKind::Dense(DenseFormat::Q4_K),
rows: 1,
columns: large_n,
})
.is_ok()
);
// Positive individually-valid M and N still refuse when their Q4_K
// row/block product would overflow the native signed byte offset.
let max_i32_n = (i32::MAX as usize / 256) * 256;
assert!(!q4_k_native_indices_fit(2, max_i32_n));
assert_eq!(
projection_shape(ProjectionSpec {
kind: ProjectionKind::Dense(DenseFormat::Q4_K),
rows: 2,
columns: max_i32_n,
}),
Err(Error::InvalidProjectionShape)
);
}
#[cfg(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
))]
#[test]
#[ignore = "private quantizer transport only; isolated CPU mock, not GPU math"]
fn family_quantizer_transport_child() {
assert_eq!(
std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(),
Ok("1")
);
let n: usize = std::env::var("LELEKA_FAMILY_N").unwrap().parse().unwrap();
let driver = Driver::load().unwrap();
let context = driver.device(0).unwrap().create_context(8192).unwrap();
let trace_path = std::env::var("MOCK_CUDA_TRACE").unwrap();
let before = std::fs::read(&trace_path).unwrap();
for (kind, alignment) in KINDS.into_iter().zip([2, 4, 2, 2, 2, 2, 2, 4, 4, 2]) {
let shape = projection_shape(ProjectionSpec {
kind,
rows: 1,
columns: 256,
})
.unwrap();
let addresses = [
ffi::BufferHandle::synthetic(2),
ffi::BufferHandle::synthetic(4096),
ffi::BufferHandle::synthetic(8192),
];
assert_eq!(
projection_ranges(kind, &shape, addresses),
if alignment == 4 {
Err(Error::InvalidProjectionShape)
} else {
Ok(())
}
);
assert_eq!(std::fs::read(&trace_path).unwrap(), before);
assert_eq!(context.allocated_bytes(), 0);
assert!(context.common_quantizer.get().is_none());
assert!(
context
.projection_kernels
.iter()
.all(|slot| slot.get().is_none())
);
}
let mut input = context.allocate(4 * n).unwrap();
input.copy_from(&vec![0; 4 * n]).unwrap();
let scratch = context.allocate(n / 32 * 36).unwrap();
let mut status = context.allocate(4).unwrap();
let operation = (|| {
status.copy_from(&[0; 4])?;
let guard = context.enter()?;
let kernel = match context.fixed_kernel(FixedOperation::CommonQuantize) {
Ok(k) => k,
Err(e) => return combine(Err(e), guard.finish()),
};
combine(Ok(()), guard.finish())?;
let mut args = ffi::Q8QuantizeArguments::new(
input.handle.unwrap(),
scratch.handle.unwrap(),
status.handle.unwrap(),
n as u32,
);
let guard = context.enter()?;
let launch = context.driver.api.launch_q8_quantize(
kernel.function,
n.div_ceil(256) as u32,
&mut args,
);
context.complete_launch(launch, args, guard)?;
let mut bytes = [0; 4];
status.copy_to(&mut bytes)?;
let expected = std::env::var("MOCK_FAMILY_STATUS")
.unwrap_or_else(|_| "0".into())
.parse::<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();
}
}
File diff suppressed because it is too large Load Diff
+111
View File
@@ -0,0 +1,111 @@
//! Moved out of the parent file by STRA-338 (same module path as before).
use super::*;
use libc::{c_int, c_uint, c_void};
type CuResult = c_int;
type CuDevice = c_int;
type CuContext = *mut c_void;
type CuDevicePtr = u64;
type Init = unsafe extern "C" fn(c_uint) -> CuResult;
type DriverGetVersion = unsafe extern "C" fn(*mut c_int) -> CuResult;
type DeviceGet = unsafe extern "C" fn(*mut CuDevice, c_int) -> CuResult;
type ContextCreateV2 = unsafe extern "C" fn(*mut CuContext, c_uint, CuDevice) -> CuResult;
type ContextDestroyV2 = unsafe extern "C" fn(CuContext) -> CuResult;
type ContextPushCurrentV2 = unsafe extern "C" fn(CuContext) -> CuResult;
type ContextPopCurrentV2 = unsafe extern "C" fn(*mut CuContext) -> CuResult;
type ContextSynchronize = unsafe extern "C" fn() -> CuResult;
type StreamSynchronizeRaw = unsafe extern "C" fn(*mut c_void) -> CuResult;
type MemAllocV2 = unsafe extern "C" fn(*mut CuDevicePtr, usize) -> CuResult;
type MemFreeV2 = unsafe extern "C" fn(CuDevicePtr) -> CuResult;
type MemGetInfoV2 = unsafe extern "C" fn(*mut usize, *mut usize) -> CuResult;
type MemcpyHtoDV2 = unsafe extern "C" fn(CuDevicePtr, *const c_void, usize) -> CuResult;
type ModuleLoadData = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> CuResult;
type ModuleGetFunction =
unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> CuResult;
type ModuleUnload = unsafe extern "C" fn(*mut c_void) -> CuResult;
type LaunchKernel = unsafe extern "C" fn(
*mut c_void,
c_uint,
c_uint,
c_uint,
c_uint,
c_uint,
c_uint,
c_uint,
*mut c_void,
*mut *mut c_void,
*mut *mut c_void,
) -> CuResult;
static FIXED_PTX: &[u8] = concat!(include_str!("../vector_add.ptx"), "\0").as_bytes();
static MATVEC_PTX: &[u8] = concat!(include_str!("../matvec.ptx"), "\0").as_bytes();
static Q5_K_PTX: &[u8] = concat!(include_str!("../q5_k_q8_1.ptx"), "\0").as_bytes();
static COMMON_QUANTIZER_PTX: &[u8] =
concat!(include_str!("../q8_1_quantize.ptx"), "\0").as_bytes();
static Q6_K_PTX: &[u8] = concat!(include_str!("../q6_k_q8_1.ptx"), "\0").as_bytes();
type MemcpyDtoHV2 = unsafe extern "C" fn(*mut c_void, CuDevicePtr, usize) -> CuResult;
type MemcpyDtoDV2 = unsafe extern "C" fn(CuDevicePtr, CuDevicePtr, usize) -> CuResult;
type MemsetD8V2 = unsafe extern "C" fn(CuDevicePtr, u8, usize) -> CuResult;
struct Library(*mut c_void);
pub(crate) struct Api {
_library: Library,
init: Init,
version: DriverGetVersion,
device: DeviceGet,
create: ContextCreateV2,
destroy: ContextDestroyV2,
push: ContextPushCurrentV2,
pop: ContextPopCurrentV2,
synchronize: ContextSynchronize,
stream_synchronize: StreamSynchronizeRaw,
allocate: MemAllocV2,
free: MemFreeV2,
copy_from: MemcpyHtoDV2,
copy_to: MemcpyDtoHV2,
copy_moe_down: MemcpyDtoDV2,
zero: MemsetD8V2,
load_module: ModuleLoadData,
get_function: ModuleGetFunction,
unload_module: ModuleUnload,
launch_kernel: LaunchKernel,
}
// Module/function/launch entries of the Strata-prefill GDN and native dequant modules.
#[cfg(target_arch = "x86_64")]
include!("../gdn_native_batch_ffi.rs");
// Module/function entries of the Strata-prefill MoE router / shared-expert module.
#[cfg(target_arch = "x86_64")]
include!("../moe_prefill_batch_ffi.rs");
// Module/function entries of the Original-Strata single-token fused GDN module.
#[cfg(target_arch = "x86_64")]
include!("../gdn_fused_t1_ffi.rs");
// Fixed names/signatures remain explicitly paired. This macro is not a
// caller-selected resolver; a missing symbol exits before initialization.
macro_rules! symbol {
($library:ident, $name:literal, $ty:ty) => {{
// SAFETY: valid owned library handle and static C name.
let address = unsafe { libc::dlsym($library.0, $name.as_ptr()) };
if address.is_null() {
return Err(Error::MissingSymbol(
$name.to_str().expect("static ASCII symbol"),
));
}
// SAFETY: the fixed ABI name is paired with its exact
// documented signature. Linux64 supports dlsym function
// addresses; no generic or caller-selected reinterpretation.
unsafe { std::mem::transmute::<*mut c_void, $ty>(address) }
}};
}
// Closed KAR level-decode ABI; kept in its own file, same module scope.
include!("../kar_decode_levels_ffi.rs");
mod impl_drop_for_library;
#[allow(unused_imports)]
use impl_drop_for_library::check;
mod impl_api;
mod impl_api_2;
mod impl_api_3;
mod impl_api_4;
mod impl_api_5;
mod impl_api_6;
@@ -0,0 +1,248 @@
//! Moved out of the parent module by STRA-338: impl Api.
#[allow(unused_imports)]
use super::*;
impl Api {
pub(crate) fn memory_info(&self) -> Result<(usize, usize)> {
// Lazy fixed resolution leaves unrelated existing/mock APIs intact.
// A missing query symbol fails explicitly; it never fabricates free VRAM.
let library = &self._library;
let query = symbol!(library, c"cuMemGetInfo_v2", MemGetInfoV2);
let mut free = 0usize;
let mut total = 0usize;
// SAFETY: exact Linux64 size_t* ABI, distinct non-null writable
// outputs live through this synchronous query, owner Context current.
check("cuMemGetInfo_v2", unsafe { query(&mut free, &mut total) })?;
if total == 0 || free > total {
return Err(Error::InvalidDriverValue("cuMemGetInfo_v2"));
}
Ok((free, total))
}
pub(crate) fn mmq_capabilities(&self) -> Result<u32> {
let library = &self._library;
let get = symbol!(
library,
c"cuCtxGetDevice",
unsafe extern "C" fn(*mut c_int) -> CuResult
);
let attr = symbol!(
library,
c"cuDeviceGetAttribute",
unsafe extern "C" fn(*mut c_int, c_int, CuDevice) -> CuResult
);
let mut device = 0;
// SAFETY: fixed optional Driver ABI, owner context current, valid output.
check("cuCtxGetDevice", unsafe { get(&mut device) })?;
let mut values = [0; 4];
for (slot, key) in values.iter_mut().zip([75, 76, 97, 16]) {
// SAFETY: fixed capability selectors and live device returned above.
check("cuDeviceGetAttribute", unsafe { attr(slot, key, device) })?;
}
if !crate::arch_ptx::mmq_cc_ok(values[0], values[1])
|| values[2] < 52480
|| !(1..=4096).contains(&values[3])
{
return Err(Error::InvalidDriverValue("MMQ SM120 capabilities"));
}
Ok(crate::arch_ptx::forced_sms(values[3] as u32))
}
pub(crate) fn load_mmq(&self, kind: u32) -> Result<ModuleHandle> {
let ptx = crate::mmq::asset(kind)?;
let mut module = std::ptr::null_mut();
// SAFETY: pinned immutable NUL-terminated artifact, live owning current context.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut module, crate::arch_ptx::image(ptx).as_ptr().cast())
})?;
ModuleHandle::qwen_success(module as usize)
}
pub(crate) fn mmq_function(
&self,
module: ModuleHandle,
format: Option<(crate::mmq::MmqFormat, crate::mmq::Tile)>,
fixup: bool,
) -> Result<FunctionHandle> {
let entry = match format {
Some((f, j)) if fixup => f.fixup_entry(j),
Some((f, j)) => f.entry(j),
None => crate::mmq::QUANT_ENTRY,
};
let mut function = std::ptr::null_mut();
// SAFETY: fixed entry map, actual owned module and valid writable output.
check("cuModuleGetFunction", unsafe {
(self.get_function)(&mut function, module.0 as *mut c_void, entry.as_ptr())
})?;
FunctionHandle::qwen_success(function as usize)
}
pub(crate) fn mmq_shared(&self, function: FunctionHandle, bytes: u32) -> Result<()> {
if !matches!(
bytes,
40992
| 42048
| 43104
| 44160
| 45216
| 46272
| 48384
| 45088
| 46144
| 47200
| 48256
| 49312
| 50368
| 52480
| 51520
| 53632
| 55616
| 55744
| 57728
| 57856
| 59840
| 61952
) {
return Err(Error::InvalidProjectionShape);
}
let library = &self._library;
let set = symbol!(
library,
c"cuFuncSetAttribute",
unsafe extern "C" fn(*mut c_void, c_int, c_int) -> CuResult
);
// SAFETY: fixed attribute8, admitted shared bytes and live owned function.
check("cuFuncSetAttribute", unsafe {
set(function.0 as *mut c_void, 8, bytes as c_int)
})
}
pub(crate) fn load_iq3_native_integer(&self) -> Result<ModuleHandle> {
let ptx = crate::mmq::resident::native_integer::asset()?;
let mut m = std::ptr::null_mut();
// SAFETY: ROOT-sealed fixed NUL PTX, actual owning current Context.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast())
})?;
ModuleHandle::qwen_success(m as usize)
}
pub(crate) fn iq3_native_integer_function(
&self,
m: ModuleHandle,
reduce: bool,
) -> Result<FunctionHandle> {
let name = if reduce {
c"leleka_iq3_native_order_reduce"
} else {
c"leleka_iq3_native_integer_dot"
};
let mut f = std::ptr::null_mut();
// SAFETY: closed fixed two-entry map in actual owned module.
check("cuModuleGetFunction", unsafe {
(self.get_function)(&mut f, m.0 as *mut c_void, name.as_ptr())
})?;
FunctionHandle::qwen_success(f as usize)
}
pub(crate) fn launch_iq3_native_integer(
&self,
f: FunctionHandle,
tokens: u32,
reduce: bool,
args: &mut Iq3NativeIntegerArguments,
) -> Result<()> {
if !(1..=64).contains(&tokens) {
return Err(Error::InvalidProjectionShape);
}
let (x, y, z, by) = if reduce {
(160, tokens, 1, 4)
} else {
(40, tokens.div_ceil(8), 80, 1)
};
// SAFETY: fixed complete M640/K2560/T1..64 grid, exact privately boxed ABI;
// queue retains every owner through one same-default-stream synchronize/pop.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
f.0 as *mut c_void,
x,
y,
z,
32,
by,
1,
0,
std::ptr::null_mut(),
args.parameters(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn load_native_resident_d4(&self) -> Result<ModuleHandle> {
let ptx = crate::mmq::resident::native_activation::asset()?;
let mut m = std::ptr::null_mut();
// SAFETY: pinned immutable NUL PTX in current owned Context.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast())
})?;
ModuleHandle::qwen_success(m as usize)
}
pub(crate) fn native_resident_d4_function(
&self,
m: ModuleHandle,
) -> Result<FunctionHandle> {
let mut f = std::ptr::null_mut();
// SAFETY: fixed entry in actual owned module.
check("cuModuleGetFunction", unsafe {
(self.get_function)(
&mut f,
m.0 as *mut c_void,
c"leleka_native_resident_d4".as_ptr(),
)
})?;
FunctionHandle::qwen_success(f as usize)
}
pub(crate) fn load_head_greedy(&self) -> Result<ModuleHandle> {
let asset = crate::head_greedy::asset()?;
let mut module = std::ptr::null_mut();
// SAFETY: pinned hand-authored NUL PTX, actual current Context.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut module, crate::arch_ptx::image(asset).as_ptr().cast())
})?;
ModuleHandle::qwen_success(module as usize)
}
pub(crate) fn head_greedy_function(
&self,
module: ModuleHandle,
last: bool,
) -> Result<FunctionHandle> {
let name = if last {
c"leleka_head_final"
} else {
c"leleka_head_groups"
};
let mut function = std::ptr::null_mut();
// SAFETY: closed two-entry map, actual retained module.
check("cuModuleGetFunction", unsafe {
(self.get_function)(&mut function, module.0 as *mut c_void, name.as_ptr())
})?;
FunctionHandle::qwen_success(function as usize)
}
pub(crate) fn launch_head_greedy(
&self,
function: FunctionHandle,
last: bool,
args: &mut HeadGreedyArguments,
) -> Result<()> {
// SAFETY: closed whole-vocabulary topology, block256, stable two-pointer ABI.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
if last { 1 } else { 970 },
1,
1,
256,
1,
1,
0,
std::ptr::null_mut(),
args.parameters(),
std::ptr::null_mut(),
)
})
}
}
@@ -0,0 +1,243 @@
//! Moved out of the parent module by STRA-338: impl Api (2).
#[allow(unused_imports)]
use super::*;
impl Api {
pub(crate) fn mmq_original_group_shared_limit(&self) -> Result<u32> {
let library = &self._library;
let get = symbol!(
library,
c"cuCtxGetDevice",
unsafe extern "C" fn(*mut c_int) -> CuResult
);
let attr = symbol!(
library,
c"cuDeviceGetAttribute",
unsafe extern "C" fn(*mut c_int, c_int, CuDevice) -> CuResult
);
let mut device = 0;
let mut limit = 0;
// SAFETY: current real Context, fixed attribute97 and live output slots.
check("cuCtxGetDevice", unsafe { get(&mut device) })?;
check("cuDeviceGetAttribute", unsafe {
attr(&mut limit, 97, device)
})?;
u32::try_from(limit).map_err(|_| Error::InvalidDriverValue("MMQ shared capacity"))
}
pub(crate) fn load_mmq_original_group(&self, kind: u32) -> Result<ModuleHandle> {
let ptx = crate::mmq::resident::original_group::asset(kind)?;
let mut module = std::ptr::null_mut();
// SAFETY: sealed immutable NUL asset, live current Context.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut module, crate::arch_ptx::image(ptx).as_ptr().cast())
})?;
ModuleHandle::qwen_success(module as usize)
}
pub(crate) fn mmq_original_group_function(
&self,
module: ModuleHandle,
kind: u32,
width: u32,
fixup: bool,
) -> Result<FunctionHandle> {
let name=match(kind,width,fixup){
(0,0,false)=>c"leleka_original_mmq_swiglu",
(1,0,false)=>c"leleka_original_mmq_gather",
(2,0,false)=>c"leleka_original_mmq_gu_finite",
(18,8,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,16,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,24,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,32,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,40,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,48,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,64,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,80,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,96,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,112,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(18,128,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(18,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,8,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,16,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,24,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,32,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,40,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,48,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,64,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,80,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,96,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,112,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(22,128,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(22,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,8,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,16,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,24,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,32,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,40,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,48,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,64,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,80,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,96,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,112,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(21,128,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(21,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,8,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,16,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,24,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,32,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,40,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,48,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,64,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,80,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,96,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,112,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(23,128,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(23,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,8,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,16,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,24,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,32,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,40,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,48,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,64,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,80,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,96,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,112,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(20,128,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(20,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,8,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,16,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,24,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,32,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,40,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,48,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,64,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,80,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,96,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,112,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
(42,128,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_",
(42,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_",
_=>return Err(Error::InvalidProjectionShape),
};
let mut f = std::ptr::null_mut();
// SAFETY: closed literal Original template symbols only.
check("cuModuleGetFunction", unsafe {
(self.get_function)(&mut f, module.0 as *mut c_void, name.as_ptr())
})?;
FunctionHandle::qwen_success(f as usize)
}
pub(crate) fn launch_mmq_original_gather(
&self,
f: FunctionHandle,
words: u32,
args: &mut MmqOriginalGatherArguments,
) -> Result<()> {
if words == 0 || words > 172800 {
return Err(Error::InvalidProjectionShape);
}
// SAFETY: literal Original copy16 block256, complete genuine same
// Context input loans plus actual bank destination retained to drain.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
f.0 as *mut c_void,
words.div_ceil(256),
1,
1,
256,
1,
1,
0,
std::ptr::null_mut(),
args.parameters(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn launch_mmq_original_group_helper(
&self,
f: FunctionHandle,
words: u32,
args: &mut MmqResidentArguments,
) -> Result<()> {
if words == 0 || words > 209715200 {
return Err(Error::InvalidProjectionShape);
}
// SAFETY: same integer helper kernel, closed admitted bank extent
// <=8192*10*2560 F32 words, retained through unchanged final drain.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
f.0 as *mut c_void,
words.div_ceil(256),
1,
1,
256,
1,
1,
0,
std::ptr::null_mut(),
args.parameters(),
std::ptr::null_mut(),
)
})
}
}
@@ -0,0 +1,252 @@
//! Moved out of the parent module by STRA-338: impl Api (3).
#[allow(unused_imports)]
use super::*;
impl Api {
pub(crate) fn launch_mmq_original_swiglu(
&self,
f: FunctionHandle,
rows: u32,
args: &mut MmqOriginalSwigluArguments,
) -> Result<()> {
if !(1..=81920).contains(&rows) {
return Err(Error::InvalidProjectionShape);
}
// SAFETY: admitted closed whole GU/H roles; literal Original block256 grid.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
f.0 as *mut c_void,
(rows * 640).div_ceil(256),
1,
1,
256,
1,
1,
0,
std::ptr::null_mut(),
args.parameters(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn load_mmq_resident(&self) -> Result<ModuleHandle> {
let ptx = crate::mmq::resident::asset()?;
let mut module = std::ptr::null_mut();
// SAFETY: exact pinned immutable NUL PTX, current live Context.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut module, crate::arch_ptx::image(ptx).as_ptr().cast())
})?;
ModuleHandle::qwen_success(module as usize)
}
pub(crate) fn mmq_resident_function(
&self,
module: ModuleHandle,
kind: u8,
) -> Result<FunctionHandle> {
let name = match kind {
0 => c"leleka_mmq_zero",
1 => c"leleka_mmq_finite",
2 => c"leleka_mmq_gather",
_ => return Err(Error::InvalidProjectionShape),
};
let mut f = std::ptr::null_mut();
// SAFETY: closed three-entry name map, actual retained helper module.
check("cuModuleGetFunction", unsafe {
(self.get_function)(&mut f, module.0 as *mut c_void, name.as_ptr())
})?;
FunctionHandle::qwen_success(f as usize)
}
pub(crate) fn launch_mmq_resident(
&self,
f: FunctionHandle,
words: u32,
args: &mut MmqResidentArguments,
) -> Result<()> {
if words == 0 || words > 33554432 {
return Err(Error::InvalidProjectionShape);
}
// SAFETY: fixed helper ABI, block256, checked complete capacity, stable args through sync.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
f.0 as *mut c_void,
words.div_ceil(256),
1,
1,
256,
1,
1,
0,
std::ptr::null_mut(),
args.parameters(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn quantize_mmq(
&self,
function: FunctionHandle,
l: crate::mmq::Layout,
args: &mut MmqQuantArguments,
) -> Result<()> {
// SAFETY: exact closed upstream quantizer ABI, complete disjoint extents, stable args through sync.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
l.tokens,
l.padded_columns / 512,
1,
128,
1,
1,
0,
std::ptr::null_mut(),
args.parameters(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn project_mmq(
&self,
function: FunctionHandle,
l: crate::mmq::Layout,
grid: u32,
args: &mut MmqArguments,
) -> Result<()> {
// SAFETY: exact closed upstream mul ABI and original shared geometry; args retained through sync.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid,
1,
1,
32,
8,
1,
l.shared,
std::ptr::null_mut(),
args.parameters(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn fixup_mmq(
&self,
function: FunctionHandle,
grid: u32,
args: &mut MmqFixupArguments,
) -> Result<()> {
// SAFETY: closed fixed 13-param ABI, actual same scratch/result after completed mul; args retained through sync.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid,
4,
1,
32,
4,
1,
0,
std::ptr::null_mut(),
args.parameters(),
std::ptr::null_mut(),
)
})
}
// Numerical qualification loader exists only in a libtest ELF.
// Immutable candidate bytes are statically pinned; no external executable input.
#[cfg(target_arch = "x86_64")]
pub(crate) fn load_gr_batch_preview_module(&self) -> Result<ModuleHandle> {
let ptx = crate::qwen_ffi::gr_batch_preview_ptx()?;
let mut module = std::ptr::null_mut();
// SAFETY: fixed NUL-terminated immutable proof PTX, current owner context.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut module, crate::arch_ptx::image(ptx).as_ptr().cast())
})?;
ModuleHandle::qwen_success(module as usize)
}
pub(crate) fn load_qsa_selected(&self) -> Result<ModuleHandle> {
let ptx = crate::qsa_selected_kv::asset()?;
let mut module = std::ptr::null_mut();
// SAFETY: fixed privately pinned NUL-terminated PTX, current owning Context.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut module, crate::arch_ptx::image(ptx).as_ptr().cast())
})?;
ModuleHandle::qwen_success(module as usize)
}
pub(crate) fn qsa_selected_function(
&self,
module: ModuleHandle,
gather: bool,
) -> Result<FunctionHandle> {
let name = if gather {
c"leleka_qsa_selected_gather"
} else {
c"leleka_qsa_selected_scatter"
};
let mut function = std::ptr::null_mut();
// SAFETY: two fixed entry names, live retained module and writable out pointer.
check("cuModuleGetFunction", unsafe {
(self.get_function)(&mut function, module.0 as *mut c_void, name.as_ptr())
})?;
FunctionHandle::qwen_success(function as usize)
}
pub(crate) fn launch_qsa_selected(
&self,
function: FunctionHandle,
count: u32,
args: &mut QsaSelectedArguments,
) -> Result<()> {
if !(1..=2051).contains(&count) {
return Err(Error::InvalidQwenShape);
}
// SAFETY: closed seven-argument byte ABI; fixed 256 threads and checked count.
// Owned argument storage and buffers survive final sync/restore.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
(count * 1024).div_ceil(256),
1,
1,
256,
1,
1,
0,
std::ptr::null_mut(),
args.parameters(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn load_qwen_module(
&self,
asset: &crate::qwen_ffi::Asset,
) -> Result<ModuleHandle> {
asset.validate(asset.operation)?;
let mut module = std::ptr::null_mut();
// SAFETY: validated immutable closed-map NUL-terminated PTX and
// current owning context. No caller can supply this asset.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut module, crate::arch_ptx::image(asset.ptx).as_ptr().cast())
})?;
ModuleHandle::qwen_success(module as usize)
}
pub(crate) fn qwen_function(
&self,
module: ModuleHandle,
operation: crate::qwen_ffi::Operation,
) -> Result<FunctionHandle> {
let mut function = std::ptr::null_mut();
// SAFETY: live private module, fixed operation-to-entry map and
// writable output. No external symbol resolver is exposed.
check("cuModuleGetFunction", unsafe {
(self.get_function)(
&mut function,
module.0 as *mut c_void,
operation.entry().as_ptr(),
)
})?;
FunctionHandle::qwen_success(function as usize)
}
}
@@ -0,0 +1,254 @@
//! Moved out of the parent module by STRA-338: impl Api (4).
#[allow(unused_imports)]
use super::*;
impl Api {
pub(crate) fn launch_qwen(
&self,
function: FunctionHandle,
operation: crate::qwen_ffi::Operation,
arguments: &mut crate::qwen_ffi::Arguments,
) -> Result<()> {
let layout = arguments.layout();
let _ = operation;
// SAFETY: fixed qualified function/geometry, validated complete
// extents/aliases/ownership and stable raw-owned typed scalars.
// Caller syncs every launch attempt and retains on uncertainty.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
layout.grid,
layout.grid_y,
layout.grid_z,
layout.block,
layout.block_y,
1,
layout.shared_bytes,
std::ptr::null_mut(),
arguments.parameters(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn load() -> Result<Self> {
// SAFETY: fixed NUL-terminated soname and immediate local lookup.
let handle = unsafe {
libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL)
};
if handle.is_null() {
return Err(Error::LibraryUnavailable);
}
Self::resolve(Library(handle))
}
pub(super) fn resolve(library: Library) -> Result<Self> {
// Evaluation order preserves all sixteen pre-init resolutions.
// The library moves only after every fallible symbol check.
Ok(Self {
init: symbol!(library, c"cuInit", Init),
version: symbol!(library, c"cuDriverGetVersion", DriverGetVersion),
device: symbol!(library, c"cuDeviceGet", DeviceGet),
create: symbol!(library, c"cuCtxCreate_v2", ContextCreateV2),
destroy: symbol!(library, c"cuCtxDestroy_v2", ContextDestroyV2),
push: symbol!(library, c"cuCtxPushCurrent_v2", ContextPushCurrentV2),
pop: symbol!(library, c"cuCtxPopCurrent_v2", ContextPopCurrentV2),
synchronize: symbol!(library, c"cuCtxSynchronize", ContextSynchronize),
stream_synchronize: symbol!(library, c"cuStreamSynchronize", StreamSynchronizeRaw),
allocate: symbol!(library, c"cuMemAlloc_v2", MemAllocV2),
free: symbol!(library, c"cuMemFree_v2", MemFreeV2),
copy_from: symbol!(library, c"cuMemcpyHtoD_v2", MemcpyHtoDV2),
copy_to: symbol!(library, c"cuMemcpyDtoH_v2", MemcpyDtoHV2),
copy_moe_down: symbol!(library, c"cuMemcpyDtoD_v2", MemcpyDtoDV2),
zero: symbol!(library, c"cuMemsetD8_v2", MemsetD8V2),
load_module: symbol!(library, c"cuModuleLoadData", ModuleLoadData),
get_function: symbol!(library, c"cuModuleGetFunction", ModuleGetFunction),
unload_module: symbol!(library, c"cuModuleUnload", ModuleUnload),
launch_kernel: symbol!(library, c"cuLaunchKernel", LaunchKernel),
_library: library,
})
}
#[cfg(target_arch = "x86_64")]
pub(crate) fn load_q6_batch_preview(&self) -> Result<ModuleHandle> {
let bytes = crate::qwen_ffi::q6_batch_preview_ptx()?;
let mut module = std::ptr::null_mut();
// SAFETY: fixed immutable pinned candidate bytes, NUL terminated,
// current owned context and writable private opaque output.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut module, crate::arch_ptx::image(bytes).as_ptr().cast())
})?;
ModuleHandle::qwen_success(module as usize)
}
#[cfg(target_arch = "x86_64")]
pub(crate) fn quantize_q6_batch(
&self,
function: FunctionHandle,
grid: u32,
tokens: u32,
arguments: &mut Q8QuantizeArguments,
) -> Result<()> {
// SAFETY: checked whole matrix spans/context and fixed candidate
// entry; raw-owned arguments survive synchronization by caller.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid,
tokens,
1,
256,
1,
1,
0,
std::ptr::null_mut(),
(&raw mut (*arguments.storage.as_ptr()).parameters).cast(),
std::ptr::null_mut(),
)
})
}
#[cfg(target_arch = "x86_64")]
pub(crate) fn project_q6_batch(
&self,
function: FunctionHandle,
grid: u32,
tokens: u32,
arguments: &mut Q6ProjectionArguments,
) -> Result<()> {
// SAFETY: checked unchanged weights and whole Q8_1/output matrix
// spans; scalar geometry except grid_y; retained typed arguments.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid,
tokens,
1,
32,
4,
1,
0,
std::ptr::null_mut(),
(&raw mut (*arguments.storage.as_ptr()).parameters).cast(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn load_fixed_module(&self, operation: FixedOperation) -> Result<ModuleHandle> {
let bytes = match operation {
FixedOperation::CommonQuantize => COMMON_QUANTIZER_PTX,
FixedOperation::GroupedSwiglu => {
concat!(include_str!("../../moe_group_swiglu.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedDownIq4 => {
concat!(include_str!("../../moe_group_down_iq4_nl.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedDownQ2 => {
concat!(include_str!("../../moe_group_down_q2_0.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedIq3 => {
concat!(include_str!("../../moe_group_iq3_xxs.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedIq2 => {
concat!(include_str!("../../moe_group_iq2_s.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedIq3S => {
concat!(include_str!("../../moe_group_iq3_s.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedIq4Xs => {
concat!(include_str!("../../moe_group_iq4_xs.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedIq3SNc4 => {
concat!(include_str!("../../moe_group_iq3_s_nc4.ptx"), "\0").as_bytes()
}
FixedOperation::GroupedIq4XsNc4 => {
concat!(include_str!("../../moe_group_iq4_xs_nc4.ptx"), "\0").as_bytes()
}
FixedOperation::Projection(kind) => {
projection_ptx(kind).ok_or(Error::UnsupportedProjection)?
}
FixedOperation::VectorAdd => FIXED_PTX,
FixedOperation::GrReadFinite => {
concat!(include_str!("../../gr_read_guard.ptx"), "\0").as_bytes()
}
FixedOperation::Matvec => MATVEC_PTX,
FixedOperation::Q5K | FixedOperation::Q5KQuantize | FixedOperation::Q5KProject => {
Q5_K_PTX
}
FixedOperation::Q6K | FixedOperation::Q6KQuantize | FixedOperation::Q6KProject => {
Q6_K_PTX
}
};
if matches!(
operation,
FixedOperation::CommonQuantize
| FixedOperation::GroupedSwiglu
| FixedOperation::GroupedDownIq4
| FixedOperation::GroupedDownQ2
| FixedOperation::GroupedIq3
| FixedOperation::GroupedIq2
| FixedOperation::GroupedIq3S
| FixedOperation::GroupedIq4Xs
| FixedOperation::GroupedIq3SNc4
| FixedOperation::GroupedIq4XsNc4
| FixedOperation::Projection(_)
| FixedOperation::Q6K
| FixedOperation::Q6KQuantize
| FixedOperation::Q6KProject
) {
validate_projection_ptx(bytes)?;
}
let mut module = std::ptr::null_mut();
// SAFETY: current owned context, writable module out pointer, and
// static trusted NUL-terminated PTX remains live indefinitely.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut module, crate::arch_ptx::image(bytes).as_ptr().cast())
})?;
if module.is_null() {
return Err(Error::InvalidDriverValue("cuModuleLoadData"));
}
Ok(ModuleHandle(module as usize))
}
pub(crate) fn fixed_function(
&self,
module: ModuleHandle,
operation: FixedOperation,
) -> Result<FunctionHandle> {
let mut function = std::ptr::null_mut();
// SAFETY: live private module in current owner context; fixed C
// entry name; valid writable opaque function output.
check("cuModuleGetFunction", unsafe {
(self.get_function)(
&mut function,
module.0 as *mut c_void,
match operation {
FixedOperation::CommonQuantize => c"leleka_quantize_q8_1",
FixedOperation::GroupedSwiglu => c"leleka_moe_swiglu_f32_columns",
FixedOperation::GroupedDownIq4 => c"leleka_iq4_nl_q8_1_routed_columns",
FixedOperation::GroupedDownQ2 => c"leleka_q2_0_q8_1_routed_columns",
FixedOperation::GroupedIq3 => c"leleka_iq3_xxs_q8_1_routed_columns",
FixedOperation::GroupedIq2 => c"leleka_iq2_s_q8_1_routed_columns",
FixedOperation::GroupedIq3S => c"leleka_iq3_s_q8_1_routed_columns",
FixedOperation::GroupedIq4Xs => c"leleka_iq4_xs_q8_1_routed_columns",
FixedOperation::GroupedIq3SNc4 => c"leleka_iq3_s_q8_1_routed_columns_nc4",
FixedOperation::GroupedIq4XsNc4 => c"leleka_iq4_xs_q8_1_routed_columns_nc4",
FixedOperation::Projection(kind) => projection_entry(kind),
FixedOperation::VectorAdd => c"leleka_vector_add_f32",
FixedOperation::GrReadFinite => c"leleka_gr_read_finite",
FixedOperation::Matvec => c"leleka_matvec_f32",
FixedOperation::Q5K => {
return Err(Error::InvalidDriverValue("fixed Q5_K entry selector"));
}
FixedOperation::Q5KQuantize => c"leleka_quantize_q8_1",
FixedOperation::Q5KProject => c"leleka_q5_k_q8_1",
FixedOperation::Q6K => {
return Err(Error::InvalidDriverValue("fixed Q6_K entry selector"));
}
FixedOperation::Q6KQuantize => c"leleka_quantize_q8_1",
FixedOperation::Q6KProject => c"leleka_q6_k_q8_1",
}
.as_ptr(),
)
})?;
if function.is_null() {
return Err(Error::InvalidDriverValue("cuModuleGetFunction"));
}
Ok(FunctionHandle(function as usize))
}
}
@@ -0,0 +1,251 @@
//! Moved out of the parent module by STRA-338: impl Api (5).
#[allow(unused_imports)]
use super::*;
impl Api {
pub(crate) fn unload(&self, module: ModuleHandle) -> Result<()> {
// SAFETY: usable handle was consumed before this single attempt,
// current context owns it, and all prior work completed. It is
// never retried or reused even when unload reports failure.
check("cuModuleUnload", unsafe {
(self.unload_module)(module.0 as *mut c_void)
})
}
pub(crate) fn launch(
&self,
function: FunctionHandle,
grid: u32,
arguments: &mut LaunchArguments,
) -> Result<()> {
// SAFETY: fixed live function/owner context; checked exact shapes,
// nonaliasing output and grid; six fixed dimensions + sharedBytes;
// null stream/extra. Four pointer entries address initialized typed
// boxed values, NOT device addresses interpreted as host pointers.
// Caller keeps the entire box/table alive through mandatory sync,
// and retains it permanently on ambiguous completion.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid,
1,
1,
128,
1,
1,
0,
std::ptr::null_mut(),
(&raw mut (*arguments.storage.as_ptr()).parameters).cast(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn launch_gr_read_guard(
&self,
function: FunctionHandle,
arguments: &mut GrReadGuardArguments,
) -> Result<()> {
// SAFETY: fixed immutable five-stage pointer ABI+private4Bstatus,
// admitted lengths/current owner and pinned storage until sync.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
80,
1,
1,
128,
1,
1,
0,
std::ptr::null_mut(),
(&raw mut (*arguments.storage.as_ptr()).parameters).cast(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn launch_matvec(
&self,
function: FunctionHandle,
grid: u32,
arguments: &mut MatvecArguments,
) -> Result<()> {
// SAFETY: private trusted function in current owner context;
// checked shapes/extents/output identity and fixed geometry. Five
// pointers address initialized typed scalars in stable raw storage.
// Caller synchronizes each attempt or permanently retains storage.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid,
1,
1,
128,
1,
1,
0,
std::ptr::null_mut(),
(&raw mut (*arguments.storage.as_ptr()).parameters).cast(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn launch_q8_quantize(
&self,
function: FunctionHandle,
grid: u32,
arguments: &mut Q8QuantizeArguments,
) -> Result<()> {
// SAFETY: fixed entry, exact bounded grid, 256 threads, and stable
// raw-owned scalar/pointer table retained through synchronization.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid,
1,
1,
256,
1,
1,
0,
std::ptr::null_mut(),
(&raw mut (*arguments.storage.as_ptr()).parameters).cast(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn launch_q5_projection(
&self,
function: FunctionHandle,
grid: u32,
arguments: &mut Q5ProjectionArguments,
) -> Result<()> {
// SAFETY: fixed entry, 32x4 threads, fixed launch geometry and
// stable raw-owned argument storage through synchronized completion.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid,
1,
1,
32,
4,
1,
0,
std::ptr::null_mut(),
(&raw mut (*arguments.storage.as_ptr()).parameters).cast(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn launch_q6_projection(
&self,
function: FunctionHandle,
grid: u32,
arguments: &mut Q6ProjectionArguments,
) -> Result<()> {
// SAFETY: fixed entry, checked Q6 geometry, and stable raw-owned
// pointer/scalar storage retained through synchronized completion.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid,
1,
1,
32,
4,
1,
0,
std::ptr::null_mut(),
(&raw mut (*arguments.storage.as_ptr()).parameters).cast(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn launch_projection(
&self,
function: FunctionHandle,
grid: u32,
arguments: &mut ProjectionArguments,
) -> Result<()> {
// SAFETY: fixed entry, checked common projection geometry, and stable raw-owned
// pointer/scalar storage retained through synchronized completion.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid,
1,
1,
32,
4,
1,
0,
std::ptr::null_mut(),
(&raw mut (*arguments.storage.as_ptr()).parameters).cast(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn launch_grouped_projection(
&self,
function: FunctionHandle,
grid: u32,
columns: u32,
arguments: &mut ProjectionArguments,
) -> Result<()> {
// SAFETY: fixed entry, checked common projection geometry, and stable raw-owned
// pointer/scalar storage retained through synchronized completion.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid,
columns,
1,
32,
4,
1,
0,
std::ptr::null_mut(),
(&raw mut (*arguments.storage.as_ptr()).parameters).cast(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn launch_grouped_swiglu(
&self,
function: FunctionHandle,
grid: u32,
columns: u32,
arguments: &mut ProjectionArguments,
) -> Result<()> {
// SAFETY: fixed entry, checked common projection geometry, and stable raw-owned
// pointer/scalar storage retained through synchronized completion.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid,
columns,
1,
128,
1,
1,
0,
std::ptr::null_mut(),
(&raw mut (*arguments.storage.as_ptr()).parameters).cast(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn init(&self) -> Result<()> {
// SAFETY: resolved exact ABI, mandated zero flags, live library.
check("cuInit", unsafe { (self.init)(0) })
}
pub(crate) fn version(&self) -> Result<i32> {
let mut value = 0;
// SAFETY: resolved ABI and valid initialized writable C int.
check("cuDriverGetVersion", unsafe { (self.version)(&mut value) })?;
Ok(value)
}
}
@@ -0,0 +1,167 @@
//! Moved out of the parent module by STRA-338: impl Api (6).
#[allow(unused_imports)]
use super::*;
impl Api {
pub(crate) fn device(&self, ordinal: i32) -> Result<i32> {
let mut value = 0;
// SAFETY: resolved ABI, valid out pointer, ordinal prevalidated.
check("cuDeviceGet", unsafe { (self.device)(&mut value, ordinal) })?;
Ok(value)
}
pub(crate) fn create(&self, device: i32) -> Result<ContextHandle> {
let mut context = std::ptr::null_mut();
// SAFETY: exact legacy v2 THREE-argument ABI, zero flags, a device
// returned by cuDeviceGet, and a valid writable context pointer.
check("cuCtxCreate_v2", unsafe {
(self.create)(&mut context, 0, device)
})?;
if context.is_null() {
return Err(Error::InvalidDriverValue("cuCtxCreate_v2"));
}
Ok(ContextHandle(context as usize))
}
pub(crate) fn destroy(&self, context: ContextHandle) -> Result<()> {
// SAFETY: this handle was created by this Api and remains owned by
// the caller context. No buffer can outlive the borrow owner. This
// API explicitly supports destroying a non-current owned context.
check("cuCtxDestroy_v2", unsafe {
(self.destroy)(context.0 as CuContext)
})
}
pub(crate) fn push(&self, context: ContextHandle) -> Result<()> {
// SAFETY: live private context, same creating thread (Rc owners).
check("cuCtxPushCurrent_v2", unsafe {
(self.push)(context.0 as CuContext)
})
}
pub(crate) fn pop(&self) -> Result<ContextHandle> {
let mut context = std::ptr::null_mut();
// SAFETY: called after successful create/push on the same thread,
// valid out pointer. Callers verify identity and poison on failure.
check("cuCtxPopCurrent_v2", unsafe { (self.pop)(&mut context) })?;
Ok(ContextHandle(context as usize))
}
pub(crate) fn synchronize(&self) -> Result<()> {
if crate::compute_drain::background() != 0 {
// a chunk expert stream is in flight: queue a few more of its copies behind the work being
// drained, then wait for the compute streams only (never for the copy stream)
crate::prefetch_point();
// SAFETY: caller guard makes its live owned context current; registered live streams.
return crate::compute_drain::timed(5, || crate::compute_drain::drain(|s| {
check("cuStreamSynchronize", unsafe { (self.stream_synchronize)(s as *mut c_void) })
}));
}
// SAFETY: caller guard makes its live owned context current.
check("cuCtxSynchronize", unsafe { (self.synchronize)() })
}
pub(crate) fn allocate(&self, bytes: usize) -> Result<BufferHandle> {
crate::compute_drain::note_alloc("cuMemAlloc", bytes);
let mut ptr = 0;
// SAFETY: current-context guard; nonzero, bounded size validated
// before mutation; valid u64 CUdeviceptr output on Linux64.
crate::compute_drain::timed(0, || check("cuMemAlloc_v2", unsafe { (self.allocate)(&mut ptr, bytes) }))?;
if ptr == 0 {
return Err(Error::InvalidDriverValue("cuMemAlloc_v2"));
}
Ok(BufferHandle(ptr))
}
pub(crate) fn free(&self, buffer: BufferHandle) -> Result<()> {
crate::compute_drain::note_alloc("cuMemFree", 0);
// SAFETY: uniquely owned allocation, owner context is current.
// Poisoned/uncertain contexts never enter this operation.
crate::compute_drain::timed(1, || check("cuMemFree_v2", unsafe { (self.free)(buffer.0) }))
}
pub(crate) fn copy_from(&self, buffer: BufferHandle, owned: &[u8]) -> Result<()> {
// SAFETY: buffer owner is current, exact allocation size checked,
// and the caller owns this staging allocation. It synchronizes on
// both success/error and leaks staging on ambiguous completion, so
// the pointer stays valid even if the call retains it after return.
if crate::compute_drain::zero_memset() && owned.len() <= 1 << 20 && owned.iter().all(|b| *b == 0) {
// EXPERIMENT (chunk stream in flight): an all-zero upload is a device memset, which does not queue
// behind the expert copies on the host-to-device copy engine
return crate::compute_drain::timed(4, || check("cuMemsetD8_v2", unsafe {
(self.zero)(buffer.0, 0, owned.len())
}));
}
crate::compute_drain::timed(2, || check("cuMemcpyHtoD_v2", unsafe {
(self.copy_from)(buffer.0, owned.as_ptr().cast(), owned.len())
}))
}
pub(crate) fn copy_to(&self, buffer: BufferHandle, owned: &mut [u8]) -> Result<()> {
// SAFETY: valid owned writable staging of exactly the allocation
// size; current owner context; caller synchronizes or leaks as
// above. No borrowed output is passed directly to the driver.
crate::compute_drain::timed(3, || check("cuMemcpyDtoH_v2", unsafe {
(self.copy_to)(owned.as_mut_ptr().cast(), buffer.0, owned.len())
}))
}
pub(crate) fn zero(&self, destination: u64, bytes: usize) -> Result<()> {
if destination == 0 || bytes == 0 {
return Err(Error::InvalidSize);
}
// SAFETY: caller owns the current-context allocation and has
// validated this exact nonzero extent before dispatch.
crate::compute_drain::timed(4, || check("cuMemsetD8_v2", unsafe {
(self.zero)(destination, 0, bytes)
}))
}
pub(crate) fn copy_mmq_weight(
&self,
destination: BufferHandle,
source: BufferHandle,
bytes: usize,
) -> Result<()> {
if !matches!(bytes, 627200 | 524800 | 704000 | 870400 | 921600 | 460800) {
return Err(Error::InvalidProjectionShape);
}
// SAFETY: the closed MMQ facade validates actual same-context,
// disjoint whole raw source and padded destination allocations.
// Owners stay borrowed until synchronize/pop, with poison on uncertainty.
crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe {
(self.copy_moe_down)(destination.0, source.0, bytes)
}))
}
pub(crate) fn copy_moe_down(
&self,
destination: BufferHandle,
source: BufferHandle,
) -> Result<()> {
// SAFETY: facade admits exact same-context disjoint owned extents,
// a checked ten-slot destination address and exactly10240 bytes.
// Both allocations remain borrowed until sync and context restore;
// ambiguous completion poisons their context before any later free.
crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe {
(self.copy_moe_down)(destination.0, source.0, 10_240)
}))
}
pub(crate) fn copy_original_down_group(
&self,
destination: BufferHandle,
source: BufferHandle,
bytes: usize,
) -> Result<()> {
if bytes == 0 || !bytes.is_multiple_of(10_240) || bytes > 8192 * 10 * 10_240 {
return Err(Error::InvalidProjectionShape);
}
// SAFETY: actual affine grouped Down producer and prompt arena
// supply disjoint checked extents; both survive sync and pop.
crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe {
(self.copy_moe_down)(destination.0, source.0, bytes)
}))
}
pub(crate) fn copy_moe_group_column(
&self,
destination: BufferHandle,
source: BufferHandle,
) -> Result<()> {
// SAFETY: facade admits exact same-context disjoint owned extents,
// a checked 64-column destination address and exactly2560 bytes.
// Both allocations remain borrowed until sync and context restore;
// ambiguous completion poisons their context before any later free.
crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe {
(self.copy_moe_down)(destination.0, source.0, 2560)
}))
}
}
@@ -0,0 +1,22 @@
//! Moved out of the parent module by STRA-338: impl Drop_for_Library, fn check.
#[allow(unused_imports)]
use super::*;
impl Drop for Library {
fn drop(&mut self) {
// SAFETY: this is the successful dlopen handle, owned exactly once.
// All loaded functions live in Api alongside this Library. Driver
// owner borrows retain Api through all resource operations/cleanup.
unsafe {
libc::dlclose(self.0);
}
}
}
pub(super) fn check(operation: &'static str, code: CuResult) -> Result<()> {
if code == 0 {
Ok(())
} else {
Err(Error::Driver { operation, code })
}
}
@@ -0,0 +1,143 @@
//! Moved out of the parent file by STRA-338 (same module path as before).
use super::*;
#[test]
fn new_fixed_asset_encoding_refuses_unicode_before_driver_call() {
assert_eq!(
validate_projection_ptx(include_bytes!("../q6_k_q8_1.ptx")),
Ok(())
);
assert_eq!(
validate_projection_ptx(include_bytes!("../q8_1_quantize.ptx")),
Ok(())
);
assert_eq!(validate_projection_ptx(b"// plain ASCII\n\0"), Ok(()));
assert_eq!(
validate_projection_ptx("// \u{d7}\n\0".as_bytes()),
Err(Error::InvalidDriverValue("fixed PTX encoding"))
);
}
#[test]
fn q4_k_dense_selector_resolves_only_its_qualified_asset() {
let kind = ProjectionKind::Dense(DenseFormat::Q4_K);
let bytes = projection_ptx(kind).expect("fixed Q4_K asset is integrated");
assert_eq!(
bytes,
concat!(include_str!("../q4_k_q8_1.ptx"), "\0").as_bytes()
);
assert_eq!(validate_projection_ptx(bytes), Ok(()));
assert_eq!(projection_entry(kind).to_bytes(), b"leleka_q4_k_q8_1_dense");
}
#[test]
fn iq3_s_routed_selector_resolves_only_its_qualified_asset() {
let kind = ProjectionKind::Routed(RoutedFormat::IQ3_S);
let bytes = projection_ptx(kind).expect("fixed IQ3_S asset is integrated");
assert_eq!(
bytes,
concat!(include_str!("../iq3_s_q8_1.ptx"), "\0").as_bytes()
);
assert_eq!(validate_projection_ptx(bytes), Ok(()));
assert_eq!(
projection_entry(kind).to_bytes(),
b"leleka_iq3_s_q8_1_routed"
);
}
#[test]
fn iq2_s_routed_selector_resolves_only_its_qualified_asset() {
let kind = ProjectionKind::Routed(RoutedFormat::IQ2_S);
let bytes = projection_ptx(kind).expect("fixed IQ2_S asset is integrated");
assert_eq!(
bytes,
concat!(include_str!("../iq2_s_q8_1.ptx"), "\0").as_bytes()
);
assert_eq!(validate_projection_ptx(bytes), Ok(()));
assert_eq!(
projection_entry(kind).to_bytes(),
b"leleka_iq2_s_q8_1_routed"
);
}
#[test]
fn q2_0_routed_selector_resolves_only_its_qualified_asset() {
let kind = ProjectionKind::Routed(RoutedFormat::Q2_0);
let bytes = projection_ptx(kind).expect("fixed Q2_0 asset is integrated");
assert_eq!(
bytes,
concat!(include_str!("../q2_0_q8_1.ptx"), "\0").as_bytes()
);
assert_eq!(validate_projection_ptx(bytes), Ok(()));
assert_eq!(
projection_entry(kind).to_bytes(),
b"leleka_q2_0_q8_1_routed"
);
}
#[test]
fn iq4_nl_dense_and_routed_select_distinct_entries_from_one_asset() {
let dense = ProjectionKind::Dense(DenseFormat::IQ4_NL);
let routed = ProjectionKind::Routed(RoutedFormat::IQ4_NL);
let bytes = concat!(include_str!("../iq4_nl_q8_1.ptx"), "\0").as_bytes();
assert_eq!(projection_ptx(dense), Some(bytes));
assert_eq!(projection_ptx(routed), Some(bytes));
assert_eq!(validate_projection_ptx(bytes), Ok(()));
assert_eq!(
projection_entry(dense).to_bytes(),
b"leleka_iq4_nl_q8_1_dense"
);
assert_eq!(
projection_entry(routed).to_bytes(),
b"leleka_iq4_nl_q8_1_routed"
);
}
#[test]
fn iq4_xs_dense_and_routed_select_distinct_entries_from_one_asset() {
let dense = ProjectionKind::Dense(DenseFormat::IQ4_XS);
let routed = ProjectionKind::Routed(RoutedFormat::IQ4_XS);
let bytes = concat!(include_str!("../iq4_xs_q8_1.ptx"), "\0").as_bytes();
assert_eq!(projection_ptx(dense), Some(bytes));
assert_eq!(projection_ptx(routed), Some(bytes));
assert_eq!(validate_projection_ptx(bytes), Ok(()));
assert_eq!(
projection_entry(dense).to_bytes(),
b"leleka_iq4_xs_q8_1_dense"
);
assert_eq!(
projection_entry(routed).to_bytes(),
b"leleka_iq4_xs_q8_1_routed"
);
}
#[test]
fn packed_alignment_extents_and_overlap() {
assert_eq!(BufferHandle(2).validate_projection_extent(34, 2), Ok(()));
assert_eq!(
BufferHandle(2).validate_projection_extent(4, 4),
Err(Error::InvalidProjectionShape)
);
assert_eq!(
BufferHandle(u64::MAX - 1).validate_projection_extent(4, 2),
Err(Error::InvalidProjectionShape)
);
assert!(BufferHandle(16).overlaps(8, BufferHandle(12), 8));
assert!(!BufferHandle(16).overlaps(8, BufferHandle(8), 8));
}
#[test]
fn common_projection_raw_owner_keeps_exact_parameter_widths() {
let args = ProjectionArguments::new(
BufferHandle(11),
BufferHandle(22),
BufferHandle(33),
129,
u32::MAX,
);
let pointer = args.storage.as_ptr();
let moved = vec![args].pop().unwrap();
let churn: Vec<_> = (0..1024).map(|_| Box::new([7u64; 8])).collect();
std::hint::black_box(churn);
assert_eq!(moved.storage.as_ptr(), pointer);
// SAFETY: live privately raw-owned fixed fields, read their exact widths.
unsafe {
for (i, v) in [11u64, 22, 33].into_iter().enumerate() {
assert_eq!(*(*pointer).parameters[i].cast::<u64>(), v);
}
assert_eq!(*(*pointer).parameters[3].cast::<u32>(), 129);
assert_eq!(*(*pointer).parameters[4].cast::<u32>(), u32::MAX);
}
}
+67
View File
@@ -0,0 +1,67 @@
//! Moved out of the parent file by STRA-338 (same module path as before).
#[test]
fn checked_subspan_refuses_empty_wrap_and_outside_allocation() {
use crate::Error;
let h = super::BufferHandle::synthetic(4096);
assert!(h.checked_subspan(1024, 0, 1024).is_ok());
assert!(h.checked_subspan(1024, 1023, 1).is_ok());
for (offset, bytes) in [(0, 0), (1024, 1), (1023, 2), (usize::MAX, 1)] {
assert!(matches!(
h.checked_subspan(1024, offset, bytes),
Err(Error::InvalidSize)
));
}
assert!(
super::BufferHandle::synthetic(u64::MAX - 2)
.checked_subspan(4, 0, 1)
.is_err()
);
assert!(
super::BufferHandle::synthetic(0)
.checked_subspan(4, 0, 1)
.is_err()
);
}
use super::*;
#[test]
fn matvec_address_extents() {
assert_eq!(
BufferHandle(0).validate_extent(4),
Err(Error::InvalidMatvecShape)
);
assert_eq!(
BufferHandle(1).validate_extent(0),
Err(Error::InvalidMatvecShape)
);
assert_eq!(
BufferHandle(u64::MAX - 3).validate_extent(4),
Err(Error::InvalidMatvecShape)
);
assert_eq!(BufferHandle(u64::MAX - 4).validate_extent(4), Ok(()));
}
#[test]
fn matvec_raw_storage_survives_owner_moves() {
let arguments = MatvecArguments::new(
BufferHandle(11),
BufferHandle(22),
BufferHandle(33),
129,
u32::MAX,
);
let pointer = arguments.storage.as_ptr();
let moved = vec![arguments].pop().unwrap();
let churn: Vec<_> = (0..1024).map(|_| Box::new([0xdeadbeefu64; 8])).collect();
std::hint::black_box(&churn);
assert_eq!(moved.storage.as_ptr(), pointer);
// SAFETY: the still-owned raw allocation and every initialized field
// pointer remain live. Read exactly their documented scalar widths.
unsafe {
for (i, expected) in [11u64, 22, 33].into_iter().enumerate() {
assert_eq!(*(*pointer).parameters[i].cast::<u64>(), expected);
}
assert_eq!(*(*pointer).parameters[3].cast::<u32>(), 129);
assert_eq!(*(*pointer).parameters[4].cast::<u32>(), u32::MAX);
}
}
+244
View File
@@ -0,0 +1,244 @@
//! Moved out of the parent module by STRA-338: impl Context.
#[allow(unused_imports)]
use super::*;
impl Context<'_> {
/// Private sticky failure primitive shared by native owners.
pub(super) fn poison(&self) {
self.poisoned.set(true);
}
/// Retain the actual loaded API after uncertain completion/restoration.
pub(super) 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())
}
pub(super) 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())?;
vram_ledger::note_alloc(handle.qwen_address(), bytes);
Ok(DeviceBuffer {
context: self,
handle: Some(handle),
bytes,
_thread: PhantomData,
borrowed: false,
})
}
/// Queue a buffer's release for after the chunk's expert stream (it stays charged until then); when the
/// queued bytes pass `LELEKA_PREFILL_DEFER_FREE_MIB` (512) they are freed at once.
pub(super) 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)
}
pub(super) 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))
}
pub(super) 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)
}
}
+220
View File
@@ -0,0 +1,220 @@
//! Moved out of the parent module by STRA-338: impl Context (2).
#[allow(unused_imports)]
use super::*;
impl Context<'_> {
/// 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)
}
}
+194
View File
@@ -0,0 +1,194 @@
//! Moved out of the parent module by STRA-338: impl Context (3).
#[allow(unused_imports)]
use super::*;
impl Context<'_> {
pub(super) 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,
)
}
}
+256
View File
@@ -0,0 +1,256 @@
//! Moved out of the parent module by STRA-338: impl Context (4).
#[allow(unused_imports)]
use super::*;
impl Context<'_> {
pub(super) 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)
}
pub(super) 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))
}
pub(super) 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))
}
pub(super) 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))
}
pub(super) 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())
}
}
+245
View File
@@ -0,0 +1,245 @@
//! Moved out of the parent module by STRA-338: impl Context (5).
#[allow(unused_imports)]
use super::*;
impl Context<'_> {
pub(super) 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]))
}
pub(super) 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")
}
}
}
pub(super) 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)
}
}
}
pub(super) 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())
}
pub(super) 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)
}
pub(super) fn q5_kernels(&self) -> Result<FixedPairKernels> {
self.fixed_pair(
&self.q5_k_kernel,
FixedOperation::Q5K,
FixedOperation::Q5KQuantize,
FixedOperation::Q5KProject,
)
}
pub(super) fn q6_kernels(&self) -> Result<FixedPairKernels> {
self.fixed_pair(
&self.q6_k_kernel,
FixedOperation::Q6K,
FixedOperation::Q6KQuantize,
FixedOperation::Q6KProject,
)
}
pub(super) 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())
}
pub(super) 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))
}
}
+162
View File
@@ -0,0 +1,162 @@
//! Moved out of the parent module by STRA-338: impl Context (6), impl Drop_for_Context, impl CurrentGuard, impl Drop_for_CurrentGuard.
#[allow(unused_imports)]
use super::*;
impl Context<'_> {
pub(super) 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
}
pub(super) fn unload_q5_kernels(&self) -> Result<()> {
self.unload_pair(&self.q5_k_kernel)
}
pub(super) 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.
pub(super) 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())
}
pub(super) 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();
}
}
impl CurrentGuard<'_, '_> {
pub(super) fn finish(mut self) -> Result<()> {
self.restore()
}
pub(super) 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();
}
}
+196
View File
@@ -0,0 +1,196 @@
//! Moved out of the parent module by STRA-338: impl DeviceBuffer, impl Drop_for_DeviceBuffer, fn chain_selects_mtp, fn chain_selects_mtp, fn set_chain_down_override.
#[allow(unused_imports)]
use super::*;
impl DeviceBuffer<'_> {
pub fn len(&self) -> usize {
self.bytes
}
pub fn is_empty(&self) -> bool {
false
}
pub(super) 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)
}
pub(super) 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()
}
pub(super) fn free(&mut self) -> Result<()> {
let Some(handle) = self.handle.take() else {
return Ok(());
};
if self.borrowed {
return Ok(());
}
vram_ledger::note_free(handle.qwen_address());
if compute_drain::background() != 0 && !self.context.poisoned.get() {
// a chunk expert stream is in flight: do not synchronize the device now
return self.context.defer_free(handle, self.bytes);
}
let guard = self.context.enter()?;
let free = self.context.driver.api.free(handle);
if free.is_ok() {
self.context
.allocated
.set(self.context.allocated.get() - self.bytes);
}
combine(free, guard.finish())
}
}
impl Drop for DeviceBuffer<'_> {
fn drop(&mut self) {
let _ = self.free();
}
}
/// `LELEKA_CHAIN` selects the chain-kernel group `mtp` (claude/chain-kernels): the draft step reads the hyper-connections with the
/// staged variant the Original runs on this card (bit-identical to the plain one) and uses the load-hoisted attention kernels.
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub fn chain_selects_mtp() -> bool {
original_verify::chain::flags().mtp
}
#[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))]
pub fn chain_selects_mtp() -> bool {
false
}
/// Without the CUDA driver there is no chain window: the override is a no-op.
#[cfg(not(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
target_pointer_width = "64"
)))]
pub fn set_chain_down_override(_: i8) {}
@@ -0,0 +1,213 @@
//! Moved out of the parent module by STRA-338: impl ProjectionKind, fn q4_k_native_indices_fit, fn projection_shape, fn projection_ranges, fn q5_k_shape.
#[allow(unused_imports)]
use super::*;
impl ProjectionKind {
pub(super) 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),
}
}
pub(super) 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,
}
}
pub(super) 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)),
}
}
}
// 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.
pub(super) 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
}
pub(super) 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.
pub(super) 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(())
}
pub(super) 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)?,
})
}
File diff suppressed because it is too large Load Diff
+113
View File
@@ -0,0 +1,113 @@
//! Moved out of the parent module by STRA-338: fn q6_k_shape, fn matvec_shape, fn matvec_allocations, fn vector_shape.
#[allow(unused_imports)]
use super::*;
pub(super) 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)?,
})
}
pub(super) 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)?,
})
}
pub(super) 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.
pub(super) 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)?,
))
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,248 @@
//! Moved out of the parent file by STRA-338 (same module path as before).
use super::*;
use crate::Driver;
fn encode(values: impl Iterator<Item = f32>) -> Vec<u8> {
values.flat_map(f32::to_le_bytes).collect()
}
fn read_pair(next: &DeviceBuffer<'_>, output: &DeviceBuffer<'_>) -> Result<[Vec<u8>; 2]> {
let mut state = vec![0; 3145728];
let mut readout = vec![0; 24576];
next.copy_to(&mut state)?;
output.copy_to(&mut readout)?;
Ok([state, readout])
}
fn count_difference(expected: &[Vec<u8>; 2], actual: &[Vec<u8>; 2]) -> u64 {
expected
.iter()
.zip(actual)
.map(|(x, y)| {
x.chunks_exact(4)
.zip(y.chunks_exact(4))
.filter(|(a, b)| a != b)
.count() as u64
})
.sum()
}
#[test]
#[ignore = "Root-only new GDN whole-product transport boundary"]
fn original_first_gdn_full_products_exact_and_whole_owner_guards() {
assert_eq!(
std::env::var("LELEKA_STRA169_RUN_GDN_PRODUCTS").as_deref(),
Ok("yes")
);
let driver = Driver::load().expect("installed driver");
let device = driver.device(0).expect("device");
let context = device
.create_context(24 * 1024 * 1024)
.expect("bounded context");
let result: Result<(u64, u32)> = (|| {
let mut inputs = [
context.allocate(3145728)?,
context.allocate(40960)?,
context.allocate(40960)?,
context.allocate(192)?,
context.allocate(192)?,
];
let mut uploaded = [
context.allocate(8192)?,
context.allocate(8192)?,
context.allocate(24576)?,
context.allocate(192)?,
context.allocate(192)?,
];
let mut outputs = [
context.allocate(3145728)?,
context.allocate(24576)?,
context.allocate(3145728)?,
context.allocate(24576)?,
];
let operation: Result<(u64, u32)> = (|| {
let mut mismatches = 0u64;
let mut guards = 0u32;
let mut last_expected = None;
let mut last_qk = Vec::new();
let mut last_h = Vec::new();
for pattern in 0..2usize {
let state = encode((0..786432usize).map(|i| {
if pattern == 0 {
if i % 2 == 0 { 0.0f32 } else { -0.0f32 }
} else {
((i % 13) as f32 - 6.0) / 1024.0
}
}));
let qk = encode((0..10240usize).map(|i| {
if i >= 4096 {
17.0f32 + (i % 7) as f32
} else if pattern == 0 {
if i % 2 == 0 { 0.0f32 } else { -0.0f32 }
} else {
((i % 11) as f32 - 5.0) / 64.0
}
}));
let h = encode((0..10240usize).map(|i| {
if i < 4096 {
-23.0f32 - (i % 9) as f32
} else if pattern == 0 {
if i % 2 == 0 { 0.0f32 } else { -0.0f32 }
} else {
((i % 29) as f32 - 14.0) / 32.0
}
}));
let gate = encode((0..48usize).map(|i| -0.0625f32 * (1 + (i % 5)) as f32));
let beta = encode((0..48usize).map(|i| 0.125f32 + (i % 7) as f32 / 16.0));
inputs[0].copy_from(&state)?;
// Independent OLD marshaling FIRST from canonical host
// slices, not candidate handles or fitted expected math.
uploaded[0].copy_from(&qk[..8192])?;
uploaded[1].copy_from(&qk[8192..16384])?;
uploaded[2].copy_from(&h[16384..])?;
uploaded[3].copy_from(&gate)?;
uploaded[4].copy_from(&beta)?;
{
let [next, output, _, _] = &mut outputs;
context.gdn_step_f32(
&inputs[0],
&uploaded[0],
&uploaded[1],
&uploaded[2],
&uploaded[3],
&uploaded[4],
next,
output,
)?;
}
let expected = read_pair(&outputs[0], &outputs[1])?;
if expected.iter().any(|bytes| {
bytes.chunks_exact(4).any(|b| {
!f32::from_le_bytes(b.try_into().expect("four bytes")).is_finite()
})
}) {
mismatches += 1;
}
inputs[1].copy_from(&qk)?;
inputs[2].copy_from(&h)?;
inputs[3].copy_from(&gate)?;
inputs[4].copy_from(&beta)?;
{
let [_, _, next, output] = &mut outputs;
context.gdn_step_from_products_f32(
&inputs[0], &inputs[1], &inputs[2], &inputs[3], &inputs[4], next,
output,
)?;
}
mismatches +=
count_difference(&expected, &read_pair(&outputs[2], &outputs[3])?);
last_expected = Some(expected);
last_qk = qk;
last_h = h;
}
// Only unused portions are poisoned. The same original old
// expected output proves exact fixed subrange association.
for bytes in last_qk[16384..].chunks_exact_mut(4) {
bytes.copy_from_slice(&f32::NAN.to_le_bytes());
}
for bytes in last_h[..16384].chunks_exact_mut(4) {
bytes.copy_from_slice(&f32::INFINITY.to_le_bytes());
}
inputs[1].copy_from(&last_qk)?;
inputs[2].copy_from(&last_h)?;
{
let [_, _, next, output] = &mut outputs;
context.gdn_step_from_products_f32(
&inputs[0], &inputs[1], &inputs[2], &inputs[3], &inputs[4], next, output,
)?;
}
mismatches += count_difference(
&last_expected.ok_or(Error::InvalidQwenShape)?,
&read_pair(&outputs[2], &outputs[3])?,
);
let before = read_pair(&outputs[2], &outputs[3])?;
// New whole-owner admission must reject both full shape gaps
// before writing either next-state or readout candidate.
let bad = context.allocate(40956)?;
let shape_operation: Result<()> = (|| {
let [_, _, next, output] = &mut outputs;
if context.gdn_step_from_products_f32(
&inputs[0], &bad, &inputs[2], &inputs[3], &inputs[4], next, output,
) != Err(Error::InvalidQwenShape)
{
mismatches += 1;
}
if context.gdn_step_from_products_f32(
&inputs[0], &inputs[1], &bad, &inputs[3], &inputs[4], next, output,
) != Err(Error::InvalidQwenShape)
{
mismatches += 1;
}
Ok(())
})();
combine(shape_operation, bad.release())?;
guards += 2;
let foreign_context = device.create_context(1024 * 1024)?;
let foreign = foreign_context.allocate(40960)?;
let context_operation: Result<()> = (|| {
let [_, _, next, output] = &mut outputs;
if context.gdn_step_from_products_f32(
&inputs[0], &foreign, &inputs[2], &inputs[3], &inputs[4], next, output,
) != Err(Error::ContextMismatch)
{
mismatches += 1;
}
Ok(())
})();
let context_operation = combine(context_operation, foreign.release());
combine(context_operation, foreign_context.close())?;
guards += 1;
// Safe public mutable references cannot express state==next.
// Test the SAME private whole-owner admission with duplicated
// actual immutable owner refs; no forged buffer or launch.
let mut whole = Operation::GdnStep.layout();
whole.bytes = [3145728, 40960, 40960, 192, 192, 3145728, 24576, 0, 0];
whole.align = [4; 9];
whole.count = 7;
whole.outputs = 0b1100000;
let alias = admission(
&context,
&[
&inputs[0],
&inputs[1],
&inputs[2],
&inputs[3],
&inputs[4],
&inputs[0],
&outputs[3],
],
Admission {
operation: Operation::GdnStep,
layout: Ok(whole),
asset: qwen_ffi::asset(Operation::GdnStep),
epsilon: 0.0,
in_place: false,
},
);
if !matches!(alias, Err(Error::OutputAliasesInput)) {
mismatches += 1;
}
guards += 1;
if read_pair(&outputs[2], &outputs[3])? != before {
mismatches += 1;
}
Ok((mismatches, guards))
})();
let mut cleanup = Ok(());
for buffer in outputs.into_iter().chain(uploaded).chain(inputs) {
cleanup = combine(cleanup, buffer.release());
}
combine(operation, cleanup)
})();
let allocated = context.allocated_bytes();
let result = combine(result, context.close());
let (mismatches, guards) = result.expect("completed changed GDN boundary and cleanup");
assert_eq!(allocated, 0);
assert_eq!(mismatches, 0);
assert_eq!(guards, 4);
eprintln!(
"GDN_PRODUCTS PASS finite_words=1585152 unused_tail_words=792576 exact_words=2377728 old_first=true next_state_and_readout=true guards={guards} allocated0=true"
);
}
@@ -0,0 +1,170 @@
//! Moved out of the parent file by STRA-338 (same module path as before).
use super::*;
use crate::Driver;
const OUTPUT_BYTES: [usize; 6] = [40960, 1280, 1280, 40960, 40960, 10240];
fn execute_read(
context: &Context<'_>,
inputs: &[DeviceBuffer<'_>; 4],
outputs: &mut [DeviceBuffer<'_>; 6],
queued: bool,
epsilon: f32,
) -> Result<u32> {
let [residual, gamma, dw, uw] = inputs;
let [xn, down, activated, gates, products, mixed] = outputs;
if queued {
context.gr_read_chain_queued(
residual, gamma, dw, uw, epsilon, xn, down, activated, gates, products, mixed,
)
} else {
context.gr_norm_f32(residual, gamma, epsilon, xn)?;
context.gr_down_projection_bf16_f32(dw, xn, down)?;
context.gr_down_silu_hc_f32(down, activated)?;
context.gr_up_projection_bf16_f32(uw, activated, gates)?;
context.gr_gate_mean_layer_fused_f32(xn, gates, products, mixed)?;
context.gr_read_finite_mask([xn, down, activated, gates, products])
}
}
fn read_outputs(outputs: &[DeviceBuffer<'_>; 6]) -> Result<Vec<Vec<u8>>> {
outputs
.iter()
.map(|buffer| {
let mut bytes = vec![0; buffer.bytes];
buffer.copy_to(&mut bytes)?;
Ok(bytes)
})
.collect()
}
fn residual_bytes(pattern: usize) -> Vec<u8> {
(0..10240usize)
.flat_map(|i| {
let x = if pattern == 0 {
if i % 2 == 0 { 0.0f32 } else { -0.0f32 }
} else {
((i % 37) as f32 - 18.0) / 32.0
};
x.to_le_bytes()
})
.collect()
}
#[test]
#[ignore = "Root-only new same-kernel queued GR completion boundary"]
fn original_first_queued_gr_read_exact_and_status_reset() {
assert_eq!(
std::env::var("LELEKA_STRA169_RUN_QUEUED_GR").as_deref(),
Ok("yes")
);
let driver = Driver::load().expect("installed driver");
let device = driver.device(0).expect("device");
let context = device
.create_context(32 * 1024 * 1024)
.expect("bounded context");
let result: Result<(u64, u32)> = (|| {
let mut inputs = [
context.allocate(40960)?,
context.allocate(40960)?,
context.allocate(6553600)?,
context.allocate(6553600)?,
];
let mut outputs = [
context.allocate(40960)?,
context.allocate(1280)?,
context.allocate(1280)?,
context.allocate(40960)?,
context.allocate(40960)?,
context.allocate(10240)?,
];
let operation: Result<(u64, u32)> = (|| {
inputs[1].copy_from(
&(0..10240usize)
.flat_map(|i| (1.0f32 + (i % 7) as f32 / 16.0).to_le_bytes())
.collect::<Vec<_>>(),
)?;
// Sanitized exact BF16 powers and sign bits, independent of
// candidate outputs. Original admitted kernels are the oracle.
for (role, weight) in inputs[2..].iter_mut().enumerate() {
let bytes: Vec<_> = (0..3276800usize)
.flat_map(|i| {
let bits = if (i + role) % 3 == 0 {
0x3b00u16
} else {
0xbb00u16
};
bits.to_le_bytes()
})
.collect();
weight.copy_from(&bytes)?;
}
let mut mismatches = 0u64;
let mut guards = 0u32;
let mut reset_expected = None;
for pattern in 0..2 {
inputs[0].copy_from(&residual_bytes(pattern))?;
let original_mask = execute_read(&context, &inputs, &mut outputs, false, 1e-6)?;
let expected = read_outputs(&outputs)?;
let candidate_mask = execute_read(&context, &inputs, &mut outputs, true, 1e-6)?;
let actual = read_outputs(&outputs)?;
if original_mask != 0 || candidate_mask != original_mask {
mismatches += 1;
}
for (x, y) in expected.iter().zip(&actual) {
mismatches += x
.chunks_exact(4)
.zip(y.chunks_exact(4))
.filter(|(a, b)| a != b)
.count() as u64;
}
if pattern == 1 {
reset_expected = Some(expected);
}
}
let before = read_outputs(&outputs)?;
if execute_read(&context, &inputs, &mut outputs, true, -1.0)
!= Err(Error::InvalidQwenShape)
{
mismatches += 1;
}
if read_outputs(&outputs)? != before {
mismatches += 1;
}
guards += 1;
// Full-state late NaN: compare actual original finite mask,
// then prove dedicated status reset by a valid recovery.
let mut invalid = residual_bytes(1);
invalid[40956..].copy_from_slice(&f32::NAN.to_le_bytes());
inputs[0].copy_from(&invalid)?;
let old = execute_read(&context, &inputs, &mut outputs, false, 1e-6)?;
let queued = execute_read(&context, &inputs, &mut outputs, true, 1e-6)?;
if old == 0 || old != queued {
mismatches += 1;
}
guards += 1;
inputs[0].copy_from(&residual_bytes(1))?;
if execute_read(&context, &inputs, &mut outputs, true, 1e-6)? != 0
|| read_outputs(&outputs)? != reset_expected.ok_or(Error::InvalidQwenShape)?
{
mismatches += 1;
}
guards += 1;
if outputs.iter().map(|b| b.bytes).ne(OUTPUT_BYTES) {
mismatches += 1;
}
Ok((mismatches, guards))
})();
// Attempt every owned release even after any primary refusal.
let mut cleanup = Ok(());
for buffer in outputs.into_iter().chain(inputs) {
cleanup = combine(cleanup, buffer.release());
}
combine(operation, cleanup)
})();
let allocated = context.allocated_bytes();
let result = combine(result, context.close());
let (mismatches, guards) = result.expect("completed new boundary with exhaustive cleanup");
assert_eq!(allocated, 0);
assert_eq!(mismatches, 0);
assert_eq!(guards, 3);
eprintln!(
"QUEUED_GR PASS exact_words=67840 old_first=true all6_outputs=true status_reset=true guards={guards} allocated0=true"
);
}
File diff suppressed because it is too large Load Diff
+1 -821
View File
@@ -822,827 +822,7 @@ pub(super) struct Arguments {
drop_observer: Option<std::rc::Rc<std::cell::Cell<usize>>>,
}
#[cfg(test)]
mod tests {
#[test]
fn full_s2_expert_scalar_and_fixed_bank_abi() {
for (operation, q, scales, out, name) in [
(
Operation::MtpS2GateUpFull,
2720,
320,
5120,
c"leleka_mtp_s2_gate_up_full",
),
(
Operation::MtpS2DownFull,
680,
80,
10240,
c"leleka_mtp_s2_down_full",
),
] {
for expert in [0, 257, 511] {
let layout = mtp_s2_full_layout(operation, expert).unwrap();
assert_eq!(layout.bytes[..4], [707_788_800, q, scales, out]);
assert_eq!(layout.align[..4], [8, 4, 4, 4]);
assert_eq!(
(layout.count, layout.outputs, layout.grid, layout.block),
(4, 8, 40, 256)
);
assert_eq!(
(layout.grid_y, layout.grid_z, layout.shared_bytes),
(1, 1, 0)
);
assert_eq!(layout.integer, Some((expert, 1)));
assert_eq!(operation.entry(), name);
let handles = [11, 22, 33, 44, 0, 0, 0, 0, 0].map(ffi::BufferHandle::synthetic);
let mut args = Arguments::with_layout(operation, layout, handles, 0.0);
let table = args.parameters();
// SAFETY: these initialized raw-owned scalar fields are live;
// the pointer table is inspected only before driver execution.
unsafe {
assert_eq!(*(*table).cast::<u64>(), 11);
assert_eq!(*(*table.add(1)).cast::<u32>(), expert);
for (i, value) in [22u64, 33, 44].into_iter().enumerate() {
assert_eq!(*(*table.add(i + 2)).cast::<u64>(), value);
}
assert!((*table.add(5)).is_null());
}
}
for expert in [512, u32::MAX] {
assert!(matches!(
mtp_s2_full_layout(operation, expert),
Err(Error::InvalidQwenShape)
));
}
}
}
#[test]
fn mtp_new_nine_pointer_owner_and_scaled_packets() {
for (operation, count) in [
(Operation::MtpGrMlpDown, 9),
(Operation::MtpGrMlpUp, 9),
(Operation::MtpS2GateUp, 5),
(Operation::MtpQuant2560, 3),
(Operation::MtpQuant640, 3),
] {
let asset = asset(operation).unwrap();
asset.validate(operation).unwrap();
let layout = operation.layout();
assert_eq!(layout.count, count);
let handles =
std::array::from_fn(|i| ffi::BufferHandle::synthetic((i as u64 + 1) * 0x1000000));
let owner = Arguments::with_layout(operation, layout, handles, 0.0);
let mut moved = std::hint::black_box(vec![owner]).pop().unwrap();
let table = moved.parameters();
// SAFETY: every pointer belongs to the same live, immovable storage.
unsafe {
for (i, handle) in handles.iter().enumerate().take(count) {
assert_eq!(*(*table.add(i)).cast::<u64>(), handle.qwen_address());
}
assert!((*table.add(count)).is_null());
}
}
assert_eq!(
&Operation::MtpQuant2560.layout().bytes[..3],
&[10240, 2720, 320]
);
assert_eq!(
&Operation::MtpQuant640.layout().bytes[..3],
&[2560, 680, 80]
);
assert_eq!(Operation::MtpGrMlpDown.layout().outputs, 0b111000000);
assert_eq!(Operation::MtpGrMlpUp.layout().outputs, 0b110000000);
}
use super::*;
#[test]
fn gr_saturation_asset_requires_exact_independent_qualification_and_bytes() {
assert_eq!(
sha256(include_bytes!("offline_gr_kernel.cu")),
GR_RECEIPT.source_sha256
);
for operation in [
Operation::Norm,
Operation::DownSilu,
Operation::LayerGate,
Operation::FinalGate,
Operation::InjectResidual,
] {
let admitted = asset(operation).expect("independently reviewed GR asset");
assert_eq!(admitted.validate(operation), Ok(()));
assert_eq!(admitted.receipt, GR_RECEIPT);
let mut bad = GR_RECEIPT;
bad.ptx_sha256[0] ^= 1;
let corrupted = Asset {
operation,
ptx: admitted.ptx,
receipt: bad,
pin: bad,
};
assert_eq!(
corrupted.validate(operation),
Err(Error::UnsupportedQwenOperation)
);
}
}
#[test]
fn kar_ple_qualified_receipt_matches_frozen_source_and_ptx() {
assert_eq!(
sha256(include_bytes!("offline_kar_ple_kernel.cu")),
KAR_PLE_RECEIPT.source_sha256
);
assert_eq!(
sha256(include_bytes!("kar_ple_fixed.ptx")),
KAR_PLE_RECEIPT.ptx_sha256
);
assert_eq!(
KAR_PLE_RECEIPT.qualification_receipt,
"STRA161 SDET7ca247af-161d-4215-9128-f4ba19018b7b; GPUbb8d133b-2286-4b59-8ab0-876c2ca03321; DEV2df2eb3d-7d75-43a4-8019-7583921daf0d"
);
for op in [Operation::KarPleScatter, Operation::KarPleDecode] {
let admitted = asset(op).unwrap();
assert_eq!(admitted.receipt, KAR_PLE_RECEIPT);
admitted.validate(op).unwrap();
assert!(
std::str::from_utf8(admitted.ptx)
.unwrap()
.contains(op.entry().to_str().unwrap())
);
}
}
#[test]
fn kar_ple_fixed_abi_and_boundary_refusals() {
for (op, value, entry, bytes, align, outputs, grid, block, scalar_index) in [
(
Operation::KarPleScatter,
16,
c"leleka_kar_ple_scatter",
vec![67_108_864, 896],
vec![1, 4],
1,
16,
64,
2,
),
(
Operation::KarPleDecode,
65_535,
c"leleka_kar_ple_decode",
vec![67_108_864, 64, 524_280, 10_240],
vec![1, 4, 2, 4],
8,
16,
256,
4,
),
] {
let layout = kar_ple_layout(op, value).unwrap();
assert_eq!(op.entry(), entry);
assert_eq!(&layout.bytes[..layout.count], bytes);
assert_eq!(&layout.align[..layout.count], align);
assert_eq!(
(layout.outputs, layout.grid, layout.block),
(outputs, grid, block)
);
assert_eq!(
(
layout.grid_y,
layout.grid_z,
layout.block_y,
layout.shared_bytes
),
(1, 1, 1, 0)
);
assert_eq!(layout.integer, Some((value, scalar_index)));
asset(op)
.expect("qualified fixed KAR entry")
.validate(op)
.unwrap();
let addresses = [101u64, 202, 303, 404, 505, 606, 707, 808, 0];
let args = Arguments::with_layout(
op,
layout,
addresses.map(ffi::BufferHandle::synthetic),
0.0,
);
let mut moved = std::hint::black_box(args);
let table = moved.parameters();
// SAFETY: the private raw-owned table is live, and this frozen ABI
// contains exactly its buffer addresses followed by one u32.
unsafe {
for (i, address) in addresses.iter().enumerate().take(layout.count) {
assert_eq!(*(*table.add(i)).cast::<u64>(), *address);
}
assert_eq!(*(*table.add(scalar_index)).cast::<u32>(), value);
assert!((*table.add(scalar_index + 1)).is_null());
}
}
for (op, maximum) in [
(Operation::KarPleScatter, 16),
(Operation::KarPleDecode, 65_535),
] {
assert!(kar_ple_layout(op, 1).is_ok());
assert!(kar_ple_layout(op, maximum).is_ok());
for invalid in [0, maximum + 1, u32::MAX] {
assert!(matches!(
kar_ple_layout(op, invalid),
Err(Error::InvalidQwenShape)
));
}
}
assert!(matches!(
kar_ple_layout(Operation::Norm, 1),
Err(Error::InvalidQwenShape)
));
}
#[test]
fn qsa_new_literal_abi_scalar_order_and_geometry() {
// Independently frozen producer ABI, STRA-172 AD10; no candidate PTX.
for (operation, entry, bytes, outputs, grid, grid_y, shared, index) in [
(
Operation::QsaSplit,
c"leleka_qsa_split_q_gate",
vec![49152, 24576, 24576],
6,
24,
1,
0,
None,
),
(
Operation::QsaNormQ,
c"leleka_qsa_norm_q",
vec![24576, 1024, 24576],
4,
24,
1,
0,
None,
),
(
Operation::QsaNormK,
c"leleka_qsa_norm_k",
vec![2048, 1024, 2048],
4,
2,
1,
0,
None,
),
(
Operation::QsaNormIndexQ,
c"leleka_qsa_norm_index_q",
vec![2048, 512, 2048],
4,
4,
1,
0,
None,
),
(
Operation::QsaRopeQ,
c"leleka_qsa_rope_q",
vec![24576, 24576],
2,
1,
24,
0,
Some(1),
),
(
Operation::QsaRopeK,
c"leleka_qsa_rope_k",
vec![2048, 2048],
2,
1,
2,
0,
Some(1),
),
(
Operation::QsaRopeIndexQ,
c"leleka_qsa_rope_index_q",
vec![2048, 2048],
2,
1,
4,
0,
Some(1),
),
(
Operation::QsaIndexAppend,
c"leleka_qsa_index_append",
vec![512, 512, 2048, 2560],
8,
1,
1,
0,
Some(4),
),
(
Operation::QsaPackKv,
c"leleka_qsa_pack_kv",
vec![2048, 2048, 1024, 1024],
12,
2,
1,
0,
None,
),
(
Operation::QsaBlockScores,
c"leleka_qsa_block_scores",
vec![1024, 512, 2048, 8],
8,
256,
1,
0,
Some(4),
),
(
Operation::QsaBlockTopk,
c"leleka_qsa_block_topk",
vec![8, 8204],
2,
1,
1,
0,
Some(2),
),
(
Operation::QsaAttend,
c"leleka_qsa_attend",
vec![24576, 3072, 3072, 24576],
8,
24,
1,
8332,
Some(4),
),
(
Operation::QsaGate,
c"leleka_qsa_gate_f32",
vec![24576, 24576, 24576],
4,
24,
1,
0,
None,
),
] {
let layout = qsa_layout(operation, 3).unwrap();
assert_eq!(operation.entry(), entry);
assert_eq!(&layout.bytes[..layout.count], bytes);
assert_eq!(
(
layout.outputs,
layout.grid,
layout.grid_y,
layout.grid_z,
layout.block,
layout.block_y,
layout.shared_bytes
),
(outputs, grid, grid_y, 1, 256, 1, shared)
);
assert_eq!(layout.integer, index.map(|i| (3, i)));
asset(operation)
.expect("qualified fixed QSA asset")
.validate(operation)
.unwrap();
let addresses = [101, 202, 303, 404, 505, 606, 707, 808, 0];
let handles = addresses.map(ffi::BufferHandle::synthetic);
let arguments = Arguments::with_layout(operation, layout, handles, 0.0);
// Move the raw allocation owner, then read its initialized fields;
// no Box ownership/reborrow is introduced after pointer formation.
let mut moved = std::hint::black_box(arguments);
let table = moved.parameters();
// SAFETY: table points into one live raw-owned allocation, exact
// parameter types/order are the independent frozen ABI above.
unsafe {
for (i, address) in addresses.iter().take(bytes.len()).enumerate() {
let slot = i + usize::from(index.is_some_and(|j| j <= i));
assert_eq!(*(*table.add(slot)).cast::<u64>(), *address);
}
if let Some(i) = index {
assert_eq!(*(*table.add(i)).cast::<u32>(), 3);
}
assert!((*table.add(bytes.len() + usize::from(index.is_some()))).is_null());
}
for (i, alignment) in layout.align.iter().take(layout.count).enumerate() {
let packed = (operation == Operation::QsaPackKv && i >= 2)
|| (operation == Operation::QsaAttend && (i == 1 || i == 2));
assert_eq!(*alignment, if packed { 2 } else { 4 });
}
}
assert_eq!(OPERATIONS.len(), 58);
for operation in OPERATIONS.into_iter().filter(|op| {
!QSA_OPERATIONS.contains(op)
&& !matches!(
op,
Operation::KarPleScatter
| Operation::KarPleDecode
| Operation::MtpDenseChunk
| Operation::MtpDenseMerge
| Operation::MtpS2GateUpFull
| Operation::MtpS2DownFull
)
}) {
let old = operation.layout();
assert_eq!((old.grid_y, old.shared_bytes, old.integer), (1, 0, None));
}
}
#[test]
fn qsa_new_position_block_boundaries_and_attention_width_refusals() {
// Literal causal/block boundaries, including one past the context.
for (position, pooled, scores) in [
(0, 512, 4),
(2, 512, 4),
(3, 1024, 8),
(4, 1024, 8),
(2047, 262656, 2052),
(262143, 33554944, 262148),
// the lifted context ceiling: 131073 pooled rows of 512 bytes, 4 score bytes each
(262144, 33554944, 262148),
(524287, 67109376, 524292),
] {
let score = qsa_layout(Operation::QsaBlockScores, position).unwrap();
assert_eq!((score.bytes[0], score.bytes[3]), (pooled, scores));
let ids = qsa_layout(Operation::QsaBlockTopk, position).unwrap();
assert_eq!((ids.bytes[0], ids.bytes[1]), (scores, 8204));
assert_eq!(score.integer, Some((position, 4)));
}
for operation in QSA_OPERATIONS
.into_iter()
.filter(|op| *op != Operation::QsaAttend)
{
assert!(qsa_layout(operation, 262143).is_ok());
assert!(qsa_layout(operation, 262144).is_ok());
assert!(qsa_layout(operation, crate::MAX_CONTEXT_CELLS as u32 - 1).is_ok());
for position in [crate::MAX_CONTEXT_CELLS as u32, u32::MAX] {
assert!(matches!(
qsa_layout(operation, position),
Err(Error::InvalidQwenShape)
));
}
}
for (width, extent) in [(1, 1024), (2051, 2100224)] {
let layout = qsa_layout(Operation::QsaAttend, width).unwrap();
assert_eq!((layout.bytes[1], layout.bytes[2]), (extent, extent));
assert_eq!(layout.integer, Some((width, 4)));
}
for width in [0, 2052, u32::MAX] {
assert!(matches!(
qsa_layout(Operation::QsaAttend, width),
Err(Error::InvalidQwenShape)
));
}
assert!(matches!(
qsa_layout(Operation::Norm, 0),
Err(Error::InvalidQwenShape)
));
}
#[test]
fn moe_fixed_pointer_abi_extents_and_qualified_receipts() {
// Literal expectations come from STRA-167 AD v1 / STRA-172 AD v8.
for (operation, entry, bytes, align, count, outputs, grid) in [
(
Operation::MoeSwiglu,
c"leleka_moe_swiglu_f32",
[2560, 2560, 2560, 0],
[4, 4, 4, 4],
3,
4,
3,
),
(
Operation::MoeSharedScalar,
c"leleka_moe_shared_gate_f32_bf16",
[10240, 5120, 4, 0],
[4, 2, 4, 4],
3,
4,
1,
),
(
Operation::MoeSharedScale,
c"leleka_moe_scale_shared_f32",
[10240, 4, 10240, 0],
[4, 4, 4, 4],
3,
4,
10,
),
(
Operation::MoeCombine,
c"leleka_moe_combine_f32",
[102400, 40, 10240, 10240],
[4, 4, 4, 4],
4,
8,
10,
),
] {
let layout = operation.layout();
assert_eq!(operation.entry(), entry);
assert_eq!(layout.bytes[..4], bytes);
assert_eq!(layout.align[..4], align);
assert_eq!((layout.count, layout.outputs), (count, outputs));
assert_eq!(
(layout.grid, layout.grid_z, layout.block, layout.block_y),
(grid, 1, 256, 1)
);
assert!(!layout.projection);
assert!(!operation.has_epsilon());
let qualified = asset(operation).expect("frozen167 qualified component");
qualified.validate(operation).unwrap();
assert_eq!(qualified.receipt, MOE_RECEIPT);
let handles =
[101, 202, 303, 404, 505, 606, 707, 808, 0].map(ffi::BufferHandle::synthetic);
let mut arguments = Arguments::new(operation, handles, 0.0);
let parameters = arguments.parameters();
// SAFETY: inspect only live initialized pointer-table fields.
unsafe {
for (index, expected) in [101u64, 202, 303, 404].iter().take(count).enumerate() {
assert_eq!(*(*parameters.add(index)).cast::<u64>(), *expected);
}
assert!((*parameters.add(count)).is_null());
}
}
assert_eq!(OPERATIONS.len(), 58);
}
#[test]
fn qwen_hash_known_vectors_and_padding_boundaries() {
let hex = |bytes: &[u8]| {
sha256(bytes)
.iter()
.map(|b| format!("{b:02x}"))
.collect::<String>()
};
assert_eq!(
hex(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
assert_eq!(
hex(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(
hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
);
}
#[test]
fn qwen_raw_abi_remains_stable_after_moves() {
for op in OPERATIONS {
let handles = [11, 22, 33, 44, 55, 66, 77, 88, 0].map(ffi::BufferHandle::synthetic);
let args = Arguments::new(op, handles, 1e-6);
let pointer = args.storage.as_ptr();
let mut moved = vec![args].pop().unwrap();
let churn: Vec<_> = (0..64).map(|_| Box::new([0xdeadu64; 16])).collect();
std::hint::black_box(churn);
assert_eq!(pointer, moved.storage.as_ptr());
let layout = op.layout();
let table = moved.parameters();
// SAFETY: read exactly the live owner's initialized scalar fields;
// private ABI pointer table is valid across the owner moves above.
unsafe {
for (i, expected) in [11u64, 22, 33, 44, 55, 66, 77, 88, 0]
.iter()
.enumerate()
.take(layout.count)
{
let slot = i + usize::from(layout.integer.is_some_and(|(_, index)| index <= i));
assert_eq!(*(*table.add(slot)).cast::<u64>(), *expected);
}
if let Some((value, index)) = layout.integer {
assert_eq!(*(*table.add(index)).cast::<u32>(), value);
}
if op == Operation::MtpDenseChunk {
assert_eq!(*(*table.add(6)).cast::<u32>(), layout.rows);
assert_eq!(*(*table.add(7)).cast::<u32>(), layout.columns);
} else if layout.projection {
assert_eq!(*(*table.add(3)).cast::<u32>(), layout.rows);
assert_eq!(*(*table.add(4)).cast::<u32>(), layout.columns);
} else if op.has_epsilon() {
assert_eq!(
(*(*table.add(layout.count)).cast::<f32>()).to_bits(),
1e-6f32.to_bits()
);
}
}
}
}
#[test]
fn qwen_router_has_exact_three_pointer_abi_and_32_by_8_geometry() {
let op = Operation::RouteTop10;
let layout = op.layout();
assert_eq!(op.entry(), c"leleka_moe_route_top10");
assert_eq!(layout.bytes, [2048, 40, 40, 0, 0, 0, 0, 0, 0]);
assert_eq!((layout.grid, layout.block, layout.block_y), (1, 32, 8));
assert_eq!(layout.count, 3);
assert!(!layout.projection);
let mut args = Arguments::new(
op,
[11, 22, 33, 44, 55, 66, 77, 88, 0].map(ffi::BufferHandle::synthetic),
0.0,
);
let parameters = args.parameters();
// SAFETY: read the initialized private table while its owner is live.
// The exact router ABI has no hidden scalar/status/count arguments.
unsafe {
assert!((*parameters.add(3)).is_null());
assert!((*parameters.add(4)).is_null());
}
let admitted = asset(op).expect("independently qualified router component");
assert_eq!(admitted.validate(op), Ok(()));
assert_eq!(
admitted.receipt.qualification_receipt,
"STRA-166 b31a40ef-50b1-4ece-8d9d-1467c1feb388"
);
}
#[test]
fn qwen_ple_fixed_geometry_has_pointer_only_abi_and_exact_component_receipt() {
// Expectations are the independently frozen STRA-161/172 contract.
for (op, entry, bytes, outputs, grid) in [
(
Operation::PleValue,
c"leleka_ple_value_bf16_f32",
vec![10240, 327680, 256],
4,
1,
),
(
Operation::PleNorm,
c"leleka_ple_grouped_norm_f32",
vec![40960, 40960, 40960],
4,
4,
),
(
Operation::PleGate,
c"leleka_ple_signed_gate_f32",
vec![40960, 40960, 16],
4,
4,
),
(
Operation::PleBroadcast,
c"leleka_ple_broadcast_f32",
vec![10240, 16, 40960],
4,
40,
),
(
Operation::PleConv,
c"leleka_ple_conv_history_f32",
vec![368640, 40960, 81920, 40960, 368640],
24,
40,
),
(
Operation::PleResidual,
c"leleka_ple_residual_f32",
vec![40960, 40960, 40960, 40960],
8,
40,
),
] {
let layout = op.layout();
assert_eq!(op.entry(), entry);
assert_eq!(layout.count, bytes.len());
assert_eq!(layout.bytes[..layout.count], bytes);
assert!(layout.bytes[layout.count..].iter().all(|b| *b == 0));
assert_eq!(layout.outputs, outputs);
assert_eq!(
(layout.grid, layout.grid_z, layout.block, layout.block_y),
(grid, 1, 256, 1)
);
assert!(!layout.projection && !op.has_epsilon());
for i in 0..layout.count {
let expected = if (op == Operation::PleValue && i == 1)
|| (op == Operation::PleConv && i == 2)
{
2
} else {
4
};
assert_eq!(layout.align[i], expected);
}
let mut args = Arguments::new(
op,
[11, 22, 33, 44, 55, 66, 77, 88, 0].map(ffi::BufferHandle::synthetic),
0.0,
);
let pointers = args.parameters();
// SAFETY: table storage belongs to live args. These fixed entries
// have no scalar or hidden shape arguments after their pointers.
unsafe {
for i in layout.count..9 {
assert!((*pointers.add(i)).is_null());
}
}
let admitted = asset(op).expect("independently reviewed PLE component");
assert_eq!(admitted.validate(op), Ok(()));
assert_eq!(
admitted.receipt.qualification_receipt,
"STRA-161 ada1a470-76ad-47af-a326-e388ae592d51"
);
// A self-consistent forged pin still cannot admit different bytes.
let mut bad = admitted.receipt;
bad.ptx_sha256[0] ^= 1;
let corrupt = Asset {
operation: op,
ptx: admitted.ptx,
receipt: bad,
pin: bad,
};
assert_eq!(corrupt.validate(op), Err(Error::UnsupportedQwenOperation));
}
}
#[test]
fn mtp_new_qualified_assets_and_fixed_dense_scalar_abi() {
for operation in [
Operation::MtpEmbeddingNorm,
Operation::MtpHiddenNorm,
Operation::MtpBroadcast,
Operation::MtpDenseChunk,
Operation::MtpDenseMerge,
] {
let asset = asset(operation).unwrap();
asset.validate(operation).unwrap();
// A caller who modifies both the metadata and its duplicate pin
// still cannot admit different executable bytes.
let mut forged = Asset {
operation,
ptx: asset.ptx,
receipt: asset.receipt,
pin: asset.pin,
};
forged.receipt.ptx_sha256[0] ^= 1;
forged.pin = forged.receipt;
assert_eq!(
forged.validate(operation),
Err(Error::UnsupportedQwenOperation)
);
}
for (position, width, chunks) in [
(0, 1, 1),
(63, 64, 1),
(64, 65, 2),
(32767, 32768, 512),
(262143, 32768, 512),
] {
let layout = mtp_dense_layout(Operation::MtpDenseChunk, position).unwrap();
assert_eq!(
(layout.rows, layout.columns, layout.grid, layout.grid_y),
(width, chunks, chunks, 2)
);
assert_eq!(
(layout.bytes[1], layout.bytes[3], layout.bytes[4]),
(
width as usize * 1024,
chunks as usize * 24576,
chunks as usize * 96
)
);
let handles = [11, 22, 33, 44, 55, 66, 77, 88, 0].map(ffi::BufferHandle::synthetic);
let owner = Arguments::with_layout(Operation::MtpDenseChunk, layout, handles, 0.0);
let mut moved = std::hint::black_box(vec![owner]).pop().unwrap();
let table = moved.parameters();
// SAFETY: exact initialized fields in one live stable ABI owner.
unsafe {
for (i, address) in [11u64, 22, 33, 44, 55, 66].iter().enumerate() {
assert_eq!(*(*table.add(i)).cast::<u64>(), *address);
}
assert_eq!(*(*table.add(6)).cast::<u32>(), width);
assert_eq!(*(*table.add(7)).cast::<u32>(), chunks);
assert!((*table.add(8)).is_null());
}
let merge = mtp_dense_layout(Operation::MtpDenseMerge, position).unwrap();
assert_eq!(merge.integer, Some((chunks, 4)));
assert_eq!((merge.grid, merge.block, merge.outputs), (24, 256, 8));
}
for position in [crate::MAX_CONTEXT_CELLS as u32, u32::MAX] {
assert_eq!(
mtp_dense_layout(Operation::MtpDenseChunk, position).err(),
Some(Error::InvalidQwenShape)
);
}
assert_eq!(
mtp_dense_layout(Operation::Norm, 0).err(),
Some(Error::InvalidQwenShape)
);
}
}
mod tests;
mod impl_operation;
mod mtp_s2_full_layout_fn;
+821
View File
@@ -0,0 +1,821 @@
//! Moved out of the parent file by STRA-338 (same module path as before).
#[test]
fn full_s2_expert_scalar_and_fixed_bank_abi() {
for (operation, q, scales, out, name) in [
(
Operation::MtpS2GateUpFull,
2720,
320,
5120,
c"leleka_mtp_s2_gate_up_full",
),
(
Operation::MtpS2DownFull,
680,
80,
10240,
c"leleka_mtp_s2_down_full",
),
] {
for expert in [0, 257, 511] {
let layout = mtp_s2_full_layout(operation, expert).unwrap();
assert_eq!(layout.bytes[..4], [707_788_800, q, scales, out]);
assert_eq!(layout.align[..4], [8, 4, 4, 4]);
assert_eq!(
(layout.count, layout.outputs, layout.grid, layout.block),
(4, 8, 40, 256)
);
assert_eq!(
(layout.grid_y, layout.grid_z, layout.shared_bytes),
(1, 1, 0)
);
assert_eq!(layout.integer, Some((expert, 1)));
assert_eq!(operation.entry(), name);
let handles = [11, 22, 33, 44, 0, 0, 0, 0, 0].map(ffi::BufferHandle::synthetic);
let mut args = Arguments::with_layout(operation, layout, handles, 0.0);
let table = args.parameters();
// SAFETY: these initialized raw-owned scalar fields are live;
// the pointer table is inspected only before driver execution.
unsafe {
assert_eq!(*(*table).cast::<u64>(), 11);
assert_eq!(*(*table.add(1)).cast::<u32>(), expert);
for (i, value) in [22u64, 33, 44].into_iter().enumerate() {
assert_eq!(*(*table.add(i + 2)).cast::<u64>(), value);
}
assert!((*table.add(5)).is_null());
}
}
for expert in [512, u32::MAX] {
assert!(matches!(
mtp_s2_full_layout(operation, expert),
Err(Error::InvalidQwenShape)
));
}
}
}
#[test]
fn mtp_new_nine_pointer_owner_and_scaled_packets() {
for (operation, count) in [
(Operation::MtpGrMlpDown, 9),
(Operation::MtpGrMlpUp, 9),
(Operation::MtpS2GateUp, 5),
(Operation::MtpQuant2560, 3),
(Operation::MtpQuant640, 3),
] {
let asset = asset(operation).unwrap();
asset.validate(operation).unwrap();
let layout = operation.layout();
assert_eq!(layout.count, count);
let handles =
std::array::from_fn(|i| ffi::BufferHandle::synthetic((i as u64 + 1) * 0x1000000));
let owner = Arguments::with_layout(operation, layout, handles, 0.0);
let mut moved = std::hint::black_box(vec![owner]).pop().unwrap();
let table = moved.parameters();
// SAFETY: every pointer belongs to the same live, immovable storage.
unsafe {
for (i, handle) in handles.iter().enumerate().take(count) {
assert_eq!(*(*table.add(i)).cast::<u64>(), handle.qwen_address());
}
assert!((*table.add(count)).is_null());
}
}
assert_eq!(
&Operation::MtpQuant2560.layout().bytes[..3],
&[10240, 2720, 320]
);
assert_eq!(
&Operation::MtpQuant640.layout().bytes[..3],
&[2560, 680, 80]
);
assert_eq!(Operation::MtpGrMlpDown.layout().outputs, 0b111000000);
assert_eq!(Operation::MtpGrMlpUp.layout().outputs, 0b110000000);
}
use super::*;
#[test]
fn gr_saturation_asset_requires_exact_independent_qualification_and_bytes() {
assert_eq!(
sha256(include_bytes!("../offline_gr_kernel.cu")),
GR_RECEIPT.source_sha256
);
for operation in [
Operation::Norm,
Operation::DownSilu,
Operation::LayerGate,
Operation::FinalGate,
Operation::InjectResidual,
] {
let admitted = asset(operation).expect("independently reviewed GR asset");
assert_eq!(admitted.validate(operation), Ok(()));
assert_eq!(admitted.receipt, GR_RECEIPT);
let mut bad = GR_RECEIPT;
bad.ptx_sha256[0] ^= 1;
let corrupted = Asset {
operation,
ptx: admitted.ptx,
receipt: bad,
pin: bad,
};
assert_eq!(
corrupted.validate(operation),
Err(Error::UnsupportedQwenOperation)
);
}
}
#[test]
fn kar_ple_qualified_receipt_matches_frozen_source_and_ptx() {
assert_eq!(
sha256(include_bytes!("../offline_kar_ple_kernel.cu")),
KAR_PLE_RECEIPT.source_sha256
);
assert_eq!(
sha256(include_bytes!("../kar_ple_fixed.ptx")),
KAR_PLE_RECEIPT.ptx_sha256
);
assert_eq!(
KAR_PLE_RECEIPT.qualification_receipt,
"STRA161 SDET7ca247af-161d-4215-9128-f4ba19018b7b; GPUbb8d133b-2286-4b59-8ab0-876c2ca03321; DEV2df2eb3d-7d75-43a4-8019-7583921daf0d"
);
for op in [Operation::KarPleScatter, Operation::KarPleDecode] {
let admitted = asset(op).unwrap();
assert_eq!(admitted.receipt, KAR_PLE_RECEIPT);
admitted.validate(op).unwrap();
assert!(
std::str::from_utf8(admitted.ptx)
.unwrap()
.contains(op.entry().to_str().unwrap())
);
}
}
#[test]
fn kar_ple_fixed_abi_and_boundary_refusals() {
for (op, value, entry, bytes, align, outputs, grid, block, scalar_index) in [
(
Operation::KarPleScatter,
16,
c"leleka_kar_ple_scatter",
vec![67_108_864, 896],
vec![1, 4],
1,
16,
64,
2,
),
(
Operation::KarPleDecode,
65_535,
c"leleka_kar_ple_decode",
vec![67_108_864, 64, 524_280, 10_240],
vec![1, 4, 2, 4],
8,
16,
256,
4,
),
] {
let layout = kar_ple_layout(op, value).unwrap();
assert_eq!(op.entry(), entry);
assert_eq!(&layout.bytes[..layout.count], bytes);
assert_eq!(&layout.align[..layout.count], align);
assert_eq!(
(layout.outputs, layout.grid, layout.block),
(outputs, grid, block)
);
assert_eq!(
(
layout.grid_y,
layout.grid_z,
layout.block_y,
layout.shared_bytes
),
(1, 1, 1, 0)
);
assert_eq!(layout.integer, Some((value, scalar_index)));
asset(op)
.expect("qualified fixed KAR entry")
.validate(op)
.unwrap();
let addresses = [101u64, 202, 303, 404, 505, 606, 707, 808, 0];
let args = Arguments::with_layout(
op,
layout,
addresses.map(ffi::BufferHandle::synthetic),
0.0,
);
let mut moved = std::hint::black_box(args);
let table = moved.parameters();
// SAFETY: the private raw-owned table is live, and this frozen ABI
// contains exactly its buffer addresses followed by one u32.
unsafe {
for (i, address) in addresses.iter().enumerate().take(layout.count) {
assert_eq!(*(*table.add(i)).cast::<u64>(), *address);
}
assert_eq!(*(*table.add(scalar_index)).cast::<u32>(), value);
assert!((*table.add(scalar_index + 1)).is_null());
}
}
for (op, maximum) in [
(Operation::KarPleScatter, 16),
(Operation::KarPleDecode, 65_535),
] {
assert!(kar_ple_layout(op, 1).is_ok());
assert!(kar_ple_layout(op, maximum).is_ok());
for invalid in [0, maximum + 1, u32::MAX] {
assert!(matches!(
kar_ple_layout(op, invalid),
Err(Error::InvalidQwenShape)
));
}
}
assert!(matches!(
kar_ple_layout(Operation::Norm, 1),
Err(Error::InvalidQwenShape)
));
}
#[test]
fn qsa_new_literal_abi_scalar_order_and_geometry() {
// Independently frozen producer ABI, STRA-172 AD10; no candidate PTX.
for (operation, entry, bytes, outputs, grid, grid_y, shared, index) in [
(
Operation::QsaSplit,
c"leleka_qsa_split_q_gate",
vec![49152, 24576, 24576],
6,
24,
1,
0,
None,
),
(
Operation::QsaNormQ,
c"leleka_qsa_norm_q",
vec![24576, 1024, 24576],
4,
24,
1,
0,
None,
),
(
Operation::QsaNormK,
c"leleka_qsa_norm_k",
vec![2048, 1024, 2048],
4,
2,
1,
0,
None,
),
(
Operation::QsaNormIndexQ,
c"leleka_qsa_norm_index_q",
vec![2048, 512, 2048],
4,
4,
1,
0,
None,
),
(
Operation::QsaRopeQ,
c"leleka_qsa_rope_q",
vec![24576, 24576],
2,
1,
24,
0,
Some(1),
),
(
Operation::QsaRopeK,
c"leleka_qsa_rope_k",
vec![2048, 2048],
2,
1,
2,
0,
Some(1),
),
(
Operation::QsaRopeIndexQ,
c"leleka_qsa_rope_index_q",
vec![2048, 2048],
2,
1,
4,
0,
Some(1),
),
(
Operation::QsaIndexAppend,
c"leleka_qsa_index_append",
vec![512, 512, 2048, 2560],
8,
1,
1,
0,
Some(4),
),
(
Operation::QsaPackKv,
c"leleka_qsa_pack_kv",
vec![2048, 2048, 1024, 1024],
12,
2,
1,
0,
None,
),
(
Operation::QsaBlockScores,
c"leleka_qsa_block_scores",
vec![1024, 512, 2048, 8],
8,
256,
1,
0,
Some(4),
),
(
Operation::QsaBlockTopk,
c"leleka_qsa_block_topk",
vec![8, 8204],
2,
1,
1,
0,
Some(2),
),
(
Operation::QsaAttend,
c"leleka_qsa_attend",
vec![24576, 3072, 3072, 24576],
8,
24,
1,
8332,
Some(4),
),
(
Operation::QsaGate,
c"leleka_qsa_gate_f32",
vec![24576, 24576, 24576],
4,
24,
1,
0,
None,
),
] {
let layout = qsa_layout(operation, 3).unwrap();
assert_eq!(operation.entry(), entry);
assert_eq!(&layout.bytes[..layout.count], bytes);
assert_eq!(
(
layout.outputs,
layout.grid,
layout.grid_y,
layout.grid_z,
layout.block,
layout.block_y,
layout.shared_bytes
),
(outputs, grid, grid_y, 1, 256, 1, shared)
);
assert_eq!(layout.integer, index.map(|i| (3, i)));
asset(operation)
.expect("qualified fixed QSA asset")
.validate(operation)
.unwrap();
let addresses = [101, 202, 303, 404, 505, 606, 707, 808, 0];
let handles = addresses.map(ffi::BufferHandle::synthetic);
let arguments = Arguments::with_layout(operation, layout, handles, 0.0);
// Move the raw allocation owner, then read its initialized fields;
// no Box ownership/reborrow is introduced after pointer formation.
let mut moved = std::hint::black_box(arguments);
let table = moved.parameters();
// SAFETY: table points into one live raw-owned allocation, exact
// parameter types/order are the independent frozen ABI above.
unsafe {
for (i, address) in addresses.iter().take(bytes.len()).enumerate() {
let slot = i + usize::from(index.is_some_and(|j| j <= i));
assert_eq!(*(*table.add(slot)).cast::<u64>(), *address);
}
if let Some(i) = index {
assert_eq!(*(*table.add(i)).cast::<u32>(), 3);
}
assert!((*table.add(bytes.len() + usize::from(index.is_some()))).is_null());
}
for (i, alignment) in layout.align.iter().take(layout.count).enumerate() {
let packed = (operation == Operation::QsaPackKv && i >= 2)
|| (operation == Operation::QsaAttend && (i == 1 || i == 2));
assert_eq!(*alignment, if packed { 2 } else { 4 });
}
}
assert_eq!(OPERATIONS.len(), 58);
for operation in OPERATIONS.into_iter().filter(|op| {
!QSA_OPERATIONS.contains(op)
&& !matches!(
op,
Operation::KarPleScatter
| Operation::KarPleDecode
| Operation::MtpDenseChunk
| Operation::MtpDenseMerge
| Operation::MtpS2GateUpFull
| Operation::MtpS2DownFull
)
}) {
let old = operation.layout();
assert_eq!((old.grid_y, old.shared_bytes, old.integer), (1, 0, None));
}
}
#[test]
fn qsa_new_position_block_boundaries_and_attention_width_refusals() {
// Literal causal/block boundaries, including one past the context.
for (position, pooled, scores) in [
(0, 512, 4),
(2, 512, 4),
(3, 1024, 8),
(4, 1024, 8),
(2047, 262656, 2052),
(262143, 33554944, 262148),
// the lifted context ceiling: 131073 pooled rows of 512 bytes, 4 score bytes each
(262144, 33554944, 262148),
(524287, 67109376, 524292),
] {
let score = qsa_layout(Operation::QsaBlockScores, position).unwrap();
assert_eq!((score.bytes[0], score.bytes[3]), (pooled, scores));
let ids = qsa_layout(Operation::QsaBlockTopk, position).unwrap();
assert_eq!((ids.bytes[0], ids.bytes[1]), (scores, 8204));
assert_eq!(score.integer, Some((position, 4)));
}
for operation in QSA_OPERATIONS
.into_iter()
.filter(|op| *op != Operation::QsaAttend)
{
assert!(qsa_layout(operation, 262143).is_ok());
assert!(qsa_layout(operation, 262144).is_ok());
assert!(qsa_layout(operation, crate::MAX_CONTEXT_CELLS as u32 - 1).is_ok());
for position in [crate::MAX_CONTEXT_CELLS as u32, u32::MAX] {
assert!(matches!(
qsa_layout(operation, position),
Err(Error::InvalidQwenShape)
));
}
}
for (width, extent) in [(1, 1024), (2051, 2100224)] {
let layout = qsa_layout(Operation::QsaAttend, width).unwrap();
assert_eq!((layout.bytes[1], layout.bytes[2]), (extent, extent));
assert_eq!(layout.integer, Some((width, 4)));
}
for width in [0, 2052, u32::MAX] {
assert!(matches!(
qsa_layout(Operation::QsaAttend, width),
Err(Error::InvalidQwenShape)
));
}
assert!(matches!(
qsa_layout(Operation::Norm, 0),
Err(Error::InvalidQwenShape)
));
}
#[test]
fn moe_fixed_pointer_abi_extents_and_qualified_receipts() {
// Literal expectations come from STRA-167 AD v1 / STRA-172 AD v8.
for (operation, entry, bytes, align, count, outputs, grid) in [
(
Operation::MoeSwiglu,
c"leleka_moe_swiglu_f32",
[2560, 2560, 2560, 0],
[4, 4, 4, 4],
3,
4,
3,
),
(
Operation::MoeSharedScalar,
c"leleka_moe_shared_gate_f32_bf16",
[10240, 5120, 4, 0],
[4, 2, 4, 4],
3,
4,
1,
),
(
Operation::MoeSharedScale,
c"leleka_moe_scale_shared_f32",
[10240, 4, 10240, 0],
[4, 4, 4, 4],
3,
4,
10,
),
(
Operation::MoeCombine,
c"leleka_moe_combine_f32",
[102400, 40, 10240, 10240],
[4, 4, 4, 4],
4,
8,
10,
),
] {
let layout = operation.layout();
assert_eq!(operation.entry(), entry);
assert_eq!(layout.bytes[..4], bytes);
assert_eq!(layout.align[..4], align);
assert_eq!((layout.count, layout.outputs), (count, outputs));
assert_eq!(
(layout.grid, layout.grid_z, layout.block, layout.block_y),
(grid, 1, 256, 1)
);
assert!(!layout.projection);
assert!(!operation.has_epsilon());
let qualified = asset(operation).expect("frozen167 qualified component");
qualified.validate(operation).unwrap();
assert_eq!(qualified.receipt, MOE_RECEIPT);
let handles =
[101, 202, 303, 404, 505, 606, 707, 808, 0].map(ffi::BufferHandle::synthetic);
let mut arguments = Arguments::new(operation, handles, 0.0);
let parameters = arguments.parameters();
// SAFETY: inspect only live initialized pointer-table fields.
unsafe {
for (index, expected) in [101u64, 202, 303, 404].iter().take(count).enumerate() {
assert_eq!(*(*parameters.add(index)).cast::<u64>(), *expected);
}
assert!((*parameters.add(count)).is_null());
}
}
assert_eq!(OPERATIONS.len(), 58);
}
#[test]
fn qwen_hash_known_vectors_and_padding_boundaries() {
let hex = |bytes: &[u8]| {
sha256(bytes)
.iter()
.map(|b| format!("{b:02x}"))
.collect::<String>()
};
assert_eq!(
hex(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
assert_eq!(
hex(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(
hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
);
}
#[test]
fn qwen_raw_abi_remains_stable_after_moves() {
for op in OPERATIONS {
let handles = [11, 22, 33, 44, 55, 66, 77, 88, 0].map(ffi::BufferHandle::synthetic);
let args = Arguments::new(op, handles, 1e-6);
let pointer = args.storage.as_ptr();
let mut moved = vec![args].pop().unwrap();
let churn: Vec<_> = (0..64).map(|_| Box::new([0xdeadu64; 16])).collect();
std::hint::black_box(churn);
assert_eq!(pointer, moved.storage.as_ptr());
let layout = op.layout();
let table = moved.parameters();
// SAFETY: read exactly the live owner's initialized scalar fields;
// private ABI pointer table is valid across the owner moves above.
unsafe {
for (i, expected) in [11u64, 22, 33, 44, 55, 66, 77, 88, 0]
.iter()
.enumerate()
.take(layout.count)
{
let slot = i + usize::from(layout.integer.is_some_and(|(_, index)| index <= i));
assert_eq!(*(*table.add(slot)).cast::<u64>(), *expected);
}
if let Some((value, index)) = layout.integer {
assert_eq!(*(*table.add(index)).cast::<u32>(), value);
}
if op == Operation::MtpDenseChunk {
assert_eq!(*(*table.add(6)).cast::<u32>(), layout.rows);
assert_eq!(*(*table.add(7)).cast::<u32>(), layout.columns);
} else if layout.projection {
assert_eq!(*(*table.add(3)).cast::<u32>(), layout.rows);
assert_eq!(*(*table.add(4)).cast::<u32>(), layout.columns);
} else if op.has_epsilon() {
assert_eq!(
(*(*table.add(layout.count)).cast::<f32>()).to_bits(),
1e-6f32.to_bits()
);
}
}
}
}
#[test]
fn qwen_router_has_exact_three_pointer_abi_and_32_by_8_geometry() {
let op = Operation::RouteTop10;
let layout = op.layout();
assert_eq!(op.entry(), c"leleka_moe_route_top10");
assert_eq!(layout.bytes, [2048, 40, 40, 0, 0, 0, 0, 0, 0]);
assert_eq!((layout.grid, layout.block, layout.block_y), (1, 32, 8));
assert_eq!(layout.count, 3);
assert!(!layout.projection);
let mut args = Arguments::new(
op,
[11, 22, 33, 44, 55, 66, 77, 88, 0].map(ffi::BufferHandle::synthetic),
0.0,
);
let parameters = args.parameters();
// SAFETY: read the initialized private table while its owner is live.
// The exact router ABI has no hidden scalar/status/count arguments.
unsafe {
assert!((*parameters.add(3)).is_null());
assert!((*parameters.add(4)).is_null());
}
let admitted = asset(op).expect("independently qualified router component");
assert_eq!(admitted.validate(op), Ok(()));
assert_eq!(
admitted.receipt.qualification_receipt,
"STRA-166 b31a40ef-50b1-4ece-8d9d-1467c1feb388"
);
}
#[test]
fn qwen_ple_fixed_geometry_has_pointer_only_abi_and_exact_component_receipt() {
// Expectations are the independently frozen STRA-161/172 contract.
for (op, entry, bytes, outputs, grid) in [
(
Operation::PleValue,
c"leleka_ple_value_bf16_f32",
vec![10240, 327680, 256],
4,
1,
),
(
Operation::PleNorm,
c"leleka_ple_grouped_norm_f32",
vec![40960, 40960, 40960],
4,
4,
),
(
Operation::PleGate,
c"leleka_ple_signed_gate_f32",
vec![40960, 40960, 16],
4,
4,
),
(
Operation::PleBroadcast,
c"leleka_ple_broadcast_f32",
vec![10240, 16, 40960],
4,
40,
),
(
Operation::PleConv,
c"leleka_ple_conv_history_f32",
vec![368640, 40960, 81920, 40960, 368640],
24,
40,
),
(
Operation::PleResidual,
c"leleka_ple_residual_f32",
vec![40960, 40960, 40960, 40960],
8,
40,
),
] {
let layout = op.layout();
assert_eq!(op.entry(), entry);
assert_eq!(layout.count, bytes.len());
assert_eq!(layout.bytes[..layout.count], bytes);
assert!(layout.bytes[layout.count..].iter().all(|b| *b == 0));
assert_eq!(layout.outputs, outputs);
assert_eq!(
(layout.grid, layout.grid_z, layout.block, layout.block_y),
(grid, 1, 256, 1)
);
assert!(!layout.projection && !op.has_epsilon());
for i in 0..layout.count {
let expected = if (op == Operation::PleValue && i == 1)
|| (op == Operation::PleConv && i == 2)
{
2
} else {
4
};
assert_eq!(layout.align[i], expected);
}
let mut args = Arguments::new(
op,
[11, 22, 33, 44, 55, 66, 77, 88, 0].map(ffi::BufferHandle::synthetic),
0.0,
);
let pointers = args.parameters();
// SAFETY: table storage belongs to live args. These fixed entries
// have no scalar or hidden shape arguments after their pointers.
unsafe {
for i in layout.count..9 {
assert!((*pointers.add(i)).is_null());
}
}
let admitted = asset(op).expect("independently reviewed PLE component");
assert_eq!(admitted.validate(op), Ok(()));
assert_eq!(
admitted.receipt.qualification_receipt,
"STRA-161 ada1a470-76ad-47af-a326-e388ae592d51"
);
// A self-consistent forged pin still cannot admit different bytes.
let mut bad = admitted.receipt;
bad.ptx_sha256[0] ^= 1;
let corrupt = Asset {
operation: op,
ptx: admitted.ptx,
receipt: bad,
pin: bad,
};
assert_eq!(corrupt.validate(op), Err(Error::UnsupportedQwenOperation));
}
}
#[test]
fn mtp_new_qualified_assets_and_fixed_dense_scalar_abi() {
for operation in [
Operation::MtpEmbeddingNorm,
Operation::MtpHiddenNorm,
Operation::MtpBroadcast,
Operation::MtpDenseChunk,
Operation::MtpDenseMerge,
] {
let asset = asset(operation).unwrap();
asset.validate(operation).unwrap();
// A caller who modifies both the metadata and its duplicate pin
// still cannot admit different executable bytes.
let mut forged = Asset {
operation,
ptx: asset.ptx,
receipt: asset.receipt,
pin: asset.pin,
};
forged.receipt.ptx_sha256[0] ^= 1;
forged.pin = forged.receipt;
assert_eq!(
forged.validate(operation),
Err(Error::UnsupportedQwenOperation)
);
}
for (position, width, chunks) in [
(0, 1, 1),
(63, 64, 1),
(64, 65, 2),
(32767, 32768, 512),
(262143, 32768, 512),
] {
let layout = mtp_dense_layout(Operation::MtpDenseChunk, position).unwrap();
assert_eq!(
(layout.rows, layout.columns, layout.grid, layout.grid_y),
(width, chunks, chunks, 2)
);
assert_eq!(
(layout.bytes[1], layout.bytes[3], layout.bytes[4]),
(
width as usize * 1024,
chunks as usize * 24576,
chunks as usize * 96
)
);
let handles = [11, 22, 33, 44, 55, 66, 77, 88, 0].map(ffi::BufferHandle::synthetic);
let owner = Arguments::with_layout(Operation::MtpDenseChunk, layout, handles, 0.0);
let mut moved = std::hint::black_box(vec![owner]).pop().unwrap();
let table = moved.parameters();
// SAFETY: exact initialized fields in one live stable ABI owner.
unsafe {
for (i, address) in [11u64, 22, 33, 44, 55, 66].iter().enumerate() {
assert_eq!(*(*table.add(i)).cast::<u64>(), *address);
}
assert_eq!(*(*table.add(6)).cast::<u32>(), width);
assert_eq!(*(*table.add(7)).cast::<u32>(), chunks);
assert!((*table.add(8)).is_null());
}
let merge = mtp_dense_layout(Operation::MtpDenseMerge, position).unwrap();
assert_eq!(merge.integer, Some((chunks, 4)));
assert_eq!((merge.grid, merge.block, merge.outputs), (24, 256, 8));
}
for position in [crate::MAX_CONTEXT_CELLS as u32, u32::MAX] {
assert_eq!(
mtp_dense_layout(Operation::MtpDenseChunk, position).err(),
Some(Error::InvalidQwenShape)
);
}
assert_eq!(
mtp_dense_layout(Operation::Norm, 0).err(),
Some(Error::InvalidQwenShape)
);
}
+259
View File
@@ -0,0 +1,259 @@
//! Moved out of the parent file by STRA-338 (same module path as before).
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[test]
#[ignore = "Root-only original-first owned whole-buffer readback proof"]
fn owned_readback_original_first_preserves_gdn_extents_and_raw_words() {
let driver = super::Driver::load().unwrap();
let context = driver
.device(0)
.unwrap()
.create_context(16 * 1024 * 1024)
.unwrap();
let mut exact_bytes = 0usize;
let mut bounds = 0usize;
// Full real recurrence state, convolution history and readout extents.
for size in [3_145_728usize, 122_880, 24_576] {
let mut buffer = context.allocate(size).unwrap();
for round in 0..2u32 {
let words = [
0u32,
0x8000_0000,
0x3f80_0000,
0xbf80_0000,
0x7f80_0000,
0xff80_0000,
0x7fc0_0101,
1,
];
let mut source = Vec::with_capacity(size);
for i in 0..size / 4 {
let word = if i < words.len() {
words[i]
} else {
(i as u32).wrapping_mul(0x9e37_79b9).wrapping_add(round)
};
source.extend_from_slice(&word.to_le_bytes());
}
buffer.copy_from(&source).unwrap();
let mut original = vec![0; size];
buffer.copy_to(&mut original).unwrap();
assert_eq!(original, source);
let owned = buffer.copy_to_owned(size).unwrap();
assert_eq!(owned, original);
// The downstream original LE conversion preserves all bits,
// including signed zero and nonfinite values (later rejected
// by the unchanged GDN finite guard).
for (a, b) in original
.as_chunks::<4>()
.0
.iter()
.zip(owned.as_chunks::<4>().0)
{
assert_eq!(
f32::from_le_bytes(*a).to_bits(),
f32::from_le_bytes(*b).to_bits()
);
}
exact_bytes += size;
for invalid in [0, size - 1, size + 1] {
assert!(matches!(buffer.copy_to_owned(invalid),
Err(super::Error::ShapeMismatch { expected, actual })
if expected == size && actual == invalid));
bounds += 1;
}
assert_eq!(buffer.copy_to_owned(size).unwrap(), original);
exact_bytes += size;
}
buffer.release().unwrap();
assert_eq!(context.allocated_bytes(), 0);
}
assert_eq!(exact_bytes, 13_172_736);
assert_eq!(bounds, 18);
assert_eq!(context.allocated_bytes(), 0);
context.close().unwrap();
println!(
"owned_gdn_readback exact_bytes={exact_bytes} bounds={bounds} original_first=true allocated=0 raw_nonfinite_preserved=true"
);
}
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[test]
#[ignore = "Root-only installed driver partial-copy guard proof"]
fn checked_subspan_real_copy_preserves_untouched_bytes() {
let driver = super::Driver::load().unwrap();
let context = driver.device(0).unwrap().create_context(65536).unwrap();
let mut buffer = context.allocate(1024).unwrap();
buffer.copy_from(&[0x5a; 1024]).unwrap();
buffer.copy_from_range(255, &[0x73; 513]).unwrap();
let mut out = [0; 1024];
buffer.copy_to(&mut out).unwrap();
assert_eq!(&out[..255], &[0x5a; 255]);
assert_eq!(&out[255..768], &[0x73; 513]);
assert_eq!(&out[768..], &[0x5a; 256]);
assert!(buffer.copy_from_range(1023, &[1, 2]).is_err());
assert!(buffer.copy_from_range(0, &[]).is_err());
let mut after = [0; 1024];
buffer.copy_to(&mut after).unwrap();
assert_eq!(out, after);
buffer.release().unwrap();
assert_eq!(context.allocated_bytes(), 0);
context.close().unwrap();
}
use super::*;
#[test]
fn sizes_and_error_composition() {
assert_eq!(valid_size(0), Err(Error::InvalidSize));
assert_eq!(valid_size(usize::MAX), Err(Error::InvalidSize));
assert_eq!(valid_size(1), Ok(()));
assert_eq!(
combine::<()>(Err(Error::InvalidSize), Err(Error::UnexpectedContext)),
Err(Error::Multiple {
primary: Box::new(Error::InvalidSize),
secondary: Box::new(Error::UnexpectedContext)
})
);
}
#[test]
fn vector_count_geometry_boundaries() {
for bytes in [0, 1, 3, 5, usize::MAX] {
assert!(vector_shape(bytes).is_err());
}
for n in [1u32, 127, 128, 129, 1025, u32::MAX] {
let bytes = usize::try_from(u64::from(n) * 4).unwrap();
assert_eq!(
vector_shape(bytes),
Ok((n, u32::try_from(u64::from(n).div_ceil(128)).unwrap()))
);
}
assert!(vector_shape((u32::MAX as usize + 1) * 4).is_err());
}
#[test]
fn matvec_shape_boundaries() {
for (m, n) in [
(0, 1),
(1, 0),
(usize::MAX, 1),
(1, usize::MAX),
(u32::MAX as usize + 1, 1),
(1, u32::MAX as usize + 1),
(u32::MAX as usize, u32::MAX as usize),
] {
assert_eq!(matvec_shape(m, n), Err(Error::InvalidMatvecShape));
}
for m in [1u32, 127, 128, 129, 1025, u32::MAX] {
let shape = matvec_shape(m as usize, 1).unwrap();
assert_eq!(shape.rows, m);
assert_eq!(shape.matrix_bytes, m as usize * 4);
assert_eq!(shape.output_bytes, m as usize * 4);
assert_eq!(shape.grid as u64, u64::from(m).div_ceil(128));
}
let shape = matvec_shape(1, u32::MAX as usize).unwrap();
assert_eq!(shape.columns, u32::MAX);
assert_eq!(shape.vector_bytes, u32::MAX as usize * 4);
let largest_columns = (isize::MAX as usize / 4) / u32::MAX as usize;
assert!(matvec_shape(u32::MAX as usize, largest_columns).is_ok());
assert_eq!(
matvec_shape(u32::MAX as usize, largest_columns + 1),
Err(Error::InvalidMatvecShape)
);
// Element count is deliberately not restricted to u32.
assert!(matvec_shape(65536, 65536).is_ok());
}
#[test]
fn matvec_allocation_identity_and_absent_handles() {
let shape = matvec_shape(1, 1).unwrap();
let h = |v| Some(ffi::BufferHandle::synthetic(v));
for handles in [(h(4), h(8), h(4)), (h(4), h(8), h(8))] {
assert!(matches!(
matvec_allocations(handles.0, handles.1, handles.2, &shape),
Err(Error::OutputAliasesInput)
));
}
for handles in [(None, h(8), h(12)), (h(4), None, h(12)), (h(4), h(8), None)] {
assert!(matches!(
matvec_allocations(handles.0, handles.1, handles.2, &shape),
Err(Error::ContextPoisoned)
));
}
for handles in [
(h(u64::MAX - 3), h(8), h(12)),
(h(4), h(u64::MAX - 3), h(12)),
(h(4), h(8), h(u64::MAX - 3)),
] {
assert!(matches!(
matvec_allocations(handles.0, handles.1, handles.2, &shape),
Err(Error::InvalidMatvecShape)
));
}
assert!(matvec_allocations(h(4), h(4), h(12), &shape).is_ok());
}
#[cfg(not(feature = "cuda-driver"))]
#[test]
fn matvec_private_admission_refuses_without_cuda() {
let driver = Driver {
api: Rc::new(ffi::Api),
version: 0,
};
let context = Context {
driver: &driver,
handle: None,
ordinal: 0,
budget: 64,
allocated: Cell::new(12),
poisoned: PoisonCell::new(false),
vector_add_kernel: Cell::new(None),
matvec_kernel: Cell::new(None),
q5_k_kernel: Cell::new(None),
q6_k_kernel: Cell::new(None),
common_quantizer: Cell::new(None),
grouped_iq3: Cell::new(None),
grouped_iq2: Cell::new(None),
grouped_iq3_s: Cell::new(None),
grouped_iq4_xs: Cell::new(None),
grouped_iq3_s_nc4: Cell::new(None),
grouped_iq4_xs_nc4: Cell::new(None),
grouped_swiglu: Cell::new(None),
grouped_down_iq4: Cell::new(None),
grouped_down_q2: Cell::new(None),
gr_read_guard_kernel: Cell::new(None),
projection_kernels: std::array::from_fn(|_| Cell::new(None)),
qwen_kernels: qwen_dispatch::Cache::new(),
kar_levels: Cell::new(None),
experimental: std::array::from_fn(|_| Cell::new(None)),
window_modules: RefCell::new(Vec::new()),
deferred_frees: RefCell::new(Vec::new()),
};
let make = |handle| DeviceBuffer {
context: &context,
handle,
bytes: 4,
_thread: PhantomData,
borrowed: false,
};
let matrix = make(Some(ffi::BufferHandle::synthetic(4)));
let vector = make(Some(ffi::BufferHandle::synthetic(8)));
let mut output = make(Some(ffi::BufferHandle::synthetic(12)));
assert_eq!(
context.matvec_f32(&matrix, &vector, &mut output, 1, 1),
Err(Error::ContextPoisoned)
);
// No native context exists in this test. Pure allocation identity and
// extent instruments supply the remaining impossible-safe-call cases.
assert_eq!(context.allocated_bytes(), 12);
assert!(context.matvec_kernel.get().is_none());
}
#[cfg(not(feature = "cuda-driver"))]
#[test]
fn default_load_rejects_before_driver_use() {
assert!(matches!(Driver::load(), Err(Error::Disabled)));
}
#[cfg(all(
feature = "cuda-driver",
not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))
))]
#[test]
fn unsupported_load_rejects_before_driver_use() {
assert!(matches!(Driver::load(), Err(Error::UnsupportedPlatform)));
}
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Move large inline `mod NAME { ... }` blocks of a Rust file into their own files (STRA-338).
`foo.rs` keeps the attributes, visibility and name of the module and ends the block with `;`; the body moves, dedented,
to `foo/NAME.rs` (beside the file for `mod.rs`, `lib.rs` and `main.rs`). The module path is the same as before, so
`super::` paths, test ids and visibility need no edit. Relative `include_str!` / `include_bytes!` paths get one more `../`
(the body sits one directory deeper). A block that contains a `#[path]` attribute is left alone. The compiler judges the rest.
Usage: scripts/dev/extract_modules.py [--dry-run] [--min-lines 60] FILE.rs... prints "moved|skipped <file> <detail>"
"""
import argparse
import pathlib
import re
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from rustsplit.items import parse_items # noqa: E402
from rustsplit.lexer import tokenize # noqa: E402
INCLUDE = re.compile(r'(include(?:_str|_bytes)?!\(\s*")(?=[^/])')
PATH_ATTR = re.compile(r"#\[\s*path\s*=")
MODULE = re.compile(r"(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)\s*\{")
HEADER = "//! Moved out of the parent file by STRA-338 (same module path as before).\n\n"
def read(path):
with open(path, encoding="utf-8", newline="") as handle:
return handle.read().replace("\r\n", "\n")
def write(path, text):
with open(path, "w", encoding="utf-8", newline="\n") as handle:
handle.write(text)
def child_dir(path):
return path.parent if path.name in ("mod.rs", "lib.rs", "main.rs") else path.with_suffix("")
def brace_index(text, item):
"""Index of the `{` that opens the module body."""
for tok in tokenize(text[item.head:item.end]):
if tok.text == "{":
return item.head + tok.start
raise ValueError("no opening brace")
def dedent(body):
return "\n".join(row[4:] if row.startswith(" ") else row for row in body.split("\n"))
def plan(text, directory, min_lines):
"""(new source text, {file: text}, [skipped reasons]) for the inline modules of `text` with at least `min_lines` lines."""
edits, files, skipped = [], {}, []
for item in parse_items(text):
found = MODULE.match(text[item.head:item.end]) if item.kind == "other" else None
if found is None:
continue
name, opening = found.group(1), brace_index(text, item)
body = text[opening + 1:item.end - 1]
if body.count("\n") < min_lines:
continue
if PATH_ATTR.search(body):
skipped.append(f"{name}: contains a #[path] attribute")
elif (directory / f"{name}.rs").exists():
skipped.append(f"{name}: {directory / (name + '.rs')} exists")
else:
content = INCLUDE.sub(lambda m: m.group(1) + "../", dedent(body).strip("\n"))
files[directory / f"{name}.rs"] = HEADER + content + "\n"
edits.append((opening, item.end))
for start, end in sorted(edits, reverse=True):
text = text[:start].rstrip() + ";" + text[end:]
return text, files, skipped
def process(path, min_lines, dry_run):
text, files, skipped = plan(read(path), child_dir(path), min_lines)
if not files:
return "skipped", "; ".join(skipped) or "no inline module of that size"
if not dry_run:
for target, body in files.items():
target.parent.mkdir(parents=True, exist_ok=True)
write(target, body)
write(path, text)
detail = ", ".join(f"{p.name} ({b.count(chr(10))} lines)" for p, b in files.items())
return "moved", detail + (f" | left: {'; '.join(skipped)}" if skipped else "")
def main(argv):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--min-lines", type=int, default=60)
parser.add_argument("files", nargs="+")
args = parser.parse_args(argv)
for name in args.files:
verdict, detail = process(pathlib.Path(name), args.min_lines, args.dry_run)
print(f"{verdict} {name} {detail}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Proofs for scripts/dev/extract_modules.py on synthetic sources."""
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from extract_modules import plan # noqa: E402
BODY = "".join(f" fn f{n}() {{}}\n" for n in range(5))
SOURCE = f'use a::b;\n\n#[cfg(test)]\nmod tests {{\n const P: &str = include_str!("x.ptx");\n{BODY}}}\n\npub(crate) mod small {{\n fn g() {{}}\n}}\n\nfn keep() {{}}\n'
class ExtractModules(unittest.TestCase):
def test_a_large_inline_module_moves_and_keeps_its_attributes(self):
text, files, skipped = plan(SOURCE, pathlib.Path("d"), 3)
self.assertIn("#[cfg(test)]\nmod tests;", text)
self.assertEqual(list(files), [pathlib.Path("d/tests.rs")])
self.assertEqual(skipped, [])
def test_the_body_is_dedented_and_includes_go_one_level_up(self):
_, files, _ = plan(SOURCE, pathlib.Path("d"), 3)
body = files[pathlib.Path("d/tests.rs")]
self.assertIn('include_str!("../x.ptx")', body)
self.assertIn("\nfn f0() {}\n", body)
def test_small_modules_and_functions_stay(self):
text, _, _ = plan(SOURCE, pathlib.Path("d"), 3)
self.assertIn("pub(crate) mod small {", text)
self.assertIn("fn keep() {}", text)
def test_include_macro_without_a_suffix_is_deepened(self):
_, files, _ = plan("mod m {\n include!(\"a.rs\");\n fn f() {}\n}\n", pathlib.Path("d"), 1)
self.assertIn('include!("../a.rs")', files[pathlib.Path("d/m.rs")])
def test_a_path_attribute_inside_the_block_keeps_it_in_place(self):
text, files, skipped = plan('mod m {\n #[path = "q.rs"]\n mod q;\n fn f() {}\n}\n', pathlib.Path("d"), 1)
self.assertEqual(files, {})
self.assertIn("mod m {", text)
self.assertEqual(len(skipped), 1)
if __name__ == "__main__":
unittest.main()
+5 -4
View File
@@ -36,7 +36,7 @@ def is_root(path):
def child_dir(path):
return path.parent if path.name == "mod.rs" else path.with_suffix("")
return path.parent if path.name in ("mod.rs", "lib.rs", "main.rs") else path.with_suffix("")
def path_targets():
@@ -50,8 +50,8 @@ def path_targets():
return found
def process(path, target, dry_run, loaded):
if is_root(path):
def process(path, target, dry_run, loaded, allow_root=False):
if is_root(path) and not (allow_root and path.name == "lib.rs"):
return "skipped", "crate root, bin or example"
directory = child_dir(path)
explicit = directory.name if path.name in loaded else None
@@ -71,11 +71,12 @@ def main(argv):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--target", type=int, default=250)
parser.add_argument("--allow-root", action="store_true", help="also split a lib.rs crate root")
parser.add_argument("files", nargs="+")
args = parser.parse_args(argv)
loaded = path_targets()
for name in args.files:
verdict, detail = process(pathlib.Path(name), args.target, args.dry_run, loaded)
verdict, detail = process(pathlib.Path(name), args.target, args.dry_run, loaded, args.allow_root)
print(f"{verdict} {name} {detail}")
return 0