diff --git a/crates/cuda-driver/src/ffi.rs b/crates/cuda-driver/src/ffi.rs index 06c51dac..effdd9b5 100644 --- a/crates/cuda-driver/src/ffi.rs +++ b/crates/cuda-driver/src/ffi.rs @@ -7,13 +7,27 @@ //! verification evidence only and is not a production dependency. Do not infer //! a fixed export ABI from the newer alias. -use crate::{Error, Result}; +use crate::{Error, FixedOperation, Result}; #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) struct ContextHandle(usize); #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) struct BufferHandle(u64); +impl BufferHandle { + pub(crate) fn validate_extent(self, bytes: usize) -> Result<()> { + let bytes = u64::try_from(bytes).map_err(|_| Error::InvalidMatvecShape)?; + if self.0 == 0 || bytes == 0 || self.0.checked_add(bytes).is_none() { + return Err(Error::InvalidMatvecShape); + } + Ok(()) + } + #[cfg(test)] + pub(crate) fn synthetic(address: u64) -> Self { + Self(address) + } +} + #[derive(Clone, Copy)] pub(crate) struct ModuleHandle(usize); #[derive(Clone, Copy)] @@ -64,6 +78,55 @@ impl Drop for LaunchArguments { } } +struct MatvecStorage { + addresses: [u64; 3], + rows: u32, + columns: u32, + parameters: [*mut std::ffi::c_void; 5], +} +// Only this NonNull owner moves. No reference/Box is recreated while the +// self-referential field pointers may be read by the native launch. +pub(crate) struct MatvecArguments { + storage: std::ptr::NonNull, +} +impl MatvecArguments { + pub(crate) fn new( + matrix: BufferHandle, + vector: BufferHandle, + output: BufferHandle, + rows: u32, + columns: u32, + ) -> Self { + let storage = Box::into_raw(Box::new(MatvecStorage { + addresses: [matrix.0, vector.0, output.0], + rows, + columns, + parameters: [std::ptr::null_mut(); 5], + })); + // SAFETY: stable uniquely raw-owned allocation; raw projections avoid + // retagging the storage through a new Box or whole-allocation borrow. + 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 MatvecArguments { + fn drop(&mut self) { + // SAFETY: reconstructed exactly once before launch or after successful + // completion. The caller permanently forgets this owner on sync fault. + unsafe { + drop(Box::from_raw(self.storage.as_ptr())); + } + } +} + #[cfg(all( feature = "cuda-driver", target_os = "linux", @@ -106,6 +169,7 @@ mod enabled { *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(); type MemcpyDtoHV2 = unsafe extern "C" fn(*mut c_void, CuDevicePtr, usize) -> CuResult; struct Library(*mut c_void); @@ -146,81 +210,82 @@ mod enabled { Err(Error::Driver { operation, code }) } } + // 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) } + }}; + } impl Api { pub(crate) fn load() -> Result { - // SAFETY: a fixed NUL-terminated soname, no caller-provided paths; - // immediate local symbol resolution, with null checked before use. + // 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); } - let library = Library(handle); - macro_rules! symbol { - ($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) } - }}; - } - let init = symbol!(c"cuInit", Init); - let version = symbol!(c"cuDriverGetVersion", DriverGetVersion); - let device = symbol!(c"cuDeviceGet", DeviceGet); - let create = symbol!(c"cuCtxCreate_v2", ContextCreateV2); - let destroy = symbol!(c"cuCtxDestroy_v2", ContextDestroyV2); - let push = symbol!(c"cuCtxPushCurrent_v2", ContextPushCurrentV2); - let pop = symbol!(c"cuCtxPopCurrent_v2", ContextPopCurrentV2); - let synchronize = symbol!(c"cuCtxSynchronize", ContextSynchronize); - let allocate = symbol!(c"cuMemAlloc_v2", MemAllocV2); - let free = symbol!(c"cuMemFree_v2", MemFreeV2); - let copy_from = symbol!(c"cuMemcpyHtoD_v2", MemcpyHtoDV2); - let copy_to = symbol!(c"cuMemcpyDtoH_v2", MemcpyDtoHV2); - let load_module = symbol!(c"cuModuleLoadData", ModuleLoadData); - let get_function = symbol!(c"cuModuleGetFunction", ModuleGetFunction); - let unload_module = symbol!(c"cuModuleUnload", ModuleUnload); - let launch_kernel = symbol!(c"cuLaunchKernel", LaunchKernel); + Self::resolve(Library(handle)) + } + fn resolve(library: Library) -> Result { + // 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), + 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), + 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, - init, - version, - device, - create, - destroy, - push, - pop, - synchronize, - allocate, - free, - copy_from, - copy_to, - load_module, - get_function, - unload_module, - launch_kernel, }) } - pub(crate) fn load_fixed_module(&self) -> Result { + pub(crate) fn load_fixed_module(&self, operation: FixedOperation) -> Result { 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, FIXED_PTX.as_ptr().cast()) + (self.load_module)( + &mut module, + match operation { + FixedOperation::VectorAdd => FIXED_PTX, + FixedOperation::Matvec => MATVEC_PTX, + } + .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) -> Result { + pub(crate) fn fixed_function( + &self, + module: ModuleHandle, + operation: FixedOperation, + ) -> Result { let mut function = std::ptr::null_mut(); // SAFETY: live private module in current owner context; fixed C // entry name; valid writable opaque function output. @@ -228,7 +293,11 @@ mod enabled { (self.get_function)( &mut function, module.0 as *mut c_void, - c"leleka_vector_add_f32".as_ptr(), + match operation { + FixedOperation::VectorAdd => c"leleka_vector_add_f32", + FixedOperation::Matvec => c"leleka_matvec_f32", + } + .as_ptr(), ) })?; if function.is_null() { @@ -272,6 +341,33 @@ mod enabled { ) }) } + + 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 init(&self) -> Result<()> { // SAFETY: resolved exact ABI, mandated zero flags, live library. check("cuInit", unsafe { (self.init)(0) }) @@ -385,10 +481,14 @@ impl Api { Err(Error::Disabled) } } - pub(crate) fn load_fixed_module(&self) -> Result { + pub(crate) fn load_fixed_module(&self, _: FixedOperation) -> Result { Err(Error::UnsupportedPlatform) } - pub(crate) fn fixed_function(&self, module: ModuleHandle) -> Result { + pub(crate) fn fixed_function( + &self, + module: ModuleHandle, + _: FixedOperation, + ) -> Result { let _ = module.0; Err(Error::UnsupportedPlatform) } @@ -405,6 +505,16 @@ impl Api { let _ = (function.0, arguments.storage); Err(Error::UnsupportedPlatform) } + + pub(crate) fn launch_matvec( + &self, + function: FunctionHandle, + _: u32, + arguments: &mut MatvecArguments, + ) -> 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) @@ -443,3 +553,48 @@ impl Api { Err(Error::UnsupportedPlatform) } } + +#[cfg(test)] +mod tests { + 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::(), expected); + } + assert_eq!(*(*pointer).parameters[3].cast::(), 129); + assert_eq!(*(*pointer).parameters[4].cast::(), u32::MAX); + } + } +} diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index ce3b5440..8e4529f8 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -28,6 +28,7 @@ pub enum Error { }, ContextMismatch, InvalidVectorShape, + InvalidMatvecShape, OutputAliasesInput, InvalidOrdinal, InvalidSize, @@ -45,14 +46,46 @@ pub enum Error { }, } +impl Error { + fn environment_message(&self) -> Option<&'static str> { + Some(match self { + Self::Disabled => "CUDA Driver feature is disabled", + Self::UnsupportedPlatform => "CUDA Driver requires Linux with 64-bit pointers", + Self::LibraryUnavailable => "cannot load libcuda.so.1", + Self::InvalidOrdinal => "device ordinal must be nonnegative", + Self::HostAllocation => "cannot allocate owned host staging memory", + Self::ContextPoisoned => { + "context is poisoned after uncertain completion or restoration" + } + Self::UnexpectedContext => "CUDA pop returned a different context", + _ => return None, + }) + } + fn validation_message(&self) -> Option<&'static str> { + Some(match self { + Self::ContextMismatch => "buffers must belong to this exact context", + Self::InvalidVectorShape => { + "vector shape must be nonempty f32 bytes with a bounded u32 count/grid" + } + Self::InvalidMatvecShape => { + "matvec requires exact nonempty bounded row-major f32 shapes" + } + Self::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::Disabled => f.write_str("CUDA Driver feature is disabled"), - Self::UnsupportedPlatform => { - f.write_str("CUDA Driver requires Linux with 64-bit pointers") - } - Self::LibraryUnavailable => f.write_str("cannot load libcuda.so.1"), Self::MissingSymbol(symbol) => write!(f, "missing CUDA Driver symbol {symbol}"), Self::InvalidDriverValue(operation) => { write!(f, "{operation} returned an invalid handle on success") @@ -60,27 +93,13 @@ impl fmt::Display for Error { Self::Driver { operation, code } => { write!(f, "{operation} failed with CUDA code {code}") } - Self::ContextMismatch => { - f.write_str("vector buffers must belong to this exact context") - } - Self::InvalidVectorShape => { - f.write_str("vector shape must be nonempty f32 bytes with a bounded u32 count/grid") - } - Self::OutputAliasesInput => f.write_str("vector output must not alias an input"), - Self::InvalidOrdinal => f.write_str("device ordinal must be nonnegative"), - Self::InvalidSize => f.write_str("byte size must be nonzero and fit isize"), - Self::BudgetExceeded => f.write_str("allocation exceeds context byte budget"), Self::ShapeMismatch { expected, actual } => { write!(f, "byte shape mismatch: expected {expected}, got {actual}") } - Self::HostAllocation => f.write_str("cannot allocate owned host staging memory"), - Self::ContextPoisoned => { - f.write_str("context is poisoned after uncertain completion or restoration") - } - Self::UnexpectedContext => f.write_str("CUDA pop returned a different context"), Self::Multiple { primary, secondary } => { write!(f, "{primary}; subsequent error: {secondary}") } + _ => unreachable!("static errors have a message"), } } } @@ -163,7 +182,8 @@ impl<'driver> Device<'driver> { budget: byte_budget, allocated: Cell::new(0), poisoned: Cell::new(false), - kernel: Cell::new(None), + vector_add_kernel: Cell::new(None), + matvec_kernel: Cell::new(None), }) } } @@ -175,7 +195,8 @@ pub struct Context<'driver> { budget: usize, allocated: Cell, poisoned: Cell, - kernel: Cell>, + vector_add_kernel: Cell>, + matvec_kernel: Cell>, } #[derive(Clone, Copy)] struct FixedKernel { @@ -183,6 +204,67 @@ struct FixedKernel { function: ffi::FunctionHandle, } +// Closed selector: callers cannot choose executable bytes, names or geometry. +#[derive(Clone, Copy)] +enum FixedOperation { + VectorAdd, + Matvec, +} + +#[derive(Debug, PartialEq, Eq)] +struct MatvecShape { + matrix_bytes: usize, + vector_bytes: usize, + output_bytes: usize, + rows: u32, + columns: u32, + grid: u32, +} +fn matvec_shape(rows: usize, columns: usize) -> Result { + let rows_abi = u32::try_from(rows).map_err(|_| Error::InvalidMatvecShape)?; + let columns_abi = u32::try_from(columns).map_err(|_| Error::InvalidMatvecShape)?; + let bytes = |elements: Option| -> Result { + let bytes = elements + .and_then(|v| v.checked_mul(4)) + .ok_or(Error::InvalidMatvecShape)?; + valid_size(bytes).map_err(|_| Error::InvalidMatvecShape)?; + Ok(bytes) + }; + let matrix_bytes = bytes(rows.checked_mul(columns))?; + let vector_bytes = bytes(Some(columns))?; + let output_bytes = bytes(Some(rows))?; + let grid = u64::from(rows_abi).div_ceil(128); + if grid == 0 || grid > i32::MAX as u64 { + return Err(Error::InvalidMatvecShape); + } + Ok(MatvecShape { + matrix_bytes, + vector_bytes, + output_bytes, + rows: rows_abi, + columns: columns_abi, + grid: u32::try_from(grid).map_err(|_| Error::InvalidMatvecShape)?, + }) +} + +fn matvec_allocations( + matrix: Option, + vector: Option, + output: Option, + shape: &MatvecShape, +) -> Result<(ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle)> { + let matrix = matrix.ok_or(Error::ContextPoisoned)?; + let vector = vector.ok_or(Error::ContextPoisoned)?; + let output = output.ok_or(Error::ContextPoisoned)?; + if matrix == output || vector == output { + return Err(Error::OutputAliasesInput); + } + matrix.validate_extent(shape.matrix_bytes)?; + vector.validate_extent(shape.vector_bytes)?; + output.validate_extent(shape.output_bytes)?; + Ok((matrix, vector, output)) +} + // Wider integer arithmetic also covers the final partial block at u32::MAX. fn vector_shape(bytes: usize) -> Result<(u32, u32)> { if valid_size(bytes).is_err() || !bytes.is_multiple_of(4) { @@ -261,6 +343,28 @@ impl Context<'_> { b: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { + let (handles, count, grid) = self.vector_admission(a, b, output)?; + let [a_handle, b_handle, out_handle] = handles; + // Establish the owned parameter addresses after their stable heap + // placement, before any native mutation. No caller host data is used. + let mut arguments = ffi::LaunchArguments::new(a_handle, b_handle, out_handle, count); + let guard = self.enter()?; + let kernel = match self.fixed_kernel(FixedOperation::VectorAdd) { + Ok(kernel) => kernel, + Err(error) => return combine(Err(error), guard.finish()), + }; + let launch = self + .driver + .api + .launch(kernel.function, grid, &mut arguments); + self.complete_launch(launch, arguments, guard) + } + fn vector_admission( + &self, + a: &DeviceBuffer<'_>, + b: &DeviceBuffer<'_>, + output: &DeviceBuffer<'_>, + ) -> Result<([ffi::BufferHandle; 3], u32, u32)> { if self.poisoned.get() { return Err(Error::ContextPoisoned); } @@ -280,38 +384,98 @@ impl Context<'_> { if a_handle == out_handle || b_handle == out_handle { return Err(Error::OutputAliasesInput); } - // 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); + Ok(([a_handle, b_handle, out_handle], count, grid)) + } + fn complete_launch( + &self, + launch: Result<()>, + arguments: T, + guard: CurrentGuard<'_, '_>, + ) -> Result<()> { + // A launch error may describe earlier asynchronous work. Synchronize + // every attempted launch; preserve launch/sync/pop error order. + let sync = self.driver.api.synchronize(); + if sync.is_err() { + self.poisoned.set(true); + // 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()) + } + /// 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() { + 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(kernel.function, grid, &mut arguments); - // A launch error can describe earlier asynchronous work. Synchronize - // after EVERY attempted launch; preserve launch/sync/pop error order. - let sync = self.driver.api.synchronize(); - if sync.is_err() { - self.poisoned.set(true); - // Both boxed scalars and their pointer table may still be read. - // One poisoned context admits no further launch or explicit frees. - std::mem::forget(arguments); - } - combine(combine(launch, sync), guard.finish()) + .launch_matvec(kernel.function, shape.grid, &mut arguments); + self.complete_launch(launch, arguments, guard) } - fn fixed_kernel(&self) -> Result { - if let Some(kernel) = self.kernel.get() { + fn matvec_admission( + &self, + buffers: [&DeviceBuffer<'_>; 3], + rows: usize, + columns: usize, + ) -> Result<(MatvecShape, [ffi::BufferHandle; 3])> { + let [matrix, vector, output] = buffers; + if self.poisoned.get() || self.handle.is_none() { + return Err(Error::ContextPoisoned); + } + if !std::ptr::eq(self, matrix.context) + || !std::ptr::eq(self, vector.context) + || !std::ptr::eq(self, output.context) + { + return Err(Error::ContextMismatch); + } + let shape = matvec_shape(rows, columns)?; + if matrix.bytes != shape.matrix_bytes + || vector.bytes != shape.vector_bytes + || output.bytes != shape.output_bytes + { + return Err(Error::InvalidMatvecShape); + } + let handles = matvec_allocations(matrix.handle, vector.handle, output.handle, &shape)?; + Ok((shape, [handles.0, handles.1, handles.2])) + } + fn kernel_slot(&self, operation: FixedOperation) -> &Cell> { + match operation { + FixedOperation::VectorAdd => &self.vector_add_kernel, + FixedOperation::Matvec => &self.matvec_kernel, + } + } + fn fixed_kernel(&self, operation: FixedOperation) -> Result { + let slot = self.kernel_slot(operation); + if let Some(kernel) = slot.get() { return Ok(kernel); } - let module = self.driver.api.load_fixed_module()?; - match self.driver.api.fixed_function(module) { + let module = self.driver.api.load_fixed_module(operation)?; + match self.driver.api.fixed_function(module, operation) { Ok(function) => { let kernel = FixedKernel { module, function }; - self.kernel.set(Some(kernel)); + slot.set(Some(kernel)); Ok(kernel) } Err(error) => { @@ -325,9 +489,9 @@ impl Context<'_> { } } } - fn unload_kernel(&self) -> Result<()> { + fn unload_kernel(&self, operation: FixedOperation) -> Result<()> { // Consume BEFORE attempting unload; even an error can invalidate it. - let Some(kernel) = self.kernel.take() else { + let Some(kernel) = self.kernel_slot(operation).take() else { return Ok(()); }; if self.poisoned.get() { @@ -352,7 +516,11 @@ impl Context<'_> { self.destroy() } fn destroy(&mut self) -> Result<()> { - let unload = self.unload_kernel(); + // Fixed teardown order; shared poison suppresses the second native unload. + let unload = combine( + self.unload_kernel(FixedOperation::VectorAdd), + self.unload_kernel(FixedOperation::Matvec), + ); 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. @@ -525,6 +693,100 @@ mod tests { } 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, + budget: 64, + allocated: Cell::new(12), + poisoned: Cell::new(false), + vector_add_kernel: Cell::new(None), + matvec_kernel: Cell::new(None), + }; + let make = |handle| DeviceBuffer { + context: &context, + handle, + bytes: 4, + _thread: PhantomData, + }; + let matrix = make(Some(ffi::BufferHandle::synthetic(4))); + let vector = make(Some(ffi::BufferHandle::synthetic(8))); + let mut output = make(Some(ffi::BufferHandle::synthetic(12))); + assert_eq!( + context.matvec_f32(&matrix, &vector, &mut output, 1, 1), + Err(Error::ContextPoisoned) + ); + // No native context exists in this test. Pure allocation identity and + // extent instruments supply the remaining impossible-safe-call cases. + assert_eq!(context.allocated_bytes(), 12); + assert!(context.matvec_kernel.get().is_none()); + } #[cfg(not(feature = "cuda-driver"))] #[test] fn default_load_rejects_before_driver_use() { diff --git a/crates/cuda-driver/src/matvec.ptx b/crates/cuda-driver/src/matvec.ptx new file mode 100644 index 00000000..6d32007f --- /dev/null +++ b/crates/cuda-driver/src/matvec.ptx @@ -0,0 +1,33 @@ +// Trusted row-major serial binary32 recurrence, embedded with final NUL. +.version 7.0 +.target sm_75 +.address_size 64 + +.visible .entry leleka_matvec_f32( + .param .u64 matrix, .param .u64 vector, .param .u64 output, + .param .u32 rows, .param .u32 columns ) +{ + .reg .pred %p<2>; .reg .b32 %r<4>; + .reg .b64 %rd<15>; .reg .f32 %f<4>; + + ld.param.u64 %rd0, [matrix]; ld.param.u64 %rd1, [vector]; + ld.param.u64 %rd2, [output]; ld.param.u32 %r2, [rows]; ld.param.u32 %r3, [columns]; + mov.u32 %r0, %ctaid.x; mov.u32 %r1, %tid.x; + mul.wide.u32 %rd3, %r0, 128; cvt.u64.u32 %rd4, %r1; + add.u64 %rd3, %rd3, %rd4; cvt.u64.u32 %rd4, %r2; + setp.ge.u64 %p0, %rd3, %rd4; @%p0 bra DONE; + + cvt.u64.u32 %rd5, %r3; mul.lo.u64 %rd6, %rd3, %rd5; + mov.u64 %rd7, 0; mov.f32 %f3, 0f00000000; +LOOP: + add.u64 %rd8, %rd6, %rd7; shl.b64 %rd8, %rd8, 2; + add.u64 %rd9, %rd0, %rd8; shl.b64 %rd10, %rd7, 2; + add.u64 %rd11, %rd1, %rd10; + ld.global.f32 %f0, [%rd9]; ld.global.f32 %f1, [%rd11]; + mul.rn.f32 %f2, %f0, %f1; add.rn.f32 %f3, %f3, %f2; + add.u64 %rd7, %rd7, 1; setp.lt.u64 %p1, %rd7, %rd5; @%p1 bra LOOP; + + shl.b64 %rd12, %rd3, 2; add.u64 %rd13, %rd2, %rd12; + st.global.f32 [%rd13], %f3; +DONE: ret; +} diff --git a/crates/cuda-driver/tests/gpu_driver.rs b/crates/cuda-driver/tests/gpu_driver.rs new file mode 100644 index 00000000..212eccc1 --- /dev/null +++ b/crates/cuda-driver/tests/gpu_driver.rs @@ -0,0 +1,300 @@ +#![cfg(all( + feature = "cuda-driver", + target_os = "linux", + target_pointer_width = "64" +))] + +use leleka_cuda_driver::{Context, Device, DeviceBuffer, Driver, Error}; + +// Recorded binary32 expectations, independent of wrapper code and PTX output. +const ARITHMETIC: &[(&[u32], &[u32], u32)] = &[ + (&[0x4b800000, 0x3f800000, 0xcb800000], &[0x3f800000; 3], 0), + (&[0xbf800000, 0x3f800001], &[0x3f800000, 0x3f7ffffe], 0), + (&[0x80000000], &[0x3f800000], 0), + (&[0], &[0xbf800000], 0), + (&[1], &[0x3f800000], 1), + (&[0x00800000], &[0x3f000000], 0x00400000), + (&[1], &[0x3f000000], 0), + (&[3], &[0x3f000000], 2), + (&[0x7f7fffff], &[0x40000000], 0x7f800000), + (&[0xff800000], &[0x3f800000], 0xff800000), + (&[0x7f800000, 0xff800000], &[0x3f800000; 2], 0x7fc00000), + (&[0x7fc00000], &[0x3f800000], 0x7fc00000), + (&[0x7f800000], &[0], 0x7fc00000), +]; +const ADD_INPUTS: &[(u32, u32)] = &[ + (0x80000000, 0x80000000), + (0, 0x80000000), + (1, 1), + (0x00800000, 0x80800000), + (0x3f800000, 0x33800000), + (0x7f7fffff, 0x7f7fffff), + (0xff800000, 0x3f800000), + (0x7f800000, 0xff800000), + (0x7fc00000, 0x3f800000), +]; + +struct MatvecCase { + matrix: Vec, + vector: Vec, +} + +#[inline(never)] +fn rounded_product(a: f32, b: f32) -> f32 { + std::hint::black_box(a * b) +} + +#[inline(never)] +fn rounded_add(a: f32, b: f32) -> f32 { + std::hint::black_box(a + b) +} + +// Separate non-inlined operations publish a binary32 result at each step. +// No f64 accumulation, fused multiply/add, tolerance or PTX-derived reference. +fn oracle(case: &MatvecCase) -> Vec { + case.matrix + .chunks_exact(case.vector.len()) + .map(|row| { + row.iter() + .zip(&case.vector) + .fold(0.0f32, |s, (&a, &b)| rounded_add(s, rounded_product(a, b))) + }) + .collect() +} + +fn bytes(values: &[f32]) -> Vec { + values.iter().flat_map(|v| v.to_ne_bytes()).collect() +} + +fn upload<'a>(context: &'a Context<'_>, values: &[f32]) -> DeviceBuffer<'a> { + let mut buffer = context.allocate(values.len() * 4).expect("allocation"); + buffer.copy_from(&bytes(values)).expect("upload"); + buffer +} + +fn read(buffer: &DeviceBuffer<'_>) -> Vec { + let mut output = vec![0; buffer.len()]; + buffer.copy_to(&mut output).expect("readback"); + output +} + +fn assert_value(actual: f32, expected: f32) { + if expected.is_nan() { + assert!(actual.is_nan(), "expected NaN classification"); + } else { + assert_eq!(actual.to_bits(), expected.to_bits(), "zero bit tolerance"); + } +} + +fn assert_output(buffer: &DeviceBuffer<'_>, expected: &[f32]) { + let actual = read(buffer); + assert_eq!(actual.len(), expected.len() * 4); + for (word, &expected) in actual.as_chunks::<4>().0.iter().zip(expected) { + assert_value(f32::from_ne_bytes(*word), expected); + } +} + +fn finish(context: Context<'_>) { + assert_eq!(context.allocated_bytes(), 0, "all explicit frees succeeded"); + context.close().expect("module unload and context destroy"); + println!("CONTEXT_CLEANUP PASS allocated=0 close=ok"); +} + +fn double_output(context: &Context<'_>, input: &DeviceBuffer<'_>, values: &[f32]) { + let expected: Vec<_> = values.iter().map(|&v| rounded_add(v, v)).collect(); + let mut output = upload(context, &vec![f32::NAN; values.len()]); + context + .vector_add_f32(input, input, &mut output) + .expect("interleaved add"); + assert_output(&output, &expected); + output.release().expect("interleaved output free"); + println!("VECTOR PASS count={} interleaved=true", values.len()); +} + +fn execute_matvec(context: &Context<'_>, case: &MatvecCase, interleave: bool) { + let expected = oracle(case); + let matrix = upload(context, &case.matrix); + let vector = upload(context, &case.vector); + let mut output = upload(context, &vec![f32::NAN; expected.len()]); + launch_matvec(context, case, [&matrix, &vector], &mut output); + assert_output(&output, &expected); + assert_eq!(read(&matrix), bytes(&case.matrix), "matrix unchanged"); + assert_eq!(read(&vector), bytes(&case.vector), "vector unchanged"); + if interleave { + double_output(context, &output, &expected); + assert_output(&output, &expected); + } + matrix.release().expect("matrix free"); + vector.release().expect("vector free"); + output.release().expect("output free"); + assert_eq!(context.allocated_bytes(), 0); + println!( + "MATVEC PASS rows={} columns={}", + expected.len(), + case.vector.len() + ); +} + +fn launch_matvec( + context: &Context<'_>, + case: &MatvecCase, + inputs: [&DeviceBuffer<'_>; 2], + output: &mut DeviceBuffer<'_>, +) { + context + .matvec_f32( + inputs[0], + inputs[1], + output, + case.matrix.len() / case.vector.len(), + case.vector.len(), + ) + .expect("installed-driver matvec launch, sync and restoration"); +} + +fn arithmetic(device: &Device<'_>) { + assert_eq!(rounded_add(rounded_add(16777216.0, -16777216.0), 1.0), 1.0); + assert_eq!( + f32::from_bits(0x3f800001) + .mul_add(f32::from_bits(0x3f7ffffe), -1.0) + .to_bits(), + 0xa8800000 + ); + for (index, &(a, b, expected)) in ARITHMETIC.iter().enumerate() { + let case = MatvecCase { + matrix: a.iter().map(|&bits| f32::from_bits(bits)).collect(), + vector: b.iter().map(|&bits| f32::from_bits(bits)).collect(), + }; + assert_value(oracle(&case)[0], f32::from_bits(expected)); + let context = device.create_context(65536).expect("arithmetic context"); + execute_matvec(&context, &case, false); + finish(context); + println!("ARITHMETIC PASS index={index} expected_bits={expected:08x}"); + } +} + +fn rectangular_case(rows: usize, columns: usize, offset: f32) -> MatvecCase { + MatvecCase { + matrix: (0..rows) + .flat_map(|r| (0..columns).map(move |c| offset + r as f32 * 0.25 + c as f32 * 0.125)) + .collect(), + vector: (0..columns) + .map(|c| (c as f32 + 1.0) * if c % 2 == 0 { 0.5 } else { -0.5 }) + .collect(), + } +} + +fn shapes(device: &Device<'_>) { + for rows in [1, 127, 128, 129] { + for columns in [1, 2, 3] { + let context = device.create_context(65536).expect("shape context"); + execute_matvec(&context, &rectangular_case(rows, columns, 1.0), false); + finish(context); + } + } + let context = device + .create_context(65536) + .expect("larger partial block context"); + execute_matvec(&context, &rectangular_case(1025, 7, 1.0), false); + finish(context); +} + +fn shared_input(device: &Device<'_>) { + let context = device.create_context(16).expect("shared-input context"); + let input = upload(&context, &[1.0, -2.0, 3.0]); + let mut output = upload(&context, &[f32::NAN]); + assert_eq!(context.allocated_bytes(), 16, "shared input charged once"); + context + .matvec_f32(&input, &input, &mut output, 1, 3) + .expect("shared immutable input"); + assert_output(&output, &[14.0]); + assert_eq!(read(&input), bytes(&[1.0, -2.0, 3.0])); + input.release().expect("shared input free"); + output.release().expect("shared output free"); + finish(context); + println!("MATVEC PASS rows=1 columns=3 shared_input=true"); +} + +fn foreign_refusal(first: &Context<'_>, second: &Context<'_>) { + let matrix = upload(first, &[2.0]); + let vector = upload(second, &[3.0]); + let mut output = upload(second, &[-0.0]); + assert_eq!( + second.matvec_f32(&matrix, &vector, &mut output, 1, 1), + Err(Error::ContextMismatch) + ); + assert_eq!( + second.matvec_f32(&vector, &vector, &mut output, 0, 1), + Err(Error::InvalidMatvecShape) + ); + assert_eq!(read(&output), bytes(&[-0.0]), "refusals preserve output"); + assert_eq!(first.allocated_bytes(), 4); + assert_eq!(second.allocated_bytes(), 8); + matrix.release().expect("foreign matrix free"); + vector.release().expect("foreign vector free"); + output.release().expect("foreign output free"); + println!("ADMISSION PASS foreign_context and zero_rows"); +} + +fn two_contexts(device: &Device<'_>) { + let first = device + .create_context(65536) + .expect("first concurrent context"); + let second = device + .create_context(65536) + .expect("second concurrent context"); + foreign_refusal(&first, &second); + for _ in 0..2 { + execute_matvec(&first, &rectangular_case(129, 3, 1.0), true); + execute_matvec(&second, &rectangular_case(127, 2, -2.0), true); + } + finish(first); + finish(second); +} + +fn vector_case(device: &Device<'_>, count: usize) { + let pairs: Vec<_> = (0..count) + .map(|i| ADD_INPUTS[i % ADD_INPUTS.len()]) + .collect(); + let a: Vec<_> = pairs.iter().map(|&(a, _)| f32::from_bits(a)).collect(); + let b: Vec<_> = pairs.iter().map(|&(_, b)| f32::from_bits(b)).collect(); + let expected: Vec<_> = a.iter().zip(&b).map(|(&a, &b)| rounded_add(a, b)).collect(); + assert_eq!( + expected[0].to_bits(), + 0x80000000, + "negative-zero add reference" + ); + let context = device.create_context(count * 12).expect("vector context"); + let input_a = upload(&context, &a); + let input_b = upload(&context, &b); + let mut output = upload(&context, &vec![f32::NAN; count]); + context + .vector_add_f32(&input_a, &input_b, &mut output) + .expect("installed-driver vector add"); + assert_output(&output, &expected); + assert_eq!(read(&input_a), bytes(&a)); + assert_eq!(read(&input_b), bytes(&b)); + input_a.release().expect("vector a free"); + input_b.release().expect("vector b free"); + output.release().expect("vector output free"); + finish(context); + println!("VECTOR PASS count={count} interleaved=false"); +} + +#[test] +#[ignore = "requires explicit installed-driver GPU experiment authorization"] +fn installed_driver_fixed_kernels() { + assert_eq!(std::env::var("LELEKA_CUDA_REAL_GPU").as_deref(), Ok("1")); + println!("TOLERANCE finite/zero/infinity=exact_bits NaN=classification"); + let driver = Driver::load().expect("trusted installed libcuda.so.1"); + println!("DRIVER API version={}", driver.version()); + let device = driver.device(0).expect("authorized GPU ordinal zero"); + arithmetic(&device); + shapes(&device); + shared_input(&device); + two_contexts(&device); + for count in [1, 127, 128, 129, 1025] { + vector_case(&device, count); + } + println!("GPU_NUMERICAL PASS matvec=31 vector=9 arithmetic=13 contexts_closed=34 refusals=2"); +} diff --git a/crates/cuda-driver/tests/mock_cuda.c b/crates/cuda-driver/tests/mock_cuda.c index 4c95a349..4e7207c3 100644 --- a/crates/cuda-driver/tests/mock_cuda.c +++ b/crates/cuda-driver/tests/mock_cuda.c @@ -17,11 +17,12 @@ static int context_live(CUcontext ctx){for(size_t i=0;i<16;i++)if(contexts[i]==c static int live_context; static unsigned failed_mask; static struct {void *raw,*ptr;size_t size;CUcontext owner;} buffers[16]; -static struct {void *handle,*function;CUcontext owner;} modules[16]; +static struct {void *handle,*function;CUcontext owner;int matvec;} modules[16]; static size_t next_module; static void **pending_args; static uint64_t pending_values[3]; -static uint32_t pending_n; +static uint32_t pending_n,pending_columns; +static int pending_matvec; static CUcontext pending_owner; static const void *pending_host; static void *pending_device; @@ -54,12 +55,29 @@ static void check_canary(size_t i) { if(!raw)return; for(size_t j=0;j<8;j++)if(raw[j]!=0xa5||raw[8+buffers[i].size+j]!=0xa5){trace("canary",1,i);abort();} } +static void compute_pending_kernel(void) { + float *a=(float *)(uintptr_t)pending_values[0]; + float *b=(float *)(uintptr_t)pending_values[1],*out=(float *)(uintptr_t)pending_values[2]; + if(pending_matvec){ + /* Volatile rounds each operation to binary32. Build flags forbid + contraction/reassociation; this fixture never interprets PTX. */ + for(uint64_t r=0;r=16)return 2; size_t slot=next_module++;modules[slot].handle=(void *)(uintptr_t)(0x100+slot); modules[slot].function=(void *)(uintptr_t)(0x200+slot);modules[slot].owner=current; - *result=modules[slot].handle;trace("load",0,0);return 0; + modules[slot].matvec=matvec; + *result=modules[slot].handle;trace("load",0,0); + trace(matvec?"module_matvec":"module_add",0,slot);return 0; } CUresult cuModuleGetFunction(void **result,void *module,const char *name) { - if(fault(13))return 700;if(require_context()||strcmp(name,"leleka_vector_add_f32"))return 201; + if(fault(13))return 700;if(require_context())return 201; if(getenv("MOCK_CUDA_NULL_FUNCTION")){*result=NULL;trace("lookup_null",0,0);return 0;} - for(size_t i=0;i<16;i++)if(modules[i].handle==module&&modules[i].owner==current){*result=modules[i].function;trace("lookup",0,0);return 0;} + for(size_t i=0;i<16;i++)if(modules[i].handle==module&&modules[i].owner==current){ + if(strcmp(name,modules[i].matvec?"leleka_matvec_f32":"leleka_vector_add_f32"))return 201; + *result=modules[i].function;trace("lookup",0,0);return 0;} return 201; } CUresult cuModuleUnload(void *module) { if(pending_args){trace("unsafe_pending_unload",0,0);abort();} if(fault(14))return 700;if(require_context())return 201; - for(size_t i=0;i<16;i++)if(modules[i].handle==module&&modules[i].owner==current){memset(&modules[i],0,sizeof(modules[i]));trace("unload",0,0);return 0;} + for(size_t i=0;i<16;i++)if(modules[i].handle==module&&modules[i].owner==current){ + trace(modules[i].matvec?"unload_matvec":"unload_add",0,i); + memset(&modules[i],0,sizeof(modules[i]));trace("unload",0,0);return 0; + } return 201; } -CUresult cuLaunchKernel(void *function,unsigned gx,unsigned gy,unsigned gz,unsigned bx,unsigned by,unsigned bz,unsigned shared,void *stream,void **params,void **extra) { +static int capture_arguments(void **params,int matvec,uint32_t n,uint32_t columns,uintptr_t stack_address) { + for(size_t i=0;i<(matvec?5u:4u);i++){ + uintptr_t arg=(uintptr_t)params[i];if(!arg||(arg>stack_address-1048576&&argstack_address-1048576&&table_addressstack_address-1048576&&arg Vec<(&'static str, i32)> { } } +const SCENARIOS: &[&str] = &[ + "success", + "bounds", + "missing", + "missing_cuInit", + "missing_cuDriverGetVersion", + "missing_cuDeviceGet", + "missing_cuCtxCreate_v2", + "missing_cuCtxDestroy_v2", + "missing_cuCtxPushCurrent_v2", + "missing_cuCtxPopCurrent_v2", + "missing_cuCtxSynchronize", + "missing_cuMemAlloc_v2", + "missing_cuMemFree_v2", + "missing_cuMemcpyHtoD_v2", + "init", + "version", + "device", + "create", + "create_pop", + "push", + "pop", + "wrong_pop", + "operation_wrong_pop", + "context_sync", + "alloc", + "htod", + "dtoh", + "sync_htod", + "sync_dtoh", + "htod_sync", + "dtoh_sync", + "free", + "destroy", + "missing_cuModuleLoadData", + "missing_cuModuleGetFunction", + "missing_cuModuleUnload", + "missing_cuLaunchKernel", + "vector_1", + "vector_127", + "vector_128", + "vector_129", + "vector_1025", + "vector_cache", + "vector_contexts", + "vector_bounds", + "vector_same_input", + "vector_load", + "vector_lookup", + "vector_null_load", + "vector_null_function", + "vector_launch", + "vector_sync", + "vector_launch_sync", + "vector_launch_sync_pop", + "vector_pop", + "vector_wrong_pop", + "vector_unload", + "vector_lookup_unload", + "vector_close_pop", + "vector_close_destroy", + "vector_push", + "matvec_1", + "matvec_127", + "matvec_128", + "matvec_129", + "matvec_1025", + "matvec_n1", + "matvec_same_input", + "matvec_arithmetic", + "matvec_bounds", + "matvec_cache", + "matvec_contexts", + "matvec_interleave", + "matvec_interleave_reverse", + "matvec_load", + "matvec_lookup", + "matvec_null_load", + "matvec_null_function", + "matvec_launch", + "matvec_sync", + "matvec_launch_sync", + "matvec_launch_sync_pop", + "matvec_pop", + "matvec_wrong_pop", + "matvec_lookup_unload", + "matvec_push", + "matvec_unload", + "matvec_close_pop", + "matvec_close_wrong_pop", + "matvec_close_destroy", + "matvec_close_push", + "matvec_unload_destroy", + "matvec_both_unload_add", + "matvec_both_unload_matvec", + "matvec_both_pop_add", + "matvec_both_pop_matvec", + "matvec_both_wrong_pop_add", + "matvec_both_wrong_pop_matvec", + "matvec_both_push_add", + "matvec_both_push_matvec", +]; + +const SCENARIO_FAILURES: &[(&str, &str)] = &[ + ("matvec_load", "load"), + ("matvec_lookup", "lookup"), + ("matvec_launch", "launch"), + ("matvec_sync", "sync:3"), + ("matvec_launch_sync", "launch,sync:3"), + ("matvec_launch_sync_pop", "launch,sync:3,pop:7"), + ("matvec_pop", "pop:7"), + ("matvec_lookup_unload", "lookup,unload"), + ("matvec_push", "push:6"), + ("matvec_unload", "unload"), + ("matvec_close_pop", "pop:14"), + ("matvec_close_push", "push:13"), + ("matvec_close_destroy", "destroy"), + ("matvec_unload_destroy", "unload,destroy"), + ("matvec_both_unload_add", "unload"), + ("matvec_both_unload_matvec", "unload:2"), + ("matvec_both_pop_add", "pop:18"), + ("matvec_both_pop_matvec", "pop:19"), + ("matvec_both_push_add", "push:17"), + ("matvec_both_push_matvec", "push:18"), + ("vector_load", "load"), + ("vector_lookup", "lookup"), + ("vector_launch", "launch"), + ("vector_sync", "sync:3"), + ("vector_launch_sync", "launch,sync:3"), + ("vector_launch_sync_pop", "launch,sync:3,pop:7"), + ("vector_pop", "pop:7"), + ("vector_unload", "unload"), + ("vector_lookup_unload", "lookup,unload"), + ("vector_close_pop", "pop:14"), + ("vector_close_destroy", "destroy"), + ("vector_push", "push:6"), + ("create_pop", "pop"), + ("pop", "pop:2"), + ("sync_htod", "sync"), + ("sync_dtoh", "sync:2"), + ("htod_sync", "htod,sync"), + ("dtoh_sync", "dtoh,sync:2"), + ("context_sync", "sync"), +]; +const WRONG_POP: &[(&str, &str)] = &[ + ("wrong_pop", "1"), + ("operation_wrong_pop", "2"), + ("vector_wrong_pop", "7"), + ("matvec_wrong_pop", "7"), + ("matvec_close_wrong_pop", "14"), + ("matvec_both_wrong_pop_add", "18"), + ("matvec_both_wrong_pop_matvec", "19"), +]; + #[test] #[ignore = "requires isolated CPU-only fake libcuda harness"] fn isolated_cpu_elf_matrix() { @@ -69,142 +223,76 @@ fn isolated_cpu_elf_matrix() { ); let root = PathBuf::from(std::env::var("LELEKA_CUDA_MOCK_ROOT").unwrap()); assert!(root.is_absolute()); - let scenarios = [ + for scenario in SCENARIOS { + run_fixture_case(&root, scenario); + } +} +fn run_fixture_case(root: &std::path::Path, scenario: &str) { + let mut command = scenario_command(root, scenario); + configure_faults(&mut command, scenario); + let output = command.output().unwrap(); + assert!( + output.status.success(), + "scenario {scenario}\n{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + println!("synthetic CPU ELF scenario {scenario}: PASS"); +} +fn scenario_command(root: &std::path::Path, scenario: &str) -> Command { + let mut command = Command::new(std::env::current_exe().unwrap()); + command + .args(["--exact", "fixture_child", "--ignored", "--nocapture"]) + .env("LELEKA_CUDA_CASE", scenario) + .env("MOCK_CUDA_TRACE", root.join(format!("trace-{scenario}"))) + .env_remove("MOCK_CUDA_FAIL") + .env_remove("MOCK_CUDA_WRONG_POP") + .env_remove("MOCK_CUDA_NULL_LOAD") + .env_remove("MOCK_CUDA_NULL_FUNCTION") + .env_remove("MOCK_CUDA_VECTOR"); + if scenario.starts_with("vector_") || scenario.starts_with("matvec_") { + command.env("MOCK_CUDA_VECTOR", "1"); + } + let library = if scenario.starts_with("missing") { + scenario + } else { + "complete" + }; + command.env("LD_LIBRARY_PATH", root.join(library)); + command +} +fn scenario_failure(scenario: &str) -> Option<&str> { + if let Some(row) = SCENARIO_FAILURES.iter().find(|row| row.0 == scenario) { + return Some(row.1); + } + if scenario.starts_with("matvec_") || scenario.starts_with("vector_") { + return None; + } + if [ "success", "bounds", "missing", - "missing_cuInit", - "missing_cuDriverGetVersion", - "missing_cuDeviceGet", - "missing_cuCtxCreate_v2", - "missing_cuCtxDestroy_v2", - "missing_cuCtxPushCurrent_v2", - "missing_cuCtxPopCurrent_v2", - "missing_cuCtxSynchronize", - "missing_cuMemAlloc_v2", - "missing_cuMemFree_v2", - "missing_cuMemcpyHtoD_v2", - "init", - "version", - "device", - "create", - "create_pop", - "push", - "pop", "wrong_pop", "operation_wrong_pop", - "context_sync", - "alloc", - "htod", - "dtoh", - "sync_htod", - "sync_dtoh", - "htod_sync", - "dtoh_sync", - "free", - "destroy", - "missing_cuModuleLoadData", - "missing_cuModuleGetFunction", - "missing_cuModuleUnload", - "missing_cuLaunchKernel", - "vector_1", - "vector_127", - "vector_128", - "vector_129", - "vector_1025", - "vector_cache", - "vector_contexts", - "vector_bounds", - "vector_same_input", - "vector_load", - "vector_lookup", - "vector_null_load", - "vector_null_function", - "vector_launch", - "vector_sync", - "vector_launch_sync", - "vector_launch_sync_pop", - "vector_pop", - "vector_wrong_pop", - "vector_unload", - "vector_lookup_unload", - "vector_close_pop", - "vector_close_destroy", - "vector_push", - ]; - for scenario in scenarios { - let path = root.join(format!("trace-{scenario}")); - let mut command = Command::new(std::env::current_exe().unwrap()); - command - .args(["--exact", "fixture_child", "--ignored", "--nocapture"]) - .env("LELEKA_CUDA_CASE", scenario) - .env("MOCK_CUDA_TRACE", &path) - .env_remove("MOCK_CUDA_FAIL") - .env_remove("MOCK_CUDA_WRONG_POP") - .env_remove("MOCK_CUDA_NULL_LOAD") - .env_remove("MOCK_CUDA_NULL_FUNCTION") - .env_remove("MOCK_CUDA_VECTOR"); - if scenario.starts_with("vector_") { - command.env("MOCK_CUDA_VECTOR", "1"); - } - command.env( - "LD_LIBRARY_PATH", - root.join(if scenario.starts_with("missing") { - scenario - } else { - "complete" - }), - ); - let failure = match scenario { - "vector_load" => Some("load"), - "vector_lookup" => Some("lookup"), - "vector_launch" => Some("launch"), - "vector_sync" => Some("sync:3"), - "vector_launch_sync" => Some("launch,sync:3"), - "vector_launch_sync_pop" => Some("launch,sync:3,pop:7"), - "vector_pop" => Some("pop:7"), - "vector_unload" => Some("unload"), - "vector_lookup_unload" => Some("lookup,unload"), - "vector_close_pop" => Some("pop:14"), - "vector_close_destroy" => Some("destroy"), - "vector_push" => Some("push:6"), - other if other.starts_with("vector_") => None, - "create_pop" => Some("pop"), - "pop" => Some("pop:2"), - "sync_htod" => Some("sync"), - "sync_dtoh" => Some("sync:2"), - "htod_sync" => Some("htod,sync"), - "dtoh_sync" => Some("dtoh,sync:2"), - "success" | "bounds" | "missing" | "wrong_pop" | "operation_wrong_pop" => None, - "context_sync" => Some("sync"), - other => Some(other), - }; - if let Some(failure) = failure { - command.env("MOCK_CUDA_FAIL", failure); - } - if ["wrong_pop", "operation_wrong_pop"].contains(&scenario) { - command.env( - "MOCK_CUDA_WRONG_POP", - if scenario == "wrong_pop" { "1" } else { "2" }, - ); - } - if scenario == "vector_wrong_pop" { - command.env("MOCK_CUDA_WRONG_POP", "7"); - } - if scenario == "vector_null_load" { - command.env("MOCK_CUDA_NULL_LOAD", "1"); - } - if scenario == "vector_null_function" { - command.env("MOCK_CUDA_NULL_FUNCTION", "1"); - } - let output = command.output().unwrap(); - assert!( - output.status.success(), - "scenario {scenario}\n{}\n{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); - println!("synthetic CPU ELF scenario {scenario}: PASS"); + ] + .contains(&scenario) + { + return None; + } + Some(scenario) +} +fn configure_faults(command: &mut Command, scenario: &str) { + if let Some(failure) = scenario_failure(scenario) { + command.env("MOCK_CUDA_FAIL", failure); + } + if let Some(row) = WRONG_POP.iter().find(|row| row.0 == scenario) { + command.env("MOCK_CUDA_WRONG_POP", row.1); + } + if ["vector_null_load", "matvec_null_load"].contains(&scenario) { + command.env("MOCK_CUDA_NULL_LOAD", "1"); + } + if ["vector_null_function", "matvec_null_function"].contains(&scenario) { + command.env("MOCK_CUDA_NULL_FUNCTION", "1"); } } @@ -213,28 +301,34 @@ fn isolated_cpu_elf_matrix() { fn fixture_child() { assert_eq!(std::env::var("LELEKA_CUDA_MOCK_HARNESS").unwrap(), "1"); let case = std::env::var("LELEKA_CUDA_CASE").unwrap(); - if case.starts_with("vector_") { + if case == "matvec_arithmetic" { + matvec_arithmetic(); + } else if case.starts_with("matvec_") { + matvec_child(&case); + } else if case.starts_with("vector_") { vector_child(&case); - return; + } else if case.starts_with("missing") || ["init", "version"].contains(&case.as_str()) { + bootstrap_load_failure(&case); + } else { + bootstrap_child(&case); } - if case.starts_with("missing") || ["init", "version"].contains(&case.as_str()) { - let error = Driver::load() - .err() - .expect("missing ABI/init/version must fail"); - if case.starts_with("missing") { - let symbol = case.strip_prefix("missing_").unwrap_or("cuMemcpyDtoH_v2"); - assert!( - matches!(error,leleka_cuda_driver::Error::MissingSymbol(actual) if actual==symbol) - ); - } - let rows = trace(); - if case.starts_with("missing") { - assert!(rows.is_empty(), "symbol resolution must precede init"); - } else { - assert!(rows.iter().any(|row| row.stage == case && row.code == 700)); - } - return; +} +fn bootstrap_load_failure(case: &str) { + let error = Driver::load() + .err() + .expect("missing ABI/init/version must fail"); + if case.starts_with("missing") { + let symbol = case.strip_prefix("missing_").unwrap_or("cuMemcpyDtoH_v2"); + assert!(matches!(error,leleka_cuda_driver::Error::MissingSymbol(actual) if actual==symbol)); } + let rows = trace(); + if case.starts_with("missing") { + assert!(rows.is_empty(), "symbol resolution must precede init"); + } else { + assert!(rows.iter().any(|row| row.stage == case && row.code == 700)); + } +} +fn bootstrap_child(case: &str) { let driver = Driver::load().unwrap(); assert_eq!(driver.version(), 13000); if case == "device" { @@ -243,156 +337,225 @@ fn fixture_child() { } assert!(driver.device(-1).is_err()); let device = driver.device(0).unwrap(); - if case == "bounds" { - let before = trace().len(); - assert!(device.create_context(0).is_err()); - assert!(device.create_context(usize::MAX).is_err()); - assert_eq!(trace().len(), before); - } - if ["create", "create_pop", "wrong_pop"].contains(&case.as_str()) { - assert!(device.create_context(16).is_err()); - let rows = trace(); - if case == "create" { - assert!(!rows.iter().any(|row| row.stage == "destroy")); - } else { - assert!( - rows.iter() - .any(|row| row.stage == "destroy" && row.code == 0) - ); - } + if bootstrap_create(&device, case) { return; } let context = device.create_context(16).unwrap(); assert_eq!(context.budget_bytes(), 16); assert_eq!(context.allocated_bytes(), 0); assert_eq!(trace().last().unwrap().current, 0x11); - if ["alloc", "push", "pop", "operation_wrong_pop"].contains(&case.as_str()) { - assert!(context.allocate(8).is_err()); - if ["pop", "operation_wrong_pop"].contains(&case.as_str()) { - let before = trace().len(); - assert!(context.allocate(8).is_err()); - assert!(context.synchronize().is_err()); - assert_eq!(trace().len(), before, "poison must reject native work"); - } else { - assert_eq!(context.allocated_bytes(), 0); - } - drop(context); - valid_context_trace(&trace()); - return; - } - if case == "context_sync" { - assert!(context.synchronize().is_err()); + if bootstrap_early_fault(&context, case) { drop(context); valid_context_trace(&trace()); return; } + if case == "bounds" { + bootstrap_allocation_bounds(&context); + } + let output = bootstrap_buffer_path(&context, case); + bootstrap_close(context, case); + let rows = trace(); + bootstrap_copy_trace(case, &rows, output); + bootstrap_final_trace(case, &rows); +} +fn bootstrap_create(device: &leleka_cuda_driver::Device<'_>, case: &str) -> bool { if case == "bounds" { let before = trace().len(); - assert!(context.allocate(0).is_err()); - assert!(context.allocate(17).is_err()); - assert!(context.allocate(usize::MAX).is_err()); + assert!(device.create_context(0).is_err()); + assert!(device.create_context(usize::MAX).is_err()); assert_eq!(trace().len(), before); } + if !["create", "create_pop", "wrong_pop"].contains(&case) { + return false; + } + assert!(device.create_context(16).is_err()); + let rows = trace(); + if case == "create" { + assert!(!rows.iter().any(|row| row.stage == "destroy")); + } else { + assert!( + rows.iter() + .any(|row| row.stage == "destroy" && row.code == 0) + ); + } + true +} +fn bootstrap_early_fault(context: &leleka_cuda_driver::Context<'_>, case: &str) -> bool { + if case == "context_sync" { + assert!(context.synchronize().is_err()); + return true; + } + if !["alloc", "push", "pop", "operation_wrong_pop"].contains(&case) { + return false; + } + assert!(context.allocate(8).is_err()); + if ["pop", "operation_wrong_pop"].contains(&case) { + let before = trace().len(); + assert!(context.allocate(8).is_err()); + assert!(context.synchronize().is_err()); + assert_eq!(trace().len(), before, "poison must reject native work"); + } else { + assert_eq!(context.allocated_bytes(), 0); + } + true +} +fn bootstrap_allocation_bounds(context: &leleka_cuda_driver::Context<'_>) { + let before = trace().len(); + assert!(context.allocate(0).is_err()); + assert!(context.allocate(17).is_err()); + assert!(context.allocate(usize::MAX).is_err()); + assert_eq!(trace().len(), before); +} +fn bootstrap_buffer_path(context: &leleka_cuda_driver::Context<'_>, case: &str) -> [u8; 8] { let mut buffer = context.allocate(8).unwrap(); assert_eq!(buffer.len(), 8); assert_eq!(context.allocated_bytes(), 8); if case == "bounds" { - let before = trace().len(); - assert!(context.allocate(9).is_err()); - assert!(buffer.copy_from(&[1; 7]).is_err()); - assert!(buffer.copy_from(&[1; 9]).is_err()); - let mut short = [0x99; 7]; - assert!(buffer.copy_to(&mut short).is_err()); - assert_eq!(short, [0x99; 7]); - assert_eq!( - trace().len(), - before, - "bounds reject before driver mutation" - ); + bootstrap_buffer_bounds(context, &mut buffer); } + let output = bootstrap_copies(context, &mut buffer, case); + bootstrap_release(context, buffer, case); + output +} +fn bootstrap_buffer_bounds( + context: &leleka_cuda_driver::Context<'_>, + buffer: &mut leleka_cuda_driver::DeviceBuffer<'_>, +) { + let before = trace().len(); + assert!(context.allocate(9).is_err()); + assert!(buffer.copy_from(&[1; 7]).is_err()); + assert!(buffer.copy_from(&[1; 9]).is_err()); + let mut short = [0x99; 7]; + assert!(buffer.copy_to(&mut short).is_err()); + assert_eq!(short, [0x99; 7]); + assert_eq!( + trace().len(), + before, + "bounds reject before driver mutation" + ); +} +fn bootstrap_copies( + context: &leleka_cuda_driver::Context<'_>, + buffer: &mut leleka_cuda_driver::DeviceBuffer<'_>, + case: &str, +) -> [u8; 8] { let mut input = [0, 1, 2, 3, 0xff, 0x80, 0x55, 0xaa]; let mut output = [0x99; 8]; - if ["htod", "sync_htod", "htod_sync"].contains(&case.as_str()) { - let error = buffer.copy_from(&input).unwrap_err(); - let expected = match case.as_str() { - "htod" => vec![("cuMemcpyHtoD_v2", 700)], - "sync_htod" => vec![("cuCtxSynchronize", 700)], - _ => vec![("cuMemcpyHtoD_v2", 700), ("cuCtxSynchronize", 700)], - }; - assert_eq!( - cuda_errors(&error), - expected, - "copy/completion errors retained in order" - ); - input.fill(0); - std::hint::black_box(input); - if ["sync_htod", "htod_sync"].contains(&case.as_str()) { - let before = trace().len(); - assert!(context.allocate(1).is_err()); - assert_eq!(trace().len(), before); - } + if ["htod", "sync_htod", "htod_sync"].contains(&case) { + bootstrap_htod_fault(context, buffer, case, &mut input); } else { buffer.copy_from(&input).unwrap(); - if ["dtoh", "sync_dtoh", "dtoh_sync"].contains(&case.as_str()) { - let error = buffer.copy_to(&mut output).unwrap_err(); - let expected = match case.as_str() { - "dtoh" => vec![("cuMemcpyDtoH_v2", 700)], - "sync_dtoh" => vec![("cuCtxSynchronize", 700)], - _ => vec![("cuMemcpyDtoH_v2", 700), ("cuCtxSynchronize", 700)], - }; - assert_eq!( - cuda_errors(&error), - expected, - "copy/completion errors retained in order" - ); - assert_eq!(output, [0x99; 8], "failed copy must not publish staging"); - if ["sync_dtoh", "dtoh_sync"].contains(&case.as_str()) { - let before = trace().len(); - assert!(context.synchronize().is_err()); - assert_eq!(trace().len(), before); - } + if ["dtoh", "sync_dtoh", "dtoh_sync"].contains(&case) { + bootstrap_dtoh_fault(context, buffer, case, &mut output); } else { buffer.copy_to(&mut output).unwrap(); assert_eq!(output, input); } } + output +} +fn bootstrap_copy_errors(case: &str, copy: &'static str) -> Vec<(&'static str, i32)> { + if case.starts_with("sync_") { + vec![("cuCtxSynchronize", 700)] + } else if case.ends_with("_sync") { + vec![(copy, 700), ("cuCtxSynchronize", 700)] + } else { + vec![(copy, 700)] + } +} +fn bootstrap_htod_fault( + context: &leleka_cuda_driver::Context<'_>, + buffer: &mut leleka_cuda_driver::DeviceBuffer<'_>, + case: &str, + input: &mut [u8; 8], +) { + let error = buffer.copy_from(input).unwrap_err(); + assert_eq!( + cuda_errors(&error), + bootstrap_copy_errors(case, "cuMemcpyHtoD_v2"), + "copy/completion errors retained in order" + ); + input.fill(0); + std::hint::black_box(*input); + if ["sync_htod", "htod_sync"].contains(&case) { + let before = trace().len(); + assert!(context.allocate(1).is_err()); + assert_eq!(trace().len(), before); + } +} +fn bootstrap_dtoh_fault( + context: &leleka_cuda_driver::Context<'_>, + buffer: &leleka_cuda_driver::DeviceBuffer<'_>, + case: &str, + output: &mut [u8; 8], +) { + let error = buffer.copy_to(output).unwrap_err(); + assert_eq!( + cuda_errors(&error), + bootstrap_copy_errors(case, "cuMemcpyDtoH_v2"), + "copy/completion errors retained in order" + ); + assert_eq!(*output, [0x99; 8], "failed copy must not publish staging"); + if ["sync_dtoh", "dtoh_sync"].contains(&case) { + let before = trace().len(); + assert!(context.synchronize().is_err()); + assert_eq!(trace().len(), before); + } +} +const COPY_POISON: &[&str] = &["sync_htod", "sync_dtoh", "htod_sync", "dtoh_sync"]; +fn bootstrap_release( + context: &leleka_cuda_driver::Context<'_>, + buffer: leleka_cuda_driver::DeviceBuffer<'_>, + case: &str, +) { if case == "free" { let error = buffer.release().unwrap_err(); assert_eq!(cuda_errors(&error), vec![("cuMemFree_v2", 700)]); assert_eq!(context.allocated_bytes(), 8); - } else if ["sync_htod", "sync_dtoh", "htod_sync", "dtoh_sync"].contains(&case.as_str()) { + } else if COPY_POISON.contains(&case) { drop(buffer); } else { buffer.release().unwrap(); assert_eq!(context.allocated_bytes(), 0); } +} +fn bootstrap_close(context: leleka_cuda_driver::Context<'_>, case: &str) { if case == "destroy" { - let error = context.close().unwrap_err(); - assert_eq!(cuda_errors(&error), vec![("cuCtxDestroy_v2", 700)]); - } else if ["sync_htod", "sync_dtoh", "htod_sync", "dtoh_sync"].contains(&case.as_str()) { + assert_eq!( + cuda_errors(&context.close().unwrap_err()), + vec![("cuCtxDestroy_v2", 700)] + ); + } else if COPY_POISON.contains(&case) { drop(context); } else { context.close().unwrap(); } - let rows = trace(); +} +fn bootstrap_copy_trace(case: &str, rows: &[Row], output: [u8; 8]) { + bootstrap_pending_trace(case, rows, output); + bootstrap_failed_copy_sync(case, rows); +} +fn bootstrap_pending_trace(case: &str, rows: &[Row], output: [u8; 8]) { if case == "sync_htod" { assert!( rows.iter() - .any(|row| row.stage == "pending_htod" && row.code == 0 && row.bytes == 644), + .any(|r| r.stage == "pending_htod" && r.code == 0 && r.bytes == 644), "delayed source retained original owned bytes after caller input changed" ); } if case == "sync_dtoh" { assert!( rows.iter() - .any(|row| row.stage == "pending_dtoh" && row.bytes == 8) + .any(|r| r.stage == "pending_dtoh" && r.bytes == 8) ); assert_eq!( output, [0x99; 8], - "completion after failed sync must target retained staging, never caller output" + "completion after failed sync targets retained staging, never caller output" ); } - if ["htod", "dtoh", "htod_sync", "dtoh_sync"].contains(&case.as_str()) { +} +fn bootstrap_failed_copy_sync(case: &str, rows: &[Row]) { + if ["htod", "dtoh", "htod_sync", "dtoh_sync"].contains(&case) { let copy = if case.starts_with("htod") { "htod" } else { @@ -400,7 +563,7 @@ fn fixture_child() { }; let index = rows .iter() - .position(|row| row.stage == copy && row.code == 700) + .position(|r| r.stage == copy && r.code == 700) .unwrap(); assert_eq!( rows[index + 1].stage, @@ -412,218 +575,293 @@ fn fixture_child() { if case.ends_with("_sync") { 700 } else { 0 } ); } - valid_context_trace(&rows); +} +fn bootstrap_final_trace(case: &str, rows: &[Row]) { + valid_context_trace(rows); assert!( - rows.iter().any(|row| row.stage == "destroy"), + rows.iter().any(|r| r.stage == "destroy"), "owned context cleanup attempted" ); assert!( - !rows.iter().any(|row| row.stage == "unsafe_pending_free"), + !rows.iter().any(|r| r.stage == "unsafe_pending_free"), "pending copy device freed early" ); - for row in rows - .iter() - .filter(|row| row.stage == "alloc" && row.code == 0) - { - assert_eq!(row.bytes, 8); - assert_eq!(row.charged, 8); + for r in rows.iter().filter(|r| r.stage == "alloc" && r.code == 0) { + assert_eq!(r.bytes, 8); + assert_eq!(r.charged, 8); } - if !["destroy"].contains(&case.as_str()) { - let destroyed = rows + if case != "destroy" { + let r = rows .iter() .rev() - .find(|row| row.stage == "destroy" && row.code == 0) + .find(|r| r.stage == "destroy" && r.code == 0) .unwrap(); - assert_eq!(destroyed.live, 0); - assert_eq!(destroyed.charged, 0); - assert_eq!(destroyed.current, 0x11); + assert_eq!(r.live, 0); + assert_eq!(r.charged, 0); + assert_eq!(r.current, 0x11); } } // Expected values and geometry are derived from FR-VADD-1..5 and the NVIDIA // launch ABI, independent of the wrapper/PTX implementation. CPU mock results // are host dataflow/ownership evidence only. -fn vector_child(case: &str) { - use leleka_cuda_driver::Error; - let driver = Driver::load().unwrap(); - let device = driver.device(0).unwrap(); - let count = case - .strip_prefix("vector_") - .unwrap() - .parse::() - .unwrap_or(129); +const VECTOR_EXECUTION_FAILURES: &[&str] = &[ + "vector_load", + "vector_lookup", + "vector_null_load", + "vector_null_function", + "vector_launch", + "vector_sync", + "vector_launch_sync", + "vector_launch_sync_pop", + "vector_pop", + "vector_wrong_pop", + "vector_lookup_unload", + "vector_push", +]; +const VECTOR_POISON: &[&str] = &[ + "vector_sync", + "vector_launch_sync", + "vector_launch_sync_pop", + "vector_pop", + "vector_wrong_pop", + "vector_lookup_unload", +]; +const VECTOR_ERRORS: &[(&str, &[&str])] = &[ + ("vector_load", &["cuModuleLoadData"]), + ("vector_lookup", &["cuModuleGetFunction"]), + ( + "vector_lookup_unload", + &["cuModuleGetFunction", "cuModuleUnload"], + ), + ("vector_launch", &["cuLaunchKernel"]), + ("vector_sync", &["cuCtxSynchronize"]), + ( + "vector_launch_sync", + &["cuLaunchKernel", "cuCtxSynchronize"], + ), + ( + "vector_launch_sync_pop", + &["cuLaunchKernel", "cuCtxSynchronize", "cuCtxPopCurrent_v2"], + ), + ("vector_pop", &["cuCtxPopCurrent_v2"]), + ("vector_push", &["cuCtxPushCurrent_v2"]), +]; +struct VectorFixture<'a> { + context: &'a leleka_cuda_driver::Context<'a>, + case: &'a str, + a: leleka_cuda_driver::DeviceBuffer<'a>, + b: leleka_cuda_driver::DeviceBuffer<'a>, + out: leleka_cuda_driver::DeviceBuffer<'a>, + av: Vec, + bv: Vec, + count: usize, + bytes: usize, +} +fn vector_count(case: &str) -> usize { + case.strip_prefix("vector_").unwrap().parse().unwrap_or(129) +} +fn vector_fixture<'a>( + context: &'a leleka_cuda_driver::Context<'a>, + case: &'a str, +) -> VectorFixture<'a> { + let count = vector_count(case); let bytes = count * 4; - let context = device.create_context(bytes * 4 + 16).unwrap(); let mut a = context.allocate(bytes).unwrap(); let mut b = context.allocate(bytes).unwrap(); - let mut out = context.allocate(bytes).unwrap(); - let av: Vec = (0..count) + let out = context.allocate(bytes).unwrap(); + let av: Vec<_> = (0..count) .map(|i| (i as i32 % 31 - 15) as f32 * 0.5) .collect(); - let bv: Vec = (0..count) + let bv: Vec<_> = (0..count) .map(|i| (i as i32 % 23 - 11) as f32 * 0.25) .collect(); - let encode = |v: &[f32]| { - v.iter() - .flat_map(|value| value.to_ne_bytes()) - .collect::>() - }; - a.copy_from(&encode(&av)).unwrap(); - b.copy_from(&encode(&bv)).unwrap(); - if case == "vector_bounds" { - let foreign = device.create_context(bytes * 3).unwrap(); - let foreign_input = foreign.allocate(bytes).unwrap(); - let short = context.allocate(4).unwrap(); - let odd = context.allocate(3).unwrap(); - let mut odd_out = context.allocate(3).unwrap(); - let before = trace().len(); - assert!(matches!( - context.vector_add_f32(&foreign_input, &b, &mut out), - Err(Error::ContextMismatch) - )); - assert!(context.vector_add_f32(&a, &short, &mut out).is_err()); - assert!(context.vector_add_f32(&odd, &odd, &mut odd_out).is_err()); - assert_eq!(trace().len(), before, "validation before ABI mutation"); - drop((foreign_input, short, odd, odd_out)); - foreign.close().unwrap(); + a.copy_from(&f32_bytes(&av)).unwrap(); + b.copy_from(&f32_bytes(&bv)).unwrap(); + VectorFixture { + context, + case, + a, + b, + out, + av, + bv, + count, + bytes, } - let result = if case == "vector_same_input" { - context.vector_add_f32(&a, &a, &mut out) - } else { - context.vector_add_f32(&a, &b, &mut out) - }; - let execution_failure = [ - "vector_load", - "vector_lookup", - "vector_null_load", - "vector_null_function", - "vector_launch", - "vector_sync", - "vector_launch_sync", - "vector_launch_sync_pop", - "vector_pop", - "vector_wrong_pop", - "vector_lookup_unload", - "vector_push", - ] - .contains(&case); - if execution_failure { - let error = result.unwrap_err(); - let expected = match case { - "vector_load" => vec![("cuModuleLoadData", 700)], - "vector_lookup" => vec![("cuModuleGetFunction", 700)], - "vector_lookup_unload" => vec![("cuModuleGetFunction", 700), ("cuModuleUnload", 700)], - "vector_launch" => vec![("cuLaunchKernel", 700)], - "vector_sync" => vec![("cuCtxSynchronize", 700)], - "vector_launch_sync" => vec![("cuLaunchKernel", 700), ("cuCtxSynchronize", 700)], - "vector_launch_sync_pop" => vec![ - ("cuLaunchKernel", 700), - ("cuCtxSynchronize", 700), - ("cuCtxPopCurrent_v2", 700), - ], - "vector_pop" => vec![("cuCtxPopCurrent_v2", 700)], - "vector_push" => vec![("cuCtxPushCurrent_v2", 700)], - _ => vec![], - }; - assert_eq!(cuda_errors(&error), expected); - if case == "vector_null_load" { - assert!(matches!( - error, - Error::InvalidDriverValue("cuModuleLoadData") - )); - } - if case == "vector_null_function" { - assert!(matches!( - error, - Error::InvalidDriverValue("cuModuleGetFunction") - )); - } - if case == "vector_wrong_pop" { - assert_eq!(error, Error::UnexpectedContext); - } - if [ - "vector_sync", - "vector_launch_sync", - "vector_launch_sync_pop", - "vector_pop", - "vector_wrong_pop", - "vector_lookup_unload", - ] - .contains(&case) - { - let before = trace().len(); - assert!(context.vector_add_f32(&a, &b, &mut out).is_err()); - assert!(context.allocate(4).is_err()); - assert!(a.copy_from(&encode(&av)).is_err()); - assert!(context.synchronize().is_err()); - assert_eq!(trace().len(), before, "poison admits zero native work"); - // Encourage allocator reuse before containment reads pending args. - let churn: Vec<_> = (0..1024).map(|_| Box::new([0xdeadbeefu64; 8])).collect(); - std::hint::black_box(churn); +} +fn vector_call(f: &mut VectorFixture<'_>) -> leleka_cuda_driver::Result<()> { + f.context.vector_add_f32( + &f.a, + if f.case == "vector_same_input" { + &f.a + } else { + &f.b + }, + &mut f.out, + ) +} +fn vector_child(case: &str) { + let driver = Driver::load().unwrap(); + let device = driver.device(0).unwrap(); + let bytes = vector_count(case) * 4; + let context = device.create_context(bytes * 4 + 16).unwrap(); + let mut f = vector_fixture(&context, case); + if case == "vector_bounds" { + vector_bounds(&device, &mut f); + } + let result = vector_call(&mut f); + if VECTOR_EXECUTION_FAILURES.contains(&case) { + vector_error(case, result.unwrap_err()); + if VECTOR_POISON.contains(&case) { + vector_poison_refusals(&mut f); } } else { result.unwrap(); - if case == "vector_cache" { - context.vector_add_f32(&a, &b, &mut out).unwrap(); - } - let mut output = vec![0; bytes]; - out.copy_to(&mut output).unwrap(); - let expected: Vec<_> = av - .iter() - .zip(if case == "vector_same_input" { - &av - } else { - &bv - }) - .map(|(a, b)| (a + b).to_bits()) - .collect(); - let actual: Vec<_> = output - .as_chunks::<4>() - .0 - .iter() - .map(|v| u32::from_ne_bytes(*v)) - .collect(); - assert_eq!(actual, expected, "independent exact finite f32 reference"); - let mut unchanged = vec![0; bytes]; - a.copy_to(&mut unchanged).unwrap(); - assert_eq!(unchanged, encode(&av)); - b.copy_to(&mut unchanged).unwrap(); - assert_eq!(unchanged, encode(&bv)); - if case == "vector_contexts" { - let second = device.create_context(bytes * 3).unwrap(); - let mut x = second.allocate(bytes).unwrap(); - let mut y = second.allocate(bytes).unwrap(); - let mut z = second.allocate(bytes).unwrap(); - x.copy_from(&encode(&av)).unwrap(); - y.copy_from(&encode(&bv)).unwrap(); - second.vector_add_f32(&x, &y, &mut z).unwrap(); - z.copy_to(&mut output).unwrap(); - assert_eq!( - output, - encode(&av.iter().zip(&bv).map(|(a, b)| a + b).collect::>()) - ); - drop((x, y, z)); - second.close().unwrap(); - } - } - drop((a, b, out)); - let closed = context.close(); - match case { - "vector_unload" => assert_eq!( - cuda_errors(&closed.unwrap_err()), - vec![("cuModuleUnload", 700)] - ), - "vector_close_pop" => assert_eq!( - cuda_errors(&closed.unwrap_err()), - vec![("cuCtxPopCurrent_v2", 700)] - ), - "vector_close_destroy" => assert_eq!( - cuda_errors(&closed.unwrap_err()), - vec![("cuCtxDestroy_v2", 700)] - ), - _ => closed.unwrap(), + vector_success(&device, &mut f); } + let count = f.count; + drop(f); + vector_close(case, context.close()); let rows = trace(); + vector_trace(case, count, &rows); +} +fn vector_bounds(device: &leleka_cuda_driver::Device<'_>, f: &mut VectorFixture<'_>) { + use leleka_cuda_driver::Error; + let foreign = device.create_context(f.bytes * 3).unwrap(); + let foreign_input = foreign.allocate(f.bytes).unwrap(); + let short = f.context.allocate(4).unwrap(); + let odd = f.context.allocate(3).unwrap(); + let mut odd_out = f.context.allocate(3).unwrap(); + let before = trace().len(); + assert!(matches!( + f.context.vector_add_f32(&foreign_input, &f.b, &mut f.out), + Err(Error::ContextMismatch) + )); + assert!(f.context.vector_add_f32(&f.a, &short, &mut f.out).is_err()); + assert!(f.context.vector_add_f32(&odd, &odd, &mut odd_out).is_err()); + assert_eq!(trace().len(), before, "validation before ABI mutation"); + drop((foreign_input, short, odd, odd_out)); + foreign.close().unwrap(); +} +fn vector_error(case: &str, error: leleka_cuda_driver::Error) { + use leleka_cuda_driver::Error; + let expected = VECTOR_ERRORS + .iter() + .find(|r| r.0 == case) + .map(|r| r.1) + .unwrap_or(&[]); + assert_eq!( + cuda_errors(&error), + expected.iter().map(|&s| (s, 700)).collect::>() + ); + if case == "vector_null_load" { + assert!(matches!( + error, + Error::InvalidDriverValue("cuModuleLoadData") + )); + } + if case == "vector_null_function" { + assert!(matches!( + error, + Error::InvalidDriverValue("cuModuleGetFunction") + )); + } + if case == "vector_wrong_pop" { + assert_eq!(error, Error::UnexpectedContext); + } +} +fn vector_poison_refusals(f: &mut VectorFixture<'_>) { + use leleka_cuda_driver::Error; + let before = trace().len(); + assert!(vector_call(f).is_err()); + assert_eq!( + f.context.matvec_f32(&f.a, &f.b, &mut f.out, 1, f.count), + Err(Error::ContextPoisoned) + ); + assert!(f.context.allocate(4).is_err()); + assert!(f.a.copy_from(&f32_bytes(&f.av)).is_err()); + assert!(f.context.synchronize().is_err()); + assert_eq!(trace().len(), before, "poison admits zero native work"); + let churn: Vec<_> = (0..1024).map(|_| Box::new([0xdeadbeefu64; 8])).collect(); + std::hint::black_box(churn); +} +fn vector_expected(f: &VectorFixture<'_>) -> Vec { + f.av.iter() + .zip(if f.case == "vector_same_input" { + &f.av + } else { + &f.bv + }) + .map(|(a, b)| (a + b).to_bits()) + .collect() +} +fn vector_success(device: &leleka_cuda_driver::Device<'_>, f: &mut VectorFixture<'_>) { + if f.case == "vector_cache" { + vector_call(f).unwrap(); + } + let mut output = vec![0; f.bytes]; + f.out.copy_to(&mut output).unwrap(); + let actual: Vec<_> = output + .as_chunks::<4>() + .0 + .iter() + .map(|v| u32::from_ne_bytes(*v)) + .collect(); + assert_eq!( + actual, + vector_expected(f), + "independent exact finite f32 reference" + ); + let mut unchanged = vec![0; f.bytes]; + f.a.copy_to(&mut unchanged).unwrap(); + assert_eq!(unchanged, f32_bytes(&f.av)); + f.b.copy_to(&mut unchanged).unwrap(); + assert_eq!(unchanged, f32_bytes(&f.bv)); + if f.case == "vector_contexts" { + vector_second_context(device, f, &mut output); + } +} +fn vector_second_context( + device: &leleka_cuda_driver::Device<'_>, + f: &VectorFixture<'_>, + output: &mut [u8], +) { + let second = device.create_context(f.bytes * 3).unwrap(); + let mut x = second.allocate(f.bytes).unwrap(); + let mut y = second.allocate(f.bytes).unwrap(); + let mut z = second.allocate(f.bytes).unwrap(); + x.copy_from(&f32_bytes(&f.av)).unwrap(); + y.copy_from(&f32_bytes(&f.bv)).unwrap(); + second.vector_add_f32(&x, &y, &mut z).unwrap(); + z.copy_to(output).unwrap(); + assert_eq!( + output, + f32_bytes( + &f.av + .iter() + .zip(&f.bv) + .map(|(a, b)| a + b) + .collect::>() + ) + ); + drop((x, y, z)); + second.close().unwrap(); +} +fn vector_close(case: &str, closed: leleka_cuda_driver::Result<()>) { + let operation = match case { + "vector_unload" => Some("cuModuleUnload"), + "vector_close_pop" => Some("cuCtxPopCurrent_v2"), + "vector_close_destroy" => Some("cuCtxDestroy_v2"), + _ => None, + }; + if let Some(operation) = operation { + assert_eq!(cuda_errors(&closed.unwrap_err()), vec![(operation, 700)]); + } else { + closed.unwrap(); + } +} +fn vector_trace(case: &str, count: usize, rows: &[Row]) { assert!(!rows.iter().any(|r| { [ "unsafe_pending_free", @@ -632,42 +870,63 @@ fn vector_child(case: &str) { ] .contains(&r.stage.as_str()) })); - let expected_modules = if case == "vector_contexts" { 2 } else { 1 }; + vector_cache_trace(case, count, rows); + vector_launch_sync(rows); + vector_fault_trace(case, count, rows); + vector_module_context_trace(rows); + if case != "vector_close_destroy" { + let last = rows + .iter() + .rev() + .find(|r| r.stage == "destroy" && r.code == 0) + .unwrap(); + assert_eq!(last.current, 0x11); + assert_eq!(last.live, 0); + assert_eq!(last.charged, 0); + } +} +fn vector_cache_trace(case: &str, count: usize, rows: &[Row]) { + let modules = if case == "vector_contexts" { 2 } else { 1 }; if !["vector_load", "vector_null_load", "vector_push"].contains(&case) { assert_eq!( rows.iter() .filter(|r| r.stage == "load" && r.code == 0) .count(), - expected_modules + modules ); } - if !execution_failure { - assert_eq!( - rows.iter() - .filter(|r| r.stage == "lookup" && r.code == 0) - .count(), - expected_modules - ); - let launches = if ["vector_cache", "vector_contexts"].contains(&case) { - 2 - } else { - 1 - }; - assert_eq!( - rows.iter().filter(|r| r.stage == "launch").count(), - launches - ); - assert!( - rows.iter() - .filter(|r| r.stage == "geometry") - .all(|r| r.bytes == count.div_ceil(128)) - ); - assert!( - rows.iter() - .filter(|r| r.stage == "arguments") - .all(|r| r.bytes == count) - ); + if !VECTOR_EXECUTION_FAILURES.contains(&case) { + vector_successful_cache_trace(case, count, rows, modules); } +} +fn vector_successful_cache_trace(case: &str, count: usize, rows: &[Row], modules: usize) { + assert_eq!( + rows.iter() + .filter(|r| r.stage == "lookup" && r.code == 0) + .count(), + modules + ); + let launches = if ["vector_cache", "vector_contexts"].contains(&case) { + 2 + } else { + 1 + }; + assert_eq!( + rows.iter().filter(|r| r.stage == "launch").count(), + launches + ); + assert!( + rows.iter() + .filter(|r| r.stage == "geometry") + .all(|r| r.bytes == count.div_ceil(128)) + ); + assert!( + rows.iter() + .filter(|r| r.stage == "arguments") + .all(|r| r.bytes == count) + ); +} +fn vector_launch_sync(rows: &[Row]) { for (i, row) in rows.iter().enumerate().filter(|(_, r)| r.stage == "launch") { assert!( rows[i + 1..] @@ -678,6 +937,8 @@ fn vector_child(case: &str) { ); assert!([0, 700].contains(&row.code)); } +} +fn vector_fault_trace(case: &str, count: usize, rows: &[Row]) { if [ "vector_sync", "vector_launch_sync", @@ -698,13 +959,498 @@ fn vector_child(case: &str) { "failed handle consumed once" ); } +} +fn vector_module_context_trace(rows: &[Row]) { for stage in ["load", "lookup", "unload", "launch"] { for row in rows.iter().filter(|r| r.stage == stage && r.code == 0) { assert!([0x22, 0x23].contains(&row.current)); assert_eq!(row.depth, 1); } } - if case != "vector_close_destroy" { +} + +fn f32_bytes(values: &[f32]) -> Vec { + values.iter().flat_map(|v| v.to_ne_bytes()).collect() +} +#[inline(never)] +fn rounded_product(a: f32, b: f32) -> f32 { + std::hint::black_box(a * b) +} +#[inline(never)] +fn rounded_add(a: f32, b: f32) -> f32 { + std::hint::black_box(a + b) +} +// Independent ascending binary32 oracle. Separate non-inlined operations +// publish f32 results, preventing multiplication from contracting into addition. +// Zero finite-bit tolerance; NaN payload/sign are intentionally unspecified. +fn matvec_oracle(matrix: &[f32], vector: &[f32]) -> Vec { + matrix + .chunks_exact(vector.len()) + .map(|row| { + row.iter() + .zip(vector) + .fold(0.0f32, |s, (&a, &b)| rounded_add(s, rounded_product(a, b))) + }) + .collect() +} +fn check_f32_output(bytes: &[u8], expected: &[f32]) { + assert_eq!(bytes.len(), expected.len() * 4); + for (actual, expected) in bytes.as_chunks::<4>().0.iter().zip(expected) { + let actual = f32::from_ne_bytes(*actual); + if expected.is_nan() { + assert!(actual.is_nan()); + } else { + assert_eq!( + actual.to_bits(), + expected.to_bits(), + "zero finite-bit tolerance, including signed zero/infinity" + ); + } + } +} +const ARITHMETIC_FIXTURES: &[(&[u32], &[u32], u32)] = &[ + (&[0x4b800000, 0x3f800000, 0xcb800000], &[0x3f800000; 3], 0), + (&[0xbf800000, 0x3f800001], &[0x3f800000, 0x3f7ffffe], 0), + (&[0x80000000], &[0x3f800000], 0), + (&[0], &[0xbf800000], 0), + (&[1], &[0x3f800000], 1), + (&[0x00800000], &[0x3f000000], 0x00400000), + (&[1], &[0x3f000000], 0), + (&[3], &[0x3f000000], 2), + (&[0x7f7fffff], &[0x40000000], 0x7f800000), + (&[0xff800000], &[0x3f800000], 0xff800000), + (&[0x7f800000, 0xff800000], &[0x3f800000; 2], 0x7fc00000), + (&[0x7fc00000], &[0x3f800000], 0x7fc00000), + (&[0x7f800000], &[0], 0x7fc00000), +]; +const MATVEC_EXECUTION_FAILURES: &[&str] = &[ + "matvec_load", + "matvec_lookup", + "matvec_null_load", + "matvec_null_function", + "matvec_launch", + "matvec_sync", + "matvec_launch_sync", + "matvec_launch_sync_pop", + "matvec_pop", + "matvec_wrong_pop", + "matvec_lookup_unload", + "matvec_push", +]; +const MATVEC_POISON: &[&str] = &[ + "matvec_sync", + "matvec_launch_sync", + "matvec_launch_sync_pop", + "matvec_pop", + "matvec_wrong_pop", + "matvec_lookup_unload", +]; +const MATVEC_ERRORS: &[(&str, &[&str])] = &[ + ("matvec_load", &["cuModuleLoadData"]), + ("matvec_lookup", &["cuModuleGetFunction"]), + ( + "matvec_lookup_unload", + &["cuModuleGetFunction", "cuModuleUnload"], + ), + ("matvec_launch", &["cuLaunchKernel"]), + ("matvec_sync", &["cuCtxSynchronize"]), + ( + "matvec_launch_sync", + &["cuLaunchKernel", "cuCtxSynchronize"], + ), + ( + "matvec_launch_sync_pop", + &["cuLaunchKernel", "cuCtxSynchronize", "cuCtxPopCurrent_v2"], + ), + ("matvec_pop", &["cuCtxPopCurrent_v2"]), + ("matvec_push", &["cuCtxPushCurrent_v2"]), +]; +fn matvec_arithmetic() { + let driver = Driver::load().unwrap(); + let device = driver.device(0).unwrap(); + // These expected bits are recorded independently of mock/wrapper/PTX. + assert_eq!(rounded_add(rounded_add(16777216.0, -16777216.0), 1.0), 1.0); + assert_ne!( + f32::from_bits(0x3f800001) + .mul_add(f32::from_bits(0x3f7ffffe), -1.0) + .to_bits(), + 0 + ); + for &(a, b, bits) in ARITHMETIC_FIXTURES { + check_arithmetic_fixture(&device, a, b, bits); + } + assert_eq!( + trace() + .iter() + .filter(|r| r.stage == "pending_matvec") + .count(), + 13 + ); +} +fn check_arithmetic_fixture( + device: &leleka_cuda_driver::Device<'_>, + a: &[u32], + b: &[u32], + bits: u32, +) { + let matrix: Vec<_> = a.iter().map(|&v| f32::from_bits(v)).collect(); + let vector: Vec<_> = b.iter().map(|&v| f32::from_bits(v)).collect(); + let expected = matvec_oracle(&matrix, &vector); + if f32::from_bits(bits).is_nan() { + assert!(expected[0].is_nan()); + } else { + assert_eq!(expected[0].to_bits(), bits, "recorded recurrence fixture"); + } + let budget = (matrix.len() + vector.len() + 1) * 4; + let context = device.create_context(budget).unwrap(); + let mut a = context.allocate(matrix.len() * 4).unwrap(); + let mut b = context.allocate(vector.len() * 4).unwrap(); + let mut out = context.allocate(4).unwrap(); + a.copy_from(&f32_bytes(&matrix)).unwrap(); + b.copy_from(&f32_bytes(&vector)).unwrap(); + context + .matvec_f32(&a, &b, &mut out, 1, vector.len()) + .unwrap(); + let mut bytes = [0u8; 4]; + out.copy_to(&mut bytes).unwrap(); + check_f32_output(&bytes, &expected); + drop((a, b, out)); + context.close().unwrap(); +} +struct MatvecFixture<'a> { + context: &'a leleka_cuda_driver::Context<'a>, + case: &'a str, + a: leleka_cuda_driver::DeviceBuffer<'a>, + b: leleka_cuda_driver::DeviceBuffer<'a>, + out: leleka_cuda_driver::DeviceBuffer<'a>, + matrix: Vec, + vector: Vec, + rows: usize, + columns: usize, +} +fn matvec_rows(case: &str) -> usize { + if case == "matvec_same_input" { + 1 + } else { + case.strip_prefix("matvec_").unwrap().parse().unwrap_or(129) + } +} +fn matvec_fixture<'a>( + context: &'a leleka_cuda_driver::Context<'a>, + case: &'a str, +) -> MatvecFixture<'a> { + let rows = matvec_rows(case); + let columns = if case == "matvec_n1" { 1 } else { 3 }; + let matrix: Vec<_> = (0..rows * columns) + .map(|i| (i as i32 % 37 - 18) as f32 * 0.25) + .collect(); + let vector: Vec<_> = (0..columns).map(|i| (i as f32 + 1.0) * 0.5).collect(); + let mut a = context.allocate(rows * columns * 4).unwrap(); + let mut b = context.allocate(columns * 4).unwrap(); + let out = context.allocate(rows * 4).unwrap(); + a.copy_from(&f32_bytes(&matrix)).unwrap(); + b.copy_from(&f32_bytes(&vector)).unwrap(); + MatvecFixture { + context, + case, + a, + b, + out, + matrix, + vector, + rows, + columns, + } +} +fn matvec_call(f: &mut MatvecFixture<'_>) -> leleka_cuda_driver::Result<()> { + f.context.matvec_f32( + &f.a, + if f.case == "matvec_same_input" { + &f.a + } else { + &f.b + }, + &mut f.out, + f.rows, + f.columns, + ) +} +fn matvec_child(case: &str) { + let driver = Driver::load().unwrap(); + let device = driver.device(0).unwrap(); + let context = device.create_context(65536).unwrap(); + let mut f = matvec_fixture(&context, case); + if case == "matvec_bounds" { + matvec_bounds(&device, &mut f); + } + let result = matvec_call(&mut f); + if MATVEC_EXECUTION_FAILURES.contains(&case) { + check_matvec_error(case, result.unwrap_err()); + } else { + result.unwrap(); + matvec_success(&device, &mut f); + } + if MATVEC_POISON.contains(&case) { + matvec_poison_refusals(&mut f); + release_poisoned_fixture(f); + context.close().unwrap(); + check_poison_trace(case); + return; + } + let dimensions = (f.rows, f.columns); + drop(f); + check_matvec_close(case, context.close()); + check_matvec_trace(case, dimensions); +} +fn matvec_bounds(device: &leleka_cuda_driver::Device<'_>, f: &mut MatvecFixture<'_>) { + f.out.copy_from(&vec![0x99; f.rows * 4]).unwrap(); + check_matvec_dimensions(f); + check_matvec_foreign(device, f); + check_matvec_lengths(f); + assert!(!trace().iter().any(|r| r.stage == "load")); + let mut untouched = vec![0; f.rows * 4]; + f.out.copy_to(&mut untouched).unwrap(); + assert_eq!(untouched, vec![0x99; f.rows * 4]); +} +fn check_matvec_dimensions(f: &mut MatvecFixture<'_>) { + let before = trace().len(); + let charged = f.context.allocated_bytes(); + let dimensions = [ + (0, f.columns), + (f.rows, 0), + (u32::MAX as usize + 1, f.columns), + (f.rows, u32::MAX as usize + 1), + (usize::MAX, usize::MAX), + (1, f.columns), + (f.rows, 1), + ]; + for (m, n) in dimensions { + assert!(f.context.matvec_f32(&f.a, &f.b, &mut f.out, m, n).is_err()); + } + assert_eq!(trace().len(), before); + assert_eq!(f.context.allocated_bytes(), charged); +} +fn check_matvec_foreign(device: &leleka_cuda_driver::Device<'_>, f: &mut MatvecFixture<'_>) { + use leleka_cuda_driver::Error; + let foreign = device.create_context(65536).unwrap(); + let a = foreign.allocate(f.a.len()).unwrap(); + let b = foreign.allocate(f.b.len()).unwrap(); + let mut out = foreign.allocate(f.out.len()).unwrap(); + let before = trace().len(); + assert_eq!( + f.context + .matvec_f32(&a, &f.b, &mut f.out, f.rows, f.columns), + Err(Error::ContextMismatch) + ); + assert_eq!( + f.context + .matvec_f32(&f.a, &b, &mut f.out, f.rows, f.columns), + Err(Error::ContextMismatch) + ); + assert_eq!( + f.context + .matvec_f32(&f.a, &f.b, &mut out, f.rows, f.columns), + Err(Error::ContextMismatch) + ); + assert_eq!(trace().len(), before); + drop((a, b, out)); + foreign.close().unwrap(); +} +fn check_matvec_lengths(f: &mut MatvecFixture<'_>) { + for slot in 0..3 { + let exact = [f.a.len(), f.b.len(), f.out.len()][slot]; + for bytes in [exact - 1, exact + 1, exact + 4] { + check_matvec_bad_length(f, slot, bytes); + } + } +} +fn check_matvec_bad_length(f: &mut MatvecFixture<'_>, slot: usize, bytes: usize) { + let mut bad = f.context.allocate(bytes).unwrap(); + let before = trace().len(); + let charged = f.context.allocated_bytes(); + let error = match slot { + 0 => f + .context + .matvec_f32(&bad, &f.b, &mut f.out, f.rows, f.columns), + 1 => f + .context + .matvec_f32(&f.a, &bad, &mut f.out, f.rows, f.columns), + _ => f + .context + .matvec_f32(&f.a, &f.b, &mut bad, f.rows, f.columns), + }; + assert_eq!(error, Err(leleka_cuda_driver::Error::InvalidMatvecShape)); + assert_eq!(trace().len(), before); + assert_eq!(f.context.allocated_bytes(), charged); +} +fn check_matvec_error(case: &str, error: leleka_cuda_driver::Error) { + use leleka_cuda_driver::Error; + let expected = MATVEC_ERRORS + .iter() + .find(|r| r.0 == case) + .map(|r| r.1) + .unwrap_or(&[]); + assert_eq!( + cuda_errors(&error), + expected.iter().map(|&s| (s, 700)).collect::>() + ); + match case { + "matvec_null_load" => assert_eq!(error, Error::InvalidDriverValue("cuModuleLoadData")), + "matvec_null_function" => { + assert_eq!(error, Error::InvalidDriverValue("cuModuleGetFunction")) + } + "matvec_wrong_pop" => assert_eq!(error, Error::UnexpectedContext), + _ => (), + } +} +fn matvec_poison_refusals(f: &mut MatvecFixture<'_>) { + use leleka_cuda_driver::Error; + let before = trace().len(); + assert_eq!(matvec_call(f), Err(Error::ContextPoisoned)); + assert_eq!( + f.context.vector_add_f32(&f.a, &f.b, &mut f.out), + Err(Error::ContextPoisoned) + ); + assert!(matches!(f.context.allocate(4), Err(Error::ContextPoisoned))); + assert_eq!( + f.a.copy_from(&f32_bytes(&f.matrix)), + Err(Error::ContextPoisoned) + ); + assert_eq!( + f.b.copy_to(&mut vec![0; f.columns * 4]), + Err(Error::ContextPoisoned) + ); + assert_eq!(f.context.synchronize(), Err(Error::ContextPoisoned)); + assert_eq!(trace().len(), before); +} +fn release_poisoned_fixture(f: MatvecFixture<'_>) { + let churn: Vec<_> = (0..2048).map(|_| Box::new([0xdeadbeefu64; 8])).collect(); + std::hint::black_box(&churn); + let before = trace().len(); + let poison = Err(leleka_cuda_driver::Error::ContextPoisoned); + assert_eq!(f.a.release(), poison); + assert_eq!(f.b.release(), poison); + assert_eq!(f.out.release(), poison); + assert_eq!(trace().len(), before); +} +fn check_poison_trace(case: &str) { + let rows = trace(); + assert!(!rows.iter().any(|r| r.stage == "free")); + assert_eq!( + rows.iter().filter(|r| r.stage == "unload").count(), + usize::from(case == "matvec_lookup_unload") + ); + if case.contains("sync") { + assert!( + rows.iter() + .any(|r| r.stage == "pending_matvec" && r.bytes == 3) + ); + } + check_launch_sync(&rows); +} +fn matvec_success(device: &leleka_cuda_driver::Device<'_>, f: &mut MatvecFixture<'_>) { + if f.case == "matvec_cache" { + matvec_call(f).unwrap(); + } + if f.case.contains("interleave") || f.case.starts_with("matvec_both_") { + matvec_interleave(f); + } + let expected = matvec_oracle( + &f.matrix, + if f.case == "matvec_same_input" { + &f.matrix + } else { + &f.vector + }, + ); + let mut actual = vec![0; f.rows * 4]; + f.out.copy_to(&mut actual).unwrap(); + check_f32_output(&actual, &expected); + let mut unchanged = vec![0; f.a.len()]; + f.a.copy_to(&mut unchanged).unwrap(); + assert_eq!(unchanged, f32_bytes(&f.matrix)); + let mut unchanged = vec![0; f.b.len()]; + f.b.copy_to(&mut unchanged).unwrap(); + assert_eq!(unchanged, f32_bytes(&f.vector)); + if f.case == "matvec_contexts" { + matvec_second_context(device, f, &expected); + } +} +fn matvec_interleave(f: &mut MatvecFixture<'_>) { + let mut add_out = f.context.allocate(f.rows * 4).unwrap(); + f.context + .vector_add_f32(&f.out, &f.out, &mut add_out) + .unwrap(); + matvec_call(f).unwrap(); + if f.case == "matvec_interleave_reverse" { + f.context + .vector_add_f32(&f.out, &f.out, &mut add_out) + .unwrap(); + } +} +fn matvec_second_context( + device: &leleka_cuda_driver::Device<'_>, + f: &MatvecFixture<'_>, + expected: &[f32], +) { + let second = device.create_context(65536).unwrap(); + let mut x = second.allocate(f.a.len()).unwrap(); + let mut y = second.allocate(f.b.len()).unwrap(); + let mut z = second.allocate(f.out.len()).unwrap(); + x.copy_from(&f32_bytes(&f.matrix)).unwrap(); + y.copy_from(&f32_bytes(&f.vector)).unwrap(); + second + .matvec_f32(&x, &y, &mut z, f.rows, f.columns) + .unwrap(); + let mut actual = vec![0; f.rows * 4]; + z.copy_to(&mut actual).unwrap(); + check_f32_output(&actual, expected); + drop((x, y, z)); + second.close().unwrap(); +} +fn check_matvec_close(case: &str, closed: leleka_cuda_driver::Result<()>) { + use leleka_cuda_driver::Error; + let operation = if case.contains("unload") && case != "matvec_lookup_unload" { + Some("cuModuleUnload") + } else if case.contains("pop") && !case.contains("wrong") { + Some("cuCtxPopCurrent_v2") + } else if case.contains("push") && case != "matvec_push" { + Some("cuCtxPushCurrent_v2") + } else if case == "matvec_close_destroy" { + Some("cuCtxDestroy_v2") + } else { + None + }; + if case.contains("wrong_pop") { + assert_eq!(closed, Err(Error::UnexpectedContext)); + } else if let Some(operation) = operation { + let mut expected = vec![(operation, 700)]; + if case == "matvec_unload_destroy" { + expected.push(("cuCtxDestroy_v2", 700)); + } + assert_eq!(cuda_errors(&closed.unwrap_err()), expected); + } else { + closed.unwrap(); + } +} +fn check_matvec_trace(case: &str, dimensions: (usize, usize)) { + let rows = trace(); + check_launch_sync(&rows); + if !MATVEC_EXECUTION_FAILURES.contains(&case) { + check_matvec_cache_trace(case, dimensions, &rows); + } + if case.starts_with("matvec_both_") { + check_matvec_both_cleanup(case, &rows); + } + if case.contains("interleave") { + let order: Vec<_> = rows + .iter() + .filter(|r| ["unload_add", "unload_matvec"].contains(&r.stage.as_str())) + .map(|r| r.stage.as_str()) + .collect(); + assert_eq!(order, ["unload_add", "unload_matvec"]); + } + if !["matvec_close_destroy", "matvec_unload_destroy"].contains(&case) { let last = rows .iter() .rev() @@ -715,3 +1461,100 @@ fn vector_child(case: &str) { assert_eq!(last.charged, 0); } } +fn check_matvec_cache_trace(case: &str, (m, n): (usize, usize), rows: &[Row]) { + let modules = if case == "matvec_contexts" + || case.contains("interleave") + || case.starts_with("matvec_both_") + { + 2 + } else { + 1 + }; + assert_eq!( + rows.iter() + .filter(|r| r.stage == "load" && r.code == 0) + .count(), + modules + ); + assert_eq!( + rows.iter() + .filter(|r| r.stage == "lookup" && r.code == 0) + .count(), + modules + ); + check_matvec_geometry((m, n), rows); + let launches = matvec_launch_count(case); + assert_eq!( + rows.iter().filter(|r| r.stage == "launch").count(), + launches + ); +} +fn matvec_launch_count(case: &str) -> usize { + if case == "matvec_interleave_reverse" { + 4 + } else if case.contains("interleave") || case.starts_with("matvec_both_") { + 3 + } else if ["matvec_cache", "matvec_contexts"].contains(&case) { + 2 + } else { + 1 + } +} +fn check_matvec_geometry((m, n): (usize, usize), rows: &[Row]) { + assert!( + rows.iter() + .filter(|r| r.stage == "matvec_rows") + .all(|r| r.bytes == m) + ); + assert!( + rows.iter() + .filter(|r| r.stage == "matvec_columns") + .all(|r| r.bytes == n) + ); + assert!( + rows.iter() + .filter(|r| r.stage == "geometry") + .all(|r| r.bytes == m.div_ceil(128)) + ); +} + +fn check_matvec_both_cleanup(case: &str, rows: &[Row]) { + assert_eq!(rows.iter().filter(|r| r.stage == "module_add").count(), 1); + assert_eq!( + rows.iter().filter(|r| r.stage == "module_matvec").count(), + 1 + ); + let attempts = rows.iter().filter(|r| r.stage == "unload").count(); + let expected = if case.ends_with("matvec") { + if case.contains("push") { 1 } else { 2 } + } else if case.contains("push") { + 0 + } else { + 1 + }; + assert_eq!( + attempts, expected, + "fault suppresses unsafe later slot unload" + ); +} +fn check_launch_sync(rows: &[Row]) { + assert!(!rows.iter().any(|r| { + [ + "unsafe_pending_free", + "unsafe_pending_unload", + "stack_arguments", + ] + .contains(&r.stage.as_str()) + })); + for (i, _) in rows.iter().enumerate().filter(|(_, r)| r.stage == "launch") { + assert_eq!( + rows[i + 1..] + .iter() + .take_while(|r| r.stage != "pop") + .filter(|r| r.stage == "sync") + .count(), + 1, + "exactly one mandatory sync after each attempt" + ); + } +} diff --git a/docs/cuda-fixed-matvec.md b/docs/cuda-fixed-matvec.md new file mode 100644 index 00000000..eef9e027 --- /dev/null +++ b/docs/cuda-fixed-matvec.md @@ -0,0 +1,501 @@ +# Fixed CUDA f32 matrix-vector requirements + +Bounded requirements delta for served item **STRA-140**, parent **STRA-102**, +read fresh on 2026-10-08. Written against source revision +`b9519f967af43514331e29e778bd2605d8e4b98b` before implementation. The active MCP +item and [project charter](../PROJECT_CHARTER.md) are the business/specification +authority; this file is the task's reviewable requirements artifact, not a second +project backlog or an assertion that implementation has passed qualification. + +The [bootstrap contract](cuda-driver-bootstrap.md) owns driver loading, platform, +copy staging and resource ownership. The [vector-add contract](cuda-fixed-vector-add.md) +owns the existing fixed operation. STRA-140 adds one bounded fixed matvec action +without changing either historical qualification receipt. Production remains +independent of Python, Strata and a CUDA Toolkit runtime dependency. + +## Scope, actor and outcome + +An internal engine developer explicitly enables `cuda-driver`, loads the driver, +creates a private context and supplies three owned device buffers and dimensions +to `Context::matvec_f32`. The matrix is contiguous row-major f32, the vector has +one value per column, and the output has one value per row. Success means the +attempted kernel completed and the caller's previous context was restored. + +Using `Context::matvec_f32`, the developer can compute the recurrence below over +valid owned buffers, yielding a completed output or structured failure. Invalid +inputs must yield failure before any CUDA mutation. After uncertain completion +or restoration, future work on the context must yield refusal without native work. + +This unit is an application/library deliverable with executable automated +verification. It introduces no serving endpoint, deployment integration, model +loader, inference, tensor view/stride, transposition, batching, quantization, +arbitrary executable, caller stream or caller launch geometry. Default feature +admission stays off. It establishes neither model compatibility nor a speed/SLO +claim; the serial column recurrence is a correctness baseline. + +## FR-MATVEC-1 — exact shapes, bounds and ownership + +The public interface takes an immutable matrix buffer, immutable vector buffer, +exclusive mutable output buffer, and host `usize` row/column dimensions. Dimensions +are checked before conversion to the private ABI; no truncating cast is allowed. + +| Quantity | Required admission bound / meaning | +| --- | --- | +| Rows `M` | `1 <= M <= u32::MAX` (4,294,967,295) | +| Columns `N` | `1 <= N <= u32::MAX` (4,294,967,295) | +| Matrix elements | Checked `M * N`; product need not fit u32 | +| Matrix bytes | Checked `4 * M * N`, exactly the matrix buffer length | +| Vector bytes | Checked `4 * N`, exactly the vector buffer length | +| Output bytes | Checked `4 * M`, exactly the output buffer length | +| Every byte length | Nonzero, fits host `usize`, and `<= isize::MAX` | +| Allocation capacity | Existing context byte budget bounds actual live allocations; matvec allocates no device buffer implicitly | +| Launch | Fixed block `(128, 1, 1)`; checked `grid.x = ceil(M / 128)`, `1 <= grid.x <= i32::MAX`; grid y/z one | +| Addressing | 64-bit row/index/byte offsets; checked allocation address ranges cannot wrap | + +These are representation and ownership limits, not a promise that the GPU has +enough memory or will admit the fixed launch. On Linux64 the matrix constraint +is `M * N <= floor(isize::MAX / 4) = 2,305,843,009,213,693,951` elements, +further restricted by actual owned allocation sizes and the caller's context +budget. The three buffers normally require `4 * (M*N + N + M)` live bytes, +alongside other context allocations. When the two inputs share one allocation, +charge that allocation once, as the existing allocation accounting does. + +The safe API currently exposes only whole owned allocations: `DeviceBuffer::len` +is an exact byte length, with no distinct logical length, spare capacity, +subslice, offset view, cloned handle or raw/imported pointer API. Consequently an +oversized buffer is invalid even if it could contain the requested tensor. +Check each expected byte length for exact equality; do not accept a prefix. +Also reject odd/nonmultiple-four lengths. Shape and overflow refusal must be +possible without allocating a giant test buffer or executing CUDA. + +Both inputs and output must belong to this exact `Context` instance. Equal device +ordinals or separate contexts on the same device do not suffice. Reject poisoned +contexts and absent/released resource handles before push/load/lookup/launch. +No validation refusal changes output bytes, allocation accounting or cache state. + +### Output alias contract + +Inputs may share the same immutable allocation when exact shape checks permit +it; for whole buffers that means `M = 1`. A caller may reuse an output allocation +between completed calls, but output must be a distinct allocation from both +inputs during each call. Rust's immutable input and exclusive mutable output +borrows prevent a safe caller from passing the same buffer as input and output. +Defensively reject equality of output/input device allocation identities before +native mutation, matching the existing vector-add check. Do not create a public +unsafe bypass to test that defense. + +Distinct valid live whole allocations from the same CUDA allocator do not +overlap. The present API therefore needs no tensor-view overlap semantics. A +future imported pointer or view API would require a separately specified range +overlap contract before it could consume this operation. Validate non-wrapping +address extents in the private boundary so arithmetic does not rely on silent +u64 wrapping; invalid synthetic address extents must never be launched. Private +alias tests exercise allocation-identity refusal; they do not invent a public +view/import facility. + +## FR-MATVEC-2 — deterministic arithmetic and access + +For every row `r = 0 .. M-1`, define binary32 recurrence: + +```text +s = +0.0_f32 +for c = 0 .. N-1 in ascending order: + p = round_nearest_even_f32(matrix[r*N + c] * vector[c]) + s = round_nearest_even_f32(s + p) +output[r] = s +``` + +Use a separate `mul.rn.f32` followed by `add.rn.f32` for every column. No FMA, +floating-point MAD, reassociation, parallel/warp/tree reduction, approximate +operation, saturation, `.ftz`, or f64 accumulator may replace this recurrence. +The accumulator starts at positive zero, including for `N = 1`; it does not +initialize from the first product. All f32 bit patterns are valid inputs. +Signed zeros, subnormals, overflow and infinities follow these operations. NaN +results are compared by classification; NaN payload and sign are not guaranteed. + +The arithmetic follows NVIDIA's archived PTX definitions for +[multiply](https://docs.nvidia.com/cuda/archive/13.0.1/parallel-thread-execution/index.html#floating-point-instructions-mul) +and [add](https://docs.nvidia.com/cuda/archive/13.0.1/parallel-thread-execution/index.html#floating-point-instructions-add). +Explicit rounding modifiers preserve the required separate operation semantics; +assembler acceptance alone does not demonstrate installed-driver execution. + +One thread owns one row, checks `r < M` before any memory access, loops columns +in order and stores output once after the last addition. Other threads may +process other rows independently. Compute `r`, `r*N+c` and scaled offsets with +64-bit arithmetic, including threads in the last partial block. The loop must +terminate correctly at `N = u32::MAX`; increments and comparisons may not wrap +into another iteration. Matrix/vector are never written. Threads beyond `M` +perform no read or write. No atomics, shared-memory reductions, external symbols +or indirect calls participate. + +## FR-MATVEC-3 — trusted executable and fixed launch ABI + +Embed one bounded NUL-terminated matvec PTX image containing exactly the fixed +matvec entry `leleka_matvec_f32`. Preserve the existing image's PTX 7.0, +`sm_75`, and `.address_size 64` baseline; incompatible driver/target combinations +return explicit failures. No fallback or external PTX lookup is allowed. + +The private `kernelParams` table has five entries, in this order: + +| Position | Value stored in owned host argument storage | ABI width | +| --- | --- | --- | +| 0 | Matrix device allocation address | u64 | +| 1 | Vector device allocation address | u64 | +| 2 | Output device allocation address | u64 | +| 3 | Rows `M` | u32 | +| 4 | Columns `N` | u32 | + +Each table entry points to its typed host scalar, not directly to a device +address interpreted as a host pointer. Shared bytes are zero; stream and +`extra` are null. Geometry comes only from FR-MATVEC-1. The existing fixed +16-symbol loader suffices; no new driver symbol, caller executable/name, +function/module handle, callback or launch option enters the public API. + +Cache only a fully loaded/validated matvec module and non-null function under +its owner context. Repeated successful calls reuse that cache; separate contexts +never share it. The matvec cache adds at most one usable module/function per +context. It must coexist with the existing vector-add cache without replacing, +misidentifying or invalidating vector-add's function. Cache topology and shared +cleanup integration require the ARCH decision below before implementation. + +## FR-MATVEC-4 — completion, argument lifetime and faults + +Create and stabilize all scalar storage and its five-entry pointer table before +CUDA mutation. Maintain the existing raw-owned stable allocation discipline: +moving the argument owner must not move or retag referenced storage. No caller +host pointer is retained. Scalars/table stay live through mandatory completion. + +Push the owned context, check load/lookup and non-null success handles, attempt +the launch once, then synchronize after **every attempted launch**, even a +launch returning failure. Preserve primary and subsequent sync/pop errors in +operation order. Load/lookup failure does not count as an attempted launch. +After every successful push, attempt pop and verify it popped the owned handle. + +Return success only when launch, synchronization and restoration all succeed. +After native execution failure, output is unspecified and cannot be presented +as a successfully computed result. A launch failure followed by successful sync +and restoration follows existing policy; it does not by itself imply poisoning. +Never retry a failed launch automatically. + +Failed sync makes completion uncertain: poison the context, permanently retain +all potentially referenced host argument storage, keep buffers/module contained +by the context, and refuse future allocate/copy/sync/kernel work without native +calls. Do not reclaim retained argument storage merely because a later destroy +succeeds. A failed or mismatched pop likewise poisons the context; successful +sync alone cannot justify a success result after restoration failure. Existing +copy staging and thread/borrow safety remain part of the contract. + +## FR-MATVEC-5 — cache cleanup and teardown + +On lookup failure after load, consume the local usable module handle before its +single unload attempt in the owned current context. Preserve lookup, unload and +pop failures in order. Failed unload poisons the context; no retry, cache +publication, handle reuse or healthy cache reinitialization is allowed. + +Healthy teardown unloads each usable owned fixed module at most once after work +completed, before context destruction. Pending/uncertain work or a poisoned +context must never be followed by explicit module unload or buffer free. +Any unload/restoration failure must suppress further unsafe cleanup mutations; +context destruction remains the final containment attempt. Explicit fallible +close reports errors; drop stays best effort and nonpanicking. Failed destroy +retains the loaded library. Permanently failed driver cleanup is not a cleanup +success; repeated poisoned contexts may accumulate resources, so this unit +cannot claim process-wide recovery or bounded serving memory. + +## Security and non-functional acceptance + +| Dimension | Metric / threshold | Verification | +| --- | --- | --- | +| Critical usability | One typed synchronous operation, structured failure, no public raw launch surface | API/source review and synthetic caller | +| Reliability / performance | Success requires launch+sync+restoration; zero automatic retries; one mandatory completion sync per attempted launch; no latency/throughput assertion | ABI and fault traces | +| Capacity / concurrency | Checked bounds above; whole allocations within context budget; creating thread only; at most one additional usable matvec cache/context | Boundary, accounting, cache and compile gates | +| Security / tenancy | In-process context isolation; no network/tenant admission is introduced; zero foreign-context/aliased-output launches; only private fixed executable | Ownership, adversarial alias and ABI review | +| Audit / retention | Only synthetic fixtures; generated traces/artifacts outside Git; record exact source/tool identities and cleanup | Artifact and tracked-file inspection | +| Observability | Fixed operation names and driver codes; preserve primary/cleanup order; errors disclose no pointer/PTX dumps | Error assertions/review | +| Accessibility / i18n | No UI surface or new locale; structured errors remain available to the existing caller | Public-surface review | +| Rate / admission | Synchronous operation on one owning thread with the existing byte budget; no process recovery/rate SLA | API, budget and poison checks | +| Deploy / rollback | Existing opt-in default off; no production consumer or new runtime dependency; caller can omit the new operation | Feature/dependency/consumer inspection | +| Support | Load/lookup/launch/sync/cleanup failures diagnosable; no new production SLA | Fault matrix and documented residuals | +| AI dependence | Zero model/LLM calls in this operation | Consumer/source inspection | +| Integrity / consistency | Inputs unchanged; exact recurrence; no success for partial/uncertain output; only bounded fixed cache persists | Oracle, canary and trace checks | +| Backup / recovery | No durable data created; uncertain teardown retained/reported, never claimed recovered | Fault/source review | +| Privacy | No PII/model/request data in committed fixtures or gate evidence | Fixture/artifact review | +| Maintainability | Existing 16-symbol ABI; bounded fixed matvec module; no new normal dependency | Source/ABI/dependency review | +| Compatibility | Linux64 explicit opt-in; preserve bootstrap/vector-add and ownership behavior; static-musl loader stays unqualified | Existing regression and platform gates | +| Cost / efficiency | CPU-only fixture and offline assembly for this unit; no GPU/device/driver/model access | Recorded container guards and commands | + +## Acceptance mapping and planned verification + +Expected values come from this recurrence, independently recorded fixtures and +the official ABI, not from wrapper code or PTX parsing. The fake driver witnesses +host argument/dataflow and cleanup; it does not execute PTX. The mock's arithmetic +and oracle must have contraction/reassociation disabled and establish binary32 +rounding at each multiply and add; a tolerant f64 dot product is not the oracle. +Declare **zero finite-bit tolerance** against this reference before verification; +compare signed zero bits and non-finite classifications, excluding NaN payloads. + +| Served acceptance criterion | Requirement(s) | Required positive and adversarial evidence | +| --- | --- | --- | +| AC-1: checked typed operation | FR-MATVEC-1 | Exact shapes, rectangular matrix and whole-allocation ownership; zero M/N; each dimension u32 max/max+1; checked product/scaling/isize/address/grid bounds; one-byte short/long and nonmultiple4 lengths for each buffer; foreign context on same device; output aliases each input; accepted immutable same-input case M=1; poisoned/refused handles. Refusals produce zero new CUDA trace entries and unchanged accounting/output/cache. Giant limits use pure/private admission instruments, not giant allocations. | +| AC-2: trusted executable | FR-MATVEC-3, FR-MATVEC-5 | Exact PTX bytes/hash and entry; five argument widths/order/values; fixed grid/block/shared/stream/extra; cache reuse and separate contexts; interleave matvec/vector-add; missing fixed symbols fail pre-init; no public arbitrary PTX/name/geometry API. | +| AC-3: column order and separate rounding | FR-MATVEC-2 | Distinct rows/columns detect transpose/stride errors; M=1 and N=1; M=127/128/129 and larger partial block; varying N; input/canary preservation; independent order/FMA-sensitive fixtures; PTX instruction/control-flow inspection plus pinned offline assembly and inspectable emitted instruction evidence. | +| AC-4: lifetime and poison/cleanup | FR-MATVEC-4, FR-MATVEC-5 | Delayed mock reads retained five-argument table/scalars at sync and containment after failed sync, with allocator churn; push/load/lookup/null-success/launch/sync/pop/wrong-pop/unload/destroy faults; launch+sync+pop and lookup+unload combinations; no unload/free while pending; no retry/reuse; preserved error order; healthy unload before destroy and one unload attempt per module. | +| AC-5: CPU and GPU-hidden gates | All | Preserve existing bootstrap/vector-add mock, default/platform, thread/lifetime compile, format and enabled-FFI lint gates; run new ABI/oracle/boundary/fault checks in disposable Linux CPU fixture; pinned offline PTX assembly with no installed driver calls or exposed GPU/device. Report actual counts and receipts; no GPU/model/quality/speed inference. | + +Arithmetic adversaries must include the row `[2^24, 1, -2^24]` with all-one +vector (ascending recurrence yields positive zero; a reordered sum can yield +one), and row `[-1, 1+2^-23]` with vector `[1, 1-2^-23]` (separate rounding yields +positive zero; fusing the second multiply/add yields `-2^-46`). Add signed-zero, +subnormal, ties, overflow, infinity and NaN-classification fixtures. These are +fixture expectations, not measured GPU results. + +The offline gate must record exact PTX (including its embedded NUL) and assembler +output hashes, pinned image/tool version, target/flags, full argv, source/commit, +host/container architecture, environment/device guards, test counts, exit codes, +and cleanup. Inspect executable instructions/control flow, not comments or the +mere presence of opcode substrings. Establish the ascending loop and separate +multiply/add/no FMA in the recorded offline artifact; its claim is limited to +that tool/target. Installed-driver JIT/numerical execution remains separate. +Keep generated artifacts out of Git and remove only owned disposable resources. + +```mermaid +sequenceDiagram + participant Caller as Internal caller + participant Context as Owned Rust context + participant Driver as Fixed Driver ABI + Caller->>Context: matvec_f32(matrix, vector, output, M, N) + Context->>Context: Validate shape, ownership, alias, poison and bounds + alt Validation refusal + Context-->>Caller: Structured error, no CUDA mutation + else Valid + Context->>Context: Own stable five-argument storage + Context->>Driver: Push owned context + Driver-->>Context: Push result + alt Push failure + Context-->>Caller: Structured push error, no launch + else Owned context entered + opt Cache absent + Context->>Driver: Load trusted matvec, look up fixed entry + Driver-->>Context: Handles or load/lookup failure + end + alt Kernel available + Context->>Driver: Attempt fixed launch once + Driver-->>Context: Launch result + Context->>Driver: Mandatory synchronize, including launch error + Driver-->>Context: Completion result + opt Completion uncertain + Context->>Context: Poison and retain referenced storage/resources + end + else No kernel + Context->>Driver: Single safe partial-module cleanup if needed + end + Context->>Driver: Pop, verify owned handle + Driver-->>Context: Restoration result + Context-->>Caller: Success only if launch, sync and restoration succeeded + end + end +``` + +## Lifecycle and architecture inputs + +**Design need: architectural.** The new public buffer operation crosses the safe +Rust ownership/validation boundary into private FFI and fixed executable code, +and adds a second fixed-kernel lifetime under the existing context poison and +teardown state. This classification comes from served AC-2/AC-4 and the existing +`Context::kernel`, `fixed_kernel`, `unload_kernel`, `LaunchArguments` and +`DeviceBuffer` source at the pinned revision. It requires an ARCH pass before DEV. +This BA artifact does not select cache topology or author an architecture option +matrix. + +ARCH must confirm the single-thread-per-row, ascending-column mapping and checked +u64 addresses meet the caps; five stable host arguments preserve raw ownership; +matvec and vector-add retain distinct function identities; the additional cache +stays bounded; and an unload/pop fault while tearing down either operation +prevents unsafe subsequent unload/free while preserving final destruction/error +reporting. Return any incompatible requirement for refinement before code changes. + +BA has resolved the served row/column and output-alias questions from the fixed +u32 launch convention and exact whole-buffer ownership surface, with overflow +checks above. No user clarification remains for those routine constraints. +Architecture confirmation remains outstanding. No new business-rule conflict was +found with the referenced bootstrap/vector-add/charter invariants. + +Lifecycle inputs for root coordination: clarification deliverable is this +contract; design needs the ARCH decision; backend deliverable is the bounded +typed operation and private PTX/FFI integration; testing deliverable is executable +automated CPU and offline assembly evidence. No frontend, visual-composition, +marketing or deployment/runtime-operation artifact is requested. Those scope +observations are not lifecycle waivers or stage closures; root records applicable +stages and gate evidence through the active served process. Existing task +estimates are not re-estimated by this BA unit. + +No active host-local `.leasevibe.yaml` pointer was supplied and none is present in +this worktree; host settings are unavailable, never inferred or copied. Root +owns coordination records. This BA unit writes only this file, performs no build, +test suite, assembly, GPU, inference, server, commit or publication operation, +and reports no implementation gate as passed. Static-musl loading, installed +driver/JIT execution, whole-model quality/protocol and paired performance remain +the separate qualification boundaries named in the foundation contracts. + +Standing Defaults (§0.10): report honestly, do not cut corners, follow applicable +rules, continue the authorized backlog through root coordination, and be concise. + +## Architecture decision + +**Status: selected for implementation.** This decision is bounded to STRA-140 at +`b9519f967af43514331e29e778bd2605d8e4b98b`. The user authorized completion and +autonomous routine implementation choices; root confirmed that authorization for +these reversible local seams. It selects no new technology, serving topology or +model scope. FR-MATVEC-1 through FR-MATVEC-5 remain the governing contract. + +### Drivers and alternatives + +Workload archetype: synchronous, explicitly enabled, single-thread-owned numerical +library operation. RPS, latency SLO and production recovery are unspecified because +this unit has no serving consumer or throughput claim. + +| Driver | Evidence / constraint | Design consequence | +| --- | --- | --- | +| Correctness and completion | Charter priorities; FR-MATVEC-2/-4 | Serial ascending recurrence and mandatory completion before success | +| Capacity / concurrency | FR-MATVEC-1/-3; existing `Context` and `Rc` ownership | Two bounded fixed caches per context, creating thread only | +| Isolation and operability | Existing `enter`, `CurrentGuard`, `combine`, `destroy` | One context poison state; ordered fallible cleanup and final containment | +| Cost / deployment | Existing `cuda-driver` opt-in, fixed16 ABI and libc dependency | No new runtime dependency or installed Toolkit requirement | +| Data / organization | Three transient owned buffers; existing Rust/FFI boundary | Data Model: N/A for this operation; no durable state, UI or new team/process boundary | + +| Option | Workload / scale | Latency / cold load | Operations / cost | Debugging / readiness | Isolation | Portability / lock-in | +| --- | --- | --- | --- | --- | --- | --- | +| **A: two named cache slots, closed private operation selector** | Exact two-operation bound | Each image loads once on first valid use | Two modules maximum; existing cleanup machinery | Distinct identities, localized source changes | Context owns both; shared poison | Existing Driver/PTX limits only | +| B: one combined image and two functions | Bounded, but couples existing operation to new image | One module load; matvec bytes load for vector-add callers | One unload, broader regression surface | Changes historical vector-add image identity | Same owner and poison | Same Driver/PTX limits | +| C: replaceable single cache or generic kernel registry | Replacement causes reload; registry adds unnecessary growth policy | Reloads or generalized lookup | More invalidation/ownership policy | More state and generic dispatch to audit | Requires extra eviction/lifetime rules | Encourages a future arbitrary executable surface | + +- A pros: preserves vector-add executable identity, isolates lazy initialization, + and makes the two-module bound explicit. Cons: cleanup must sequence two slots. +- B pros: one module lifecycle. Cons: changes the already qualified image and + couples vector-add admission to matvec loading; rejected for this bounded delta. +- C pros: replacement can cap one module, and a registry can accommodate future + operations. Cons: adds reloads or speculative generality; rejected because the + requirements need coexistence of exactly two trusted operations. + +**Architecture Decision: A.** **Architecture Alternatives Considered: B and C** +with the rejection reasons above. The architecture-strategy user-decision step +is satisfied by the existing implementation authorization confirmed by root; +there is no new unresolved external architecture choice to request. + +### Selected source seams and invariants + +In `crates/cuda-driver/src/lib.rs`, retain `FixedKernel` and introduce two named +`Cell>` slots for vector-add and matvec. A private closed +`FixedOperation` enum selects only those slots and their trusted FFI bindings. +It carries no caller bytes, names, handles or launch options. Publish a slot only +after module load and non-null function lookup both succeed. Cache reuse is +per-operation and per-context; no process/global map or eviction is introduced. + +Keep safe validation and orchestration in `lib.rs`; all raw pointer handling +stays in `ffi.rs`. Add a pure checked matvec shape helper producing three expected +byte lengths, ABI rows/columns and row grid. Require exact buffer lengths and +exact context identity, live context/buffer handles, and output allocation +inequality before native calls. Use checked dimensions/product/scaling and +`valid_size`; compute ceil(M/128) in u64 before bounded conversion. Add a private +FFI extent check using checked u64 base-plus-byte-length for each live buffer; +synthetic wraparound refuses before `enter`. Inputs sharing the same whole +allocation remain valid when M=1. A structured matvec shape/range error may be +added; ownership, alias and poison errors retain their existing meanings and +driver errors retain operation/code and `combine` ordering. + +In `ffi.rs`, embed `matvec.ptx` with a final NUL alongside the unchanged vector-add +image. The closed selector matches each image and fixed C entry name explicitly. +Extend both enabled and unsupported API implementations consistently; keep the +existing sixteen symbol resolutions and their pre-init missing-symbol behavior. +Keep vector-add's four-argument launch unchanged; add a private matvec launch +with the same fixed geometry/shared/stream/extra policy and five-argument owner. +Do not introduce a public or crate-generic raw parameter launch interface. + +Matvec argument storage contains three u64 addresses, two separate u32 scalars +(rows, columns), and five host parameter pointers. Convert its allocation with +`Box::into_raw` before forming field pointers using raw projections; its moving +owner contains only `NonNull` and never recreates a reference to the whole +allocation while the pointers are live. Populate every scalar/table entry before +`enter`. Reconstruct the Box exactly once before any launch or after successful +sync; on failed sync permanently forget the owner, including its pointer table. +Moving the owner or borrowing the owner for launch must not move/retag the +storage. A later successful destroy never reclaims forgotten arguments. + +`matvec.ptx` uses the fixed five-entry ABI and PTX7.0/sm_75/address64 baseline. +Compute row as wide block-index times 128 plus widened thread-index, guard row +against widened M before memory access, and use u64 for N, column counter, +row*N+column and byte offsets. A u64 counter allows N=u32::MAX to terminate +without wrap. Begin with positive-zero bits, issue separate `mul.rn.f32` then +`add.rn.f32` for each ascending column, and store once. This is a correctness +baseline; neither source shape nor offline assembler acceptance proves installed +driver execution or performance. + +Both operations use the same `poisoned` cell and `CurrentGuard`. After an attempted +launch, synchronize exactly once even on launch error, then attempt and verify +pop after every successful push. Compose launch, sync and pop errors in that +order. Lookup failure consumes its local module before one unload attempt; +unload failure poisons the shared context, and no partial cache is published. +Load/lookup failure has no launch sync. No automatic launch or unload retry occurs. + +Refactor `unload_kernel` into a bounded slot-cleanup helper and sequential +`unload_kernels`: vector-add slot first, then matvec slot. Each helper consumes +its usable slot before an unload attempt, checks shared poison before push, +unloads only with the owned context current, then finishes the guard. A push, +unload, failed pop or wrong-pop failure poisons the context before another slot +can mutate CUDA. Thus failure in the first cleanup suppresses second unload; +failure in the second still suppresses later explicit frees. A poisoned slot is +only discarded as a usable Rust handle; its native resource remains contained +by the context. `destroy` always performs the final owned non-current context +destruction attempt and preserves earlier cleanup errors; failed destroy retains +the library. Existing buffer free admission through `enter` supplies the shared +poison defense. Drop stays nonpanicking. This is containment, not recovery. + +The level above this change comprises typed owned resources in `lib.rs`, private +Driver bindings and argument ownership in `ffi.rs`, and trusted executable bytes +in PTX; `Context` orchestrates those boundaries. This change belongs inside those +existing units because they own shape admission, module lifetime and completion. +A serving/model layer or public general kernel executor would be appropriate +only if separately authorized consumer/launch contracts existed; neither does. +No durable-state capability or persistence-layer change is introduced. + +### Handoff and revisit conditions + +Required DEV paths are `crates/cuda-driver/src/lib.rs` (API, checked admission, +cache and teardown, inline pure boundary tests), `crates/cuda-driver/src/ffi.rs` +(closed fixed bindings, extent validation and argument ownership, inline private +tests), new `crates/cuda-driver/src/matvec.ptx`, and +`scripts/test-cuda-fixed-ptx.sh` (extend existing pinned offline gate, including +inspectable instruction/control-flow evidence). Automated fixture integration +belongs to the separately routed test owner in existing +`crates/cuda-driver/tests/mock_cuda.c`, +`crates/cuda-driver/tests/mock_driver.rs` and +`scripts/test-cuda-driver-bootstrap.sh`; this decision does not transfer its claim. +No DevOps/IaC work, dependency, CI topology or new child task is implied. + +FR-MATVEC acceptance cases remain mandatory. In addition to shape/rounding cases, +the cross-operation witnesses must interleave add/matvec/add and matvec/add/matvec, +prove distinct function/module identity and one lazy load per slot, and inject +each slot's unload/pop failure with both caches populated. After any poison, +attempt the other operation, allocation, copy, sync and releases: none may call +CUDA. Delayed mock reads must dereference all five arguments at sync and pending +containment after owner movement/allocator churn; no unload/free may precede +uncertain completion. Pure boundary tests cover address wrap and giant geometry +without allocating giant buffers. The independent oracle retains zero finite-bit +tolerance, signed-zero bits and non-finite classification limits declared above. + +The safe Rust to private native execution crossing merits §809 review; root +records the canonical served threat-model artifact before DESIGN closes, using +the trust-boundary input returned with this decision. No committed threat-model +copy substitutes for that served carrier. LIGHT/FULL, implementation and GPU +gates remain root-coordinated; this section reports no such gate as passed. + +Revisit only when a separately specified third fixed operation needs generalized +reuse, asynchronous completion is introduced, or views/imported pointers create +range overlap. First specify its admission/ownership/cleanup contract, then +extend or replace these seams under a new decision and qualification gates. +Rollback for this unit is omission of the new API/image changes and restoration +of the existing vector-add cache path; no stored data migration is needed. +Screened companion decisions (argument layout, u64 counter, fixed teardown order) +are reversible local choices or directly required by FR-MATVEC, so none satisfies +all three grounds for an additional durable ADR. No BA correction is required; +installed-driver/JIT, static-musl loading, model quality and paired performance +remain separately qualified boundaries. No implementation ambiguity remains. diff --git a/scripts/test-cuda-driver-bootstrap.sh b/scripts/test-cuda-driver-bootstrap.sh index 5255f80c..98737206 100755 --- a/scripts/test-cuda-driver-bootstrap.sh +++ b/scripts/test-cuda-driver-bootstrap.sh @@ -20,14 +20,15 @@ if [[ "${1:-}" == --inside ]]; then work="$(mktemp -d /tmp/leleka-cuda-mock.XXXXXX)" trap 'result=$?; rm -rf "$work" || { if [[ "$result" == 0 ]]; then result=1; fi; }; exit "$result"' EXIT mkdir -p "$work/complete" "$work/missing" - cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -shared -fPIC \ + cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -ffp-contract=off -fno-fast-math -shared -fPIC \ "${repo_root}/crates/cuda-driver/tests/mock_cuda.c" -o "$work/complete/libcuda.so.1" - cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -shared -fPIC -DMOCK_MISSING_DTOH \ + cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -ffp-contract=off -fno-fast-math -shared -fPIC \ + -DMOCK_MISSING_DTOH \ "${repo_root}/crates/cuda-driver/tests/mock_cuda.c" -o "$work/missing/libcuda.so.1" for symbol in cuInit cuDriverGetVersion cuDeviceGet cuCtxCreate_v2 cuCtxDestroy_v2 \ cuCtxPushCurrent_v2 cuCtxPopCurrent_v2 cuCtxSynchronize cuMemAlloc_v2 cuMemFree_v2 cuMemcpyHtoD_v2 cuModuleLoadData cuModuleGetFunction cuModuleUnload cuLaunchKernel; do mkdir "$work/missing_$symbol" - cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -shared -fPIC \ + cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -ffp-contract=off -fno-fast-math -shared -fPIC \ "-D${symbol}=mock_replaced_${symbol}" "${repo_root}/crates/cuda-driver/tests/mock_cuda.c" \ -o "$work/missing_$symbol/libcuda.so.1" done @@ -35,7 +36,7 @@ if [[ "${1:-}" == --inside ]]; then sha256sum "$work/complete/libcuda.so.1" "$work/missing/libcuda.so.1" sha256sum "${repo_root}/crates/cuda-driver/Cargo.toml" \ "${repo_root}/crates/cuda-driver/src/lib.rs" "${repo_root}/crates/cuda-driver/src/ffi.rs" \ - "${repo_root}/crates/cuda-driver/src/vector_add.ptx" \ + "${repo_root}/crates/cuda-driver/src/vector_add.ptx" "${repo_root}/crates/cuda-driver/src/matvec.ptx" \ "${repo_root}/crates/cuda-driver/tests/mock_cuda.c" "${repo_root}/crates/cuda-driver/tests/mock_driver.rs" rustup component list --installed rustc --version @@ -44,8 +45,12 @@ if [[ "${1:-}" == --inside ]]; then cd "$repo_root" cargo fmt --manifest-path "${repo_root}/Cargo.toml" --all -- --check cargo test --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --lib + cargo test --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver \ + --features cuda-driver --lib cargo clippy --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --all-targets --all-features -- -D warnings - LELEKA_CUDA_MOCK_HARNESS=1 LELEKA_CUDA_MOCK_ROOT="$work" \ + MOCK_CUDA_ADD_PTX="${repo_root}/crates/cuda-driver/src/vector_add.ptx" \ + MOCK_CUDA_MATVEC_PTX="${repo_root}/crates/cuda-driver/src/matvec.ptx" \ + 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 rlib="$(find "$work/target/debug/deps" -maxdepth 1 -name 'libleleka_cuda_driver-*.rlib' -print -quit)" @@ -86,6 +91,19 @@ RS "$work/reject.rs" -o "$work/reject" 2>"$work/reject.log"; then echo '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 'vector output alias compile refusal: PASS' + cat > "$work/reject.rs" <<'RS' +use leleka_cuda_driver::Driver; +fn main(){ + let driver=Driver::load().unwrap(); + let context=driver.device(0).unwrap().create_context(16).unwrap(); + let mut buffer=context.allocate(4).unwrap(); + context.matvec_f32(&buffer,&buffer,&mut buffer,1,1).unwrap(); +} +RS + 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 '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' cargo tree --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --edges normal exit 0 fi @@ -102,6 +120,7 @@ cleanup() { if [[ -n "$fixture_image" ]]; then docker image rm "$fixture_image" >/dev/null || failed=1; fi rm -rf "$staging" || failed=1 if [[ "$result" == 0 && "$failed" == 1 ]]; then result=1; fi + if [[ "$failed" == 0 ]]; then echo 'CPU mock owned containers/image/files removed; shared base retained'; fi exit "$result" } trap cleanup EXIT diff --git a/scripts/test-cuda-fixed-ptx.sh b/scripts/test-cuda-fixed-ptx.sh index f558b0b3..e694e04a 100755 --- a/scripts/test-cuda-fixed-ptx.sh +++ b/scripts/test-cuda-fixed-ptx.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Offline assembly acceptance only; no installed driver, GPU, or PTX execution. +# Pinned offline assembly/disassembly only; no installed driver/GPU execution. set -euo pipefail [[ $# == 0 ]] || { echo 'Usage: scripts/test-cuda-fixed-ptx.sh' >&2; exit 2; } repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -16,7 +16,7 @@ cleanup() { } trap cleanup EXIT python3 - "$repo_root" "$work" <<'PY' -import hashlib, json, pathlib, sys, tarfile, urllib.request +import hashlib, json, pathlib, re, sys, tarfile, urllib.request root, work = map(pathlib.Path, sys.argv[1:]) lock = json.loads((root/'deploy/cuda-toolkit.lock.json').read_text()) component = next(row for row in lock['components'] if row['component'] == 'cuda_nvcc') @@ -24,26 +24,69 @@ expected = '48e35be3cfbf4b4fbc16828eaec8a7048ee789403049dc409f7b643d6259cf7a' assert component['version']=='13.0.88' and component['sha256']==expected assert component['relative_path']=='cuda_nvcc/linux-x86_64/cuda_nvcc-linux-x86_64-13.0.88-archive.tar.xz' assert int(component['size'])==26657716 -url='https://developer.download.nvidia.com/compute/cuda/redist/'+component['relative_path'] -with urllib.request.urlopen(url, timeout=60) as response: - data=response.read(26657717) -assert len(data)==26657716 and hashlib.sha256(data).hexdigest()==expected -archive=work/'nvcc.tar.xz'; archive.write_bytes(data) -with tarfile.open(archive, 'r:xz') as source: - member=source.getmember('cuda_nvcc-linux-x86_64-13.0.88-archive/bin/ptxas') - assert member.isfile() and member.size < 100_000_000 - binary=source.extractfile(member).read() -assert binary[:4]==b'\x7fELF' -(work/'ptxas').write_bytes(binary); (work/'ptxas').chmod(0o755) -ptx=(root/'crates/cuda-driver/src/vector_add.ptx').read_bytes() -assert 0clean.index(required[-2]) +ops=[line.split()[0] for line in statements if not line.startswith('.')] +assert not any(re.match(r'(fma|mad)\..*f32|.*\.ftz',op) for op in ops) +assert sum(op.startswith('st.global') for op in ops)==1 +assert sum(op.startswith('ld.global') for op in ops)==2 +assert not any(op.startswith(('atom','call','red','st.shared','ld.shared')) for op in ops) +print('Executable PTX dataflow: widened row guard before access, +zero, u64 ascending counter, ' + 'row*N+c, separate mul/add, single final store: PASS') PY +echo "Source root=$repo_root commit=$(git -C "$repo_root" rev-parse HEAD) host=$(uname -sm)" +shasum -a 256 "$repo_root/crates/cuda-driver/src/ffi.rs" "$repo_root/scripts/test-cuda-fixed-ptx.sh" docker pull --platform linux/amd64 "$image" >/dev/null docker image inspect "$image" --format 'Pinned assembly CPU base {{.Id}} architecture={{.Architecture}}' container="$(docker create --platform linux/amd64 --runtime runc --user 65532:65532 \ @@ -54,19 +97,81 @@ configuration="$(docker inspect "$container" --format '{{.HostConfig.NetworkMode [[ "$configuration" == 'none|runc|false|65532:65532|0|0|0|[ALL]|[no-new-privileges]' ]] echo "PTX assembly container $container: $configuration" docker start "$container" >/dev/null -# Docker cp writes the container rootfs rather than this running tmpfs on some -# daemon versions. Stream only the two verified files into the owned tmpfs. -docker exec -i "$container" sh -c 'cat > /tmp/ptxas && chmod 0755 /tmp/ptxas' < "$work/ptxas" -docker exec -i "$container" sh -c 'cat > /tmp/vector_add.ptx' < "$work/vector_add.ptx" +for file in ptxas nvdisasm vector_add.ptx matvec.ptx; do + docker exec -i "$container" sh -c "cat > /tmp/$file" < "$work/$file" +done +docker exec "$container" chmod 0755 /tmp/ptxas /tmp/nvdisasm docker exec "$container" bash -euc ' for device in /dev/nvidia* /dev/dri/*; do [[ ! -e "$device" ]] || exit 1; done [[ "$(awk '\''/^Cap(Eff|Prm|Bnd):/{print $2}'\'' /proc/self/status)" == $'\''0000000000000000\n0000000000000000\n0000000000000000'\'' ]] if ldconfig -p 2>/dev/null | grep -q "libcuda\.so"; then exit 1; fi uname -sm /tmp/ptxas --version - echo "argv: /tmp/ptxas -arch=sm_120 /tmp/vector_add.ptx -o /tmp/vector_add.cubin" - /tmp/ptxas -arch=sm_120 /tmp/vector_add.ptx -o /tmp/vector_add.cubin - sha256sum /tmp/ptxas /tmp/vector_add.ptx /tmp/vector_add.cubin - test -s /tmp/vector_add.cubin - echo "Pinned PTX assembler acceptance: PASS (no GPU execution)" + /tmp/nvdisasm --version + for name in vector_add matvec; do + echo "argv: /tmp/ptxas -arch=sm_120 /tmp/$name.ptx -o /tmp/$name.cubin" + /tmp/ptxas -arch=sm_120 "/tmp/$name.ptx" -o "/tmp/$name.cubin" + sha256sum /tmp/ptxas /tmp/nvdisasm "/tmp/$name.ptx" "/tmp/$name.cubin" + test -s "/tmp/$name.cubin" + done + echo "argv: /tmp/nvdisasm -c /tmp/matvec.cubin" + /tmp/nvdisasm -c /tmp/matvec.cubin > /tmp/matvec.sass + echo "argv: /tmp/nvdisasm -cfg /tmp/matvec.cubin" + /tmp/nvdisasm -cfg /tmp/matvec.cubin > /tmp/matvec.cfg.dot + sha256sum /tmp/matvec.sass /tmp/matvec.cfg.dot + cat /tmp/matvec.sass /tmp/matvec.cfg.dot + echo "Pinned PTX assembler acceptance: PASS (two images; no GPU execution)" ' +docker exec "$container" cat /tmp/matvec.sass > "$work/matvec.sass" +docker exec "$container" cat /tmp/matvec.cfg.dot > "$work/matvec.cfg.dot" +python3 - "$work" <<'PY' +import pathlib,re,sys +root=pathlib.Path(sys.argv[1]);sass=(root/'matvec.sass').read_text() +instructions=[] +for line in sass.splitlines(): + match=re.search(r'/\*[0-9a-fA-F]+\*/\s+((?:@!?P\d+\s+)?[A-Z][^;]*);',line) + if match:instructions.append(match.group(1).strip()) +assert instructions,'no emitted executable instructions' +ops=[re.sub(r'^@!?P\d+\s+','',s).split()[0].split('.')[0] for s in instructions] +assert 'FMUL' in ops and 'FADD' in ops and 'FFMA' not in ops and 'FMAD' not in ops +assert 'LDG' in ops and 'STG' in ops and 'BRA' in ops and 'EXIT' in ops +cfg=(root/'matvec.cfg.dot').read_text() +assert '->' in cfg and 'FMUL' in cfg and 'FADD' in cfg +# Pinned sm_120 machine dataflow, including the assembler's four-column +# unrolling. Loads may be scheduled ahead; accumulator dependencies preserve +# ascending addition order. Each check addresses executable operands/edges. +assert instructions.index('IMAD.WIDE.U32 R2, R5, 0x80, R2') < instructions.index('ISETP.GE.U64.AND P0, PT, R2, UR4, PT') +exit_guard=instructions.index('@P0 EXIT') +assert exit_guard < min(i for i,op in enumerate(ops) if op in ['LDG','STG']) +assert 'MOV.64 R4, RZ' in instructions and 'MOV R0, RZ' in instructions +loop=sass.split('.L_x_1:',1)[1].split('.L_x_0:',1)[0] +loop_instructions=[s for s in instructions if s in [ + 'FMUL R15, R14, R15', 'FADD R15, R15, R0', + 'FMUL R18, R18, R19', 'FMUL R20, R20, R21', + 'FADD R15, R15, R18', 'FADD R15, R15, R20', + 'FMUL R22, R22, R23', 'FADD R0, R15, R22']] +assert loop_instructions==[ + 'FMUL R15, R14, R15', 'FADD R15, R15, R0', + 'FMUL R18, R18, R19', 'FMUL R20, R20, R21', + 'FADD R15, R15, R18', 'FADD R15, R15, R20', + 'FMUL R22, R22, R23', 'FADD R0, R15, R22'] +for statement in ['IADD.64 R4, R4, 0x4','ISETP.GE.U64.AND P1, PT, R4, UR6, PT', + 'LDG.E R15, desc[UR8][R12.64]', 'LDG.E R14, desc[UR8][R16.64]', + 'LDG.E R19, desc[UR8][R12.64+0x4]', 'LDG.E R18, desc[UR8][R16.64+0x4]', + 'LDG.E R21, desc[UR8][R12.64+0x8]', 'LDG.E R20, desc[UR8][R16.64+0x8]', + 'LDG.E R23, desc[UR8][R12.64+0xc]', 'LDG.E R22, desc[UR8][R16.64+0xc]']: + assert statement in loop +assert '".L_x_1":exit0:e -> ".L_x_1":entry:n' in cfg +assert 'FADD R0, R0, R13' in instructions and 'FADD R0, R0, R19' in instructions +assert '@P0 FMUL R7, R8, R11' in instructions and '@P0 FADD R0, R0, R7' in instructions +assert ops.count('STG')==1 +# HFMA2 here materializes integer address high-half zero only; it is not an +# f32 recurrence operation. Explicitly identify it instead of hiding it. +assert [s for s in instructions if 'HFMA2' in s]==['HFMA2 R3, -RZ, RZ, 0, 0'] +print('Emitted dataflow/CFG: row guard, positive-zero accumulator, u64 column induction, ' + 'ascending four/two/one column additions and final single store: PASS') +print('HFMA2 R3 zero materialization is address initialization; no FFMA/FMAd in binary32 recurrence') +print('Actual emitted instruction counts:',len(instructions),{op:ops.count(op) for op in sorted(set(ops))}) +print('Emitted separate FMUL/FADD, no FMA/MAD, guarded memory/control-flow artifact: PASS; ' + 'inspect printed operands/loop edges for this pinned target only') +PY