From 1789ef99282951fd0dcb4bfc58c8377c0bc5b3e7 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 22:03:02 +0100 Subject: [PATCH 1/7] STRA-338 size2 cd1: stream_k_off, async owned copy, gr batch preview, bringup trace and closed kernels functions under the limits --- .../src/arch_ptx/stream_k_off_fn.rs | 35 +-- crates/cuda-driver/src/async_owned_copy.rs | 207 ++++++++++-------- crates/cuda-driver/src/batch_gr_preview.rs | 54 +++-- .../src/bringup_trace_enabled_fn.rs | 41 ++-- .../src/closed_kernels/s_gemv_slots_fn.rs | 47 ++-- .../impl_closedkernels_2.rs | 115 ++++++---- .../impl_closedkernels_2_2.rs | 136 ++++++++---- 7 files changed, 372 insertions(+), 263 deletions(-) diff --git a/crates/cuda-driver/src/arch_ptx/stream_k_off_fn.rs b/crates/cuda-driver/src/arch_ptx/stream_k_off_fn.rs index bdfbe3a4..71591de9 100644 --- a/crates/cuda-driver/src/arch_ptx/stream_k_off_fn.rs +++ b/crates/cuda-driver/src/arch_ptx/stream_k_off_fn.rs @@ -10,37 +10,44 @@ use super::*; /// (looked at most every 250 ms, so an A/B can switch arms inside one engine). On a native sm_120 device with none of these set it /// is false and every grid is exactly the one of the sealed code. pub(crate) fn stream_k_off() -> bool { - use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; + use std::sync::atomic::Ordering::Relaxed; static FIXED: std::sync::OnceLock = std::sync::OnceLock::new(); static PATHS: std::sync::OnceLock<[Option; 2]> = std::sync::OnceLock::new(); - static CHECKED: std::sync::OnceLock = std::sync::OnceLock::new(); - static LAST_MS: AtomicU64 = AtomicU64::new(u64::MAX); - static PRESENT: [AtomicBool; 2] = [const { AtomicBool::new(false) }; 2]; let fixed = *FIXED.get_or_init(|| std::env::var_os("LELEKA_MMQ_NO_STREAMK").is_some_and(|v| v != "0")); let paths = PATHS.get_or_init(|| { ["LELEKA_MMQ_NO_STREAMK_FILE", "LELEKA_MMQ_STREAMK_FILE"] .map(|name| std::env::var_os(name).map(std::path::PathBuf::from)) }); if paths.iter().any(Option::is_some) { - let now = CHECKED.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64; - let last = LAST_MS.load(Relaxed); - if last == u64::MAX || now.saturating_sub(last) >= 250 { - LAST_MS.store(now, Relaxed); - for (path, present) in paths.iter().zip(&PRESENT) { - present.store(path.as_ref().is_some_and(|p| p.exists()), Relaxed); - } - } + let [no_streamk, streamk] = marker_files_present(paths); // the file of `LELEKA_MMQ_STREAMK_FILE` forces the stream-K grid back on (an A/B control inside one engine) - if PRESENT[1].load(Relaxed) { + if streamk { return false; } - if PRESENT[0].load(Relaxed) { + if no_streamk { return true; } } fixed || STREAM_K_AVOIDED.load(Relaxed) } +/// Presence of the two marker files (`LELEKA_MMQ_NO_STREAMK_FILE`, `LELEKA_MMQ_STREAMK_FILE`), looked at most every 250 ms. +fn marker_files_present(paths: &[Option; 2]) -> [bool; 2] { + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; + static CHECKED: std::sync::OnceLock = std::sync::OnceLock::new(); + static LAST_MS: AtomicU64 = AtomicU64::new(u64::MAX); + static PRESENT: [AtomicBool; 2] = [const { AtomicBool::new(false) }; 2]; + let now = CHECKED.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64; + let last = LAST_MS.load(Relaxed); + if last == u64::MAX || now.saturating_sub(last) >= 250 { + LAST_MS.store(now, Relaxed); + for (path, present) in paths.iter().zip(&PRESENT) { + present.store(path.as_ref().is_some_and(|p| p.exists()), Relaxed); + } + } + [PRESENT[0].load(Relaxed), PRESENT[1].load(Relaxed)] +} + /// EXPERIMENTAL diagnostic (STRA-235): `LELEKA_FORCE_SMS=N` makes the MMQ and MTP-prefill owners plan their stream-K grids (and size /// their fixup workspaces) for N SMs instead of the device's count, e.g. 48 on a 5090 to run the laptop's decomposition there. pub(crate) fn forced_sms(real: u32) -> u32 { diff --git a/crates/cuda-driver/src/async_owned_copy.rs b/crates/cuda-driver/src/async_owned_copy.rs index 927cd55f..6daaba8e 100644 --- a/crates/cuda-driver/src/async_owned_copy.rs +++ b/crates/cuda-driver/src/async_owned_copy.rs @@ -68,6 +68,49 @@ fn close_input_pairs(pairs: Vec<(DeviceBuffer<'_>, Vec)>) -> Result<()> { } result } +/// Unregisters every still-registered source (clearing its flag on success); failures fold in order. +fn unregister_sources( + api: &api::AsyncApi, + pairs: &mut OwnedCopyPairs<'_>, + registered: &mut [bool; MAX_ASYNC_COPY_PAIRS], + count: usize, +) -> Result<()> { + let mut result = Ok(()); + for i in 0..count { + if registered[i] { + let (_, source) = pairs[i].as_mut().expect("registered owner retained"); + let release = api.unregister(source); + if release.is_ok() { + registered[i] = false; + } + result = combine(result, release); + } + } + result +} +/// Destroys the event then the stream (dropping each handle on success); failures fold into `result` in order. +fn destroy_handles( + api: &api::AsyncApi, + event: &mut Option, + stream: &mut Option, + mut result: Result<()>, +) -> Result<()> { + if let Some(handle) = *event { + let release = api.destroy_event(handle); + if release.is_ok() { + *event = None; + } + result = combine(result, release); + } + if let Some(handle) = *stream { + let release = api.destroy_stream(handle); + if release.is_ok() { + *stream = None; + } + result = combine(result, release); + } + result +} impl Context<'_> { /// Start a bounded whole-owner batch on its own NON_BLOCKING stream. /// The complete owned host capacities must fit this Context's byte budget; @@ -77,34 +120,7 @@ impl Context<'_> { &'ctx self, pairs: Vec<(DeviceBuffer<'ctx>, Vec)>, ) -> Result> { - let admitted = (|| -> Result<()> { - if !(1..=MAX_ASYNC_COPY_PAIRS).contains(&pairs.len()) { - return Err(Error::InvalidSize); - } - let mut capacities = [(0usize, 0usize); MAX_ASYNC_COPY_PAIRS]; - for (i, (destination, source)) in pairs.iter().enumerate() { - if !std::ptr::eq(destination.context, self) { - return Err(Error::ContextMismatch); - } - if destination.bytes != source.len() { - return Err(Error::ShapeMismatch { expected: destination.bytes, actual: source.len() }); - } - let handle = destination.handle.ok_or(Error::ContextPoisoned)?; - handle.validate_extent(destination.bytes)?; - capacities[i] = (source.len(), source.capacity()); - for (prior, _) in &pairs[..i] { - let prior_handle = prior.handle.ok_or(Error::ContextPoisoned)?; - if handle.overlaps(destination.bytes, prior_handle, prior.bytes) { - return Err(Error::OutputAliasesInput); - } - } - } - admit_count_and_capacities(&capacities[..pairs.len()], self.budget)?; - if self.is_poisoned() { - return Err(Error::ContextPoisoned); - } - Ok(()) - })(); + let admitted = self.admit_owned_pairs(&pairs); if let Err(primary) = admitted { return combine(Err(primary), close_input_pairs(pairs)); } @@ -113,9 +129,54 @@ impl Context<'_> { Ok(api) => Rc::new(api), Err(primary) => return combine(Err(primary), close_input_pairs(pairs)), }; + let mut pending = PendingOwnedCopy::new(self, pairs, api); + let guard = self.enter()?; + let launch = pending.enqueue(); + let result = combine(launch, guard.finish()); + if let Err(primary) = result { + return pending.launch_failed(primary); + } + Ok(pending) + } + fn admit_owned_pairs(&self, pairs: &[(DeviceBuffer<'_>, Vec)]) -> Result<()> { + if !(1..=MAX_ASYNC_COPY_PAIRS).contains(&pairs.len()) { + return Err(Error::InvalidSize); + } + let mut capacities = [(0usize, 0usize); MAX_ASYNC_COPY_PAIRS]; + for i in 0..pairs.len() { + capacities[i] = self.admit_owned_pair(pairs, i)?; + } + admit_count_and_capacities(&capacities[..pairs.len()], self.budget)?; + if self.is_poisoned() { + return Err(Error::ContextPoisoned); + } + Ok(()) + } + /// Checks pair `i` against this context and the pairs before it; returns its `(len, capacity)`. + fn admit_owned_pair(&self, pairs: &[(DeviceBuffer<'_>, Vec)], i: usize) -> Result<(usize, usize)> { + let (destination, source) = &pairs[i]; + if !std::ptr::eq(destination.context, self) { + return Err(Error::ContextMismatch); + } + if destination.bytes != source.len() { + return Err(Error::ShapeMismatch { expected: destination.bytes, actual: source.len() }); + } + let handle = destination.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_extent(destination.bytes)?; + for (prior, _) in &pairs[..i] { + let prior_handle = prior.handle.ok_or(Error::ContextPoisoned)?; + if handle.overlaps(destination.bytes, prior_handle, prior.bytes) { + return Err(Error::OutputAliasesInput); + } + } + Ok((source.len(), source.capacity())) + } +} +impl<'ctx> PendingOwnedCopy<'ctx> { + fn new(context: &'ctx Context<'ctx>, pairs: Vec<(DeviceBuffer<'ctx>, Vec)>, api: Rc) -> Self { let count = pairs.len(); let mut pending = PendingOwnedCopy { - context: self, + context, pairs: std::array::from_fn(|_| None), count, api: Some(api), @@ -129,26 +190,27 @@ impl Context<'_> { for (i, pair) in pairs.into_iter().enumerate() { pending.pairs[i] = Some(pair); } - let guard = self.enter()?; - let launch = pending.enqueue(); - let result = combine(launch, guard.finish()); - if let Err(primary) = result { - // Any native failure may report older asynchronous work. No pending - // bytes or registrations are reclaimable under uncertain completion. - if pending.attempted || self.is_poisoned() { - self.poisoned.set(true); - pending.retain_uncertain(); - return Err(primary); - } - // No copy has been attempted: release every successful partial - // registration/event/stream, preserving the initial native error. - let cleanup = pending.drain_and_close(); - return combine(Err(primary), cleanup); + pending + } + fn launch_failed(&mut self, primary: Error) -> Result { + // Any native failure may report older asynchronous work. No pending + // bytes or registrations are reclaimable under uncertain completion. + if self.attempted || self.context.is_poisoned() { + self.context.poisoned.set(true); + self.retain_uncertain(); + return Err(primary); } - Ok(pending) + // No copy has been attempted: release every successful partial + // registration/event/stream, preserving the initial native error. + let cleanup = self.drain_and_close(); + combine(Err(primary), cleanup) + } + /// Marks the context poisoned and retains every owner; hands the error back. + fn poison_and_retain(&mut self, error: Error) -> Error { + self.context.poisoned.set(true); + self.retain_uncertain(); + error } -} -impl<'ctx> PendingOwnedCopy<'ctx> { pub fn len(&self) -> usize { self.count } @@ -189,14 +251,7 @@ impl<'ctx> PendingOwnedCopy<'ctx> { } return Err(Error::ContextPoisoned); } - let guard = match self.context.enter() { - Ok(guard) => guard, - Err(primary) => { - self.context.poisoned.set(true); - self.retain_uncertain(); - return Err(primary); - } - }; + let guard = self.context.enter().map_err(|primary| self.poison_and_retain(primary))?; let api = self.api.as_ref().expect("private live ABI"); let event = self.event.expect("actual recorded event"); let observed = if wait { api.wait(event).map(|()| true) } else { api.query(event) }; @@ -207,11 +262,7 @@ impl<'ctx> PendingOwnedCopy<'ctx> { Ok(true) } Ok(false) => Ok(false), - Err(primary) => { - self.context.poisoned.set(true); - self.retain_uncertain(); - Err(primary) - } + Err(primary) => Err(self.poison_and_retain(primary)), } } /// Poll actual CUDA event; the caller receives this same pending owner when @@ -248,42 +299,12 @@ impl<'ctx> PendingOwnedCopy<'ctx> { self.retain_uncertain(); return Err(Error::ContextPoisoned); } - let guard = match self.context.enter() { - Ok(guard) => guard, - Err(error) => { - self.context.poisoned.set(true); - self.retain_uncertain(); - return Err(error); - } - }; + let guard = self.context.enter().map_err(|error| self.poison_and_retain(error))?; let api = self.api.as_ref().expect("private live ABI"); - let mut result = Ok(()); // Completed work no longer references host storage. Still attempt every // unregister/destroy on partial cleanup failure, retaining failed owners. - for i in 0..self.count { - if self.registered[i] { - let (_, source) = self.pairs[i].as_mut().expect("registered owner retained"); - let release = api.unregister(source); - if release.is_ok() { - self.registered[i] = false; - } - result = combine(result, release); - } - } - if let Some(event) = self.event { - let release = api.destroy_event(event); - if release.is_ok() { - self.event = None; - } - result = combine(result, release); - } - if let Some(stream) = self.stream { - let release = api.destroy_stream(stream); - if release.is_ok() { - self.stream = None; - } - result = combine(result, release); - } + let mut result = unregister_sources(api, &mut self.pairs, &mut self.registered, self.count); + result = destroy_handles(api, &mut self.event, &mut self.stream, result); result = combine(result, guard.finish()); if result.is_err() { self.context.poisoned.set(true); diff --git a/crates/cuda-driver/src/batch_gr_preview.rs b/crates/cuda-driver/src/batch_gr_preview.rs index 8463d010..a256a905 100644 --- a/crates/cuda-driver/src/batch_gr_preview.rs +++ b/crates/cuda-driver/src/batch_gr_preview.rs @@ -35,6 +35,14 @@ mod installed { _ => Err(Error::InvalidQwenShape), } } + fn gr_functions(context: &Context<'_>, module: ffi::ModuleHandle) -> Result<[ffi::FunctionHandle; 4]> { + Ok([ + context.driver.api.qwen_function(module, Operation::LayerGate)?, + context.driver.api.qwen_function(module, Operation::FinalGate)?, + context.driver.api.qwen_function(module, Operation::InjectResidual)?, + context.driver.api.qwen_function(module, Operation::Norm)?, + ]) + } pub struct GrBatchPreview<'ctx> { context: &'ctx Context<'ctx>, module: Option, @@ -51,15 +59,7 @@ mod installed { Ok(v) => v, Err(e) => return combine(Err(e), guard.finish()), }; - let result = (|| { - Ok([ - context.driver.api.qwen_function(module, Operation::LayerGate)?, - context.driver.api.qwen_function(module, Operation::FinalGate)?, - context.driver.api.qwen_function(module, Operation::InjectResidual)?, - context.driver.api.qwen_function(module, Operation::Norm)?, - ]) - })(); - let functions = match result { + let functions = match gr_functions(context, module) { Ok(v) => v, Err(e) => { let cleanup = context.driver.api.unload(module); @@ -108,22 +108,36 @@ mod installed { if buffers.len() != layout.count { return Err(Error::InvalidQwenShape); } - let first = buffers[0].handle.ok_or(Error::ContextPoisoned)?; - let mut handles = [first; 9]; - let mut bytes = [0; 9]; - for (i, b) in buffers.iter().enumerate() { - if !std::ptr::eq(context, b.context) { - return Err(Error::ContextMismatch); - } - handles[i] = b.handle.ok_or(Error::ContextPoisoned)?; - bytes[i] = b.bytes; - } + let (handles, bytes) = self.buffer_handles(buffers)?; ranges_layout(operation, layout, handles, bytes, false)?; if context.allocated_bytes() > context.budget_bytes() { return Err(Error::BudgetExceeded); } let kernel = self.functions[slot(operation)?]; - let mut arguments = Arguments::with_layout(operation, layout, handles, epsilon); + let arguments = Arguments::with_layout(operation, layout, handles, epsilon); + self.launch_synchronized(kernel, operation, arguments) + } + fn buffer_handles(&self, buffers: &[&DeviceBuffer<'_>]) -> Result<([ffi::BufferHandle; 9], [usize; 9])> { + let first = buffers[0].handle.ok_or(Error::ContextPoisoned)?; + let mut handles = [first; 9]; + let mut bytes = [0; 9]; + for (i, b) in buffers.iter().enumerate() { + if !std::ptr::eq(self.context, b.context) { + return Err(Error::ContextMismatch); + } + handles[i] = b.handle.ok_or(Error::ContextPoisoned)?; + bytes[i] = b.bytes; + } + Ok((handles, bytes)) + } + fn launch_synchronized( + &self, + kernel: ffi::FunctionHandle, + operation: Operation, + arguments: Arguments, + ) -> Result<()> { + let context = self.context; + let mut arguments = arguments; let guard = context.enter()?; let launch = context.driver.api.launch_qwen(kernel, operation, &mut arguments); self.launch_attempts.set(self.launch_attempts.get() + 1); diff --git a/crates/cuda-driver/src/bringup_trace_enabled_fn.rs b/crates/cuda-driver/src/bringup_trace_enabled_fn.rs index cbbc5be2..20330956 100644 --- a/crates/cuda-driver/src/bringup_trace_enabled_fn.rs +++ b/crates/cuda-driver/src/bringup_trace_enabled_fn.rs @@ -62,6 +62,11 @@ impl fmt::Display for Error { if let Some(message) = self.environment_message().or_else(|| self.validation_message()) { return f.write_str(message); } + self.fmt_dynamic(f) + } +} +impl Error { + fn fmt_dynamic(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::MissingSymbol(symbol) => write!(f, "missing CUDA Driver symbol {symbol}"), Self::InvalidDriverValue(operation) => { @@ -73,18 +78,15 @@ impl fmt::Display for Error { Self::ShapeMismatch { expected, actual } => { write!(f, "byte shape mismatch: expected {expected}, got {actual}") } - Self::GraphOutOfMemory { window: 0 } => { - write!( - f, - "the verifier commit graph did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)" - ) - } - Self::GraphOutOfMemory { window } => { - write!( - f, - "the verifier window graph T={window} did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)" - ) - } + Self::GraphOutOfMemory { window: 0 } => f.write_str( + "the verifier commit graph did not fit in device memory \ + (cuGraphInstantiateWithFlags: out of memory)", + ), + Self::GraphOutOfMemory { window } => write!( + f, + "the verifier window graph T={window} did not fit in device memory \ + (cuGraphInstantiateWithFlags: out of memory)" + ), Self::Multiple { primary, secondary } => { write!(f, "{primary}; subsequent error: {secondary}") } @@ -139,11 +141,16 @@ impl<'driver> Device<'driver> { } return combine(Err(error), cleanup); } - Ok(Context { - driver: self.driver, + Ok(Context::fresh(self.driver, handle, self.ordinal, byte_budget)) + } +} +impl<'driver> Context<'driver> { + fn fresh(driver: &'driver Driver, handle: ffi::ContextHandle, ordinal: i32, budget: usize) -> Self { + Context { + driver, handle: Some(handle), - ordinal: self.ordinal, - budget: byte_budget, + ordinal, + budget, allocated: Cell::new(0), poisoned: PoisonCell::new(false), vector_add_kernel: Cell::new(None), @@ -167,7 +174,7 @@ impl<'driver> Device<'driver> { experimental: std::array::from_fn(|_| Cell::new(None)), window_modules: RefCell::new(Vec::new()), deferred_frees: RefCell::new(Vec::new()), - }) + } } } impl PoisonCell { diff --git a/crates/cuda-driver/src/closed_kernels/s_gemv_slots_fn.rs b/crates/cuda-driver/src/closed_kernels/s_gemv_slots_fn.rs index a4e60063..361435fb 100644 --- a/crates/cuda-driver/src/closed_kernels/s_gemv_slots_fn.rs +++ b/crates/cuda-driver/src/closed_kernels/s_gemv_slots_fn.rs @@ -7,38 +7,29 @@ use super::*; pub fn s_gemv_slots(plan: &Plan, form: &SForm, n_in: i64, n_out: i64, offset_present: bool) -> Vec { let offset = if offset_present { Slot::Ptr(Role::Offset) } else { Slot::Null }; let tpr = Slot::I32(plan.launch.block[0] as i32); - let head = |with_offset: bool| -> Vec { - let mut v = vec![Slot::Ptr(Role::X), Slot::Ptr(Role::Codes), Slot::Ptr(Role::Scales)]; - if with_offset { - v.push(offset); - } - v.push(Slot::Ptr(Role::Y)); - v.extend([Slot::I64(n_in), Slot::I64(n_out)]); - v - }; + let slots = |with_offset: bool, tail: &[Slot]| head_slots(offset, n_in, n_out, with_offset, tail); let (bias, codebook, has_offset) = (Slot::I32(form.code_bias), Slot::I32(form.codebook as i32), Slot::I32(i32::from(form.has_offset))); + let (group, shift) = (Slot::I32(form.group_elems), Slot::I32(plan.group_shift)); match plan.kernel { - Kernel::SGemv(_) | Kernel::SGemvQ8k(_) => { - let mut v = head(true); - v.extend([bias, codebook, Slot::I32(form.group_elems), has_offset]); - v - } - Kernel::SGemvSplit(_) => { - let mut v = head(true); - v.extend([bias, codebook, Slot::I32(form.group_elems), Slot::I32(plan.group_shift), has_offset, tpr]); - v - } - Kernel::SGemvQ8kSplit(_) | Kernel::SGemvQ80Split(_) => { - let mut v = head(true); - v.extend([bias, codebook, Slot::I32(plan.group_shift), has_offset]); - v - } - Kernel::S2Gemv => head(false), + Kernel::SGemv(_) | Kernel::SGemvQ8k(_) => slots(true, &[bias, codebook, group, has_offset]), + Kernel::SGemvSplit(_) => slots(true, &[bias, codebook, group, shift, has_offset, tpr]), + Kernel::SGemvQ8kSplit(_) | Kernel::SGemvQ80Split(_) => slots(true, &[bias, codebook, shift, has_offset]), + Kernel::S2Gemv => slots(false, &[]), Kernel::S2GemvQuads | Kernel::S2GemvQ8 | Kernel::S2GemvFastStaged | Kernel::S2GemvFastUnstaged => { - let mut v = head(false); - v.push(tpr); - v + slots(false, &[tpr]) } } } + +/// `x, codes, scales, [offset,] y, n_in, n_out`, then the kernel-specific `tail`. +fn head_slots(offset: Slot, n_in: i64, n_out: i64, with_offset: bool, tail: &[Slot]) -> Vec { + let mut v = vec![Slot::Ptr(Role::X), Slot::Ptr(Role::Codes), Slot::Ptr(Role::Scales)]; + if with_offset { + v.push(offset); + } + v.push(Slot::Ptr(Role::Y)); + v.extend([Slot::I64(n_in), Slot::I64(n_out)]); + v.extend(tail.iter().copied()); + v +} diff --git a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs index e19fa0ac..b6efc2fd 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs @@ -3,6 +3,31 @@ #[allow(unused_imports)] use super::*; +/// Resolves every entry of the program in order; the first failure is returned and nothing is kept. +fn resolve_functions( + api: &ffi::Api, + module: ffi::ModuleHandle, + program: Program, +) -> DriverResult> { + let mut functions = Vec::with_capacity(program.entries().len()); + for entry in program.entries() { + functions.push(api.kar_levels_function(module, entry.name)?); + } + Ok(functions) +} + +/// No two admitted buffers overlap when either of them is written. +fn reject_aliasing(admitted: &[Admitted]) -> Result<()> { + for (i, a) in admitted.iter().enumerate() { + for b in &admitted[i + 1..] { + if (a.writes || b.writes) && a.handle.overlaps(a.bytes, b.handle, b.bytes) { + return Err(Error::OutputAliasesInput.into()); + } + } + } + Ok(()) +} + impl<'c> ClosedKernels<'c> { /// Pin gate, then load the module and resolve every entry; nothing is kept unless all of them resolve. pub fn open(context: &'c Context<'c>, program: Program) -> Result { @@ -16,19 +41,8 @@ impl<'c> ClosedKernels<'c> { Ok(module) => module, Err(error) => return Err(failure(error, guard.finish())), }; - let mut functions = Vec::with_capacity(program.entries().len()); - let mut resolved: DriverResult<()> = Ok(()); - for entry in program.entries() { - match api.kar_levels_function(module, entry.name) { - Ok(function) => functions.push(function), - Err(error) => { - resolved = Err(error); - break; - } - } - } - match resolved { - Ok(()) => { + match resolve_functions(api, module, program) { + Ok(functions) => { guard.finish()?; Ok(Self { context, program, module, functions }) } @@ -90,41 +104,54 @@ impl<'c> ClosedKernels<'c> { let mut args = Vec::with_capacity(slots.len()); let mut admitted = Vec::new(); for slot in slots { - match *slot { - Slot::Ptr(role) => { - let mut found = operands.iter().filter(|o| o.role == role); - let (Some(operand), None) = (found.next(), found.next()) else { - return invalid("closed launch needs exactly one buffer per pointer role"); - }; - if !std::ptr::eq(context, operand.buffer.context) { - return Err(Error::ContextMismatch.into()); - } - let handle = operand.buffer.handle.ok_or(Error::ContextPoisoned)?; - let min = usize::try_from(operand.min).or_else(|_| invalid("closed buffer size exceeds usize"))?; - if min == 0 || operand.buffer.bytes < min { - return invalid("closed buffer is smaller than the geometry requires"); - } - handle.validate_projection_extent(operand.buffer.bytes, 16)?; - admitted.push(Admitted { handle, bytes: operand.buffer.bytes, writes: operand.writes }); - let at = handle.experimental_offset(operand.offset)?; - args.push(ffi::KarArgument::Scalar64(at.qwen_address())); - } - Slot::Null => args.push(ffi::KarArgument::Scalar64(0)), - Slot::I32(value) => args.push(ffi::KarArgument::Scalar(value as u32)), - Slot::I64(value) => args.push(ffi::KarArgument::Scalar64(value as u64)), - Slot::F32(value) => args.push(ffi::KarArgument::Scalar(value.to_bits())), - } - } - for (i, a) in admitted.iter().enumerate() { - for b in &admitted[i + 1..] { - if (a.writes || b.writes) && a.handle.overlaps(a.bytes, b.handle, b.bytes) { - return Err(Error::OutputAliasesInput.into()); - } - } + args.push(match *slot { + Slot::Ptr(role) => self.admit_operand(role, operands, &mut admitted)?, + Slot::Null => ffi::KarArgument::Scalar64(0), + Slot::I32(value) => ffi::KarArgument::Scalar(value as u32), + Slot::I64(value) => ffi::KarArgument::Scalar64(value as u64), + Slot::F32(value) => ffi::KarArgument::Scalar(value.to_bits()), + }); } + reject_aliasing(&admitted)?; Ok(Launch { function: self.functions[entry], grid, block, shared, args: ffi::KarLevelsArgs::new(&args)? }) } + /// Admits the one buffer offered for `role` (this context, extent and alignment); returns its pointer argument. + fn admit_operand( + &self, + role: Role, + operands: &[Operand<'_, '_>], + admitted: &mut Vec, + ) -> Result { + let mut found = operands.iter().filter(|o| o.role == role); + let (Some(operand), None) = (found.next(), found.next()) else { + return invalid("closed launch needs exactly one buffer per pointer role"); + }; + if !std::ptr::eq(self.context, operand.buffer.context) { + return Err(Error::ContextMismatch.into()); + } + let handle = operand.buffer.handle.ok_or(Error::ContextPoisoned)?; + let min = usize::try_from(operand.min).or_else(|_| invalid("closed buffer size exceeds usize"))?; + if min == 0 || operand.buffer.bytes < min { + return invalid("closed buffer is smaller than the geometry requires"); + } + handle.validate_projection_extent(operand.buffer.bytes, 16)?; + admitted.push(Admitted { handle, bytes: operand.buffer.bytes, writes: operand.writes }); + let at = handle.experimental_offset(operand.offset)?; + Ok(ffi::KarArgument::Scalar64(at.qwen_address())) + } + + /// The slots agree with the entry and the geometry is non-empty and within 1024 threads per block. + fn check_launch(&self, entry: usize, grid: [u32; 3], block: [u32; 3], slots: &[Slot]) -> Result<()> { + if !conforms(&self.program.entries()[entry], slots) { + return invalid("closed launch arguments differ from the entry's fixed signature"); + } + if block.contains(&0) || grid.contains(&0) || block.iter().map(|b| u64::from(*b)).product::() > 1024 { + return invalid("closed launch geometry is empty or exceeds 1024 threads per block"); + } + Ok(()) + } + /// Launch in order and drain with exactly one synchronize. pub(in super::super) fn run(&self, mut launches: Vec) -> Result<()> { let context = self.context; diff --git a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs index a720fc34..4ad754c9 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs @@ -3,6 +3,90 @@ #[allow(unused_imports)] use super::*; +use crate::closed_kernels::FlashBytes; + +/// The buffers of one short FlashAttention step. +struct FlashBuffers<'a, 'b> { + q: &'a DeviceBuffer<'b>, + k: &'a DeviceBuffer<'b>, + v: &'a DeviceBuffer<'b>, + step: &'a DeviceBuffer<'b>, + mask: Option<&'a DeviceBuffer<'b>>, + out: &'a DeviceBuffer<'b>, + status: &'a DeviceBuffer<'b>, +} + +impl<'a, 'b> FlashBuffers<'a, 'b> { + /// `native_flash_attn::admit` over the buffers' device addresses; returns `(grid, block, dynamic_shared)`. + fn admit(&self, capacity: i64, idx_top_k: i64, max_context: i32) -> Result<([u32; 3], [u32; 3], u32)> { + let address = |b: &DeviceBuffer<'_>| -> Result { + let handle = b.handle.ok_or(Error::ContextPoisoned)?; + usize::try_from(handle.qwen_address()).or_else(|_| invalid("device address exceeds usize")) + }; + let launch = flash::admit(&flash::Arguments { + n_head: flash::HEADS as i64, + n_head_kv: flash::KV_HEADS as i64, + head_dim: flash::HEAD_DIM as i64, + idx_block: 4, + idx_top_k, + capacity, + max_context, + stream_present: true, + q: address(self.q)?, + k: address(self.k)?, + v: address(self.v)?, + step: address(self.step)?, + output: address(self.out)?, + status: address(self.status)?, + mask: self.mask.map(address).transpose()?, + }) + .map_err(|e| ExperimentalError::Invalid(e.message()))?; + Ok((launch.grid, launch.block, launch.dynamic_shared)) + } + + /// The operands of the step, each with the bytes its role must hold (the mask last, when there is one). + fn operands(&self, bytes: &FlashBytes) -> Vec> { + let mut operands = vec![ + Operand { role: Role::Q, buffer: self.q, min: bytes.q, offset: 0, writes: false }, + Operand { role: Role::K, buffer: self.k, min: bytes.kv, offset: 0, writes: false }, + Operand { role: Role::V, buffer: self.v, min: bytes.kv, offset: 0, writes: false }, + Operand { role: Role::Step, buffer: self.step, min: bytes.step, offset: 0, writes: false }, + Operand { role: Role::Out, buffer: self.out, min: bytes.out, offset: 0, writes: true }, + Operand { role: Role::Status, buffer: self.status, min: bytes.status, offset: 0, writes: true }, + ]; + if let Some(mask) = self.mask { + operands.push(Operand { role: Role::Mask, buffer: mask, min: bytes.mask, offset: 0, writes: false }); + } + operands + } +} + +/// The operands of an S-form GEMV: `x`, `codes`, `scales`, `y` and (when the form has one) the offset. +fn s_gemv_operands<'a, 'b>( + plan: &Plan, + form: &SForm, + n_in: i64, + n_out: i64, + [x, codes, scales]: [&'a DeviceBuffer<'b>; 3], + offset: Option<&'a DeviceBuffer<'b>>, + y: &'a DeviceBuffer<'b>, +) -> Result>> { + let bytes = s_operand_bytes(plan.kernel, form, n_in, n_out)?; + if bytes.offset.is_some() != offset.is_some() { + return invalid("the S-form has an offset exactly when an offset buffer is passed"); + } + let mut operands = vec![ + Operand { role: Role::X, buffer: x, min: bytes.x, offset: 0, writes: false }, + Operand { role: Role::Codes, buffer: codes, min: bytes.codes, offset: 0, writes: false }, + Operand { role: Role::Scales, buffer: scales, min: bytes.scales, offset: 0, writes: false }, + Operand { role: Role::Y, buffer: y, min: bytes.y, offset: 0, writes: true }, + ]; + if let (Some(buffer), Some(min)) = (offset, bytes.offset) { + operands.push(Operand { role: Role::Offset, buffer, min, offset: 0, writes: false }); + } + Ok(operands) +} + impl<'c> ClosedKernels<'c> { // --------------------------------------------------------------------------- short FlashAttention @@ -27,41 +111,11 @@ impl<'c> ClosedKernels<'c> { ) -> Result<()> { self.expect(Program::NativeFlashAttn)?; let bytes = flash_bytes(capacity)?; - let address = |b: &DeviceBuffer<'_>| -> Result { - let handle = b.handle.ok_or(Error::ContextPoisoned)?; - usize::try_from(handle.qwen_address()).or_else(|_| invalid("device address exceeds usize")) - }; - let launch = flash::admit(&flash::Arguments { - n_head: flash::HEADS as i64, - n_head_kv: flash::KV_HEADS as i64, - head_dim: flash::HEAD_DIM as i64, - idx_block: 4, - idx_top_k, - capacity, - max_context, - stream_present: true, - q: address(q)?, - k: address(k)?, - v: address(v)?, - step: address(step)?, - output: address(out)?, - status: address(status)?, - mask: mask.map(address).transpose()?, - }) - .map_err(|e| ExperimentalError::Invalid(e.message()))?; - let mut operands = vec![ - Operand { role: Role::Q, buffer: q, min: bytes.q, offset: 0, writes: false }, - Operand { role: Role::K, buffer: k, min: bytes.kv, offset: 0, writes: false }, - Operand { role: Role::V, buffer: v, min: bytes.kv, offset: 0, writes: false }, - Operand { role: Role::Step, buffer: step, min: bytes.step, offset: 0, writes: false }, - Operand { role: Role::Out, buffer: out, min: bytes.out, offset: 0, writes: true }, - Operand { role: Role::Status, buffer: status, min: bytes.status, offset: 0, writes: true }, - ]; - if let Some(mask) = mask { - operands.push(Operand { role: Role::Mask, buffer: mask, min: bytes.mask, offset: 0, writes: false }); - } + let buffers = FlashBuffers { q, k, v, step, mask, out, status }; + let (grid, block, shared) = buffers.admit(capacity, idx_top_k, max_context)?; + let operands = buffers.operands(&bytes); let slots = flash_slots(max_context, mask.is_some()); - let launch = self.build(FLASH_SHORT, launch.grid, launch.block, launch.dynamic_shared, &slots, &operands)?; + let launch = self.build(FLASH_SHORT, grid, block, shared, &slots, &operands)?; self.run(vec![launch]) } @@ -116,19 +170,7 @@ impl<'c> ClosedKernels<'c> { y: &mut DeviceBuffer<'_>, ) -> Result<()> { self.expect(Program::SGemvLegacy)?; - let bytes = s_operand_bytes(plan.kernel, form, n_in, n_out)?; - if bytes.offset.is_some() != offset.is_some() { - return invalid("the S-form has an offset exactly when an offset buffer is passed"); - } - let mut operands = vec![ - Operand { role: Role::X, buffer: x, min: bytes.x, offset: 0, writes: false }, - Operand { role: Role::Codes, buffer: codes, min: bytes.codes, offset: 0, writes: false }, - Operand { role: Role::Scales, buffer: scales, min: bytes.scales, offset: 0, writes: false }, - Operand { role: Role::Y, buffer: y, min: bytes.y, offset: 0, writes: true }, - ]; - if let (Some(buffer), Some(min)) = (offset, bytes.offset) { - operands.push(Operand { role: Role::Offset, buffer, min, offset: 0, writes: false }); - } + let operands = s_gemv_operands(plan, form, n_in, n_out, [x, codes, scales], offset, y)?; let slots = s_gemv_slots(plan, form, n_in, n_out, offset.is_some()); let launch = self.build( s_gemv_entry_index(plan.kernel), From 2d5215bcda8ae6279fbb1fe31722bfcee91a6ff8 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 22:21:00 +0100 Subject: [PATCH 2/7] STRA-338 size2 cd1: drain timing, deferred status, owned copy proof and experimental KV launches under the limits --- .../cuda-driver/src/async_owned_copy_gpu.rs | 239 +++++++++++------- .../impl_closedkernels_2.rs | 24 +- crates/cuda-driver/src/compute_drain.rs | 54 ++-- crates/cuda-driver/src/deferred_status.rs | 18 +- crates/cuda-driver/src/deferred_status_ffi.rs | 29 ++- crates/cuda-driver/src/deferred_status_gpu.rs | 77 +++--- .../src/experimental_gpu/impl_context.rs | 47 ++-- .../impl_experimental/impl_experimental_2.rs | 38 +-- .../impl_experimental_2/call_shape.rs | 19 ++ .../impl_experimental_2_2.rs | 155 ++++++++---- .../impl_experimental/impl_experimental_3.rs | 71 +----- .../impl_experimental_3/attend_inputs.rs | 148 +++++++++++ 12 files changed, 575 insertions(+), 344 deletions(-) create mode 100644 crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2/call_shape.rs create mode 100644 crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3/attend_inputs.rs diff --git a/crates/cuda-driver/src/async_owned_copy_gpu.rs b/crates/cuda-driver/src/async_owned_copy_gpu.rs index 02190cf2..80f943d7 100644 --- a/crates/cuda-driver/src/async_owned_copy_gpu.rs +++ b/crates/cuda-driver/src/async_owned_copy_gpu.rs @@ -12,6 +12,149 @@ fn bounded_host_capacity_admission_has_no_completion_shortcut() { assert!(admit_count_and_capacities(&[(10, 16), (10, 16), (10, 16)], 48).is_ok()); } +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +mod proof { + use super::*; + + const SIZES: [usize; 3] = [262_144, 524_288, 786_432]; + + /// Running totals of the triplet proof, compared with fixed numbers once everything is released. + #[derive(Default)] + pub(super) struct Counts { + pub(super) compared: usize, + pub(super) receipts: usize, + pub(super) refusals: usize, + } + + /// The original-first reference bytes of one round and the staging pointers of its host buffers. + struct Reference { + expected: Vec>, + pointers: [usize; 3], + } + + /// Host bytes of one staging buffer: a word pattern per round (round 2 carries zeros, infinities and NaNs). + fn host_source(round: u32, role: usize, bytes: usize) -> Result> { + let mut source = Vec::new(); + source.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?; + for i in 0..bytes / 4 { + let word = if round == 2 { + [0, 0x8000_0000, 1, 0x7f80_0000, 0xff80_0000, 0x7fc0_0042][i % 6] + } else { + (i as u32).wrapping_mul(0x9e37_79b9).wrapping_add(round + role as u32) + }; + source.extend_from_slice(&word.to_le_bytes()); + } + Ok(source) + } + + /// Stages one round: every pair's bytes go through the original borrowed synchronous copy FIRST. + fn stage_round<'c>(context: &'c Context<'c>, round: u32) -> Result<(Vec<(DeviceBuffer<'c>, Vec)>, Reference)> { + let mut pairs = Vec::new(); + pairs.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; + let mut expected = Vec::new(); + expected.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; + let mut pointers = [0usize; 3]; + for (role, bytes) in SIZES.into_iter().enumerate() { + let source = host_source(round, role, bytes)?; + // Original borrowed synchronous copy FIRST on the same complete + // bytes; no candidate-derived expected outputs or ready flags. + let mut original = context.allocate(bytes)?; + original.copy_from(&source)?; + let reference = original.copy_to_owned(bytes)?; + original.release()?; + if reference != source { + return Err(Error::InvalidDriverValue("original byte reference")); + } + expected.push(reference); + pointers[role] = source.as_ptr() as usize; + pairs.push((context.allocate(bytes)?, source)); + } + Ok((pairs, Reference { expected, pointers })) + } + + /// Completes the batch: polled once first (round 1) or waited for outright. + fn complete<'c>(pending: PendingOwnedCopy<'c>, poll_first: bool) -> Result> { + if !poll_first { + return pending.wait(); + } + match pending.poll()? { + OwnedCopyPoll::Complete(receipt) => Ok(receipt), + OwnedCopyPoll::Pending(pending) => pending.wait(), + } + } + + /// Compares one completed pair with its reference and releases its destination; failures fold into `acc` in order. + fn check_pair( + reference: &Reference, + i: usize, + pair: (DeviceBuffer<'_>, Vec), + compared: &mut usize, + acc: Result<()>, + ) -> Result<()> { + let (destination, source) = pair; + let mut completion_error = acc; + let observed = destination.copy_to_owned(SIZES[i]); + if source.as_ptr() as usize != reference.pointers[i] { + completion_error = combine(completion_error, Err(Error::InvalidDriverValue("staging ownership"))); + } + match observed { + Ok(bytes) if bytes == reference.expected[i] && source == reference.expected[i] => *compared += bytes.len(), + Ok(_) => { + completion_error = combine(completion_error, Err(Error::InvalidDriverValue("async byte equality"))) + } + Err(error) => completion_error = combine(completion_error, Err(error)), + } + combine(completion_error, destination.release()) + } + + /// One round: stage, copy asynchronously, complete, and compare every pair with the original-first bytes. + pub(super) fn run_round<'c>(context: &'c Context<'c>, round: u32, counts: &mut Counts) -> Result<()> { + let (pairs, reference) = stage_round(context, round)?; + let pending = context.copy_owned_batch_async(pairs)?; + let receipt = complete(pending, round == 1)?; + if receipt.len() != 3 { + return Err(Error::InvalidDriverValue("receipt pair count")); + } + counts.receipts += 1; + let mut completion_error = Ok(()); + for (i, pair) in receipt.into_pairs().into_iter().enumerate() { + if let Some(pair) = pair { + completion_error = check_pair(&reference, i, pair, &mut counts.compared, completion_error); + } + } + completion_error + } + + /// Genuine foreign allocation and exact whole-byte shape admission, then an abandoned pending owner. + pub(super) fn run_refusals(context: &Context<'_>, foreign: &Context<'_>, counts: &mut Counts) -> Result<()> { + let invalid = context.copy_owned_batch_async(vec![(foreign.allocate(4096)?, vec![0; 4096])]); + if !matches!(invalid, Err(Error::ContextMismatch)) { + return Err(Error::InvalidDriverValue("foreign refusal")); + } + drop(invalid); + counts.refusals += 1; + let invalid = context.copy_owned_batch_async(vec![(context.allocate(4096)?, vec![0; 4095])]); + if !matches!(invalid, Err(Error::ShapeMismatch { expected: 4096, actual: 4095 })) { + return Err(Error::InvalidDriverValue("extent refusal")); + } + drop(invalid); + counts.refusals += 1; + // Real abandoned pending owner explicitly drains without publication. + context.copy_owned_batch_async(vec![(context.allocate(262_144)?, vec![7; 262_144])])?.close()?; + Ok(()) + } + + /// A poisoned pending owner holds nothing any more: everything moved to retention. + pub(super) fn assert_retained(pending: &PendingOwnedCopy<'_>) { + assert!(pending.pairs.iter().all(Option::is_none)); + assert!(pending.api.is_none()); + assert!(pending.stream.is_none()); + assert!(pending.event.is_none()); + assert!(pending.registered.iter().all(|registered| !registered)); + assert!(!pending.recorded); + } +} + #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[test] #[ignore = "Root-only genuine registered triplet event transport proof"] @@ -21,91 +164,12 @@ fn original_three_copies_first_owned_event_triplet_bytes_guards_and_cleanup() { let device = driver.device(0).unwrap(); let context = device.create_context(16 * 1024 * 1024).unwrap(); let foreign = device.create_context(16 * 1024 * 1024).unwrap(); - let mut compared = 0usize; - let mut receipts = 0usize; - let mut refusals = 0usize; + let mut counts = proof::Counts::default(); let result = (|| -> Result<()> { - let sizes = [262_144usize, 524_288, 786_432]; for round in 0..3u32 { - let mut pairs = Vec::new(); - pairs.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; - let mut expected = Vec::new(); - expected.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; - let mut pointers = [0usize; 3]; - for (role, bytes) in sizes.into_iter().enumerate() { - let mut source = Vec::new(); - source.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?; - for i in 0..bytes / 4 { - let word = if round == 2 { - [0, 0x8000_0000, 1, 0x7f80_0000, 0xff80_0000, 0x7fc0_0042][i % 6] - } else { - (i as u32).wrapping_mul(0x9e37_79b9).wrapping_add(round + role as u32) - }; - source.extend_from_slice(&word.to_le_bytes()); - } - // Original borrowed synchronous copy FIRST on the same complete - // bytes; no candidate-derived expected outputs or ready flags. - let mut original = context.allocate(bytes)?; - original.copy_from(&source)?; - let reference = original.copy_to_owned(bytes)?; - original.release()?; - if reference != source { - return Err(Error::InvalidDriverValue("original byte reference")); - } - expected.push(reference); - pointers[role] = source.as_ptr() as usize; - pairs.push((context.allocate(bytes)?, source)); - } - let pending = context.copy_owned_batch_async(pairs)?; - let receipt = if round == 1 { - match pending.poll()? { - OwnedCopyPoll::Complete(receipt) => receipt, - OwnedCopyPoll::Pending(pending) => pending.wait()?, - } - } else { - pending.wait()? - }; - if receipt.len() != 3 { - return Err(Error::InvalidDriverValue("receipt pair count")); - } - receipts += 1; - let mut completion_error = Ok(()); - for (i, pair) in receipt.into_pairs().into_iter().enumerate() { - if let Some((destination, source)) = pair { - let observed = destination.copy_to_owned(sizes[i]); - if source.as_ptr() as usize != pointers[i] { - completion_error = - combine(completion_error, Err(Error::InvalidDriverValue("staging ownership"))); - } - match observed { - Ok(bytes) if bytes == expected[i] && source == expected[i] => compared += bytes.len(), - Ok(_) => { - completion_error = - combine(completion_error, Err(Error::InvalidDriverValue("async byte equality"))) - } - Err(error) => completion_error = combine(completion_error, Err(error)), - } - completion_error = combine(completion_error, destination.release()); - } - } - completion_error?; + proof::run_round(&context, round, &mut counts)?; } - // Genuine foreign allocation and exact whole-byte shape admission. - let invalid = context.copy_owned_batch_async(vec![(foreign.allocate(4096)?, vec![0; 4096])]); - if !matches!(invalid, Err(Error::ContextMismatch)) { - return Err(Error::InvalidDriverValue("foreign refusal")); - } - drop(invalid); - refusals += 1; - let invalid = context.copy_owned_batch_async(vec![(context.allocate(4096)?, vec![0; 4095])]); - if !matches!(invalid, Err(Error::ShapeMismatch { expected: 4096, actual: 4095 })) { - return Err(Error::InvalidDriverValue("extent refusal")); - } - drop(invalid); - refusals += 1; - // Real abandoned pending owner explicitly drains without publication. - context.copy_owned_batch_async(vec![(context.allocate(262_144)?, vec![7; 262_144])])?.close()?; - Ok(()) + proof::run_refusals(&context, &foreign, &mut counts) })(); let sync = context.synchronize(); let foreign_sync = foreign.synchronize(); @@ -117,9 +181,11 @@ fn original_three_copies_first_owned_event_triplet_bytes_guards_and_cleanup() { assert!(result.is_ok(), "transport {result:?}"); assert!(sync.is_ok() && foreign_sync.is_ok() && foreign_close.is_ok() && close.is_ok()); assert_eq!((allocated, foreign_allocated), (0, 0)); + let proof::Counts { compared, receipts, refusals } = counts; assert_eq!((compared, receipts, refusals), (4_718_592, 3, 2)); println!( - "owned_async_copy original_first=true complete_bytes={compared} receipts={receipts} refusals={refusals} abandoned_pending_drained=true allocated=0 overlap_not_measured=true injected_cuda_faults=false" + "owned_async_copy original_first=true complete_bytes={compared} receipts={receipts} refusals={refusals} \ + abandoned_pending_drained=true allocated=0 overlap_not_measured=true injected_cuda_faults=false" ); } @@ -147,12 +213,7 @@ fn poison_while_pending_retains_registered_owners_and_preserves_the_primary_erro assert!(matches!(pending.observe(true), Err(Error::ContextPoisoned))); // ... and ownership has moved to retention BEFORE Drop runs: no destination, host Vec, // registration, stream, event or ABI handle is left for drain_and_close()/Drop to free. - assert!(pending.pairs.iter().all(Option::is_none)); - assert!(pending.api.is_none()); - assert!(pending.stream.is_none()); - assert!(pending.event.is_none()); - assert!(pending.registered.iter().all(|registered| !registered)); - assert!(!pending.recorded); + proof::assert_retained(&pending); // The retained destination stays charged: forgotten buffers are never credited back. assert_eq!(context.allocated_bytes(), charged); drop(pending); diff --git a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs index b6efc2fd..3658c131 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs @@ -104,18 +104,28 @@ impl<'c> ClosedKernels<'c> { let mut args = Vec::with_capacity(slots.len()); let mut admitted = Vec::new(); for slot in slots { - args.push(match *slot { - Slot::Ptr(role) => self.admit_operand(role, operands, &mut admitted)?, - Slot::Null => ffi::KarArgument::Scalar64(0), - Slot::I32(value) => ffi::KarArgument::Scalar(value as u32), - Slot::I64(value) => ffi::KarArgument::Scalar64(value as u64), - Slot::F32(value) => ffi::KarArgument::Scalar(value.to_bits()), - }); + args.push(self.slot_argument(*slot, operands, &mut admitted)?); } reject_aliasing(&admitted)?; Ok(Launch { function: self.functions[entry], grid, block, shared, args: ffi::KarLevelsArgs::new(&args)? }) } + /// The launch argument of one slot; a pointer slot admits its operand. + fn slot_argument( + &self, + slot: Slot, + operands: &[Operand<'_, '_>], + admitted: &mut Vec, + ) -> Result { + Ok(match slot { + Slot::Ptr(role) => self.admit_operand(role, operands, admitted)?, + Slot::Null => ffi::KarArgument::Scalar64(0), + Slot::I32(value) => ffi::KarArgument::Scalar(value as u32), + Slot::I64(value) => ffi::KarArgument::Scalar64(value as u64), + Slot::F32(value) => ffi::KarArgument::Scalar(value.to_bits()), + }) + } + /// Admits the one buffer offered for `role` (this context, extent and alignment); returns its pointer argument. fn admit_operand( &self, diff --git a/crates/cuda-driver/src/compute_drain.rs b/crates/cuda-driver/src/compute_drain.rs index 8d532cd6..d780dea8 100644 --- a/crates/cuda-driver/src/compute_drain.rs +++ b/crates/cuda-driver/src/compute_drain.rs @@ -98,38 +98,40 @@ pub(crate) fn timed(kind: usize, f: impl FnOnce() -> T) -> T { let took = started.elapsed(); BLOCK_NS[kind].fetch_add(took.as_nanos() as usize, Ordering::Relaxed); BLOCK_N[kind].fetch_add(1, Ordering::Relaxed); - // LELEKA_PREFILL_STALL_TRACE=1: every blocking call over 2 ms (first 40 per chunk) with its callers, and a - // per-call-site histogram of the host-to-device / device-to-host / memset / device-to-device calls - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - if *ON.get_or_init(|| std::env::var_os("LELEKA_PREFILL_STALL_TRACE").is_some_and(|v| v == "1")) { + if stall_trace() { let trace = std::backtrace::Backtrace::force_capture().to_string(); - let frames: Vec<&str> = trace - .lines() - .filter(|l| l.contains("leleka_cuda_driver::") || l.contains("leleka_runtime::")) - .skip(1) - .take(6) - .collect(); - let key = format!("kind={kind} {}", frames.join(" <- ")); - let mut sites = SITES.lock().unwrap_or_else(|e| e.into_inner()); - let entry = sites.entry(key).or_insert((0, 0)); - entry.0 += 1; - entry.1 += took.as_nanos() as usize; + note_site(kind, took, &trace); } - if took.as_micros() > 2000 - && *ON.get_or_init(|| std::env::var_os("LELEKA_PREFILL_STALL_TRACE").is_some_and(|v| v == "1")) - && SHOWN.fetch_add(1, Ordering::Relaxed) < 40 - { + if took.as_micros() > 2000 && stall_trace() && SHOWN.fetch_add(1, Ordering::Relaxed) < 40 { let trace = std::backtrace::Backtrace::force_capture().to_string(); - let frames: Vec<&str> = trace - .lines() - .filter(|l| l.contains("leleka_cuda_driver::") || l.contains("leleka_runtime::")) - .skip(1) - .take(6) - .collect(); - eprintln!("PREFILL-STALL kind={kind} ms={:.1} at {}", took.as_secs_f64() * 1e3, frames.join(" <- ")); + eprintln!("PREFILL-STALL kind={kind} ms={:.1} at {}", took.as_secs_f64() * 1e3, stall_frames(&trace)); } out } +/// LELEKA_PREFILL_STALL_TRACE=1: every blocking call over 2 ms (first 40 per chunk) with its callers, and a +/// per-call-site histogram of the host-to-device / device-to-host / memset / device-to-device calls +fn stall_trace() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LELEKA_PREFILL_STALL_TRACE").is_some_and(|v| v == "1")) +} +/// The driver and runtime frames of a backtrace taken in `timed`, past `timed` itself. +fn stall_frames(trace: &str) -> String { + let frames: Vec<&str> = trace + .lines() + .filter(|l| l.contains("leleka_cuda_driver::") || l.contains("leleka_runtime::")) + .skip(1) + .take(6) + .collect(); + frames.join(" <- ") +} +/// Adds one blocking call of `took` to the histogram of its call site. +fn note_site(kind: usize, took: std::time::Duration, trace: &str) { + let key = format!("kind={kind} {}", stall_frames(trace)); + let mut sites = SITES.lock().unwrap_or_else(|e| e.into_inner()); + let entry = sites.entry(key).or_insert((0, 0)); + entry.0 += 1; + entry.1 += took.as_nanos() as usize; +} /// `alloc n/ms free n/ms h2d n/ms d2h n/ms memset n/ms drain n/ms` since the last call. pub(crate) fn take_blocking_report() -> String { SHOWN.store(0, Ordering::Relaxed); diff --git a/crates/cuda-driver/src/deferred_status.rs b/crates/cuda-driver/src/deferred_status.rs index 9852e1dd..51dedd0e 100644 --- a/crates/cuda-driver/src/deferred_status.rs +++ b/crates/cuda-driver/src/deferred_status.rs @@ -113,6 +113,17 @@ mod device { verdict } + /// Step 2 of a deferred run: copy the words into the slot, record its event, order every other stream after it. + fn queue_readback(st: &State, slot_index: usize, status: BufferHandle, bytes: usize, stream: usize) -> Result<()> { + let slot = &st.slots[slot_index]; + st.api.read_async(&slot.host, status, bytes, stream)?; + st.api.record(slot.event, stream)?; + for other in crate::compute_drain::streams_except(stream) { + st.api.wait_stream(other, slot.event)?; + } + Ok(()) + } + /// Step 1 of a deferred run: zero the status words, stream ordered. pub(crate) fn begin( context: &Context<'_>, @@ -158,12 +169,7 @@ mod device { } let slot_index = st.head % SLOTS; st.head += 1; - let slot = &st.slots[slot_index]; - st.api.read_async(&slot.host, status, bytes, stream)?; - st.api.record(slot.event, stream)?; - for other in crate::compute_drain::streams_except(stream) { - st.api.wait_stream(other, slot.event)?; - } + queue_readback(st, slot_index, status, bytes, stream)?; st.live.push_back(Check { slot: slot_index, bytes, diff --git a/crates/cuda-driver/src/deferred_status_ffi.rs b/crates/cuda-driver/src/deferred_status_ffi.rs index e4ea8ea5..8ca83c8d 100644 --- a/crates/cuda-driver/src/deferred_status_ffi.rs +++ b/crates/cuda-driver/src/deferred_status_ffi.rs @@ -57,6 +57,21 @@ impl Drop for Api { } } } +/// A dlopen handle that is closed again unless `Api::load` forgets it once every symbol resolved. +struct Opening(Handle); +impl Drop for Opening { + fn drop(&mut self) { + // SAFETY: dlopen handle not yet transferred to `Api`. + unsafe { + libc::dlclose(self.0); + } + } +} +fn symbol(l: Handle, n: &'static CStr) -> Result { + // SAFETY: valid dlopen handle and NUL-terminated name. + let p = unsafe { libc::dlsym(l, n.as_ptr()) }; + if p.is_null() { Err(Error::MissingSymbol(n.to_str().unwrap_or("deferred status symbol"))) } else { Ok(p) } +} impl Api { pub(crate) fn load() -> Result { // SAFETY: NUL-terminated literal name. @@ -64,21 +79,7 @@ impl Api { if l.is_null() { return Err(Error::LibraryUnavailable); } - struct Opening(Handle); - impl Drop for Opening { - fn drop(&mut self) { - // SAFETY: dlopen handle not yet transferred to `Api`. - unsafe { - libc::dlclose(self.0); - } - } - } let opening = Opening(l); - fn symbol(l: Handle, n: &'static CStr) -> Result { - // SAFETY: valid dlopen handle and NUL-terminated name. - let p = unsafe { libc::dlsym(l, n.as_ptr()) }; - if p.is_null() { Err(Error::MissingSymbol(n.to_str().unwrap_or("deferred status symbol"))) } else { Ok(p) } - } macro_rules! sym { ($n:literal,$t:ty) => { // SAFETY: the CUDA driver ABI of this symbol is exactly the declared function type. diff --git a/crates/cuda-driver/src/deferred_status_gpu.rs b/crates/cuda-driver/src/deferred_status_gpu.rs index eeee1079..a4244af2 100644 --- a/crates/cuda-driver/src/deferred_status_gpu.rs +++ b/crates/cuda-driver/src/deferred_status_gpu.rs @@ -8,6 +8,46 @@ fn status_bytes(words: &[u32]) -> Vec { words.iter().flat_map(|w| w.to_le_bytes()).collect() } +const STRIDE: usize = 4; +const ROWS: usize = 8; +const BYTES: usize = ROWS * STRIDE * 4; +const ORDER: [usize; 4] = [0, 1, 2, 3]; +const LABELS: [&str; 4] = ["n", "d", "s", "u"]; + +/// Stands in for the kernels' flag writes: uploads `words`, padded to the 4096-byte status buffer. +fn put(status: &mut DeviceBuffer<'_>, words: &[u32]) { + let mut b = status_bytes(words); + b.resize(4096, 0); + status.copy_from(&b).expect("upload"); +} + +/// Clean runs (the zeroing must have cleared the previous words), then more runs than slots: the ring wraps. +fn clean_runs(context: &Context<'_>, status: &mut DeviceBuffer<'_>, run: &impl Fn(&mut DeviceBuffer<'_>, &[u32])) { + run(status, &vec![0; ROWS * STRIDE]); + run(status, &vec![0; ROWS * STRIDE]); + assert_eq!(pending(), 2); + resolve(context).expect("clean runs"); + assert_eq!(pending(), 0); + // more runs than slots: the ring wraps and resolves its oldest entries by itself + for _ in 0..150 { + run(status, &vec![0; ROWS * STRIDE]); + } + assert!(pending() <= 64); + resolve(context).expect("wrapped ring"); +} + +/// A set flag: same label as the immediate evaluation, and the context is poisoned. +fn flagged_run(context: &Context<'_>, status: &mut DeviceBuffer<'_>, run: &impl Fn(&mut DeviceBuffer<'_>, &[u32])) { + let mut words = vec![0u32; ROWS * STRIDE]; + words[3 * STRIDE + 2] = 1; + run(status, &words); + let expected = evaluate(&status_bytes(&words), STRIDE, &ORDER, &LABELS).unwrap_err(); + let got = resolve(context).unwrap_err(); + assert_eq!(format!("{got:?}"), format!("{expected:?}")); + assert!(context.is_poisoned()); + assert!(matches!(context.enter(), Err(Error::ContextPoisoned))); +} + #[test] #[ignore = "Root-only: needs a CUDA device"] fn deferred_status_equals_the_immediate_evaluation_and_poisons() { @@ -17,45 +57,16 @@ fn deferred_status_equals_the_immediate_evaluation_and_poisons() { let context = device.create_context(1usize << 30).expect("context"); let workspace = context.native_batch_workspace().expect("workspace"); let blas = workspace.blas().expect("blas"); - let stride = 4usize; - let rows = 8usize; - let bytes = rows * stride * 4; - let order = [0usize, 1, 2, 3]; - let labels = ["n", "d", "s", "u"]; let mut status: DeviceBuffer<'_> = context.allocate(4096).expect("alloc"); let handle = status.handle.expect("handle"); - let put = |status: &mut DeviceBuffer<'_>, words: &[u32]| { - let mut b = status_bytes(words); - b.resize(4096, 0); - status.copy_from(&b).expect("upload"); - }; let run = |status: &mut DeviceBuffer<'_>, words: &[u32]| { let guard = context.enter().expect("enter"); - begin(&context, handle, bytes, blas.stream(), 4096).expect("begin"); + begin(&context, handle, BYTES, blas.stream(), 4096).expect("begin"); blas.synchronize().expect("sync"); put(status, words); // stands in for the kernels' flag writes - finish(&context, handle, bytes, blas.stream(), stride, &order, &labels).expect("finish"); + finish(&context, handle, BYTES, blas.stream(), STRIDE, &ORDER, &LABELS).expect("finish"); guard.finish().expect("pop"); }; - // clean run, the zeroing must have cleared the previous words - run(&mut status, &vec![0; rows * stride]); - run(&mut status, &vec![0; rows * stride]); - assert_eq!(pending(), 2); - resolve(&context).expect("clean runs"); - assert_eq!(pending(), 0); - // more runs than slots: the ring wraps and resolves its oldest entries by itself - for _ in 0..150 { - run(&mut status, &vec![0; rows * stride]); - } - assert!(pending() <= 64); - resolve(&context).expect("wrapped ring"); - // a set flag: same label as the immediate evaluation - let mut words = vec![0u32; rows * stride]; - words[3 * stride + 2] = 1; - run(&mut status, &words); - let expected = evaluate(&status_bytes(&words), stride, &order, &labels).unwrap_err(); - let got = resolve(&context).unwrap_err(); - assert_eq!(format!("{got:?}"), format!("{expected:?}")); - assert!(context.is_poisoned()); - assert!(matches!(context.enter(), Err(Error::ContextPoisoned))); + clean_runs(&context, &mut status, &run); + flagged_run(&context, &mut status, &run); } diff --git a/crates/cuda-driver/src/experimental_gpu/impl_context.rs b/crates/cuda-driver/src/experimental_gpu/impl_context.rs index 0dccb336..9880ae17 100644 --- a/crates/cuda-driver/src/experimental_gpu/impl_context.rs +++ b/crates/cuda-driver/src/experimental_gpu/impl_context.rs @@ -20,19 +20,8 @@ impl Context<'_> { Ok(module) => module, Err(error) => return Err(failure(error, guard.finish())), }; - let mut functions = [None; 5]; - let mut resolved: DriverResult<()> = Ok(()); - for (slot, entry) in functions.iter_mut().zip(program.entries()) { - match api.kar_levels_function(module, entry.name) { - Ok(function) => *slot = Some(function), - Err(error) => { - resolved = Err(error); - break; - } - } - } - match resolved { - Ok(()) => { + match resolve_entries(api, module, program) { + Ok(functions) => { // Nothing is published until every entry resolves and the context restore succeeds. guard.finish()?; let loaded = LoadedProgram { module, functions }; @@ -40,16 +29,36 @@ impl Context<'_> { Ok(loaded) } Err(error) => { - let cleanup = api.unload(module); - if cleanup.is_err() { - self.poisoned.set(true); - std::mem::forget(Rc::clone(api)); - } - let primary = combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary"); + let primary = self.unload_failed(module, error); Err(failure(primary, guard.finish())) } } } + + /// Unloads a module whose entries did not all resolve; an unload failure poisons the context. Returns the + /// resolution failure as the primary error. + fn unload_failed(&self, module: ffi::ModuleHandle, error: Error) -> Error { + let api = &self.driver.api; + let cleanup = api.unload(module); + if cleanup.is_err() { + self.poisoned.set(true); + std::mem::forget(Rc::clone(api)); + } + combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary") + } +} + +/// Resolves the program's entries in order; the first failure is returned and nothing is kept. +fn resolve_entries( + api: &ffi::Api, + module: ffi::ModuleHandle, + program: Program, +) -> DriverResult<[Option; 5]> { + let mut functions = [None; 5]; + for (slot, entry) in functions.iter_mut().zip(program.entries()) { + *slot = Some(api.kar_levels_function(module, entry.name)?); + } + Ok(functions) } pub(super) fn i32_of(value: u64) -> Result { diff --git a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2.rs b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2.rs index 3a8fdb32..26d04a21 100644 --- a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2.rs +++ b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2.rs @@ -3,6 +3,8 @@ #[allow(unused_imports)] use super::*; +mod call_shape; + impl<'c> Experimental<'c> { /// Load (once) and return the cached program. Fails closed with `NotEnabled` / `Unpinned`. pub fn open(context: &'c Context<'c>, program: Program, opt_in: &OptIn) -> Result { @@ -110,26 +112,12 @@ impl<'c> Experimental<'c> { } let grid = experimental::q4_batch_grid(tokens, &p.shape)?; let rows = tokens * p.shape.kv_heads as u64 * p.shape.head_dim as u64 * 4; + let (q4, table_bytes) = (p.shape.q4_bytes(p.pages), p.table_entries * 4); let mut launches = Vec::new(); for is_v in 0..2 { - launches.push( - self.call(Q4_APPEND_BATCH) - .rw(k_q4, p.shape.q4_bytes(p.pages))? - .rw(v_q4, p.shape.q4_bytes(p.pages))? - .ro(table, p.table_entries * 4)? - .i64(pos0) - .ro(k, rows)? - .ro(v, rows)? - .i32(p.shape.kv_heads as i32) - .i32(p.shape.head_dim as i32) - .i32(p.shape.page_size as i32) - .i32(is_v) - .null() - .null() - .null() - .null() - .finish(grid)?, - ); + let call = self.call(Q4_APPEND_BATCH).rw(k_q4, q4)?.rw(v_q4, q4)?.ro(table, table_bytes)?; + let call = call.i64(pos0).ro(k, rows)?.ro(v, rows)?; + launches.push(call.shape_scalars(&p.shape).i32(is_v).nulls(4).finish(grid)?); } self.run(launches) } @@ -183,8 +171,7 @@ impl<'c> Experimental<'c> { ) -> Result<()> { self.expect(Program::KvQ8)?; let grid = experimental::q8_step_grid(&p.shape, keys.is_some())?; - let codes = p.shape.q8_code_bytes(p.pages); - let scales = p.shape.q8_scale_bytes(p.pages); + let (codes, scales) = (p.shape.q8_code_bytes(p.pages), p.shape.q8_scale_bytes(p.pages)); let cell = p.shape.kv_heads as u64 * p.shape.head_dim as u64 * 4; let mut c = self.call(Q8_APPEND_STEP); match keys { @@ -198,16 +185,7 @@ impl<'c> Experimental<'c> { c = c.ro(table, p.table_entries * 4)?.ro(step, STEP_BYTES)?.null(); } } - let launch = c - .ro(vcur, cell)? - .i32(p.shape.kv_heads as i32) - .i32(p.shape.head_dim as i32) - .i32(p.shape.page_size as i32) - .null() - .null() - .null() - .null() - .finish(grid)?; + let launch = c.ro(vcur, cell)?.shape_scalars(&p.shape).nulls(4).finish(grid)?; self.run(vec![launch]) } } diff --git a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2/call_shape.rs b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2/call_shape.rs new file mode 100644 index 00000000..7d645d72 --- /dev/null +++ b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2/call_shape.rs @@ -0,0 +1,19 @@ +//! Argument groups that the experimental KV launches repeat: the page-shape scalars and runs of null pointers. + +#[allow(unused_imports)] +use super::*; + +impl<'g, 'c> Call<'g, 'c> { + /// `kv_heads`, `head_dim` and `page_size` of the pool shape, as three i32 scalars. + pub(in crate::experimental_gpu) fn shape_scalars(self, shape: &KvShape) -> Self { + self.i32(shape.kv_heads as i32).i32(shape.head_dim as i32).i32(shape.page_size as i32) + } + + /// `n` null pointer arguments. + pub(in crate::experimental_gpu) fn nulls(mut self, n: usize) -> Self { + for _ in 0..n { + self = self.null(); + } + self + } +} diff --git a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2_2.rs b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2_2.rs index 53c7c0a0..972db249 100644 --- a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2_2.rs +++ b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2_2.rs @@ -22,24 +22,12 @@ impl<'c> Experimental<'c> { ) -> Result<()> { self.expect(Program::KvQ8)?; let grid = experimental::q8_gather_grid(max_ids, &p.shape)?; - let codes = p.shape.q8_code_bytes(p.pages); - let scales = p.shape.q8_scale_bytes(p.pages); + let (codes, scales) = (p.shape.q8_code_bytes(p.pages), p.shape.q8_scale_bytes(p.pages)); let scratch = p.shape.gather_scratch_bytes(max_ids); - let launch = self - .call(Q8_GATHER_STEP) - .ro(k_q, codes)? - .ro(v_q, codes)? - .ro(k_scale, scales)? - .ro(v_scale, scales)? - .ro(table, p.table_entries * 4)? - .ro(ids, max_ids * 4)? - .ro(step, STEP_BYTES)? - .i32(p.shape.kv_heads as i32) - .i32(p.shape.head_dim as i32) - .i32(p.shape.page_size as i32) - .rw(k_scratch, scratch)? - .rw(v_scratch, scratch)? - .finish(grid)?; + let reads = + self.call(Q8_GATHER_STEP).ro(k_q, codes)?.ro(v_q, codes)?.ro(k_scale, scales)?.ro(v_scale, scales)?; + let reads = reads.ro(table, p.table_entries * 4)?.ro(ids, max_ids * 4)?.ro(step, STEP_BYTES)?; + let launch = reads.shape_scalars(&p.shape).rw(k_scratch, scratch)?.rw(v_scratch, scratch)?.finish(grid)?; self.run(vec![launch]) } @@ -80,20 +68,45 @@ impl<'c> Experimental<'c> { if host.len() != runs.len() || slots.len() != runs.len() || runs.len() > 4 { return invalid("kv_stream: host/slot array counts differ from the format's runs"); } - let resolve = map - .bind(self.call(STREAM_RESOLVE), n_blocks, n_slots, true)? - .i64(i64_of(n_slots)?) - .ro(ids, n_q * cap * 4)? - .ro(steps, n_q * STEP_BYTES)? - .i32(i32_of(n_q)?) - .i32(i32_of(cap)?) - .i32(shape.page_size as i32) - .finish(experimental::STREAM_RESOLVE_GRID)?; - let mut copy = self + let call = map.bind(self.call(STREAM_RESOLVE), n_blocks, n_slots, true)?; + let call = call.i64(i64_of(n_slots)?).ro(ids, n_q * cap * 4)?.ro(steps, n_q * STEP_BYTES)?; + let resolve = call.i32(i32_of(n_q)?).i32(i32_of(cap)?).i32(shape.page_size as i32); + let resolve = resolve.finish(experimental::STREAM_RESOLVE_GRID)?; + let copy = self.stream_copy(map, &runs, host, slots, n_blocks, n_slots)?; + self.run(vec![resolve, copy]) + } + + /// The `copy_kernel` launch of `stream_resolve`: the miss list, the host and slot arrays, the run widths. + fn stream_copy( + &self, + map: &StreamMap<'_, '_>, + runs: &[(&'static str, u64)], + host: &[&DeviceBuffer<'_>], + slots: &[&mut DeviceBuffer<'_>], + n_blocks: u64, + n_slots: u64, + ) -> Result { + let copy = self .call(STREAM_COPY) .rw(&*map.ctl, CTL_INTS as u64 * 4)? .rw(&*map.miss_block, n_slots * 4)? .rw(&*map.miss_slot, n_slots * 4)?; + let mut copy = Self::stream_copy_arrays(copy, runs, host, slots, n_blocks, n_slots)?; + for i in 0..4 { + copy = copy.i32(runs.get(i).map_or(0, |r| r.1 as i32)); + } + copy.i32(runs.len() as i32).finish(experimental::STREAM_COPY_GRID) + } + + /// Up to four host-tier arrays then up to four slot arrays, a null pointer for each run the format lacks. + fn stream_copy_arrays<'g>( + mut copy: Call<'g, 'c>, + runs: &[(&'static str, u64)], + host: &[&DeviceBuffer<'_>], + slots: &[&mut DeviceBuffer<'_>], + n_blocks: u64, + n_slots: u64, + ) -> Result> { for i in 0..4 { copy = match (host.get(i), runs.get(i)) { (Some(h), Some(run)) => copy.ro(h, n_blocks * run.1)?, @@ -106,11 +119,7 @@ impl<'c> Experimental<'c> { _ => copy.null(), }; } - for i in 0..4 { - copy = copy.i32(runs.get(i).map_or(0, |r| r.1 as i32)); - } - let copy = copy.i32(runs.len() as i32).finish(experimental::STREAM_COPY_GRID)?; - self.run(vec![resolve, copy]) + Ok(copy) } /// `kv_ring_table`: the ring layout's fixed block -> slot table (`block % n_slots`). @@ -184,29 +193,65 @@ impl<'c> Experimental<'c> { if layer >= n_layers || r_ld < hc * n_embd { return invalid("control vector: layer or row stride out of range"); } - let rows = |ld: u64, width: u64| (tokens - 1) * ld + width; - let mut c = self - .call(CVEC_APPLY) - .rw(r, rows(r_ld, hc * n_embd) * 4)? - .ro(dir, n_layers * n_embd * 4)? - .ro(s_l, n_layers * 4)? - .ro(on, 4)? - .i32(mode as i32) - .i64(i64_of(layer)?) - .i32(i32_of(n_embd)?) - .i32(i32_of(hc)?) - .i64(i64_of(r_ld)?); - match pending { - Some((bo, bo_ld, inj, inj_ld)) => { - if bo_ld < n_embd || inj_ld < hc { - return invalid("control vector: pending-write strides are too small"); - } - c = c.ro(bo, rows(bo_ld, n_embd) * 4)?.i64(i64_of(bo_ld)?); - c = c.ro(inj, rows(inj_ld, hc) * 4)?.i64(i64_of(inj_ld)?); - } - None => c = c.null().i64(0).null().i64(0), - } - let launch = c.i32(i32::from(pending.is_some())).finish(grid)?; + let dims = CvecDims { n_embd, hc, tokens, layer, n_layers, r_ld }; + let c = dims.head(self.call(CVEC_APPLY), r, dir, s_l, on, mode)?; + let launch = dims.pending(c, pending)?.i32(i32::from(pending.is_some())).finish(grid)?; self.run(vec![launch]) } } + +/// The geometry of one `cvec_apply`: `tokens` residual rows of `hc` streams of `n_embd`, at row stride `r_ld`. +struct CvecDims { + n_embd: u64, + hc: u64, + tokens: u64, + layer: u64, + n_layers: u64, + r_ld: u64, +} + +impl CvecDims { + /// Elements spanned by `tokens` rows of `width` at row stride `ld`. + fn rows(&self, ld: u64, width: u64) -> u64 { + (self.tokens - 1) * ld + width + } + + /// The residual, direction, layer-scale and on-flag pointers, then mode, layer, width, streams and row stride. + fn head<'g, 'c>( + &self, + c: Call<'g, 'c>, + r: &DeviceBuffer<'_>, + dir: &DeviceBuffer<'_>, + s_l: &DeviceBuffer<'_>, + on: &DeviceBuffer<'_>, + mode: leleka_experimental_ref::cvec::CvecMode, + ) -> Result> { + Ok(c.rw(r, self.rows(self.r_ld, self.hc * self.n_embd) * 4)? + .ro(dir, self.n_layers * self.n_embd * 4)? + .ro(s_l, self.n_layers * 4)? + .ro(on, 4)? + .i32(mode as i32) + .i64(i64_of(self.layer)?) + .i32(i32_of(self.n_embd)?) + .i32(i32_of(self.hc)?) + .i64(i64_of(self.r_ld)?)) + } + + /// The optional pending FFN write `(bo, bo_ld, inj, inj_ld)`, folded in first (null pointers when absent). + fn pending<'g, 'c>( + &self, + c: Call<'g, 'c>, + pending: Option<(&DeviceBuffer<'_>, u64, &DeviceBuffer<'_>, u64)>, + ) -> Result> { + match pending { + Some((bo, bo_ld, inj, inj_ld)) => { + if bo_ld < self.n_embd || inj_ld < self.hc { + return invalid("control vector: pending-write strides are too small"); + } + let c = c.ro(bo, self.rows(bo_ld, self.n_embd) * 4)?.i64(i64_of(bo_ld)?); + Ok(c.ro(inj, self.rows(inj_ld, self.hc) * 4)?.i64(i64_of(inj_ld)?)) + } + None => Ok(c.null().i64(0).null().i64(0)), + } + } +} diff --git a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3.rs b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3.rs index 9305c3fe..7a84cb8e 100644 --- a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3.rs +++ b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3.rs @@ -3,6 +3,9 @@ #[allow(unused_imports)] use super::*; +mod attend_inputs; +use attend_inputs::Attend; + impl<'c> Experimental<'c> { // ------------------------------------------------------------------------------------ attention @@ -26,71 +29,9 @@ impl<'c> Experimental<'c> { self.expect(Program::QsaAttn)?; let chunk_grid = experimental::attn_chunk_grid(cap, &p.shape, n_q)?; let merge_grid = experimental::attn_merge_grid(&p.shape, n_q)?; - let n_chunks = chunk_grid[0] as u64; - let n_head = p.shape.n_head() as u64; - let stride = experimental::attn_scratch_floats(cap, &p.shape); - let m_offset = n_chunks * n_head * attn::HD as u64 * 4; - let l_offset = m_offset + n_chunks * n_head * 4; - let q_bytes = n_q * n_head * attn::HD as u64 * 4; - let (kv, ps) = (p.shape.kv_heads as i32, p.shape.page_size as i32); - let table_bytes = p.table_entries * 4; - let mut chunk = match pools { - AttnPools::Q4 { k_q4, v_q4 } => self - .call(ATTN_CHUNK_M2) - .ro(q, q_bytes)? - .ro(k_q4, p.shape.q4_bytes(p.pages))? - .ro(v_q4, p.shape.q4_bytes(p.pages))? - .ro(table, table_bytes)? - .ro(ids, n_q * cap * 4)? - .ro(steps, n_q * STEP_BYTES)? - .i32(kv) - .i32(ps), - AttnPools::K8V4 { k_q, k_scale, v_q4 } => self - .call(ATTN_CHUNK_M3) - .ro(q, q_bytes)? - .ro(k_q, p.shape.q8_code_bytes(p.pages))? - .ro(k_scale, p.shape.q8_scale_bytes(p.pages))? - .ro(v_q4, p.shape.q4_bytes(p.pages))? - .ro(table, table_bytes)? - .ro(ids, n_q * cap * 4)? - .ro(steps, n_q * STEP_BYTES)? - .i32(kv) - .i32(ps), - AttnPools::Keyless { v_q, v_scale, cos, sin, mrope } => { - let n_rot = leleka_experimental_ref::keyless::N_ROT as u64; - let c = self - .call(ATTN_CHUNK_M4) - .ro(q, q_bytes)? - .ro(v_q, p.shape.q8_code_bytes(p.pages))? - .ro(v_scale, p.shape.q8_scale_bytes(p.pages))? - .ro(table, table_bytes)? - .ro(cos, 4)? - .ro(sin, 4)?; - let c = match mrope { - Some(m) => c.ro(m, 4)?, - None => c.null(), - }; - c.i32(n_rot as i32).ro(ids, n_q * cap * 4)?.ro(steps, n_q * STEP_BYTES)?.i32(kv).i32(ps) - } - }; - let scratch_bytes = n_q * stride * 4; - chunk = chunk - .rw_at(scratch, scratch_bytes, 0)? - .rw_at(scratch, scratch_bytes, m_offset)? - .rw_at(scratch, scratch_bytes, l_offset)? - .i32(i32_of(n_chunks)?) - .i32(i32_of(cap)?) - .i64(i64_of(stride)?); - let chunk = chunk.finish(chunk_grid)?; - let merge = self - .call(ATTN_MERGE) - .ro_at(scratch, scratch_bytes, 0)? - .ro_at(scratch, scratch_bytes, m_offset)? - .ro_at(scratch, scratch_bytes, l_offset)? - .i32(i32_of(n_chunks)?) - .rw(out, q_bytes)? - .i64(i64_of(stride)?) - .finish(merge_grid)?; + let a = Attend { p, q, table, ids, steps, cap, n_q, n_chunks: chunk_grid[0] as u64 }; + let chunk = a.chunk_scratch(a.chunk(self, pools)?, scratch)?.finish(chunk_grid)?; + let merge = a.merge(self, scratch, out)?.finish(merge_grid)?; self.run(vec![chunk, merge]) } } diff --git a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3/attend_inputs.rs b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3/attend_inputs.rs new file mode 100644 index 00000000..ea6edb38 --- /dev/null +++ b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3/attend_inputs.rs @@ -0,0 +1,148 @@ +//! The inputs and derived sizes shared by the chunk and merge launches of `Experimental::attend`. + +#[allow(unused_imports)] +use super::*; + +/// The inputs and the derived sizes of one `attend`. +pub(super) struct Attend<'a, 'b> { + pub(super) p: &'a Paged, + pub(super) q: &'a DeviceBuffer<'b>, + pub(super) table: &'a DeviceBuffer<'b>, + pub(super) ids: &'a DeviceBuffer<'b>, + pub(super) steps: &'a DeviceBuffer<'b>, + pub(super) cap: u64, + pub(super) n_q: u64, + pub(super) n_chunks: u64, +} + +impl Attend<'_, '_> { + fn n_head(&self) -> u64 { + self.p.shape.n_head() as u64 + } + fn stride(&self) -> u64 { + experimental::attn_scratch_floats(self.cap, &self.p.shape) + } + fn m_offset(&self) -> u64 { + self.n_chunks * self.n_head() * attn::HD as u64 * 4 + } + fn l_offset(&self) -> u64 { + self.m_offset() + self.n_chunks * self.n_head() * 4 + } + fn q_bytes(&self) -> u64 { + self.n_q * self.n_head() * attn::HD as u64 * 4 + } + fn scratch_bytes(&self) -> u64 { + self.n_q * self.stride() * 4 + } + fn table_bytes(&self) -> u64 { + self.p.table_entries * 4 + } + + /// The chunk kernel of `pools`' mode with its pool, table, id and step pointers and page scalars. + pub(super) fn chunk<'g, 'c>(&self, gpu: &'g Experimental<'c>, pools: &AttnPools<'_, '_>) -> Result> { + match pools { + AttnPools::Q4 { k_q4, v_q4 } => self.q4_chunk(gpu, k_q4, v_q4), + AttnPools::K8V4 { k_q, k_scale, v_q4 } => self.k8v4_chunk(gpu, k_q, k_scale, v_q4), + AttnPools::Keyless { v_q, v_scale, cos, sin, mrope } => { + self.keyless_chunk(gpu, [v_q, v_scale, cos, sin], *mrope) + } + } + } + + /// `ids`, `steps` and the page scalars that close the leading arguments of every chunk kernel. + fn ids_steps<'g, 'c>(&self, c: Call<'g, 'c>) -> Result> { + Ok(c.ro(self.ids, self.n_q * self.cap * 4)? + .ro(self.steps, self.n_q * STEP_BYTES)? + .i32(self.p.shape.kv_heads as i32) + .i32(self.p.shape.page_size as i32)) + } + + /// Mode 2: Q4_0 keys and values. + fn q4_chunk<'g, 'c>( + &self, + gpu: &'g Experimental<'c>, + k_q4: &DeviceBuffer<'_>, + v_q4: &DeviceBuffer<'_>, + ) -> Result> { + let p = self.p; + let c = gpu + .call(ATTN_CHUNK_M2) + .ro(self.q, self.q_bytes())? + .ro(k_q4, p.shape.q4_bytes(p.pages))? + .ro(v_q4, p.shape.q4_bytes(p.pages))? + .ro(self.table, self.table_bytes())?; + self.ids_steps(c) + } + + /// Mode 3: INT8 keys with their scales, Q4_0 values. + fn k8v4_chunk<'g, 'c>( + &self, + gpu: &'g Experimental<'c>, + k_q: &DeviceBuffer<'_>, + k_scale: &DeviceBuffer<'_>, + v_q4: &DeviceBuffer<'_>, + ) -> Result> { + let p = self.p; + let c = gpu + .call(ATTN_CHUNK_M3) + .ro(self.q, self.q_bytes())? + .ro(k_q, p.shape.q8_code_bytes(p.pages))? + .ro(k_scale, p.shape.q8_scale_bytes(p.pages))? + .ro(v_q4, p.shape.q4_bytes(p.pages))? + .ro(self.table, self.table_bytes())?; + self.ids_steps(c) + } + + /// Mode 4: V-only INT8 (`[v_q, v_scale, cos, sin]`), keys rebuilt by RoPE, optional M-RoPE positions. + fn keyless_chunk<'g, 'c>( + &self, + gpu: &'g Experimental<'c>, + [v_q, v_scale, cos, sin]: [&DeviceBuffer<'_>; 4], + mrope: Option<&DeviceBuffer<'_>>, + ) -> Result> { + let p = self.p; + let n_rot = leleka_experimental_ref::keyless::N_ROT as u64; + let c = gpu + .call(ATTN_CHUNK_M4) + .ro(self.q, self.q_bytes())? + .ro(v_q, p.shape.q8_code_bytes(p.pages))? + .ro(v_scale, p.shape.q8_scale_bytes(p.pages))? + .ro(self.table, self.table_bytes())? + .ro(cos, 4)? + .ro(sin, 4)?; + let c = match mrope { + Some(m) => c.ro(m, 4)?, + None => c.null(), + }; + self.ids_steps(c.i32(n_rot as i32)) + } + + /// The three scratch carve-outs the chunk kernel writes (partials, running max, running sum) and its scalars. + pub(super) fn chunk_scratch<'g, 'c>(&self, c: Call<'g, 'c>, scratch: &DeviceBuffer<'_>) -> Result> { + let bytes = self.scratch_bytes(); + Ok(c.rw_at(scratch, bytes, 0)? + .rw_at(scratch, bytes, self.m_offset())? + .rw_at(scratch, bytes, self.l_offset())? + .i32(i32_of(self.n_chunks)?) + .i32(i32_of(self.cap)?) + .i64(i64_of(self.stride())?)) + } + + /// The merge kernel: reads the same three carve-outs back and writes `out`. + pub(super) fn merge<'g, 'c>( + &self, + gpu: &'g Experimental<'c>, + scratch: &DeviceBuffer<'_>, + out: &DeviceBuffer<'_>, + ) -> Result> { + let bytes = self.scratch_bytes(); + Ok(gpu + .call(ATTN_MERGE) + .ro_at(scratch, bytes, 0)? + .ro_at(scratch, bytes, self.m_offset())? + .ro_at(scratch, bytes, self.l_offset())? + .i32(i32_of(self.n_chunks)?) + .rw(out, self.q_bytes())? + .i64(i64_of(self.stride())?)) + } +} From 00eb77d05cd233bd1527a0f89ab5af9dadaa2db7 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 22:25:00 +0100 Subject: [PATCH 3/7] STRA-338 size2 cd1: experimental and closed program GPU smokes split into cases --- .../src/closed_kernels_gpu_smoke.rs | 150 +-------- .../src/closed_kernels_gpu_smoke/cases.rs | 186 +++++++++++ .../cuda-driver/src/experimental_gpu_smoke.rs | 313 +++++++++++------- 3 files changed, 397 insertions(+), 252 deletions(-) create mode 100644 crates/cuda-driver/src/closed_kernels_gpu_smoke/cases.rs diff --git a/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs b/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs index 2b472d5c..7d350a1f 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs @@ -49,85 +49,18 @@ fn closed_gpu_native_flash_attn_matches_the_fp64_specification() { let ctx = driver.device(0).unwrap().create_context(128 << 20).unwrap(); { let gpu = open(&ctx, Program::NativeFlashAttn); - let capacity = 256usize; let mut worst = 0f64; for width in [1usize, 2, 5, 31, 32, 33, 100, 128, 129, 255, 256] { for with_mask in [false, true] { - let mut rng = Rng(0xf1a5_0000 + width as u64 * 2 + u64::from(with_mask)); - let q: Vec = (0..24 * 256).map(|_| 0.8 * rng.normal()).collect(); - let k: Vec = (0..capacity * 512).map(|_| f16_bits(rng.normal())).collect(); - let v: Vec = (0..capacity * 512).map(|_| f16_bits(rng.normal())).collect(); - let mask: Vec = - (0..256).map(|c| f16_bits(if with_mask { ((c * 7) % 5) as f32 * -0.5 } else { 0.0 })).collect(); - let step = [width as i32 - 1, width as i32, width as i32 / 4, width as i32]; - let bytes = |h: &[u16]| h.iter().flat_map(|x| x.to_le_bytes()).collect::>(); - let (q_b, k_b, v_b) = ( - upload(&ctx, &q.iter().flat_map(|x| x.to_le_bytes()).collect::>()), - upload(&ctx, &bytes(&k)), - upload(&ctx, &bytes(&v)), - ); - let step_b = upload(&ctx, &step.iter().flat_map(|x| x.to_le_bytes()).collect::>()); - let mask_b = upload(&ctx, &bytes(&mask)); - let mut out_b = upload(&ctx, &vec![0xffu8; 24 * 256 * 4]); - let mut status_b = upload(&ctx, &(-1i32).to_le_bytes()); - gpu.native_flash_attn_short( - &q_b, - &k_b, - &v_b, - &step_b, - with_mask.then_some(&mask_b), - capacity as i64, - 2051, - 256, - &mut out_b, - &mut status_b, - ) - .unwrap(); - assert_eq!( - i32::from_le_bytes(download(&status_b, 4)[..4].try_into().unwrap()), - flash::STATUS_SUCCESS, - "width {width}" - ); - let out = f32s(&download(&out_b, 24 * 256 * 4)); - let h2f = |b: u16| sg::f16_to_f32(b); - for head in 0..24 { - let kv = head / 12; - let kk: Vec> = - (0..width).map(|c| (0..256).map(|d| h2f(k[(c * 2 + kv) * 256 + d])).collect()).collect(); - let vv: Vec> = - (0..width).map(|c| (0..256).map(|d| h2f(v[(c * 2 + kv) * 256 + d])).collect()).collect(); - let m: Vec = (0..width).map(|c| h2f(mask[c])).collect(); - let want = - flash::reference_head(&q[head * 256..(head + 1) * 256], &kk, &vv, with_mask.then_some(&m[..])); - let magnitude = want.iter().fold(1e-6f64, |a, w| a.max(f64::from(w.abs()))); - for d in 0..256 { - worst = worst.max(f64::from((out[head * 256 + d] - want[d]).abs()) / magnitude); - } - } + let case = cases::FlashCase::random(width, with_mask); + let (status, out) = case.run(&ctx, &gpu); + assert_eq!(status, flash::STATUS_SUCCESS, "width {width}"); + worst = worst.max(case.worst_error(&out)); } } println!("CLOSED native_flash_attn worst relative error {worst:.3e}"); assert!(worst < 5e-5, "worst relative error {worst}"); - // an invalid step record is refused on the device: status 1 and a NaN output - let zeros = vec![0u8; 24 * 256 * 4]; - let (q_b, kv_b) = (upload(&ctx, &zeros), upload(&ctx, &vec![0u8; 256 * 1024])); - let step_b = upload(&ctx, &[0u8; 16]); - let (mut out_b, mut status_b) = (upload(&ctx, &zeros), upload(&ctx, &0i32.to_le_bytes())); - gpu.native_flash_attn_short( - &q_b, - &kv_b, - &zero_kv(&ctx), - &step_b, - None, - 256, - 2051, - 256, - &mut out_b, - &mut status_b, - ) - .unwrap(); - assert_eq!(i32::from_le_bytes(download(&status_b, 4)[..4].try_into().unwrap()), flash::STATUS_UNSUPPORTED_STEP); - assert!(f32s(&download(&out_b, 24 * 256 * 4)).iter().all(|x| x.is_nan())); + cases::assert_invalid_step_refused(&ctx, &gpu); gpu.close().unwrap(); } ctx.close().unwrap(); @@ -148,73 +81,10 @@ fn closed_gpu_s_gemv_matches_the_shim_executed_golden() { let mut worst = 0f64; let mut launches = 0; for case in golden["cases"].as_array().unwrap() { - let name = case["name"].as_str().unwrap(); - let form = SForm { - code_bits: case["bits"].as_i64().unwrap() as i32, - code_bias: case["bias"].as_i64().unwrap() as i32, - group_elems: case["group"].as_i64().unwrap() as i32, - codebook: if case["codebook"].as_i64().unwrap() == 1 { Codebook::Iq4Nl } else { Codebook::Affine }, - has_offset: case["has_offset"].as_i64().unwrap() == 1, - act_kind: 0, - }; - let (n_in, n_out) = (case["n_in"].as_i64().unwrap(), case["n_out"].as_i64().unwrap()); - let exact = case["exact"].as_i64().unwrap() == 1; - let codes = upload(&ctx, &json_bytes(&case["codes"])); - let scales = - upload(&ctx, &json_f32(&case["scales"]).iter().flat_map(|x| x.to_le_bytes()).collect::>()); - let offset = form.has_offset.then(|| { - upload(&ctx, &json_f32(&case["offset"]).iter().flat_map(|x| x.to_le_bytes()).collect::>()) - }); - let x16: Vec = - case["x"].as_array().unwrap().iter().flat_map(|v| (v.as_u64().unwrap() as u16).to_le_bytes()).collect(); - let (x16_b, q8k, q80) = (upload(&ctx, &x16), json_bytes(&case["q8k"]), json_bytes(&case["q80"])); - let mut check = |what: &str, plan: sg::Plan, x: &DeviceBuffer<'_>, want: &[f32]| { - let mut y = upload(&ctx, &vec![0xffu8; n_out as usize * 4]); - if form.code_bits == 2 && matches!(plan.kernel, Kernel::S2Gemv | Kernel::S2GemvQuads | Kernel::S2GemvQ8) - { - gpu.s2_gemv(&plan, n_in, n_out, x, &codes, &scales, &mut y).unwrap(); - } else { - gpu.s_gemv(&plan, &form, n_in, n_out, x, &codes, &scales, offset.as_ref(), &mut y).unwrap(); - } - let got = f32s(&download(&y, n_out as usize * 4)); - let magnitude = want.iter().fold(1e-6f64, |a, w| a.max(f64::from(w.abs()))); - for (o, (g, w)) in got.iter().zip(want).enumerate() { - if exact { - assert_eq!(g.to_bits(), w.to_bits(), "{name} {what} row {o}"); - } - worst = worst.max(f64::from((g - w).abs()) / magnitude); - } - launches += 1; - }; - let y_fp16 = json_f32(&case["y_fp16"]); - let offset_present = form.has_offset; - if exact { - check("s_gemv", sg::plan_s_gemv(n_in, n_out, &form, offset_present).unwrap().unwrap(), &x16_b, &y_fp16); - } - check( - "s_gemv_split64", - sg::plan_s_gemv_split(n_in, n_out, &form, 64, offset_present).unwrap().unwrap(), - &x16_b, - &y_fp16, - ); - if form.code_bits != 2 && !q8k.is_empty() { - let b = upload(&ctx, &q8k); - check( - "q8k_split", - sg::plan_s_gemv_q8k_split(n_in, n_out, &form).unwrap().unwrap(), - &b, - &json_f32(&case["y_q8k"]), - ); - } - if form.code_bits != 2 && !q80.is_empty() { - let b = upload(&ctx, &q80); - check( - "q8_0_split", - sg::plan_s_gemv_q8_0_split(n_in, n_out, &form).unwrap().unwrap(), - &b, - &json_f32(&case["y_q80"]), - ); - } + let mut replay = cases::Replay::new(&ctx, &gpu, case); + replay.run(case); + worst = worst.max(replay.worst); + launches += replay.launches; } println!("CLOSED s_gemv_legacy launches={launches} worst relative error {worst:.3e}"); assert!(worst < 1e-4, "worst relative error {worst}"); @@ -223,6 +93,8 @@ fn closed_gpu_s_gemv_matches_the_shim_executed_golden() { ctx.close().unwrap(); } +#[path = "closed_kernels_gpu_smoke/cases.rs"] +mod cases; #[path = "closed_kernels_gpu_smoke/impl_rng.rs"] mod impl_rng; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/closed_kernels_gpu_smoke/cases.rs b/crates/cuda-driver/src/closed_kernels_gpu_smoke/cases.rs new file mode 100644 index 00000000..ae28e55f --- /dev/null +++ b/crates/cuda-driver/src/closed_kernels_gpu_smoke/cases.rs @@ -0,0 +1,186 @@ +//! The cases of the closed-program smokes: one short FlashAttention case and one replayed S-form GEMV golden case. + +#[allow(unused_imports)] +use super::*; + +const CAPACITY: usize = 256; + +fn half_bytes(h: &[u16]) -> Vec { + h.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +fn f32_bytes(v: &[f32]) -> Vec { + v.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +fn json_f32_bytes(v: &serde_json::Value) -> Vec { + f32_bytes(&json_f32(v)) +} + +/// Random inputs of one short FlashAttention case of `width` cells, with or without the additive mask. +pub(super) struct FlashCase { + q: Vec, + k: Vec, + v: Vec, + mask: Vec, + width: usize, + with_mask: bool, +} + +impl FlashCase { + pub(super) fn random(width: usize, with_mask: bool) -> Self { + let mut rng = Rng(0xf1a5_0000 + width as u64 * 2 + u64::from(with_mask)); + let q = (0..24 * 256).map(|_| 0.8 * rng.normal()).collect(); + let k = (0..CAPACITY * 512).map(|_| f16_bits(rng.normal())).collect(); + let v = (0..CAPACITY * 512).map(|_| f16_bits(rng.normal())).collect(); + let mask = (0..256).map(|c| f16_bits(if with_mask { ((c * 7) % 5) as f32 * -0.5 } else { 0.0 })).collect(); + Self { q, k, v, mask, width, with_mask } + } + + /// The device's status word and output floats for this case. + pub(super) fn run<'c>(&self, ctx: &'c Context<'c>, gpu: &ClosedKernels<'c>) -> (i32, Vec) { + let width = self.width as i32; + let step = [width - 1, width, width / 4, width]; + let (q_b, k_b, v_b) = + (upload(ctx, &f32_bytes(&self.q)), upload(ctx, &half_bytes(&self.k)), upload(ctx, &half_bytes(&self.v))); + let step_b = upload(ctx, &step.iter().flat_map(|x| x.to_le_bytes()).collect::>()); + let mask_b = upload(ctx, &half_bytes(&self.mask)); + let mut out_b = upload(ctx, &vec![0xffu8; 24 * 256 * 4]); + let mut status_b = upload(ctx, &(-1i32).to_le_bytes()); + let mask = self.with_mask.then_some(&mask_b); + gpu.native_flash_attn_short( + &q_b, + &k_b, + &v_b, + &step_b, + mask, + CAPACITY as i64, + 2051, + 256, + &mut out_b, + &mut status_b, + ) + .unwrap(); + let status = i32::from_le_bytes(download(&status_b, 4)[..4].try_into().unwrap()); + (status, f32s(&download(&out_b, 24 * 256 * 4))) + } + + /// The worst error of `out` relative to the largest reference magnitude of its head, over all heads. + pub(super) fn worst_error(&self, out: &[f32]) -> f64 { + (0..24).fold(0f64, |worst, head| worst.max(self.head_error(out, head))) + } + + /// The worst error of one head against the fp64 reference, relative to its largest reference magnitude. + fn head_error(&self, out: &[f32], head: usize) -> f64 { + let h2f = |b: u16| sg::f16_to_f32(b); + let (width, kv) = (self.width, head / 12); + let cells = |x: &[u16]| -> Vec> { + (0..width).map(|c| (0..256).map(|d| h2f(x[(c * 2 + kv) * 256 + d])).collect()).collect() + }; + let (kk, vv) = (cells(&self.k), cells(&self.v)); + let m: Vec = (0..width).map(|c| h2f(self.mask[c])).collect(); + let q = &self.q[head * 256..(head + 1) * 256]; + let want = flash::reference_head(q, &kk, &vv, self.with_mask.then_some(&m[..])); + let magnitude = want.iter().fold(1e-6f64, |a, w| a.max(f64::from(w.abs()))); + (0..256).fold(0f64, |worst, d| worst.max(f64::from((out[head * 256 + d] - want[d]).abs()) / magnitude)) + } +} + +/// An invalid step record is refused on the device: status 1 and a NaN output. +pub(super) fn assert_invalid_step_refused<'c>(ctx: &'c Context<'c>, gpu: &ClosedKernels<'c>) { + let zeros = vec![0u8; 24 * 256 * 4]; + let (q_b, kv_b) = (upload(ctx, &zeros), upload(ctx, &vec![0u8; 256 * 1024])); + let step_b = upload(ctx, &[0u8; 16]); + let (mut out_b, mut status_b) = (upload(ctx, &zeros), upload(ctx, &0i32.to_le_bytes())); + gpu.native_flash_attn_short(&q_b, &kv_b, &zero_kv(ctx), &step_b, None, 256, 2051, 256, &mut out_b, &mut status_b) + .unwrap(); + assert_eq!(i32::from_le_bytes(download(&status_b, 4)[..4].try_into().unwrap()), flash::STATUS_UNSUPPORTED_STEP); + assert!(f32s(&download(&out_b, 24 * 256 * 4)).iter().all(|x| x.is_nan())); +} + +fn golden_form(case: &serde_json::Value) -> SForm { + SForm { + code_bits: case["bits"].as_i64().unwrap() as i32, + code_bias: case["bias"].as_i64().unwrap() as i32, + group_elems: case["group"].as_i64().unwrap() as i32, + codebook: if case["codebook"].as_i64().unwrap() == 1 { Codebook::Iq4Nl } else { Codebook::Affine }, + has_offset: case["has_offset"].as_i64().unwrap() == 1, + act_kind: 0, + } +} + +/// One golden case of the S-form GEMVs replayed on the device, with the worst relative error of its launches. +pub(super) struct Replay<'a, 'c> { + ctx: &'c Context<'c>, + gpu: &'a ClosedKernels<'c>, + name: &'a str, + form: SForm, + n_in: i64, + n_out: i64, + exact: bool, + codes: DeviceBuffer<'c>, + scales: DeviceBuffer<'c>, + offset: Option>, + pub(super) worst: f64, + pub(super) launches: usize, +} + +impl<'a, 'c> Replay<'a, 'c> { + pub(super) fn new(ctx: &'c Context<'c>, gpu: &'a ClosedKernels<'c>, case: &'a serde_json::Value) -> Self { + let name = case["name"].as_str().unwrap(); + let form = golden_form(case); + let (n_in, n_out) = (case["n_in"].as_i64().unwrap(), case["n_out"].as_i64().unwrap()); + let exact = case["exact"].as_i64().unwrap() == 1; + let codes = upload(ctx, &json_bytes(&case["codes"])); + let scales = upload(ctx, &json_f32_bytes(&case["scales"])); + let offset = form.has_offset.then(|| upload(ctx, &json_f32_bytes(&case["offset"]))); + Self { ctx, gpu, name, form, n_in, n_out, exact, codes, scales, offset, worst: 0.0, launches: 0 } + } + + /// Launches the planned kernel on activation `x` and compares with `want`: bit for bit when the case is exact. + fn check(&mut self, what: &str, plan: sg::Plan, x: &DeviceBuffer<'_>, want: &[f32]) { + let (n_in, n_out) = (self.n_in, self.n_out); + let mut y = upload(self.ctx, &vec![0xffu8; n_out as usize * 4]); + let s2 = matches!(plan.kernel, Kernel::S2Gemv | Kernel::S2GemvQuads | Kernel::S2GemvQ8); + if self.form.code_bits == 2 && s2 { + self.gpu.s2_gemv(&plan, n_in, n_out, x, &self.codes, &self.scales, &mut y).unwrap(); + } else { + let offset = self.offset.as_ref(); + self.gpu.s_gemv(&plan, &self.form, n_in, n_out, x, &self.codes, &self.scales, offset, &mut y).unwrap(); + } + let got = f32s(&download(&y, n_out as usize * 4)); + let magnitude = want.iter().fold(1e-6f64, |a, w| a.max(f64::from(w.abs()))); + for (o, (g, w)) in got.iter().zip(want).enumerate() { + if self.exact { + assert_eq!(g.to_bits(), w.to_bits(), "{} {what} row {o}", self.name); + } + self.worst = self.worst.max(f64::from((g - w).abs()) / magnitude); + } + self.launches += 1; + } + + /// The fp16-activation launches, then the split launches over the case's `block_q8_K` / `block_q8_0` activations. + pub(super) fn run(&mut self, case: &serde_json::Value) { + let x16: Vec = + case["x"].as_array().unwrap().iter().flat_map(|v| (v.as_u64().unwrap() as u16).to_le_bytes()).collect(); + let (x16_b, q8k, q80) = (upload(self.ctx, &x16), json_bytes(&case["q8k"]), json_bytes(&case["q80"])); + let (n_in, n_out, offset_present) = (self.n_in, self.n_out, self.form.has_offset); + let y_fp16 = json_f32(&case["y_fp16"]); + if self.exact { + let plan = sg::plan_s_gemv(n_in, n_out, &self.form, offset_present).unwrap().unwrap(); + self.check("s_gemv", plan, &x16_b, &y_fp16); + } + let plan = sg::plan_s_gemv_split(n_in, n_out, &self.form, 64, offset_present).unwrap().unwrap(); + self.check("s_gemv_split64", plan, &x16_b, &y_fp16); + if self.form.code_bits != 2 && !q8k.is_empty() { + let b = upload(self.ctx, &q8k); + let plan = sg::plan_s_gemv_q8k_split(n_in, n_out, &self.form).unwrap().unwrap(); + self.check("q8k_split", plan, &b, &json_f32(&case["y_q8k"])); + } + if self.form.code_bits != 2 && !q80.is_empty() { + let b = upload(self.ctx, &q80); + let plan = sg::plan_s_gemv_q8_0_split(n_in, n_out, &self.form).unwrap().unwrap(); + self.check("q8_0_split", plan, &b, &json_f32(&case["y_q80"])); + } + } +} diff --git a/crates/cuda-driver/src/experimental_gpu_smoke.rs b/crates/cuda-driver/src/experimental_gpu_smoke.rs index a00c19fb..5e3d9f84 100644 --- a/crates/cuda-driver/src/experimental_gpu_smoke.rs +++ b/crates/cuda-driver/src/experimental_gpu_smoke.rs @@ -89,6 +89,67 @@ fn experimental_gpu_fwht256_matches_cpu() { } ctx.close().unwrap(); } +/// Appends 13 cells through `q4_append_step`; returns the device pools and the cells for the CPU model. +fn append_cells<'c>( + ctx: &'c Context<'c>, + gpu: &Experimental<'c>, + p: &Paged, + table_b: &DeviceBuffer<'_>, +) -> (DeviceBuffer<'c>, DeviceBuffer<'c>, Vec<(i32, Vec, Vec)>) { + let mut rng = Rng(0x57a7_0002); + let n = 2 * 256; + let mut cells = Vec::new(); + let (mut k_b, mut v_b) = (zeroed(ctx, p.shape.q4_bytes(4) as usize), zeroed(ctx, p.shape.q4_bytes(4) as usize)); + for pos in 0..13i32 { + let kc: Vec = (0..n).map(|_| rng.unit()).collect(); + let vc: Vec = (0..n).map(|_| rng.unit()).collect(); + let step = upload(ctx, &i32_bytes(&[pos, 0, 0, 0])); + let (kb, vb) = (upload(ctx, &f32_bytes(&kc)), upload(ctx, &f32_bytes(&vc))); + gpu.q4_append_step(p, &mut k_b, &mut v_b, table_b, &step, &kb, &vb).unwrap(); + cells.push((pos, kc, vc)); + } + (k_b, v_b, cells) +} + +/// The CPU pools after the same cells under the first contraction model (fused, else separate) that reproduces the +/// device bytes; `"none"` with fresh pools when neither does. +fn matching_model( + p: &Paged, + q: &QsaShapes, + table: &[i32], + cells: &[(i32, Vec, Vec)], + got: (&[u8], &[u8]), +) -> (&'static str, PoolSet) { + for (name, c) in [("fused", Contraction::Fused), ("separate", Contraction::Separate)] { + let mut m = PoolSet::new(KvFormat::Q4_0, q, p.shape.rows(p.pages)).unwrap(); + for (pos, kc, vc) in cells { + append_cell(KvFormat::Q4_0, &mut m, None, table, i64::from(*pos), kc, vc, q, c).unwrap(); + } + if m.k_q4 == got.0 && m.v_q4 == got.1 { + return (name, m); + } + } + ("none", PoolSet::new(KvFormat::Q4_0, q, p.shape.rows(p.pages)).unwrap()) +} + +/// Gathers cells 0, 3, 5, 7, 9, 12 on the device and compares the fp16 K bits with the CPU gather. +fn assert_q4_gather<'c>( + ctx: &'c Context<'c>, + gpu: &Experimental<'c>, + p: &Paged, + pools: [&DeviceBuffer<'_>; 4], + cpu: (&PoolSet, &[i32], &QsaShapes), +) { + let [k_b, v_b, table_b, ids_b] = pools; + let ids = [0, 3, 5, 7, 9, 12]; + let step = upload(ctx, &i32_bytes(&[0, 13, 0, 6])); + let scratch = p.shape.gather_scratch_bytes(6) as usize; + let (mut ks, mut vs) = (zeroed(ctx, scratch), zeroed(ctx, scratch)); + gpu.q4_gather_step(p, k_b, v_b, table_b, ids_b, &step, 6, &mut ks, &mut vs).unwrap(); + let want_k = gather_q4(&cpu.0.k_q4, cpu.1, &ids, cpu.2).unwrap(); + let got: Vec = download(&ks, scratch).chunks(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect(); + assert_eq!(got, want_k, "gathered fp16 K bits"); +} #[test] #[ignore = "Root schedules the first experimental GPU gate after nvcc build and pin freeze"] @@ -100,47 +161,15 @@ fn experimental_gpu_q4_append_and_gather_match_cpu() { let q = QsaShapes::real(); let p = Paged { shape: KvShape::real(), pages: 4, table_entries: 4 }; let table: Vec = vec![0, 1, 2, 3]; - let mut rng = Rng(0x57a7_0002); - let n = 2 * 256; - let mut cpu = PoolSet::new(KvFormat::Q4_0, &q, p.shape.rows(p.pages)).unwrap(); - let mut cells = Vec::new(); - let (mut k_b, mut v_b) = - (zeroed(&ctx, p.shape.q4_bytes(4) as usize), zeroed(&ctx, p.shape.q4_bytes(4) as usize)); let (table_b, ids_b) = (upload(&ctx, &i32_bytes(&table)), upload(&ctx, &i32_bytes(&[0, 3, 5, 7, 9, 12]))); - for pos in 0..13i32 { - let kc: Vec = (0..n).map(|_| rng.unit()).collect(); - let vc: Vec = (0..n).map(|_| rng.unit()).collect(); - let step = upload(&ctx, &i32_bytes(&[pos, 0, 0, 0])); - let (kb, vb) = (upload(&ctx, &f32_bytes(&kc)), upload(&ctx, &f32_bytes(&vc))); - gpu.q4_append_step(&p, &mut k_b, &mut v_b, &table_b, &step, &kb, &vb).unwrap(); - cells.push((pos, kc, vc)); - } + let (k_b, v_b, cells) = append_cells(&ctx, &gpu, &p, &table_b); let got_k = download(&k_b, p.shape.q4_bytes(4) as usize); let got_v = download(&v_b, p.shape.q4_bytes(4) as usize); // nvcc contracts a*b+c; the Fused model is the expectation, Separate the fallback we report. - let mut which = "none"; - for (name, c) in [("fused", Contraction::Fused), ("separate", Contraction::Separate)] { - let mut m = PoolSet::new(KvFormat::Q4_0, &q, p.shape.rows(p.pages)).unwrap(); - for (pos, kc, vc) in &cells { - append_cell(KvFormat::Q4_0, &mut m, None, &table, i64::from(*pos), kc, vc, &q, c).unwrap(); - } - if m.k_q4 == got_k && m.v_q4 == got_v { - which = name; - cpu = m; - break; - } - } + let (which, cpu) = matching_model(&p, &q, &table, &cells, (&got_k, &got_v)); assert_ne!(which, "none", "device Q4_0 pools differ from both contraction models"); println!("EXPERIMENTAL q4_append cells=13 matches={which}"); - // gather - let ids = [0, 3, 5, 7, 9, 12]; - let step = upload(&ctx, &i32_bytes(&[0, 13, 0, 6])); - let scratch = p.shape.gather_scratch_bytes(6) as usize; - let (mut ks, mut vs) = (zeroed(&ctx, scratch), zeroed(&ctx, scratch)); - gpu.q4_gather_step(&p, &k_b, &v_b, &table_b, &ids_b, &step, 6, &mut ks, &mut vs).unwrap(); - let want_k = gather_q4(&cpu.k_q4, &table, &ids, &q).unwrap(); - let got: Vec = download(&ks, scratch).chunks(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect(); - assert_eq!(got, want_k, "gathered fp16 K bits"); + assert_q4_gather(&ctx, &gpu, &p, [&k_b, &v_b, &table_b, &ids_b], (&cpu, &table, &q)); gpu.close().unwrap(); } ctx.close().unwrap(); @@ -170,6 +199,134 @@ fn experimental_gpu_keyless_route_matches_cpu() { ctx.close().unwrap(); } +const STREAM_BLOCKS: u64 = 4096; +const STREAM_SLOTS: u64 = 1024; +const STREAM_QUERIES: u64 = 2; +const STREAM_CAP: u64 = 64; + +/// The seven device buffers of one streamed layer's residency map. +struct MapBuffers<'c> { + page_table: DeviceBuffer<'c>, + slot_block: DeviceBuffer<'c>, + slot_stamp: DeviceBuffer<'c>, + slot_ref: DeviceBuffer<'c>, + ctl: DeviceBuffer<'c>, + miss_block: DeviceBuffer<'c>, + miss_slot: DeviceBuffer<'c>, +} + +impl<'c> MapBuffers<'c> { + fn new(ctx: &'c Context<'c>) -> Self { + let slots = STREAM_SLOTS as usize; + Self { + page_table: upload(ctx, &i32_bytes(&vec![-1; STREAM_BLOCKS as usize])), + slot_block: zeroed(ctx, slots * 4), + slot_stamp: zeroed(ctx, slots * 4), + slot_ref: zeroed(ctx, slots * 4), + ctl: zeroed(ctx, CTL_INTS * 4), + miss_block: zeroed(ctx, slots * 4), + miss_slot: zeroed(ctx, slots * 4), + } + } + + fn map(&mut self) -> StreamMap<'_, 'c> { + StreamMap { + page_table: &mut self.page_table, + slot_block: &mut self.slot_block, + slot_stamp: &mut self.slot_stamp, + slot_ref: &mut self.slot_ref, + ctl: &mut self.ctl, + miss_block: &mut self.miss_block, + miss_slot: &mut self.miss_slot, + } + } +} + +/// Two queries, ascending cell ids; a cell is page_size = 4 per block. +fn resolve_inputs() -> (Vec, Vec) { + let width = STREAM_CAP as i32; + let mut ids = Vec::new(); + let mut steps = Vec::new(); + for qi in 0..STREAM_QUERIES as i32 { + ids.extend((0..STREAM_CAP as i32).map(|i| i * 4 + qi * 8)); + steps.extend([STREAM_CAP as i32 * 4, 0, 0, width]); + } + (ids, steps) +} + +/// Uploads the ids and step records and runs `stream_resolve` (+ copy) over the host arrays into the slot arrays. +fn resolve_on_device<'c>( + ctx: &'c Context<'c>, + gpu: &Experimental<'c>, + buffers: &mut MapBuffers<'c>, + host: &[DeviceBuffer<'c>], + slots: &mut [DeviceBuffer<'c>], + inputs: (&[i32], &[i32]), +) { + let (ids_b, steps_b) = (upload(ctx, &i32_bytes(inputs.0)), upload(ctx, &i32_bytes(inputs.1))); + let host_refs: Vec<&DeviceBuffer<'_>> = host.iter().collect(); + let mut slot_refs: Vec<&mut DeviceBuffer<'_>> = slots.iter_mut().collect(); + gpu.stream_resolve( + &mut buffers.map(), + StreamFormat::F16, + &KvShape::real(), + STREAM_BLOCKS, + STREAM_SLOTS, + &ids_b, + &steps_b, + STREAM_QUERIES, + STREAM_CAP, + &host_refs, + &mut slot_refs, + ) + .unwrap(); +} + +/// Block `b` sits in slot `slot` of every array, byte for byte as in the host array. +fn assert_block_copied( + slots: &[DeviceBuffer<'_>], + host_bytes: &[Vec], + runs: &[(&'static str, u64)], + at: (usize, usize), +) { + let (b, slot) = at; + for (i, (_, len)) in runs.iter().enumerate() { + let len = *len as usize; + let got = download(&slots[i], (STREAM_SLOTS as usize) * len); + assert_eq!(&got[slot * len..(slot + 1) * len], &host_bytes[i][b * len..(b + 1) * len], "block {b} array {i}"); + } +} + +/// The CPU model sees the same distinct blocks (same miss count, consistent residency map) and the copies landed. +fn assert_resolved_like_cpu( + buffers: &MapBuffers<'_>, + slots: &[DeviceBuffer<'_>], + host_bytes: &[Vec], + runs: &[(&'static str, u64)], + inputs: (&[i32], &[i32]), +) { + let mut cpu = CpuMap::new(STREAM_BLOCKS as usize, STREAM_SLOTS as usize); + let report = cpu + .resolve( + inputs.0, + inputs.1, + STREAM_QUERIES as usize, + STREAM_CAP as usize, + 4, + &leleka_experimental_ref::kv_stream::MissOrder::Canonical, + ) + .expect("cpu resolve"); + let _ = report; + let table = download(&buffers.page_table, STREAM_BLOCKS as usize * 4); + let table: Vec = table.chunks(4).map(|b| i32::from_le_bytes(b.try_into().unwrap())).collect(); + let resident: Vec = (0..STREAM_BLOCKS as usize).filter(|b| table[*b] >= 0).collect(); + assert_eq!(resident.len(), cpu.resident_blocks(), "same set of distinct blocks resident"); + for b in resident { + assert_block_copied(slots, host_bytes, runs, (b, table[b] as usize)); + } + println!("EXPERIMENTAL kv_stream resolve+copy resident={}", cpu.resident_blocks()); +} + #[test] #[ignore = "Root schedules the first experimental GPU gate after nvcc build and pin freeze"] fn experimental_gpu_stream_resolve_copies_missed_blocks() { @@ -177,88 +334,18 @@ fn experimental_gpu_stream_resolve_copies_missed_blocks() { let ctx = driver.device(0).unwrap().create_context(512 << 20).unwrap(); { let gpu = open(&ctx, Program::KvStream, Mode::KvStreamed); - let shape = KvShape::real(); - let q = QsaShapes::real(); - let (n_blocks, n_slots, n_q, cap) = (4096u64, 1024u64, 2u64, 64u64); - let runs = stream_runs(&q, StreamFormat::F16); + let runs = stream_runs(&QsaShapes::real(), StreamFormat::F16); let mut rng = Rng(0x57a7_0004); let host_bytes: Vec> = - runs.iter().map(|(_, len)| (0..n_blocks * len).map(|_| rng.next() as u8).collect()).collect(); + runs.iter().map(|(_, len)| (0..STREAM_BLOCKS * len).map(|_| rng.next() as u8).collect()).collect(); let host: Vec> = host_bytes.iter().map(|b| upload(&ctx, b)).collect(); let mut slots: Vec> = - runs.iter().map(|(_, len)| zeroed(&ctx, (n_slots * len) as usize)).collect(); - let mut page_table = upload(&ctx, &i32_bytes(&vec![-1; n_blocks as usize])); - let mut slot_block = zeroed(&ctx, n_slots as usize * 4); - let mut slot_stamp = zeroed(&ctx, n_slots as usize * 4); - let mut slot_ref = zeroed(&ctx, n_slots as usize * 4); - let mut ctl = zeroed(&ctx, CTL_INTS * 4); - let mut miss_block = zeroed(&ctx, n_slots as usize * 4); - let mut miss_slot = zeroed(&ctx, n_slots as usize * 4); - let mut map = StreamMap { - page_table: &mut page_table, - slot_block: &mut slot_block, - slot_stamp: &mut slot_stamp, - slot_ref: &mut slot_ref, - ctl: &mut ctl, - miss_block: &mut miss_block, - miss_slot: &mut miss_slot, - }; - gpu.stream_reset(&mut map, n_blocks, n_slots).unwrap(); - // two queries, ascending cell ids; a cell is page_size = 4 per block - let width = cap as i32; - let mut ids = Vec::new(); - let mut steps = Vec::new(); - for qi in 0..n_q as i32 { - ids.extend((0..cap as i32).map(|i| i * 4 + qi * 8)); - steps.extend([cap as i32 * 4, 0, 0, width]); - } - let (ids_b, steps_b) = (upload(&ctx, &i32_bytes(&ids)), upload(&ctx, &i32_bytes(&steps))); - let host_refs: Vec<&DeviceBuffer<'_>> = host.iter().collect(); - let mut slot_refs: Vec<&mut DeviceBuffer<'_>> = slots.iter_mut().collect(); - gpu.stream_resolve( - &mut map, - StreamFormat::F16, - &shape, - n_blocks, - n_slots, - &ids_b, - &steps_b, - n_q, - cap, - &host_refs, - &mut slot_refs, - ) - .unwrap(); - // CPU model: same distinct blocks, so the same miss count and a consistent residency map - let mut cpu = CpuMap::new(n_blocks as usize, n_slots as usize); - let report = cpu - .resolve( - &ids, - &steps, - n_q as usize, - cap as usize, - 4, - &leleka_experimental_ref::kv_stream::MissOrder::Canonical, - ) - .expect("cpu resolve"); - let _ = report; - let table = download(&*map.page_table, n_blocks as usize * 4); - let table: Vec = table.chunks(4).map(|b| i32::from_le_bytes(b.try_into().unwrap())).collect(); - let resident: Vec = (0..n_blocks as usize).filter(|b| table[*b] >= 0).collect(); - assert_eq!(resident.len(), cpu.resident_blocks(), "same set of distinct blocks resident"); - for b in resident { - let slot = table[b] as usize; - for (i, (_, len)) in runs.iter().enumerate() { - let len = *len as usize; - let got = download(&slots[i], (n_slots as usize) * len); - assert_eq!( - &got[slot * len..(slot + 1) * len], - &host_bytes[i][b * len..(b + 1) * len], - "block {b} array {i}" - ); - } - } - println!("EXPERIMENTAL kv_stream resolve+copy resident={}", cpu.resident_blocks()); + runs.iter().map(|(_, len)| zeroed(&ctx, (STREAM_SLOTS * len) as usize)).collect(); + let mut buffers = MapBuffers::new(&ctx); + gpu.stream_reset(&mut buffers.map(), STREAM_BLOCKS, STREAM_SLOTS).unwrap(); + let (ids, steps) = resolve_inputs(); + resolve_on_device(&ctx, &gpu, &mut buffers, &host, &mut slots, (&ids, &steps)); + assert_resolved_like_cpu(&buffers, &slots, &host_bytes, &runs, (&ids, &steps)); gpu.close().unwrap(); } ctx.close().unwrap(); From 8d9213266068b90b82967cc3073d491d8e14d288 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 22:40:48 +0100 Subject: [PATCH 4/7] STRA-338 size2 cd1: ffi tables and the GDN row queue split into phases --- .../cuda-driver/src/ffi/enabled/impl_api.rs | 31 +-- .../cuda-driver/src/ffi/enabled/impl_api_4.rs | 139 ++++++------ .../cuda-driver/src/ffi/impl_contexthandle.rs | 52 +++-- .../gdn_closed_queue/impl_gdnqueuestage.rs | 54 +++-- .../impl_gdnrowprefix/impl_gdnrowprefix_2.rs | 92 +++++--- .../impl_gdnrowprefix_2_2.rs | 108 +++++---- .../impl_gdnrowprefix/impl_gdnrowprefix_3.rs | 113 +++++---- .../src/gdn_closed_queue/impl_gdnrowqueue.rs | 62 ++--- .../cuda-driver/src/gdn_closed_queue_gpu.rs | 161 +------------ .../src/gdn_closed_queue_gpu/scenarios.rs | 214 ++++++++++++++++++ .../cuda-driver/src/gdn_native_batch_ffi.rs | 11 +- 11 files changed, 592 insertions(+), 445 deletions(-) create mode 100644 crates/cuda-driver/src/gdn_closed_queue_gpu/scenarios.rs diff --git a/crates/cuda-driver/src/ffi/enabled/impl_api.rs b/crates/cuda-driver/src/ffi/enabled/impl_api.rs index 0e7891a8..b4a5f23a 100644 --- a/crates/cuda-driver/src/ffi/enabled/impl_api.rs +++ b/crates/cuda-driver/src/ffi/enabled/impl_api.rs @@ -4,6 +4,11 @@ use super::*; impl Api { + /// The dynamic shared-memory sizes an MMQ kernel may be raised to: a closed list. + const MMQ_SHARED_BYTES: [u32; 22] = [ + 40992, 42048, 43104, 44160, 45216, 46272, 48384, 45088, 46144, 47200, 48256, 49312, 50368, 52480, 51520, 53632, + 55616, 55744, 57728, 57856, 59840, 61952, + ]; pub(crate) fn memory_info(&self) -> Result<(usize, usize)> { // Lazy fixed resolution leaves unrelated existing/mock APIs intact. // A missing query symbol fails explicitly; it never fabricates free VRAM. @@ -65,31 +70,7 @@ impl Api { FunctionHandle::qwen_success(function as usize) } pub(crate) fn mmq_shared(&self, function: FunctionHandle, bytes: u32) -> Result<()> { - if !matches!( - bytes, - 40992 - | 42048 - | 43104 - | 44160 - | 45216 - | 46272 - | 48384 - | 45088 - | 46144 - | 47200 - | 48256 - | 49312 - | 50368 - | 52480 - | 51520 - | 53632 - | 55616 - | 55744 - | 57728 - | 57856 - | 59840 - | 61952 - ) { + if !Self::MMQ_SHARED_BYTES.contains(&bytes) { return Err(Error::InvalidProjectionShape); } let library = &self._library; diff --git a/crates/cuda-driver/src/ffi/enabled/impl_api_4.rs b/crates/cuda-driver/src/ffi/enabled/impl_api_4.rs index ded5b151..6723bfd1 100644 --- a/crates/cuda-driver/src/ffi/enabled/impl_api_4.rs +++ b/crates/cuda-driver/src/ffi/enabled/impl_api_4.rs @@ -3,6 +3,75 @@ #[allow(unused_imports)] use super::*; +/// The sealed PTX image of a fixed operation. +fn fixed_ptx(operation: FixedOperation) -> Result<&'static [u8]> { + Ok(match operation { + FixedOperation::CommonQuantize => COMMON_QUANTIZER_PTX, + FixedOperation::GroupedSwiglu => concat!(include_str!("../../moe_group_swiglu.ptx"), "\0").as_bytes(), + FixedOperation::GroupedDownIq4 => concat!(include_str!("../../moe_group_down_iq4_nl.ptx"), "\0").as_bytes(), + FixedOperation::GroupedDownQ2 => concat!(include_str!("../../moe_group_down_q2_0.ptx"), "\0").as_bytes(), + FixedOperation::GroupedIq3 => concat!(include_str!("../../moe_group_iq3_xxs.ptx"), "\0").as_bytes(), + FixedOperation::GroupedIq2 => concat!(include_str!("../../moe_group_iq2_s.ptx"), "\0").as_bytes(), + FixedOperation::GroupedIq3S => concat!(include_str!("../../moe_group_iq3_s.ptx"), "\0").as_bytes(), + FixedOperation::GroupedIq4Xs => concat!(include_str!("../../moe_group_iq4_xs.ptx"), "\0").as_bytes(), + FixedOperation::GroupedIq3SNc4 => concat!(include_str!("../../moe_group_iq3_s_nc4.ptx"), "\0").as_bytes(), + FixedOperation::GroupedIq4XsNc4 => concat!(include_str!("../../moe_group_iq4_xs_nc4.ptx"), "\0").as_bytes(), + FixedOperation::Projection(kind) => projection_ptx(kind).ok_or(Error::UnsupportedProjection)?, + FixedOperation::VectorAdd => FIXED_PTX, + FixedOperation::GrReadFinite => concat!(include_str!("../../gr_read_guard.ptx"), "\0").as_bytes(), + FixedOperation::Matvec => MATVEC_PTX, + FixedOperation::Q5K | FixedOperation::Q5KQuantize | FixedOperation::Q5KProject => Q5_K_PTX, + FixedOperation::Q6K | FixedOperation::Q6KQuantize | FixedOperation::Q6KProject => Q6_K_PTX, + }) +} + +/// The operations whose PTX is a closed asset family, checked for its encoding before the driver sees it. +fn is_projection_family(operation: FixedOperation) -> bool { + matches!( + operation, + FixedOperation::CommonQuantize + | FixedOperation::GroupedSwiglu + | FixedOperation::GroupedDownIq4 + | FixedOperation::GroupedDownQ2 + | FixedOperation::GroupedIq3 + | FixedOperation::GroupedIq2 + | FixedOperation::GroupedIq3S + | FixedOperation::GroupedIq4Xs + | FixedOperation::GroupedIq3SNc4 + | FixedOperation::GroupedIq4XsNc4 + | FixedOperation::Projection(_) + | FixedOperation::Q6K + | FixedOperation::Q6KQuantize + | FixedOperation::Q6KProject + ) +} + +/// The fixed C entry name of an operation; the Q5_K / Q6_K family selectors name no entry of their own. +fn fixed_entry(operation: FixedOperation) -> Result<&'static std::ffi::CStr> { + Ok(match operation { + FixedOperation::CommonQuantize => c"leleka_quantize_q8_1", + FixedOperation::GroupedSwiglu => c"leleka_moe_swiglu_f32_columns", + FixedOperation::GroupedDownIq4 => c"leleka_iq4_nl_q8_1_routed_columns", + FixedOperation::GroupedDownQ2 => c"leleka_q2_0_q8_1_routed_columns", + FixedOperation::GroupedIq3 => c"leleka_iq3_xxs_q8_1_routed_columns", + FixedOperation::GroupedIq2 => c"leleka_iq2_s_q8_1_routed_columns", + FixedOperation::GroupedIq3S => c"leleka_iq3_s_q8_1_routed_columns", + FixedOperation::GroupedIq4Xs => c"leleka_iq4_xs_q8_1_routed_columns", + FixedOperation::GroupedIq3SNc4 => c"leleka_iq3_s_q8_1_routed_columns_nc4", + FixedOperation::GroupedIq4XsNc4 => c"leleka_iq4_xs_q8_1_routed_columns_nc4", + FixedOperation::Projection(kind) => projection_entry(kind), + FixedOperation::VectorAdd => c"leleka_vector_add_f32", + FixedOperation::GrReadFinite => c"leleka_gr_read_finite", + FixedOperation::Matvec => c"leleka_matvec_f32", + FixedOperation::Q5K => return Err(Error::InvalidDriverValue("fixed Q5_K entry selector")), + FixedOperation::Q5KQuantize => c"leleka_quantize_q8_1", + FixedOperation::Q5KProject => c"leleka_q5_k_q8_1", + FixedOperation::Q6K => return Err(Error::InvalidDriverValue("fixed Q6_K entry selector")), + FixedOperation::Q6KQuantize => c"leleka_quantize_q8_1", + FixedOperation::Q6KProject => c"leleka_q6_k_q8_1", + }) +} + impl Api { pub(crate) fn launch_qwen( &self, @@ -129,41 +198,8 @@ impl Api { }) } pub(crate) fn load_fixed_module(&self, operation: FixedOperation) -> Result { - let bytes = match operation { - FixedOperation::CommonQuantize => COMMON_QUANTIZER_PTX, - FixedOperation::GroupedSwiglu => concat!(include_str!("../../moe_group_swiglu.ptx"), "\0").as_bytes(), - FixedOperation::GroupedDownIq4 => concat!(include_str!("../../moe_group_down_iq4_nl.ptx"), "\0").as_bytes(), - FixedOperation::GroupedDownQ2 => concat!(include_str!("../../moe_group_down_q2_0.ptx"), "\0").as_bytes(), - FixedOperation::GroupedIq3 => concat!(include_str!("../../moe_group_iq3_xxs.ptx"), "\0").as_bytes(), - FixedOperation::GroupedIq2 => concat!(include_str!("../../moe_group_iq2_s.ptx"), "\0").as_bytes(), - FixedOperation::GroupedIq3S => concat!(include_str!("../../moe_group_iq3_s.ptx"), "\0").as_bytes(), - FixedOperation::GroupedIq4Xs => concat!(include_str!("../../moe_group_iq4_xs.ptx"), "\0").as_bytes(), - FixedOperation::GroupedIq3SNc4 => concat!(include_str!("../../moe_group_iq3_s_nc4.ptx"), "\0").as_bytes(), - FixedOperation::GroupedIq4XsNc4 => concat!(include_str!("../../moe_group_iq4_xs_nc4.ptx"), "\0").as_bytes(), - FixedOperation::Projection(kind) => projection_ptx(kind).ok_or(Error::UnsupportedProjection)?, - FixedOperation::VectorAdd => FIXED_PTX, - FixedOperation::GrReadFinite => concat!(include_str!("../../gr_read_guard.ptx"), "\0").as_bytes(), - FixedOperation::Matvec => MATVEC_PTX, - FixedOperation::Q5K | FixedOperation::Q5KQuantize | FixedOperation::Q5KProject => Q5_K_PTX, - FixedOperation::Q6K | FixedOperation::Q6KQuantize | FixedOperation::Q6KProject => Q6_K_PTX, - }; - if matches!( - operation, - FixedOperation::CommonQuantize - | FixedOperation::GroupedSwiglu - | FixedOperation::GroupedDownIq4 - | FixedOperation::GroupedDownQ2 - | FixedOperation::GroupedIq3 - | FixedOperation::GroupedIq2 - | FixedOperation::GroupedIq3S - | FixedOperation::GroupedIq4Xs - | FixedOperation::GroupedIq3SNc4 - | FixedOperation::GroupedIq4XsNc4 - | FixedOperation::Projection(_) - | FixedOperation::Q6K - | FixedOperation::Q6KQuantize - | FixedOperation::Q6KProject - ) { + let bytes = fixed_ptx(operation)?; + if is_projection_family(operation) { validate_projection_ptx(bytes)?; } let mut module = std::ptr::null_mut(); @@ -179,40 +215,11 @@ impl Api { } pub(crate) fn fixed_function(&self, module: ModuleHandle, operation: FixedOperation) -> Result { let mut function = std::ptr::null_mut(); + let entry = fixed_entry(operation)?; // SAFETY: live private module in current owner context; fixed C // entry name; valid writable opaque function output. check("cuModuleGetFunction", unsafe { - (self.get_function)( - &mut function, - module.0 as *mut c_void, - match operation { - FixedOperation::CommonQuantize => c"leleka_quantize_q8_1", - FixedOperation::GroupedSwiglu => c"leleka_moe_swiglu_f32_columns", - FixedOperation::GroupedDownIq4 => c"leleka_iq4_nl_q8_1_routed_columns", - FixedOperation::GroupedDownQ2 => c"leleka_q2_0_q8_1_routed_columns", - FixedOperation::GroupedIq3 => c"leleka_iq3_xxs_q8_1_routed_columns", - FixedOperation::GroupedIq2 => c"leleka_iq2_s_q8_1_routed_columns", - FixedOperation::GroupedIq3S => c"leleka_iq3_s_q8_1_routed_columns", - FixedOperation::GroupedIq4Xs => c"leleka_iq4_xs_q8_1_routed_columns", - FixedOperation::GroupedIq3SNc4 => c"leleka_iq3_s_q8_1_routed_columns_nc4", - FixedOperation::GroupedIq4XsNc4 => c"leleka_iq4_xs_q8_1_routed_columns_nc4", - FixedOperation::Projection(kind) => projection_entry(kind), - FixedOperation::VectorAdd => c"leleka_vector_add_f32", - FixedOperation::GrReadFinite => c"leleka_gr_read_finite", - FixedOperation::Matvec => c"leleka_matvec_f32", - FixedOperation::Q5K => { - return Err(Error::InvalidDriverValue("fixed Q5_K entry selector")); - } - FixedOperation::Q5KQuantize => c"leleka_quantize_q8_1", - FixedOperation::Q5KProject => c"leleka_q5_k_q8_1", - FixedOperation::Q6K => { - return Err(Error::InvalidDriverValue("fixed Q6_K entry selector")); - } - FixedOperation::Q6KQuantize => c"leleka_quantize_q8_1", - FixedOperation::Q6KProject => c"leleka_q6_k_q8_1", - } - .as_ptr(), - ) + (self.get_function)(&mut function, module.0 as *mut c_void, entry.as_ptr()) })?; if function.is_null() { return Err(Error::InvalidDriverValue("cuModuleGetFunction")); diff --git a/crates/cuda-driver/src/ffi/impl_contexthandle.rs b/crates/cuda-driver/src/ffi/impl_contexthandle.rs index f4797a91..3a1e6832 100644 --- a/crates/cuda-driver/src/ffi/impl_contexthandle.rs +++ b/crates/cuda-driver/src/ffi/impl_contexthandle.rs @@ -97,43 +97,51 @@ impl BufferHandle { // placeholder PTX or success stand-in is embedded for an unavailable format. pub(super) fn projection_ptx(kind: ProjectionKind) -> Option<&'static [u8]> { match kind { + ProjectionKind::Dense(format) => Some(dense_ptx(format)), + ProjectionKind::Routed(format) => Some(routed_ptx(format)), + } +} +fn dense_ptx(format: DenseFormat) -> &'static [u8] { + match format { // Root-delivered STRA-146 frozen artifact341abbd0; independent // installed-Driver proof precedes this bounded public composition. - ProjectionKind::Dense(DenseFormat::Q8_0) => Some(concat!(include_str!("../q8_0_q8_1.ptx"), "\0").as_bytes()), + DenseFormat::Q8_0 => concat!(include_str!("../q8_0_q8_1.ptx"), "\0").as_bytes(), // Source-qualified STRA-154 Q4_K dense artifact; its independent // qualification receipt is 017f1d90. Keep the original dense entry. - ProjectionKind::Dense(DenseFormat::Q4_K) => Some(concat!(include_str!("../q4_k_q8_1.ptx"), "\0").as_bytes()), + DenseFormat::Q4_K => concat!(include_str!("../q4_k_q8_1.ptx"), "\0").as_bytes(), + DenseFormat::IQ4_NL => iq4_nl_ptx(), + DenseFormat::IQ4_XS => iq4_xs_ptx(), + } +} +fn routed_ptx(format: RoutedFormat) -> &'static [u8] { + match format { // Root-delivered STRA-148 frozen routed artifact f9c10814; its // standalone installed-Driver proof is distinct from composition. - ProjectionKind::Routed(RoutedFormat::IQ3_XXS) => { - Some(concat!(include_str!("../iq3_xxs_q8_1.ptx"), "\0").as_bytes()) - } + RoutedFormat::IQ3_XXS => concat!(include_str!("../iq3_xxs_q8_1.ptx"), "\0").as_bytes(), // Root-delivered STRA-149 frozen routed artifact // 94f798c00813c2fb860b4bf77be9225767d408955e3421330ac34a4ebd43978f. - ProjectionKind::Routed(RoutedFormat::IQ3_S) => { - Some(concat!(include_str!("../iq3_s_q8_1.ptx"), "\0").as_bytes()) - } + RoutedFormat::IQ3_S => concat!(include_str!("../iq3_s_q8_1.ptx"), "\0").as_bytes(), // Root-delivered STRA-150 frozen routed artifact a31e653d. - ProjectionKind::Routed(RoutedFormat::IQ2_S) => { - Some(concat!(include_str!("../iq2_s_q8_1.ptx"), "\0").as_bytes()) - } - // Root-delivered STRA-151 frozen paired IQ4_NL artifact 189b02ce. - // One module contains the separately named dense and routed entries. - ProjectionKind::Dense(DenseFormat::IQ4_NL) | ProjectionKind::Routed(RoutedFormat::IQ4_NL) => { - Some(concat!(include_str!("../iq4_nl_q8_1.ptx"), "\0").as_bytes()) - } - // Root-delivered STRA-152 frozen paired IQ4_XS artifact 2c853bad. - // Its dense and routed entries share one isolated cache module. - ProjectionKind::Dense(DenseFormat::IQ4_XS) | ProjectionKind::Routed(RoutedFormat::IQ4_XS) => { - Some(concat!(include_str!("../iq4_xs_q8_1.ptx"), "\0").as_bytes()) - } + RoutedFormat::IQ2_S => concat!(include_str!("../iq2_s_q8_1.ptx"), "\0").as_bytes(), + RoutedFormat::IQ4_NL => iq4_nl_ptx(), + RoutedFormat::IQ4_XS => iq4_xs_ptx(), // STRA-153 qualified the routed Q2_0 artifact independently (exact // producer source SHA-256: 8e81dbbaa76d8516476339c168f1d9c172341a78ccecda08714a13a5687e3b6e). // This fixed arm only composes that frozen asset; public GPU parity is // still a separate STRA-154 acceptance gate. - ProjectionKind::Routed(RoutedFormat::Q2_0) => Some(concat!(include_str!("../q2_0_q8_1.ptx"), "\0").as_bytes()), + RoutedFormat::Q2_0 => concat!(include_str!("../q2_0_q8_1.ptx"), "\0").as_bytes(), } } +// Root-delivered STRA-151 frozen paired IQ4_NL artifact 189b02ce. +// One module contains the separately named dense and routed entries. +fn iq4_nl_ptx() -> &'static [u8] { + concat!(include_str!("../iq4_nl_q8_1.ptx"), "\0").as_bytes() +} +// Root-delivered STRA-152 frozen paired IQ4_XS artifact 2c853bad. +// Its dense and routed entries share one isolated cache module. +fn iq4_xs_ptx() -> &'static [u8] { + concat!(include_str!("../iq4_xs_q8_1.ptx"), "\0").as_bytes() +} #[cfg(any( test, all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64") diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnqueuestage.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnqueuestage.rs index ece0f612..42c14ce0 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnqueuestage.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnqueuestage.rs @@ -97,35 +97,41 @@ impl<'ctx> GdnRowQueue<'ctx> { return Err(Error::BudgetExceeded); } let mut owner = Self { context, status: None, module: None, kernels: None, failed: false }; - let result = (|| { - owner.status = Some(context.allocate(STATUS_BYTES)?); - let guard = context.enter()?; - let load = (|| { - let mut qwen = [None; 6]; - for (i, operation) in OPS.into_iter().enumerate() { - let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; - qwen[i] = Some(registered(context, &context.qwen_kernels, asset)?.function); - } - let module = context.driver.api.load_mmq_resident()?; - owner.module = Some(module); - Ok(Kernels { - qwen: qwen.map(|function| function.expect("every GDN kernel resolved")), - zero: context.driver.api.mmq_resident_function(module, 0)?, - finite: context.driver.api.mmq_resident_function(module, 1)?, - }) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poisoned.set(true); - } - owner.kernels = Some(combine(load, pop)?); - Ok(()) - })(); + let result = owner.open(); if let Err(error) = result { return combine(Err(error), owner.close_inner()); } Ok(owner) } + /// Allocates the status buffer and loads the kernels under the context; the restore failing poisons it. + fn open(&mut self) -> Result<()> { + let context = self.context; + self.status = Some(context.allocate(STATUS_BYTES)?); + let guard = context.enter()?; + let load = self.load_kernels(); + let pop = guard.finish(); + if pop.is_err() { + context.poisoned.set(true); + } + self.kernels = Some(combine(load, pop)?); + Ok(()) + } + /// Resolves the six GDN kernels and the finite-scan helper module (kept in `self.module`). + fn load_kernels(&mut self) -> Result { + let context = self.context; + let mut qwen = [None; 6]; + for (i, operation) in OPS.into_iter().enumerate() { + let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; + qwen[i] = Some(registered(context, &context.qwen_kernels, asset)?.function); + } + let module = context.driver.api.load_mmq_resident()?; + self.module = Some(module); + Ok(Kernels { + qwen: qwen.map(|function| function.expect("every GDN kernel resolved")), + zero: context.driver.api.mmq_resident_function(module, 0)?, + finite: context.driver.api.mmq_resident_function(module, 1)?, + }) + } pub(super) fn status_handle(&self) -> Result { if self.is_failed() || self.kernels.is_none() || self.module.is_none() { return Err(Error::ContextPoisoned); diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2.rs index 4864a16f..f1905175 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2.rs @@ -192,45 +192,65 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { raw: &'lease DeviceBuffer<'lease>, h: &'lease DeviceBuffer<'lease>, ) -> Result<()> { + let bufs = [history, columns, weights, next_history, raw, h]; let result = (|| { self.ready(Step::Conv)?; - let (whole, scanned_row, range) = self.columns.ok_or(Error::InvalidQwenShape)?; - if scanned_row != row || columns.handle != Some(whole) { - return Err(Error::InvalidQwenShape); - } - let original = Operation::GdnConv.layout(); - let mut layout = original; - layout.bytes[1] = columns.bytes; - let queue = &*self.queue; - let (_, _, owners) = admission( - queue.context, - &[history, columns, weights, next_history, raw, h], - Admission { - operation: Operation::GdnConv, - layout: Ok(layout), - asset: qwen_ffi::asset(Operation::GdnConv), - epsilon: 0.0, - in_place: false, - }, - )?; - let mut handles = owners; - handles[1] = range; - ranges_layout(Operation::GdnConv, original, handles, original.bytes, false)?; - let function = queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[CONV]; - self.commands.push(Command::Qwen( - function, - Operation::GdnConv, - Box::new(Arguments::with_layout(Operation::GdnConv, original, handles, 0.0)), - )); - self.held.extend_from_slice(&[history, columns, weights, next_history, raw, h]); - self.push_scan(GdnQueueStage::ConvRaw, raw)?; - self.push_scan(GdnQueueStage::NextHistory, next_history)?; - self.push_scan(GdnQueueStage::ConvH, h)?; - self.next_history = next_history.handle; - self.h = h.handle; - self.step = self.step.next(); - Ok(()) + let range = self.conv_range(columns, row)?; + let handles = self.admit_conv(&bufs, range)?; + self.push_conv(bufs, handles) })(); self.latch(result) } + /// The retained QKV row's range, once `columns` is the very scanned allocation and `row` its scanned row. + fn conv_range(&self, columns: &DeviceBuffer<'_>, row: usize) -> Result { + let (whole, scanned_row, range) = self.columns.ok_or(Error::InvalidQwenShape)?; + if scanned_row != row || columns.handle != Some(whole) { + return Err(Error::InvalidQwenShape); + } + Ok(range) + } + /// Admits the whole batched owner; only the fixed row range replaces its handle. + fn admit_conv( + &self, + bufs: &[&'lease DeviceBuffer<'lease>; 6], + range: ffi::BufferHandle, + ) -> Result<[ffi::BufferHandle; 9]> { + let original = Operation::GdnConv.layout(); + let mut layout = original; + layout.bytes[1] = bufs[1].bytes; + let queue = &*self.queue; + let (_, _, owners) = admission( + queue.context, + bufs, + Admission { + operation: Operation::GdnConv, + layout: Ok(layout), + asset: qwen_ffi::asset(Operation::GdnConv), + epsilon: 0.0, + in_place: false, + }, + )?; + let mut handles = owners; + handles[1] = range; + ranges_layout(Operation::GdnConv, original, handles, original.bytes, false)?; + Ok(handles) + } + fn push_conv(&mut self, bufs: [&'lease DeviceBuffer<'lease>; 6], handles: [ffi::BufferHandle; 9]) -> Result<()> { + let original = Operation::GdnConv.layout(); + let [_, _, _, next_history, raw, h] = bufs; + let function = self.queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[CONV]; + self.commands.push(Command::Qwen( + function, + Operation::GdnConv, + Box::new(Arguments::with_layout(Operation::GdnConv, original, handles, 0.0)), + )); + self.held.extend_from_slice(&bufs); + self.push_scan(GdnQueueStage::ConvRaw, raw)?; + self.push_scan(GdnQueueStage::NextHistory, next_history)?; + self.push_scan(GdnQueueStage::ConvH, h)?; + self.next_history = next_history.handle; + self.h = h.handle; + self.step = self.step.next(); + Ok(()) + } } diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs index d9187df5..1a2422c6 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs @@ -72,59 +72,79 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { next_state: &'lease DeviceBuffer<'lease>, readout: &'lease DeviceBuffer<'lease>, ) -> Result<()> { + let bufs = [state, qk, h, gate, beta, next_state, readout]; let result = (|| { self.ready(Step::Recurrence)?; self.same(self.qk, qk)?; self.same(self.h, h)?; self.same(self.gate, gate)?; self.same(self.sigmoid, beta)?; - let original = Operation::GdnStep.layout(); - // Admit the WHOLE real allocations, including aliases outside the - // consumed ranges, before deriving any private pointer operands. - let mut whole = original; - whole.bytes = [STATE_BYTES, QK_BYTES, QK_BYTES, 192, 192, STATE_BYTES, 24_576, 0, 0]; - whole.align = [4; 9]; - whole.count = 7; - whole.outputs = 0b110_0000; - let queue = &*self.queue; - let (_, _, owners) = admission( - queue.context, - &[state, qk, h, gate, beta, next_state, readout], - Admission { - operation: Operation::GdnStep, - layout: Ok(whole), - asset: qwen_ffi::asset(Operation::GdnStep), - epsilon: 0.0, - in_place: false, - }, - )?; - let status = queue.status_handle()?; - for owner in &owners[..7] { - if owner.overlaps(1, status, STATUS_BYTES) { - return Err(Error::OutputAliasesInput); - } - } - let q = owners[1].checked_subspan(QK_BYTES, 0, 8192)?; - let k = owners[1].checked_subspan(QK_BYTES, 8192, 8192)?; - let v = owners[2].checked_subspan(QK_BYTES, 16_384, 24_576)?; - let handles = [owners[0], q, k, v, owners[3], owners[4], owners[5], owners[6], owners[0]]; - ranges_layout(Operation::GdnStep, original, handles, original.bytes, false)?; - let function = queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[STEP]; - self.commands.push(Command::Qwen( - function, - Operation::GdnStep, - Box::new(Arguments::with_layout(Operation::GdnStep, original, handles, 0.0)), - )); - self.held.extend_from_slice(&[state, qk, h, gate, beta, next_state, readout]); - // Earliest full-state refusal precedes the readout, as before. - self.push_scan(GdnQueueStage::NextState, next_state)?; - self.push_scan(GdnQueueStage::Readout, readout)?; - self.readout = readout.handle; - self.step = self.step.next(); - Ok(()) + let owners = self.admit_whole_step(&bufs)?; + let handles = self.step_handles(owners)?; + self.push_recurrence(bufs, handles) })(); self.latch(result) } + /// Admits the WHOLE real allocations, including aliases outside the consumed ranges, before any private + /// pointer operand is derived. + fn admit_whole_step(&self, bufs: &[&'lease DeviceBuffer<'lease>; 7]) -> Result<[ffi::BufferHandle; 9]> { + let original = Operation::GdnStep.layout(); + let mut whole = original; + whole.bytes = [STATE_BYTES, QK_BYTES, QK_BYTES, 192, 192, STATE_BYTES, 24_576, 0, 0]; + whole.align = [4; 9]; + whole.count = 7; + whole.outputs = 0b110_0000; + let queue = &*self.queue; + let (_, _, owners) = admission( + queue.context, + bufs, + Admission { + operation: Operation::GdnStep, + layout: Ok(whole), + asset: qwen_ffi::asset(Operation::GdnStep), + epsilon: 0.0, + in_place: false, + }, + )?; + Ok(owners) + } + /// The consumed Q/K/V ranges of the admitted owners, none of which may overlap the status words. + fn step_handles(&self, owners: [ffi::BufferHandle; 9]) -> Result<[ffi::BufferHandle; 9]> { + let original = Operation::GdnStep.layout(); + let status = self.queue.status_handle()?; + for owner in &owners[..7] { + if owner.overlaps(1, status, STATUS_BYTES) { + return Err(Error::OutputAliasesInput); + } + } + let q = owners[1].checked_subspan(QK_BYTES, 0, 8192)?; + let k = owners[1].checked_subspan(QK_BYTES, 8192, 8192)?; + let v = owners[2].checked_subspan(QK_BYTES, 16_384, 24_576)?; + let handles = [owners[0], q, k, v, owners[3], owners[4], owners[5], owners[6], owners[0]]; + ranges_layout(Operation::GdnStep, original, handles, original.bytes, false)?; + Ok(handles) + } + fn push_recurrence( + &mut self, + bufs: [&'lease DeviceBuffer<'lease>; 7], + handles: [ffi::BufferHandle; 9], + ) -> Result<()> { + let original = Operation::GdnStep.layout(); + let [_, _, _, _, _, next_state, readout] = bufs; + let function = self.queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[STEP]; + self.commands.push(Command::Qwen( + function, + Operation::GdnStep, + Box::new(Arguments::with_layout(Operation::GdnStep, original, handles, 0.0)), + )); + self.held.extend_from_slice(&bufs); + // Earliest full-state refusal precedes the readout, as before. + self.push_scan(GdnQueueStage::NextState, next_state)?; + self.push_scan(GdnQueueStage::Readout, readout)?; + self.readout = readout.handle; + self.step = self.step.next(); + Ok(()) + } /// Device-only projection output of the Z role (6,144 words). pub fn scan_z(&mut self, z: &'lease DeviceBuffer<'lease>) -> Result<()> { let result = (|| { diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_3.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_3.rs index 967ef24d..5822f76f 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_3.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_3.rs @@ -10,40 +10,14 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { let write_fetch = fetch && self.refusal.is_none(); let mut fetched = staging(if write_fetch { HISTORY_BYTES } else { 0 })?; if !self.commands.is_empty() { - let zero = self.queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.zero; - let mut reset = ffi::MmqResidentArguments::zero(status, SLOTS as u32); - let context = self.queue.context; - let guard = context.enter().inspect_err(|_| { - self.queue.failed = true; - context.poisoned.set(true); - })?; - let mut operation = context.driver.api.launch_mmq_resident(zero, SLOTS as u32, &mut reset); - for command in &mut self.commands { - if operation.is_err() { - break; - } - operation = command.launch(context); - } - if operation.is_ok() { - operation = context.driver.api.copy_to(status, &mut statuses); - } - if operation.is_ok() && write_fetch { - let source = self.fetch.ok_or(Error::InvalidQwenShape)?; - operation = context.driver.api.copy_to(source, &mut fetched); - } - let sync = context.driver.api.synchronize(); - let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { - self.queue.failed = true; - context.poisoned.set(true); - } - if sync.is_err() || pop.is_err() { + let fenced = self.fenced(status, &mut statuses, &mut fetched, write_fetch)?; + if fenced.uncertain { // Completion is uncertain: retain every actual argument/staging // owner and every borrowed buffer; Context poison forbids reuse. - std::mem::forget((reset, self.commands, self.held, statuses, fetched)); - return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain GDN row drain")); + std::mem::forget((fenced.reset, self.commands, self.held, statuses, fetched)); + return fenced.outcome.map(|()| unreachable!("uncertain GDN row drain")); } - combine(combine(operation, sync), pop)?; + fenced.outcome?; } let (_, refusal) = match decode_statuses(&statuses, self.checks) { Ok(decoded) => decoded, @@ -53,14 +27,75 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { return Err(error); } }; - let next_history = if write_fetch && refusal.is_none() { - let mut values = Vec::new(); - values.try_reserve_exact(HISTORY_BYTES / 4).map_err(|_| Error::HostAllocation)?; - values.extend(fetched.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))); - Some(values.into_boxed_slice()) - } else { - None - }; + let next_history = if write_fetch && refusal.is_none() { Some(history_words(&fetched)?) } else { None }; Ok(Drained { refusal, deferred: self.refusal, next_history }) } + /// Resets the status words, launches every command, reads the words (and the history) back and + /// synchronizes, all inside one context entry. + fn fenced( + &mut self, + status: ffi::BufferHandle, + statuses: &mut [u8], + fetched: &mut [u8], + write_fetch: bool, + ) -> Result { + let zero = self.queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.zero; + let mut reset = ffi::MmqResidentArguments::zero(status, SLOTS as u32); + let context = self.queue.context; + let guard = context.enter().inspect_err(|_| { + self.queue.failed = true; + context.poisoned.set(true); + })?; + let api = &context.driver.api; + let operation = api.launch_mmq_resident(zero, SLOTS as u32, &mut reset); + let mut operation = self.launch_commands(operation); + if operation.is_ok() { + operation = api.copy_to(status, statuses); + } + if operation.is_ok() && write_fetch { + let source = self.fetch.ok_or(Error::InvalidQwenShape)?; + operation = api.copy_to(source, fetched); + } + let sync = api.synchronize(); + let pop = guard.finish(); + Ok(self.settle(reset, [operation, sync, pop])) + } + /// Launches the commands in order until one fails; `operation` is the outcome so far. + fn launch_commands(&mut self, mut operation: Result<()>) -> Result<()> { + let context = self.queue.context; + for command in &mut self.commands { + if operation.is_err() { + break; + } + operation = command.launch(context); + } + operation + } + /// Latches the queue and poisons the context on any failure; a failed fence or pop leaves completion uncertain. + fn settle(&mut self, reset: ffi::MmqResidentArguments, [operation, sync, pop]: [Result<()>; 3]) -> Fenced { + let failed = operation.is_err() || sync.is_err() || pop.is_err(); + let uncertain = sync.is_err() || pop.is_err(); + let outcome = combine(combine(operation, sync), pop); + if failed { + self.queue.failed = true; + self.queue.context.poisoned.set(true); + } + Fenced { reset, outcome, uncertain } + } +} + +/// The result of one fenced drain: the reset arguments (to be retained when uncertain), the combined outcome +/// and whether completion is uncertain. +struct Fenced { + reset: ffi::MmqResidentArguments, + outcome: Result<()>, + uncertain: bool, +} + +/// The canonical next history as words, in the order fetched. +fn history_words(fetched: &[u8]) -> Result> { + let mut values = Vec::new(); + values.try_reserve_exact(HISTORY_BYTES / 4).map_err(|_| Error::HostAllocation)?; + values.extend(fetched.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))); + Ok(values.into_boxed_slice()) } diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowqueue.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowqueue.rs index aae1d781..444f9fde 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowqueue.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowqueue.rs @@ -9,39 +9,45 @@ impl GdnRowQueue<'_> { self.kernels = None; let mut result = Ok(()); if let Some(buffer) = self.status.take() { - let release = if self.context.is_poisoned() { - std::mem::forget(buffer); - Err(Error::ContextPoisoned) - } else { - buffer.release() - }; - if release.is_err() { - self.context.poisoned.set(true); - } - result = combine(result, release); + result = combine(result, self.release_status(buffer)); } if let Some(module) = self.module.take() { - let release = if self.context.is_poisoned() { - self.context.retain_driver(); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(guard) => { - let unload = self.context.driver.api.unload(module); - let pop = guard.finish(); - combine(unload, pop) - } - Err(error) => Err(error), - } - }; - if release.is_err() { - self.context.poisoned.set(true); - self.context.retain_driver(); - } - result = combine(result, release); + result = combine(result, self.release_module(module)); } result } + fn release_status(&self, buffer: DeviceBuffer<'_>) -> Result<()> { + let release = if self.context.is_poisoned() { + std::mem::forget(buffer); + Err(Error::ContextPoisoned) + } else { + buffer.release() + }; + if release.is_err() { + self.context.poisoned.set(true); + } + release + } + fn release_module(&self, module: ffi::ModuleHandle) -> Result<()> { + let release = if self.context.is_poisoned() { + self.context.retain_driver(); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(guard) => { + let unload = self.context.driver.api.unload(module); + let pop = guard.finish(); + combine(unload, pop) + } + Err(error) => Err(error), + } + }; + if release.is_err() { + self.context.poisoned.set(true); + self.context.retain_driver(); + } + release + } } impl Drop for GdnRowQueue<'_> { fn drop(&mut self) { diff --git a/crates/cuda-driver/src/gdn_closed_queue_gpu.rs b/crates/cuda-driver/src/gdn_closed_queue_gpu.rs index 748ae42f..2028ae59 100644 --- a/crates/cuda-driver/src/gdn_closed_queue_gpu.rs +++ b/crates/cuda-driver/src/gdn_closed_queue_gpu.rs @@ -59,164 +59,7 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() { let context = device.create_context(256 * 1024 * 1024).unwrap(); let foreign = device.create_context(64 * 1024 * 1024).unwrap(); let mut report = Report::default(); - let result = (|| -> Result<()> { - let mut queue = context.gdn_row_queue()?; - if queue.allocated_bytes() != STATUS_BYTES { - return Err(Error::InvalidDriverValue("unexpected queue charge")); - } - // Three clean rows on one queue: statuses are reset on every drain. - for salt in [0, 1, 2] { - clean_pair(&context, &mut queue, salt, &mut report)?; - } - // Earliest refusal in program order, then the queue stays usable. - let cases = [ - (Poison { alpha: true, ..Poison::default() }, GdnQueueStage::Alpha), - (Poison { conv_weights: true, ..Poison::default() }, GdnQueueStage::ConvRaw), - (Poison { state: true, ..Poison::default() }, GdnQueueStage::NextState), - (Poison { z: true, ..Poison::default() }, GdnQueueStage::Z), - (Poison { alpha: true, z: true, ..Poison::default() }, GdnQueueStage::Alpha), - ]; - for (poison, stage) in cases { - refusal_case(&context, &mut queue, poison, stage, &mut report)?; - clean_pair(&context, &mut queue, 3, &mut report)?; - } - // Retained batched QKV rows: first, middle and last of a 3-row and a - // 64-row batch; a poisoned OTHER row is irrelevant, the USED row refuses. - for (tokens, used) in [(3usize, 0usize), (3, 1), (3, 2), (64, 63)] { - columns_pair(&context, &mut queue, 8, tokens, used, false, false, &mut report)?; - columns_pair(&context, &mut queue, 8, tokens, used, false, true, &mut report)?; - columns_pair(&context, &mut queue, 8, tokens, used, true, false, &mut report)?; - clean_pair(&context, &mut queue, 3, &mut report)?; - } - // Program order, data flow, aliasing, context and shape admission. - let row = Row::new(&context, 7, Poison::default())?; - let other = Row::new(&foreign, 7, Poison::default())?; - let admission = (|| -> Result<()> { - // Convolution before the two input scans. - let mut prefix = queue.begin()?; - refuse( - prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h), - Error::InvalidQwenShape, - &mut report, - )?; - refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; - // Q/K over a buffer that is not the convolution H output. - let mut prefix = queue.begin()?; - prefix.scan_alpha(&row.alpha)?; - prefix.scan_beta_raw(&row.beta_raw)?; - prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?; - refuse(prefix.qk_l2(&row.raw, &row.qk, EPSILON), Error::InvalidQwenShape, &mut report)?; - // A latched admission error still drains the admitted prefix first. - refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; - // Recurrence whose current state and next state are one owner. - let mut prefix = queue.begin()?; - prefix.scan_alpha(&row.alpha)?; - prefix.scan_beta_raw(&row.beta_raw)?; - prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?; - prefix.qk_l2(&row.h, &row.qk, EPSILON)?; - prefix.beta_sigmoid(&row.beta_raw, &row.sigmoid)?; - prefix.gate_softplus(&row.alpha, &row.dt, &row.a, &row.gate)?; - refuse( - prefix.recurrence(&row.state, &row.qk, &row.h, &row.gate, &row.sigmoid, &row.state, &row.readout), - Error::OutputAliasesInput, - &mut report, - )?; - refuse(prefix.finish(), Error::OutputAliasesInput, &mut report)?; - // A buffer from another Context. - let mut prefix = queue.begin()?; - refuse(prefix.scan_alpha(&other.alpha), Error::ContextMismatch, &mut report)?; - refuse(prefix.finish(), Error::ContextMismatch, &mut report)?; - // A whole buffer of the wrong size. - let short = blank(&context, 47)?; - let mut prefix = queue.begin()?; - let result = prefix.scan_alpha(&short); - refuse(result, Error::InvalidQwenShape, &mut report)?; - refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; - short.release()?; - // History fetch of a buffer that is not the convolution output, - // a second fetch, and a finish before the program is complete. - let mut prefix = queue.begin()?; - prefix.scan_alpha(&row.alpha)?; - prefix.scan_beta_raw(&row.beta_raw)?; - prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?; - refuse(prefix.fetch_next_history(&row.history), Error::InvalidQwenShape, &mut report)?; - refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; - let mut prefix = queue.begin()?; - prefix.scan_alpha(&row.alpha)?; - let incomplete = prefix.finish(); - refuse(incomplete, Error::InvalidQwenShape, &mut report)?; - // Retained-row admission: not a whole number of rows, a row beyond - // the batch, the host convolution after a column scan, a different - // row index or owner at the convolution, and a late column scan. - let ragged = blank(&context, CHANNELS + 1)?; - let image = upload(&context, &column_image(1, 3, 1))?; - let admission = (|| -> Result<()> { - let mut prefix = queue.begin()?; - refuse(prefix.scan_qkv_columns(&ragged, 0), Error::InvalidQwenShape, &mut report)?; - refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; - let mut prefix = queue.begin()?; - refuse(prefix.scan_qkv_columns(&image, 3), Error::InvalidQwenShape, &mut report)?; - refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; - let mut prefix = queue.begin()?; - prefix.scan_qkv_columns(&image, 1)?; - prefix.scan_alpha(&row.alpha)?; - prefix.scan_beta_raw(&row.beta_raw)?; - refuse( - prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h), - Error::InvalidQwenShape, - &mut report, - )?; - refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; - let mut prefix = queue.begin()?; - prefix.scan_qkv_columns(&image, 1)?; - prefix.scan_alpha(&row.alpha)?; - prefix.scan_beta_raw(&row.beta_raw)?; - refuse( - prefix.conv_silu_columns( - &row.history, - &image, - 2, - &row.weights, - &row.next_history, - &row.raw, - &row.h, - ), - Error::InvalidQwenShape, - &mut report, - )?; - refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; - let mut prefix = queue.begin()?; - prefix.scan_alpha(&row.alpha)?; - refuse(prefix.scan_qkv_columns(&image, 1), Error::InvalidQwenShape, &mut report)?; - refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; - // The retained-row conv over another owner than the scanned one. - let mut prefix = queue.begin()?; - prefix.scan_qkv_columns(&image, 1)?; - prefix.scan_alpha(&row.alpha)?; - prefix.scan_beta_raw(&row.beta_raw)?; - refuse( - prefix.conv_silu_columns( - &row.history, - &ragged, - 1, - &row.weights, - &row.next_history, - &row.raw, - &row.h, - ), - Error::InvalidQwenShape, - &mut report, - )?; - refuse(prefix.finish(), Error::InvalidQwenShape, &mut report) - })(); - combine(combine(admission, ragged.release()), image.release()) - })(); - let cleanup = combine(row.release(), other.release()); - combine(admission, cleanup)?; - // The queue survives every refusal above and still matches the scalar path. - clean_pair(&context, &mut queue, 4, &mut report)?; - queue.close() - })(); + let result = scenarios::run(&context, &foreign, &mut report); let allocated = (context.allocated_bytes(), foreign.allocated_bytes()); let closes = (context.close(), foreign.close()); result.expect("completed changed GDN row queue proof"); @@ -233,6 +76,8 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() { #[path = "gdn_closed_queue_gpu/bytes_fn.rs"] mod bytes_fn; +#[path = "gdn_closed_queue_gpu/scenarios.rs"] +mod scenarios; #[allow(unused_imports)] use bytes_fn::blank; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/gdn_closed_queue_gpu/scenarios.rs b/crates/cuda-driver/src/gdn_closed_queue_gpu/scenarios.rs new file mode 100644 index 00000000..83852628 --- /dev/null +++ b/crates/cuda-driver/src/gdn_closed_queue_gpu/scenarios.rs @@ -0,0 +1,214 @@ +//! The scenarios of the changed GDN row queue proof: clean rows, ordered numerical refusals, retained batched +//! rows and the admission refusals, all on one queue. + +#[allow(unused_imports)] +use super::*; + +/// The whole proof on one queue of `context`; `foreign` supplies the buffers of another Context. +pub(super) fn run(context: &Context<'_>, foreign: &Context<'_>, report: &mut Report) -> Result<()> { + let mut queue = context.gdn_row_queue()?; + if queue.allocated_bytes() != STATUS_BYTES { + return Err(Error::InvalidDriverValue("unexpected queue charge")); + } + clean_and_refused_rows(context, &mut queue, report)?; + column_groups(context, &mut queue, report)?; + // Program order, data flow, aliasing, context and shape admission. + let row = Row::new(context, 7, Poison::default())?; + let other = Row::new(foreign, 7, Poison::default())?; + let admission = admission_refusals(context, &mut queue, [&row, &other], report); + let cleanup = combine(row.release(), other.release()); + combine(admission, cleanup)?; + // The queue survives every refusal above and still matches the scalar path. + clean_pair(context, &mut queue, 4, report)?; + queue.close() +} + +fn clean_and_refused_rows(context: &Context<'_>, queue: &mut GdnRowQueue<'_>, report: &mut Report) -> Result<()> { + // Three clean rows on one queue: statuses are reset on every drain. + for salt in [0, 1, 2] { + clean_pair(context, queue, salt, report)?; + } + // Earliest refusal in program order, then the queue stays usable. + let cases = [ + (Poison { alpha: true, ..Poison::default() }, GdnQueueStage::Alpha), + (Poison { conv_weights: true, ..Poison::default() }, GdnQueueStage::ConvRaw), + (Poison { state: true, ..Poison::default() }, GdnQueueStage::NextState), + (Poison { z: true, ..Poison::default() }, GdnQueueStage::Z), + (Poison { alpha: true, z: true, ..Poison::default() }, GdnQueueStage::Alpha), + ]; + for (poison, stage) in cases { + refusal_case(context, queue, poison, stage, report)?; + clean_pair(context, queue, 3, report)?; + } + Ok(()) +} + +/// Retained batched QKV rows: first, middle and last of a 3-row and a 64-row batch; a poisoned OTHER row is +/// irrelevant, the USED row refuses. +fn column_groups(context: &Context<'_>, queue: &mut GdnRowQueue<'_>, report: &mut Report) -> Result<()> { + for (tokens, used) in [(3usize, 0usize), (3, 1), (3, 2), (64, 63)] { + columns_pair(context, queue, 8, tokens, used, false, false, report)?; + columns_pair(context, queue, 8, tokens, used, false, true, report)?; + columns_pair(context, queue, 8, tokens, used, true, false, report)?; + clean_pair(context, queue, 3, report)?; + } + Ok(()) +} + +fn admission_refusals( + context: &Context<'_>, + queue: &mut GdnRowQueue<'_>, + [row, other]: [&Row<'_>; 2], + report: &mut Report, +) -> Result<()> { + scan_order_refusals(queue, row, report)?; + recurrence_refusals(queue, row, report)?; + foreign_and_short_refusals(context, queue, other, report)?; + fetch_refusals(queue, row, report)?; + retained_row_refusals(context, queue, row, report) +} + +fn scan_order_refusals(queue: &mut GdnRowQueue<'_>, row: &Row<'_>, report: &mut Report) -> Result<()> { + // Convolution before the two input scans. + let mut prefix = queue.begin()?; + refuse( + prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h), + Error::InvalidQwenShape, + report, + )?; + refuse(prefix.finish(), Error::InvalidQwenShape, report)?; + // Q/K over a buffer that is not the convolution H output. + let mut prefix = queue.begin()?; + prefix.scan_alpha(&row.alpha)?; + prefix.scan_beta_raw(&row.beta_raw)?; + prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?; + refuse(prefix.qk_l2(&row.raw, &row.qk, EPSILON), Error::InvalidQwenShape, report)?; + // A latched admission error still drains the admitted prefix first. + refuse(prefix.finish(), Error::InvalidQwenShape, report) +} + +fn recurrence_refusals(queue: &mut GdnRowQueue<'_>, row: &Row<'_>, report: &mut Report) -> Result<()> { + // Recurrence whose current state and next state are one owner. + let mut prefix = queue.begin()?; + prefix.scan_alpha(&row.alpha)?; + prefix.scan_beta_raw(&row.beta_raw)?; + prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?; + prefix.qk_l2(&row.h, &row.qk, EPSILON)?; + prefix.beta_sigmoid(&row.beta_raw, &row.sigmoid)?; + prefix.gate_softplus(&row.alpha, &row.dt, &row.a, &row.gate)?; + refuse( + prefix.recurrence(&row.state, &row.qk, &row.h, &row.gate, &row.sigmoid, &row.state, &row.readout), + Error::OutputAliasesInput, + report, + )?; + refuse(prefix.finish(), Error::OutputAliasesInput, report) +} + +fn foreign_and_short_refusals( + context: &Context<'_>, + queue: &mut GdnRowQueue<'_>, + other: &Row<'_>, + report: &mut Report, +) -> Result<()> { + // A buffer from another Context. + let mut prefix = queue.begin()?; + refuse(prefix.scan_alpha(&other.alpha), Error::ContextMismatch, report)?; + refuse(prefix.finish(), Error::ContextMismatch, report)?; + // A whole buffer of the wrong size. + let short = blank(context, 47)?; + let mut prefix = queue.begin()?; + let result = prefix.scan_alpha(&short); + refuse(result, Error::InvalidQwenShape, report)?; + refuse(prefix.finish(), Error::InvalidQwenShape, report)?; + short.release() +} + +fn fetch_refusals(queue: &mut GdnRowQueue<'_>, row: &Row<'_>, report: &mut Report) -> Result<()> { + // History fetch of a buffer that is not the convolution output, + // a second fetch, and a finish before the program is complete. + let mut prefix = queue.begin()?; + prefix.scan_alpha(&row.alpha)?; + prefix.scan_beta_raw(&row.beta_raw)?; + prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?; + refuse(prefix.fetch_next_history(&row.history), Error::InvalidQwenShape, report)?; + refuse(prefix.finish(), Error::InvalidQwenShape, report)?; + let mut prefix = queue.begin()?; + prefix.scan_alpha(&row.alpha)?; + let incomplete = prefix.finish(); + refuse(incomplete, Error::InvalidQwenShape, report) +} + +/// Retained-row admission: not a whole number of rows, a row beyond the batch, the host convolution after a column +/// scan, a different row index or owner at the convolution, and a late column scan. +fn retained_row_refusals( + context: &Context<'_>, + queue: &mut GdnRowQueue<'_>, + row: &Row<'_>, + report: &mut Report, +) -> Result<()> { + let ragged = blank(context, CHANNELS + 1)?; + let image = upload(context, &column_image(1, 3, 1))?; + let admission = retained_admission(queue, row, [&ragged, &image], report); + combine(combine(admission, ragged.release()), image.release()) +} + +fn retained_admission( + queue: &mut GdnRowQueue<'_>, + row: &Row<'_>, + [ragged, image]: [&DeviceBuffer<'_>; 2], + report: &mut Report, +) -> Result<()> { + let mut prefix = queue.begin()?; + refuse(prefix.scan_qkv_columns(ragged, 0), Error::InvalidQwenShape, report)?; + refuse(prefix.finish(), Error::InvalidQwenShape, report)?; + let mut prefix = queue.begin()?; + refuse(prefix.scan_qkv_columns(image, 3), Error::InvalidQwenShape, report)?; + refuse(prefix.finish(), Error::InvalidQwenShape, report)?; + retained_host_conv(queue, row, image, report)?; + retained_conv_columns(queue, row, image, (image, 2), report)?; + let mut prefix = queue.begin()?; + prefix.scan_alpha(&row.alpha)?; + refuse(prefix.scan_qkv_columns(image, 1), Error::InvalidQwenShape, report)?; + refuse(prefix.finish(), Error::InvalidQwenShape, report)?; + // The retained-row conv over another owner than the scanned one. + retained_conv_columns(queue, row, image, (ragged, 1), report) +} + +/// The host convolution after a column scan. +fn retained_host_conv( + queue: &mut GdnRowQueue<'_>, + row: &Row<'_>, + image: &DeviceBuffer<'_>, + report: &mut Report, +) -> Result<()> { + let mut prefix = queue.begin()?; + prefix.scan_qkv_columns(image, 1)?; + prefix.scan_alpha(&row.alpha)?; + prefix.scan_beta_raw(&row.beta_raw)?; + refuse( + prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h), + Error::InvalidQwenShape, + report, + )?; + refuse(prefix.finish(), Error::InvalidQwenShape, report) +} + +/// Row 1 of `image` is scanned, then the retained-row convolution runs over `conv` = (owner, row index). +fn retained_conv_columns( + queue: &mut GdnRowQueue<'_>, + row: &Row<'_>, + image: &DeviceBuffer<'_>, + conv: (&DeviceBuffer<'_>, usize), + report: &mut Report, +) -> Result<()> { + let mut prefix = queue.begin()?; + prefix.scan_qkv_columns(image, 1)?; + prefix.scan_alpha(&row.alpha)?; + prefix.scan_beta_raw(&row.beta_raw)?; + refuse( + prefix.conv_silu_columns(&row.history, conv.0, conv.1, &row.weights, &row.next_history, &row.raw, &row.h), + Error::InvalidQwenShape, + report, + )?; + refuse(prefix.finish(), Error::InvalidQwenShape, report) +} diff --git a/crates/cuda-driver/src/gdn_native_batch_ffi.rs b/crates/cuda-driver/src/gdn_native_batch_ffi.rs index 402e44dd..8b792d26 100644 --- a/crates/cuda-driver/src/gdn_native_batch_ffi.rs +++ b/crates/cuda-driver/src/gdn_native_batch_ffi.rs @@ -5,6 +5,13 @@ // `gdn_native_batch`; no caller can supply code or an entry name. use crate::qwen_dispatch::gdn_native_batch::{self as batch, Kernel}; +fn nonzero_geometry(grid: [u32; 3], block: [u32; 3]) -> Result<()> { + if grid.contains(&0) || block.contains(&0) { + return Err(Error::InvalidQwenShape); + } + Ok(()) +} + impl Api { pub(crate) fn load_gdn_native_module(&self, dequant: bool) -> Result { let ptx = if dequant { @@ -40,9 +47,7 @@ impl Api { block: [u32; 3], args: &mut GdnPrefillArguments, ) -> Result<()> { - if grid.contains(&0) || block.contains(&0) { - return Err(Error::InvalidQwenShape); - } + nonzero_geometry(grid, block)?; // SAFETY: geometry and parameter list are derived from the closed kernel // table and admitted extents; the owned argument storage survives the // final synchronize. `stream` is the adapter-owned stream (or the default From d800f589922e58fb57ab1b21ba10ce08ead1280f Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 23:02:30 +0100 Subject: [PATCH 5/7] STRA-338 size2 cd1: GDN fused t1, native batch, state guard and gemm loan split into phases --- crates/cuda-driver/src/gdn_batch_gemm.rs | 110 +++++----- .../src/gdn_closed_queue_gpu/bytes_fn.rs | 39 ++-- .../gdn_closed_queue_gpu/columns_pair_fn.rs | 76 ++++--- .../impl_gdnfusedprefix_2.rs | 72 +++---- .../impl_gdnfusedprefix_2_2.rs | 190 +++++++++++------- .../src/gdn_fused_t1/impl_gdnfusedt1.rs | 57 +++--- .../cuda-driver/src/gdn_fused_t1/words_fn.rs | 101 +++++----- .../src/gdn_native_batch/impl_context.rs | 84 ++++---- .../impl_gdnbatchprefix_2.rs | 74 ++++--- .../impl_gdnbatchprefix_2_2.rs | 186 ++++++++++------- .../impl_gdnbatchprefix_3.rs | 170 ++++++++++------ .../src/gdn_native_batch/staging_fn.rs | 62 +++--- .../cuda-driver/src/gdn_native_batch_gpu.rs | 76 ++++--- .../src/gdn_native_batch_gpu/bytes_of_fn.rs | 65 ++++-- .../src/gdn_native_batch_gpu/impl_hostgemm.rs | 163 ++++++++------- .../src/gdn_native_batch_gpu/run_case_fn.rs | 161 +++++++++------ .../cuda-driver/src/gdn_state_finite_guard.rs | 110 ++++++---- 17 files changed, 1066 insertions(+), 730 deletions(-) diff --git a/crates/cuda-driver/src/gdn_batch_gemm.rs b/crates/cuda-driver/src/gdn_batch_gemm.rs index 29da540e..eb927494 100644 --- a/crates/cuda-driver/src/gdn_batch_gemm.rs +++ b/crates/cuda-driver/src/gdn_batch_gemm.rs @@ -11,6 +11,45 @@ pub struct NativeGdnGemm<'loan, 'ctx> { stream: GdnStream, } +/// The closed set of shapes: `tokens` in 1..=64; the BF16 gate/MoE matrices and the ordinary F16 projections. +fn admit_shape(bf16: bool, shape: &GemmShape) -> Result<()> { + if !(1..=64).contains(&shape.tokens) { + return Err(Error::InvalidQwenShape); + } + let ordinary = + matches!((shape.rows, shape.depth), (10240, 2560) | (6144, 2560) | (2560, 6144) | (640, 2560) | (2560, 640)); + if bf16 { + let interleaved = (shape.rows, shape.depth, shape.ldy) == (48, 2560, 96) && matches!(shape.y_offset, 0 | 48); + let moe = matches!((shape.rows, shape.depth), (512, 2560) | (1, 2560)) + && shape.ldy == shape.rows + && shape.y_offset == 0; + if (!interleaved && !moe) || (shape.beta != 0.0 && shape.beta != 1.0) { + return Err(Error::InvalidQwenShape); + } + } else if !ordinary || shape.ldy != shape.rows || shape.y_offset != 0 || shape.beta != 0.0 { + return Err(Error::InvalidQwenShape); + } + Ok(()) +} + +/// The byte sizes of `x`, `w` and `y` agree with the shape. +fn admit_bytes(bf16: bool, shape: &GemmShape, [x, w, y]: [&DeviceBuffer<'_>; 3]) -> Result<()> { + let input_bytes = shape.tokens * shape.depth * 2; + let matrix_bytes = shape.rows * shape.depth * 2; + let output_bytes = shape.tokens * shape.ldy * 4; + if x.bytes != input_bytes + || y.bytes != output_bytes + || (bf16 && w.bytes != matrix_bytes) + || (!bf16 + && w.bytes != matrix_bytes + && w.bytes != DEQUANT_BYTES + && !(matches!((shape.rows, shape.depth), (640, 2560) | (2560, 640)) && w.bytes == 3_276_800)) + { + return Err(Error::InvalidQwenShape); + } + Ok(()) +} + impl<'loan, 'ctx> NativeGdnGemm<'loan, 'ctx> { pub(crate) fn new(workspace: &'loan mut NativeBatchWorkspace<'ctx>) -> Result { let stream = workspace.blas()?.stream(); @@ -30,40 +69,30 @@ impl<'loan, 'ctx> NativeGdnGemm<'loan, 'ctx> { ) -> Result<()> { let context = self.workspace.context_for_gdn(); self.workspace.validate_context(context)?; - if !(1..=64).contains(&shape.tokens) { - return Err(Error::InvalidQwenShape); - } - let ordinary = matches!( - (shape.rows, shape.depth), - (10240, 2560) | (6144, 2560) | (2560, 6144) | (640, 2560) | (2560, 640) - ); - if bf16 { - let interleaved = - (shape.rows, shape.depth, shape.ldy) == (48, 2560, 96) && matches!(shape.y_offset, 0 | 48); - let moe = matches!((shape.rows, shape.depth), (512, 2560) | (1, 2560)) - && shape.ldy == shape.rows - && shape.y_offset == 0; - if (!interleaved && !moe) || (shape.beta != 0.0 && shape.beta != 1.0) { - return Err(Error::InvalidQwenShape); - } - } else if !ordinary || shape.ldy != shape.rows || shape.y_offset != 0 || shape.beta != 0.0 { - return Err(Error::InvalidQwenShape); - } - let input_bytes = shape.tokens * shape.depth * 2; - let matrix_bytes = shape.rows * shape.depth * 2; - let output_bytes = shape.tokens * shape.ldy * 4; - if x.bytes != input_bytes - || y.bytes != output_bytes - || (bf16 && w.bytes != matrix_bytes) - || (!bf16 - && w.bytes != matrix_bytes - && w.bytes != DEQUANT_BYTES - && !(matches!((shape.rows, shape.depth), (640, 2560) | (2560, 640)) && w.bytes == 3_276_800)) - { - return Err(Error::InvalidQwenShape); - } - // Validate WHOLE actual owners, including the unused dequantized tail. - // Only the fixed matrix prefix is consumed by the original GEMM. + admit_shape(bf16, &shape)?; + admit_bytes(bf16, &shape, [x, w, y])?; + let [xh, wh, yh] = self.admit_owners(context, [x, w, y])?; + self.workspace.blas()?.gemm_gdn( + bf16, + xh, + wh, + yh, + shape.tokens as i32, + shape.rows as i32, + shape.depth as i32, + shape.ldy as i32, + shape.y_offset, + &shape.beta, + ) + } + + /// Validates WHOLE actual owners, including the unused dequantized tail; only the fixed matrix prefix is + /// consumed by the original GEMM. Returns the `x`, `w`, `y` handles, none of which may overlap another. + fn admit_owners( + &self, + context: &crate::Context<'_>, + [x, w, y]: [&DeviceBuffer<'_>; 3], + ) -> Result<[crate::ffi::BufferHandle; 3]> { for buffer in [x, w, y] { if !std::ptr::eq(buffer.context, context) { return Err(Error::ContextMismatch); @@ -78,18 +107,7 @@ impl<'loan, 'ctx> NativeGdnGemm<'loan, 'ctx> { if xh.overlaps(x.bytes, wh, w.bytes) || xh.overlaps(x.bytes, yh, y.bytes) || wh.overlaps(w.bytes, yh, y.bytes) { return Err(Error::OutputAliasesInput); } - self.workspace.blas()?.gemm_gdn( - bf16, - xh, - wh, - yh, - shape.tokens as i32, - shape.rows as i32, - shape.depth as i32, - shape.ldy as i32, - shape.y_offset, - &shape.beta, - ) + Ok([xh, wh, yh]) } } diff --git a/crates/cuda-driver/src/gdn_closed_queue_gpu/bytes_fn.rs b/crates/cuda-driver/src/gdn_closed_queue_gpu/bytes_fn.rs index e7f493e2..092b0334 100644 --- a/crates/cuda-driver/src/gdn_closed_queue_gpu/bytes_fn.rs +++ b/crates/cuda-driver/src/gdn_closed_queue_gpu/bytes_fn.rs @@ -26,23 +26,7 @@ pub(super) fn pattern(count: usize, salt: usize, modulus: usize, scale: f32, off } impl<'a> Row<'a> { pub(super) fn new(context: &'a Context<'_>, salt: usize, poison: Poison) -> Result { - let nan = f32::from_bits(0x7fc0_0001); - let mut alpha = pattern(48, salt, 17, 1.0 / 32.0, 0.25); - if poison.alpha { - alpha[47] = nan; - } - let mut weights = (0..4 * CHANNELS).map(|i| [0.25, 0.5, -0.25, 0.125][(i + salt) % 4]).collect::>(); - if poison.conv_weights { - weights[4 * CHANNELS - 1] = nan; - } - let mut state = pattern(STATE, salt, 19, 1.0 / 512.0, 0.0175); - if poison.state { - state[STATE - 1] = nan; - } - let mut z = pattern(VALUES, salt + 2, 23, 1.0 / 64.0, 0.17); - if poison.z { - z[VALUES - 1] = nan; - } + let (alpha, weights, state, z) = Self::host_inputs(salt, poison); Ok(Self { history: upload(context, &pattern(HISTORY, salt, 13, 1.0 / 256.0, 0.0234))?, qkv: upload(context, &pattern(CHANNELS, salt + 1, 29, 1.0 / 64.0, 0.21))?, @@ -66,6 +50,27 @@ impl<'a> Row<'a> { normalized: blank(context, VALUES)?, }) } + /// The host words of the alpha, convolution weights, state and Z inputs, each with its optional NaN tail. + fn host_inputs(salt: usize, poison: Poison) -> (Vec, Vec, Vec, Vec) { + let nan = f32::from_bits(0x7fc0_0001); + let mut alpha = pattern(48, salt, 17, 1.0 / 32.0, 0.25); + if poison.alpha { + alpha[47] = nan; + } + let mut weights = (0..4 * CHANNELS).map(|i| [0.25, 0.5, -0.25, 0.125][(i + salt) % 4]).collect::>(); + if poison.conv_weights { + weights[4 * CHANNELS - 1] = nan; + } + let mut state = pattern(STATE, salt, 19, 1.0 / 512.0, 0.0175); + if poison.state { + state[STATE - 1] = nan; + } + let mut z = pattern(VALUES, salt + 2, 23, 1.0 / 64.0, 0.17); + if poison.z { + z[VALUES - 1] = nan; + } + (alpha, weights, state, z) + } pub(super) fn release(self) -> Result<()> { let mut result = Ok(()); for buffer in [ diff --git a/crates/cuda-driver/src/gdn_closed_queue_gpu/columns_pair_fn.rs b/crates/cuda-driver/src/gdn_closed_queue_gpu/columns_pair_fn.rs index a0a47d11..07f3b2ed 100644 --- a/crates/cuda-driver/src/gdn_closed_queue_gpu/columns_pair_fn.rs +++ b/crates/cuda-driver/src/gdn_closed_queue_gpu/columns_pair_fn.rs @@ -17,6 +17,16 @@ pub(super) fn columns_pair( poison_other: bool, report: &mut Report, ) -> Result<()> { + let image = poisoned_image(salt, tokens, used, poison_used, poison_other); + let mut old = Row::new(context, salt, Poison::default())?; + let actual = Row::new(context, salt, Poison::default())?; + let columns = upload(context, &image)?; + let operation = compare_columns(context, queue, (&mut old, &actual), (&columns, used), poison_used, report); + combine(combine(combine(operation, old.release()), actual.release()), columns.release()) +} + +/// The batched host image with a non-finite word in the used row and/or in another row. +fn poisoned_image(salt: usize, tokens: usize, used: usize, poison_used: bool, poison_other: bool) -> Vec { let nan = f32::from_bits(0x7fc0_0001); let mut image = column_image(salt, tokens, used); if poison_used { @@ -26,33 +36,45 @@ pub(super) fn columns_pair( let other = (used + 1) % tokens; image[other * CHANNELS + 3] = nan; } - let mut old = Row::new(context, salt, Poison::default())?; - let actual = Row::new(context, salt, Poison::default())?; - let columns = upload(context, &image)?; - let operation = (|| { - scalar(context, &mut old)?; - let expected = old.products()?; - let completion = queued_columns(queue, &actual, &columns, used)?; - report.guards += 1; - if poison_used { - if completion.numerical_refusal() == Some(GdnQueueStage::Qkv) { - report.refusals += 1; - } else { - report.differences += 1; - } - return Ok(()); - } - let history = - completion.into_next_history().map_err(|_| Error::InvalidDriverValue("unexpected GDN column refusal"))?; - let found = actual.products()?; - compare(&expected, &found, report); - if bytes(&history) != found[0] { - report.differences += 1; - } - report.rows += 1; - Ok(()) - })(); - combine(combine(combine(operation, old.release()), actual.release()), columns.release()) + image +} + +/// The original sequence over `rows.0`, then the queued program over `rows.1` with `columns` (buffer, row index). +fn compare_columns( + context: &Context<'_>, + queue: &mut GdnRowQueue<'_>, + rows: (&mut Row<'_>, &Row<'_>), + columns: (&DeviceBuffer<'_>, usize), + poison_used: bool, + report: &mut Report, +) -> Result<()> { + let (old, actual) = rows; + scalar(context, old)?; + let expected = old.products()?; + let completion = queued_columns(queue, actual, columns.0, columns.1)?; + report.guards += 1; + if poison_used { + note_qkv_refusal(&completion, report); + return Ok(()); + } + let history = + completion.into_next_history().map_err(|_| Error::InvalidDriverValue("unexpected GDN column refusal"))?; + let found = actual.products()?; + compare(&expected, &found, report); + if bytes(&history) != found[0] { + report.differences += 1; + } + report.rows += 1; + Ok(()) +} + +/// A poisoned used row must refuse at the first stage (the QKV scan). +fn note_qkv_refusal(completion: &GdnRowCompletion, report: &mut Report) { + if completion.numerical_refusal() == Some(GdnQueueStage::Qkv) { + report.refusals += 1; + } else { + report.differences += 1; + } } pub(super) fn compare(old: &[Vec], actual: &[Vec], report: &mut Report) { diff --git a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs index f0cf168c..d5fab16c 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs @@ -143,10 +143,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { ) -> Result<()> { let result = (|| { self.ready(Step::Conv)?; - let qkv = self.handle(Role::Qkv)?; - let hist = self.bind(Role::NextHistory, next_history, GdnFusedStage::NextHistory.bytes())?; - let w = self.bind(Role::ConvW, conv_weights, 4 * C * F32)?; - let h_handle = self.bind(Role::H, h, GdnFusedStage::H.bytes())?; + let [hist, qkv, w, h_handle] = self.bind_conv(next_history, conv_weights, h)?; self.push( FusedKernel::ConvL2, ([(C / S) as u32, 1, 1], [S as u32, 1, 1]), @@ -165,6 +162,19 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { })(); self.latch(result) } + /// The retained QKV handle and the bindings of the convolution (history, weights, H), in call order. + fn bind_conv( + &mut self, + next_history: &'lease DeviceBuffer<'lease>, + conv_weights: &'lease DeviceBuffer<'lease>, + h: &'lease DeviceBuffer<'lease>, + ) -> Result<[ffi::BufferHandle; 4]> { + let qkv = self.handle(Role::Qkv)?; + let hist = self.bind(Role::NextHistory, next_history, GdnFusedStage::NextHistory.bytes())?; + let w = self.bind(Role::ConvW, conv_weights, 4 * C * F32)?; + let h_handle = self.bind(Role::H, h, GdnFusedStage::H.bytes())?; + Ok([hist, qkv, w, h_handle]) + } /// `fused_gdn_ab`: gate = softplus(alpha . x + dt) * ssm_a, beta = sigmoid(beta . x). `w_alpha` / `w_beta` are /// the exact BF16 `[48][2560]` matrices, `mixed` the exact f32 `[2560]` activation. #[allow(clippy::too_many_arguments)] // The Original call has the same operand list. @@ -180,36 +190,9 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { ) -> Result<()> { let result = (|| { self.ready(Step::Ab)?; - let x = self.bind(Role::Mixed, mixed, N_EMBD * F32)?; - let wa = self.bind(Role::WAlpha, w_alpha, HV * N_EMBD * F16)?; - let wb = self.bind(Role::WBeta, w_beta, HV * N_EMBD * F16)?; - let dt_h = self.bind(Role::Dt, dt, HV * F32)?; - let a_h = self.bind(Role::A, ssm_a, HV * F32)?; - let gate_h = self.bind(Role::Gate, gate, GdnFusedStage::Gate.bytes())?; - let beta_h = self.bind(Role::Beta, beta, GdnFusedStage::Beta.bytes())?; - if self.checks != GdnFusedStage::RawAlpha.slot() { - return Err(Error::InvalidQwenShape); - } - // Two adjacent private words receive only integer classifications of the original raw accumulators. - let raw_status = self.batch.status_handle()?.checked_subspan( - STATUS_BYTES, - GdnFusedStage::RawAlpha.slot() * F32, - 2 * F32, - )?; - self.push( - FusedKernel::Ab, - ([((2 * HV + 7) / 8) as u32, 1, 1], [256, 1, 1]), - &[ - ffi::KernelArg::Pointer(x), - ffi::KernelArg::Pointer(wa), - ffi::KernelArg::Pointer(wb), - ffi::KernelArg::Pointer(dt_h), - ffi::KernelArg::Pointer(a_h), - ffi::KernelArg::Pointer(gate_h), - ffi::KernelArg::Pointer(beta_h), - ffi::KernelArg::Pointer(raw_status), - ], - )?; + let pointers = self.bind_ab([mixed, w_alpha, w_beta, dt, ssm_a, gate, beta])?; + let grid = ([((2 * HV + 7) / 8) as u32, 1, 1], [256, 1, 1]); + self.push(FusedKernel::Ab, grid, &pointers.map(ffi::KernelArg::Pointer))?; self.checks = GdnFusedStage::RawBeta.slot() + 1; self.scan(GdnFusedStage::Gate, Role::Gate)?; self.scan(GdnFusedStage::Beta, Role::Beta)?; @@ -218,4 +201,25 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { })(); self.latch(result) } + /// Binds the seven operands of `fused_gdn_ab` and the two private words that receive only integer + /// classifications of the original raw accumulators; returns the eight pointers in argument order. + fn bind_ab( + &mut self, + [mixed, w_alpha, w_beta, dt, ssm_a, gate, beta]: [&'lease DeviceBuffer<'lease>; 7], + ) -> Result<[ffi::BufferHandle; 8]> { + let x = self.bind(Role::Mixed, mixed, N_EMBD * F32)?; + let wa = self.bind(Role::WAlpha, w_alpha, HV * N_EMBD * F16)?; + let wb = self.bind(Role::WBeta, w_beta, HV * N_EMBD * F16)?; + let dt_h = self.bind(Role::Dt, dt, HV * F32)?; + let a_h = self.bind(Role::A, ssm_a, HV * F32)?; + let gate_h = self.bind(Role::Gate, gate, GdnFusedStage::Gate.bytes())?; + let beta_h = self.bind(Role::Beta, beta, GdnFusedStage::Beta.bytes())?; + if self.checks != GdnFusedStage::RawAlpha.slot() { + return Err(Error::InvalidQwenShape); + } + // Two adjacent private words receive only integer classifications of the original raw accumulators. + let raw_status = + self.batch.status_handle()?.checked_subspan(STATUS_BYTES, GdnFusedStage::RawAlpha.slot() * F32, 2 * F32)?; + Ok([x, wa, wb, dt_h, a_h, gate_h, beta_h, raw_status]) + } } diff --git a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs index 3e1a4c19..b4d711bb 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs @@ -15,27 +15,8 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { ) -> Result<()> { let result = (|| { self.ready(Step::Norm)?; - let state = self.handle(Role::NextState)?; - let h = self.handle(Role::H)?; - let gate = self.handle(Role::Gate)?; - let beta = self.handle(Role::Beta)?; - let z = self.handle(Role::Z)?; - let gamma_h = self.bind(Role::Gamma, gamma, S * F32)?; - let y_h = self.bind(Role::Y, y, GdnFusedStage::Y.bytes())?; - self.push( - FusedKernel::StepNorm, - ([HV as u32, 1, 1], [S as u32, 4, 1]), - &[ - ffi::KernelArg::Pointer(state), - ffi::KernelArg::Pointer(h), - ffi::KernelArg::Pointer(gate), - ffi::KernelArg::Pointer(beta), - ffi::KernelArg::Pointer(z), - ffi::KernelArg::Pointer(gamma_h), - ffi::KernelArg::F32(epsilon), - ffi::KernelArg::Pointer(y_h), - ], - )?; + let handles = self.step_norm_handles(gamma, y)?; + self.push_step_norm(handles, epsilon)?; self.scan(GdnFusedStage::Y, Role::Y)?; self.scan(GdnFusedStage::State, Role::NextState)?; self.step = self.step.next(); @@ -43,6 +24,41 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { })(); self.latch(result) } + /// The retained state, H, gate, beta and Z handles, then the bound gamma and Y: `[state, h, gate, beta, z, gamma, y]`. + fn step_norm_handles( + &mut self, + gamma: &'lease DeviceBuffer<'lease>, + y: &'lease DeviceBuffer<'lease>, + ) -> Result<[ffi::BufferHandle; 7]> { + let state = self.handle(Role::NextState)?; + let h = self.handle(Role::H)?; + let gate = self.handle(Role::Gate)?; + let beta = self.handle(Role::Beta)?; + let z = self.handle(Role::Z)?; + let gamma_h = self.bind(Role::Gamma, gamma, S * F32)?; + let y_h = self.bind(Role::Y, y, GdnFusedStage::Y.bytes())?; + Ok([state, h, gate, beta, z, gamma_h, y_h]) + } + fn push_step_norm( + &mut self, + [state, h, gate, beta, z, gamma_h, y_h]: [ffi::BufferHandle; 7], + epsilon: f32, + ) -> Result<()> { + self.push( + FusedKernel::StepNorm, + ([HV as u32, 1, 1], [S as u32, 4, 1]), + &[ + ffi::KernelArg::Pointer(state), + ffi::KernelArg::Pointer(h), + ffi::KernelArg::Pointer(gate), + ffi::KernelArg::Pointer(beta), + ffi::KernelArg::Pointer(z), + ffi::KernelArg::Pointer(gamma_h), + ffi::KernelArg::F32(epsilon), + ffi::KernelArg::Pointer(y_h), + ], + ) + } /// Ask for the candidate state and history on the host after a clean complete drain. pub fn fetch_candidate(&mut self) -> Result<()> { let result = (|| { @@ -82,53 +98,16 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { let mut fetched_state = staging(if write_fetch { GDN_FUSED_T1_STATE_BYTES } else { 0 })?; let mut fetched_history = staging(if write_fetch { HISTORY_WORDS * F32 } else { 0 })?; if self.commands.len() > 1 { - let context = self.batch.context; - let guard = context.enter().inspect_err(|_| { - self.batch.failed = true; - context.poisoned.set(true); - })?; - // The caller's inputs may have arrived by synchronous pageable H2D (candidate history/state seeds), which - // can return after host staging only: one real context synchronization precedes the first launch. - let stream = GdnStream::default_stream(); - let mut operation = context.driver.api.synchronize(); - if operation.is_ok() { - for command in &mut self.commands { - operation = context.driver.api.launch_gdn_native( - command.function, - stream, - command.grid, - command.block, - &mut command.args, - ); - if operation.is_err() { - break; - } - } - } - // Every kernel ran on the default stream; the D2H below is ordered after them by this completion fence. - let sync = context.driver.api.synchronize(); - if operation.is_ok() && sync.is_ok() { - operation = context.driver.api.copy_to(status, &mut statuses); - } - if operation.is_ok() && sync.is_ok() && write_fetch { - let (state, history) = self.fetch.ok_or(Error::InvalidQwenShape)?; - operation = context.driver.api.copy_to(state, &mut fetched_state); - if operation.is_ok() { - operation = context.driver.api.copy_to(history, &mut fetched_history); - } - } - let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { - self.batch.failed = true; - context.poisoned.set(true); - } - if sync.is_err() || pop.is_err() { - // Completion is uncertain: retain every actual argument/staging owner. The borrowed buffers are kept alive - // by the poisoned context (it refuses to enter, so their frees leak instead of racing the device). + let fetched = (&mut fetched_state[..], &mut fetched_history[..]); + let fenced = self.fenced(status, &mut statuses, fetched, write_fetch)?; + if fenced.uncertain { + // Completion is uncertain: retain every actual argument/staging owner. The borrowed buffers are + // kept alive by the poisoned context (it refuses to enter, so their frees leak instead of racing + // the device). std::mem::forget((self.commands, self.held, statuses, fetched_state, fetched_history)); - return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain fused GDN T1 drain")); + return fenced.outcome.map(|()| unreachable!("uncertain fused GDN T1 drain")); } - combine(combine(operation, sync), pop)?; + fenced.outcome?; } let refusal = match decode_statuses(&statuses, self.checks) { Ok(refusal) => refusal, @@ -139,13 +118,84 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { } }; let fetched = if write_fetch && refusal.is_none() { - Some(( - words::(&fetched_state, f32::from_le_bytes)?, - words::(&fetched_history, f32::from_le_bytes)?, - )) + Some(candidate_words(&fetched_state, &fetched_history)?) } else { None }; Ok(Drained { refusal, deferred: self.refusal, fetched }) } + /// Runs the commands on the default stream under one context entry, reads the status words (and the candidate + /// state and history) back and synchronizes. + /// + /// The caller's inputs may have arrived by synchronous pageable H2D (candidate history/state seeds), which can + /// return after host staging only: one real context synchronization precedes the first launch. Every kernel ran + /// on the default stream; the D2H is ordered after them by the completion fence. + fn fenced( + &mut self, + status: ffi::BufferHandle, + statuses: &mut [u8], + fetched: (&mut [u8], &mut [u8]), + write_fetch: bool, + ) -> Result { + let context = self.batch.context; + let guard = context.enter().inspect_err(|_| { + self.batch.failed = true; + context.poisoned.set(true); + })?; + let mut operation = self.launch_all(); + let api = &context.driver.api; + let sync = api.synchronize(); + if operation.is_ok() && sync.is_ok() { + operation = api.copy_to(status, statuses); + } + if operation.is_ok() && sync.is_ok() && write_fetch { + let (state, history) = self.fetch.ok_or(Error::InvalidQwenShape)?; + operation = api.copy_to(state, fetched.0); + if operation.is_ok() { + operation = api.copy_to(history, fetched.1); + } + } + let pop = guard.finish(); + Ok(self.settle([operation, sync, pop])) + } + /// One real context synchronization, then (when it succeeded) the commands in order. + fn launch_all(&mut self) -> Result<()> { + let operation = self.batch.context.driver.api.synchronize(); + if operation.is_ok() { self.launch_commands() } else { operation } + } + /// Launches the commands in order on the default stream until one fails. + fn launch_commands(&mut self) -> Result<()> { + let stream = GdnStream::default_stream(); + let api = &self.batch.context.driver.api; + let mut operation = Ok(()); + for command in &mut self.commands { + operation = api.launch_gdn_native(command.function, stream, command.grid, command.block, &mut command.args); + if operation.is_err() { + break; + } + } + operation + } + /// Latches the batch and poisons the context on any failure; a failed fence or pop leaves completion uncertain. + fn settle(&mut self, [operation, sync, pop]: [Result<()>; 3]) -> Fenced { + let failed = operation.is_err() || sync.is_err() || pop.is_err(); + let uncertain = sync.is_err() || pop.is_err(); + let outcome = combine(combine(operation, sync), pop); + if failed { + self.batch.failed = true; + self.batch.context.poisoned.set(true); + } + Fenced { outcome, uncertain } + } +} + +/// The candidate state and history as words, in the order fetched. +fn candidate_words(state: &[u8], history: &[u8]) -> Result<(Box<[f32]>, Box<[f32]>)> { + Ok((words::(state, f32::from_le_bytes)?, words::(history, f32::from_le_bytes)?)) +} + +/// The result of one fenced drain: the combined outcome and whether completion is uncertain. +struct Fenced { + outcome: Result<()>, + uncertain: bool, } diff --git a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedt1.rs b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedt1.rs index 7200aceb..76046e98 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedt1.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedt1.rs @@ -15,37 +15,42 @@ impl<'ctx> GdnFusedT1<'ctx> { return Err(Error::BudgetExceeded); } let mut owner = Self { context, status: None, module: None, functions: None, failed: false }; - let result = (|| { - owner.status = Some(context.allocate(STATUS_BYTES)?); - let guard = context.enter().inspect_err(|_| { - owner.failed = true; - context.poisoned.set(true); - })?; - let load = (|| { - let api = &context.driver.api; - let module = api.load_gdn_fused_t1_module()?; - owner.module = Some(module); - let mut all = [None; FUSED_KERNELS.len()]; - for kernel in FUSED_KERNELS { - all[kernel.index()] = Some(api.gdn_fused_t1_function(module, kernel)?); - } - Ok(all.map(|f| f.expect("every fused GDN T1 kernel resolved"))) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poisoned.set(true); - } - owner.functions = Some(combine(load, pop)?); - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); + let result = owner.open(); if let Err(error) = result { return combine(Err(error), owner.close_inner()); } Ok(owner) } + /// Allocates the status buffer and loads the kernels under the context; the restore failing poisons it. + fn open(&mut self) -> Result<()> { + let context = self.context; + self.status = Some(context.allocate(STATUS_BYTES)?); + let guard = context.enter().inspect_err(|_| { + self.failed = true; + context.poisoned.set(true); + })?; + let load = self.load_functions(); + let pop = guard.finish(); + if pop.is_err() { + context.poisoned.set(true); + } + self.functions = Some(combine(load, pop)?); + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + /// Loads the fused module (kept in `self.module`) and resolves every kernel of it. + fn load_functions(&mut self) -> Result<[ffi::FunctionHandle; FUSED_KERNELS.len()]> { + let api = &self.context.driver.api; + let module = api.load_gdn_fused_t1_module()?; + self.module = Some(module); + let mut all = [None; FUSED_KERNELS.len()]; + for kernel in FUSED_KERNELS { + all[kernel.index()] = Some(api.gdn_fused_t1_function(module, kernel)?); + } + Ok(all.map(|f| f.expect("every fused GDN T1 kernel resolved"))) + } pub(super) fn status_handle(&self) -> Result { if self.is_failed() || self.functions.is_none() { return Err(Error::ContextPoisoned); diff --git a/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs b/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs index d60517a6..21e2db0a 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs @@ -22,39 +22,45 @@ impl GdnFusedT1<'_> { self.functions = None; let mut result = Ok(()); if let Some(buffer) = self.status.take() { - let release = if self.context.is_poisoned() { - std::mem::forget(buffer); - Err(Error::ContextPoisoned) - } else { - buffer.release() - }; - if release.is_err() { - self.context.poisoned.set(true); - } - result = combine(result, release); + result = combine(result, self.release_status(buffer)); } if let Some(module) = self.module.take() { - let release = if self.context.is_poisoned() { - self.context.retain_driver(); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(guard) => { - let unload = self.context.driver.api.unload(module); - let pop = guard.finish(); - combine(unload, pop) - } - Err(error) => Err(error), - } - }; - if release.is_err() { - self.context.poisoned.set(true); - self.context.retain_driver(); - } - result = combine(result, release); + result = combine(result, self.release_module(module)); } result } + fn release_status(&self, buffer: DeviceBuffer<'_>) -> Result<()> { + let release = if self.context.is_poisoned() { + std::mem::forget(buffer); + Err(Error::ContextPoisoned) + } else { + buffer.release() + }; + if release.is_err() { + self.context.poisoned.set(true); + } + release + } + fn release_module(&self, module: ffi::ModuleHandle) -> Result<()> { + let release = if self.context.is_poisoned() { + self.context.retain_driver(); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(guard) => { + let unload = self.context.driver.api.unload(module); + let pop = guard.finish(); + combine(unload, pop) + } + Err(error) => Err(error), + } + }; + if release.is_err() { + self.context.poisoned.set(true); + self.context.retain_driver(); + } + release + } } impl Drop for GdnFusedT1<'_> { fn drop(&mut self) { @@ -77,26 +83,8 @@ impl GdnFusedT1<'_> { readout: &DeviceBuffer<'_>, ) -> Result { let mut prefix = self.begin()?; - let input = prefix.bind(Role::Resident, state, STATE_WORDS * F32)?; - let qk_h = prefix.bind(Role::Qkv, qk, C * F32)?; - let h_h = prefix.bind(Role::H, h, C * F32)?; - let gate_h = prefix.bind(Role::Gate, gate, HV * F32)?; - let beta_h = prefix.bind(Role::Beta, beta, HV * F32)?; - let output = prefix.bind(Role::NextState, next, STATE_WORDS * F32)?; - let y = prefix.bind(Role::Y, readout, VALUES * F32)?; - prefix.push( - FusedKernel::ReplayState, - ([HV as u32, 1, 1], [S as u32, 4, 1]), - &[ - ffi::KernelArg::Pointer(input), - ffi::KernelArg::Pointer(qk_h), - ffi::KernelArg::Pointer(h_h), - ffi::KernelArg::Pointer(gate_h), - ffi::KernelArg::Pointer(beta_h), - ffi::KernelArg::Pointer(output), - ffi::KernelArg::Pointer(y), - ], - )?; + let arguments = prefix.bind_replay([state, qk, h, gate, beta, next, readout])?; + prefix.push(FusedKernel::ReplayState, ([HV as u32, 1, 1], [S as u32, 4, 1]), &arguments)?; // Earlier words remain the actual zero-reset unused slots; only this // fixed operation's two full output scans contribute numeric witnesses. prefix.checks = GdnFusedStage::Y.slot(); @@ -106,6 +94,23 @@ impl GdnFusedT1<'_> { Ok(drained.refusal.is_none()) } } + +impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { + /// Binds the seven journal operands of the replay (state, Q/K, H, gate, beta, next state, readout) in order. + fn bind_replay( + &mut self, + [state, qk, h, gate, beta, next, readout]: [&'lease DeviceBuffer<'lease>; 7], + ) -> Result<[ffi::KernelArg; 7]> { + let input = self.bind(Role::Resident, state, STATE_WORDS * F32)?; + let qk_h = self.bind(Role::Qkv, qk, C * F32)?; + let h_h = self.bind(Role::H, h, C * F32)?; + let gate_h = self.bind(Role::Gate, gate, HV * F32)?; + let beta_h = self.bind(Role::Beta, beta, HV * F32)?; + let output = self.bind(Role::NextState, next, STATE_WORDS * F32)?; + let y = self.bind(Role::Y, readout, VALUES * F32)?; + Ok([input, qk_h, h_h, gate_h, beta_h, output, y].map(ffi::KernelArg::Pointer)) + } +} impl GdnFusedPrefix<'_, '_> { /// Completed native row; state stays in its actual exclusive journal owner. /// No full host state allocation/readback and no new session certificate. diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_context.rs b/crates/cuda-driver/src/gdn_native_batch/impl_context.rs index 93681fa1..3458de9e 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_context.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_context.rs @@ -3,6 +3,13 @@ #[allow(unused_imports)] use super::*; +/// An empty vector with room for `capacity` elements, or a typed host-allocation failure. +fn reserved(capacity: usize) -> Result> { + let mut vector = Vec::new(); + vector.try_reserve_exact(capacity).map_err(|_| Error::HostAllocation)?; + Ok(vector) +} + impl Context<'_> { pub fn gdn_prefill_batch(&self) -> Result> { GdnPrefillBatch::new(self) @@ -27,34 +34,39 @@ impl<'ctx> GdnPrefillBatch<'ctx> { return Err(Error::BudgetExceeded); } let mut owner = Self { capacity, context, status: None, modules: [None, None], functions: None, failed: false }; - let result = (|| { - owner.status = Some(context.allocate(STATUS_BYTES)?); - let guard = context.enter()?; - let load = (|| { - let api = &context.driver.api; - let prefill = api.load_gdn_native_module(false)?; - owner.modules[0] = Some(prefill); - let dequant = api.load_gdn_native_module(true)?; - owner.modules[1] = Some(dequant); - let mut all = [None; KERNELS.len()]; - for kernel in KERNELS { - let module = if kernel.is_dequant() { dequant } else { prefill }; - all[kernel.index()] = Some(api.gdn_native_function(module, kernel)?); - } - Ok(Functions { all: all.map(|function| function.expect("every GDN batch kernel resolved")) }) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poisoned.set(true); - } - owner.functions = Some(combine(load, pop)?); - Ok(()) - })(); + let result = owner.open(); if let Err(error) = result { return combine(Err(error), owner.close_inner()); } Ok(owner) } + /// Allocates the status buffer and loads the kernels under the context; the restore failing poisons it. + fn open(&mut self) -> Result<()> { + let context = self.context; + self.status = Some(context.allocate(STATUS_BYTES)?); + let guard = context.enter()?; + let load = self.load_functions(); + let pop = guard.finish(); + if pop.is_err() { + context.poisoned.set(true); + } + self.functions = Some(combine(load, pop)?); + Ok(()) + } + /// Loads the prefill and dequantization modules (kept in `self.modules`) and resolves every kernel. + fn load_functions(&mut self) -> Result { + let api = &self.context.driver.api; + let prefill = api.load_gdn_native_module(false)?; + self.modules[0] = Some(prefill); + let dequant = api.load_gdn_native_module(true)?; + self.modules[1] = Some(dequant); + let mut all = [None; KERNELS.len()]; + for kernel in KERNELS { + let module = if kernel.is_dequant() { dequant } else { prefill }; + all[kernel.index()] = Some(api.gdn_native_function(module, kernel)?); + } + Ok(Functions { all: all.map(|function| function.expect("every GDN batch kernel resolved")) }) + } pub(super) fn status_handle(&self) -> Result { if self.is_failed() || self.functions.is_none() { return Err(Error::ContextPoisoned); @@ -92,19 +104,10 @@ impl<'ctx> GdnPrefillBatch<'ctx> { return Err(Error::InvalidQwenShape); } let status = self.status_handle()?; - let mut held = Vec::new(); - held.try_reserve_exact(48).map_err(|_| Error::HostAllocation)?; - let mut commands = Vec::new(); - commands.try_reserve_exact(64).map_err(|_| Error::HostAllocation)?; + let held = reserved(48)?; + let mut commands = reserved(64)?; // The zeroing of the status words is the first command of every drain. - let (grid, block) = linear(SLOTS)?; - commands.push(Command::Kernel { - function: self.functions.as_ref().ok_or(Error::ContextPoisoned)?.get(Kernel::Zero), - stream: gemm.stream(), - grid, - block, - args: ffi::GdnPrefillArguments::new(&[ffi::KernelArg::Pointer(status), ffi::KernelArg::U32(SLOTS as u32)])?, - }); + commands.push(self.zero_command(status, gemm.stream())?); Ok(GdnBatchPrefix { batch: self, tokens, @@ -119,6 +122,17 @@ impl<'ctx> GdnPrefillBatch<'ctx> { fetch: None, }) } + /// The command that zeroes the status words on `stream`. + fn zero_command<'a>(&self, status: ffi::BufferHandle, stream: GdnStream) -> Result> { + let (grid, block) = linear(SLOTS)?; + Ok(Command::Kernel { + function: self.functions.as_ref().ok_or(Error::ContextPoisoned)?.get(Kernel::Zero), + stream, + grid, + block, + args: ffi::GdnPrefillArguments::new(&[ffi::KernelArg::Pointer(status), ffi::KernelArg::U32(SLOTS as u32)])?, + }) + } pub fn close(mut self) -> Result<()> { self.close_inner() } diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs index 19c31350..9e774699 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs @@ -126,30 +126,32 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { let result = (|| { self.ready(Step::Images)?; let t = self.tokens; - let source = self.bind(Role::Mixed, mixed, t * N * F32, false)?; - let h = self.bind(Role::MixedH, mixed_h, t * N * F16, false)?; - let bf = self.bind(Role::MixedBf, mixed_bf, t * N * F16, false)?; - let lo = match mixed_bf_lo { - Some(buffer) => ffi::KernelArg::Pointer(self.bind(Role::MixedBfLo, buffer, t * N * F16, false)?), - None => ffi::KernelArg::NullPointer, - }; - self.push_kernel( - Kernel::MixedPack, - linear(t * N)?, - &[ - ffi::KernelArg::Pointer(source), - ffi::KernelArg::Pointer(h), - ffi::KernelArg::Pointer(bf), - lo, - ffi::KernelArg::I64(t as i64), - ], - )?; + let [source, h, bf, lo] = self.mixed_arguments(mixed, mixed_h, mixed_bf, mixed_bf_lo)?; + self.push_kernel(Kernel::MixedPack, linear(t * N)?, &[source, h, bf, lo, ffi::KernelArg::I64(t as i64)])?; self.scan(GdnBatchStage::MixedH, Role::MixedH)?; self.step = self.step.next(); Ok(()) })(); self.latch(result) } + /// Binds the f32 source, the FP16 and BF16 hi images and the optional BF16 lo image. + fn mixed_arguments( + &mut self, + mixed: &'lease DeviceBuffer<'lease>, + mixed_h: &'lease DeviceBuffer<'lease>, + mixed_bf: &'lease DeviceBuffer<'lease>, + mixed_bf_lo: Option<&'lease DeviceBuffer<'lease>>, + ) -> Result<[ffi::KernelArg; 4]> { + let t = self.tokens; + let source = self.bind(Role::Mixed, mixed, t * N * F32, false)?; + let h = self.bind(Role::MixedH, mixed_h, t * N * F16, false)?; + let bf = self.bind(Role::MixedBf, mixed_bf, t * N * F16, false)?; + let lo = match mixed_bf_lo { + Some(buffer) => ffi::KernelArg::Pointer(self.bind(Role::MixedBfLo, buffer, t * N * F16, false)?), + None => ffi::KernelArg::NullPointer, + }; + Ok([ffi::KernelArg::Pointer(source), ffi::KernelArg::Pointer(h), ffi::KernelArg::Pointer(bf), lo]) + } /// The three images were produced by the caller's own (original) gr_mix. pub fn images_supplied( &mut self, @@ -185,13 +187,31 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { depth: usize, output_bytes: usize, ) -> Result<()> { - let t = self.tokens; let matrix = format.matrix_bytes(rows, depth)?; let half_bytes = rows * depth * F16; let blocks = self.bind(weights.0, weights.1, matrix, false)?; let scratch_handle = self.bind(Role::Scratch, scratch, half_bytes, true)?; self.bind(output.0, output.1, output_bytes, false)?; - // The dequantized weights: one thread per 32-value group, 256 per block. + self.push_dequant(format, (rows, depth), blocks, scratch_handle)?; + let x = self.buffer_ref(activation)?; + self.commands.push(Command::Gemm { + gemm: self.gemm, + bf16: false, + x, + w: scratch, + y: output.1, + shape: GemmShape { tokens: self.tokens, rows, depth, ldy: rows, y_offset: 0, beta: 0.0 }, + }); + Ok(()) + } + /// The dequantized weights: one thread per 32-value group, 256 per block. + fn push_dequant( + &mut self, + format: GdnNativeFormat, + (rows, depth): (usize, usize), + blocks: ffi::BufferHandle, + scratch: ffi::BufferHandle, + ) -> Result<()> { let groups_per_row = depth / 32; let groups = rows * groups_per_row; self.push_kernel( @@ -203,18 +223,8 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { ffi::KernelArg::I64(0), ffi::KernelArg::I64(rows as i64), ffi::KernelArg::I64(groups_per_row as i64), - ffi::KernelArg::Pointer(scratch_handle), + ffi::KernelArg::Pointer(scratch), ], - )?; - let x = self.buffer_ref(activation)?; - self.commands.push(Command::Gemm { - gemm: self.gemm, - bf16: false, - x, - w: scratch, - y: output.1, - shape: GemmShape { tokens: t, rows, depth, ldy: rows, y_offset: 0, beta: 0.0 }, - }); - Ok(()) + ) } } diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs index 2885c084..8982be10 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs @@ -60,25 +60,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { let x = self.buffer_ref(Role::MixedBf)?; let lo = self.buffer_ref(Role::MixedBfLo).ok(); for (weights, y_offset) in [(alpha_weights, 0), (beta_weights, HV)] { - let shape = |beta| GemmShape { tokens: t, rows: HV, depth: N, ldy: 2 * HV, y_offset, beta }; - self.commands.push(Command::Gemm { - gemm: self.gemm, - bf16: true, - x, - w: weights, - y: ab, - shape: shape(0.0), - }); - if let Some(lo) = lo { - self.commands.push(Command::Gemm { - gemm: self.gemm, - bf16: true, - x: lo, - w: weights, - y: ab, - shape: shape(1.0), - }); - } + self.push_ab_gemm(weights, y_offset, ab, (x, lo)); } self.scan(GdnBatchStage::Ab, Role::Ab)?; self.step = self.step.next(); @@ -86,6 +68,30 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { })(); self.latch(result) } + /// One BF16 projection into the interleaved `ab`: the hi image with `beta = 0`, then, when given, the lo image + /// accumulated with `beta = 1`. + fn push_ab_gemm( + &mut self, + weights: &'lease DeviceBuffer<'lease>, + y_offset: usize, + ab: &'lease DeviceBuffer<'lease>, + images: (&'lease DeviceBuffer<'lease>, Option<&'lease DeviceBuffer<'lease>>), + ) { + let t = self.tokens; + let shape = |beta| GemmShape { tokens: t, rows: HV, depth: N, ldy: 2 * HV, y_offset, beta }; + let (x, lo) = images; + self.commands.push(Command::Gemm { gemm: self.gemm, bf16: true, x, w: weights, y: ab, shape: shape(0.0) }); + if let Some(lo) = lo { + self.commands.push(Command::Gemm { + gemm: self.gemm, + bf16: true, + x: lo, + w: weights, + y: ab, + shape: shape(1.0), + }); + } + } // ---------------------------------------------------------------- GDN kernels /// `gdn_gates`: `gate` and sigmoid `beta` `[T][48]` from `ab`; two scans. @@ -99,23 +105,8 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { let result = (|| { self.ready(Step::Gates)?; let t = self.tokens; - let ab = self.handle(Role::Ab)?; - let dt_h = self.bind(Role::Dt, dt, HV * F32, false)?; - let a_h = self.bind(Role::SsmA, ssm_a, HV * F32, false)?; - let gate_h = self.bind(Role::Gate, gate, t * HV * F32, false)?; - let beta_h = self.bind(Role::Beta, beta, t * HV * F32, false)?; - self.push_kernel( - Kernel::Gates, - linear(t * HV)?, - &[ - ffi::KernelArg::Pointer(ab), - ffi::KernelArg::Pointer(dt_h), - ffi::KernelArg::Pointer(a_h), - ffi::KernelArg::Pointer(gate_h), - ffi::KernelArg::Pointer(beta_h), - ffi::KernelArg::I64(t as i64), - ], - )?; + let arguments = self.gate_arguments(dt, ssm_a, gate, beta)?; + self.push_kernel(Kernel::Gates, linear(t * HV)?, &arguments)?; self.scan(GdnBatchStage::Gate, Role::Gate)?; self.scan(GdnBatchStage::Beta, Role::Beta)?; self.step = self.step.next(); @@ -123,6 +114,29 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { })(); self.latch(result) } + /// Binds the gate operands; returns the kernel arguments in order. + fn gate_arguments( + &mut self, + dt: &'lease DeviceBuffer<'lease>, + ssm_a: &'lease DeviceBuffer<'lease>, + gate: &'lease DeviceBuffer<'lease>, + beta: &'lease DeviceBuffer<'lease>, + ) -> Result<[ffi::KernelArg; 6]> { + let t = self.tokens; + let ab = self.handle(Role::Ab)?; + let dt_h = self.bind(Role::Dt, dt, HV * F32, false)?; + let a_h = self.bind(Role::SsmA, ssm_a, HV * F32, false)?; + let gate_h = self.bind(Role::Gate, gate, t * HV * F32, false)?; + let beta_h = self.bind(Role::Beta, beta, t * HV * F32, false)?; + Ok([ + ffi::KernelArg::Pointer(ab), + ffi::KernelArg::Pointer(dt_h), + ffi::KernelArg::Pointer(a_h), + ffi::KernelArg::Pointer(gate_h), + ffi::KernelArg::Pointer(beta_h), + ffi::KernelArg::I64(t as i64), + ]) + } /// `gdn_conv`: the 4-tap causal convolution + SiLU over the chunk into `h` /// `[T][10240]`, and the history after the chunk into `next_history` /// (`history` stays untouched). Chunks of at most 64 rows use the serial @@ -137,57 +151,73 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { ) -> Result<()> { let result = (|| { self.ready(Step::Conv)?; - let t = self.tokens; - let qkv = self.handle(Role::Qkv)?; - let hist = self.bind(Role::History, history, HISTORY_WORDS * F32, false)?; - let w = self.bind(Role::ConvW, conv_weights, C * 4 * F32, false)?; - let next = self.bind(Role::NextHistory, next_history, HISTORY_WORDS * F32, false)?; - let h_h = self.bind(Role::H, h, t * C * F32, false)?; - let t_arg = ffi::KernelArg::I64(t as i64); - if t <= CONV_TILE { - self.push_kernel( - Kernel::Conv, - ([(C / 128) as u32, 1, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(hist), - ffi::KernelArg::Pointer(next), - ffi::KernelArg::Pointer(qkv), - ffi::KernelArg::Pointer(w), - ffi::KernelArg::Pointer(h_h), - t_arg, - ], - )?; + let handles = self.bind_conv(history, conv_weights, next_history, h)?; + if self.tokens <= CONV_TILE { + self.push_conv_serial(handles)?; } else { - self.push_kernel( - Kernel::ConvTiled, - ([(C / 128) as u32, t.div_ceil(CONV_TILE) as u32, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(hist), - ffi::KernelArg::Pointer(qkv), - ffi::KernelArg::Pointer(w), - ffi::KernelArg::Pointer(h_h), - t_arg, - ], - )?; - self.push_kernel( - Kernel::ConvHist, - ([(C / 128) as u32, 1, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(next), - ffi::KernelArg::Pointer(hist), - ffi::KernelArg::Pointer(qkv), - t_arg, - ], - )?; + self.push_conv_tiled(handles)?; } self.scan(GdnBatchStage::ConvH, Role::H)?; self.scan(GdnBatchStage::NextHistory, Role::NextHistory)?; - self.fetch = Some(next); + self.fetch = Some(handles[3]); self.step = self.step.next(); Ok(()) })(); self.latch(result) } + /// Binds the convolution operands; returns `[qkv, history, weights, next_history, h]`. + fn bind_conv( + &mut self, + history: &'lease DeviceBuffer<'lease>, + conv_weights: &'lease DeviceBuffer<'lease>, + next_history: &'lease DeviceBuffer<'lease>, + h: &'lease DeviceBuffer<'lease>, + ) -> Result<[ffi::BufferHandle; 5]> { + let t = self.tokens; + let qkv = self.handle(Role::Qkv)?; + let hist = self.bind(Role::History, history, HISTORY_WORDS * F32, false)?; + let w = self.bind(Role::ConvW, conv_weights, C * 4 * F32, false)?; + let next = self.bind(Role::NextHistory, next_history, HISTORY_WORDS * F32, false)?; + let h_h = self.bind(Role::H, h, t * C * F32, false)?; + Ok([qkv, hist, w, next, h_h]) + } + /// Chunks of at most `CONV_TILE` rows: the serial walk. + fn push_conv_serial(&mut self, [qkv, hist, w, next, h_h]: [ffi::BufferHandle; 5]) -> Result<()> { + let t_arg = ffi::KernelArg::I64(self.tokens as i64); + self.push_kernel( + Kernel::Conv, + ([(C / 128) as u32, 1, 1], [128, 1, 1]), + &[ + ffi::KernelArg::Pointer(hist), + ffi::KernelArg::Pointer(next), + ffi::KernelArg::Pointer(qkv), + ffi::KernelArg::Pointer(w), + ffi::KernelArg::Pointer(h_h), + t_arg, + ], + ) + } + /// Longer chunks: the tiled kernel plus the history kernel. + fn push_conv_tiled(&mut self, [qkv, hist, w, next, h_h]: [ffi::BufferHandle; 5]) -> Result<()> { + let t = self.tokens; + let t_arg = ffi::KernelArg::I64(t as i64); + self.push_kernel( + Kernel::ConvTiled, + ([(C / 128) as u32, t.div_ceil(CONV_TILE) as u32, 1], [128, 1, 1]), + &[ + ffi::KernelArg::Pointer(hist), + ffi::KernelArg::Pointer(qkv), + ffi::KernelArg::Pointer(w), + ffi::KernelArg::Pointer(h_h), + t_arg, + ], + )?; + self.push_kernel( + Kernel::ConvHist, + ([(C / 128) as u32, 1, 1], [128, 1, 1]), + &[ffi::KernelArg::Pointer(next), ffi::KernelArg::Pointer(hist), ffi::KernelArg::Pointer(qkv), t_arg], + ) + } /// `gdn_l2`: in-place L2 normalization of the 32 Q/K heads of every row of /// `h` (the original's `rsqrtf(ss + eps)` with `eps = 1e-6`); then the scan. pub fn l2(&mut self) -> Result<()> { diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs index 28d38633..5cbb8039 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs @@ -17,28 +17,8 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { ) -> Result<()> { let result = (|| { self.ready(Step::Recurrence)?; - let t = self.tokens; - let h = self.handle(Role::H)?; - let gate = self.handle(Role::Gate)?; - let beta = self.handle(Role::Beta)?; - let s_in = self.bind(Role::StateIn, state_in, STATE_WORDS * F32, false)?; - let s_out = self.bind(Role::StateOut, state_out, STATE_WORDS * F32, false)?; - let y_h = self.bind(Role::Y, y, t * ZV * F32, false)?; - let witness = self.witness_word(GdnBatchStage::StateSteps)?; - self.push_kernel( - Kernel::RecColsPipe, - ([(HV * (S / 32)) as u32, 1, 1], [32, 4, 1]), - &[ - ffi::KernelArg::Pointer(s_in), - ffi::KernelArg::Pointer(s_out), - ffi::KernelArg::Pointer(h), - ffi::KernelArg::Pointer(gate), - ffi::KernelArg::Pointer(beta), - ffi::KernelArg::Pointer(y_h), - ffi::KernelArg::I64(t as i64), - ffi::KernelArg::Pointer(witness), - ], - )?; + let arguments = self.recurrence_arguments(state_in, state_out, y)?; + self.push_kernel(Kernel::RecColsPipe, ([(HV * (S / 32)) as u32, 1, 1], [32, 4, 1]), &arguments)?; self.scan(GdnBatchStage::NextState, Role::StateOut)?; self.scan(GdnBatchStage::Readout, Role::Y)?; self.step = self.step.next(); @@ -46,6 +26,32 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { })(); self.latch(result) } + /// Binds the recurrence operands and the per-step witness word; returns the kernel arguments in order. + fn recurrence_arguments( + &mut self, + state_in: &'lease DeviceBuffer<'lease>, + state_out: &'lease DeviceBuffer<'lease>, + y: &'lease DeviceBuffer<'lease>, + ) -> Result<[ffi::KernelArg; 8]> { + let t = self.tokens; + let h = self.handle(Role::H)?; + let gate = self.handle(Role::Gate)?; + let beta = self.handle(Role::Beta)?; + let s_in = self.bind(Role::StateIn, state_in, STATE_WORDS * F32, false)?; + let s_out = self.bind(Role::StateOut, state_out, STATE_WORDS * F32, false)?; + let y_h = self.bind(Role::Y, y, t * ZV * F32, false)?; + let witness = self.witness_word(GdnBatchStage::StateSteps)?; + Ok([ + ffi::KernelArg::Pointer(s_in), + ffi::KernelArg::Pointer(s_out), + ffi::KernelArg::Pointer(h), + ffi::KernelArg::Pointer(gate), + ffi::KernelArg::Pointer(beta), + ffi::KernelArg::Pointer(y_h), + ffi::KernelArg::I64(t as i64), + ffi::KernelArg::Pointer(witness), + ]) + } /// `gdn_out_norm`: in place on `y` (f32) plus the half image `y16` /// (`hf(v)`), gated by `z`; then the Y and Y16 scans. pub fn out_norm(&mut self, gamma: &'lease DeviceBuffer<'lease>, y16: &'lease DeviceBuffer<'lease>) -> Result<()> { @@ -120,46 +126,14 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { let write_fetch = fetch && self.refusal.is_none(); let mut fetched = staging(if write_fetch { HISTORY_WORDS * F32 } else { 0 })?; if self.commands.len() > 1 { - let context = self.batch.context; - let guard = context.enter().inspect_err(|_| { - self.batch.failed = true; - context.poisoned.set(true); - })?; - // The caller's inputs arrived by synchronous pageable H2D, which may - // return after host staging only. The program runs on the adapter's - // dedicated NON-BLOCKING stream, which the legacy default stream does - // not order against: one real context synchronization separates them. - let mut operation = context.driver.api.synchronize(); - if operation.is_ok() { - for command in &mut self.commands { - operation = command.launch(context); - if operation.is_err() { - break; - } - } - } - // Every program kernel and GEMM is on the non-blocking stream: the - // D2H below is only ordered after them by this completion fence. - let sync = context.driver.api.synchronize(); - if operation.is_ok() && sync.is_ok() { - operation = context.driver.api.copy_to(status, &mut statuses); - } - if operation.is_ok() && sync.is_ok() && write_fetch { - let source = self.fetch.ok_or(Error::InvalidQwenShape)?; - operation = context.driver.api.copy_to(source, &mut fetched); - } - let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { - self.batch.failed = true; - context.poisoned.set(true); - } - if sync.is_err() || pop.is_err() { + let fenced = self.fenced(status, &mut statuses, &mut fetched, write_fetch)?; + if fenced.uncertain { // Completion is uncertain: retain every actual argument/staging // owner and every borrowed buffer; Context poison forbids reuse. std::mem::forget((self.commands, self.held, statuses, fetched)); - return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain GDN batch drain")); + return fenced.outcome.map(|()| unreachable!("uncertain GDN batch drain")); } - combine(combine(operation, sync), pop)?; + fenced.outcome?; } let refusal = match decode_statuses(&statuses, self.checks) { Ok(refusal) => refusal, @@ -169,14 +143,78 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { return Err(error); } }; - let next_history = if write_fetch && refusal.is_none() { - let mut values = Vec::new(); - values.try_reserve_exact(HISTORY_WORDS).map_err(|_| Error::HostAllocation)?; - values.extend(fetched.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))); - Some(values.into_boxed_slice()) - } else { - None - }; + let next_history = if write_fetch && refusal.is_none() { Some(history_words(&fetched)?) } else { None }; Ok(Drained { refusal, deferred: self.refusal, next_history }) } + /// Runs the commands under one context entry, reads the status words (and the history) back and synchronizes. + /// + /// The caller's inputs arrived by synchronous pageable H2D, which may return after host staging only. The + /// program runs on the adapter's dedicated NON-BLOCKING stream, which the legacy default stream does not order + /// against: one real context synchronization separates them. Every program kernel and GEMM is on the + /// non-blocking stream: the D2H is only ordered after them by the completion fence. + fn fenced( + &mut self, + status: ffi::BufferHandle, + statuses: &mut [u8], + fetched: &mut [u8], + write_fetch: bool, + ) -> Result { + let context = self.batch.context; + let guard = context.enter().inspect_err(|_| { + self.batch.failed = true; + context.poisoned.set(true); + })?; + let api = &context.driver.api; + let mut operation = api.synchronize(); + if operation.is_ok() { + operation = self.launch_commands(); + } + let sync = api.synchronize(); + if operation.is_ok() && sync.is_ok() { + operation = api.copy_to(status, statuses); + } + if operation.is_ok() && sync.is_ok() && write_fetch { + let source = self.fetch.ok_or(Error::InvalidQwenShape)?; + operation = api.copy_to(source, fetched); + } + let pop = guard.finish(); + Ok(self.settle([operation, sync, pop])) + } + /// Launches the commands in order until one fails. + fn launch_commands(&mut self) -> Result<()> { + let context = self.batch.context; + let mut operation = Ok(()); + for command in &mut self.commands { + operation = command.launch(context); + if operation.is_err() { + break; + } + } + operation + } + /// Latches the batch and poisons the context on any failure; a failed fence or pop leaves completion uncertain. + fn settle(&mut self, [operation, sync, pop]: [Result<()>; 3]) -> Fenced { + let failed = operation.is_err() || sync.is_err() || pop.is_err(); + let uncertain = sync.is_err() || pop.is_err(); + let outcome = combine(combine(operation, sync), pop); + if failed { + self.batch.failed = true; + self.batch.context.poisoned.set(true); + } + Fenced { outcome, uncertain } + } +} + +/// The result of one fenced drain: the combined outcome and whether completion is uncertain. +struct Fenced { + outcome: Result<()>, + uncertain: bool, +} + +/// The canonical next history as words, in the order fetched. +fn history_words(fetched: &[u8]) -> Result> { + let mut values = Vec::new(); + values.try_reserve_exact(HISTORY_WORDS).map_err(|_| Error::HostAllocation)?; + values.extend(fetched.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))); + Ok(values.into_boxed_slice()) } diff --git a/crates/cuda-driver/src/gdn_native_batch/staging_fn.rs b/crates/cuda-driver/src/gdn_native_batch/staging_fn.rs index aa79687d..bebbb7cd 100644 --- a/crates/cuda-driver/src/gdn_native_batch/staging_fn.rs +++ b/crates/cuda-driver/src/gdn_native_batch/staging_fn.rs @@ -16,40 +16,46 @@ impl GdnPrefillBatch<'_> { self.functions = None; let mut result = Ok(()); if let Some(buffer) = self.status.take() { - let release = if self.context.is_poisoned() { - std::mem::forget(buffer); - Err(Error::ContextPoisoned) - } else { - buffer.release() - }; - if release.is_err() { - self.context.poisoned.set(true); - } - result = combine(result, release); + result = combine(result, self.release_status(buffer)); } let modules = std::mem::take(&mut self.modules); for module in modules.into_iter().flatten() { - let release = if self.context.is_poisoned() { - self.context.retain_driver(); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(guard) => { - let unload = self.context.driver.api.unload(module); - let pop = guard.finish(); - combine(unload, pop) - } - Err(error) => Err(error), - } - }; - if release.is_err() { - self.context.poisoned.set(true); - self.context.retain_driver(); - } - result = combine(result, release); + result = combine(result, self.release_module(module)); } result } + fn release_status(&self, buffer: DeviceBuffer<'_>) -> Result<()> { + let release = if self.context.is_poisoned() { + std::mem::forget(buffer); + Err(Error::ContextPoisoned) + } else { + buffer.release() + }; + if release.is_err() { + self.context.poisoned.set(true); + } + release + } + fn release_module(&self, module: ffi::ModuleHandle) -> Result<()> { + let release = if self.context.is_poisoned() { + self.context.retain_driver(); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(guard) => { + let unload = self.context.driver.api.unload(module); + let pop = guard.finish(); + combine(unload, pop) + } + Err(error) => Err(error), + } + }; + if release.is_err() { + self.context.poisoned.set(true); + self.context.retain_driver(); + } + release + } } impl Drop for GdnPrefillBatch<'_> { fn drop(&mut self) { diff --git a/crates/cuda-driver/src/gdn_native_batch_gpu.rs b/crates/cuda-driver/src/gdn_native_batch_gpu.rs index 4d5be8ce..fbf36731 100644 --- a/crates/cuda-driver/src/gdn_native_batch_gpu.rs +++ b/crates/cuda-driver/src/gdn_native_batch_gpu.rs @@ -41,7 +41,8 @@ struct HostGemm { calls: Cell, } -struct Fixture<'a> { +/// Device copies of the immutable inputs and the weights. +struct FixtureInputs<'a> { mixed: DeviceBuffer<'a>, mixed_h: DeviceBuffer<'a>, mixed_bf: DeviceBuffer<'a>, @@ -52,31 +53,41 @@ struct Fixture<'a> { alpha_w: DeviceBuffer<'a>, beta_w: DeviceBuffer<'a>, scratch: DeviceBuffer<'a>, + dt: DeviceBuffer<'a>, + a: DeviceBuffer<'a>, + history: DeviceBuffer<'a>, + conv_w: DeviceBuffer<'a>, + state: DeviceBuffer<'a>, + gamma: DeviceBuffer<'a>, +} +/// The buffers the program writes. +struct FixtureOutputs<'a> { qkv: DeviceBuffer<'a>, z: DeviceBuffer<'a>, ab: DeviceBuffer<'a>, - dt: DeviceBuffer<'a>, - a: DeviceBuffer<'a>, gate: DeviceBuffer<'a>, beta: DeviceBuffer<'a>, - history: DeviceBuffer<'a>, - conv_w: DeviceBuffer<'a>, next_history: DeviceBuffer<'a>, h: DeviceBuffer<'a>, - state: DeviceBuffer<'a>, next_state: DeviceBuffer<'a>, y: DeviceBuffer<'a>, - gamma: DeviceBuffer<'a>, y16: DeviceBuffer<'a>, bo: DeviceBuffer<'a>, - // host copies of the immutable inputs - host_mixed: Vec, - host_history: Vec, - host_conv_w: Vec, - host_dt: Vec, - host_a: Vec, - host_gamma: Vec, - host_state: Vec, +} +/// Host copies of the immutable inputs. +struct HostInputs { + mixed: Vec, + history: Vec, + conv_w: Vec, + dt: Vec, + a: Vec, + gamma: Vec, + state: Vec, +} +struct Fixture<'a> { + inp: FixtureInputs<'a>, + out: FixtureOutputs<'a>, + host: HostInputs, } #[test] @@ -91,24 +102,7 @@ fn strata_prefill_gdn_program_runs_in_order_refuses_earliest_and_cleans_up() { if batch.allocated_bytes() != STATUS_BYTES { return mismatch("unexpected owner charge"); } - // Serial-conv chunk, tiled-conv chunk, then the same owner again. - for tokens in [2, 70, 5] { - run_case(&context, &mut batch, tokens, Poison::default(), None)?; - } - // Earliest stage in program order wins and the owner stays usable. - run_case(&context, &mut batch, 4, Poison { z: true, ab: true, ..Poison::default() }, Some(GdnBatchStage::Z))?; - run_case(&context, &mut batch, 4, Poison { ab: true, ..Poison::default() }, Some(GdnBatchStage::Ab))?; - run_case(&context, &mut batch, 4, Poison { dt: true, ..Poison::default() }, Some(GdnBatchStage::Gate))?; - // A non-finite prior state is caught by the recurrence kernel's own witness - // before the final-state scan could see it. - run_case( - &context, - &mut batch, - 4, - Poison { state: true, ..Poison::default() }, - Some(GdnBatchStage::StateSteps), - )?; - run_case(&context, &mut batch, 3, Poison::default(), None)?; + run_cases(&context, &mut batch)?; // Admission refusals leave nothing behind. let idle = HostGemm { poison: Poison::default(), captured: RefCell::new(Captured::default()), calls: Cell::new(0) }; @@ -122,6 +116,22 @@ fn strata_prefill_gdn_program_runs_in_order_refuses_earliest_and_cleans_up() { assert_eq!(leaked, 0, "bytes still allocated after close"); } +/// The clean chunks, the earliest-refusal cases and the clean chunk after them, all on one owner. +fn run_cases(context: &Context<'_>, batch: &mut GdnPrefillBatch<'_>) -> Result<()> { + // Serial-conv chunk, tiled-conv chunk, then the same owner again. + for tokens in [2, 70, 5] { + run_case(context, batch, tokens, Poison::default(), None)?; + } + // Earliest stage in program order wins and the owner stays usable. + run_case(context, batch, 4, Poison { z: true, ab: true, ..Poison::default() }, Some(GdnBatchStage::Z))?; + run_case(context, batch, 4, Poison { ab: true, ..Poison::default() }, Some(GdnBatchStage::Ab))?; + run_case(context, batch, 4, Poison { dt: true, ..Poison::default() }, Some(GdnBatchStage::Gate))?; + // A non-finite prior state is caught by the recurrence kernel's own witness + // before the final-state scan could see it. + run_case(context, batch, 4, Poison { state: true, ..Poison::default() }, Some(GdnBatchStage::StateSteps))?; + run_case(context, batch, 3, Poison::default(), None) +} + #[path = "gdn_native_batch_gpu/bytes_of_fn.rs"] mod bytes_of_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs b/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs index 0a852eb5..238ec515 100644 --- a/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs +++ b/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs @@ -26,18 +26,7 @@ pub(super) fn f16_bits(f: f32) -> u16 { return sign | 0x7c00; } if e <= 0 { - if e < -10 { - return sign; - } - let m = man | 0x80_0000; - let shift = (14 - e) as u32; - let mut h = (m >> shift) as u16; - let rem = m & ((1 << shift) - 1); - let mid = 1 << (shift - 1); - if rem > mid || (rem == mid && h & 1 == 1) { - h += 1; - } - return sign | h; + return f16_subnormal(sign, man, e); } let mut h = ((e as u32) << 10) | (man >> 13); let rem = man & 0x1fff; @@ -46,6 +35,21 @@ pub(super) fn f16_bits(f: f32) -> u16 { } sign | h as u16 } +/// The binary16 of a magnitude below the smallest normal (`e` is the biased binary16 exponent, at most 0). +fn f16_subnormal(sign: u16, man: u32, e: i32) -> u16 { + if e < -10 { + return sign; + } + let m = man | 0x80_0000; + let shift = (14 - e) as u32; + let mut h = (m >> shift) as u16; + let rem = m & ((1 << shift) - 1); + let mid = 1 << (shift - 1); + if rem > mid || (rem == mid && h & 1 == 1) { + h += 1; + } + sign | h +} pub(super) fn f16_value(h: u16) -> f32 { let sign = ((h & 0x8000) as u32) << 16; let exp = ((h >> 10) & 0x1f) as i32; @@ -107,6 +111,17 @@ pub(super) fn reference( gamma: &[f32], state: &[f32], ) -> Reference { + let (gate, beta) = reference_gates(tokens, ab, dt, a); + let mut h = reference_conv(tokens, qkv, history, conv_w); + let next_history = reference_next_history(tokens, qkv, history); + reference_l2(tokens, &mut h); + let (next_state, mut y) = reference_recurrence(tokens, [&h, &gate, &beta], state); + let y16 = reference_out_norm(tokens, &mut y, z, gamma); + Reference { h, next_history, next_state, y, y16 } +} + +/// `gdn_gates`: the gate (softplus) and the sigmoid beta of every row. +fn reference_gates(tokens: usize, ab: &[f32], dt: &[f32], a: &[f32]) -> (Vec, Vec) { let mut gate = vec![0f32; tokens * HV]; let mut beta = vec![0f32; tokens * HV]; for t in 0..tokens { @@ -116,6 +131,11 @@ pub(super) fn reference( beta[t * HV + h] = sigm(ab[t * 2 * HV + HV + h]); } } + (gate, beta) +} + +/// `gdn_conv`: the 4-tap causal convolution + SiLU of every channel over the chunk. +fn reference_conv(tokens: usize, qkv: &[f32], history: &[f32], conv_w: &[f32]) -> Vec { let mut h = vec![0f32; tokens * C]; for c in 0..C { let (mut v0, mut v1, mut v2) = (history[c * 3], history[c * 3 + 1], history[c * 3 + 2]); @@ -127,6 +147,11 @@ pub(super) fn reference( (v0, v1, v2) = (v1, v2, x); } } + h +} + +/// The history after the chunk: the last three inputs of every channel. +fn reference_next_history(tokens: usize, qkv: &[f32], history: &[f32]) -> Vec { let mut next_history = vec![0f32; HISTORY_WORDS]; for c in 0..C { for k in 0..3 { @@ -134,6 +159,11 @@ pub(super) fn reference( next_history[c * 3 + k] = if t >= 0 { qkv[t as usize * C + c] } else { history[c * 3 + (t + 3) as usize] }; } } + next_history +} + +/// `gdn_l2`: in-place L2 normalization of the 32 Q/K heads of every row. +fn reference_l2(tokens: usize, h: &mut [f32]) { for t in 0..tokens { for head in 0..2 * 16 { let x = &mut h[t * C + head * S..t * C + head * S + S]; @@ -142,6 +172,10 @@ pub(super) fn reference( x.iter_mut().for_each(|v| *v *= scale); } } +} + +/// `gdn_rec_cols_pipe`: the whole-chunk recurrence over `[h, gate, beta]`; returns the next state and the readout. +fn reference_recurrence(tokens: usize, [h, gate, beta]: [&[f32]; 3], state: &[f32]) -> (Vec, Vec) { let mut next_state = state.to_vec(); let mut y = vec![0f32; tokens * ZV]; for head in 0..HV { @@ -166,6 +200,11 @@ pub(super) fn reference( } } } + (next_state, y) +} + +/// `gdn_out_norm`: in place on `y`, gated by `z`; returns the half image of the normalized readout. +fn reference_out_norm(tokens: usize, y: &mut [f32], z: &[f32], gamma: &[f32]) -> Vec { let mut y16 = vec![0u16; tokens * ZV]; for t in 0..tokens { for head in 0..HV { @@ -178,5 +217,5 @@ pub(super) fn reference( } } } - Reference { h, next_history, next_state, y, y16 } + y16 } diff --git a/crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs b/crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs index 1e14f770..aa718799 100644 --- a/crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs +++ b/crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs @@ -13,36 +13,12 @@ impl HostGemm { shape: GemmShape, ) -> Result<()> { self.calls.set(self.calls.get() + 1); - let mut xb = vec![0u8; x.len()]; - x.copy_to(&mut xb)?; - let mut wb = vec![0u8; w.len()]; - w.copy_to(&mut wb)?; - let mut yb = vec![0u8; y.len()]; - y.copy_to(&mut yb)?; - let value = |bits: u16| { - if bf16 { bf_value(bits) } else { f16_value(bits) } - }; - let xh = halves_of(&xb); - let wh = halves_of(&wb); + let (xb, wb, yb) = (read(x)?, read(w)?, read(y)?); + let (xh, wh) = (halves_of(&xb), halves_of(&wb)); let mut out = words_of(&yb); - let GemmShape { tokens, rows, depth, ldy, y_offset, beta } = shape; - if xh.len() < tokens * depth || wh.len() < rows * depth || out.len() < tokens * ldy { - return Err(Error::InvalidQwenShape); - } - for t in 0..tokens { - for n in 0..rows { - let mut acc = 0f32; - for k in 0..4 { - acc += value(xh[t * depth + (7 * n + k) % depth]) * value(wh[n * depth + (3 * k + n) % depth]); - } - let at = t * ldy + y_offset + n; - out[at] = acc + beta * out[at]; - } - } - if self.poison.z && rows == ZV { - out[tokens * ldy - 1] = f32::from_bits(0x7fc0_0001); - } - if self.poison.ab && rows == HV { + host_gemm(bf16, shape, [&xh, &wh], &mut out)?; + let GemmShape { tokens, rows, depth, ldy, .. } = shape; + if (self.poison.z && rows == ZV) || (self.poison.ab && rows == HV) { out[tokens * ldy - 1] = f32::from_bits(0x7fc0_0001); } y.context.driver.api.copy_from(y.handle.ok_or(Error::ContextPoisoned)?, &bytes_of(&out))?; @@ -55,6 +31,28 @@ impl HostGemm { Ok(()) } } + +/// The host stand-in of one adapter GEMM: a four-term strided dot per output word, added onto `beta * out`. +fn host_gemm(bf16: bool, shape: GemmShape, [xh, wh]: [&[u16]; 2], out: &mut [f32]) -> Result<()> { + let value = |bits: u16| { + if bf16 { bf_value(bits) } else { f16_value(bits) } + }; + let GemmShape { tokens, rows, depth, ldy, y_offset, beta } = shape; + if xh.len() < tokens * depth || wh.len() < rows * depth || out.len() < tokens * ldy { + return Err(Error::InvalidQwenShape); + } + for t in 0..tokens { + for n in 0..rows { + let mut acc = 0f32; + for k in 0..4 { + acc += value(xh[t * depth + (7 * n + k) % depth]) * value(wh[n * depth + (3 * k + n) % depth]); + } + let at = t * ldy + y_offset + n; + out[at] = acc + beta * out[at]; + } + } + Ok(()) +} impl GdnGemm for HostGemm { fn stream(&self) -> GdnStream { // The host stand-in copies synchronously on the default stream. @@ -83,25 +81,44 @@ pub(super) fn read(buffer: &DeviceBuffer<'_>) -> Result> { } impl<'a> Fixture<'a> { pub(super) fn new(context: &'a Context<'_>, tokens: usize, poison: Poison) -> Result { - let blank = |bytes: usize| upload(context, &vec![0; bytes]); + let host = HostInputs::new(tokens, poison); + let inp = FixtureInputs::new(context, tokens, &host)?; + let out = FixtureOutputs::new(context, tokens)?; + Ok(Self { inp, out, host }) + } + pub(super) fn release(self) -> Result<()> { + combine(self.inp.release(), self.out.release()) + } +} +impl HostInputs { + fn new(tokens: usize, poison: Poison) -> Self { let mut dt = vec![-2.0f32; HV]; if poison.dt { dt[0] = f32::INFINITY; } - let host_mixed = pattern(tokens * N, 1, 37, 1.0 / 32.0, 0.5); - let host_history = pattern(HISTORY_WORDS, 2, 13, 1.0 / 128.0, 0.04); - let host_conv_w: Vec = (0..4 * C).map(|i| [0.25, 0.5, -0.25, 0.125][i % 4]).collect(); - let host_a = vec![-1.0f32; HV]; - let host_gamma = pattern(S, 3, 7, 1.0 / 16.0, 0.0).iter().map(|v| v + 0.5).collect::>(); - let mut host_state = pattern(STATE_WORDS, 4, 19, 1.0 / 2048.0, 0.004); + let mut state = pattern(STATE_WORDS, 4, 19, 1.0 / 2048.0, 0.004); if poison.state { - host_state[STATE_WORDS - 1] = f32::from_bits(0x7fc0_0001); + state[STATE_WORDS - 1] = f32::from_bits(0x7fc0_0001); } + Self { + mixed: pattern(tokens * N, 1, 37, 1.0 / 32.0, 0.5), + history: pattern(HISTORY_WORDS, 2, 13, 1.0 / 128.0, 0.04), + conv_w: (0..4 * C).map(|i| [0.25, 0.5, -0.25, 0.125][i % 4]).collect(), + dt, + a: vec![-1.0f32; HV], + gamma: pattern(S, 3, 7, 1.0 / 16.0, 0.0).iter().map(|v| v + 0.5).collect(), + state, + } + } +} +impl<'a> FixtureInputs<'a> { + fn new(context: &'a Context<'_>, tokens: usize, host: &HostInputs) -> Result { + let blank = |bytes: usize| upload(context, &vec![0; bytes]); let bf16_weights = |salt: usize| -> Vec { pattern(HV * N, salt, 11, 1.0 / 64.0, 0.08).into_iter().flat_map(|v| bf_bits(v).to_le_bytes()).collect() }; Ok(Self { - mixed: upload(context, &bytes_of(&host_mixed))?, + mixed: upload(context, &bytes_of(&host.mixed))?, mixed_h: blank(tokens * N * 2)?, mixed_bf: blank(tokens * N * 2)?, mixed_bf_lo: blank(tokens * N * 2)?, @@ -111,33 +128,15 @@ impl<'a> Fixture<'a> { alpha_w: upload(context, &bf16_weights(5))?, beta_w: upload(context, &bf16_weights(6))?, scratch: blank(C * N * 2)?, - qkv: blank(tokens * C * 4)?, - z: blank(tokens * ZV * 4)?, - ab: blank(tokens * 2 * HV * 4)?, - dt: upload(context, &bytes_of(&dt))?, - a: upload(context, &bytes_of(&host_a))?, - gate: blank(tokens * HV * 4)?, - beta: blank(tokens * HV * 4)?, - history: upload(context, &bytes_of(&host_history))?, - conv_w: upload(context, &bytes_of(&host_conv_w))?, - next_history: blank(HISTORY_WORDS * 4)?, - h: blank(tokens * C * 4)?, - state: upload(context, &bytes_of(&host_state))?, - next_state: blank(STATE_WORDS * 4)?, - y: blank(tokens * ZV * 4)?, - gamma: upload(context, &bytes_of(&host_gamma))?, - y16: blank(tokens * ZV * 2)?, - bo: blank(tokens * N * 4)?, - host_mixed, - host_history, - host_conv_w, - host_dt: dt, - host_a, - host_gamma, - host_state, + dt: upload(context, &bytes_of(&host.dt))?, + a: upload(context, &bytes_of(&host.a))?, + history: upload(context, &bytes_of(&host.history))?, + conv_w: upload(context, &bytes_of(&host.conv_w))?, + state: upload(context, &bytes_of(&host.state))?, + gamma: upload(context, &bytes_of(&host.gamma))?, }) } - pub(super) fn release(self) -> Result<()> { + fn release(self) -> Result<()> { let mut result = Ok(()); for buffer in [ self.mixed, @@ -150,21 +149,47 @@ impl<'a> Fixture<'a> { self.alpha_w, self.beta_w, self.scratch, + self.dt, + self.a, + self.history, + self.conv_w, + self.state, + self.gamma, + ] { + result = combine(result, buffer.release()); + } + result + } +} +impl<'a> FixtureOutputs<'a> { + fn new(context: &'a Context<'_>, tokens: usize) -> Result { + let blank = |bytes: usize| upload(context, &vec![0; bytes]); + Ok(Self { + qkv: blank(tokens * C * 4)?, + z: blank(tokens * ZV * 4)?, + ab: blank(tokens * 2 * HV * 4)?, + gate: blank(tokens * HV * 4)?, + beta: blank(tokens * HV * 4)?, + next_history: blank(HISTORY_WORDS * 4)?, + h: blank(tokens * C * 4)?, + next_state: blank(STATE_WORDS * 4)?, + y: blank(tokens * ZV * 4)?, + y16: blank(tokens * ZV * 2)?, + bo: blank(tokens * N * 4)?, + }) + } + fn release(self) -> Result<()> { + let mut result = Ok(()); + for buffer in [ self.qkv, self.z, self.ab, - self.dt, - self.a, self.gate, self.beta, - self.history, - self.conv_w, self.next_history, self.h, - self.state, self.next_state, self.y, - self.gamma, self.y16, self.bo, ] { diff --git a/crates/cuda-driver/src/gdn_native_batch_gpu/run_case_fn.rs b/crates/cuda-driver/src/gdn_native_batch_gpu/run_case_fn.rs index 0244dcd3..2eef0391 100644 --- a/crates/cuda-driver/src/gdn_native_batch_gpu/run_case_fn.rs +++ b/crates/cuda-driver/src/gdn_native_batch_gpu/run_case_fn.rs @@ -14,67 +14,110 @@ pub(super) fn run_case( ) -> Result<()> { let fixture = Fixture::new(context, tokens, poison)?; let gemm = HostGemm { poison, captured: RefCell::new(Captured::default()), calls: Cell::new(0) }; - let result = (|| -> Result<()> { - let mut prefix = batch.begin(tokens, &gemm)?; - let program = (|| -> Result<()> { - prefix.pack_mixed(&fixture.mixed, &fixture.mixed_h, &fixture.mixed_bf, Some(&fixture.mixed_bf_lo))?; - prefix.project_qkv(GdnNativeFormat::Q8_0, &fixture.qkv_w, &fixture.scratch, &fixture.qkv)?; - prefix.project_z(GdnNativeFormat::Q8_0, &fixture.z_w, &fixture.scratch, &fixture.z)?; - prefix.project_alpha_beta(&fixture.alpha_w, &fixture.beta_w, &fixture.ab)?; - prefix.gates(&fixture.dt, &fixture.a, &fixture.gate, &fixture.beta)?; - prefix.conv(&fixture.history, &fixture.conv_w, &fixture.next_history, &fixture.h)?; - prefix.l2()?; - prefix.recurrence(&fixture.state, &fixture.next_state, &fixture.y)?; - prefix.out_norm(&fixture.gamma, &fixture.y16)?; - prefix.project_out(GdnNativeFormat::Q8_0, &fixture.out_w, &fixture.scratch, &fixture.bo) - })(); - let completion = prefix.finish(); - program?; - let completion = completion?; - if completion.numerical_refusal() != expect { - return mismatch("refusal stage differs from the expected earliest stage"); - } - // The immutable inputs are untouched in every case. - if read(&fixture.state)? != bytes_of(&fixture.host_state) - || read(&fixture.history)? != bytes_of(&fixture.host_history) - { - return mismatch("prior state or history was modified"); - } - let history = completion.into_next_history(); - if expect.is_some() { - return match history { - Err(stage) if Some(stage) == expect => Ok(()), - _ => mismatch("refused batch must withhold its history"), - }; - } - let history = history.map_err(|_| Error::InvalidDriverValue("clean batch lost its history"))?; - check_clean(&fixture, &gemm, tokens, &history) - })(); + let result = check_case(batch, &fixture, &gemm, tokens, expect); combine(result, fixture.release()) } +/// Runs the whole program on `fixture`, then compares the completion with `expect`. +fn check_case( + batch: &mut GdnPrefillBatch<'_>, + fixture: &Fixture<'_>, + gemm: &HostGemm, + tokens: usize, + expect: Option, +) -> Result<()> { + let mut prefix = batch.begin(tokens, gemm)?; + let program = push_program(&mut prefix, fixture); + let completion = prefix.finish(); + program?; + let completion = completion?; + if completion.numerical_refusal() != expect { + return mismatch("refusal stage differs from the expected earliest stage"); + } + inputs_untouched(fixture)?; + let history = completion.into_next_history(); + if expect.is_some() { + return match history { + Err(stage) if Some(stage) == expect => Ok(()), + _ => mismatch("refused batch must withhold its history"), + }; + } + let history = history.map_err(|_| Error::InvalidDriverValue("clean batch lost its history"))?; + check_clean(fixture, gemm, tokens, &history) +} + +/// The ten calls of the program, in order. +fn push_program<'lease>(prefix: &mut GdnBatchPrefix<'lease, '_>, fixture: &'lease Fixture<'lease>) -> Result<()> { + let (i, o) = (&fixture.inp, &fixture.out); + prefix.pack_mixed(&i.mixed, &i.mixed_h, &i.mixed_bf, Some(&i.mixed_bf_lo))?; + prefix.project_qkv(GdnNativeFormat::Q8_0, &i.qkv_w, &i.scratch, &o.qkv)?; + prefix.project_z(GdnNativeFormat::Q8_0, &i.z_w, &i.scratch, &o.z)?; + prefix.project_alpha_beta(&i.alpha_w, &i.beta_w, &o.ab)?; + prefix.gates(&i.dt, &i.a, &o.gate, &o.beta)?; + prefix.conv(&i.history, &i.conv_w, &o.next_history, &o.h)?; + prefix.l2()?; + prefix.recurrence(&i.state, &o.next_state, &o.y)?; + prefix.out_norm(&i.gamma, &o.y16)?; + prefix.project_out(GdnNativeFormat::Q8_0, &i.out_w, &i.scratch, &o.bo) +} + +/// The immutable inputs are untouched in every case. +fn inputs_untouched(fixture: &Fixture<'_>) -> Result<()> { + if read(&fixture.inp.state)? != bytes_of(&fixture.host.state) + || read(&fixture.inp.history)? != bytes_of(&fixture.host.history) + { + return mismatch("prior state or history was modified"); + } + Ok(()) +} + pub(super) fn check_clean(f: &Fixture<'_>, gemm: &HostGemm, tokens: usize, next_history: &[f32]) -> Result<()> { // Five projections' FP16 matrices, the images and four GEMM calls with the lo pass. let captured = gemm.captured.borrow(); if gemm.calls.get() != 3 + 4 || captured.x.len() != 7 { return mismatch("unexpected GEMM call sequence"); } - // Dequantization is exact against the host transcription of group32<8>. + check_dequantized(&captured)?; + check_images(f)?; + // Downstream kernels against the host reference built from the adapter's own outputs. + let want = host_reference(f, &captured, tokens)?; + if next_history != want.next_history.as_slice() { + return mismatch("next history is not the exact last three inputs"); + } + let y16 = check_outputs(f, &want)?; + // The Out GEMM consumed exactly the device y16. + let last = captured.x.last().ok_or(Error::InvalidDriverValue("out call missing"))?; + if last.0 != ZV || halves_of(&last.1) != y16 { + return mismatch("Out GEMM did not read the y16 image"); + } + Ok(()) +} + +/// Dequantization is exact against the host transcription of group32<8>. +fn check_dequantized(captured: &Captured) -> Result<()> { for ((rows, half), (r, c, salt)) in captured.scratch.iter().zip([(C, N, 1usize), (ZV, N, 2), (N, ZV, 3)]) { if *rows != r || half != &q8_0(r, c, salt).1 { return mismatch("dequantized FP16 weights differ from the original group32"); } } - // The images of `mixed`. + Ok(()) +} + +/// The images of `mixed`. +fn check_images(f: &Fixture<'_>) -> Result<()> { let (h_img, bf_img, lo_img) = - (halves_of(&read(&f.mixed_h)?), halves_of(&read(&f.mixed_bf)?), halves_of(&read(&f.mixed_bf_lo)?)); - for (i, &s) in f.host_mixed.iter().enumerate() { + (halves_of(&read(&f.inp.mixed_h)?), halves_of(&read(&f.inp.mixed_bf)?), halves_of(&read(&f.inp.mixed_bf_lo)?)); + for (i, &s) in f.host.mixed.iter().enumerate() { let hi = bf_bits(s); if h_img[i] != f16_bits(s) || bf_img[i] != hi || lo_img[i] != bf_bits(s - bf_value(hi)) { return mismatch("mixed images differ from bf()/bf_lo()/hf()"); } } - // Downstream kernels against the host reference built from the adapter's own outputs. + Ok(()) +} + +/// The host reference built from the adapter's own qkv, z and (last) interleaved ab outputs. +fn host_reference(f: &Fixture<'_>, captured: &Captured, tokens: usize) -> Result { let by_rows = |rows: usize, nth: usize| -> Option<&Vec> { captured.y.iter().filter(|(r, _)| *r == rows).nth(nth).map(|(_, y)| y) }; @@ -88,25 +131,16 @@ pub(super) fn check_clean(f: &Fixture<'_>, gemm: &HostGemm, tokens: usize, next_ .find(|(r, _)| *r == HV) .map(|(_, y)| y) .ok_or(Error::InvalidDriverValue("ab calls missing"))?; - let want = reference( - tokens, - qkv, - z, - ab, - &f.host_history, - &f.host_conv_w, - &f.host_dt, - &f.host_a, - &f.host_gamma, - &f.host_state, - ); - if next_history != want.next_history.as_slice() { - return mismatch("next history is not the exact last three inputs"); - } - let h = words_of(&read(&f.h)?); - let state = words_of(&read(&f.next_state)?); - let y = words_of(&read(&f.y)?); - let y16 = halves_of(&read(&f.y16)?); + let host = &f.host; + Ok(reference(tokens, qkv, z, ab, &host.history, &host.conv_w, &host.dt, &host.a, &host.gamma, &host.state)) +} + +/// The device outputs against the reference; returns the `y16` image for the Out GEMM comparison. +fn check_outputs(f: &Fixture<'_>, want: &Reference) -> Result> { + let h = words_of(&read(&f.out.h)?); + let state = words_of(&read(&f.out.next_state)?); + let y = words_of(&read(&f.out.y)?); + let y16 = halves_of(&read(&f.out.y16)?); for (name, got, expected) in [("conv+l2", &h, &want.h), ("next state", &state, &want.next_state), ("normalized output", &y, &want.y)] { @@ -122,10 +156,5 @@ pub(super) fn check_clean(f: &Fixture<'_>, gemm: &HostGemm, tokens: usize, next_ if y16.iter().zip(&want.y16).any(|(g, e)| !close(f16_value(*g), f16_value(*e), 4e-3)) { return mismatch("y16 differs from the host reference"); } - // The Out GEMM consumed exactly the device y16. - let last = captured.x.last().ok_or(Error::InvalidDriverValue("out call missing"))?; - if last.0 != ZV || halves_of(&last.1) != y16 { - return mismatch("Out GEMM did not read the y16 image"); - } - Ok(()) + Ok(y16) } diff --git a/crates/cuda-driver/src/gdn_state_finite_guard.rs b/crates/cuda-driver/src/gdn_state_finite_guard.rs index 6d23ca97..566e72b3 100644 --- a/crates/cuda-driver/src/gdn_state_finite_guard.rs +++ b/crates/cuda-driver/src/gdn_state_finite_guard.rs @@ -33,30 +33,32 @@ impl<'ctx> GdnStateFiniteGuard<'ctx> { return Err(Error::BudgetExceeded); } let mut owner = Self { context, status: None, module: None, functions: None, failed: false }; - let result = (|| { - owner.status = Some(context.allocate(STATUS_BYTES)?); - let guard = context.enter()?; - let load = (|| { - // This existing loader validates the immutable asset digest/NUL. - let module = context.driver.api.load_mmq_resident()?; - owner.module = Some(module); - owner.functions = Some([ - context.driver.api.mmq_resident_function(module, 0)?, - context.driver.api.mmq_resident_function(module, 1)?, - ]); - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poisoned.set(true); - } - combine(load, pop) - })(); + let result = owner.open(); if let Err(error) = result { return combine(Err(error), owner.close()); } Ok(owner) } + /// Allocates the status word and loads the helper module under the context; the restore failing poisons it. + fn open(&mut self) -> Result<()> { + let context = self.context; + self.status = Some(context.allocate(STATUS_BYTES)?); + let guard = context.enter()?; + let load = self.load(); + let pop = guard.finish(); + if pop.is_err() { + context.poisoned.set(true); + } + combine(load, pop) + } + fn load(&mut self) -> Result<()> { + // This existing loader validates the immutable asset digest/NUL. + let api = &self.context.driver.api; + let module = api.load_mmq_resident()?; + self.module = Some(module); + self.functions = Some([api.mmq_resident_function(module, 0)?, api.mmq_resident_function(module, 1)?]); + Ok(()) + } /// Whether this guard refused or lost its owners (a failed guard is never reused). pub fn is_failed(&self) -> bool { @@ -72,6 +74,35 @@ impl<'ctx> GdnStateFiniteGuard<'ctx> { /// `Err` retains driver/admission errors, with CUDA uncertainty fenced. /// No capability asserting causal origin or committed state is minted here. pub fn check_next_state(&mut self, next: &DeviceBuffer<'_>) -> Result { + let (functions, source, status) = self.admit_next(next)?; + // Stable boxed ABI arguments and owned staging precede all CUDA work. + let mut reset = ffi::MmqResidentArguments::zero(status, 1); + let mut scan = ffi::MmqResidentArguments::finite(source, status, 0, STATE_WORDS, 0); + let mut staging = Vec::new(); + staging.try_reserve_exact(STATUS_BYTES).map_err(|_| Error::HostAllocation)?; + staging.resize(STATUS_BYTES, 0); + let guard = self.context.enter()?; + let operation = self.launch_scan(functions, status, (&mut reset, &mut scan), &mut staging); + let sync = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if operation.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + self.context.poisoned.set(true); + } + if sync.is_err() || pop.is_err() { + // Completion is uncertain: retain all actual argument/staging owners. + // Context poison prevents state/status release or subsequent reuse. + std::mem::forget((reset, scan, staging)); + return combine(combine(operation, sync), pop).map(|()| false); + } + combine(combine(operation, sync), pop)?; + self.witness(&staging) + } + /// Admission of the owner state and status buffers; returns the two functions and the state and status handles. + fn admit_next( + &self, + next: &DeviceBuffer<'_>, + ) -> Result<([ffi::FunctionHandle; 2], ffi::BufferHandle, ffi::BufferHandle)> { if self.failed || self.context.is_poisoned() || self.context.handle.is_none() { return Err(Error::ContextPoisoned); } @@ -93,33 +124,28 @@ impl<'ctx> GdnStateFiniteGuard<'ctx> { if source.overlaps(STATE_BYTES, status, STATUS_BYTES) { return Err(Error::OutputAliasesInput); } - // Stable boxed ABI arguments and owned staging precede all CUDA work. - let mut reset = ffi::MmqResidentArguments::zero(status, 1); - let mut scan = ffi::MmqResidentArguments::finite(source, status, 0, STATE_WORDS, 0); - let mut staging = Vec::new(); - staging.try_reserve_exact(STATUS_BYTES).map_err(|_| Error::HostAllocation)?; - staging.resize(STATUS_BYTES, 0); - let guard = self.context.enter()?; - let mut operation = self.context.driver.api.launch_mmq_resident(functions[0], 1, &mut reset); + Ok((functions, source, status)) + } + /// Zeroes the status word, scans the whole state and reads the word back. + fn launch_scan( + &self, + functions: [ffi::FunctionHandle; 2], + status: ffi::BufferHandle, + arguments: (&mut ffi::MmqResidentArguments, &mut ffi::MmqResidentArguments), + staging: &mut [u8], + ) -> Result<()> { + let api = &self.context.driver.api; + let mut operation = api.launch_mmq_resident(functions[0], 1, arguments.0); if operation.is_ok() { - operation = self.context.driver.api.launch_mmq_resident(functions[1], STATE_WORDS, &mut scan); + operation = api.launch_mmq_resident(functions[1], STATE_WORDS, arguments.1); } if operation.is_ok() { - operation = self.context.driver.api.copy_to(status, &mut staging); + operation = api.copy_to(status, staging); } - let sync = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { - self.failed = true; - self.context.poisoned.set(true); - } - if sync.is_err() || pop.is_err() { - // Completion is uncertain: retain all actual argument/staging owners. - // Context poison prevents state/status release or subsequent reuse. - std::mem::forget((reset, scan, staging)); - return combine(combine(operation, sync), pop).map(|()| false); - } - combine(combine(operation, sync), pop)?; + operation + } + /// `true` for a clean scan, `false` for a completed numerical refusal; any other word fails the guard. + fn witness(&mut self, staging: &[u8]) -> Result { match u32::from_le_bytes(staging.as_chunks::<4>().0[0]) { 0 => Ok(true), 1 => Ok(false), From 0be6c1596179b78dcfd898acbc93638dc38e81f9 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 23:17:30 +0100 Subject: [PATCH 6/7] STRA-338 size2 cd1: GR batch workspace and microbatch read, prompt device, fused t1 smoke and gpu report split into phases --- .../impl_gdnfusedprefix_2_2.rs | 16 +- crates/cuda-driver/src/gdn_fused_t1_gpu.rs | 211 +++++++++---- .../impl_originalgdnpromptdevice_2.rs | 48 +-- .../impl_originalgdnpromptdevice_3.rs | 61 ++-- crates/cuda-driver/src/gpu_report.rs | 134 +++++---- .../src/gr_batch_inject_workspace.rs | 276 +++++++++++------- .../src/gr_batch_inject_workspace_gpu.rs | 204 +++++++------ .../impl_grmicrobatchread_2.rs | 135 +++++---- 8 files changed, 654 insertions(+), 431 deletions(-) diff --git a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs index b4d711bb..4d79227c 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs @@ -101,9 +101,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { let fetched = (&mut fetched_state[..], &mut fetched_history[..]); let fenced = self.fenced(status, &mut statuses, fetched, write_fetch)?; if fenced.uncertain { - // Completion is uncertain: retain every actual argument/staging owner. The borrowed buffers are - // kept alive by the poisoned context (it refuses to enter, so their frees leak instead of racing - // the device). + // Completion is uncertain: retain every actual argument/staging owner (see `Fenced`). std::mem::forget((self.commands, self.held, statuses, fetched_state, fetched_history)); return fenced.outcome.map(|()| unreachable!("uncertain fused GDN T1 drain")); } @@ -117,11 +115,9 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { return Err(error); } }; - let fetched = if write_fetch && refusal.is_none() { - Some(candidate_words(&fetched_state, &fetched_history)?) - } else { - None - }; + let fetched = (write_fetch && refusal.is_none()) + .then(|| candidate_words(&fetched_state, &fetched_history)) + .transpose()?; Ok(Drained { refusal, deferred: self.refusal, fetched }) } /// Runs the commands on the default stream under one context entry, reads the status words (and the candidate @@ -194,7 +190,9 @@ fn candidate_words(state: &[u8], history: &[u8]) -> Result<(Box<[f32]>, Box<[f32 Ok((words::(state, f32::from_le_bytes)?, words::(history, f32::from_le_bytes)?)) } -/// The result of one fenced drain: the combined outcome and whether completion is uncertain. +/// The result of one fenced drain: the combined outcome and whether completion is uncertain. When it is, the caller +/// retains every actual argument/staging owner; the borrowed buffers are kept alive by the poisoned context (it +/// refuses to enter, so their frees leak instead of racing the device). struct Fenced { outcome: Result<()>, uncertain: bool, diff --git a/crates/cuda-driver/src/gdn_fused_t1_gpu.rs b/crates/cuda-driver/src/gdn_fused_t1_gpu.rs index c362ee3a..f8e623fd 100644 --- a/crates/cuda-driver/src/gdn_fused_t1_gpu.rs +++ b/crates/cuda-driver/src/gdn_fused_t1_gpu.rs @@ -71,6 +71,13 @@ struct Reference { state: Vec, } fn reference(c: &Case) -> Reference { + let (history, h) = reference_conv_l2(c); + let (gate, beta) = reference_ab(c); + let (state, y) = reference_step_norm(c, &h, [&gate, &beta]); + Reference { history, h, gate, beta, y, state } +} +/// `fused_gdn_conv_l2`: the convolution + SiLU of every channel (updating the history) and the L2 norms of Q/K. +fn reference_conv_l2(c: &Case) -> (Vec, Vec) { let mut history = c.history.clone(); let mut h = vec![0f32; C]; for ch in 0..C { @@ -88,6 +95,10 @@ fn reference(c: &Case) -> Reference { *v *= scale; } } + (history, h) +} +/// `fused_gdn_ab`: gate = softplus(alpha . x + dt) * ssm_a, beta = sigmoid(beta . x). +fn reference_ab(c: &Case) -> (Vec, Vec) { let mut gate = vec![0f32; HV]; let mut beta = vec![0f32; HV]; for r in 0..HV { @@ -102,6 +113,10 @@ fn reference(c: &Case) -> Reference { gate[r] = sp * c.a[r]; beta[r] = 1.0 / (1.0 + (-ab).exp()); } + (gate, beta) +} +/// `fused_gdn_step_norm`: the in-place state update, the readout and the per-head norm / ssm_norm / sigmoid(z) gate. +fn reference_step_norm(c: &Case, h: &[f32], [gate, beta]: [&[f32]; 2]) -> (Vec, Vec) { let mut state = c.state.clone(); let mut y = vec![0f32; VALUES]; for head in 0..HV { @@ -129,7 +144,7 @@ fn reference(c: &Case) -> Reference { y[head * S + col] = oc[col] * scale * c.gamma[col] / (1.0 + (-zz).exp()); } } - Reference { history, h, gate, beta, y, state } + (state, y) } const QK: usize = 2048; const HK: usize = 16; @@ -169,64 +184,126 @@ fn run( from_resident: bool, poison_qkv: bool, ) -> Result> { - let mut qkv = c.qkv.clone(); - if poison_qkv { - qkv[17] = f32::NAN; - } - let qkv_b = upload(context, &qkv)?; - let z_b = upload(context, &c.z)?; - let hist_b = upload(context, &c.history)?; - let conv_b = upload(context, &c.conv)?; - let h_b = context.allocate(C * 4)?; - let mixed_b = upload(context, &c.mixed)?; - let wa_b = upload_bf(context, &c.wa)?; - let wb_b = upload_bf(context, &c.wb)?; - let dt_b = upload(context, &c.dt)?; - let a_b = upload(context, &c.a)?; - let gate_b = context.allocate(HV * 4)?; - let beta_b = context.allocate(HV * 4)?; - let gamma_b = upload(context, &c.gamma)?; - let y_b = context.allocate(VALUES * 4)?; - let resident = upload(context, &c.state)?; - let next_state = if from_resident { context.allocate(STATE_WORDS * 4)? } else { upload(context, &c.state)? }; - let refusal = (|| -> Result> { - let mut prefix = owner.begin()?; - prefix.scan_inputs(&qkv_b, &z_b)?; - prefix.seed_state(if from_resident { Some(&resident) } else { None }, &next_state)?; - prefix.conv_l2(&hist_b, &conv_b, &h_b, EPS)?; - prefix.ab(&mixed_b, &wa_b, &wb_b, &dt_b, &a_b, &gate_b, &beta_b)?; - prefix.step_norm(&gamma_b, &y_b, EPS)?; - prefix.fetch_candidate()?; - let completion = prefix.finish()?; - if let Some(stage) = completion.numerical_refusal() { - return Ok(Some(stage)); - } - let (state, history) = completion.into_fetched().map_err(|_| Error::InvalidQwenShape)?; - let want = reference(c); - close("history", &history, &want.history)?; - close("state", &state, &want.state)?; - close("h", &download(&h_b, C)?, &want.h)?; - close("gate", &download(&gate_b, HV)?, &want.gate)?; - close("beta", &download(&beta_b, HV)?, &want.beta)?; - close("y", &download(&y_b, VALUES)?, &want.y)?; - // The immutable prior (bound only on the key-hit run) is never written. - if from_resident && download(&resident, STATE_WORDS)? != c.state { - return mismatch("resident prior state was modified"); - } - Ok(None) - })(); - let mut cleanup = Ok(()); - for buffer in [ - qkv_b, z_b, hist_b, conv_b, h_b, mixed_b, wa_b, wb_b, dt_b, a_b, gate_b, beta_b, gamma_b, y_b, resident, - next_state, - ] { - cleanup = combine(cleanup, buffer.release()); - } + let buffers = RunBuffers::upload(context, c, from_resident, poison_qkv)?; + let refusal = drive(owner, &buffers, c, from_resident); + let cleanup = buffers.release(); let refusal = refusal?; cleanup?; Ok(refusal) } +/// Every device buffer of one run. +struct RunBuffers<'c> { + qkv: DeviceBuffer<'c>, + z: DeviceBuffer<'c>, + hist: DeviceBuffer<'c>, + conv: DeviceBuffer<'c>, + h: DeviceBuffer<'c>, + mixed: DeviceBuffer<'c>, + wa: DeviceBuffer<'c>, + wb: DeviceBuffer<'c>, + dt: DeviceBuffer<'c>, + a: DeviceBuffer<'c>, + gate: DeviceBuffer<'c>, + beta: DeviceBuffer<'c>, + gamma: DeviceBuffer<'c>, + y: DeviceBuffer<'c>, + resident: DeviceBuffer<'c>, + next_state: DeviceBuffer<'c>, +} + +impl<'c> RunBuffers<'c> { + fn upload(context: &'c Context<'c>, c: &Case, from_resident: bool, poison_qkv: bool) -> Result { + let mut qkv = c.qkv.clone(); + if poison_qkv { + qkv[17] = f32::NAN; + } + Ok(Self { + qkv: upload(context, &qkv)?, + z: upload(context, &c.z)?, + hist: upload(context, &c.history)?, + conv: upload(context, &c.conv)?, + h: context.allocate(C * 4)?, + mixed: upload(context, &c.mixed)?, + wa: upload_bf(context, &c.wa)?, + wb: upload_bf(context, &c.wb)?, + dt: upload(context, &c.dt)?, + a: upload(context, &c.a)?, + gate: context.allocate(HV * 4)?, + beta: context.allocate(HV * 4)?, + gamma: upload(context, &c.gamma)?, + y: context.allocate(VALUES * 4)?, + resident: upload(context, &c.state)?, + next_state: if from_resident { context.allocate(STATE_WORDS * 4)? } else { upload(context, &c.state)? }, + }) + } + + /// Releases every buffer in upload order; failures fold in order. + fn release(self) -> Result<()> { + let mut cleanup = Ok(()); + for buffer in [ + self.qkv, + self.z, + self.hist, + self.conv, + self.h, + self.mixed, + self.wa, + self.wb, + self.dt, + self.a, + self.gate, + self.beta, + self.gamma, + self.y, + self.resident, + self.next_state, + ] { + cleanup = combine(cleanup, buffer.release()); + } + cleanup + } +} + +/// The whole program over `b`: the refusal stage, or none once the candidate matched the host reference. +fn drive<'c>( + owner: &mut GdnFusedT1<'_>, + b: &'c RunBuffers<'c>, + c: &Case, + from_resident: bool, +) -> Result> { + let mut prefix = owner.begin()?; + prefix.scan_inputs(&b.qkv, &b.z)?; + prefix.seed_state(if from_resident { Some(&b.resident) } else { None }, &b.next_state)?; + prefix.conv_l2(&b.hist, &b.conv, &b.h, EPS)?; + prefix.ab(&b.mixed, &b.wa, &b.wb, &b.dt, &b.a, &b.gate, &b.beta)?; + prefix.step_norm(&b.gamma, &b.y, EPS)?; + prefix.fetch_candidate()?; + let completion = prefix.finish()?; + if let Some(stage) = completion.numerical_refusal() { + return Ok(Some(stage)); + } + let (state, history) = completion.into_fetched().map_err(|_| Error::InvalidQwenShape)?; + check_candidate(b, c, from_resident, (&state, &history))?; + Ok(None) +} + +/// The fetched candidate and the device intermediates against the host reference; the resident prior is untouched. +fn check_candidate(b: &RunBuffers<'_>, c: &Case, from_resident: bool, fetched: (&[f32], &[f32])) -> Result<()> { + let want = reference(c); + close("history", fetched.1, &want.history)?; + close("state", fetched.0, &want.state)?; + close("h", &download(&b.h, C)?, &want.h)?; + close("gate", &download(&b.gate, HV)?, &want.gate)?; + close("beta", &download(&b.beta, HV)?, &want.beta)?; + close("y", &download(&b.y, VALUES)?, &want.y)?; + // The immutable prior (bound only on the key-hit run) is never written. + if from_resident && download(&b.resident, STATE_WORDS)? != c.state { + return mismatch("resident prior state was modified"); + } + Ok(()) +} + #[test] #[ignore = "Root-only GPU qualification; never run by the source owner"] fn original_fused_t1_gdn_program_runs_in_order_refuses_earliest_and_cleans_up() { @@ -241,22 +318,30 @@ fn original_fused_t1_gdn_program_runs_in_order_refuses_earliest_and_cleans_up() } let c = case(); // Candidate seeded by a host upload (key miss), then by the device copy of the resident mirror (key hit). - if run(&context, &mut owner, &c, false, false)?.is_some() { - return mismatch("unexpected refusal (miss)"); - } - if run(&context, &mut owner, &c, true, false)?.is_some() { - return mismatch("unexpected refusal (hit)"); - } + expect_clean(&context, &mut owner, &c, false, "unexpected refusal (miss)")?; + expect_clean(&context, &mut owner, &c, true, "unexpected refusal (hit)")?; // A non-finite projected QKV is the earliest refusal and the owner stays usable. if run(&context, &mut owner, &c, false, true)? != Some(GdnFusedStage::Qkv) { return mismatch("non-finite qkv not refused at the first stage"); } - if run(&context, &mut owner, &c, true, false)?.is_some() { - return mismatch("owner unusable after a refusal"); - } + expect_clean(&context, &mut owner, &c, true, "owner unusable after a refusal")?; owner.close() })(); let leaked = context.allocated_bytes(); assert!(result.is_ok(), "{result:?}"); assert_eq!(leaked, 0, "bytes still allocated after close"); } + +/// One clean run: no refusal, or `what`. +fn expect_clean( + context: &Context<'_>, + owner: &mut GdnFusedT1<'_>, + c: &Case, + from_resident: bool, + what: &'static str, +) -> Result<()> { + if run(context, owner, c, from_resident, false)?.is_some() { + return mismatch(what); + } + Ok(()) +} diff --git a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2.rs index 800ffcde..0fc3c07d 100644 --- a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2.rs +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2.rs @@ -15,15 +15,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { capacity: usize, profile: crate::GrNativeProfile, ) -> Result { - let required = Self::device_bytes(capacity)?.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if context.is_poisoned() { - return Err(Error::ContextPoisoned); - } - if context.allocated_bytes().checked_add(required).is_none_or(|x| x > context.budget_bytes()) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } + Self::admit_budget(context, capacity)?; let mut owner = Self { context, capacity, @@ -34,23 +26,39 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { stage: None, failed: false, }; - let operation = (|| -> Result<()> { - owner.batch = Some(context.gdn_prefill_batch_for_prompt(capacity)?); - owner.scratch = Some(context.allocate(SCRATCH)?); - for slot in &mut owner.history { - *slot = Some(context.allocate(HISTORY)?) - } - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); + let operation = owner.open(); if let Err(e) = operation { let _ = owner.close(); return Err(e); } Ok(owner) } + /// The device budget and the free memory must cover the owner plus its reserve. + fn admit_budget(context: &'ctx Context<'ctx>, capacity: usize) -> Result<()> { + let required = Self::device_bytes(capacity)?.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if context.allocated_bytes().checked_add(required).is_none_or(|x| x > context.budget_bytes()) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + /// Creates the batch owner, the scratch and the two history buffers. + fn open(&mut self) -> Result<()> { + let context = self.context; + self.batch = Some(context.gdn_prefill_batch_for_prompt(self.capacity)?); + self.scratch = Some(context.allocate(SCRATCH)?); + for slot in &mut self.history { + *slot = Some(context.allocate(HISTORY)?) + } + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + } pub fn is_failed(&self) -> bool { self.failed || self.context.is_poisoned() || self.batch.as_ref().is_none_or(GdnPrefillBatch::is_failed) } diff --git a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_3.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_3.rs index 9d2ff333..b2be42ec 100644 --- a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_3.rs +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_3.rs @@ -3,6 +3,16 @@ #[allow(unused_imports)] use super::*; +/// Releases one buffer, or leaks it when the context is poisoned (nothing may be freed against an uncertain one). +fn release_buffer(context: &Context<'_>, b: DeviceBuffer<'_>) -> Result<()> { + if context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + b.release() + } +} + impl<'ctx> OriginalGdnPromptDevice<'ctx> { pub fn close(mut self) -> Result<()> { self.close_inner() @@ -11,37 +21,13 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { self.failed = true; let mut result = Ok(()); for b in self.history.iter_mut().filter_map(Option::take).chain(self.scratch.take()) { - let r = if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - b.release() - }; - result = combine(result, r); + result = combine(result, release_buffer(self.context, b)); } if let Some(m) = self.stage.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - std::mem::forget(m); - Err(e) - } - } - }; - result = combine(result, r); + result = combine(result, self.release_stage(m)); } if let Some(b) = self.batch.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - b.close() - }; - result = combine(result, r); + result = combine(result, self.release_batch(b)); } if result.is_err() { self.context.poison(); @@ -49,4 +35,25 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { } result } + fn release_stage(&self, m: KernelModule) -> Result<()> { + if self.context.is_poisoned() { + std::mem::forget(m); + return Err(Error::ContextPoisoned); + } + match self.context.enter() { + Ok(g) => combine(m.close(), g.finish()), + Err(e) => { + std::mem::forget(m); + Err(e) + } + } + } + fn release_batch(&self, b: GdnPrefillBatch<'ctx>) -> Result<()> { + if self.context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + b.close() + } + } } diff --git a/crates/cuda-driver/src/gpu_report.rs b/crates/cuda-driver/src/gpu_report.rs index 21b5c87a..e2dac3cb 100644 --- a/crates/cuda-driver/src/gpu_report.rs +++ b/crates/cuda-driver/src/gpu_report.rs @@ -52,72 +52,98 @@ mod imp { } } + /// The driver entry points the report calls. + struct Api { + init: Init, + count: Count, + get: Get, + name: Name, + total: TotalMem, + attr: Attr, + version: Version, + } + pub(super) fn report() -> Vec { // SAFETY: fixed library name; the handle is closed below. let handle = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW) }; if handle.is_null() { return Vec::new(); } - let lines = (|| { - // SAFETY: fixed driver symbol names, paired with their documented signatures. - let (init, count, get, name, total, attr, version) = unsafe { - ( - symbol::(handle, c"cuInit")?, - symbol::(handle, c"cuDeviceGetCount")?, - symbol::(handle, c"cuDeviceGet")?, - symbol::(handle, c"cuDeviceGetName")?, - symbol::(handle, c"cuDeviceTotalMem_v2")?, - symbol::(handle, c"cuDeviceGetAttribute")?, - symbol::(handle, c"cuDriverGetVersion")?, - ) - }; - let sm86_build = cfg!(feature = "sm86"); - let mut lines = Vec::new(); - let (mut n, mut v) = (0, 0); - // SAFETY: valid writable outputs for every driver call below; devices are queried by ordinals the driver just counted. - unsafe { - if init(0) != 0 || count(&mut n) != 0 { - return None; - } - let _ = version(&mut v); - lines.push(format!( - "gpu: CUDA driver {}.{}, {n} device(s), sm_86 companions in this build: {}, chain kernels: {}", - v / 1000, - v % 1000 / 10, - if sm86_build { "yes" } else { "no" }, - std::env::var("LELEKA_CHAIN").unwrap_or_else(|_| "default".to_owned()) - )); - for ordinal in 0..n { - let mut dev = 0; - if get(&mut dev, ordinal) != 0 { - continue; - } - let mut label = [0 as c_char; 128]; - let label = if name(label.as_mut_ptr(), 128, dev) == 0 { - CStr::from_ptr(label.as_ptr()).to_string_lossy().into_owned() - } else { - "unknown model".to_owned() - }; - let (mut major, mut minor, mut sms, mut bytes) = (0, 0, 0, 0usize); - let _ = attr(&mut major, 75, dev); - let _ = attr(&mut minor, 76, dev); - let _ = attr(&mut sms, 16, dev); - let _ = total(&mut bytes, dev); - let (set, mmq) = kernel_set(major, minor, sm86_build); - lines.push(format!( - "gpu {ordinal}: {label}, cc {major}.{minor}, {sms} SMs, {:.1} GiB; kernels: {set}; MMQ launch: {mmq}", - bytes as f64 / f64::from(1u32 << 30) - )); - } - } - Some(lines) - })(); + let lines = load_api(handle).and_then(|api| device_lines(&api)); // SAFETY: the handle returned above, closed exactly once. unsafe { libc::dlclose(handle); } lines.unwrap_or_default() } + + fn load_api(handle: *mut c_void) -> Option { + // SAFETY: fixed driver symbol names, paired with their documented signatures. + unsafe { + Some(Api { + init: symbol::(handle, c"cuInit")?, + count: symbol::(handle, c"cuDeviceGetCount")?, + get: symbol::(handle, c"cuDeviceGet")?, + name: symbol::(handle, c"cuDeviceGetName")?, + total: symbol::(handle, c"cuDeviceTotalMem_v2")?, + attr: symbol::(handle, c"cuDeviceGetAttribute")?, + version: symbol::(handle, c"cuDriverGetVersion")?, + }) + } + } + + fn device_lines(api: &Api) -> Option> { + let sm86_build = cfg!(feature = "sm86"); + let mut lines = Vec::new(); + let (mut n, mut v) = (0, 0); + // SAFETY: valid writable outputs for every driver call below; devices are queried by ordinals the driver + // just counted. + unsafe { + if (api.init)(0) != 0 || (api.count)(&mut n) != 0 { + return None; + } + let _ = (api.version)(&mut v); + lines.push(format!( + "gpu: CUDA driver {}.{}, {n} device(s), sm_86 companions in this build: {}, chain kernels: {}", + v / 1000, + v % 1000 / 10, + if sm86_build { "yes" } else { "no" }, + std::env::var("LELEKA_CHAIN").unwrap_or_else(|_| "default".to_owned()) + )); + for ordinal in 0..n { + let mut dev = 0; + if (api.get)(&mut dev, ordinal) != 0 { + continue; + } + lines.push(device_line(api, ordinal, dev, sm86_build)); + } + } + Some(lines) + } + + /// The `gpu ` line of one device: name, compute capability, SM count, memory and the kernel set. + fn device_line(api: &Api, ordinal: c_int, dev: c_int, sm86_build: bool) -> String { + // SAFETY: valid writable outputs for every driver call below; `dev` was just returned by the driver. + unsafe { + let mut label = [0 as c_char; 128]; + let label = if (api.name)(label.as_mut_ptr(), 128, dev) == 0 { + CStr::from_ptr(label.as_ptr()).to_string_lossy().into_owned() + } else { + "unknown model".to_owned() + }; + let (mut major, mut minor, mut sms, mut bytes) = (0, 0, 0, 0usize); + let _ = (api.attr)(&mut major, 75, dev); + let _ = (api.attr)(&mut minor, 76, dev); + let _ = (api.attr)(&mut sms, 16, dev); + let _ = (api.total)(&mut bytes, dev); + let (set, mmq) = kernel_set(major, minor, sm86_build); + format!( + "gpu {ordinal}: {label}, cc {major}.{minor}, {sms} SMs, {:.1} GiB; \ + kernels: {set}; MMQ launch: {mmq}", + bytes as f64 / f64::from(1u32 << 30) + ) + } + } } #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] diff --git a/crates/cuda-driver/src/gr_batch_inject_workspace.rs b/crates/cuda-driver/src/gr_batch_inject_workspace.rs index e66f352d..c53d34a0 100644 --- a/crates/cuda-driver/src/gr_batch_inject_workspace.rs +++ b/crates/cuda-driver/src/gr_batch_inject_workspace.rs @@ -54,6 +54,23 @@ fn layout(shape: GrBatchInjectShape) -> Result { } impl<'ctx> GrBatchInjectWorkspace<'ctx> { fn new(context: &'ctx Context<'ctx>) -> Result { + Self::admit_budget(context)?; + let mut owner = Self { + context, + buffers: std::array::from_fn(|_| std::array::from_fn(|_| None)), + module: None, + kernel: None, + failed: false, + }; + let operation = owner.open(); + if let Err(primary) = operation { + return combine(Err(primary), owner.close()); + } + Ok(owner) + } + /// The context is live, the original module receipt valid, and the budget and free memory cover the whole + /// workspace plus the reserve; nothing is allocated yet. + fn admit_budget(context: &Context<'_>) -> Result<()> { if context.is_poisoned() || context.handle.is_none() { return Err(Error::ContextPoisoned); } @@ -65,43 +82,38 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { { return Err(Error::BudgetExceeded); } - let mut owner = Self { - context, - buffers: std::array::from_fn(|_| std::array::from_fn(|_| None)), - module: None, - kernel: None, - failed: false, - }; - let operation = (|| { - for (bank, buffers) in owner.buffers.iter_mut().enumerate() { - for (slot, size) in ROW_BYTES.into_iter().enumerate() { - buffers[slot] = Some(context.allocate(size * (bank + 1))?); - } + Ok(()) + } + /// Allocates the twelve whole owners, loads the module and validates the T1 layout. + fn open(&mut self) -> Result<()> { + let context = self.context; + for (bank, buffers) in self.buffers.iter_mut().enumerate() { + for (slot, size) in ROW_BYTES.into_iter().enumerate() { + buffers[slot] = Some(context.allocate(size * (bank + 1))?); } - let guard = context.enter()?; - let load = (|| { - let module = context.driver.api.load_gr_batch_preview_module()?; - owner.module = Some(module); - owner.kernel = Some(context.driver.api.qwen_function(module, Operation::InjectResidual)?); - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poison(); - context.retain_driver(); - } - combine(load, pop)?; - // Module overhead consumes real free memory; retain the full reserve. - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - owner.handles(GrBatchInjectShape::T1)?; - Ok(()) - })(); - if let Err(primary) = operation { - return combine(Err(primary), owner.close()); } - Ok(owner) + let guard = context.enter()?; + let load = self.load_kernel(); + let pop = guard.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver(); + } + combine(load, pop)?; + // Module overhead consumes real free memory; retain the full reserve. + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + self.handles(GrBatchInjectShape::T1)?; + Ok(()) + } + /// Loads the original module (kept in `self.module`) and resolves the inject kernel. + fn load_kernel(&mut self) -> Result<()> { + let api = &self.context.driver.api; + let module = api.load_gr_batch_preview_module()?; + self.module = Some(module); + self.kernel = Some(api.qwen_function(module, Operation::InjectResidual)?); + Ok(()) } pub fn is_failed(&self) -> bool { self.failed || self.context.is_poisoned() || self.context.handle.is_none() @@ -113,31 +125,9 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { if self.is_failed() || self.module.is_none() || self.kernel.is_none() { return Err(Error::ContextPoisoned); } - // Fixed stack ledger; no heap allocation in whole-owner validation. - let first = self.buffers[0][0].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?; - let mut owned = [(first, 0usize); 12]; - let mut count = 0; - for (bank, buffers) in self.buffers.iter().enumerate() { - for (slot, buffer) in buffers.iter().enumerate() { - let buffer = buffer.as_ref().ok_or(Error::ContextPoisoned)?; - let bytes = ROW_BYTES[slot] * (bank + 1); - if !std::ptr::eq(self.context, buffer.context) { - return Err(Error::ContextMismatch); - } - if buffer.bytes != bytes { - return Err(Error::InvalidQwenShape); - } - let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; - handle.validate_projection_extent(bytes, 4)?; - if owned.iter().take(count).any(|(prior, prior_bytes)| handle.overlaps(bytes, *prior, *prior_bytes)) { - return Err(Error::OutputAliasesInput); - } - owned[count] = (handle, bytes); - count += 1; - } - } + let owned = self.owned_ledger()?; let start = shape.bank() * 4; - let mut handles = [first; 9]; + let mut handles = [owned[0].0; 9]; let mut bytes = [0usize; 9]; for i in 0..4 { (handles[i], bytes[i]) = owned[start + i]; @@ -148,6 +138,38 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { } Ok(handles) } + /// Validates every whole owner in bank order against this context, its size and every owner before it; a fixed + /// stack ledger, no heap allocation. + fn owned_ledger(&self) -> Result<[(ffi::BufferHandle, usize); 12]> { + let first = self.buffers[0][0].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?; + let mut owned = [(first, 0usize); 12]; + let mut count = 0; + for (bank, buffers) in self.buffers.iter().enumerate() { + for (slot, buffer) in buffers.iter().enumerate() { + let buffer = buffer.as_ref().ok_or(Error::ContextPoisoned)?; + let bytes = ROW_BYTES[slot] * (bank + 1); + let handle = self.validate_owner(buffer, bytes)?; + if owned.iter().take(count).any(|(prior, prior_bytes)| handle.overlaps(bytes, *prior, *prior_bytes)) { + return Err(Error::OutputAliasesInput); + } + owned[count] = (handle, bytes); + count += 1; + } + } + Ok(owned) + } + /// An owner of this context with exactly `bytes` and a valid extent. + fn validate_owner(&self, buffer: &DeviceBuffer<'_>, bytes: usize) -> Result { + if !std::ptr::eq(self.context, buffer.context) { + return Err(Error::ContextMismatch); + } + if buffer.bytes != bytes { + return Err(Error::InvalidQwenShape); + } + let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_projection_extent(bytes, 4)?; + Ok(handle) + } /// Three initialized uploads and the original kernel share one completion. /// The full output is copied by the unchanged synchronized copy helper. /// Numeric overflow remains raw output; the runtime validates each real row. @@ -163,18 +185,50 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { return Err(Error::ContextMismatch); } let handles = self.handles(shape)?; - let tokens = shape.tokens(); - if streams.len() != 10240 * tokens || blocks.len() != 2560 * tokens || injects.len() != 4 * tokens { - return Err(Error::InvalidQwenShape); - } - if streams.iter().chain(blocks).chain(injects).any(|value| !value.is_finite()) { - return Err(Error::InvalidDriverValue("GR batch injection finite input")); - } + check_inputs(shape.tokens(), [streams, blocks, injects])?; // Fallible initialized staging is retained through every attempted command. let staging = [encode(streams)?, encode(blocks)?, encode(injects)?]; let mut arguments = Box::new(Arguments::with_layout(Operation::InjectResidual, layout(shape)?, handles, 0.)); let kernel = self.kernel.ok_or(Error::ContextPoisoned)?; + let (outcome, uncertain) = self.fenced(handles, &staging, kernel, &mut arguments)?; + if uncertain { + // close/Drop retains the real module and all charged device owners. + std::mem::forget((staging, arguments)); + } + outcome?; + self.read_output(shape) + } + /// The three uploads and the kernel under one context entry and one completion: `(outcome, uncertain)`. + fn fenced( + &mut self, + handles: [ffi::BufferHandle; 9], + staging: &[Vec; 3], + kernel: ffi::FunctionHandle, + arguments: &mut Arguments, + ) -> Result<(Result<()>, bool)> { let guard = self.context.enter()?; + let commands = self.upload_and_launch(handles, staging, kernel, arguments); + // Fence all attempted uploads/launches, including the first failed call. + let sync = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if commands.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + } + let uncertain = sync.is_err() || pop.is_err(); + if uncertain { + self.context.poison(); + self.context.retain_driver(); + } + Ok((combine(combine(commands, sync), pop), uncertain)) + } + /// The three initialized uploads, then (when all succeeded) the original kernel. + fn upload_and_launch( + &self, + handles: [ffi::BufferHandle; 9], + staging: &[Vec; 3], + kernel: ffi::FunctionHandle, + arguments: &mut Arguments, + ) -> Result<()> { let mut commands = Ok(()); for (handle, bytes) in handles.iter().zip(staging.iter()).take(3) { commands = self.context.driver.api.copy_from(*handle, bytes); @@ -183,21 +237,13 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { } } if commands.is_ok() { - commands = self.context.driver.api.launch_qwen(kernel, Operation::InjectResidual, &mut arguments); + commands = self.context.driver.api.launch_qwen(kernel, Operation::InjectResidual, arguments); } - // Fence all attempted uploads/launches, including the first failed call. - let sync = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if commands.is_err() || sync.is_err() || pop.is_err() { - self.failed = true; - } - if sync.is_err() || pop.is_err() { - self.context.poison(); - self.context.retain_driver(); - // close/Drop retains the real module and all charged device owners. - std::mem::forget((staging, arguments)); - } - combine(combine(commands, sync), pop)?; + commands + } + /// The full output, copied by the unchanged synchronized copy helper. + fn read_output(&mut self, shape: GrBatchInjectShape) -> Result> { + let tokens = shape.tokens(); let output = self.buffers[shape.bank()][3].as_ref().ok_or(Error::ContextPoisoned)?; let readback = match output.copy_to_owned(40960 * tokens) { Ok(bytes) => bytes, @@ -222,39 +268,57 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { let mut result = Ok(()); for buffer in self.buffers.iter_mut().flatten() { if let Some(buffer) = buffer.take() { - let release = if self.context.is_poisoned() { - std::mem::forget(buffer); - self.context.retain_driver(); - Err(Error::ContextPoisoned) - } else { - buffer.release() - }; - if release.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - result = combine(result, release); + result = combine(result, release_owner(self.context, buffer)); } } if let Some(module) = self.module.take() { - let release = if self.context.is_poisoned() { - self.context.retain_driver(); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(guard) => combine(self.context.driver.api.unload(module), guard.finish()), - Err(error) => Err(error), - } - }; - if release.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - result = combine(result, release); + result = combine(result, release_module(self.context, module)); } result } } +/// Releases one owned buffer, or leaks it when the context is poisoned; a failed release poisons the context. +fn release_owner(context: &Context<'_>, buffer: DeviceBuffer<'_>) -> Result<()> { + let release = if context.is_poisoned() { + std::mem::forget(buffer); + context.retain_driver(); + Err(Error::ContextPoisoned) + } else { + buffer.release() + }; + if release.is_err() { + context.poison(); + context.retain_driver(); + } + release +} +/// Unloads the module under the context; a failed unload poisons the context and keeps the driver loaded. +fn release_module(context: &Context<'_>, module: ffi::ModuleHandle) -> Result<()> { + let release = if context.is_poisoned() { + context.retain_driver(); + Err(Error::ContextPoisoned) + } else { + match context.enter() { + Ok(guard) => combine(context.driver.api.unload(module), guard.finish()), + Err(error) => Err(error), + } + }; + if release.is_err() { + context.poison(); + context.retain_driver(); + } + release +} +/// The three input slices have the lengths of `tokens` rows and are all finite. +fn check_inputs(tokens: usize, [streams, blocks, injects]: [&[f32]; 3]) -> Result<()> { + if streams.len() != 10240 * tokens || blocks.len() != 2560 * tokens || injects.len() != 4 * tokens { + return Err(Error::InvalidQwenShape); + } + if streams.iter().chain(blocks).chain(injects).any(|value| !value.is_finite()) { + return Err(Error::InvalidDriverValue("GR batch injection finite input")); + } + Ok(()) +} impl Drop for GrBatchInjectWorkspace<'_> { fn drop(&mut self) { let _ = self.close_inner(); diff --git a/crates/cuda-driver/src/gr_batch_inject_workspace_gpu.rs b/crates/cuda-driver/src/gr_batch_inject_workspace_gpu.rs index 3371113f..25883141 100644 --- a/crates/cuda-driver/src/gr_batch_inject_workspace_gpu.rs +++ b/crates/cuda-driver/src/gr_batch_inject_workspace_gpu.rs @@ -9,44 +9,30 @@ fn check(ok: bool) -> Result<()> { fn bytes(values: &[f32]) -> Vec { values.iter().flat_map(|v| v.to_le_bytes()).collect() } +/// Signed zeros alternating by index. +fn alternating(i: usize, even: f32, odd: f32) -> f32 { + if i % 2 == 0 { even } else { odd } +} fn inputs(tokens: usize, pattern: usize) -> [Vec; 3] { let streams = (0..10240 * tokens) .map(|i| match pattern { 0 => (i as i32 % 83 - 41) as f32 * 0.03125, 1 => (i as i32 % 107 - 53) as f32 * -0.0625, - _ => { - if i % 2 == 0 { - -0.0 - } else { - 0.0 - } - } + _ => alternating(i, -0.0, 0.0), }) .collect(); let blocks = (0..2560 * tokens) .map(|i| match pattern { 0 => (i as i32 % 31 - 15) as f32 * 0.015625, 1 => (i as i32 % 53 - 26) as f32 * -0.125, - _ => { - if i % 2 == 0 { - 0.0 - } else { - -0.0 - } - } + _ => alternating(i, 0.0, -0.0), }) .collect(); let injects = (0..4 * tokens) .map(|i| match pattern { 0 => (i % 7) as f32 * 0.25, 1 => (i as i32 % 13 - 6) as f32 * -0.0625, - _ => { - if i % 2 == 0 { - -0.0 - } else { - 0.0 - } - } + _ => alternating(i, -0.0, 0.0), }) .collect(); [streams, blocks, injects] @@ -124,6 +110,103 @@ fn refuses_without_change( check(products(workspace, shape)? == previous && context.allocated_bytes() == charged && !workspace.is_failed()) } +/// The budget Context is one byte short of the eager workspace: it refuses and allocates nothing. +fn budget_refusal(budget: &Context<'_>) -> Result<()> { + // Scope the borrowed Result/owner before the budget Context is moved. + let refused = match budget.gr_batch_inject_workspace() { + Ok(owner) => combine(Err(Error::InvalidDriverValue("missing eager budget refusal")), owner.close()), + Err(error) => check(error == Error::BudgetExceeded), + }; + refused?; + check(budget.allocated_bytes() == 0) +} + +/// Exact words compared and guards checked so far. +struct Tally { + words: usize, + guards: usize, +} + +/// All three roles and both short/long lengths refuse before writes, and a late non-finite word refuses too. +fn role_refusals( + context: &Context<'_>, + workspace: &mut GrBatchInjectWorkspace<'_>, + shape: GrBatchInjectShape, + tally: &mut Tally, +) -> Result<()> { + for role in 0..3 { + let mut wrong = inputs(shape.tokens(), 1); + wrong[role].pop(); + refuses_without_change(context, workspace, shape, &wrong, Error::InvalidQwenShape)?; + tally.guards += 1; + wrong[role].push(0.); + wrong[role].push(0.); + refuses_without_change(context, workspace, shape, &wrong, Error::InvalidQwenShape)?; + tally.guards += 1; + for invalid in [f32::NAN, f32::INFINITY] { + let mut late = inputs(shape.tokens(), 1); + *late[role].last_mut().ok_or(Error::InvalidQwenShape)? = invalid; + let expected = Error::InvalidDriverValue("GR batch injection finite input"); + refuses_without_change(context, workspace, shape, &late, expected)?; + tally.guards += 1; + tally.words += original_first(context, workspace, shape, &inputs(shape.tokens(), 0))?; + } + } + Ok(()) +} + +/// A foreign Context is refused without change; completed numeric overflow is raw output, not transport poison. +fn foreign_and_overflow( + context: &Context<'_>, + foreign: &Context<'_>, + workspace: &mut GrBatchInjectWorkspace<'_>, + shape: GrBatchInjectShape, + tally: &mut Tally, +) -> Result<()> { + let previous = products(workspace, shape)?; + let source = inputs(shape.tokens(), 0); + let refusal = workspace.inject(foreign, shape, &source[0], &source[1], &source[2]); + check(refusal.err() == Some(Error::ContextMismatch))?; + check(products(workspace, shape)? == previous && !workspace.is_failed())?; + tally.guards += 1; + // Completed numeric overflow is raw output, not transport poison. + let overflow = [ + vec![f32::MAX; shape.tokens() * 10240], + vec![f32::MAX; shape.tokens() * 2560], + vec![f32::MAX; shape.tokens() * 4], + ]; + tally.words += original_first(context, workspace, shape, &overflow)?; + let output = &products(workspace, shape)?[3]; + check(output.as_chunks::<4>().0.iter().any(|b| !f32::from_le_bytes(*b).is_finite()))?; + tally.words += original_first(context, workspace, shape, &inputs(shape.tokens(), 1))?; + Ok(()) +} + +/// Every shape in turn, then a bank switch that must not overwrite a completed other whole bank. +fn prove( + context: &Context<'_>, + foreign: &Context<'_>, + workspace: &mut GrBatchInjectWorkspace<'_>, +) -> Result<(usize, usize)> { + check(workspace.allocated_bytes() == GR_BATCH_INJECT_WORKSPACE_BYTES)?; + let mut tally = Tally { words: 0, guards: 1 }; + for shape in [GrBatchInjectShape::T1, GrBatchInjectShape::T2, GrBatchInjectShape::T3] { + for pattern in [0, 1, 2, 0] { + tally.words += original_first(context, workspace, shape, &inputs(shape.tokens(), pattern))?; + } + // All three roles and both short/long lengths refuse before writes. + role_refusals(context, workspace, shape, &mut tally)?; + foreign_and_overflow(context, foreign, workspace, shape, &mut tally)?; + } + // Switching one bank cannot overwrite a completed other whole bank. + let t1 = products(workspace, GrBatchInjectShape::T1)?; + let t2 = products(workspace, GrBatchInjectShape::T2)?; + tally.words += original_first(context, workspace, GrBatchInjectShape::T3, &inputs(3, 2))?; + check(products(workspace, GrBatchInjectShape::T1)? == t1 && products(workspace, GrBatchInjectShape::T2)? == t2)?; + tally.guards += 1; + Ok((tally.words, tally.guards)) +} + #[test] #[ignore] fn original_first_t1_t2_t3_gr_batch_injection_overwrite_refusal_and_cleanup() { @@ -134,81 +217,9 @@ fn original_first_t1_t2_t3_gr_batch_injection_overwrite_refusal_and_cleanup() { let foreign = device.create_context(512 * 1024 * 1024).expect("foreign Context"); let budget = device.create_context(GR_BATCH_INJECT_WORKSPACE_BYTES + RESERVE - 1).expect("budget Context"); let result = (|| -> Result<(usize, usize)> { - // Scope the borrowed Result/owner before the budget Context is moved. - let refused = match budget.gr_batch_inject_workspace() { - Ok(owner) => combine(Err(Error::InvalidDriverValue("missing eager budget refusal")), owner.close()), - Err(error) => check(error == Error::BudgetExceeded), - }; - refused?; - check(budget.allocated_bytes() == 0)?; + budget_refusal(&budget)?; let mut workspace = context.gr_batch_inject_workspace()?; - let operation = (|| -> Result<(usize, usize)> { - check(workspace.allocated_bytes() == GR_BATCH_INJECT_WORKSPACE_BYTES)?; - let mut words = 0; - let mut guards = 1; - for shape in [GrBatchInjectShape::T1, GrBatchInjectShape::T2, GrBatchInjectShape::T3] { - for pattern in [0, 1, 2, 0] { - words += original_first(&context, &mut workspace, shape, &inputs(shape.tokens(), pattern))?; - } - // All three roles and both short/long lengths refuse before writes. - for role in 0..3 { - let mut wrong = inputs(shape.tokens(), 1); - wrong[role].pop(); - refuses_without_change(&context, &mut workspace, shape, &wrong, Error::InvalidQwenShape)?; - guards += 1; - wrong[role].push(0.); - wrong[role].push(0.); - refuses_without_change(&context, &mut workspace, shape, &wrong, Error::InvalidQwenShape)?; - guards += 1; - for invalid in [f32::NAN, f32::INFINITY] { - let mut late = inputs(shape.tokens(), 1); - *late[role].last_mut().ok_or(Error::InvalidQwenShape)? = invalid; - refuses_without_change( - &context, - &mut workspace, - shape, - &late, - Error::InvalidDriverValue("GR batch injection finite input"), - )?; - guards += 1; - words += original_first(&context, &mut workspace, shape, &inputs(shape.tokens(), 0))?; - } - } - let previous = products(&workspace, shape)?; - let source = inputs(shape.tokens(), 0); - check( - workspace.inject(&foreign, shape, &source[0], &source[1], &source[2]).err() - == Some(Error::ContextMismatch), - )?; - check(products(&workspace, shape)? == previous && !workspace.is_failed())?; - guards += 1; - // Completed numeric overflow is raw output, not transport poison. - let overflow = [ - vec![f32::MAX; shape.tokens() * 10240], - vec![f32::MAX; shape.tokens() * 2560], - vec![f32::MAX; shape.tokens() * 4], - ]; - words += original_first(&context, &mut workspace, shape, &overflow)?; - check( - products(&workspace, shape)?[3] - .as_chunks::<4>() - .0 - .iter() - .any(|b| !f32::from_le_bytes(*b).is_finite()), - )?; - words += original_first(&context, &mut workspace, shape, &inputs(shape.tokens(), 1))?; - } - // Switching one bank cannot overwrite a completed other whole bank. - let t1 = products(&workspace, GrBatchInjectShape::T1)?; - let t2 = products(&workspace, GrBatchInjectShape::T2)?; - words += original_first(&context, &mut workspace, GrBatchInjectShape::T3, &inputs(3, 2))?; - check( - products(&workspace, GrBatchInjectShape::T1)? == t1 - && products(&workspace, GrBatchInjectShape::T2)? == t2, - )?; - guards += 1; - Ok((words, guards)) - })(); + let operation = prove(&context, &foreign, &mut workspace); combine(operation, workspace.close()) })(); let allocated = [context.allocated_bytes(), foreign.allocated_bytes(), budget.allocated_bytes()]; @@ -217,6 +228,7 @@ fn original_first_t1_t2_t3_gr_batch_injection_overwrite_refusal_and_cleanup() { let (words, guards) = result.expect("original-first workspace proof and exhaustive teardown"); assert_eq!(allocated, [0; 3]); println!( - "GR_BATCH_INJECT_WORKSPACE PASS exact_words={words} guards={guards} allocated0=true original_first=true raw_overflow=true" + "GR_BATCH_INJECT_WORKSPACE PASS exact_words={words} guards={guards} allocated0=true original_first=true \ + raw_overflow=true" ); } diff --git a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2.rs b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2.rs index 330520ff..096022b1 100644 --- a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2.rs +++ b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2.rs @@ -5,6 +5,25 @@ use super::*; impl<'ctx> GrMicrobatchRead<'ctx> { pub(in super::super) fn new(context: &'ctx Context<'ctx>, tokens: usize, streams: &[f32]) -> Result { + Self::admit_inputs(context, tokens, streams)?; + let staging = encode(streams)?; + let mut owner = Self { + context, + tokens, + buffers: std::array::from_fn(|_| None), + finite_module: None, + finite: None, + phase: 0, + failed: false, + }; + let result = owner.open(staging); + if let Err(primary) = result { + return combine(Err(primary), owner.close()); + } + Ok(owner) + } + /// The row count and the finite streams are valid, and the budget and free memory cover the banks plus the reserve. + fn admit_inputs(context: &Context<'_>, tokens: usize, streams: &[f32]) -> Result<()> { checked_row(tokens, 0, 40960)?; if streams.len() != tokens * 10240 { return Err(Error::InvalidQwenShape); @@ -22,43 +41,34 @@ impl<'ctx> GrMicrobatchRead<'ctx> { { return Err(Error::BudgetExceeded); } - let staging = encode(streams)?; - let mut owner = Self { - context, - tokens, - buffers: std::array::from_fn(|_| None), - finite_module: None, - finite: None, - phase: 0, - failed: false, - }; - let result = (|| { - for (slot, size) in SIZES.into_iter().enumerate() { - owner.buffers[slot] = Some(context.allocate(size * tokens)?); - } - let guard = context.enter()?; - let load = (|| { - let module = context.driver.api.load_mmq_resident()?; - owner.finite_module = Some(module); - owner.finite = Some(context.driver.api.mmq_resident_function(module, 1)?); - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poison(); - context.retain_driver(); - } - combine(load, pop)?; - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - owner.buffers[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_owned(staging)?; - Ok(()) - })(); - if let Err(primary) = result { - return combine(Err(primary), owner.close()); + Ok(()) + } + /// Allocates the banks, loads the finite-scan helper and uploads the streams into the first bank. + fn open(&mut self, staging: Vec) -> Result<()> { + let context = self.context; + for (slot, size) in SIZES.into_iter().enumerate() { + self.buffers[slot] = Some(context.allocate(size * self.tokens)?); } - Ok(owner) + let guard = context.enter()?; + let load = self.load_finite(); + let pop = guard.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver(); + } + combine(load, pop)?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + self.buffers[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_owned(staging)?; + Ok(()) + } + fn load_finite(&mut self) -> Result<()> { + let api = &self.context.driver.api; + let module = api.load_mmq_resident()?; + self.finite_module = Some(module); + self.finite = Some(api.mmq_resident_function(module, 1)?); + Ok(()) } pub fn tokens(&self) -> usize { self.tokens @@ -119,6 +129,28 @@ impl<'ctx> GrMicrobatchRead<'ctx> { if !epsilon.is_finite() || epsilon < 0.0 { return Err(Error::InvalidQwenShape); } + let (w, h) = self.row_handles(row, weights)?; + let sets: [&[ffi::BufferHandle]; 6] = [ + &[h[0], w[0], h[1]], + &[w[1], h[1], h[2]], + &[h[2], h[3]], + &[w[2], h[3], h[4]], + &[h[1], h[4], h[5], h[6]], + &[w[3], h[1], h[7]], + ]; + let mut prepared = Vec::new(); + prepared.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?; + for (operation, set) in OPS.into_iter().zip(sets) { + prepared.push(Self::prepare_operation(operation, set, epsilon)?); + } + prepared.try_into().map_err(|_| Error::InvalidQwenShape) + } + /// The four weight handles (checked against their fixed sizes) and the eight bank handles of `row`. + fn row_handles( + &self, + row: usize, + weights: [&DeviceBuffer<'_>; 4], + ) -> Result<([ffi::BufferHandle; 4], [ffi::BufferHandle; 8])> { let sizes = [40960, 6553600, 6553600, 81920]; let mut w = [self.handle(0, row)?; 4]; for (i, weight) in weights.iter().enumerate() { @@ -131,25 +163,16 @@ impl<'ctx> GrMicrobatchRead<'ctx> { for (i, handle) in h.iter_mut().enumerate() { *handle = self.handle(i, row)?; } - let sets: [&[ffi::BufferHandle]; 6] = [ - &[h[0], w[0], h[1]], - &[w[1], h[1], h[2]], - &[h[2], h[3]], - &[w[2], h[3], h[4]], - &[h[1], h[4], h[5], h[6]], - &[w[3], h[1], h[7]], - ]; - let mut prepared = Vec::new(); - prepared.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?; - for (operation, set) in OPS.into_iter().zip(sets) { - let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; - asset.validate(operation)?; - let layout = operation.layout(); - let mut handles = [set[0]; 9]; - handles[..set.len()].copy_from_slice(set); - ranges_layout(operation, layout, handles, layout.bytes, false)?; - prepared.push(Arguments::with_layout(operation, layout, handles, epsilon)); - } - prepared.try_into().map_err(|_| Error::InvalidQwenShape) + Ok((w, h)) + } + /// The arguments of one fixed operation over its operand `set`, admitted against the operation's layout. + fn prepare_operation(operation: Operation, set: &[ffi::BufferHandle], epsilon: f32) -> Result { + let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; + asset.validate(operation)?; + let layout = operation.layout(); + let mut handles = [set[0]; 9]; + handles[..set.len()].copy_from_slice(set); + ranges_layout(operation, layout, handles, layout.bytes, false)?; + Ok(Arguments::with_layout(operation, layout, handles, epsilon)) } } From 712ecc93fd1f8a37012dddc00d2745866103641c Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 23:24:05 +0100 Subject: [PATCH 7/7] STRA-338 size2 cd1: batch_gr_preview launch takes its arguments by value --- crates/cuda-driver/src/batch_gr_preview.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/cuda-driver/src/batch_gr_preview.rs b/crates/cuda-driver/src/batch_gr_preview.rs index a256a905..580df092 100644 --- a/crates/cuda-driver/src/batch_gr_preview.rs +++ b/crates/cuda-driver/src/batch_gr_preview.rs @@ -134,10 +134,9 @@ mod installed { &self, kernel: ffi::FunctionHandle, operation: Operation, - arguments: Arguments, + mut arguments: Arguments, ) -> Result<()> { let context = self.context; - let mut arguments = arguments; let guard = context.enter()?; let launch = context.driver.api.launch_qwen(kernel, operation, &mut arguments); self.launch_attempts.set(self.launch_attempts.get() + 1);