From 1789ef99282951fd0dcb4bfc58c8377c0bc5b3e7 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 22:03:02 +0100 Subject: [PATCH] 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),