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())?)) + } +}