feat(cuda): add native-compatible Q5_K Q8_1 projection [skip ci]
This commit is contained in:
@@ -117,6 +117,88 @@ impl MatvecArguments {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Q8QuantizeStorage {
|
||||
addresses: [u64; 3],
|
||||
elements: u32,
|
||||
parameters: [*mut std::ffi::c_void; 4],
|
||||
}
|
||||
pub(crate) struct Q8QuantizeArguments {
|
||||
storage: std::ptr::NonNull<Q8QuantizeStorage>,
|
||||
}
|
||||
impl Q8QuantizeArguments {
|
||||
pub(crate) fn new(
|
||||
input: BufferHandle,
|
||||
scratch: BufferHandle,
|
||||
status: BufferHandle,
|
||||
elements: u32,
|
||||
) -> Self {
|
||||
let storage = Box::into_raw(Box::new(Q8QuantizeStorage {
|
||||
addresses: [input.0, scratch.0, status.0],
|
||||
elements,
|
||||
parameters: [std::ptr::null_mut(); 4],
|
||||
}));
|
||||
// SAFETY: raw-owned, stable allocation; initialize the exact fixed ABI.
|
||||
unsafe {
|
||||
for i in 0..3 {
|
||||
(*storage).parameters[i] = (&raw mut (*storage).addresses[i]).cast();
|
||||
}
|
||||
(*storage).parameters[3] = (&raw mut (*storage).elements).cast();
|
||||
}
|
||||
Self {
|
||||
storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Q8QuantizeArguments {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: uniquely reconstructed before launch or after confirmed sync.
|
||||
unsafe { drop(Box::from_raw(self.storage.as_ptr())) }
|
||||
}
|
||||
}
|
||||
|
||||
struct Q5ProjectionStorage {
|
||||
addresses: [u64; 3],
|
||||
rows: u32,
|
||||
columns: u32,
|
||||
parameters: [*mut std::ffi::c_void; 5],
|
||||
}
|
||||
pub(crate) struct Q5ProjectionArguments {
|
||||
storage: std::ptr::NonNull<Q5ProjectionStorage>,
|
||||
}
|
||||
impl Q5ProjectionArguments {
|
||||
pub(crate) fn new(
|
||||
weights: BufferHandle,
|
||||
scratch: BufferHandle,
|
||||
output: BufferHandle,
|
||||
rows: u32,
|
||||
columns: u32,
|
||||
) -> Self {
|
||||
let storage = Box::into_raw(Box::new(Q5ProjectionStorage {
|
||||
addresses: [weights.0, scratch.0, output.0],
|
||||
rows,
|
||||
columns,
|
||||
parameters: [std::ptr::null_mut(); 5],
|
||||
}));
|
||||
// SAFETY: raw-owned, stable allocation; initialize the exact fixed ABI.
|
||||
unsafe {
|
||||
for i in 0..3 {
|
||||
(*storage).parameters[i] = (&raw mut (*storage).addresses[i]).cast();
|
||||
}
|
||||
(*storage).parameters[3] = (&raw mut (*storage).rows).cast();
|
||||
(*storage).parameters[4] = (&raw mut (*storage).columns).cast();
|
||||
}
|
||||
Self {
|
||||
storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Q5ProjectionArguments {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: uniquely reconstructed before launch or after confirmed sync.
|
||||
unsafe { drop(Box::from_raw(self.storage.as_ptr())) }
|
||||
}
|
||||
}
|
||||
impl Drop for MatvecArguments {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: reconstructed exactly once before launch or after successful
|
||||
@@ -170,6 +252,7 @@ mod enabled {
|
||||
) -> 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();
|
||||
type MemcpyDtoHV2 = unsafe extern "C" fn(*mut c_void, CuDevicePtr, usize) -> CuResult;
|
||||
|
||||
struct Library(*mut c_void);
|
||||
@@ -271,6 +354,9 @@ mod enabled {
|
||||
match operation {
|
||||
FixedOperation::VectorAdd => FIXED_PTX,
|
||||
FixedOperation::Matvec => MATVEC_PTX,
|
||||
FixedOperation::Q5K
|
||||
| FixedOperation::Q5KQuantize
|
||||
| FixedOperation::Q5KProject => Q5_K_PTX,
|
||||
}
|
||||
.as_ptr()
|
||||
.cast(),
|
||||
@@ -296,6 +382,11 @@ mod enabled {
|
||||
match operation {
|
||||
FixedOperation::VectorAdd => c"leleka_vector_add_f32",
|
||||
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",
|
||||
}
|
||||
.as_ptr(),
|
||||
)
|
||||
@@ -368,6 +459,56 @@ mod enabled {
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
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 init(&self) -> Result<()> {
|
||||
// SAFETY: resolved exact ABI, mandated zero flags, live library.
|
||||
check("cuInit", unsafe { (self.init)(0) })
|
||||
@@ -515,6 +656,24 @@ impl Api {
|
||||
let _ = (function.0, arguments.storage);
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn launch_q8_quantize(
|
||||
&self,
|
||||
function: FunctionHandle,
|
||||
_: u32,
|
||||
arguments: &mut Q8QuantizeArguments,
|
||||
) -> Result<()> {
|
||||
let _ = (function.0, arguments.storage);
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn launch_q5_projection(
|
||||
&self,
|
||||
function: FunctionHandle,
|
||||
_: u32,
|
||||
arguments: &mut Q5ProjectionArguments,
|
||||
) -> Result<()> {
|
||||
let _ = (function.0, arguments.storage);
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
// These methods cannot be reached through the safe API: load always fails.
|
||||
pub(crate) fn init(&self) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
|
||||
@@ -29,6 +29,8 @@ pub enum Error {
|
||||
ContextMismatch,
|
||||
InvalidVectorShape,
|
||||
InvalidMatvecShape,
|
||||
InvalidQ5KProjectionShape,
|
||||
InvalidQ8Activation,
|
||||
OutputAliasesInput,
|
||||
InvalidOrdinal,
|
||||
InvalidSize,
|
||||
@@ -70,6 +72,10 @@ impl Error {
|
||||
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::InvalidQ8Activation => "activation cannot be represented by native Q8_1",
|
||||
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",
|
||||
@@ -184,6 +190,7 @@ impl<'driver> Device<'driver> {
|
||||
poisoned: Cell::new(false),
|
||||
vector_add_kernel: Cell::new(None),
|
||||
matvec_kernel: Cell::new(None),
|
||||
q5_k_kernel: Cell::new(None),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -197,18 +204,92 @@ pub struct Context<'driver> {
|
||||
poisoned: Cell<bool>,
|
||||
vector_add_kernel: Cell<Option<FixedKernel>>,
|
||||
matvec_kernel: Cell<Option<FixedKernel>>,
|
||||
q5_k_kernel: Cell<Option<Q5Kernels>>,
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct FixedKernel {
|
||||
module: ffi::ModuleHandle,
|
||||
function: ffi::FunctionHandle,
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct Q5Kernels {
|
||||
module: ffi::ModuleHandle,
|
||||
quantize: ffi::FunctionHandle,
|
||||
project: ffi::FunctionHandle,
|
||||
}
|
||||
|
||||
// Closed selector: callers cannot choose executable bytes, names or geometry.
|
||||
#[derive(Clone, Copy)]
|
||||
enum FixedOperation {
|
||||
VectorAdd,
|
||||
Matvec,
|
||||
Q5K,
|
||||
Q5KQuantize,
|
||||
Q5KProject,
|
||||
}
|
||||
|
||||
/// Exact one-column Q5_K matrix geometry: `rows × columns` packed weights.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Q5KProjectionShape {
|
||||
pub rows: usize,
|
||||
pub columns: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct Q5KShape {
|
||||
weight_bytes: usize,
|
||||
activation_bytes: usize,
|
||||
output_bytes: usize,
|
||||
scratch_bytes: usize,
|
||||
rows: u32,
|
||||
columns: u32,
|
||||
quant_grid: u32,
|
||||
projection_grid: u32,
|
||||
}
|
||||
|
||||
fn q5_k_shape(rows: usize, columns: usize) -> Result<Q5KShape> {
|
||||
if rows == 0 || columns == 0 || !columns.is_multiple_of(256) {
|
||||
return Err(Error::InvalidQ5KProjectionShape);
|
||||
}
|
||||
let rows_abi = u32::try_from(rows).map_err(|_| Error::InvalidQ5KProjectionShape)?;
|
||||
let columns_abi = u32::try_from(columns).map_err(|_| Error::InvalidQ5KProjectionShape)?;
|
||||
if rows_abi > i32::MAX as u32 || columns_abi > i32::MAX as u32 {
|
||||
return Err(Error::InvalidQ5KProjectionShape);
|
||||
}
|
||||
let checked_bytes = |elements: usize, width: usize| -> Result<usize> {
|
||||
let bytes = elements
|
||||
.checked_mul(width)
|
||||
.ok_or(Error::InvalidQ5KProjectionShape)?;
|
||||
valid_size(bytes).map_err(|_| Error::InvalidQ5KProjectionShape)?;
|
||||
Ok(bytes)
|
||||
};
|
||||
let weight_blocks = rows
|
||||
.checked_mul(columns / 256)
|
||||
.ok_or(Error::InvalidQ5KProjectionShape)?;
|
||||
let weight_bytes = checked_bytes(weight_blocks, 176)?;
|
||||
let activation_bytes = checked_bytes(columns, 4)?;
|
||||
let output_bytes = checked_bytes(rows, 4)?;
|
||||
let scratch_bytes = checked_bytes(columns / 32, 36)?;
|
||||
let quant_grid = columns / 256;
|
||||
if quant_grid == 0 || quant_grid > i32::MAX as usize {
|
||||
return Err(Error::InvalidQ5KProjectionShape);
|
||||
}
|
||||
let small_k = columns / 256 < 8;
|
||||
let projection_ctas = if small_k { rows.div_ceil(4) } else { rows };
|
||||
if projection_ctas == 0 || projection_ctas > i32::MAX as usize {
|
||||
return Err(Error::InvalidQ5KProjectionShape);
|
||||
}
|
||||
Ok(Q5KShape {
|
||||
weight_bytes,
|
||||
activation_bytes,
|
||||
output_bytes,
|
||||
scratch_bytes,
|
||||
rows: rows_abi,
|
||||
columns: columns_abi,
|
||||
quant_grid: u32::try_from(quant_grid).map_err(|_| Error::InvalidQ5KProjectionShape)?,
|
||||
projection_grid: u32::try_from(projection_ctas)
|
||||
.map_err(|_| Error::InvalidQ5KProjectionShape)?,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
@@ -397,11 +478,17 @@ impl Context<'_> {
|
||||
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), guard.finish())
|
||||
combine(combine(launch, sync), restore)
|
||||
}
|
||||
/// Compute each row's dot product in ascending column order with separate
|
||||
/// binary32 multiply/add rounding. All buffers are exact whole allocations;
|
||||
@@ -434,6 +521,157 @@ impl Context<'_> {
|
||||
.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_q5_temporaries(operation, scratch, status)
|
||||
}
|
||||
|
||||
fn q5_k_admission(
|
||||
&self,
|
||||
weights: &DeviceBuffer<'_>,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
output: &DeviceBuffer<'_>,
|
||||
dimensions: Q5KProjectionShape,
|
||||
) -> Result<(Q5KShape, [ffi::BufferHandle; 3], usize)> {
|
||||
if self.poisoned.get() || self.handle.is_none() {
|
||||
return Err(Error::ContextPoisoned);
|
||||
}
|
||||
if !std::ptr::eq(self, weights.context)
|
||||
|| !std::ptr::eq(self, activation.context)
|
||||
|| !std::ptr::eq(self, output.context)
|
||||
{
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
let shape = q5_k_shape(dimensions.rows, dimensions.columns)?;
|
||||
if weights.bytes != shape.weight_bytes
|
||||
|| activation.bytes != shape.activation_bytes
|
||||
|| output.bytes != shape.output_bytes
|
||||
{
|
||||
return Err(Error::InvalidQ5KProjectionShape);
|
||||
}
|
||||
let weight = weights.handle.ok_or(Error::ContextPoisoned)?;
|
||||
let activation = activation.handle.ok_or(Error::ContextPoisoned)?;
|
||||
let output = output.handle.ok_or(Error::ContextPoisoned)?;
|
||||
if output == weight || output == activation {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
weight
|
||||
.validate_extent(shape.weight_bytes)
|
||||
.map_err(|_| Error::InvalidQ5KProjectionShape)?;
|
||||
activation
|
||||
.validate_extent(shape.activation_bytes)
|
||||
.map_err(|_| Error::InvalidQ5KProjectionShape)?;
|
||||
output
|
||||
.validate_extent(shape.output_bytes)
|
||||
.map_err(|_| Error::InvalidQ5KProjectionShape)?;
|
||||
let temporary_bytes = shape
|
||||
.scratch_bytes
|
||||
.checked_add(4)
|
||||
.ok_or(Error::BudgetExceeded)?;
|
||||
Ok((shape, [weight, activation, output], temporary_bytes))
|
||||
}
|
||||
|
||||
fn release_q5_temporaries<T>(
|
||||
&self,
|
||||
operation: Result<T>,
|
||||
scratch: DeviceBuffer<'_>,
|
||||
status: DeviceBuffer<'_>,
|
||||
) -> Result<T> {
|
||||
if self.poisoned.get() {
|
||||
// Unknown completion/restoration means these allocations and
|
||||
// their context accounting must outlive this call.
|
||||
std::mem::forget(scratch);
|
||||
std::mem::forget(status);
|
||||
return operation;
|
||||
}
|
||||
let status_free = status.release();
|
||||
if self.poisoned.get() {
|
||||
std::mem::forget(scratch);
|
||||
return combine(operation, status_free);
|
||||
}
|
||||
combine(combine(operation, status_free), scratch.release())
|
||||
}
|
||||
fn matvec_admission(
|
||||
&self,
|
||||
buffers: [&DeviceBuffer<'_>; 3],
|
||||
@@ -464,6 +702,9 @@ impl Context<'_> {
|
||||
match operation {
|
||||
FixedOperation::VectorAdd => &self.vector_add_kernel,
|
||||
FixedOperation::Matvec => &self.matvec_kernel,
|
||||
FixedOperation::Q5K | FixedOperation::Q5KQuantize | FixedOperation::Q5KProject => {
|
||||
unreachable!("Q5_K kernels are cached as an atomic pair")
|
||||
}
|
||||
}
|
||||
}
|
||||
fn fixed_kernel(&self, operation: FixedOperation) -> Result<FixedKernel> {
|
||||
@@ -484,6 +725,7 @@ impl Context<'_> {
|
||||
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)
|
||||
}
|
||||
@@ -495,6 +737,8 @@ impl Context<'_> {
|
||||
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() {
|
||||
@@ -510,6 +754,74 @@ impl Context<'_> {
|
||||
}
|
||||
combine(unload, guard.finish())
|
||||
}
|
||||
fn q5_kernels(&self) -> Result<Q5Kernels> {
|
||||
if let Some(kernels) = self.q5_k_kernel.get() {
|
||||
return Ok(kernels);
|
||||
}
|
||||
let module = self.driver.api.load_fixed_module(FixedOperation::Q5K)?;
|
||||
let quantize = match self
|
||||
.driver
|
||||
.api
|
||||
.fixed_function(module, FixedOperation::Q5KQuantize)
|
||||
{
|
||||
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, FixedOperation::Q5KProject)
|
||||
{
|
||||
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 = Q5Kernels {
|
||||
module,
|
||||
quantize,
|
||||
project,
|
||||
};
|
||||
// Publish only after both fixed entries resolve successfully.
|
||||
self.q5_k_kernel.set(Some(kernels));
|
||||
Ok(kernels)
|
||||
}
|
||||
fn unload_q5_kernels(&self) -> Result<()> {
|
||||
let Some(kernels) = self.q5_k_kernel.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())
|
||||
}
|
||||
/// 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<()> {
|
||||
@@ -518,8 +830,11 @@ impl Context<'_> {
|
||||
fn destroy(&mut self) -> Result<()> {
|
||||
// Fixed teardown order; shared poison suppresses the second native unload.
|
||||
let unload = combine(
|
||||
self.unload_kernel(FixedOperation::VectorAdd),
|
||||
self.unload_kernel(FixedOperation::Matvec),
|
||||
combine(
|
||||
self.unload_kernel(FixedOperation::VectorAdd),
|
||||
self.unload_kernel(FixedOperation::Matvec),
|
||||
),
|
||||
self.unload_q5_kernels(),
|
||||
);
|
||||
if let Some(handle) = self.handle.take() {
|
||||
// cuCtxDestroy accepts an owned non-current context. Pushing here
|
||||
@@ -768,6 +1083,7 @@ mod tests {
|
||||
poisoned: Cell::new(false),
|
||||
vector_add_kernel: Cell::new(None),
|
||||
matvec_kernel: Cell::new(None),
|
||||
q5_k_kernel: Cell::new(None),
|
||||
};
|
||||
let make = |handle| DeviceBuffer {
|
||||
context: &context,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,313 @@
|
||||
#![cfg(all(
|
||||
feature = "cuda-driver",
|
||||
target_os = "linux",
|
||||
target_pointer_width = "64"
|
||||
))]
|
||||
#[path = "q5_oracle.rs"]
|
||||
mod oracle;
|
||||
use leleka_cuda_driver::{Context, DeviceBuffer, Driver, Error, Q5KProjectionShape};
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
fn upload<'a>(ctx: &'a Context<'_>, data: &[u8]) -> DeviceBuffer<'a> {
|
||||
let mut b = ctx.allocate(data.len()).unwrap();
|
||||
b.copy_from(data).unwrap();
|
||||
b
|
||||
}
|
||||
fn read(b: &DeviceBuffer<'_>) -> Vec<u8> {
|
||||
let mut x = vec![0; b.len()];
|
||||
b.copy_to(&mut x).unwrap();
|
||||
x
|
||||
}
|
||||
fn compare_output(actual: &[u8], expected: &[u8]) {
|
||||
assert_eq!(actual.len(), expected.len());
|
||||
for (i, (a, b)) in actual
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.zip(expected.as_chunks::<4>().0.iter())
|
||||
.enumerate()
|
||||
{
|
||||
let a = u32::from_le_bytes(*a);
|
||||
let b = u32::from_le_bytes(*b);
|
||||
if f32::from_bits(b).is_nan() {
|
||||
assert!(f32::from_bits(a).is_nan(), "row {i} NaN classification");
|
||||
} else {
|
||||
assert_eq!(a, b, "row {i} native exactbits");
|
||||
}
|
||||
}
|
||||
}
|
||||
fn run_case(
|
||||
ctx: &Context<'_>,
|
||||
root: &Path,
|
||||
native: &Path,
|
||||
ptx: &Path,
|
||||
rows: usize,
|
||||
columns: usize,
|
||||
pattern: usize,
|
||||
) {
|
||||
let w = oracle::weights(rows, columns, pattern);
|
||||
let x = oracle::activation(columns, pattern);
|
||||
let xb = oracle::f32bytes(&x);
|
||||
let stem = format!("m{rows}-n{columns}-p{pattern}");
|
||||
let input = root.join(format!("{stem}.input"));
|
||||
let result = root.join(format!("{stem}.native"));
|
||||
let mut data = Vec::new();
|
||||
for h in [0x35314b51, rows as u32, columns as u32] {
|
||||
data.extend_from_slice(&h.to_le_bytes());
|
||||
}
|
||||
data.extend_from_slice(&w);
|
||||
data.extend_from_slice(&xb);
|
||||
fs::write(&input, &data).unwrap();
|
||||
let output = Command::new("timeout")
|
||||
.args(["--signal=TERM", "--kill-after=5", "30"])
|
||||
.arg(native)
|
||||
.arg(&input)
|
||||
.arg(&result)
|
||||
.arg(ptx)
|
||||
.output()
|
||||
.unwrap();
|
||||
fs::write(root.join(format!("{stem}.stdout")), &output.stdout).unwrap();
|
||||
fs::write(root.join(format!("{stem}.stderr")), &output.stderr).unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"native {stem}: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let expected = fs::read(&result).unwrap();
|
||||
let qb = columns / 32 * 36;
|
||||
assert_eq!(expected.len(), 16 + 2 * qb + rows * 4);
|
||||
assert_eq!(
|
||||
u32::from_le_bytes(expected[0..4].try_into().unwrap()),
|
||||
0x35314f51
|
||||
);
|
||||
assert_eq!(&expected[4..8], &(rows as u32).to_le_bytes());
|
||||
assert_eq!(&expected[8..12], &(columns as u32).to_le_bytes());
|
||||
assert_eq!(
|
||||
&expected[12..16],
|
||||
&0u32.to_le_bytes(),
|
||||
"native-math activation admission"
|
||||
);
|
||||
let nativeq = &expected[16..16 + qb];
|
||||
let candidateq = &expected[16 + qb..16 + 2 * qb];
|
||||
assert_eq!(
|
||||
candidateq, nativeq,
|
||||
"all independently quantized Q8 bytes {stem}"
|
||||
);
|
||||
if pattern == 1 {
|
||||
for block in nativeq.as_chunks::<36>().0.iter() {
|
||||
assert_eq!(&block[..4], &[0, 0x3c, 0, 0]);
|
||||
assert_eq!(&block[4..8], &[127, 129, 1, 255]);
|
||||
assert!(block[8..].iter().all(|&v| v == 0));
|
||||
}
|
||||
}
|
||||
if pattern == 2 || pattern == 3 {
|
||||
for block in nativeq.as_chunks::<36>().0.iter() {
|
||||
assert_eq!(&block[..2], &[0, 0]);
|
||||
assert_eq!(&block[2..4], if pattern == 3 { &[0, 128] } else { &[0, 0] });
|
||||
assert!(block[4..].iter().all(|&v| v == 0));
|
||||
}
|
||||
}
|
||||
if pattern == 7 {
|
||||
for word in expected[16 + 2 * qb..].as_chunks::<4>().0.iter() {
|
||||
assert_eq!(
|
||||
f32::from_le_bytes(*word),
|
||||
959104.0 * (columns / 256) as f32,
|
||||
"independent hand projection"
|
||||
);
|
||||
}
|
||||
}
|
||||
let dw = upload(ctx, &w);
|
||||
let dx = upload(ctx, &xb);
|
||||
let sentinel = vec![0xa5; rows * 4];
|
||||
let mut dy = upload(ctx, &sentinel);
|
||||
let charged = ctx.allocated_bytes();
|
||||
ctx.q5_k_q8_1(&dw, &dx, &mut dy, Q5KProjectionShape { rows, columns })
|
||||
.expect("safe resident public projection");
|
||||
let actual = read(&dy);
|
||||
compare_output(&actual, &expected[16 + 2 * qb..]);
|
||||
assert_eq!(read(&dw), w, "compressed weights immutable");
|
||||
assert_eq!(read(&dx), xb, "resident activation immutable");
|
||||
assert_eq!(ctx.allocated_bytes(), charged, "healthy temporary cleanup");
|
||||
// Repeat proves the public cache path and stable ownership, against the SAME
|
||||
// frozen native result, not a first candidate run used as a baseline.
|
||||
ctx.q5_k_q8_1(&dw, &dx, &mut dy, Q5KProjectionShape { rows, columns })
|
||||
.unwrap();
|
||||
compare_output(&read(&dy), &expected[16 + 2 * qb..]);
|
||||
fs::write(root.join(format!("{stem}.actual")), &actual).unwrap();
|
||||
dw.release().unwrap();
|
||||
dx.release().unwrap();
|
||||
dy.release().unwrap();
|
||||
assert_eq!(ctx.allocated_bytes(), 0);
|
||||
println!(
|
||||
"Q5_NATIVE PASS {stem} q8_bytes={qb} outputs={rows} exactbits=true repeat=true cleanup=0"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "requires installed NVIDIA GPU, pinned independent native fixture and explicit private evidence root"]
|
||||
fn installed_driver_q5_native_parity() {
|
||||
assert_eq!(std::env::var("LELEKA_CUDA_REAL_GPU").as_deref(), Ok("1"));
|
||||
let root = PathBuf::from(std::env::var("LELEKA_Q5_EVIDENCE").unwrap());
|
||||
let native = PathBuf::from(std::env::var("LELEKA_Q5_NATIVE_ORACLE").unwrap());
|
||||
let ptx = PathBuf::from(std::env::var("LELEKA_Q5_TRUSTED_PTX").unwrap());
|
||||
assert!(root.is_absolute() && native.is_absolute() && ptx.is_absolute());
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
let driver = Driver::load().unwrap();
|
||||
let device = driver.device(0).unwrap();
|
||||
let ctx = device.create_context(1 << 20).unwrap();
|
||||
for rows in [1, 3, 4, 5] {
|
||||
for columns in [256, 512, 2048, 2560, 6144] {
|
||||
run_case(&ctx, &root, &native, &ptx, rows, columns, 0);
|
||||
}
|
||||
}
|
||||
for pattern in 1..=6 {
|
||||
run_case(&ctx, &root, &native, &ptx, 5, 6144, pattern);
|
||||
}
|
||||
for pattern in 7..=9 {
|
||||
run_case(&ctx, &root, &native, &ptx, 3, 256, pattern);
|
||||
}
|
||||
ctx.close().unwrap();
|
||||
println!(
|
||||
"Q5_PARITY_SUMMARY cases=29 public_launches=58 q8_exact=true outputs_exact=true context_close=ok"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "requires installed NVIDIA driver, explicit opt-in"]
|
||||
fn installed_driver_q5_numeric_refusals() {
|
||||
assert_eq!(std::env::var("LELEKA_CUDA_REAL_GPU").as_deref(), Ok("1"));
|
||||
let driver = Driver::load().unwrap();
|
||||
let device = driver.device(0).unwrap();
|
||||
let ctx = device.create_context(1 << 20).unwrap();
|
||||
let w = oracle::weights(1, 256, 0);
|
||||
let dw = upload(&ctx, &w);
|
||||
let sentinel = vec![0xa5; 4];
|
||||
let mut dy = upload(&ctx, &sentinel);
|
||||
let cases = [
|
||||
("nan", f32::NAN),
|
||||
("positive_inf", f32::INFINITY),
|
||||
("negative_inf", f32::NEG_INFINITY),
|
||||
("half_sum_overflow", 4096.0),
|
||||
("scale_overflow", f32::MAX),
|
||||
("flushed_nonzero_divisor", f32::MIN_POSITIVE),
|
||||
];
|
||||
for (name, value) in cases {
|
||||
let mut x = vec![0.0; 256];
|
||||
if name == "half_sum_overflow" {
|
||||
x[..32].fill(value);
|
||||
} else {
|
||||
x[0] = value;
|
||||
}
|
||||
let xb = oracle::f32bytes(&x);
|
||||
let dx = upload(&ctx, &xb);
|
||||
let charged = ctx.allocated_bytes();
|
||||
assert_eq!(
|
||||
ctx.q5_k_q8_1(
|
||||
&dw,
|
||||
&dx,
|
||||
&mut dy,
|
||||
Q5KProjectionShape {
|
||||
rows: 1,
|
||||
columns: 256
|
||||
}
|
||||
),
|
||||
Err(Error::InvalidQ8Activation),
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(read(&dy), sentinel, "{name} output untouched");
|
||||
assert_eq!(read(&dx), xb);
|
||||
assert_eq!(ctx.allocated_bytes(), charged);
|
||||
ctx.synchronize().unwrap();
|
||||
dx.release().unwrap();
|
||||
println!("Q5_REFUSAL PASS {name} output_unchanged=true healthy=true");
|
||||
}
|
||||
dw.release().unwrap();
|
||||
dy.release().unwrap();
|
||||
assert_eq!(ctx.allocated_bytes(), 0);
|
||||
ctx.close().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "one explicitly selected private Qwen Q5_K tensor; synthetic activation; no model-forward claim"]
|
||||
fn installed_driver_q5_real_tensor_component() {
|
||||
assert_eq!(std::env::var("LELEKA_CUDA_REAL_GPU").as_deref(), Ok("1"));
|
||||
let root = PathBuf::from(std::env::var("LELEKA_Q5_EVIDENCE").unwrap());
|
||||
let input = PathBuf::from(std::env::var("LELEKA_Q5_REAL_INPUT").unwrap());
|
||||
let native = PathBuf::from(std::env::var("LELEKA_Q5_NATIVE_ORACLE").unwrap());
|
||||
let ptx = PathBuf::from(std::env::var("LELEKA_Q5_TRUSTED_PTX").unwrap());
|
||||
assert!(root.is_absolute() && input.is_absolute() && native.is_absolute() && ptx.is_absolute());
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
let data = fs::read(&input).unwrap();
|
||||
let (m, n) = (640usize, 2560usize);
|
||||
let wb = m * (n / 256) * 176;
|
||||
let xb = n * 4;
|
||||
let qb = n / 32 * 36;
|
||||
assert_eq!(data.len(), 12 + wb + xb);
|
||||
assert_eq!(&data[..4], &0x35314b51u32.to_le_bytes());
|
||||
assert_eq!(&data[4..8], &(m as u32).to_le_bytes());
|
||||
assert_eq!(&data[8..12], &(n as u32).to_le_bytes());
|
||||
// Synthetic activation must equal our independent deterministic input,
|
||||
// rather than a captured request or an arbitrary external fixture.
|
||||
assert_eq!(
|
||||
&data[12 + wb..],
|
||||
oracle::f32bytes(&oracle::activation(n, 0))
|
||||
);
|
||||
let result = root.join("real-qwen-q5.native");
|
||||
let out = Command::new("timeout")
|
||||
.args(["--signal=TERM", "--kill-after=5", "30"])
|
||||
.arg(native)
|
||||
.arg(&input)
|
||||
.arg(&result)
|
||||
.arg(ptx)
|
||||
.output()
|
||||
.unwrap();
|
||||
fs::write(root.join("real-qwen-q5.stdout"), &out.stdout).unwrap();
|
||||
fs::write(root.join("real-qwen-q5.stderr"), &out.stderr).unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
let expected = fs::read(result).unwrap();
|
||||
assert_eq!(expected.len(), 16 + 2 * qb + m * 4);
|
||||
assert_eq!(&expected[..4], &0x35314f51u32.to_le_bytes());
|
||||
assert_eq!(&expected[12..16], &0u32.to_le_bytes());
|
||||
assert_eq!(
|
||||
&expected[16..16 + qb],
|
||||
&expected[16 + qb..16 + 2 * qb],
|
||||
"separate fresh Q8 bytes"
|
||||
);
|
||||
let driver = Driver::load().unwrap();
|
||||
let device = driver.device(0).unwrap();
|
||||
let ctx = device.create_context(8 << 20).unwrap();
|
||||
let w = upload(&ctx, &data[12..12 + wb]);
|
||||
let x = upload(&ctx, &data[12 + wb..]);
|
||||
let mut y = upload(&ctx, &vec![0xa5; m * 4]);
|
||||
let resident = ctx.allocated_bytes();
|
||||
for _ in 0..2 {
|
||||
ctx.q5_k_q8_1(
|
||||
&w,
|
||||
&x,
|
||||
&mut y,
|
||||
Q5KProjectionShape {
|
||||
rows: m,
|
||||
columns: n,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
compare_output(&read(&y), &expected[16 + 2 * qb..]);
|
||||
assert_eq!(ctx.allocated_bytes(), resident);
|
||||
}
|
||||
assert_eq!(read(&w), data[12..12 + wb]);
|
||||
assert_eq!(read(&x), data[12 + wb..]);
|
||||
fs::write(root.join("real-qwen-q5.actual"), read(&y)).unwrap();
|
||||
w.release().unwrap();
|
||||
x.release().unwrap();
|
||||
y.release().unwrap();
|
||||
assert_eq!(ctx.allocated_bytes(), 0);
|
||||
ctx.close().unwrap();
|
||||
println!(
|
||||
"Q5_REAL_COMPONENT PASS tensor=blk.4.ffn_up_shexp.weight rows=640 columns=2560 packed_bytes=1126400 q8_bytes=2880 outputs=640 exactbits=true repeat=true synthetic_activation=true cleanup=0 scope=single_projection"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
#![cfg(all(
|
||||
feature = "cuda-driver",
|
||||
target_os = "linux",
|
||||
target_pointer_width = "64"
|
||||
))]
|
||||
use leleka_cuda_driver::{Driver, Error, Q5KProjectionShape};
|
||||
use std::{fs, path::PathBuf, process::Command};
|
||||
#[derive(Debug)]
|
||||
struct Row {
|
||||
stage: String,
|
||||
code: i32,
|
||||
current: usize,
|
||||
depth: usize,
|
||||
charged: usize,
|
||||
bytes: usize,
|
||||
}
|
||||
fn trace() -> Vec<Row> {
|
||||
fs::read_to_string(std::env::var("MOCK_CUDA_TRACE").unwrap())
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.map(|l| {
|
||||
let v: Vec<_> = l.split_whitespace().collect();
|
||||
assert_eq!(v.len(), 7);
|
||||
Row {
|
||||
stage: v[0].into(),
|
||||
code: v[1].parse().unwrap(),
|
||||
current: v[2].parse().unwrap(),
|
||||
depth: v[3].parse().unwrap(),
|
||||
charged: v[5].parse().unwrap(),
|
||||
bytes: v[6].parse().unwrap(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn count(rows: &[Row], name: &str) -> usize {
|
||||
rows.iter().filter(|r| r.stage == name).count()
|
||||
}
|
||||
fn driver_codes(e: &Error) -> Vec<i32> {
|
||||
match e {
|
||||
Error::Driver { code, .. } => vec![*code],
|
||||
Error::Multiple { primary, secondary } => {
|
||||
let mut c = driver_codes(primary);
|
||||
c.extend(driver_codes(secondary));
|
||||
c
|
||||
}
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
const CASES: &[&str] = &[
|
||||
"success",
|
||||
"small_tail",
|
||||
"large_boundary",
|
||||
"bounds",
|
||||
"sizes",
|
||||
"context",
|
||||
"budget",
|
||||
"nan",
|
||||
"inf",
|
||||
"sum_overflow",
|
||||
"load",
|
||||
"second_lookup",
|
||||
"null_module",
|
||||
"null_function",
|
||||
"quant_launch",
|
||||
"projection_launch",
|
||||
"quant_sync",
|
||||
"projection_sync",
|
||||
"quant_restore",
|
||||
"projection_restore",
|
||||
"free",
|
||||
"unload",
|
||||
];
|
||||
#[test]
|
||||
#[ignore = "isolated CPU ELF protocol fixture only, no GPU arithmetic claim"]
|
||||
fn isolated_q5_protocol_matrix() {
|
||||
assert_eq!(
|
||||
std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(),
|
||||
Ok("1")
|
||||
);
|
||||
let root = PathBuf::from(std::env::var("LELEKA_CUDA_Q5_MOCK_ROOT").unwrap());
|
||||
assert!(root.is_absolute());
|
||||
for case in CASES {
|
||||
let mut c = Command::new(std::env::current_exe().unwrap());
|
||||
c.args(["--exact", "q5_fixture_child", "--ignored", "--nocapture"])
|
||||
.env("LELEKA_Q5_CASE", case)
|
||||
.env("MOCK_CUDA_TRACE", root.join(format!("trace-q5-{case}")))
|
||||
.env("LD_LIBRARY_PATH", root.join("q5"))
|
||||
.env("MOCK_CUDA_VECTOR", "1")
|
||||
.env_remove("MOCK_CUDA_FAIL")
|
||||
.env_remove("MOCK_CUDA_Q5_FAIL")
|
||||
.env_remove("MOCK_CUDA_NULL_LOAD")
|
||||
.env_remove("MOCK_CUDA_NULL_FUNCTION");
|
||||
match *case {
|
||||
"load" | "free" | "unload" => {
|
||||
c.env("MOCK_CUDA_FAIL", case);
|
||||
}
|
||||
"second_lookup" => {
|
||||
c.env("MOCK_CUDA_FAIL", "lookup:2");
|
||||
}
|
||||
"null_module" => {
|
||||
c.env("MOCK_CUDA_NULL_LOAD", "1");
|
||||
}
|
||||
"null_function" => {
|
||||
c.env("MOCK_CUDA_NULL_FUNCTION", "1");
|
||||
}
|
||||
v if v.starts_with("quant_") || v.starts_with("projection_") => {
|
||||
c.env("MOCK_CUDA_Q5_FAIL", v);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let out = c.output().unwrap();
|
||||
fs::write(root.join(format!("q5-{case}.stdout")), &out.stdout).unwrap();
|
||||
fs::write(root.join(format!("q5-{case}.stderr")), &out.stderr).unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{case}\n{}\n{}",
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
println!("Q5_MOCK PASS {case}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "only invoked by isolated_q5_protocol_matrix"]
|
||||
fn q5_fixture_child() {
|
||||
assert_eq!(
|
||||
std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(),
|
||||
Ok("1")
|
||||
);
|
||||
let case = std::env::var("LELEKA_Q5_CASE").unwrap();
|
||||
assert!(CASES.contains(&case.as_str()));
|
||||
let (m, n) = match case.as_str() {
|
||||
"small_tail" => (5, 512),
|
||||
"large_boundary" => (3, 2048),
|
||||
_ => (1, 256),
|
||||
};
|
||||
let wb = m * (n / 256) * 176;
|
||||
let xb = n * 4;
|
||||
let ob = m * 4;
|
||||
let resident = wb + xb + ob;
|
||||
let driver = Driver::load().unwrap();
|
||||
let device = driver.device(0).unwrap();
|
||||
let ctx = device
|
||||
.create_context(if case == "budget" { resident } else { 16384 })
|
||||
.unwrap();
|
||||
let mut w = ctx.allocate(wb).unwrap();
|
||||
w.copy_from(&vec![0; wb]).unwrap();
|
||||
let mut x = ctx.allocate(xb).unwrap();
|
||||
let mut input = vec![0; xb];
|
||||
let v = match case.as_str() {
|
||||
"nan" => f32::NAN,
|
||||
"inf" => f32::INFINITY,
|
||||
"sum_overflow" => 4096.0,
|
||||
_ => 1.0,
|
||||
};
|
||||
for word in input.as_chunks_mut::<4>().0.iter_mut() {
|
||||
word.copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
x.copy_from(&input).unwrap();
|
||||
let mut y = ctx.allocate(ob).unwrap();
|
||||
let sentinel = vec![0xa5; ob];
|
||||
y.copy_from(&sentinel).unwrap();
|
||||
let before = trace().len();
|
||||
let shape = Q5KProjectionShape {
|
||||
rows: m,
|
||||
columns: n,
|
||||
};
|
||||
if case == "bounds" {
|
||||
for shape in [
|
||||
Q5KProjectionShape {
|
||||
rows: 0,
|
||||
columns: 256,
|
||||
},
|
||||
Q5KProjectionShape {
|
||||
rows: 1,
|
||||
columns: 0,
|
||||
},
|
||||
Q5KProjectionShape {
|
||||
rows: 1,
|
||||
columns: 255,
|
||||
},
|
||||
Q5KProjectionShape {
|
||||
rows: 1,
|
||||
columns: 257,
|
||||
},
|
||||
Q5KProjectionShape {
|
||||
rows: usize::MAX,
|
||||
columns: 256,
|
||||
},
|
||||
Q5KProjectionShape {
|
||||
rows: 1,
|
||||
columns: usize::MAX,
|
||||
},
|
||||
Q5KProjectionShape {
|
||||
rows: i32::MAX as usize + 1,
|
||||
columns: 256,
|
||||
},
|
||||
] {
|
||||
assert_eq!(
|
||||
ctx.q5_k_q8_1(&w, &x, &mut y, shape),
|
||||
Err(Error::InvalidQ5KProjectionShape)
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
trace().len(),
|
||||
before,
|
||||
"structural admission before native mutation"
|
||||
);
|
||||
} else if case == "sizes" {
|
||||
for which in 0..3 {
|
||||
let mut short = ctx
|
||||
.allocate(if which == 0 {
|
||||
wb - 1
|
||||
} else if which == 1 {
|
||||
xb - 1
|
||||
} else {
|
||||
ob - 1
|
||||
})
|
||||
.unwrap();
|
||||
let mark = trace().len();
|
||||
let r = match which {
|
||||
0 => ctx.q5_k_q8_1(&short, &x, &mut y, shape),
|
||||
1 => ctx.q5_k_q8_1(&w, &short, &mut y, shape),
|
||||
_ => ctx.q5_k_q8_1(&w, &x, &mut short, shape),
|
||||
};
|
||||
assert_eq!(r, Err(Error::InvalidQ5KProjectionShape));
|
||||
assert_eq!(trace().len(), mark);
|
||||
short.release().unwrap();
|
||||
}
|
||||
} else if case == "context" {
|
||||
let other = device.create_context(2048).unwrap();
|
||||
let otherx = other.allocate(xb).unwrap();
|
||||
let mark = trace().len();
|
||||
assert_eq!(
|
||||
ctx.q5_k_q8_1(&w, &otherx, &mut y, shape),
|
||||
Err(Error::ContextMismatch)
|
||||
);
|
||||
assert_eq!(trace().len(), mark);
|
||||
otherx.release().unwrap();
|
||||
other.close().unwrap();
|
||||
} else {
|
||||
let result = ctx.q5_k_q8_1(&w, &x, &mut y, shape);
|
||||
match case.as_str() {
|
||||
"success" | "small_tail" | "large_boundary" => {
|
||||
result.unwrap();
|
||||
assert_eq!(ctx.allocated_bytes(), resident);
|
||||
ctx.q5_k_q8_1(&w, &x, &mut y, shape).unwrap();
|
||||
let rows = trace();
|
||||
assert_eq!(count(&rows, "module_q5"), 1);
|
||||
assert_eq!(count(&rows, "lookup_quant"), 1);
|
||||
assert_eq!(count(&rows, "lookup_projection"), 1);
|
||||
assert_eq!(count(&rows, "q5_quant_complete"), 2);
|
||||
assert_eq!(count(&rows, "q5_projection_complete"), 2);
|
||||
assert!(
|
||||
rows.iter()
|
||||
.filter(|r| r.stage == "q5_projection_launch")
|
||||
.all(|r| r.bytes == if n < 2048 { m.div_ceil(4) } else { m })
|
||||
);
|
||||
}
|
||||
"budget" => {
|
||||
assert_eq!(result, Err(Error::BudgetExceeded));
|
||||
assert_eq!(trace().len(), before);
|
||||
}
|
||||
"nan" | "inf" | "sum_overflow" => {
|
||||
assert_eq!(result, Err(Error::InvalidQ8Activation));
|
||||
assert_eq!(ctx.allocated_bytes(), resident);
|
||||
assert_eq!(count(&trace(), "q5_projection_launch"), 0);
|
||||
ctx.synchronize().unwrap();
|
||||
}
|
||||
"unload" => {
|
||||
result.unwrap();
|
||||
}
|
||||
"null_module" | "null_function" => {
|
||||
assert!(matches!(result, Err(Error::InvalidDriverValue(_))));
|
||||
assert_eq!(count(&trace(), "q5_projection_launch"), 0);
|
||||
}
|
||||
"quant_sync" | "projection_sync" | "quant_restore" | "projection_restore" => {
|
||||
assert!(driver_codes(&result.unwrap_err()).contains(&700));
|
||||
assert!(
|
||||
ctx.allocated_bytes() > resident,
|
||||
"uncertain scratch stays charged"
|
||||
);
|
||||
let mark = trace().len();
|
||||
assert_eq!(ctx.synchronize(), Err(Error::ContextPoisoned));
|
||||
assert_eq!(trace().len(), mark);
|
||||
}
|
||||
_ => {
|
||||
assert!(driver_codes(&result.unwrap_err()).contains(&700));
|
||||
if case != "free" && case != "unload" {
|
||||
assert_eq!(ctx.allocated_bytes(), resident);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let poisoned = [
|
||||
"quant_sync",
|
||||
"projection_sync",
|
||||
"quant_restore",
|
||||
"projection_restore",
|
||||
]
|
||||
.contains(&case.as_str());
|
||||
if !poisoned {
|
||||
if [
|
||||
"bounds",
|
||||
"sizes",
|
||||
"context",
|
||||
"budget",
|
||||
"nan",
|
||||
"inf",
|
||||
"sum_overflow",
|
||||
"load",
|
||||
"second_lookup",
|
||||
"null_module",
|
||||
"null_function",
|
||||
"quant_launch",
|
||||
]
|
||||
.contains(&case.as_str())
|
||||
{
|
||||
let mut data = vec![0; ob];
|
||||
y.copy_to(&mut data).unwrap();
|
||||
assert_eq!(data, sentinel, "refusal did not publish output");
|
||||
}
|
||||
let mut data = vec![0; xb];
|
||||
x.copy_to(&mut data).unwrap();
|
||||
assert_eq!(data, input);
|
||||
w.release().unwrap();
|
||||
x.release().unwrap();
|
||||
y.release().unwrap();
|
||||
} else {
|
||||
drop(w);
|
||||
drop(x);
|
||||
drop(y);
|
||||
}
|
||||
let close = ctx.close();
|
||||
if case == "unload" {
|
||||
assert!(driver_codes(&close.unwrap_err()).contains(&700));
|
||||
} else {
|
||||
close.unwrap();
|
||||
}
|
||||
let rows = trace();
|
||||
assert_eq!(
|
||||
count(&rows, "destroy"),
|
||||
if case == "context" { 2 } else { 1 }
|
||||
);
|
||||
assert_eq!(count(&rows, "unsafe_q5_pending_free"), 0);
|
||||
assert_eq!(count(&rows, "unsafe_pending_unload"), 0);
|
||||
if !poisoned {
|
||||
assert_eq!(rows.last().unwrap().charged, 0);
|
||||
for r in rows.iter().filter(|r| r.stage == "pop" && r.code == 0) {
|
||||
assert_eq!(r.current, 0x11);
|
||||
assert_eq!(r.depth, 0);
|
||||
}
|
||||
}
|
||||
println!("Q5_CHILD {case} owned_cleanup=consumed numeric_proof=mock_only");
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/* Test-only protocol oracle: reuse existing owned-byte fixture unchanged.
|
||||
This mock proves routing/lifetime/refusals, NOT GPU arithmetic parity. */
|
||||
#define cuModuleLoadData old_load
|
||||
#define cuModuleGetFunction old_get
|
||||
#define cuModuleUnload old_unload
|
||||
#define cuLaunchKernel old_launch
|
||||
#define cuCtxSynchronize old_sync
|
||||
#define cuCtxDestroy_v2 old_destroy
|
||||
#define cuCtxPopCurrent_v2 old_pop
|
||||
#define cuMemFree_v2 old_free
|
||||
#include "mock_cuda.c"
|
||||
#undef cuModuleLoadData
|
||||
#undef cuModuleGetFunction
|
||||
#undef cuModuleUnload
|
||||
#undef cuLaunchKernel
|
||||
#undef cuCtxSynchronize
|
||||
#undef cuCtxDestroy_v2
|
||||
#undef cuCtxPopCurrent_v2
|
||||
#undef cuMemFree_v2
|
||||
#include <math.h>
|
||||
static void **qargs;
|
||||
static uint64_t qp[3];
|
||||
static uint32_t qrows,qcols;
|
||||
static int qkind;
|
||||
static int restore_fault;
|
||||
static int qfail(const char*name){const char*v=getenv("MOCK_CUDA_Q5_FAIL");return v&&!strcmp(v,name);}
|
||||
static int exact_q5_image(const char *image){
|
||||
const char*path=getenv("MOCK_CUDA_Q5_PTX");if(!path)return 0;FILE*f=fopen(path,"rb");if(!f)return 0;fseek(f,0,SEEK_END);long n=ftell(f);rewind(f);if(n<=0||n>262144){fclose(f);return 0;}char*p=malloc((size_t)n+1);if(!p)abort();if(fread(p,1,n,f)!=(size_t)n)abort();p[n]=0;int ok=strcmp(p,image)==0;free(p);fclose(f);return ok;
|
||||
}
|
||||
static void qcomplete(void){
|
||||
if(!qargs)return;
|
||||
for(size_t i=0;i<3;i++)if(*(uint64_t*)qargs[i]!=qp[i])abort();
|
||||
if(*(uint32_t*)qargs[3]!=(qkind==1?qcols:qrows))abort();
|
||||
if(qkind==2&&*(uint32_t*)qargs[4]!=qcols)abort();
|
||||
if(qkind==1){
|
||||
float*x=(float*)(uintptr_t)qp[0];unsigned char*q=(unsigned char*)(uintptr_t)qp[1];uint32_t*s=(uint32_t*)(uintptr_t)qp[2];
|
||||
for(uint32_t b=0;b<qcols/32;b++){float a=0,sum=0;int bad=0;for(unsigned i=0;i<32;i++){float v=x[b*32+i];if(!isfinite(v)){bad=1;continue;}a=fmaxf(a,fabsf(v));sum+=v;}float d=a/127.0f;
|
||||
if(bad)*s|=1;else if((a!=0&&d==0)||!isfinite(d)||fabsf(d)>=65520||!isfinite(sum)||fabsf(sum)>=65520)*s|=2;
|
||||
/* Delayed write proves arguments/scratch survive completion. Math is NOT
|
||||
the native half/reduction oracle; successful mock scratch is synthetic. */
|
||||
memset(q+b*36,0,36);
|
||||
} trace("q5_quant_complete",0,qcols);
|
||||
}else{float*y=(float*)(uintptr_t)qp[2];for(uint32_t r=0;r<qrows;r++)y[r]=17.0f+(float)r;trace("q5_projection_complete",0,qrows);}
|
||||
qargs=NULL;for(size_t i=0;i<16;i++)check_canary(i);
|
||||
}
|
||||
CUresult cuCtxSynchronize(void){if(fault(7))return 700;if(require_context())return 201;int attempted=qargs!=NULL;
|
||||
if(attempted&&qfail(qkind==1?"quant_sync":"projection_sync")){trace("sync",700,0);return 700;}
|
||||
qcomplete();if(attempted&&qfail(qkind==1?"quant_restore":"projection_restore"))restore_fault=1;
|
||||
complete_pending();trace("sync",0,0);return 0;}
|
||||
CUresult cuCtxPopCurrent_v2(CUcontext*out){if(restore_fault){restore_fault=0;trace("pop",700,0);return 700;}return old_pop(out);}
|
||||
CUresult cuMemFree_v2(CUdeviceptr ptr){if(qargs&&(ptr==qp[0]||ptr==qp[1]||ptr==qp[2])){trace("unsafe_q5_pending_free",1,0);abort();}return old_free(ptr);}
|
||||
CUresult cuCtxDestroy_v2(CUcontext c){qcomplete();return old_destroy(c);}
|
||||
CUresult cuModuleLoadData(void **out,const void*image){
|
||||
const char*p=image;if(!p||!strstr(p,"leleka_quantize_q8_1"))return old_load(out,image);
|
||||
if(fault(12))return 700;if(require_context())return 201;if(!exact_q5_image(p))return 218;
|
||||
if(getenv("MOCK_CUDA_NULL_LOAD")){*out=NULL;trace("load_null",0,0);return 0;}
|
||||
if(next_module>=16)return 2;size_t i=next_module++;modules[i].handle=(void*)(uintptr_t)(0x100+i);modules[i].function=(void*)(uintptr_t)(0x200+i);modules[i].owner=current;modules[i].matvec=2;*out=modules[i].handle;trace("load",0,0);trace("module_q5",0,i);return 0;
|
||||
}
|
||||
CUresult cuModuleGetFunction(void**out,void*mod,const char*name){
|
||||
for(size_t i=0;i<16;i++)if(modules[i].handle==mod&&modules[i].matvec==2){
|
||||
if(fault(13))return 700;if(require_context()||modules[i].owner!=current)return 201;
|
||||
if(getenv("MOCK_CUDA_NULL_FUNCTION")){*out=NULL;trace("lookup_null",0,0);return 0;}
|
||||
int quant=!strcmp(name,"leleka_quantize_q8_1"),proj=!strcmp(name,"leleka_q5_k_q8_1");if(!quant&&!proj)return 201;
|
||||
*out=(void*)(uintptr_t)((quant?0x200:0x300)+i);trace("lookup",0,0);trace(quant?"lookup_quant":"lookup_projection",0,0);return 0;
|
||||
}return old_get(out,mod,name);
|
||||
}
|
||||
CUresult cuModuleUnload(void*mod){if(qargs){trace("unsafe_pending_unload",1,0);abort();}return old_unload(mod);}
|
||||
static int heap_arg(void*p,uintptr_t stackaddr){uintptr_t a=(uintptr_t)p;return a&&(a<stackaddr-1048576||a>stackaddr+1048576);}
|
||||
CUresult cuLaunchKernel(void*f,unsigned gx,unsigned gy,unsigned gz,unsigned bx,unsigned by,unsigned bz,unsigned shared,void*stream,void**args,void**extra){
|
||||
int kind=0;for(size_t i=0;i<16;i++)if(modules[i].matvec==2&&modules[i].owner==current){if(f==(void*)(uintptr_t)(0x200+i))kind=1;if(f==(void*)(uintptr_t)(0x300+i))kind=2;}
|
||||
if(!kind)return old_launch(f,gx,gy,gz,bx,by,bz,shared,stream,args,extra);
|
||||
if(require_context()||!args||extra||stream||shared||gy!=1||gz!=1||bz!=1)return 201;uintptr_t sp=(uintptr_t)&kind;
|
||||
if(!heap_arg(args,sp))abort();for(size_t i=0;i<(kind==1?4u:5u);i++)if(!heap_arg(args[i],sp))abort();
|
||||
uint32_t rows=kind==1?0:*(uint32_t*)args[3],cols=*(uint32_t*)args[kind==1?3:4];if(!cols||cols%256)return 1;
|
||||
if(kind==1){if(bx!=256||by!=1||gx!=(cols+255ull)/256)return 1;}
|
||||
else{if(!rows||bx!=32||by!=4||gx!=(cols<2048?(rows+3ull)/4:rows))return 1;}
|
||||
for(size_t i=0;i<3;i++)qp[i]=*(uint64_t*)args[i];
|
||||
size_t qbytes=(size_t)cols/32*36;
|
||||
if(kind==1){if(!lookup(qp[0],(size_t)cols*4)||!lookup(qp[1],qbytes)||!lookup(qp[2],4))return 1;}
|
||||
else{if(!lookup(qp[0],(size_t)rows*(cols/256)*176)||!lookup(qp[1],qbytes)||!lookup(qp[2],(size_t)rows*4))return 1;}
|
||||
if(qp[0]==qp[1]||qp[0]==qp[2]||qp[1]==qp[2])return 1;
|
||||
qkind=kind;qargs=args;qrows=rows;qcols=cols;trace(kind==1?"q5_quant_launch":"q5_projection_launch",0,gx);trace("q5_columns",0,cols);trace("q5_rows",0,rows);
|
||||
if(fault(15)||qfail(kind==1?"quant_launch":"projection_launch")){trace("launch",700,kind);return 700;}trace("launch",0,kind);return 0;
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
// Independent GGUF Q5_K layout/hand oracle. No production decoder/PTX imports.
|
||||
// General native fast-math numerical parity is measured on the GPU separately.
|
||||
#![allow(dead_code)]
|
||||
pub fn half(bits: u16) -> f32 {
|
||||
let sign = ((bits & 0x8000) as u32) << 16;
|
||||
let e = (bits >> 10) & 31;
|
||||
let f = bits & 1023;
|
||||
if e == 0 {
|
||||
let x = f as f32 * (1.0 / 16_777_216.0);
|
||||
if sign == 0 { x } else { -x }
|
||||
} else {
|
||||
f32::from_bits(
|
||||
sign | if e == 31 {
|
||||
0x7f800000 | ((f as u32) << 13)
|
||||
} else {
|
||||
((e as u32 + 112) << 23) | ((f as u32) << 13)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
pub fn scale_min(scales: &[u8], group: usize) -> (u8, u8) {
|
||||
assert!(scales.len() == 12 && group < 8);
|
||||
if group < 4 {
|
||||
(scales[group] & 63, scales[group + 4] & 63)
|
||||
} else {
|
||||
(
|
||||
(scales[group + 4] & 15) | ((scales[group - 4] >> 6) << 4),
|
||||
(scales[group + 4] >> 4) | ((scales[group] >> 6) << 4),
|
||||
)
|
||||
}
|
||||
}
|
||||
pub fn pack_scale_min(scales: &mut [u8], group: usize, scale: u8, min: u8) {
|
||||
assert!(scale < 64 && min < 64 && group < 8);
|
||||
if group < 4 {
|
||||
scales[group] |= scale;
|
||||
scales[group + 4] |= min;
|
||||
} else {
|
||||
scales[group + 4] |= (scale & 15) | ((min & 15) << 4);
|
||||
scales[group - 4] |= (scale >> 4) << 6;
|
||||
scales[group] |= (min >> 4) << 6;
|
||||
}
|
||||
}
|
||||
pub fn code(block: &[u8], i: usize) -> u8 {
|
||||
assert!(block.len() == 176 && i < 256);
|
||||
let group = i / 32;
|
||||
let lane = i % 32;
|
||||
let low = (block[48 + (group / 2) * 32 + lane] >> (4 * (group % 2))) & 15;
|
||||
low | (((block[16 + lane] >> group) & 1) << 4)
|
||||
}
|
||||
pub fn scalar(block: &[u8], i: usize) -> f32 {
|
||||
let (s, m) = scale_min(&block[4..16], i / 32);
|
||||
half(u16::from_le_bytes(block[0..2].try_into().unwrap())) * s as f32 * code(block, i) as f32
|
||||
- half(u16::from_le_bytes(block[2..4].try_into().unwrap())) * m as f32
|
||||
}
|
||||
pub fn weights(rows: usize, columns: usize, pattern: usize) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for row in 0..rows {
|
||||
for k in 0..columns / 256 {
|
||||
let mut b = [0u8; 176];
|
||||
// Exactly representable halves; row/block vary independently.
|
||||
b[0..2].copy_from_slice(&0x3000u16.to_le_bytes()); // 1/8
|
||||
b[2..4].copy_from_slice(&0x2800u16.to_le_bytes()); // 1/32
|
||||
for g in 0..8 {
|
||||
pack_scale_min(
|
||||
&mut b[4..16],
|
||||
g,
|
||||
((g * 9 + row * 7 + k * 3 + 1) % 64) as u8,
|
||||
((g * 13 + row * 3 + k * 5) % 64) as u8,
|
||||
);
|
||||
}
|
||||
for i in 0..256 {
|
||||
let g = i / 32;
|
||||
let lane = i % 32;
|
||||
let q = ((i * 7 + row * 11 + k * 17 + pattern * 5) % 32) as u8;
|
||||
b[48 + (g / 2) * 32 + lane] |= (q & 15) << (4 * (g % 2));
|
||||
b[16 + lane] |= (q >> 4) << g;
|
||||
}
|
||||
if pattern == 7 {
|
||||
b.fill(0);
|
||||
b[0..2].copy_from_slice(&0x3c00u16.to_le_bytes());
|
||||
b[2..4].copy_from_slice(&0x3800u16.to_le_bytes());
|
||||
for g in 0..8 {
|
||||
pack_scale_min(&mut b[4..16], g, 2, 3);
|
||||
for lane in 0..32 {
|
||||
let q = (g * 4 + lane % 4) as u8;
|
||||
b[48 + (g / 2) * 32 + lane] |= (q & 15) << (4 * (g % 2));
|
||||
b[16 + lane] |= (q >> 4) << g;
|
||||
}
|
||||
}
|
||||
} else if pattern == 8 {
|
||||
b[0..2].copy_from_slice(&0x7c00u16.to_le_bytes());
|
||||
} else if pattern == 9 {
|
||||
b[0..2].copy_from_slice(&0x7e00u16.to_le_bytes());
|
||||
}
|
||||
out.extend_from_slice(&b);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
pub fn activation(n: usize, pattern: usize) -> Vec<f32> {
|
||||
(0..n)
|
||||
.map(|i| match pattern {
|
||||
0 => ((i * 37 % 251) as i32 - 125) as f32 * 0.03125,
|
||||
1 => match i % 32 {
|
||||
0 => 127.0,
|
||||
1 => -127.0,
|
||||
2 => 0.5,
|
||||
3 => -0.5,
|
||||
_ => 0.0,
|
||||
},
|
||||
2 => 0.0,
|
||||
3 => -0.0,
|
||||
4 => {
|
||||
if i % 2 == 0 {
|
||||
1000.0
|
||||
} else {
|
||||
-1000.0
|
||||
}
|
||||
}
|
||||
5 => {
|
||||
if i % 2 == 0 {
|
||||
1.0 / 1_048_576.0
|
||||
} else {
|
||||
-1.0 / 1_048_576.0
|
||||
}
|
||||
}
|
||||
6 => match i % 32 {
|
||||
0 => 65504.0,
|
||||
1 => -65504.0,
|
||||
_ => 0.0,
|
||||
},
|
||||
7 => 127.0,
|
||||
8 | 9 => ((i * 37 % 251) as i32 - 125) as f32 * 0.03125,
|
||||
_ => unreachable!(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
pub fn f32bytes(x: &[f32]) -> Vec<u8> {
|
||||
x.iter().flat_map(|v| v.to_le_bytes()).collect()
|
||||
}
|
||||
#[test]
|
||||
fn packed_layout_independent_hand_oracle() {
|
||||
assert_eq!(half(0x3c00), 1.0);
|
||||
assert_eq!(half(0x3000), 0.125);
|
||||
assert_eq!(half(0x0001).to_bits(), 0x33800000);
|
||||
assert_eq!(half(0x8000).to_bits(), 0x80000000);
|
||||
let mut scales = [0u8; 12];
|
||||
let pairs = [
|
||||
(0, 63),
|
||||
(1, 32),
|
||||
(15, 16),
|
||||
(16, 15),
|
||||
(31, 1),
|
||||
(32, 0),
|
||||
(48, 48),
|
||||
(63, 63),
|
||||
];
|
||||
for (g, (s, m)) in pairs.into_iter().enumerate() {
|
||||
pack_scale_min(&mut scales, g, s, m);
|
||||
}
|
||||
// Recorded packed words derived from the GGUF six-bit layout, not decoder output.
|
||||
assert_eq!(scales, [64, 129, 207, 208, 63, 32, 208, 207, 31, 0, 0, 255]);
|
||||
for (g, pair) in pairs.into_iter().enumerate() {
|
||||
assert_eq!(scale_min(&scales, g), pair);
|
||||
}
|
||||
let mut b = [0u8; 176];
|
||||
b[0..2].copy_from_slice(&0x3c00u16.to_le_bytes());
|
||||
b[2..4].copy_from_slice(&0x3800u16.to_le_bytes());
|
||||
for g in 0..8 {
|
||||
pack_scale_min(&mut b[4..16], g, 2, 3);
|
||||
for lane in 0..32 {
|
||||
let q = (g * 4 + lane % 4) as u8;
|
||||
b[48 + (g / 2) * 32 + lane] |= (q & 15) << (4 * (g % 2));
|
||||
b[16 + lane] |= (q >> 4) << g;
|
||||
}
|
||||
}
|
||||
for i in 0..256 {
|
||||
let expected = (i / 32 * 4 + i % 4) as u8;
|
||||
assert_eq!(code(&b, i), expected);
|
||||
assert_eq!(scalar(&b, i), 2.0 * expected as f32 - 1.5);
|
||||
}
|
||||
// A constant d=1, scale=2, min=3, dmin=.5 block dot ones is exactly 7552.
|
||||
let hand: f32 = (0..256).map(|i| scalar(&b, i)).sum();
|
||||
assert_eq!(hand, 7552.0);
|
||||
}
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
# Test-only bounded native reference; no serving/model build or GPU execution.
|
||||
# TOOLKIT must be the verified deploy/cuda-toolkit.lock.json 13.0.88 distribution.
|
||||
set -euo pipefail
|
||||
[[ $# == 2 ]] || { echo 'Usage: build-cuda-q5-oracle.sh TOOLKIT PRIVATE_OUTPUT' >&2; exit 2; }
|
||||
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
toolkit="$(cd "$1" && pwd)"
|
||||
output="$2"
|
||||
[[ ! -e "$output" && -f "$toolkit/TOOLKIT-PROVENANCE.json" ]]
|
||||
"$toolkit/bin/nvcc" --version | grep 'V13.0.88'
|
||||
python3 - "$toolkit/TOOLKIT-PROVENANCE.json" "$root/deploy/cuda-toolkit.lock.json" <<'PY'
|
||||
import json,sys
|
||||
assert json.load(open(sys.argv[1]))['lock']==json.load(open(sys.argv[2]))
|
||||
PY
|
||||
# Exact native source identity is an oracle gate, not caller-selected reference.
|
||||
echo 'f2fc636e5e8f6db9bbb8146fbf2b78a717c0e0076bf8c72ac2b784df7b3f455f engine/strata/src/kernels/cuda/native_mmvq.cu' | (cd "$root" && sha256sum --check)
|
||||
sha256sum "$root/engine/strata/src/kernels/cuda/native_mmvq.cu" "$root/scripts/cuda-q5-oracle/native_fixture.cu"
|
||||
"$toolkit/bin/nvcc" -std=c++17 -O3 -arch=sm_120 --use_fast_math \
|
||||
-Xcompiler=-ffunction-sections,-fdata-sections -Xlinker=--gc-sections \
|
||||
-I"$root/engine/strata/include" "$root/engine/strata/src/kernels/cuda/native_mmvq.cu" \
|
||||
"$root/scripts/cuda-q5-oracle/native_fixture.cu" -ldl -o "$output"
|
||||
sha256sum "$output"
|
||||
@@ -0,0 +1,77 @@
|
||||
# Independent Q5_K projection oracle
|
||||
|
||||
Test-only fixtures for STRA-142. They do not run a model forward pass, measure
|
||||
performance, or install a Toolkit on the GPU server. Production uses its existing
|
||||
owned CUDA Driver boundary and embedded PTX.
|
||||
|
||||
## Reference and independent expectations
|
||||
|
||||
`native_fixture.cu` links the **unchanged** imported
|
||||
`engine/strata/src/kernels/cuda/native_mmvq.cu` (SHA-256
|
||||
`f2fc636e5e8f6db9bbb8146fbf2b78a717c0e0076bf8c72ac2b784df7b3f455f`).
|
||||
The native source is pinned through `c3020b71ba6cc49a81d8b374c29dd3be36fe239c`
|
||||
and attributed to llama.cpp `3cf03257f219afbe7334045ff7c6a06ac68c627d`.
|
||||
Its source/MIT notice is preserved; no quantizer or projection implementation is
|
||||
copied into this test runner.
|
||||
|
||||
Build with verified CUDA 13.0.88, `-arch=sm_120 --use_fast_math -O3`.
|
||||
`--use_fast_math` is essential: FTZ, approximate division and contraction are the
|
||||
native baseline. Function/data sections and linker garbage collection remove
|
||||
unused format dispatch references without editing the original translation unit.
|
||||
`scripts/prepare-cuda-q5-oracle-toolkit.py PRIVATE_OUTPUT` fetches only the six
|
||||
hash-pinned compiler/runtime components in `deploy/cuda-toolkit.lock.json`, verifies
|
||||
the manifest and archive hashes, and records the selection. BLAS is not needed.
|
||||
`scripts/build-cuda-q5-oracle.sh TOOLKIT PRIVATE_ELF` refuses an existing output,
|
||||
checks the native source hash, and compiles the bounded reference. Build in a
|
||||
GPU-hidden isolated Linux amd64 CPU container; preserve its actual architecture,
|
||||
compiler versions, exact commands, source hashes and ELF hash as evidence.
|
||||
|
||||
The native runner accepts a private input file: three little-endian u32 words
|
||||
(magic `0x35314b51`, M, N), exactly `M*(N/256)*176` packed bytes, then `4*N` bytes
|
||||
of finite F32 activation. Bounds are `1 <= M <= 640`, `256 <= N <= 6144`, N%256=0.
|
||||
It quantizes one native scratch allocation, then calls `native_q5_k_f32` with a
|
||||
**second fresh native scratch** and checks those native bytes agree. Neither
|
||||
native call receives candidate scratch. Separately it loads the trusted candidate
|
||||
asset and launches only `leleka_quantize_q8_1` in the private test Driver boundary.
|
||||
All allocations, stream and module are consumed on success; errors terminate the
|
||||
isolated process. Original native quantization is never fed nonfinite inputs.
|
||||
|
||||
Output has four LE u32 words (magic `0x35314f51`, M, N, candidate admission status),
|
||||
then native Q8 bytes, candidate Q8 bytes, and native F32 output bits. These are
|
||||
separate assertions: every Q8 byte must match; finite/zero/Inf outputs require
|
||||
identical bits; NaN outputs require NaN classification. No tolerance is calibrated
|
||||
from candidate results.
|
||||
|
||||
`tests/q5_oracle.rs` independently constructs/decodes GGUF six-bit scales/minima,
|
||||
high bits and nibbles; its packed words and exact scalar dot are recorded hand
|
||||
expectations. It does not import a production decoder. The GPU hand case uses
|
||||
constant activation 127: native d8=1 and original-input sums are exact, yielding
|
||||
959104 per Q5 block. CPU scalar arithmetic is supplementary and does not redefine
|
||||
native fast-math output.
|
||||
|
||||
## Executable gates
|
||||
|
||||
- `tests/q5_gpu.rs`: installed-driver opt-in tests. The standard test covers
|
||||
M=1/3/4/5 × N=256/512/2048/2560/6144, ties away from zero, signed zeros,
|
||||
cancellation, half-scale underflow, FP16 range, hand arithmetic and nonfinite
|
||||
weight halves. Public calls repeat against the frozen native result, verify
|
||||
immutable caller inputs and zero remaining temporary charge. Six numeric
|
||||
refusal cases exercise the native status path and preserve caller output.
|
||||
- Its separate real-tensor test accepts only the explicitly selected Qwen
|
||||
`blk.4.ffn_up_shexp.weight` 640×2560 private fixture and our deterministic
|
||||
synthetic activation. This proves one projection, not model quality or forward
|
||||
execution. Packed weights stay outside Git.
|
||||
- `tests/q5_mock.rs` / `q5_mock_cuda.c`: independent CPU ELF routing, geometry,
|
||||
admission, cache, delayed argument ownership, sync/restore poison, and consuming
|
||||
cleanup proof. The existing fixture is included unchanged. Synthetic mock
|
||||
scratch/output arithmetic is **not** the native numerical oracle.
|
||||
- `test-cuda-driver-bootstrap.sh` preserves the complete existing CPU gate and
|
||||
adds the focused Q5 matrix and an output-alias compile refusal.
|
||||
|
||||
GPU tests require `LELEKA_CUDA_REAL_GPU=1`, use one test thread and a bounded outer
|
||||
`timeout`. The parity test additionally requires absolute private paths in
|
||||
`LELEKA_Q5_EVIDENCE`, `LELEKA_Q5_NATIVE_ORACLE`, `LELEKA_Q5_TRUSTED_PTX`.
|
||||
The real-tensor test also requires `LELEKA_Q5_REAL_INPUT`. Fixture subprocesses have
|
||||
30-second deadlines. Capture stdout/stderr/exits and hardware/driver/pre-post GPU
|
||||
state, retain private digests and remove only owned remote resources. Ordinary
|
||||
`cargo test` leaves these GPU tests ignored.
|
||||
@@ -0,0 +1,46 @@
|
||||
// Independent test-only runner. Compile the ORIGINAL native_mmvq.cu unchanged.
|
||||
// Does not decode native weights, share candidate scratch, or select arbitrary entries.
|
||||
#include "strata/kernels/native_mmvq.hpp"
|
||||
#include <cuda_runtime.h>
|
||||
#include <cuda.h>
|
||||
#include <dlfcn.h>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <vector>
|
||||
#include <stdexcept>
|
||||
#include <iostream>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <cmath>
|
||||
static void ck(cudaError_t e){if(e!=cudaSuccess)throw std::runtime_error(cudaGetErrorString(e));}
|
||||
static void dc(CUresult e){if(e!=CUDA_SUCCESS)throw std::runtime_error("Driver test fixture status "+std::to_string(e));}
|
||||
template<class T> static T sym(void* lib,const char* name){void* p=dlsym(lib,name);if(!p)throw std::runtime_error(name);return reinterpret_cast<T>(p);}
|
||||
int main(int argc,char**argv) try {
|
||||
if(argc!=4)throw std::runtime_error("Usage: native_fixture INPUT OUTPUT TRUSTED_Q5_PTX");
|
||||
std::ifstream in(argv[1],std::ios::binary);uint32_t h[3];in.read(reinterpret_cast<char*>(h),sizeof h);
|
||||
if(!in||h[0]!=0x35314b51||h[1]<1||h[1]>640||h[2]<256||h[2]>6144||h[2]%256)throw std::runtime_error("bounded synthetic geometry");
|
||||
const auto m=h[1],n=h[2];size_t wb=size_t(m)*(n/256)*176,qb=size_t(n/32)*36;
|
||||
std::vector<unsigned char>w(wb),q(qb),fresh(qb),candidate(qb);std::vector<float>x(n),y(m);
|
||||
in.read(reinterpret_cast<char*>(w.data()),wb);in.read(reinterpret_cast<char*>(x.data()),n*4);if(!in||in.peek()!=EOF)throw std::runtime_error("fixture length");
|
||||
// Invalid activation is tested in Rust/candidate admission; never feed it into
|
||||
// the original unchecked native float-to-integer quantizer.
|
||||
for(float v:x)if(!std::isfinite(v))throw std::runtime_error("native fixture requires finite input");
|
||||
ck(cudaSetDevice(0));cudaStream_t stream;ck(cudaStreamCreate(&stream));void *dw,*dx,*dq,*df,*dcq,*dy,*ds;
|
||||
ck(cudaMalloc(&dw,wb));ck(cudaMalloc(&dx,n*4));ck(cudaMalloc(&dq,qb));ck(cudaMalloc(&df,qb));ck(cudaMalloc(&dcq,qb));ck(cudaMalloc(&dy,m*4));ck(cudaMalloc(&ds,4));
|
||||
ck(cudaMemcpy(dw,w.data(),wb,cudaMemcpyHostToDevice));ck(cudaMemcpy(dx,x.data(),n*4,cudaMemcpyHostToDevice));
|
||||
strata::kernels::native_quantize_q8_1(static_cast<float*>(dx),dq,n,1,stream);ck(cudaStreamSynchronize(stream));ck(cudaMemcpy(q.data(),dq,qb,cudaMemcpyDeviceToHost));
|
||||
// Composition independently quantizes a second fresh native scratch allocation.
|
||||
strata::kernels::native_q5_k_f32(dw,static_cast<float*>(dx),df,static_cast<float*>(dy),n,m,1,stream);ck(cudaStreamSynchronize(stream));
|
||||
ck(cudaMemcpy(fresh.data(),df,qb,cudaMemcpyDeviceToHost));ck(cudaMemcpy(y.data(),dy,m*4,cudaMemcpyDeviceToHost));if(q!=fresh)throw std::runtime_error("fresh native quantization disagrees");
|
||||
std::ifstream pt(argv[3],std::ios::binary);std::string ptx((std::istreambuf_iterator<char>(pt)),{});if(ptx.empty()||ptx.size()>262144)throw std::runtime_error("bounded trusted test asset");ptx.push_back(0);
|
||||
void* lib=dlopen("libcuda.so.1",RTLD_NOW|RTLD_LOCAL);if(!lib)throw std::runtime_error("installed Driver missing");
|
||||
auto load=sym<CUresult(*)(CUmodule*,const void*)>(lib,"cuModuleLoadData");auto get=sym<CUresult(*)(CUfunction*,CUmodule,const char*)>(lib,"cuModuleGetFunction");
|
||||
auto launch=sym<CUresult(*)(CUfunction,unsigned,unsigned,unsigned,unsigned,unsigned,unsigned,unsigned,CUstream,void**,void**)>(lib,"cuLaunchKernel");auto unload=sym<CUresult(*)(CUmodule)>(lib,"cuModuleUnload");
|
||||
CUmodule mod;CUfunction f;dc(load(&mod,ptx.data()));dc(get(&f,mod,"leleka_quantize_q8_1"));ck(cudaMemset(ds,0,4));
|
||||
CUdeviceptr px=reinterpret_cast<CUdeviceptr>(dx),pq=reinterpret_cast<CUdeviceptr>(dcq),ps=reinterpret_cast<CUdeviceptr>(ds);uint32_t cols=n;void*args[]={&px,&pq,&ps,&cols};
|
||||
dc(launch(f,(n+255)/256,1,1,256,1,1,0,reinterpret_cast<CUstream>(stream),args,nullptr));ck(cudaStreamSynchronize(stream));
|
||||
uint32_t status;ck(cudaMemcpy(&status,ds,4,cudaMemcpyDeviceToHost));ck(cudaMemcpy(candidate.data(),dcq,qb,cudaMemcpyDeviceToHost));dc(unload(mod));dlclose(lib);
|
||||
std::ofstream out(argv[2],std::ios::binary);uint32_t oh[]={0x35314f51,m,n,status};out.write(reinterpret_cast<char*>(oh),sizeof oh);out.write(reinterpret_cast<char*>(q.data()),qb);out.write(reinterpret_cast<char*>(candidate.data()),qb);out.write(reinterpret_cast<char*>(y.data()),m*4);if(!out)throw std::runtime_error("output write");
|
||||
for(void*p:{dw,dx,dq,df,dcq,dy,ds})ck(cudaFree(p));ck(cudaStreamDestroy(stream));ck(cudaDeviceReset());
|
||||
std::cout<<"NATIVE_ORACLE rows="<<m<<" columns="<<n<<" q8_bytes="<<qb<<" status="<<status<<" independent_scratch=true cleanup=ok\n";return 0;
|
||||
} catch(const std::exception&e){std::cerr<<e.what()<<'\n';return 1;}
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build-only six-component pinned toolkit, no BLAS/model/GPU/runtime installation."""
|
||||
import importlib.util,json,os,pathlib,sys,tempfile,hashlib
|
||||
root=pathlib.Path(__file__).resolve().parents[1]
|
||||
spec=importlib.util.spec_from_file_location('cuda_bootstrap',root/'scripts/bootstrap-cuda-toolkit.py')
|
||||
b=importlib.util.module_from_spec(spec);spec.loader.exec_module(b)
|
||||
assert len(sys.argv)==2
|
||||
out=pathlib.Path(sys.argv[1]).absolute();assert not out.exists();out.parent.mkdir(parents=True,exist_ok=True)
|
||||
lock=json.loads((root/'deploy/cuda-toolkit.lock.json').read_text());os.umask(0o077)
|
||||
with tempfile.TemporaryDirectory(prefix='.q5-toolkit-',dir=out.parent) as td:
|
||||
stage=pathlib.Path(td);prefix=stage/'toolkit';prefix.mkdir()
|
||||
manifest=stage/'manifest.json';b.download(lock['manifest_url'],manifest,lock['manifest_sha256'],1024**2)
|
||||
b.validate_lock(lock,json.loads(manifest.read_text()))
|
||||
components=[x for x in lock['components'] if x['component']!='libcublas'];assert len(components)==6
|
||||
for item in components:
|
||||
archive=stage/(item['component']+'.tar.xz');size=int(item['size'])
|
||||
b.download(b.BASE+item['relative_path'],archive,item['sha256'],size,size)
|
||||
tree=b.extract(archive,stage,pathlib.Path(item['relative_path']).name.removesuffix('.tar.xz'))
|
||||
for child in tree.iterdir():
|
||||
if child.is_dir() and not child.is_symlink():b.merge(child,prefix/child.name)
|
||||
else:
|
||||
license_dir=prefix/'licenses'/item['component'];license_dir.mkdir(parents=True,exist_ok=True);b.merge(child,license_dir/child.name)
|
||||
print(json.dumps(item),flush=True)
|
||||
(prefix/'lib64').symlink_to('lib',target_is_directory=True)
|
||||
for p in prefix.rglob('*'):
|
||||
if p.is_symlink():assert p.resolve().is_relative_to(prefix) and p.exists()
|
||||
(prefix/'TOOLKIT-PROVENANCE.json').write_text(json.dumps({'lock':lock,'selected_components':[x['component'] for x in components],'scope':'independent Q5 oracle/offline PTX only; no BLAS'},indent=2)+'\n')
|
||||
prefix.rename(out)
|
||||
print('Prepared '+str(out))
|
||||
@@ -53,6 +53,13 @@ if [[ "${1:-}" == --inside ]]; then
|
||||
LELEKA_CUDA_MOCK_HARNESS=1 LELEKA_CUDA_MOCK_ROOT="$work" \
|
||||
cargo test --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver \
|
||||
--features cuda-driver --test mock_driver -- --exact isolated_cpu_elf_matrix --ignored --test-threads=1 --nocapture
|
||||
mkdir -p "$work/q5"
|
||||
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -ffp-contract=off -fno-fast-math -shared -fPIC \
|
||||
"${repo_root}/crates/cuda-driver/tests/q5_mock_cuda.c" -lm -o "$work/q5/libcuda.so.1"
|
||||
MOCK_CUDA_Q5_PTX="${repo_root}/crates/cuda-driver/src/q5_k_q8_1.ptx" \
|
||||
LELEKA_CUDA_MOCK_HARNESS=1 LELEKA_CUDA_Q5_MOCK_ROOT="$work" \
|
||||
cargo test --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver \
|
||||
--features cuda-driver --test q5_mock -- --exact isolated_q5_protocol_matrix --ignored --test-threads=1 --nocapture
|
||||
rlib="$(find "$work/target/debug/deps" -maxdepth 1 -name 'libleleka_cuda_driver-*.rlib' -print -quit)"
|
||||
[[ -n "$rlib" ]]
|
||||
# Independent negative compile gates: lifetimes/auto-traits cannot escape FFI ownership.
|
||||
@@ -104,6 +111,14 @@ RS
|
||||
"$work/reject.rs" -o "$work/reject" 2>"$work/reject.log"; then echo 'matvec output alias escaped' >&2; exit 1; fi
|
||||
grep -q 'cannot borrow.*buffer.*as mutable because it is also borrowed as immutable' "$work/reject.log"
|
||||
echo 'matvec output alias compile refusal: PASS'
|
||||
cat > "$work/reject.rs" <<'RSQ5'
|
||||
use leleka_cuda_driver::{Driver,Q5KProjectionShape};
|
||||
fn main(){let d=Driver::load().unwrap();let c=d.device(0).unwrap().create_context(4096).unwrap();let mut w=c.allocate(176).unwrap();let x=c.allocate(1024).unwrap();c.q5_k_q8_1(&w,&x,&mut w,Q5KProjectionShape{rows:1,columns:256}).unwrap();}
|
||||
RSQ5
|
||||
if rustc --edition=2024 --extern "leleka_cuda_driver=$rlib" -L "dependency=$work/target/debug/deps" \
|
||||
"$work/reject.rs" -o "$work/reject" 2>"$work/reject.log"; then echo 'Q5 output alias escaped' >&2; exit 1; fi
|
||||
grep -q 'cannot borrow.*w.*as mutable because it is also borrowed as immutable' "$work/reject.log"
|
||||
echo 'Q5 output alias compile refusal: PASS'
|
||||
cargo tree --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --edges normal
|
||||
exit 0
|
||||
fi
|
||||
|
||||
Reference in New Issue
Block a user