From 3bcced5be47f8d6c13de22e4258fcf4b580c6a98 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 22:43:14 +0100 Subject: [PATCH 1/2] STRA-338 size2 cd6: long fns of verify window, qsa, ple, q6 and gpu proofs are cut into helpers (batch 1) --- .../impl_originalverifier_2.rs | 51 +- .../impl_originalverifier_4.rs | 43 +- .../original_verify_schedule/window_phases.rs | 28 +- .../src/original_verify_window_gpu.rs | 125 +-- .../original_verify_window_gr/assets_fn.rs | 17 +- .../plan_hc_read_fn.rs | 195 ++--- .../plan_ple_row_fn.rs | 135 ++-- .../src/original_verify_window_kernels.rs | 7 +- .../plan_expert_groups_fn.rs | 300 ++++---- .../plan_f32_to_bf16_fn.rs | 271 ++++--- .../impl_originalverifier.rs | 85 +- ...l_windowops_for_originalverifywindowops.rs | 153 ++-- .../q8_1_row_bytes_fn.rs | 21 +- .../impl_qsawindow/impl_qsawindow_2.rs | 85 +- .../impl_qsawindow/impl_qsawindow_2_2.rs | 209 +++-- .../src/original_verify_window_record.rs | 101 +-- .../src/owned_gate_up_upload_gpu.rs | 304 +++++--- .../src/ple_batch_ffi/enabled/impl_blas.rs | 250 +++--- .../src/ple_batch_ffi/enabled/impl_blas_2.rs | 189 ++--- .../cuda-driver/src/ple_closed_queue_gpu.rs | 438 ++++++----- crates/cuda-driver/src/ple_value_full_gpu.rs | 145 ++-- .../gdn_recurrence_equals_the_original.rs | 430 +++++------ .../gdn_stage_kernels_equal.rs | 655 ++++++++-------- crates/cuda-driver/src/prefill_stage_gpu.rs | 195 +++-- .../gr_fused_guards_equal.rs | 490 +++++------- .../gr_kernels_run_near_their.rs | 220 +++--- crates/cuda-driver/src/q6_k_shape_fn.rs | 42 +- crates/cuda-driver/src/q6_layer_preview.rs | 163 ++-- crates/cuda-driver/src/qsa_index_ffi.rs | 43 +- .../cuda-driver/src/qsa_index_ffi/enabled.rs | 190 ++--- crates/cuda-driver/src/qsa_late_gpu.rs | 725 ++++++++++-------- .../impl_originalqsamappedjournal.rs | 226 ++++-- .../impl_originalqsamappedjournal_2.rs | 123 +-- .../impl_qsanativebatchworkspace_2.rs | 288 ++++--- .../qsa_native_batch/impl_qsanativekind.rs | 114 +-- crates/cuda-driver/src/qsa_native_decode.rs | 255 +++--- crates/cuda-driver/src/qsa_native_gate.rs | 129 ++-- .../impl_qsapromptattention.rs | 334 +++++--- .../src/qsa_prompt_attention_ffi.rs | 138 ++-- .../impl_poolpresence.rs | 61 +- .../src/qsa_prompt_device_attention.rs | 66 +- crates/cuda-driver/src/qsa_prompt_host_ffi.rs | 22 +- .../impl_drop_for_qsapromptkv.rs | 50 +- .../impl_qsapromptkv/impl_qsapromptkv_2.rs | 33 +- crates/cuda-driver/src/qsa_prompt_resolver.rs | 69 +- .../cuda-driver/src/qsa_resident_attention.rs | 236 ++---- crates/cuda-driver/src/qsa_resident_decode.rs | 100 +-- 47 files changed, 4526 insertions(+), 4023 deletions(-) diff --git a/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_2.rs b/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_2.rs index da204a0b..46713406 100644 --- a/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_2.rs +++ b/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_2.rs @@ -38,28 +38,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour } let span_commit = crate::host_profile::span("drv.commit_enqueue"); self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_commit(n_keep)?; - let operation = (|| { - self.commit - .as_mut() - .ok_or(Error::ContextPoisoned)? - .enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?; - self.window_ready = false; - let forced = commit_sync_forced(); - if async_commit && !forced { - self.event - .as_mut() - .ok_or(Error::ContextPoisoned)? - .record(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?; - self.commit_pending = true; - Ok(()) - } else { - let receipt = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?; - self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_stream_drain(&receipt)?; - self.commit.as_ref().ok_or(Error::ContextPoisoned)?.verifier_complete_commit(self.bank()?)?; - self.commits = self.commits.checked_add(1).ok_or(Error::InvalidSize)?; - Ok(()) - } - })(); + let operation = self.commit_after_stage(async_commit); drop(span_commit); if let Err(primary) = operation { self.failed = true; @@ -67,4 +46,32 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour } Ok(()) } + + /// The commit graph launch after the bank staged `n_keep`: asynchronous with an event, or drained and completed. + fn commit_after_stage(&mut self, async_commit: bool) -> Result<()> { + self.commit + .as_mut() + .ok_or(Error::ContextPoisoned)? + .enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?; + self.window_ready = false; + let forced = commit_sync_forced(); + if async_commit && !forced { + self.event + .as_mut() + .ok_or(Error::ContextPoisoned)? + .record(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?; + self.commit_pending = true; + Ok(()) + } else { + self.complete_commit_sync() + } + } + + fn complete_commit_sync(&mut self) -> Result<()> { + let receipt = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?; + self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_stream_drain(&receipt)?; + self.commit.as_ref().ok_or(Error::ContextPoisoned)?.verifier_complete_commit(self.bank()?)?; + self.commits = self.commits.checked_add(1).ok_or(Error::InvalidSize)?; + Ok(()) + } } diff --git a/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_4.rs b/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_4.rs index dafb171b..709dd081 100644 --- a/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_4.rs +++ b/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_4.rs @@ -131,25 +131,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour let start = Instant::now(); // Original #267 bounded release: no blocking wait on a spin kernel forever. for s in [self.compute.as_ref(), self.copy.as_ref()].into_iter().flatten() { - loop { - match s.query() { - Ok(true) => break, - Ok(false) => { - if start.elapsed() > Duration::from_millis(5000) { - if let Some(bank) = &self.bank { - poison(bank.physical.context) - } - result = combine(result, Err(Error::InvalidDriverValue("Verifier release timeout"))); - break; - } - std::thread::sleep(Duration::from_millis(1)); - } - Err(error) => { - result = combine(result, Err(error)); - break; - } - } - } + result = self.drain_bounded(s, start, result); } if result.is_ok() { for graph in self.window.iter_mut().filter_map(Option::as_mut) { @@ -163,6 +145,29 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour self.commit_pending = false; result } + /// Polls one stream until idle; a stuck stream poisons the context after 5 s, a query error ends the wait. + fn drain_bounded(&self, s: &OriginalGpuStream<'ctx>, start: Instant, mut result: Result<()>) -> Result<()> { + loop { + match s.query() { + Ok(true) => break, + Ok(false) => { + if start.elapsed() > Duration::from_millis(5000) { + if let Some(bank) = &self.bank { + poison(bank.physical.context) + } + result = combine(result, Err(Error::InvalidDriverValue("Verifier release timeout"))); + break; + } + std::thread::sleep(Duration::from_millis(1)); + } + Err(error) => { + result = combine(result, Err(error)); + break; + } + } + } + result + } pub fn close(mut self) -> Result<()> { self.close_inner() } diff --git a/crates/cuda-driver/src/original_verify_schedule/window_phases.rs b/crates/cuda-driver/src/original_verify_schedule/window_phases.rs index 6b8c15a3..38de4c0b 100644 --- a/crates/cuda-driver/src/original_verify_schedule/window_phases.rs +++ b/crates/cuda-driver/src/original_verify_schedule/window_phases.rs @@ -120,7 +120,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour let span_bell = crate::host_profile::span("drv.doorbell_wait"); self.wait_doorbell(want, start)?; drop(span_bell); - self.pool_group(t, groups, (layer, group), want, pool)?; + self.pool_group(PoolAt { t, groups, layer, group, want }, pool)?; self.publish_group(k, groups, group, want) } @@ -160,16 +160,21 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour } Ok(last_flush) } +} +/// Where in the window a CPU group sits: `t` tokens split in `groups`, the `layer`/`group` pair, ring `want`. +#[derive(Clone, Copy)] +struct PoolAt { + t: usize, + groups: usize, + layer: usize, + group: usize, + want: u32, +} + +impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> OriginalVerifier<'ctx, R> { /// Hands the group's mapped CPU rows to the caller's pool together with the plan sink. - fn pool_group

( - &mut self, - t: usize, - groups: usize, - (layer, group): (usize, usize), - want: u32, - pool: &mut P, - ) -> Result<()> + fn pool_group

(&mut self, at: PoolAt, pool: &mut P) -> Result<()> where P: FnMut( OriginalVerifyCpuRows<'_>, @@ -177,10 +182,10 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour &mut OriginalGpuStream<'ctx>, ) -> Result<()>, { + let PoolAt { t, groups, layer, group, want } = at; let (begin, end) = window_plan::group_rows(t, groups, group); let rows = end - begin; - let g = self.bank()?.geometry(); - let physical = self.bank()?.physical.clone(); + let (g, physical) = (self.bank()?.geometry(), self.bank()?.physical.clone()); let x = physical.mapped[6].try_borrow().map_err(|_| Error::InvalidQwenShape)?; let ids = physical.mapped[7].try_borrow().map_err(|_| Error::InvalidQwenShape)?; let w = physical.mapped[8].try_borrow().map_err(|_| Error::InvalidQwenShape)?; @@ -197,7 +202,6 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour self.invoke_pool(pool, cpu, (begin, rows, groups, want)) }, )?; - drop((x, ids, w)); Ok(()) } diff --git a/crates/cuda-driver/src/original_verify_window_gpu.rs b/crates/cuda-driver/src/original_verify_window_gpu.rs index f61bf2ff..c6201751 100644 --- a/crates/cuda-driver/src/original_verify_window_gpu.rs +++ b/crates/cuda-driver/src/original_verify_window_gpu.rs @@ -3,6 +3,7 @@ //! executed. They certify that the pinned PTX loads on the card and exports every entry the //! planners name, NOT numerics (the per-kernel golden comparisons against the Original are listed in //! the work report). +use super::abi::{Arg, Command, Module}; use super::*; use crate::Driver; @@ -45,7 +46,6 @@ fn sealed_window_assets_load_on_the_device_and_export_every_named_entry() { #[test] #[ignore = "Root-only: needs a CUDA device"] fn the_pcie_span_copy_stages_gate_up_down_like_the_dma_path() { - use super::abi::{Arg, Command, Module}; assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes")); let driver = Driver::load().expect("driver"); let device = driver.device(0).expect("device"); @@ -53,6 +53,45 @@ fn the_pcie_span_copy_stages_gate_up_down_like_the_dma_path() { let roles = [1_126_400usize, 1_126_400, 655_360]; let stride: usize = roles.iter().sum(); let fetches = 5usize; + let (sources, expected) = pcie_sources(&context, roles, fetches); + // ptr2 holds 3 * fetches aliases (a 60-entry table like a max_t = 6 window's plan block) + let table = pcie_table(&context, &sources); + let mut count = context.allocate(4).expect("count"); + count.copy_from(&(fetches as i32).to_le_bytes()).expect("count upload"); + let staging = context.allocate(16 * stride).expect("staging"); + launch_span_copy_and_rebase(&context, [&table, &count, &staging], roles); + let staged = staging.copy_to_owned(16 * stride).expect("read staging"); + assert!(staged[..fetches * stride] == expected[..], "staging slots are gate|up|down per expert"); + let table_after = table.copy_to_owned(60 * 8).expect("read table"); + for q in 0..fetches { + let ptr = u64::from_le_bytes(table_after[q * 8..q * 8 + 8].try_into().unwrap()); + assert_eq!(ptr, address(&staging) + (q * stride) as u64, "ptr2[{q}] rebased to its slot"); + } + // entries past the rebased ones keep their aliases + let tail = u64::from_le_bytes(table_after[fetches * 8..fetches * 8 + 8].try_into().unwrap()); + assert_eq!(tail, address(&sources[fetches])); + eprintln!("pcie span copy: {fetches} experts x {stride} bytes staged bit-identical, ptr2 rebased"); +} + +/// The 60-entry `ptr2` table holding the device alias of every source span. +fn pcie_table<'c>(context: &'c Context<'c>, sources: &[DeviceBuffer<'_>]) -> DeviceBuffer<'c> { + let mut table = context.allocate(60 * 8).expect("table"); + let mut words = vec![0u8; 60 * 8]; + for (i, s) in sources.iter().enumerate() { + words[i * 8..i * 8 + 8].copy_from_slice(&address(s).to_le_bytes()); + } + table.copy_from(&words).expect("table upload"); + table +} + +fn address(b: &DeviceBuffer<'_>) -> u64 { + b.handle.expect("handle").qwen_address() +} + +/// Three device source spans per expert (gate, up, down) of a deterministic pattern, and the bytes the staging slots +/// must hold afterwards. +fn pcie_sources<'c>(context: &'c Context<'c>, roles: [usize; 3], fetches: usize) -> (Vec>, Vec) { + let stride: usize = roles.iter().sum(); let mut sources = Vec::new(); let mut expected = vec![0u8; fetches * stride]; for q in 0..fetches { @@ -66,62 +105,46 @@ fn the_pcie_span_copy_stages_gate_up_down_like_the_dma_path() { sources.push(buffer); } } - let address = |b: &DeviceBuffer<'_>| b.handle.expect("handle").qwen_address(); - // ptr2 holds 3 * fetches aliases (a 60-entry table like a max_t = 6 window's plan block) - let mut table = context.allocate(60 * 8).expect("table"); - let mut words = vec![0u8; 60 * 8]; - for (i, s) in sources.iter().enumerate() { - words[i * 8..i * 8 + 8].copy_from_slice(&address(s).to_le_bytes()); - } - table.copy_from(&words).expect("table upload"); - let mut count = context.allocate(4).expect("count"); - count.copy_from(&(fetches as i32).to_le_bytes()).expect("count upload"); - let staging = context.allocate(16 * stride).expect("staging"); + (sources, expected) +} + +/// The two launches of `pcie_stage` (`verify_fetch_spans_kernel`, `verify_rebase_ptrs_kernel`), then a synchronize. +fn launch_span_copy_and_rebase( + context: &Context<'_>, + [table, count, staging]: [&DeviceBuffer<'_>; 3], + roles: [usize; 3], +) { + let stride: usize = roles.iter().sum(); let guard = context.enter().expect("enter"); let pcie = Module::load(moe::PCIE.sealed().expect("sealed"), moe::PCIE.entries).expect("pcie module"); let verify = gather_rows_module().expect("verify module"); - let mut copy = Command::new( - "verify_fetch_spans_kernel", - [48 * 8, 1, 1], - [256, 1, 1], - 0, - vec![ - Arg::Address(address(&table)), - Arg::Address(address(&count)), - Arg::Address(address(&staging)), - Arg::I64((roles[0] / 16) as i64), - Arg::I64((roles[1] / 16) as i64), - Arg::I64((roles[2] / 16) as i64), - ], - ) - .expect("command"); + let mut copy = span_copy_command([table, count, staging], roles); pcie.launch(0, &mut copy).expect("launch copy"); - let mut rebase = Command::new( - "verify_rebase_ptrs_kernel", - [1, 1, 1], - [128, 1, 1], - 0, - vec![ - Arg::Address(address(&table)), - Arg::Address(address(&count)), - Arg::U64(address(&staging)), - Arg::I64(stride as i64), - ], - ) - .expect("command"); + let mut rebase = rebase_command([table, count, staging], stride); verify.launch(0, &mut rebase).expect("launch rebase"); drop((pcie, verify)); guard.finish().expect("pop"); context.synchronize().expect("sync"); - let staged = staging.copy_to_owned(16 * stride).expect("read staging"); - assert!(staged[..fetches * stride] == expected[..], "staging slots are gate|up|down per expert"); - let table_after = table.copy_to_owned(60 * 8).expect("read table"); - for q in 0..fetches { - let ptr = u64::from_le_bytes(table_after[q * 8..q * 8 + 8].try_into().unwrap()); - assert_eq!(ptr, address(&staging) + (q * stride) as u64, "ptr2[{q}] rebased to its slot"); - } - // entries past the rebased ones keep their aliases - let tail = u64::from_le_bytes(table_after[fetches * 8..fetches * 8 + 8].try_into().unwrap()); - assert_eq!(tail, address(&sources[fetches])); - eprintln!("pcie span copy: {fetches} experts x {stride} bytes staged bit-identical, ptr2 rebased"); +} + +fn span_copy_command([table, count, staging]: [&DeviceBuffer<'_>; 3], roles: [usize; 3]) -> Command { + let args = vec![ + Arg::Address(address(table)), + Arg::Address(address(count)), + Arg::Address(address(staging)), + Arg::I64((roles[0] / 16) as i64), + Arg::I64((roles[1] / 16) as i64), + Arg::I64((roles[2] / 16) as i64), + ]; + Command::new("verify_fetch_spans_kernel", [48 * 8, 1, 1], [256, 1, 1], 0, args).expect("command") +} + +fn rebase_command([table, count, staging]: [&DeviceBuffer<'_>; 3], stride: usize) -> Command { + let args = vec![ + Arg::Address(address(table)), + Arg::Address(address(count)), + Arg::U64(address(staging)), + Arg::I64(stride as i64), + ]; + Command::new("verify_rebase_ptrs_kernel", [1, 1, 1], [128, 1, 1], 0, args).expect("command") } diff --git a/crates/cuda-driver/src/original_verify_window_gr/assets_fn.rs b/crates/cuda-driver/src/original_verify_window_gr/assets_fn.rs index 978af02b..a4e16e4b 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/assets_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/assets_fn.rs @@ -20,6 +20,10 @@ impl GrVariant { } } } +/// `want` lowered to the card's opt-in limit when the card reports one. +fn cap_to_optin(want: u32, optin: u32) -> u32 { + if optin > 0 && want > optin { optin } else { want } +} impl GrConfig { /// Replicates the one-time per-device block of `down_chunk` from the four device attributes /// (`ATTR_*`). An attribute call is only emitted when the card reports an opt-in (Original @@ -34,16 +38,9 @@ impl GrConfig { ) -> Self { let optin = optin.max(0) as u32; let per_block = per_block.max(0) as u32; - let small_tile = cc_major * 10 + cc_minor == 75; - let tile: u32 = if small_tile { 1280 } else { 2560 }; - let mut want = MAX_T as u32 * tile * 4; - if optin > 0 && want > optin { - want = optin; - } - let mut want_staged = 2 * MAX_T as u32 * STAGED_TILE * 4; - if optin > 0 && want_staged > optin { - want_staged = optin; - } + let tile: u32 = if cc_major * 10 + cc_minor == 75 { 1280 } else { 2560 }; + let want = cap_to_optin(MAX_T as u32 * tile * 4, optin); + let want_staged = cap_to_optin(2 * MAX_T as u32 * STAGED_TILE * 4, optin); // Below sm_70 the opt-in is a promise the card does not keep: the per-block limit counts. let usable = if cc_major >= 7 && optin > 0 { optin } else { per_block }; let clamp = |capacity: u32| (capacity.max(1) as usize).min(MAX_T); diff --git a/crates/cuda-driver/src/original_verify_window_gr/plan_hc_read_fn.rs b/crates/cuda-driver/src/original_verify_window_gr/plan_hc_read_fn.rs index 17c59da7..44c00315 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/plan_hc_read_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/plan_hc_read_fn.rs @@ -19,12 +19,25 @@ pub(crate) fn plan_hc_read( rows: Rows, ) -> Result { check_rows(geo, rows)?; + let n = rows.len(); + let per_row = hc_read_rows(arena, half, rows)?; + let xn = arena.span("xn", rows.begin * D * 4, n * D * 4)?; + let full = multi_words(&per_row, w, apply, xn); + + let chain_gr = super::super::chain::flags().gr && cfg.variant == GrVariant::Staged; + let norm = hc_read_norm(cfg, chain_gr, n, &full)?; + let down = hc_read_down(cfg, chain_gr, n, &full)?; + let up = hc_read_up(chain_gr, full)?; + Ok(HcReadPlan { norm, down, up }) +} + +/// The per-row argument spans of the window rows; the attention half reads `inj2` and writes `inj`, the FFN the reverse. +fn hc_read_rows(arena: &dyn ArenaMap, half: HcHalf, rows: Rows) -> Result> { let (inj_prev_name, inj_out_name) = match half { HcHalf::Attention => ("inj2", "inj"), HcHalf::Ffn => ("inj", "inj2"), }; - let n = rows.len(); - let mut per_row = Vec::with_capacity(n); + let mut per_row = Vec::with_capacity(rows.len()); for t in rows.begin..rows.end { per_row.push(RowArgs { r: row_span(arena, "R", t, D * 4)?, @@ -36,27 +49,29 @@ pub(crate) fn plan_hc_read( mixed: row_span(arena, "mixed", t, N * 4)?, }); } - let xn = arena.span("xn", rows.begin * D * 4, n * D * 4)?; - let full = multi_words(&per_row, w, apply, xn); + Ok(per_row) +} - // norm: variant >= split is [n, 4] blocks, the plain read [n] blocks - let chain_gr = super::super::chain::flags().gr && cfg.variant == GrVariant::Staged; - let norm = if chain_gr { +/// norm: variant >= split is [n, 4] blocks, the plain read [n] blocks +fn hc_read_norm(cfg: &GrConfig, chain_gr: bool, n: usize, full: &[u64]) -> Result { + if chain_gr { Launch::new( &super::super::chain::CHAIN, super::super::chain::E_GR_SPLIT, [n as u32, HC as u32, 1], [THREADS, 1, 1], 0, - vec![A::Words(full.clone())], - )? + vec![A::Words(full.to_vec())], + ) } else if cfg.variant == GrVariant::Plain { - Launch::new(&GR_FUSED, E_NORM, [n as u32, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full.clone())])? + Launch::new(&GR_FUSED, E_NORM, [n as u32, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full.to_vec())]) } else { - Launch::new(&GR_FUSED, E_SPLIT, [n as u32, HC as u32, 1], [THREADS, 1, 1], 0, vec![A::Words(full.clone())])? - }; + Launch::new(&GR_FUSED, E_SPLIT, [n as u32, HC as u32, 1], [THREADS, 1, 1], 0, vec![A::Words(full.to_vec())]) + } +} - // down: launches of as many tokens as the shared memory allows +/// down: launches of as many tokens as the shared memory allows +fn hc_read_down(cfg: &GrConfig, chain_gr: bool, n: usize, full: &[u64]) -> Result> { let staged = cfg.variant == GrVariant::Staged; let per_token = if staged { 2 * STAGED_TILE * 4 } else { cfg.tile * 4 }; let chunk_tok = if staged { cfg.chunk_staged } else { cfg.chunk_plain }; @@ -72,66 +87,58 @@ pub(crate) fn plan_hc_read( // the card cannot launch it (Original would fail the launch) return Err(Error::InvalidProjectionShape); } - if chain_gr && staged && super::super::chain::down_tiled() { - // same arithmetic as the staged kernel; blocks of 8 rows x 2 tokens (grid.y = ceil(ct / 2)) spread the work over the SMs, the whole weight row - // in registers, four tile buffers of two tokens in flight - let (grid, shared) = tiled_down_geometry(ct); - if shared > cfg.usable_shared { - return Err(Error::InvalidProjectionShape); - } - down.push(Launch::new( - &super::super::chain::CHAIN, - super::super::chain::E_GR_DOWN_T2W8, - grid, - [THREADS, 1, 1], - shared, - vec![A::Words(chunk_words(&full, n, c0, ct))], - )?); - c0 += ct; - continue; - } - if chain_gr && staged { - // same arithmetic as the staged kernel; the whole weight row in registers and three (two above six tokens) tile buffers in flight - let (entry, buffers) = - if ct <= 6 { (super::super::chain::E_GR_DOWN_NB3, 3) } else { (super::super::chain::E_GR_DOWN_NB2, 2) }; - let shared = buffers * ct as u32 * (STAGED_TILE * 4); - if shared > cfg.usable_shared { - return Err(Error::InvalidProjectionShape); - } - down.push(Launch::new( - &super::super::chain::CHAIN, - entry, - [DOWN_BLOCKS, 1, 1], - [THREADS, 1, 1], - shared, - vec![A::Words(chunk_words(&full, n, c0, ct))], - )?); - c0 += ct; - continue; - } - down.push(Launch::new( - &GR_FUSED, - cfg.down_entry(), - [DOWN_BLOCKS, 1, 1], - [THREADS, 1, 1], - shared, - vec![A::Words(chunk_words(&full, n, c0, ct))], - )?); + let words = || chunk_words(full, n, c0, ct); + down.push(hc_read_down_chunk(cfg, chain_gr && staged, (ct, shared), words)?); c0 += ct; } + Ok(down) +} - let up = if chain_gr { - // 16 columns per block (160 blocks) with every load of the block's rows hoisted; chain_gr_up8 (320 blocks) is the alternative shape +/// One down launch of `ct` tokens: the tiled or two/three-buffer chain kernel under `chain_staged`, else the fused one. +fn hc_read_down_chunk( + cfg: &GrConfig, + chain_staged: bool, + (ct, shared): (usize, u32), + words: impl FnOnce() -> Vec, +) -> Result { + use super::super::chain; + if chain_staged && chain::down_tiled() { + // same arithmetic as the staged kernel; blocks of 8 rows x 2 tokens (grid.y = ceil(ct / 2)) spread the work + // over the SMs, the whole weight row in registers, four tile buffers of two tokens in flight + let (grid, shared) = tiled_down_geometry(ct); + if shared > cfg.usable_shared { + return Err(Error::InvalidProjectionShape); + } + let entry = chain::E_GR_DOWN_T2W8; + return Launch::new(&chain::CHAIN, entry, grid, [THREADS, 1, 1], shared, vec![A::Words(words())]); + } + if chain_staged { + // same arithmetic as the staged kernel; the whole weight row in registers and three (two above six tokens) + // tile buffers in flight + let (entry, buffers) = if ct <= 6 { (chain::E_GR_DOWN_NB3, 3) } else { (chain::E_GR_DOWN_NB2, 2) }; + let shared = buffers * ct as u32 * (STAGED_TILE * 4); + if shared > cfg.usable_shared { + return Err(Error::InvalidProjectionShape); + } + let blocks = [DOWN_BLOCKS, 1, 1]; + return Launch::new(&chain::CHAIN, entry, blocks, [THREADS, 1, 1], shared, vec![A::Words(words())]); + } + Launch::new(&GR_FUSED, cfg.down_entry(), [DOWN_BLOCKS, 1, 1], [THREADS, 1, 1], shared, vec![A::Words(words())]) +} + +fn hc_read_up(chain_gr: bool, full: Vec) -> Result { + if chain_gr { + // 16 columns per block (160 blocks) with every load of the block's rows hoisted; chain_gr_up8 (320 blocks) + // is the alternative shape let (entry, blocks) = if super::super::chain::up8() { (super::super::chain::E_GR_UP8, UP_BLOCKS * 2) } else { (super::super::chain::E_GR_UP16, UP_BLOCKS) }; - Launch::new(&super::super::chain::CHAIN, entry, [blocks, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full)])? + Launch::new(&super::super::chain::CHAIN, entry, [blocks, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full)]) } else { - Launch::new(&GR_FUSED, E_UP, [UP_BLOCKS, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full)])? - }; - Ok(HcReadPlan { norm, down, up }) + Launch::new(&GR_FUSED, E_UP, [UP_BLOCKS, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full)]) + } } // ------------------------------------------------------------------------------------------------ @@ -198,38 +205,34 @@ pub(crate) fn plan_head_mix( } let mut out = Vec::with_capacity(rows * 5); for t in 0..rows { - let r = row_span(arena, "R", t, D * 4)?; - let xn = row_span(arena, "xn", t, D * 4)?; - let lo = row_span(arena, "lo", t, LR * 4)?; - let gated = arena.span("parts", t * geo.k * N * 4, D * 4)?; - let mixed = mixed_out_base + (t * N * 4) as u64; - // native_gr_rms_norm_weighted(R, w_norm, xn, n_embd, hc, eps): n_cols >= 1024 -> <1024>, hc blocks - out.push(Launch::new( - &GR_NORM, - "mtp_full_gr_norm", - [HC as u32, 1, 1], - [1024, 1, 1], - 0, - vec![A::P(r), A::P(w.norm), A::P(xn), A::I32(N as i32), A::F32(EPS)], - )?); - out.push(plan_bf16_gemv(xn, D, w.down, lo, LR, D, LR, 1)?); - out.push(Launch::new( - &GR_POST, - "mtp_full_down_silu", - [(LR as u32).div_ceil(THREADS), 1, 1], - [THREADS, 1, 1], - 0, - vec![A::P(lo), A::I32(LR as i32), A::F32(QUARTER)], - )?); - out.push(plan_bf16_gemv(lo, LR, w.up, gated, D, LR, D, 1)?); - out.push(Launch::new( - &GR_POST, - "mtp_full_pre_final", - [(N as u32).div_ceil(THREADS), 1, 1], - [THREADS, 1, 1], - 0, - vec![A::P(xn), A::P(gated), A::P(mixed), A::I32(N as i32), A::I32(HC as i32), A::F32(QUARTER)], - )?); + out.extend(head_mix_row(arena, geo, w, mixed_out_base, t)?); } Ok(out) } + +/// The five launches of one head row `t`: norm, down gemv, down-silu, up gemv, final pre-mix. +fn head_mix_row( + arena: &dyn ArenaMap, + geo: &OriginalVerifyGeometry, + w: &HeadAddrs, + mixed_base: u64, + t: usize, +) -> Result<[Launch; 5]> { + let r = row_span(arena, "R", t, D * 4)?; + let xn = row_span(arena, "xn", t, D * 4)?; + let lo = row_span(arena, "lo", t, LR * 4)?; + let gated = arena.span("parts", t * geo.k * N * 4, D * 4)?; + let mixed = mixed_base + (t * N * 4) as u64; + // native_gr_rms_norm_weighted(R, w_norm, xn, n_embd, hc, eps): n_cols >= 1024 -> <1024>, hc blocks + let norm_args = vec![A::P(r), A::P(w.norm), A::P(xn), A::I32(N as i32), A::F32(EPS)]; + let norm = Launch::new(&GR_NORM, "mtp_full_gr_norm", [HC as u32, 1, 1], [1024, 1, 1], 0, norm_args)?; + let down = plan_bf16_gemv(xn, D, w.down, lo, LR, D, LR, 1)?; + let silu_grid = [(LR as u32).div_ceil(THREADS), 1, 1]; + let silu_args = vec![A::P(lo), A::I32(LR as i32), A::F32(QUARTER)]; + let silu = Launch::new(&GR_POST, "mtp_full_down_silu", silu_grid, [THREADS, 1, 1], 0, silu_args)?; + let up = plan_bf16_gemv(lo, LR, w.up, gated, D, LR, D, 1)?; + let pre_grid = [(N as u32).div_ceil(THREADS), 1, 1]; + let pre_args = vec![A::P(xn), A::P(gated), A::P(mixed), A::I32(N as i32), A::I32(HC as i32), A::F32(QUARTER)]; + let pre = Launch::new(&GR_POST, "mtp_full_pre_final", pre_grid, [THREADS, 1, 1], 0, pre_args)?; + Ok([norm, down, silu, up, pre]) +} diff --git a/crates/cuda-driver/src/original_verify_window_gr/plan_ple_row_fn.rs b/crates/cuda-driver/src/original_verify_window_gr/plan_ple_row_fn.rs index 8a0cd401..ecec3575 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/plan_ple_row_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/plan_ple_row_fn.rs @@ -43,15 +43,49 @@ pub(crate) fn plan_ple_row( let r = row_span(arena, "R", row, D * 4)?; let emb = row_span(arena, "ple", row, N * 4)?; - let key = a.scratch + SCRATCH_KEY; - let query = a.scratch + SCRATCH_QUERY; - let norm = a.scratch + SCRATCH_NORM; - let gated = a.scratch + SCRATCH_GATED; - let conv = a.scratch + SCRATCH_CONV; - let value = a.scratch + SCRATCH_VALUE; - let gate = a.scratch + SCRATCH_GATE; + let scratch = PleScratch::at(a.scratch); - // key = ple_key @ emb + plan_ple_key(arena, ple, a, emb, scratch.key, &mut out)?; + // value = ple_value @ emb + out.push(plan_bf16_gemv(emb, N, a.value, scratch.value, N, N, N, 1)?); + out.extend(plan_ple_postops(a, r, &scratch)?); + Ok(out) +} + +/// The `ple_block` workspace addresses carved from the scratch base. +struct PleScratch { + key: u64, + query: u64, + norm: u64, + gated: u64, + conv: u64, + value: u64, + gate: u64, +} + +impl PleScratch { + fn at(base: u64) -> Self { + Self { + key: base + SCRATCH_KEY, + query: base + SCRATCH_QUERY, + norm: base + SCRATCH_NORM, + gated: base + SCRATCH_GATED, + conv: base + SCRATCH_CONV, + value: base + SCRATCH_VALUE, + gate: base + SCRATCH_GATE, + } + } +} + +/// key = ple_key @ emb (BF16 MMVF, or q8_1 quantize + MMVQ for a native key). +fn plan_ple_key( + arena: &dyn ArenaMap, + ple: &PleConfig, + a: &PleAddrs, + emb: u64, + key: u64, + out: &mut Vec, +) -> Result<()> { match a.key { PleKey::Bf16(w) => out.push(plan_bf16_gemv(emb, N, w, key, D, N, D, 1)?), PleKey::Native { ty, data } => { @@ -63,59 +97,32 @@ pub(crate) fn plan_ple_row( out.push(plan_mmvq(&NativeWeight { ty, data }, q8, key, N, D, 1, ple.dispatch)?); } } - // value = ple_value @ emb - out.push(plan_bf16_gemv(emb, N, a.value, value, N, N, N, 1)?); + Ok(()) +} - // native_ple_postops(d_key, hidden, d_value, hist, w, {key=d_query, query=d_norm, gate=d_gate, - // gated=d_gated, normalized=d_norm, conv=d_conv, result=hidden}) - let rms = |input: u64, gamma: u64, output: u64| { - Launch::new( - &PLE_BATCH, - "ple_rms", - [HC as u32, 1, 1], - [1024, 1, 1], - 0, - vec![A::P(input), A::P(gamma), A::P(output)], - ) - }; - out.push(rms(key, a.norm_key, query)?); - out.push(rms(r, a.norm_query, norm)?); - out.push(Launch::new( - &PLE_BATCH, - "ple_gate", - [HC as u32, 1, 1], - [512, 1, 1], - 0, - vec![A::P(query), A::P(norm), A::P(gate), A::F32(1.0f32 / (N as f32).sqrt())], - )?); +fn ple_rms(input: u64, gamma: u64, output: u64) -> Result { + let args = vec![A::P(input), A::P(gamma), A::P(output)]; + Launch::new(&PLE_BATCH, "ple_rms", [HC as u32, 1, 1], [1024, 1, 1], 0, args) +} + +/// native_ple_postops(d_key, hidden, d_value, hist, w, {key=d_query, query=d_norm, gate=d_gate, +/// gated=d_gated, normalized=d_norm, conv=d_conv, result=hidden}), then `ple_history_advance`. +fn plan_ple_postops(a: &PleAddrs, r: u64, s: &PleScratch) -> Result<[Launch; 7]> { + let rms_key = ple_rms(s.key, a.norm_key, s.query)?; + let rms_hidden = ple_rms(r, a.norm_query, s.norm)?; + let gate_args = vec![A::P(s.query), A::P(s.norm), A::P(s.gate), A::F32(1.0f32 / (N as f32).sqrt())]; + let gate = Launch::new(&PLE_BATCH, "ple_gate", [HC as u32, 1, 1], [512, 1, 1], 0, gate_args)?; let blocks = (D as u32) / THREADS; - out.push(Launch::new( - &PLE_BATCH, - "ple_broadcast", - [blocks, 1, 1], - [THREADS, 1, 1], - 0, - vec![A::P(value), A::P(gate), A::P(gated), A::I32(1)], - )?); - out.push(rms(gated, a.norm_conv, norm)?); - out.push(Launch::new( - &PLE_BATCH, - "ple_conv", - [blocks, 1, 1], - [THREADS, 1, 1], - 0, - vec![A::P(a.history), A::P(norm), A::P(a.conv1d), A::P(r), A::P(gated), A::P(conv), A::I32(1)], - )?); + let broadcast_args = vec![A::P(s.value), A::P(s.gate), A::P(s.gated), A::I32(1)]; + let broadcast = Launch::new(&PLE_BATCH, "ple_broadcast", [blocks, 1, 1], [THREADS, 1, 1], 0, broadcast_args)?; + let rms_gated = ple_rms(s.gated, a.norm_conv, s.norm)?; + let conv_args = + vec![A::P(a.history), A::P(s.norm), A::P(a.conv1d), A::P(r), A::P(s.gated), A::P(s.conv), A::I32(1)]; + let conv = Launch::new(&PLE_BATCH, "ple_conv", [blocks, 1, 1], [THREADS, 1, 1], 0, conv_args)?; // ple_history_advance(hist, normalized) - out.push(Launch::new( - &PLE_BATCH, - "ple_history", - [blocks, 1, 1], - [THREADS, 1, 1], - 0, - vec![A::P(a.history), A::P(norm), A::I32(1)], - )?); - Ok(out) + let history_args = vec![A::P(a.history), A::P(s.norm), A::I32(1)]; + let history = Launch::new(&PLE_BATCH, "ple_history", [blocks, 1, 1], [THREADS, 1, 1], 0, history_args)?; + Ok([rms_key, rms_hidden, gate, broadcast, rms_gated, conv, history]) } /// `pre(1, group)`'s PLE loop for the rows `[tb, te)`: one `(row, launches)` entry per row, to be @@ -182,10 +189,9 @@ impl<'a, 'ctx> OriginalVerifyGrBinding<'a, 'ctx> { pub fn has_ple(&self) -> bool { self.ple.is_some() } - pub(crate) fn ple_addrs(&self) -> Result { - let p = self.ple.as_ref().ok_or(Error::InvalidQwenShape)?; + fn ple_key_addr(&self, key: &PleKeyBuffer<'a, 'ctx>) -> Result { let c = self.context; - let key = match &p.key { + Ok(match key { PleKeyBuffer::Bf16(b) => PleKey::Bf16(admit(c, b, PLE_KEY_BF16_BYTES)?), PleKeyBuffer::Native { ty, data } => { if !matches!(ty, 42 | 18 | 23 | 8) { @@ -194,7 +200,12 @@ impl<'a, 'ctx> OriginalVerifyGrBinding<'a, 'ctx> { let bytes = native_head_row_bytes(*ty, N)?.checked_mul(D).ok_or(Error::InvalidSize)?; PleKey::Native { ty: *ty, data: admit(c, data, bytes)? } } - }; + }) + } + pub(crate) fn ple_addrs(&self) -> Result { + let p = self.ple.as_ref().ok_or(Error::InvalidQwenShape)?; + let c = self.context; + let key = self.ple_key_addr(&p.key)?; let scratch = p.scratch; if !std::ptr::eq(c, scratch.context) { return Err(Error::ContextMismatch); diff --git a/crates/cuda-driver/src/original_verify_window_kernels.rs b/crates/cuda-driver/src/original_verify_window_kernels.rs index ff019c31..aeb5b80e 100644 --- a/crates/cuda-driver/src/original_verify_window_kernels.rs +++ b/crates/cuda-driver/src/original_verify_window_kernels.rs @@ -87,7 +87,12 @@ impl AssetSpec { wrong[31] ^= 1; assert_eq!(self.derived(self.ptx, wrong).sealed(), refuse, "{}", self.name); assert_eq!(self.derived(self.ptx, [0; 32]).sealed(), refuse, "{}", self.name); - // a placeholder marker is refused even when its digest matches the bytes + self.assert_marker_refused(refuse); + } + + /// A placeholder marker is refused even when its digest matches the bytes. + fn assert_marker_refused(&self, refuse: Result<&'static [u8]>) { + use crate::sealed_ptx::test_support::*; let mut marked = b"// UNSEALED placeholder\n".to_vec(); marked.extend_from_slice(&self.ptx[..self.ptx.len() - 1]); let digest = crate::qwen_ffi::sha256(&marked); diff --git a/crates/cuda-driver/src/original_verify_window_moe/plan_expert_groups_fn.rs b/crates/cuda-driver/src/original_verify_window_moe/plan_expert_groups_fn.rs index eeded43b..7c93ee9b 100644 --- a/crates/cuda-driver/src/original_verify_window_moe/plan_expert_groups_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_moe/plan_expert_groups_fn.rs @@ -27,114 +27,143 @@ pub(crate) fn plan_expert_groups( } let gu_entry = GU_ENTRIES.iter().find(|e| e.0 == blob.gu_type).ok_or(Error::UnsupportedQwenOperation)?.1; let down_entry = DOWN_ENTRIES.iter().find(|e| e.0 == blob.d_type).ok_or(Error::UnsupportedQwenOperation)?.1; - let layout = PlanLayout::new(g.max_t * g.k); - let (ptr_word, start_word, count_word) = match tier { - ExpertTier::Vram => (layout.ptr, layout.start, layout.counts), - ExpertTier::Pcie => (layout.ptr2, layout.start2, layout.counts + 2), - }; - let group = rows.group; - let grp_ptr = plan_word(arena, g, group, ptr_word)?; - let grp_start = plan_word(arena, g, group, start_word)?; - let n_groups = plan_word(arena, g, group, count_word)?; - let ent_dst = plan_word(arena, g, group, layout.dst)?; - let ent_tok = plan_word(arena, g, group, layout.tok)?; - let (n_embd, n_ff, tb) = (g.n, g.ff, rows.begin); - let cap = n * g.k; - let row_bytes = proj::q8_1_row_bytes(n_embd); - let x_q8_1 = arena.span("nat_xq", tb * row_bytes, n * row_bytes)?; - let (fa, scratch_bytes) = expert_scratch(cap, n_ff); - let scratch = arena.span("hit_scratch", 0, scratch_bytes)?; - let (gate, up, h, hq) = (scratch, scratch + fa as u64, scratch + 2 * fa as u64, scratch + 3 * fa as u64); - let out = f32s(arena, "hit_out", tb * g.k * n_embd, cap * n_embd)?; - let nh = cap * n_ff; + let plan = GroupPlan::new(arena, g, rows, tier, n)?; let words = blob.words(); let tiny = super::super::chain::flags().tiny; - let swiglu_quant = |tiny: bool| -> Result> { - if tiny { - return Ok(vec![Launch::new( - &super::super::chain::CHAIN, - super::super::chain::E_SWIGLU_QUANT, - [nh.div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![A::P(gate), A::P(up), A::P(h), A::P(hq), A::I64(nh as i64)], - )?]); - } - Ok(vec![ - Launch::new( - &HEAD_IQ_EXPERT, - E_SWIGLU_ENTRIES, - [nh.div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![A::P(gate), A::P(up), A::P(h), A::I64(nh as i64)], - )?, - Launch::new( - &HEAD_IQ_EXPERT, - E_QUANTIZE_Q8_1, - [nh.div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![A::P(h), A::P(hq), A::I64(nh as i64)], - )?, - ]) - }; - let mut launches = Vec::with_capacity(4); - // sm_120 GU_SWIGLU: one launch for gate/up + SwiGLU + q8_1 where the layer's format has the fused kernel (80 dots a row at n_embd 2560, n_ff a multiple of 32) - let fused = if knobs.gu_swiglu && blob.n_embd == 2560 && blob.n_ff % 32 == 0 { + let fused = fused_gate_up_entry(knobs, &blob); + plan.launches([gu_entry, down_entry], fused, words, tiny) +} + +/// sm_120 GU_SWIGLU: one launch for gate/up + SwiGLU + q8_1 where the layer's format has the fused kernel +/// (80 dots a row at n_embd 2560, n_ff a multiple of 32). +fn fused_gate_up_entry(knobs: &MoeKnobs, blob: &ExpertBlob) -> Option<&'static str> { + if knobs.gu_swiglu && blob.n_embd == 2560 && blob.n_ff % 32 == 0 { super::super::sm120::gu_swiglu_entry(blob.gu_type) } else { None - }; - if let Some(entry) = fused { - // upstream's 88-byte NativeExpertLayout: the 64 bytes above, then tail_off, had_block (+ padding) and d_signs, all zero - let mut fused_words = words.clone(); - fused_words.extend([0u64; 3]); - launches.push(Launch::new( - &super::super::sm120::GU_SWIGLU, - entry, - [(n_ff / 32) as u32, cap as u32, 1], - [512, 1, 1], - 0, - vec![ - A::P(grp_ptr), - A::P(grp_start), - A::P(n_groups), - A::P(ent_tok), - A::P(x_q8_1), - A::Words(fused_words), - A::P(hq), - ], - )?); - } else { - launches.push(Launch::new( - &EXPERTS, - gu_entry, - [(2 * n_ff).div_ceil(8) as u32, cap as u32, 1], - [256, 1, 1], - 0, - vec![ - A::P(grp_ptr), - A::P(grp_start), - A::P(n_groups), - A::P(ent_tok), - A::P(x_q8_1), - A::Words(words.clone()), - A::P(gate), - A::P(up), - ], - )?); - launches.extend(swiglu_quant(tiny)?); } - launches.push(Launch::new( - &EXPERTS, - down_entry, - [n_embd.div_ceil(8) as u32, cap as u32, 1], - [256, 1, 1], - 0, - vec![A::P(grp_ptr), A::P(grp_start), A::P(n_groups), A::P(ent_dst), A::P(hq), A::Words(words), A::P(out)], - )?); - Ok(launches) +} + +/// The plan words, activations and scratch addresses one grouped-expert plan launches over. +struct GroupPlan { + grp_ptr: u64, + grp_start: u64, + n_groups: u64, + ent_dst: u64, + ent_tok: u64, + x_q8_1: u64, + gate: u64, + up: u64, + h: u64, + hq: u64, + out: u64, + n_embd: usize, + n_ff: usize, + cap: usize, +} + +impl GroupPlan { + fn new(arena: &dyn ArenaMap, g: &OriginalVerifyGeometry, rows: Rows, tier: ExpertTier, n: usize) -> Result { + let layout = PlanLayout::new(g.max_t * g.k); + let (ptr_word, start_word, count_word) = match tier { + ExpertTier::Vram => (layout.ptr, layout.start, layout.counts), + ExpertTier::Pcie => (layout.ptr2, layout.start2, layout.counts + 2), + }; + let group = rows.group; + let grp_ptr = plan_word(arena, g, group, ptr_word)?; + let grp_start = plan_word(arena, g, group, start_word)?; + let n_groups = plan_word(arena, g, group, count_word)?; + let ent_dst = plan_word(arena, g, group, layout.dst)?; + let ent_tok = plan_word(arena, g, group, layout.tok)?; + let (n_embd, n_ff, tb) = (g.n, g.ff, rows.begin); + let cap = n * g.k; + let row_bytes = proj::q8_1_row_bytes(n_embd); + let x_q8_1 = arena.span("nat_xq", tb * row_bytes, n * row_bytes)?; + let (fa, scratch_bytes) = expert_scratch(cap, n_ff); + let scratch = arena.span("hit_scratch", 0, scratch_bytes)?; + let (gate, up, h, hq) = (scratch, scratch + fa as u64, scratch + 2 * fa as u64, scratch + 3 * fa as u64); + let out = f32s(arena, "hit_out", tb * g.k * n_embd, cap * n_embd)?; + Ok(Self { grp_ptr, grp_start, n_groups, ent_dst, ent_tok, x_q8_1, gate, up, h, hq, out, n_embd, n_ff, cap }) + } + + /// The gate/up launches (fused, or gate/up then SwiGLU + quantise) and the down launch. + fn launches( + &self, + entries: [&'static str; 2], + fused: Option<&'static str>, + words: Vec, + tiny: bool, + ) -> Result> { + let mut launches = Vec::with_capacity(4); + match fused { + Some(entry) => launches.push(self.fused_gate_up(entry, &words)?), + None => { + launches.push(self.gate_up(entries[0], &words)?); + launches.extend(self.swiglu_quant(tiny)?); + } + } + launches.push(self.down(entries[1], words)?); + Ok(launches) + } + + /// SwiGLU + q8_1 quantisation of the gate/up scratch: one chain launch (`tiny`) or the two expert-module ones. + fn swiglu_quant(&self, tiny: bool) -> Result> { + let nh = self.cap * self.n_ff; + let (gate, up, h, hq) = (self.gate, self.up, self.h, self.hq); + let grid = [nh.div_ceil(256) as u32, 1, 1]; + if tiny { + let args = vec![A::P(gate), A::P(up), A::P(h), A::P(hq), A::I64(nh as i64)]; + let (chain, entry) = (&super::super::chain::CHAIN, super::super::chain::E_SWIGLU_QUANT); + return Ok(vec![Launch::new(chain, entry, grid, [256, 1, 1], 0, args)?]); + } + let swiglu_args = vec![A::P(gate), A::P(up), A::P(h), A::I64(nh as i64)]; + let quant_args = vec![A::P(h), A::P(hq), A::I64(nh as i64)]; + Ok(vec![ + Launch::new(&HEAD_IQ_EXPERT, E_SWIGLU_ENTRIES, grid, [256, 1, 1], 0, swiglu_args)?, + Launch::new(&HEAD_IQ_EXPERT, E_QUANTIZE_Q8_1, grid, [256, 1, 1], 0, quant_args)?, + ]) + } + + fn fused_gate_up(&self, entry: &'static str, words: &[u64]) -> Result { + // upstream's 88-byte NativeExpertLayout: the 64 bytes above, then tail_off, had_block (+ padding) and d_signs, + // all zero + let mut fused_words = words.to_vec(); + fused_words.extend([0u64; 3]); + let args = vec![ + A::P(self.grp_ptr), + A::P(self.grp_start), + A::P(self.n_groups), + A::P(self.ent_tok), + A::P(self.x_q8_1), + A::Words(fused_words), + A::P(self.hq), + ]; + let grid = [(self.n_ff / 32) as u32, self.cap as u32, 1]; + Launch::new(&super::super::sm120::GU_SWIGLU, entry, grid, [512, 1, 1], 0, args) + } + + fn gate_up(&self, entry: &'static str, words: &[u64]) -> Result { + let args = vec![ + A::P(self.grp_ptr), + A::P(self.grp_start), + A::P(self.n_groups), + A::P(self.ent_tok), + A::P(self.x_q8_1), + A::Words(words.to_vec()), + A::P(self.gate), + A::P(self.up), + ]; + let grid = [(2 * self.n_ff).div_ceil(8) as u32, self.cap as u32, 1]; + Launch::new(&EXPERTS, entry, grid, [256, 1, 1], 0, args) + } + + fn down(&self, entry: &'static str, words: Vec) -> Result { + let (ptr, start, groups, dst) = (self.grp_ptr, self.grp_start, self.n_groups, self.ent_dst); + let args = + vec![A::P(ptr), A::P(start), A::P(groups), A::P(dst), A::P(self.hq), A::Words(words), A::P(self.out)]; + let grid = [self.n_embd.div_ceil(8) as u32, self.cap as u32, 1]; + Launch::new(&EXPERTS, entry, grid, [256, 1, 1], 0, args) + } } /// `moe_hit_add(parts_ + tb*K*N, hit_out, p_dst, p_counts + 1, cap, N)`: @@ -169,28 +198,9 @@ pub(crate) fn plan_combine( batched: bool, ) -> Result> { let n = check_rows(g, rows)?; - let (n_embd, k, tb) = (g.n, g.k, rows.begin); - let native = |parts: u64, w: u64, shared: u64, bo: u64, tokens: usize| { - Launch::new( - &COMBINE, - E_COMBINE, - [n_embd.div_ceil(256) as u32, tokens as u32, 1], - [256, 1, 1], - 0, - vec![A::P(parts), A::P(w), A::P(shared), A::P(bo), A::I64(n_embd as i64), A::I32(k as i32)], - ) - }; + let (n_embd, k) = (g.n, g.k); if batched { - if n < 2 || !knobs.native_combine { - return Err(Error::InvalidQwenShape); - } - return Ok(vec![native( - f32s(arena, "parts", tb * k * n_embd, n * k * n_embd)?, - f32s(arena, "w", tb * k, n * k)?, - f32s(arena, "shared", tb * n_embd, n * n_embd)?, - f32s(arena, "bo", tb * n_embd, n * n_embd)?, - n, - )?]); + return combine_batched(arena, g, knobs, rows); } let mut out = Vec::with_capacity(n); for t in rows.begin..rows.end { @@ -199,17 +209,43 @@ pub(crate) fn plan_combine( let shared = f32s(arena, "shared", t * n_embd, n_embd)?; let bo = f32s(arena, "bo", t * n_embd, n_embd)?; if knobs.native_combine { - out.push(native(parts, w, shared, bo, 1)?); + out.push(combine_native(g, [parts, w, shared, bo], 1)?); } else { - out.push(Launch::new( - &SHARED, - E_MOE_COMBINE, - [n_embd.div_ceil(128) as u32, 1, 1], - [128, 1, 1], - 0, - vec![A::P(parts), A::P(w), A::P(shared), A::P(bo), A::I32(n_embd as i32), A::I32(k as i32), A::I32(1)], - )?); + out.push(combine_legacy(g, [parts, w, shared, bo])?); } } Ok(out) } + +/// `native_moe_combine` over `tokens` rows of `[parts, w, shared, bo]` (`grid.y` = token). +fn combine_native(g: &OriginalVerifyGeometry, [parts, w, shared, bo]: [u64; 4], tokens: usize) -> Result { + let (n_embd, k) = (g.n, g.k); + let args = vec![A::P(parts), A::P(w), A::P(shared), A::P(bo), A::I64(n_embd as i64), A::I32(k as i32)]; + Launch::new(&COMBINE, E_COMBINE, [n_embd.div_ceil(256) as u32, tokens as u32, 1], [256, 1, 1], 0, args) +} + +/// The legacy double-precision `moe_combine` of one row. +fn combine_legacy(g: &OriginalVerifyGeometry, [parts, w, shared, bo]: [u64; 4]) -> Result { + let (n_embd, k) = (g.n, g.k); + let args = vec![A::P(parts), A::P(w), A::P(shared), A::P(bo), A::I32(n_embd as i32), A::I32(k as i32), A::I32(1)]; + Launch::new(&SHARED, E_MOE_COMBINE, [n_embd.div_ceil(128) as u32, 1, 1], [128, 1, 1], 0, args) +} + +/// ONE `native_moe_combine_multi` launch over all rows of the group. +fn combine_batched( + arena: &dyn ArenaMap, + g: &OriginalVerifyGeometry, + knobs: &MoeKnobs, + rows: Rows, +) -> Result> { + let n = rows.len(); + let (n_embd, k, tb) = (g.n, g.k, rows.begin); + if n < 2 || !knobs.native_combine { + return Err(Error::InvalidQwenShape); + } + let parts = f32s(arena, "parts", tb * k * n_embd, n * k * n_embd)?; + let w = f32s(arena, "w", tb * k, n * k)?; + let shared = f32s(arena, "shared", tb * n_embd, n * n_embd)?; + let bo = f32s(arena, "bo", tb * n_embd, n * n_embd)?; + Ok(vec![combine_native(g, [parts, w, shared, bo], n)?]) +} diff --git a/crates/cuda-driver/src/original_verify_window_moe/plan_f32_to_bf16_fn.rs b/crates/cuda-driver/src/original_verify_window_moe/plan_f32_to_bf16_fn.rs index 15259a3f..e5667dab 100644 --- a/crates/cuda-driver/src/original_verify_window_moe/plan_f32_to_bf16_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_moe/plan_f32_to_bf16_fn.rs @@ -44,19 +44,9 @@ pub(crate) fn plan_router( if ne != 512 || k != 10 { return unavailable!("router", "the router kernels are the canonical 512 experts x top-10 only"); } - let mixed = |t: usize, c: usize| f32s(arena, "mixed", t * n_embd, c * n_embd); - let logits = |t: usize, c: usize| f32s(arena, "logits", t * ne, c * ne); - let ids = |t: usize, c: usize| items(arena, "ids", t * k, c * k, 4); - let weights = |t: usize, c: usize| f32s(arena, "w", t * k, c * k); + let spans = RouterSpans { arena, n_embd, ne, k }; if batched { - if n < 2 || !knobs.native_router { - return Err(Error::InvalidQwenShape); - } - let (x, y) = (mixed(tb, n)?, logits(tb, n)?); - return Ok(vec![ - plan_bf16_gemv(x, n_embd, router, y, ne, n_embd, ne, n)?, - plan_route(y, ids(tb, n)?, weights(tb, n)?, n)?, - ]); + return router_batched(&spans, knobs, router, (tb, n)); } if !knobs.native_bf16 { return unavailable!( @@ -66,27 +56,71 @@ pub(crate) fn plan_router( } let mut out = Vec::with_capacity(2 * n); for t in rows.begin..rows.end { - let (x, y) = (mixed(t, 1)?, logits(t, 1)?); - out.push(plan_bf16_gemv(x, n_embd, router, y, ne, n_embd, ne, 1)?); - if knobs.native_router { - out.push(plan_route(y, ids(t, 1)?, weights(t, 1)?, 1)?); - } else { - // router_top10(logits, 1, NE, K, ids, weights): threads = min(NE, 512) rounded to a warp, - // smem = taken (NE rounded to 16) + NE doubles + NE floats. - let smem = ((ne + 15) & !15) + ne * 8 + ne * 4; - out.push(Launch::new( - &ROUTER_LEGACY, - E_ROUTER_TOP10, - [1, 1, 1], - [((ne.min(512) + 31) & !31) as u32, 1, 1], - smem as u32, - vec![A::P(y), A::I32(1), A::I32(ne as i32), A::I32(k as i32), A::P(ids(t, 1)?), A::P(weights(t, 1)?)], - )?); - } + router_row(&spans, knobs, router, t, &mut out)?; } Ok(out) } +/// The arena spans of the router's activations, logits, ids and weights for `c` rows from row `t`. +struct RouterSpans<'a> { + arena: &'a dyn ArenaMap, + n_embd: usize, + ne: usize, + k: usize, +} + +impl RouterSpans<'_> { + fn mixed(&self, t: usize, c: usize) -> Result { + f32s(self.arena, "mixed", t * self.n_embd, c * self.n_embd) + } + fn logits(&self, t: usize, c: usize) -> Result { + f32s(self.arena, "logits", t * self.ne, c * self.ne) + } + fn ids(&self, t: usize, c: usize) -> Result { + items(self.arena, "ids", t * self.k, c * self.k, 4) + } + fn weights(&self, t: usize, c: usize) -> Result { + f32s(self.arena, "w", t * self.k, c * self.k) + } +} + +/// ONE logits GEMV reading the weight once for the `n` rows from `tb`, and one top-10 launch. +fn router_batched( + spans: &RouterSpans<'_>, + knobs: &MoeKnobs, + router: u64, + (tb, n): (usize, usize), +) -> Result> { + if n < 2 || !knobs.native_router { + return Err(Error::InvalidQwenShape); + } + let (n_embd, ne) = (spans.n_embd, spans.ne); + let (x, y) = (spans.mixed(tb, n)?, spans.logits(tb, n)?); + Ok(vec![ + plan_bf16_gemv(x, n_embd, router, y, ne, n_embd, ne, n)?, + plan_route(y, spans.ids(tb, n)?, spans.weights(tb, n)?, n)?, + ]) +} + +/// `moe_route` of row `t`: the logits GEMV, then the native top-10 or the generic `router_top10_kernel`. +fn router_row(spans: &RouterSpans<'_>, knobs: &MoeKnobs, router: u64, t: usize, out: &mut Vec) -> Result<()> { + let (n_embd, ne, k) = (spans.n_embd, spans.ne, spans.k); + let (x, y) = (spans.mixed(t, 1)?, spans.logits(t, 1)?); + out.push(plan_bf16_gemv(x, n_embd, router, y, ne, n_embd, ne, 1)?); + if knobs.native_router { + out.push(plan_route(y, spans.ids(t, 1)?, spans.weights(t, 1)?, 1)?); + } else { + // router_top10(logits, 1, NE, K, ids, weights): threads = min(NE, 512) rounded to a warp, + // smem = taken (NE rounded to 16) + NE doubles + NE floats. + let smem = ((ne + 15) & !15) + ne * 8 + ne * 4; + let threads = ((ne.min(512) + 31) & !31) as u32; + let (ids, weights) = (spans.ids(t, 1)?, spans.weights(t, 1)?); + let args = vec![A::P(y), A::I32(1), A::I32(ne as i32), A::I32(k as i32), A::P(ids), A::P(weights)]; + out.push(Launch::new(&ROUTER_LEGACY, E_ROUTER_TOP10, [1, 1, 1], [threads, 1, 1], smem as u32, args)?); + } + Ok(()) +} + // --------------------------------------------------------------------------------------------- // shared expert // --------------------------------------------------------------------------------------------- @@ -105,87 +139,116 @@ pub(crate) fn plan_shared_expert( let n = check_rows(g, rows)?; let (n_embd, n_ff, tb) = (g.n, g.ff, rows.begin); let xm = f32s(arena, "mixed", tb * n_embd, n * n_embd)?; - let bf16 = |t: usize, c: usize| items(arena, "sh_bf16", t * n_embd, c * n_embd, 2); - let mut out = Vec::new(); let tiny = super::super::chain::flags().tiny; - // `sh_bf16` is read only by the scalar gate that runs without --native-bf16-extra - if tiny && knobs.native_bf16_extra { - } else if dec_batch { - out.push(plan_f32_to_bf16(xm, bf16(tb, n)?, n * n_embd)?); - } else { - for t in rows.begin..rows.end { - out.push(plan_f32_to_bf16(f32s(arena, "mixed", t * n_embd, n_embd)?, bf16(t, 1)?, n_embd)?); - } + let p = SharedExpert { arena, knobs, w, n, n_embd, n_ff, tb, tiny, dec_batch, xm }; + let mut out = Vec::new(); + p.convert_to_bf16(rows, &mut out)?; + let (gscalar, shared) = p.project(&mut out)?; + p.gate_scalar(gscalar, &mut out)?; + p.scale_rows(shared, gscalar, &mut out)?; + Ok(out) +} + +/// The shared expert of one group: what its launches read, in the order `plan_shared_expert` plans them. +struct SharedExpert<'a> { + arena: &'a dyn ArenaMap, + knobs: &'a MoeKnobs, + w: &'a MoeLayerAddrs, + n: usize, + n_embd: usize, + n_ff: usize, + tb: usize, + tiny: bool, + dec_batch: bool, + xm: u64, +} + +impl SharedExpert<'_> { + fn bf16(&self, t: usize, c: usize) -> Result { + items(self.arena, "sh_bf16", t * self.n_embd, c * self.n_embd, 2) } - // shared_expert_multi - // `nw.q8_1 = xq_`: first the n activation rows (N values), then the n activated gate rows (n_ff values) - let xq = arena.span("xq", 0, n * proj::q8_1_row_bytes(n_embd.max(n_ff)))?; - let gate = f32s(arena, "sh_gate", tb * n_ff, n * n_ff)?; - let up = f32s(arena, "sh_up", tb * n_ff, n * n_ff)?; - let gscalar = f32s(arena, "sh_g", tb, n)?; - let shared = f32s(arena, "shared", tb * n_embd, n * n_embd)?; - out.push(plan_quantize_q8_1(xm, xq, n_embd, n)?); - out.push(plan_mmvq(&w.gate_shexp, xq, gate, n_embd, n_ff, n, knobs.dispatch)?); - out.push(plan_mmvq(&w.up_shexp, xq, up, n_embd, n_ff, n, knobs.dispatch)?); - let count = n_ff * n; - out.push(Launch::new( - &SHARED, - E_NATIVE_SWIGLU, - [count.div_ceil(128) as u32, 1, 1], - [128, 1, 1], - 0, - vec![A::P(gate), A::P(up), A::P(gate), A::I32(count as i32)], - )?); - out.push(plan_quantize_q8_1(gate, xq, n_ff, n)?); - out.push(plan_mmvq(&w.down_shexp, xq, shared, n_ff, n_embd, n, knobs.dispatch)?); - if knobs.native_bf16_extra && dec_batch && n > 1 { - // one GEMV for all rows (outputs identical), one sigmoid launch with thread t = token t - out.push(plan_bf16_gemv(xm, n_embd, w.gate_inp_shexp, gscalar, 1, n_embd, 1, n)?); - if !tiny { - out.push(Launch::new(&SHARED, E_SIGMOID_MULTI, [1, 1, 1], [n as u32, 1, 1], 0, vec![A::P(gscalar)])?); - } - } else { - for t in 0..n { - let g_t = f32s(arena, "sh_g", tb + t, 1)?; - if knobs.native_bf16_extra { - let x_t = f32s(arena, "mixed", (tb + t) * n_embd, n_embd)?; - out.push(plan_bf16_gemv(x_t, n_embd, w.gate_inp_shexp, g_t, 1, n_embd, 1, 1)?); - if !tiny { - out.push(Launch::new(&SHARED, E_SIGMOID, [1, 1, 1], [1, 1, 1], 0, vec![A::P(g_t)])?); - } - } else { - out.push(Launch::new( - &SHARED, - E_SCALAR_GATE, - [1, 1, 1], - [256, 1, 1], - 0, - vec![A::P(bf16(tb + t, 1)?), A::P(w.gate_inp_shexp), A::P(g_t), A::I32(n_embd as i32)], - )?); + + /// `sh_bf16` is read only by the scalar gate that runs without --native-bf16-extra. + fn convert_to_bf16(&self, rows: Rows, out: &mut Vec) -> Result<()> { + let (n, n_embd, tb) = (self.n, self.n_embd, self.tb); + if self.tiny && self.knobs.native_bf16_extra { + } else if self.dec_batch { + out.push(plan_f32_to_bf16(self.xm, self.bf16(tb, n)?, n * n_embd)?); + } else { + for t in rows.begin..rows.end { + out.push(plan_f32_to_bf16(f32s(self.arena, "mixed", t * n_embd, n_embd)?, self.bf16(t, 1)?, n_embd)?); } } + Ok(()) } - if tiny && knobs.native_bf16_extra { - // sigmoid of the gate scalar folded into the row scale (the gate buffer is left raw) - out.push(Launch::new( - &super::super::chain::CHAIN, - super::super::chain::E_SCALE_SIGMOID, - [n_embd.div_ceil(128) as u32, n as u32, 1], - [128, 1, 1], - 0, - vec![A::P(shared), A::P(gscalar), A::I32(n_embd as i32)], - )?); - return Ok(out); + + /// shared_expert_multi: the gate/up projections, SwiGLU and the down projection; returns the gate scalar and + /// output spans. `nw.q8_1 = xq_`: first the n activation rows (N values), then the n activated gate rows + /// (n_ff values) + fn project(&self, out: &mut Vec) -> Result<(u64, u64)> { + let (arena, w, dispatch) = (self.arena, self.w, self.knobs.dispatch); + let (n, n_embd, n_ff, tb) = (self.n, self.n_embd, self.n_ff, self.tb); + let xq = arena.span("xq", 0, n * proj::q8_1_row_bytes(n_embd.max(n_ff)))?; + let gate = f32s(arena, "sh_gate", tb * n_ff, n * n_ff)?; + let up = f32s(arena, "sh_up", tb * n_ff, n * n_ff)?; + let gscalar = f32s(arena, "sh_g", tb, n)?; + let shared = f32s(arena, "shared", tb * n_embd, n * n_embd)?; + out.push(plan_quantize_q8_1(self.xm, xq, n_embd, n)?); + out.push(plan_mmvq(&w.gate_shexp, xq, gate, n_embd, n_ff, n, dispatch)?); + out.push(plan_mmvq(&w.up_shexp, xq, up, n_embd, n_ff, n, dispatch)?); + let count = n_ff * n; + let args = vec![A::P(gate), A::P(up), A::P(gate), A::I32(count as i32)]; + out.push(Launch::new(&SHARED, E_NATIVE_SWIGLU, [count.div_ceil(128) as u32, 1, 1], [128, 1, 1], 0, args)?); + out.push(plan_quantize_q8_1(gate, xq, n_ff, n)?); + out.push(plan_mmvq(&w.down_shexp, xq, shared, n_ff, n_embd, n, dispatch)?); + Ok((gscalar, shared)) + } + + fn gate_scalar(&self, gscalar: u64, out: &mut Vec) -> Result<()> { + let (n, n_embd) = (self.n, self.n_embd); + if self.knobs.native_bf16_extra && self.dec_batch && n > 1 { + // one GEMV for all rows (outputs identical), one sigmoid launch with thread t = token t + out.push(plan_bf16_gemv(self.xm, n_embd, self.w.gate_inp_shexp, gscalar, 1, n_embd, 1, n)?); + if !self.tiny { + out.push(Launch::new(&SHARED, E_SIGMOID_MULTI, [1, 1, 1], [n as u32, 1, 1], 0, vec![A::P(gscalar)])?); + } + return Ok(()); + } + for t in 0..n { + self.gate_scalar_row(self.tb + t, out)?; + } + Ok(()) + } + + fn gate_scalar_row(&self, row: usize, out: &mut Vec) -> Result<()> { + let n_embd = self.n_embd; + let g_t = f32s(self.arena, "sh_g", row, 1)?; + if self.knobs.native_bf16_extra { + let x_t = f32s(self.arena, "mixed", row * n_embd, n_embd)?; + out.push(plan_bf16_gemv(x_t, n_embd, self.w.gate_inp_shexp, g_t, 1, n_embd, 1, 1)?); + if !self.tiny { + out.push(Launch::new(&SHARED, E_SIGMOID, [1, 1, 1], [1, 1, 1], 0, vec![A::P(g_t)])?); + } + } else { + let args = vec![A::P(self.bf16(row, 1)?), A::P(self.w.gate_inp_shexp), A::P(g_t), A::I32(n_embd as i32)]; + out.push(Launch::new(&SHARED, E_SCALAR_GATE, [1, 1, 1], [256, 1, 1], 0, args)?); + } + Ok(()) + } + + /// Scales the shared output rows by the gate scalar; `tiny` folds the sigmoid into the row scale (the gate buffer + /// is left raw). + fn scale_rows(&self, shared: u64, gscalar: u64, out: &mut Vec) -> Result<()> { + let grid = [self.n_embd.div_ceil(128) as u32, self.n as u32, 1]; + let args = vec![A::P(shared), A::P(gscalar), A::I32(self.n_embd as i32)]; + if self.tiny && self.knobs.native_bf16_extra { + let (chain, entry) = (&super::super::chain::CHAIN, super::super::chain::E_SCALE_SIGMOID); + out.push(Launch::new(chain, entry, grid, [128, 1, 1], 0, args)?); + } else { + out.push(Launch::new(&SHARED, E_SCALE_ROWS, grid, [128, 1, 1], 0, args)?); + } + Ok(()) } - out.push(Launch::new( - &SHARED, - E_SCALE_ROWS, - [n_embd.div_ceil(128) as u32, n as u32, 1], - [128, 1, 1], - 0, - vec![A::P(shared), A::P(gscalar), A::I32(n_embd as i32)], - )?); - Ok(out) } // --------------------------------------------------------------------------------------------- diff --git a/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifier.rs b/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifier.rs index 4bae9670..e9220828 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifier.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifier.rs @@ -16,40 +16,11 @@ impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> { if resources.rows() != t { return Err(Error::InvalidQwenShape); } - // the cluster top-k needs sm_90+ and a sealed module; anything else keeps the Original's qsa_topk_ref let mut policy = policy; - if policy.qsa.cluster_topk { - let cc = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?; - policy.qsa.cluster_topk = cc >= 9 && qsa::CLUSTER.sealed().is_ok(); - static SAID: std::sync::Once = std::sync::Once::new(); - SAID.call_once(|| { - eprintln!( - "leleka-serve qsa decode top-k: {} (compute capability {cc})", - if policy.qsa.cluster_topk { "thread-block cluster" } else { "qsa_topk_ref (cluster refused)" } - ) - }); - } - // the sm_120 decode switches (original_verify_window_sm120.rs): resolved from the card and the environment, once per recording - { - let major = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?; - let minor = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MINOR)?; - let want = sm120::Sm120Switches::from_env(major, minor); - policy.qsa.attn_daily = (policy.qsa.attn_daily || want.attn_daily) && sm120::ATTN_DAILY.sealed().is_ok(); - policy.gu_swiglu = (policy.gu_swiglu || want.gu_swiglu) && sm120::GU_SWIGLU.sealed().is_ok(); - policy.side_mixer = policy.side_mixer || want.side_mixer; - static SAID: std::sync::Once = std::sync::Once::new(); - SAID.call_once(|| eprintln!("leleka-serve sm120 switches: attn_daily={} gu_swiglu={} side_mixer={} (compute capability {major}.{minor}, requested {want:?})", policy.qsa.attn_daily, policy.gu_swiglu, policy.side_mixer)); - } + resolve_cluster_topk(&resources, &mut policy)?; + resolve_sm120_switches(&resources, &mut policy)?; let ple = resources.verifier_journal().has_ple(); - let roles = if policy.pcie_mode == 2 { - let mut roles = [[0usize; 3]; WINDOW_LAYERS]; - for (layer, r) in roles.iter_mut().enumerate() { - *r = resources.experts.role_bytes(layer)?; - } - Some(roles) - } else { - None - }; + let roles = pcie_role_bytes(&resources, policy.pcie_mode)?; self.set_pcie_mode(policy.pcie_mode, roles)?; // Sealed modules load before capture begins (cuModuleLoadData is not a capturable call). let mut resources = resources; @@ -85,6 +56,56 @@ impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> { } } +/// The cluster top-k needs sm_90+ and a sealed module; anything else keeps the Original's qsa_topk_ref. +fn resolve_cluster_topk(resources: &OriginalVerifyWindowResources<'_, '_>, policy: &mut WindowPolicy) -> Result<()> { + if policy.qsa.cluster_topk { + let cc = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?; + policy.qsa.cluster_topk = cc >= 9 && qsa::CLUSTER.sealed().is_ok(); + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| { + eprintln!( + "leleka-serve qsa decode top-k: {} (compute capability {cc})", + if policy.qsa.cluster_topk { "thread-block cluster" } else { "qsa_topk_ref (cluster refused)" } + ) + }); + } + Ok(()) +} + +/// The sm_120 decode switches (original_verify_window_sm120.rs): resolved from the card and the environment, once per +/// recording. +fn resolve_sm120_switches(resources: &OriginalVerifyWindowResources<'_, '_>, policy: &mut WindowPolicy) -> Result<()> { + let major = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?; + let minor = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MINOR)?; + let want = sm120::Sm120Switches::from_env(major, minor); + policy.qsa.attn_daily = (policy.qsa.attn_daily || want.attn_daily) && sm120::ATTN_DAILY.sealed().is_ok(); + policy.gu_swiglu = (policy.gu_swiglu || want.gu_swiglu) && sm120::GU_SWIGLU.sealed().is_ok(); + policy.side_mixer = policy.side_mixer || want.side_mixer; + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| { + eprintln!( + "leleka-serve sm120 switches: attn_daily={} gu_swiglu={} side_mixer={} (compute capability {major}.{minor}, requested {want:?})", + policy.qsa.attn_daily, policy.gu_swiglu, policy.side_mixer + ) + }); + Ok(()) +} + +/// The per-layer gate/up/down role bytes of the experts for the copy-kernel pcie mode 2, else none. +fn pcie_role_bytes( + resources: &OriginalVerifyWindowResources<'_, '_>, + pcie_mode: u8, +) -> Result> { + if pcie_mode != 2 { + return Ok(None); + } + let mut roles = [[0usize; 3]; WINDOW_LAYERS]; + for (layer, r) in roles.iter_mut().enumerate() { + *r = resources.experts.role_bytes(layer)?; + } + Ok(Some(roles)) +} + /// A graph instantiate that ran out of device memory, named by the graph that did not fit (`window` = its T, 0 = the commit graph). /// Any other error, and an out-of-memory that came with a cleanup failure (`Multiple`), stays as it is. pub(crate) fn graph_oom_at(error: Error, window: usize) -> Error { diff --git a/crates/cuda-driver/src/original_verify_window_ops/impl_windowops_for_originalverifywindowops.rs b/crates/cuda-driver/src/original_verify_window_ops/impl_windowops_for_originalverifywindowops.rs index 76af0ae2..4f8202c0 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/impl_windowops_for_originalverifywindowops.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/impl_windowops_for_originalverifywindowops.rs @@ -146,35 +146,17 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { } fn wait_plan(&mut self, ring: u32, rows: Rows) -> Result<()> { if chain::flags().glue { - // wait flag A and the plan block copy in one launch (chain_window.cu) - let layout = self.plan(); - let flag = self.mapped_flag(11)?; - let device = self.journal().address("plan", self.plan_group_offset(rows.group), layout.words * 4)?; - let mapped = self.journal().physical.mapped_address( - 14, - rows.group * layout.mapped_stride() * 4, - layout.words * 4, - )?; - return self.launch(vec![Launch::new( - &chain::CHAIN, - chain::E_WAIT_COPY_I32, - [1, 1, 1], - [704, 1, 1], - 0, - vec![A::P(flag), A::I32(ring as i32), A::P(device), A::P(mapped), A::I32(layout.words as i32)], - )?]); + return self.wait_plan_glue(ring, rows); } self.wait_flag(11, ring)?; // The pool's GPU plan, copied from mapped host memory into this group's device block. - let layout = self.plan(); - let device = self.journal().address("plan", self.plan_group_offset(rows.group), layout.words * 4)?; - let mapped = - self.journal().physical.mapped_address(14, rows.group * layout.mapped_stride() * 4, layout.words * 4)?; + let words = self.plan().words; + let (device, mapped) = self.plan_copy_addresses(rows)?; self.submit(vec![command( "verify_copy_i32_from_mapped_kernel", [1, 1, 1], [128, 1, 1], - vec![Arg::Address(device), Arg::Address(mapped), Arg::I32(layout.words as i32)], + vec![Arg::Address(device), Arg::Address(mapped), Arg::I32(words as i32)], )?]) } fn expert_groups(&mut self, layer: usize, rows: Rows, tier: ExpertTier) -> Result<()> { @@ -199,25 +181,9 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { let stage = self.journal().address("staging", stage_offset, per * g.max_expert_blob)?; let source = self.plan_word(rows.group, layout.ptr2)?; let count = self.plan_word(rows.group, layout.counts + 2)?; - let words = |bytes: usize| A::I64((bytes / 16) as i64); - let (spec, entry, grid, block) = match moe::pcie_fast_kernel() { - Some((entry, grid, block)) => (&moe::PCIE_FAST, entry, grid, block), - None => (&moe::PCIE, "verify_fetch_spans_kernel", [48 * 8, 1, 1], [256, 1, 1]), - }; - self.launch(vec![Launch::new( - spec, - entry, - grid, - block, - 0, - vec![A::P(source), A::P(count), A::P(stage), words(gate), words(up), words(down)], - )?])?; - self.submit(vec![command( - "verify_rebase_ptrs_kernel", - [1, 1, 1], - [128, 1, 1], - vec![Arg::Address(source), Arg::Address(count), Arg::U64(stage), Arg::I64(stride as i64)], - )?]) + let fetch = pcie_fetch_launch(source, count, stage, [gate, up, down])?; + self.launch(vec![fetch])?; + self.submit(vec![pcie_rebase_command(source, count, stage, stride)?]) } fn wait_cpu(&mut self, ring: u32) -> Result<()> { self.wait_flag(10, ring) @@ -230,40 +196,17 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { let parts = self.journal().address("parts", first, bytes)?; let mapped = self.journal().physical.mapped_address(13, first, bytes)?; if only_cpu_hits && chain::flags().glue { - let layout = self.plan(); - let hit_rows = self.plan_word(rows.group, layout.dst)?; - let count = self.plan_word(rows.group, layout.counts + 1)?; - return self.launch(vec![Launch::new( - &chain::CHAIN, - chain::E_COPY_ROWS, - [(n * g.k) as u32, 1, 1], - [128, 1, 1], - 0, - vec![A::P(parts), A::P(mapped), A::I64((g.n / 4) as i64), A::P(hit_rows), A::P(count)], - )?]); + return self.copy_hit_rows_glue(rows, parts, mapped); } let command = if only_cpu_hits { - let layout = self.plan(); - command( - "verify_copy_rows_from_mapped_kernel", - [(n * g.k) as u32, 1, 1], - [128, 1, 1], - vec![ - Arg::Address(parts), - Arg::Address(mapped), - Arg::I64((g.n / 4) as i64), - Arg::Address(self.plan_word(rows.group, layout.dst)?), - Arg::Address(self.plan_word(rows.group, layout.counts + 1)?), - ], - )? + self.copy_hit_rows_command(rows, parts, mapped)? } else { let n4 = bytes / 16; - command( - "verify_copy_from_mapped_kernel", + let (grid, args) = ( [n4.div_ceil(256).min(64) as u32, 1, 1], - [256, 1, 1], vec![Arg::Address(parts), Arg::Address(mapped), Arg::I64(n4 as i64)], - )? + ); + command("verify_copy_from_mapped_kernel", grid, [256, 1, 1], args)? }; self.submit(vec![command]) } @@ -284,3 +227,75 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { self.resources.base.head.capture_head_greedy(self.capture) } } + +impl OriginalVerifyWindowOps<'_, '_, '_, '_> { + /// Device block and mapped source of this group's GPU plan words. + fn plan_copy_addresses(&self, rows: Rows) -> Result<(u64, u64)> { + let layout = self.plan(); + let device = self.journal().address("plan", self.plan_group_offset(rows.group), layout.words * 4)?; + let mapped = + self.journal().physical.mapped_address(14, rows.group * layout.mapped_stride() * 4, layout.words * 4)?; + Ok((device, mapped)) + } + + /// Wait flag A and the plan block copy in one launch (chain_window.cu). + fn wait_plan_glue(&mut self, ring: u32, rows: Rows) -> Result<()> { + let words = self.plan().words; + let flag = self.mapped_flag(11)?; + let (device, mapped) = self.plan_copy_addresses(rows)?; + let args = vec![A::P(flag), A::I32(ring as i32), A::P(device), A::P(mapped), A::I32(words as i32)]; + self.launch(vec![Launch::new(&chain::CHAIN, chain::E_WAIT_COPY_I32, [1, 1, 1], [704, 1, 1], 0, args)?]) + } + + /// The CPU-hit rows copied back with the plan's hit list, in the chain glue launch. + fn copy_hit_rows_glue(&mut self, rows: Rows, parts: u64, mapped: u64) -> Result<()> { + let g = self.geometry(); + let layout = self.plan(); + let hit_rows = self.plan_word(rows.group, layout.dst)?; + let count = self.plan_word(rows.group, layout.counts + 1)?; + let args = vec![A::P(parts), A::P(mapped), A::I64((g.n / 4) as i64), A::P(hit_rows), A::P(count)]; + let grid = [(rows.len() * g.k) as u32, 1, 1]; + self.launch(vec![Launch::new(&chain::CHAIN, chain::E_COPY_ROWS, grid, [128, 1, 1], 0, args)?]) + } + + /// The CPU-hit rows copied back with the plan's hit list, as a plain kernel command. + fn copy_hit_rows_command(&self, rows: Rows, parts: u64, mapped: u64) -> Result { + let g = self.geometry(); + let layout = self.plan(); + command( + "verify_copy_rows_from_mapped_kernel", + [(rows.len() * g.k) as u32, 1, 1], + [128, 1, 1], + vec![ + Arg::Address(parts), + Arg::Address(mapped), + Arg::I64((g.n / 4) as i64), + Arg::Address(self.plan_word(rows.group, layout.dst)?), + Arg::Address(self.plan_word(rows.group, layout.counts + 1)?), + ], + ) + } +} + +/// verify.cpp `fetch_blobs`: the span copy filling staging slot q with gate|up|down (the fast kernel when sealed). +fn pcie_fetch_launch(source: u64, count: u64, stage: u64, [gate, up, down]: [usize; 3]) -> Result { + let words = |bytes: usize| A::I64((bytes / 16) as i64); + let (spec, entry, grid, block) = match moe::pcie_fast_kernel() { + Some((entry, grid, block)) => (&moe::PCIE_FAST, entry, grid, block), + None => (&moe::PCIE, "verify_fetch_spans_kernel", [48 * 8, 1, 1], [256, 1, 1]), + }; + Launch::new( + spec, + entry, + grid, + block, + 0, + vec![A::P(source), A::P(count), A::P(stage), words(gate), words(up), words(down)], + ) +} + +/// verify.cpp `rebase_ptrs`: `ptr2[q]` pointed at staging slot q. +fn pcie_rebase_command(source: u64, count: u64, stage: u64, stride: usize) -> Result { + let args = vec![Arg::Address(source), Arg::Address(count), Arg::U64(stage), Arg::I64(stride as i64)]; + command("verify_rebase_ptrs_kernel", [1, 1, 1], [128, 1, 1], args) +} diff --git a/crates/cuda-driver/src/original_verify_window_proj/q8_1_row_bytes_fn.rs b/crates/cuda-driver/src/original_verify_window_proj/q8_1_row_bytes_fn.rs index 6f854ee1..ec45b0d3 100644 --- a/crates/cuda-driver/src/original_verify_window_proj/q8_1_row_bytes_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_proj/q8_1_row_bytes_fn.rs @@ -109,24 +109,13 @@ pub(crate) fn plan_bf16_gemv( (i32::try_from(n_in).map_err(|_| Error::InvalidSize)?, u32::try_from(n_out).map_err(|_| Error::InvalidSize)?); let block = mmvf_block_size(n_in); if n_tok == 1 && ldy >= n_out { - return Launch::new( - &BF16, - single_entry(block)?, - [grid, 1, 1], - [block, 1, 1], - 0, - vec![A::P(x), A::P(w), A::P(y), A::I32(n_in32)], - ); + let args = vec![A::P(x), A::P(w), A::P(y), A::I32(n_in32)]; + return Launch::new(&BF16, single_entry(block)?, [grid, 1, 1], [block, 1, 1], 0, args); } let nt = if n_tok <= 4 { 4 } else { 8 }; - Launch::new( - &BF16, - multi_entry(block, nt)?, - [grid, 1, 1], - [block, 1, 1], - 0, - vec![A::P(x), A::I64(ldx as i64), A::P(w), A::P(y), A::I64(ldy as i64), A::I32(n_in32), A::I32(n_tok as i32)], - ) + let (ldx, ldy, n_tok) = (A::I64(ldx as i64), A::I64(ldy as i64), A::I32(n_tok as i32)); + let args = vec![A::P(x), ldx, A::P(w), A::P(y), ldy, A::I32(n_in32), n_tok]; + Launch::new(&BF16, multi_entry(block, nt)?, [grid, 1, 1], [block, 1, 1], 0, args) } // ------------------------------------------------------------------------------------------------ diff --git a/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2.rs b/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2.rs index 5121fdd8..b839913a 100644 --- a/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2.rs +++ b/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2.rs @@ -51,6 +51,19 @@ impl<'a> QsaWindow<'a> { if positions % 4 != 0 || rows == 0 || rows > 65535 || (width != 128 && width != 256) { return Err(Error::InvalidQwenShape); } + let args = self.rope_args(abi, data, rows, width, positions)?; + // native_rope_apply: dim3 grid((head_dim / 2 + 127) / 128, rows), 128 threads + Launch::new( + &DECODE_POSTOPS, + "qsa_decode_rope", + [grid_u32((width / 2).div_ceil(128))?, grid_u32(rows)?, 1], + [128, 1, 1], + 0, + args, + ) + } + /// The kernel arguments of one RoPE launch; the frozen ABI refuses a scaled RoPE, the extended one appends it. + fn rope_args(&self, abi: RopeAbi, data: u64, rows: usize, width: usize, positions: u64) -> Result> { let r = &self.rope; let mut args = vec![ A::P(data), @@ -73,15 +86,7 @@ impl<'a> QsaWindow<'a> { A::F32(r.mscale), ]), } - // native_rope_apply: dim3 grid((head_dim / 2 + 127) / 128, rows), 128 threads - Launch::new( - &DECODE_POSTOPS, - "qsa_decode_rope", - [grid_u32((width / 2).div_ceil(128))?, grid_u32(rows)?, 1], - [128, 1, 1], - 0, - args, - ) + Ok(args) } pub(in super::super) fn rope(&self, data: u64, rows: usize, width: usize, positions: u64) -> Result { self.rope_with(rope_abi()?, data, rows, width, positions) @@ -148,61 +153,35 @@ impl<'a> QsaWindow<'a> { let step = self.span("step", t * 16, 16)?; let k = self.span("kcur", t * nkv * hd * 4, nkv * hd * 4)?; let v = self.span("vcur", t * nkv * hd * 4, nkv * hd * 4)?; - out.push(Launch::new( - &KV_APPEND, - "mtp_original_append", - [grid_u32(nkv)?, grid_u32(hd / 64)?, 2], - [64, 1, 1], - 0, - vec![ - A::P(kv.resident[0]), - A::P(kv.resident[1]), - A::P(kv.resident[2]), - A::P(kv.resident[3]), - A::P(kv.table), - A::P(step), - A::P(k), - A::P(v), - A::I32(declared_i32(nkv)?), - A::I32(declared_i32(hd)?), - A::I32(PAGE_SIZE), - A::P(kv.host[0]), - A::P(kv.host[1]), - A::P(kv.host[2]), - A::P(kv.host[3]), - ], - )?); + out.push(append_launch(kv, [step, k, v], (nkv, hd))?); } Ok(out) } + /// The q/gate split of `count` rows from row `from`. + fn split_q(&self, from: usize, count: usize) -> Result { + let (nh, hd) = (self.g.heads, self.g.head_dim); + let qfull = self.span("qfull", from * nh * 2 * hd * 4, count * nh * 2 * hd * 4)?; + let qcur = self.span("qcur", from * nh * hd * 4, count * nh * hd * 4)?; + // `cudaMemcpy2DAsync(qcur, HD*4, qfull, HD*2*4, HD*4, count*NH)` as the sealed word copy + let args = vec![A::P(qfull), A::P(qcur), A::I64(count as i64)]; + Launch::new(&SPLIT, "qsa_split_q", [grid_u32(count * nh)?, 1, 1], [256, 1, 1], 0, args) + } + /// `qsa_q_path`: q/gate split, q RMS norm with `attn_q_norm.weight`, RoPE with the query positions. pub fn q_path(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result> { let s = self.rows(q, rows, Some(batched))?; let g = &self.g; let (nh, hd) = (g.heads, g.head_dim); - let split = |from: usize, count: usize| -> Result { - let qfull = self.span("qfull", from * nh * 2 * hd * 4, count * nh * 2 * hd * 4)?; - let qcur = self.span("qcur", from * nh * hd * 4, count * nh * hd * 4)?; - // `cudaMemcpy2DAsync(qcur, HD*4, qfull, HD*2*4, HD*4, count*NH)` as the sealed word copy - Launch::new( - &SPLIT, - "qsa_split_q", - [grid_u32(count * nh)?, 1, 1], - [256, 1, 1], - 0, - vec![A::P(qfull), A::P(qcur), A::I64(count as i64)], - ) - }; let mut out = Vec::new(); if batched { - out.push(split(s.tb, s.n)?); + out.push(self.split_q(s.tb, s.n)?); let data = self.span("qcur", s.tb * nh * hd * 4, s.n * nh * hd * 4)?; let pos = self.span("pos", s.tb * nh * 4, s.n * nh * 4)?; out.extend(self.norm_rope(data, w.weights.q_norm, s.n * nh, hd, pos)?); } else { for t in s.tb..s.tb + s.n { - out.push(split(t, 1)?); + out.push(self.split_q(t, 1)?); let data = self.span("qcur", t * nh * hd * 4, nh * hd * 4)?; let pos = self.span("pos", t * nh * 4, nh * 4)?; out.extend(self.norm_rope(data, w.weights.q_norm, nh, hd, pos)?); @@ -239,3 +218,13 @@ impl<'a> QsaWindow<'a> { Ok(out) } } + +/// One `kv_append_q8_step` into the resident pool (if the page is resident) and the host copy. +fn append_launch(kv: &OriginalVerifyQsaKvBinding, [step, k, v]: [u64; 3], (nkv, hd): (usize, usize)) -> Result { + let grid = [grid_u32(nkv)?, grid_u32(hd / 64)?, 2]; + let mut args: Vec = kv.resident.iter().map(|&a| A::P(a)).collect(); + args.extend([A::P(kv.table), A::P(step), A::P(k), A::P(v)]); + args.extend([A::I32(declared_i32(nkv)?), A::I32(declared_i32(hd)?), A::I32(PAGE_SIZE)]); + args.extend(kv.host.iter().map(|&a| A::P(a))); + Launch::new(&KV_APPEND, "mtp_original_append", grid, [64, 1, 1], 0, args) +} diff --git a/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2_2.rs b/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2_2.rs index 496d3c23..229b53ca 100644 --- a/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2_2.rs +++ b/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2_2.rs @@ -14,62 +14,47 @@ impl<'a> QsaWindow<'a> { let steps = self.span("step", s.tb * 16, s.n * 16)?; let scores = self.span("scores", s.tb * mb * 4, s.n * mb * 4)?; let sel = self.span("sel", s.tb * cap * 4, s.n * cap * 4)?; - let scored = if self.policy.scores_multi && s.n <= SCORE_MAX_QUERIES { - // block_scores_multi_kernel<<<256, SCORE_WARPS * 32>>> - Launch::new( - &SELECT, - "qsa_decode_scores", - [256, 1, 1], - [256, 1, 1], - 0, - vec![ - A::P(w.kv.pooled), - A::P(w.kv.dead), - A::P(qidx), - A::P(steps), - A::I32(s.n as i32), - A::I64(mb as i64), - A::P(scores), - ], - )? - } else { - // block_scores_kernel<<<(ceil(max_blocks / 8), nq), 256>>> - Launch::new( - &SELECT, - SCORE_SINGLE, - [grid_u32(mb.div_ceil(8))?, grid_u32(s.n)?, 1], - [256, 1, 1], - 0, - vec![A::P(w.kv.pooled), A::P(w.kv.dead), A::P(qidx), A::P(steps), A::I64(mb as i64), A::P(scores)], - )? - }; + let scored = self.scores_launch(w, s.n, mb, [qidx, steps, scores])?; // Original dispatches the register-resident top-k (`block_topk_reg_kernel`) while max_blocks <= // 1024 * 33; Original documents it as selecting the identical ids (same radix rule, ties to the // lowest index), and only `block_topk_kernel` is sealed, so that one is always launched. - let topk = if self.policy.cluster_topk && s.n <= CLUSTER_MAX_QUERIES { - // block_topk_cluster_kernel<<<(8, nq), 1024, ceil(max_blocks / 8) * 4>>> as a cluster of 8 CTAs: the same ids - Launch::new( - &CLUSTER, - CLUSTER_ENTRIES[0], - [crate::qsa_cluster::CLUSTER_CTAS, grid_u32(s.n)?, 1], - [crate::qsa_cluster::BLOCK, 1, 1], - crate::qsa_cluster::dynamic_smem(mb), - vec![A::P(scores), A::P(steps), A::I64(mb as i64), A::I64(cap as i64), A::P(sel)], - )? - .clustered(crate::qsa_cluster::CLUSTER_CTAS) - } else { - Launch::new( - &SELECT, - "qsa_topk_ref", - [grid_u32(s.n)?, 1, 1], - [256, 1, 1], - 0, - vec![A::P(scores), A::P(steps), A::I64(mb as i64), A::I64(cap as i64), A::P(sel)], - )? - }; + let topk = self.topk_launch(s.n, (mb, cap), [scores, steps, sel])?; Ok(vec![scored, topk]) } + /// The block scores of `n` queries: the multi-query kernel, or one block grid per query. + fn scores_launch(&self, w: &QsaLayerAddrs, n: usize, mb: usize, [qidx, steps, scores]: [u64; 3]) -> Result { + if self.policy.scores_multi && n <= SCORE_MAX_QUERIES { + // block_scores_multi_kernel<<<256, SCORE_WARPS * 32>>> + let args = vec![ + A::P(w.kv.pooled), + A::P(w.kv.dead), + A::P(qidx), + A::P(steps), + A::I32(n as i32), + A::I64(mb as i64), + A::P(scores), + ]; + return Launch::new(&SELECT, "qsa_decode_scores", [256, 1, 1], [256, 1, 1], 0, args); + } + // block_scores_kernel<<<(ceil(max_blocks / 8), nq), 256>>> + let args = vec![A::P(w.kv.pooled), A::P(w.kv.dead), A::P(qidx), A::P(steps), A::I64(mb as i64), A::P(scores)]; + Launch::new(&SELECT, SCORE_SINGLE, [grid_u32(mb.div_ceil(8))?, grid_u32(n)?, 1], [256, 1, 1], 0, args) + } + + /// The top-k of `n` queries over the block scores: the thread-block cluster kernel, or `qsa_topk_ref`. + fn topk_launch(&self, n: usize, (mb, cap): (usize, usize), [scores, steps, sel]: [u64; 3]) -> Result { + let args = vec![A::P(scores), A::P(steps), A::I64(mb as i64), A::I64(cap as i64), A::P(sel)]; + if self.policy.cluster_topk && n <= CLUSTER_MAX_QUERIES { + // block_topk_cluster_kernel<<<(8, nq), 1024, ceil(max_blocks / 8) * 4>>> as a cluster of 8 CTAs: the same ids + let grid = [crate::qsa_cluster::CLUSTER_CTAS, grid_u32(n)?, 1]; + let (block, smem) = ([crate::qsa_cluster::BLOCK, 1, 1], crate::qsa_cluster::dynamic_smem(mb)); + let launch = Launch::new(&CLUSTER, CLUSTER_ENTRIES[0], grid, block, smem, args)?; + return Ok(launch.clustered(crate::qsa_cluster::CLUSTER_CTAS)); + } + Launch::new(&SELECT, "qsa_topk_ref", [grid_u32(n)?, 1, 1], [256, 1, 1], 0, args) + } + /// `qsa_kv_resolve`: the selections' blocks resident, device side (`kv_stream_resolve`). pub fn kv_resolve(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result> { let s = self.rows(q, rows, None)?; @@ -95,8 +80,14 @@ impl<'a> QsaWindow<'a> { /// `qsa_decode_attention`: `qsa_decode_attn_batch` (chunk grid `[chunks, n_head_kv, n]`, merge grid `[n_head, n]`). pub fn decode_attention(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result> { let s = self.rows(q, rows, None)?; + w.kv.validate(&self.g)?; + let a = self.attn_spans(&s)?; + Ok(vec![self.attn_chunk_launch(w, &a)?, self.attn_merge_launch(&a)?]) + } + + /// The arena spans and sizes of one decode attention (`chunks` partial accumulators merged per head). + fn attn_spans(&self, s: &Span) -> Result { let g = &self.g; - w.kv.validate(g)?; let (nh, nkv, hd, cap) = (g.heads, g.kv_heads, g.head_dim, g.selection); let chunks = cap.div_ceil(ATTN_CHUNK); let stride = scratch_floats(g); @@ -107,9 +98,13 @@ impl<'a> QsaWindow<'a> { let part_m = acc + (chunks * nh * hd * 4) as u64; let part_l = part_m + (chunks * nh * 4) as u64; let attn = self.span("attn", s.tb * nh * hd * 4, s.n * nh * hd * 4)?; - // 1.0f / sqrtf(256.0f) - let scale = 1.0f32 / (hd as f32).sqrt(); - let r = &w.kv.resident; + let dims = AttnDims { n: s.n, nh, nkv, chunks, cap, stride }; + Ok(AttnSpans { qcur, ids, steps, acc, part_m, part_l, attn, dims, scale: 1.0f32 / (hd as f32).sqrt() }) + } + + /// The chunk kernel (`[chunks, n_head_kv, n]` grid): one partial softmax accumulator per chunk. + fn attn_chunk_launch(&self, w: &QsaLayerAddrs, a: &AttnSpans) -> Result { + let d = &a.dims; let (chunk_asset, chunk_entry) = if self.policy.attn_daily { (&super::super::super::sm120::ATTN_DAILY, super::super::super::sm120::E_ATTN_CHUNK_DAILY) } else if super::super::super::chain::flags().qsa { @@ -117,67 +112,28 @@ impl<'a> QsaWindow<'a> { } else { (&ATTENTION, "leleka_qsa_decode_chunk") }; - let chunk = Launch::new( - chunk_asset, - chunk_entry, - [grid_u32(chunks)?, grid_u32(nkv)?, grid_u32(s.n)?], - [256, 1, 1], - 0, - vec![ - A::P(qcur), - A::P(r[0]), - A::P(r[1]), - A::P(r[2]), - A::P(r[3]), - A::P(w.kv.table), - A::P(ids), - A::P(steps), - A::I32(declared_i32(nkv)?), - A::I32(PAGE_SIZE), - A::F32(scale), - A::P(acc), - A::P(part_m), - A::P(part_l), - A::I32(declared_i32(chunks)?), - A::I32(declared_i32(cap)?), - A::I64(stride as i64), - ], - )?; - let merge = if self.policy.attn_daily { - Launch::new( - &super::super::super::sm120::ATTN_DAILY, - super::super::super::sm120::E_ATTN_MERGE_V2, - [grid_u32(nh)?, grid_u32(s.n)?, 1], - [256, 1, 1], - 0, - vec![ - A::P(acc), - A::P(part_m), - A::P(part_l), - A::I32(declared_i32(chunks)?), - A::P(steps), - A::P(attn), - A::I64(stride as i64), - ], - )? - } else { - Launch::new( - &ATTENTION, - "leleka_qsa_decode_merge", - [grid_u32(nh)?, grid_u32(s.n)?, 1], - [256, 1, 1], - 0, - vec![ - A::P(acc), - A::P(part_m), - A::P(part_l), - A::I32(declared_i32(chunks)?), - A::P(attn), - A::I64(stride as i64), - ], - )? - }; - Ok(vec![chunk, merge]) + let grid = [grid_u32(d.chunks)?, grid_u32(d.nkv)?, grid_u32(d.n)?]; + let mut args = vec![A::P(a.qcur)]; + args.extend(w.kv.resident.iter().map(|&r| A::P(r))); + args.extend([A::P(w.kv.table), A::P(a.ids), A::P(a.steps), A::I32(declared_i32(d.nkv)?), A::I32(PAGE_SIZE)]); + args.extend([A::F32(a.scale), A::P(a.acc), A::P(a.part_m), A::P(a.part_l)]); + args.extend([A::I32(declared_i32(d.chunks)?), A::I32(declared_i32(d.cap)?), A::I64(d.stride as i64)]); + Launch::new(chunk_asset, chunk_entry, grid, [256, 1, 1], 0, args) + } + + /// The merge kernel (`[n_head, n]` grid): the chunk accumulators combined into the attention output. + fn attn_merge_launch(&self, a: &AttnSpans) -> Result { + let d = &a.dims; + let grid = [grid_u32(d.nh)?, grid_u32(d.n)?, 1]; + let chunks = A::I32(declared_i32(d.chunks)?); + let tail = A::I64(d.stride as i64); + if self.policy.attn_daily { + let (asset, entry) = (&super::super::super::sm120::ATTN_DAILY, super::super::super::sm120::E_ATTN_MERGE_V2); + let args = vec![A::P(a.acc), A::P(a.part_m), A::P(a.part_l), chunks, A::P(a.steps), A::P(a.attn), tail]; + return Launch::new(asset, entry, grid, [256, 1, 1], 0, args); + } + let args = vec![A::P(a.acc), A::P(a.part_m), A::P(a.part_l), chunks, A::P(a.attn), tail]; + Launch::new(&ATTENTION, "leleka_qsa_decode_merge", grid, [256, 1, 1], 0, args) } /// `qsa_gate`: `native_qsa_gate_apply(attn, qfull, attn32, heads, HD)`; batched = one launch over `n * NH` heads. @@ -205,3 +161,26 @@ impl<'a> QsaWindow<'a> { (s.tb..s.tb + s.n).map(|t| one(t, 1)).collect() } } + +/// Sizes of one decode attention: `n` queries, `nh` heads over `nkv` KV heads, `chunks` partials of `cap` selected cells. +struct AttnDims { + n: usize, + nh: usize, + nkv: usize, + chunks: usize, + cap: usize, + stride: usize, +} + +/// The arena spans one decode attention reads and writes. +struct AttnSpans { + qcur: u64, + ids: u64, + steps: u64, + acc: u64, + part_m: u64, + part_l: u64, + attn: u64, + dims: AttnDims, + scale: f32, +} diff --git a/crates/cuda-driver/src/original_verify_window_record.rs b/crates/cuda-driver/src/original_verify_window_record.rs index db93ddf0..631194e9 100644 --- a/crates/cuda-driver/src/original_verify_window_record.rs +++ b/crates/cuda-driver/src/original_verify_window_record.rs @@ -235,50 +235,9 @@ fn pre(ops: &mut O, policy: &WindowPolicy, ple: bool, l: usize, ro ops.hc_read(l, HcHalf::Attention, pending, rows)?; stamp(ops, l, 1, rows)?; if !is_qsa_layer(l) { - let g = gdn_index(l).ok_or(Error::InvalidQwenShape)?; - ops.quantize_q8_1(l, QuantSource::Mixed, rows)?; - ops.mmvq(l, Projection::GdnQkv, rows)?; - stamp(ops, l, 2, rows)?; - ops.gdn_conv(g, rows)?; - stamp(ops, l, 3, rows)?; - ops.gdn_alpha_beta(g, rows)?; - stamp(ops, l, 4, rows)?; - ops.mmvq(l, Projection::GdnGate, rows)?; - stamp(ops, l, 5, rows)?; - ops.gdn_recurrence(g, rows)?; - stamp(ops, l, 6, rows)?; - ops.quantize_q8_1(l, QuantSource::GdnY, rows)?; - ops.mmvq(l, Projection::GdnOut, rows)?; + pre_gdn(ops, l, rows)?; } else { - let q = qsa_index(l).ok_or(Error::InvalidQwenShape)?; - let batched = policy.dec_batch && n > 1; - ops.quantize_q8_1(l, QuantSource::Mixed, rows)?; - ops.qsa_index_k(q, rows, batched)?; - stamp(ops, l, 7, rows)?; - ops.mmvq(l, Projection::QsaK, rows)?; - ops.mmvq(l, Projection::QsaV, rows)?; - ops.qsa_k_norm_rope(q, rows, batched)?; - stamp(ops, l, 8, rows)?; - if rows.group == 0 { - ops.qsa_tail_snapshot(q)?; - } - ops.qsa_kv_append(q, rows)?; - ops.qsa_indexer_append(q, rows)?; - stamp(ops, l, 9, rows)?; - ops.mmvq(l, Projection::QsaQ, rows)?; - ops.qsa_q_path(q, rows, batched)?; - ops.qsa_index_q_path(q, rows, batched)?; - stamp(ops, l, 10, rows)?; - ops.qsa_block_scores_topk(q, rows)?; - stamp(ops, l, 11, rows)?; - ops.qsa_kv_resolve(q, rows)?; - stamp(ops, l, 12, rows)?; - ops.qsa_decode_attention(q, rows)?; - stamp(ops, l, 13, rows)?; - ops.qsa_gate(q, rows, batched)?; - stamp(ops, l, 14, rows)?; - ops.quantize_q8_1(l, QuantSource::Attention, rows)?; - ops.mmvq(l, Projection::QsaOut, rows)?; + pre_qsa(ops, policy, l, rows)?; } stamp(ops, l, 16, rows)?; ops.hc_read(l, HcHalf::Ffn, true, rows)?; @@ -291,6 +250,62 @@ fn pre(ops: &mut O, policy: &WindowPolicy, ple: bool, l: usize, ro stamp(ops, l, 18, rows) } +/// The gated delta-net half of `pre`: QKV and gate projections, conv, alpha/beta, recurrence, output projection. +fn pre_gdn(ops: &mut O, l: usize, rows: Rows) -> Result<()> { + let g = gdn_index(l).ok_or(Error::InvalidQwenShape)?; + ops.quantize_q8_1(l, QuantSource::Mixed, rows)?; + ops.mmvq(l, Projection::GdnQkv, rows)?; + stamp(ops, l, 2, rows)?; + ops.gdn_conv(g, rows)?; + stamp(ops, l, 3, rows)?; + ops.gdn_alpha_beta(g, rows)?; + stamp(ops, l, 4, rows)?; + ops.mmvq(l, Projection::GdnGate, rows)?; + stamp(ops, l, 5, rows)?; + ops.gdn_recurrence(g, rows)?; + stamp(ops, l, 6, rows)?; + ops.quantize_q8_1(l, QuantSource::GdnY, rows)?; + ops.mmvq(l, Projection::GdnOut, rows) +} + +/// The sparse-attention half of `pre`: K/V and indexer projections and appends, then the query path and attention. +fn pre_qsa(ops: &mut O, policy: &WindowPolicy, l: usize, rows: Rows) -> Result<()> { + let q = qsa_index(l).ok_or(Error::InvalidQwenShape)?; + let batched = policy.dec_batch && rows.len() > 1; + ops.quantize_q8_1(l, QuantSource::Mixed, rows)?; + ops.qsa_index_k(q, rows, batched)?; + stamp(ops, l, 7, rows)?; + ops.mmvq(l, Projection::QsaK, rows)?; + ops.mmvq(l, Projection::QsaV, rows)?; + ops.qsa_k_norm_rope(q, rows, batched)?; + stamp(ops, l, 8, rows)?; + if rows.group == 0 { + ops.qsa_tail_snapshot(q)?; + } + ops.qsa_kv_append(q, rows)?; + ops.qsa_indexer_append(q, rows)?; + stamp(ops, l, 9, rows)?; + pre_qsa_attention(ops, l, q, (rows, batched)) +} + +/// The query path, block selection, resolve, decode attention, gate and output projection. +fn pre_qsa_attention(ops: &mut O, l: usize, q: usize, (rows, batched): (Rows, bool)) -> Result<()> { + ops.mmvq(l, Projection::QsaQ, rows)?; + ops.qsa_q_path(q, rows, batched)?; + ops.qsa_index_q_path(q, rows, batched)?; + stamp(ops, l, 10, rows)?; + ops.qsa_block_scores_topk(q, rows)?; + stamp(ops, l, 11, rows)?; + ops.qsa_kv_resolve(q, rows)?; + stamp(ops, l, 12, rows)?; + ops.qsa_decode_attention(q, rows)?; + stamp(ops, l, 13, rows)?; + ops.qsa_gate(q, rows, batched)?; + stamp(ops, l, 14, rows)?; + ops.quantize_q8_1(l, QuantSource::Attention, rows)?; + ops.mmvq(l, Projection::QsaOut, rows) +} + fn post(ops: &mut O, policy: &WindowPolicy, groups: usize, l: usize, rows: Rows) -> Result<()> { let n = rows.len(); let ring = ring(l, groups, rows.group); diff --git a/crates/cuda-driver/src/owned_gate_up_upload_gpu.rs b/crates/cuda-driver/src/owned_gate_up_upload_gpu.rs index 051e1a47..e391b5ae 100644 --- a/crates/cuda-driver/src/owned_gate_up_upload_gpu.rs +++ b/crates/cuda-driver/src/owned_gate_up_upload_gpu.rs @@ -93,126 +93,142 @@ fn copy_bytes(context: &Context<'_>, report: &mut Report) -> Result<()> { })(); combine(operation, combine(original.release(), candidate.release())) } +/// What one `products` run allocated, released by the caller whatever the operation returned. +#[derive(Default)] +struct Owners<'c, 'f> { + candidate: Option>, + other_original: Option>, + other: Option>, + activation: Option>, + expected: Option>, + actual: Option>, +} +impl<'c> Owners<'c, '_> { + /// The activation row (2560 F32), the old projection's output and the owned projection's output. + fn allocate_work(&mut self, context: &'c Context<'_>) -> Result<()> { + self.activation = Some(context.allocate(10240)?); + self.expected = Some(context.allocate(2560)?); + self.actual = Some(context.allocate(2560)?); + Ok(()) + } +} fn products(context: &Context<'_>, foreign: &Context<'_>, kind: MmqFormat, report: &mut Report) -> Result<()> { let bytes = raw(kind); // The unchanged old borrowed constructor and whole readback complete FIRST. let original = context.mmq_weights(kind, &bytes)?; - let mut candidate = None; - let mut other_original = None; - let mut other = None; - let mut activation = None; - let mut expected = None; - let mut actual = None; - let operation = (|| { - let original_bytes = read(original.native_buffer()?)?; - candidate = Some(context.mmq_weights_owned_gate_up(shape(kind), kind, consumed(&bytes, report))?); - let candidate = candidate.as_ref().ok_or(Error::ContextPoisoned)?; - compare_bytes(&original_bytes, &read(candidate.native_buffer()?)?, report); - let layout = kind.layout(1)?; - report.witness_errors += usize::from(layout.raw_weight != layout.weight || original_bytes != bytes); - activation = Some(context.allocate(10240)?); - expected = Some(context.allocate(2560)?); - actual = Some(context.allocate(2560)?); - let activation = activation.as_mut().ok_or(Error::ContextPoisoned)?; - let expected = expected.as_mut().ok_or(Error::ContextPoisoned)?; - let actual = actual.as_mut().ok_or(Error::ContextPoisoned)?; - for pattern in [0usize, 1, 2] { - let input: Vec<_> = (0usize..2560) - .flat_map(|index| { - let value = if pattern == 2 { - f32::from_bits(if index.is_multiple_of(2) { 0x8000_0000 } else { 0 }) - } else { - ((index * 13 + pattern * 19) % 43) as f32 / 16.0 - 1.25 - }; - value.to_le_bytes() - }) - .collect(); - activation.copy_from(&input)?; - let prepared = context.prepare_routed_gate_up_q8(activation)?; - let projected = (|| { - original.native_gate_up_prepared(&prepared, expected)?; - let reference = read(expected)?; - candidate.native_gate_up_prepared(&prepared, actual)?; - let observed = read(actual)?; - compare_bytes(&reference, &observed, report); - for word in reference.as_chunks::<4>().0 { - report.words += 1; - report.witness_errors += usize::from(!f32::from_le_bytes(*word).is_finite()); - } - if pattern == 0 { - other_original = Some(foreign.mmq_weights(kind, &bytes)?); - refused( - other_original - .as_ref() - .ok_or(Error::ContextPoisoned)? - .native_gate_up_prepared(&prepared, actual), - Error::ContextMismatch, - report, - )?; - other = Some(foreign.mmq_weights_owned_gate_up(shape(kind), kind, consumed(&bytes, report))?); - refused( - other.as_ref().ok_or(Error::ContextPoisoned)?.native_gate_up_prepared(&prepared, actual), - Error::ContextMismatch, - report, - )?; - compare_bytes(&reference, &read(actual)?, report); - } - Ok(()) - })(); - combine(projected, prepared.close())?; - } - Ok(()) - })(); + let mut owners = Owners::default(); + let operation = compare_products(context, foreign, (kind, &bytes), (&original, &mut owners), report); let mut cleanup = original.close(); - if let Some(owner) = candidate { + if let Some(owner) = owners.candidate { cleanup = combine(cleanup, owner.close()); } - if let Some(owner) = other_original { + if let Some(owner) = owners.other_original { cleanup = combine(cleanup, owner.close()); } - if let Some(owner) = other { + if let Some(owner) = owners.other { cleanup = combine(cleanup, owner.close()); } - for buffer in expected.into_iter().chain(actual).chain(activation) { + for buffer in owners.expected.into_iter().chain(owners.actual).chain(owners.activation) { cleanup = combine(cleanup, buffer.release()); } combine(operation, cleanup) } +fn compare_products<'c, 'f>( + context: &'c Context<'_>, + foreign: &'f Context<'_>, + (kind, bytes): (MmqFormat, &[u8]), + (original, owners): (&MmqWeights<'_>, &mut Owners<'c, 'f>), + report: &mut Report, +) -> Result<()> { + compare_candidate(context, (kind, bytes), (original, owners), report)?; + owners.allocate_work(context)?; + let candidate = owners.candidate.as_ref().ok_or(Error::ContextPoisoned)?; + let activation = owners.activation.as_mut().ok_or(Error::ContextPoisoned)?; + let expected = owners.expected.as_mut().ok_or(Error::ContextPoisoned)?; + let actual = owners.actual.as_mut().ok_or(Error::ContextPoisoned)?; + for pattern in [0usize, 1, 2] { + activation.copy_from(&pattern_input(pattern))?; + let prepared = context.prepare_routed_gate_up_q8(activation)?; + let projected = (|| { + let reference = compare_native(original, candidate, &prepared, (expected, actual), report)?; + if pattern == 0 { + let others = (&mut owners.other_original, &mut owners.other); + foreign_refusals(foreign, (kind, bytes), (&prepared, actual), others, report)?; + compare_bytes(&reference, &read(actual)?, report); + } + Ok(()) + })(); + combine(projected, prepared.close())?; + } + Ok(()) +} +/// The owned constructor over the same bytes: whole readback equal to the old one, layout witness. +fn compare_candidate<'c, 'f>( + context: &'c Context<'_>, + (kind, bytes): (MmqFormat, &[u8]), + (original, owners): (&MmqWeights<'_>, &mut Owners<'c, 'f>), + report: &mut Report, +) -> Result<()> { + let original_bytes = read(original.native_buffer()?)?; + owners.candidate = Some(context.mmq_weights_owned_gate_up(shape(kind), kind, consumed(bytes, report))?); + let candidate = owners.candidate.as_ref().ok_or(Error::ContextPoisoned)?; + compare_bytes(&original_bytes, &read(candidate.native_buffer()?)?, report); + let layout = kind.layout(1)?; + report.witness_errors += usize::from(layout.raw_weight != layout.weight || original_bytes != bytes); + Ok(()) +} +/// One F32 activation row (2560 values) of the test pattern: two arithmetic patterns and the +-0 one. +fn pattern_input(pattern: usize) -> Vec { + (0usize..2560) + .flat_map(|index| { + let value = if pattern == 2 { + f32::from_bits(if index.is_multiple_of(2) { 0x8000_0000 } else { 0 }) + } else { + ((index * 13 + pattern * 19) % 43) as f32 / 16.0 - 1.25 + }; + value.to_le_bytes() + }) + .collect() +} +/// The old and the owned projection over the same prepared activation; returns the old (reference) bytes. +fn compare_native( + original: &MmqWeights<'_>, + candidate: &MmqWeights<'_>, + prepared: &RoutedGateUpQ8<'_>, + (expected, actual): (&mut DeviceBuffer<'_>, &mut DeviceBuffer<'_>), + report: &mut Report, +) -> Result> { + original.native_gate_up_prepared(prepared, expected)?; + let reference = read(expected)?; + candidate.native_gate_up_prepared(prepared, actual)?; + let observed = read(actual)?; + compare_bytes(&reference, &observed, report); + for word in reference.as_chunks::<4>().0 { + report.words += 1; + report.witness_errors += usize::from(!f32::from_le_bytes(*word).is_finite()); + } + Ok(reference) +} +/// Owners of another Context must refuse the prepared activation of this one (both constructors). +fn foreign_refusals<'f>( + foreign: &'f Context<'_>, + (kind, bytes): (MmqFormat, &[u8]), + (prepared, actual): (&RoutedGateUpQ8<'_>, &mut DeviceBuffer<'_>), + (other_original, other): (&mut Option>, &mut Option>), + report: &mut Report, +) -> Result<()> { + *other_original = Some(foreign.mmq_weights(kind, bytes)?); + let first = other_original.as_ref().ok_or(Error::ContextPoisoned)?; + refused(first.native_gate_up_prepared(prepared, actual), Error::ContextMismatch, report)?; + *other = Some(foreign.mmq_weights_owned_gate_up(shape(kind), kind, consumed(bytes, report))?); + let second = other.as_ref().ok_or(Error::ContextPoisoned)?; + refused(second.native_gate_up_prepared(prepared, actual), Error::ContextMismatch, report) +} fn admission(context: &Context<'_>, kind: MmqFormat, report: &mut Report) -> Result<()> { let bytes = raw(kind); let allocated = context.allocated_bytes(); - for actual in [bytes.len() - 1, bytes.len() + 1] { - refused(context.mmq_weights(kind, &vec![0; actual]), Error::InvalidProjectionShape, report)?; - refused( - context.mmq_weights_owned_gate_up(shape(kind), kind, vec![0; actual]), - Error::InvalidProjectionShape, - report, - )?; - } - for bad in [ - ProjectionSpec { rows: 639, ..shape(kind) }, - ProjectionSpec { columns: 2559, ..shape(kind) }, - ProjectionSpec { kind: ProjectionKind::Dense(DenseFormat::Q4_K), ..shape(kind) }, - shape(if kind == MmqFormat::Iq3XxsGateUp { MmqFormat::Iq2SGateUp } else { MmqFormat::Iq3XxsGateUp }), - ] { - refused(context.mmq_weights_owned_gate_up(bad, kind, bytes.clone()), Error::InvalidProjectionShape, report)?; - } - for down in [MmqFormat::Iq4NlDown, MmqFormat::Q2Down] { - refused( - context.mmq_weights_owned_gate_up(shape(kind), down, bytes.clone()), - Error::UnsupportedProjection, - report, - )?; - } - let width = kind.layout(1)?.block_bytes; - for index in [0, bytes.len() - width] { - for bits in [0x7e01u16, 0x7c00, 0xfc00] { - let mut invalid = bytes.clone(); - invalid[index..index + 2].copy_from_slice(&bits.to_le_bytes()); - refused(context.mmq_weights(kind, &invalid), Error::InvalidQ8Activation, report)?; - refused(context.mmq_weights_owned_gate_up(shape(kind), kind, invalid), Error::InvalidQ8Activation, report)?; - } - } + refuse_lengths_shapes_and_formats(context, kind, &bytes, report)?; + refuse_invalid_halves(context, kind, &bytes, report)?; report.witness_errors += usize::from(context.allocated_bytes() != allocated || context.is_poisoned()); // Completed prewrite refusals cannot poison a later genuine valid upload. let owner = context.mmq_weights_owned_gate_up(shape(kind), kind, consumed(&bytes, report))?; @@ -222,6 +238,60 @@ fn admission(context: &Context<'_>, kind: MmqFormat, report: &mut Report) -> Res })(); combine(verified, owner.close()) } +/// A byte count one off, a wrong shape and a down format are refused. +fn refuse_lengths_shapes_and_formats( + context: &Context<'_>, + kind: MmqFormat, + bytes: &[u8], + report: &mut Report, +) -> Result<()> { + for actual in [bytes.len() - 1, bytes.len() + 1] { + refused(context.mmq_weights(kind, &vec![0; actual]), Error::InvalidProjectionShape, report)?; + refused( + context.mmq_weights_owned_gate_up(shape(kind), kind, vec![0; actual]), + Error::InvalidProjectionShape, + report, + )?; + } + refuse_shapes_and_down_formats(context, kind, bytes, report) +} +/// A wrong shape and a down format are refused by the owned constructor. +fn refuse_shapes_and_down_formats( + context: &Context<'_>, + kind: MmqFormat, + bytes: &[u8], + report: &mut Report, +) -> Result<()> { + for bad in [ + ProjectionSpec { rows: 639, ..shape(kind) }, + ProjectionSpec { columns: 2559, ..shape(kind) }, + ProjectionSpec { kind: ProjectionKind::Dense(DenseFormat::Q4_K), ..shape(kind) }, + shape(if kind == MmqFormat::Iq3XxsGateUp { MmqFormat::Iq2SGateUp } else { MmqFormat::Iq3XxsGateUp }), + ] { + refused(context.mmq_weights_owned_gate_up(bad, kind, bytes.to_vec()), Error::InvalidProjectionShape, report)?; + } + for down in [MmqFormat::Iq4NlDown, MmqFormat::Q2Down] { + refused( + context.mmq_weights_owned_gate_up(shape(kind), down, bytes.to_vec()), + Error::UnsupportedProjection, + report, + )?; + } + Ok(()) +} +/// A NaN or infinite f16 scale in the first or last block is refused by both constructors. +fn refuse_invalid_halves(context: &Context<'_>, kind: MmqFormat, bytes: &[u8], report: &mut Report) -> Result<()> { + let width = kind.layout(1)?.block_bytes; + for index in [0, bytes.len() - width] { + for bits in [0x7e01u16, 0x7c00, 0xfc00] { + let mut invalid = bytes.to_vec(); + invalid[index..index + 2].copy_from_slice(&bits.to_le_bytes()); + refused(context.mmq_weights(kind, &invalid), Error::InvalidQ8Activation, report)?; + refused(context.mmq_weights_owned_gate_up(shape(kind), kind, invalid), Error::InvalidQ8Activation, report)?; + } + } + Ok(()) +} fn run(context: &Context<'_>, foreign: &Context<'_>) -> Result { let mut report = Report::default(); copy_bytes(context, &mut report)?; @@ -231,6 +301,20 @@ fn run(context: &Context<'_>, foreign: &Context<'_>) -> Result { } Ok(report) } +/// A Context one byte short of the upload refuses both constructors with the budget error and keeps nothing. +fn tiny_budget_refusal(device: &Device<'_>, kind: MmqFormat, report: &mut Report) -> Result<()> { + let bytes = raw(kind); + let tiny = device.create_context(bytes.len() - 1)?; + let old = tiny.mmq_weights(kind, &bytes); + let new = tiny.mmq_weights_owned_gate_up(shape(kind), kind, consumed(&bytes, report)); + report.guards += 1; + report.refusals += + usize::from(matches!(&old, Err(Error::BudgetExceeded)) && matches!(&new, Err(Error::BudgetExceeded))); + drop(old); + drop(new); + report.witness_errors += usize::from(tiny.allocated_bytes() != 0 || tiny.is_poisoned()); + tiny.close() +} #[test] #[ignore = "Root schedules one changed owned staging comparison"] fn original_first_owned_gate_up_bytes_products_refusals_and_cleanup() { @@ -248,17 +332,7 @@ fn original_first_owned_gate_up_bytes_products_refusals_and_cleanup() { let operation = (|| { let mut report = run(&context, &foreign)?; for kind in [MmqFormat::Iq3XxsGateUp, MmqFormat::Iq2SGateUp] { - let bytes = raw(kind); - let tiny = device.create_context(bytes.len() - 1)?; - let old = tiny.mmq_weights(kind, &bytes); - let new = tiny.mmq_weights_owned_gate_up(shape(kind), kind, consumed(&bytes, &mut report)); - report.guards += 1; - report.refusals += - usize::from(matches!(&old, Err(Error::BudgetExceeded)) && matches!(&new, Err(Error::BudgetExceeded))); - drop(old); - drop(new); - report.witness_errors += usize::from(tiny.allocated_bytes() != 0 || tiny.is_poisoned()); - tiny.close()?; + tiny_budget_refusal(&device, kind, &mut report)?; } Ok(report) })(); @@ -267,6 +341,10 @@ fn original_first_owned_gate_up_bytes_products_refusals_and_cleanup() { let poisoned = context.is_poisoned() || foreign.is_poisoned(); let cleanup = combine(context.close(), foreign.close()); let report = combine(operation, cleanup).expect("fixture with all owners/Context cleanup"); + assert_clean_report(&report, [allocated, other_allocated], poisoned); +} +/// Both Contexts released everything, none is poisoned, and the comparison saw every word identical. +fn assert_clean_report(report: &Report, [allocated, other_allocated]: [usize; 2], poisoned: bool) { assert_eq!(allocated, 0); assert_eq!(other_allocated, 0); assert!(!poisoned); diff --git a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs index f5dbe97e..9741d4d5 100644 --- a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs +++ b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs @@ -26,35 +26,40 @@ impl Blas { _driver: Some(driver), _vendor: Some(vendor), }; - let result = (|| { - let mut stream = std::ptr::null_mut(); - // SAFETY: current owner Context; actual private NON_BLOCKING stream. - check("cuStreamCreate", unsafe { stream_create(&mut stream, 1) })?; - if stream.is_null() { - return Err(Error::InvalidDriverValue("cuStreamCreate")); - } - owner.stream = Some(stream as usize); - crate::compute_drain::register(stream as usize); - let mut h = std::ptr::null_mut(); - // SAFETY: current owner Context, valid writable output. - check("cublasCreate_v2", unsafe { create(&mut h) })?; - if h.is_null() { - return Err(Error::InvalidDriverValue("cublasCreate_v2")); - } - owner.handle = Some(h as usize); - // SAFETY: actual owned handle/stream and admitted whole workspace. - check("cublasSetStream_v2", unsafe { set_stream(h, stream) })?; - check("cublasSetWorkspace_v2", unsafe { - set_workspace(h, workspace.qwen_address() as *mut c_void, bytes) - })?; - check("cublasSetMathMode", unsafe { set_math(h, 0) })?; // CUBLAS_DEFAULT_MATH - Ok(()) - })(); + let result = owner.init_handle( + HandleSymbols { stream_create, create, set_stream, set_workspace, set_math }, + (workspace, bytes), + ); if let Err(e) = result { return combine(Err(e), owner.close()); } Ok(owner) } + /// Creates the private stream and the cuBLAS handle, binds them and the whole workspace; both stay recorded for + /// `close` even when a later step fails. + fn init_handle(&mut self, symbols: HandleSymbols, (workspace, bytes): (BufferHandle, usize)) -> Result<()> { + let HandleSymbols { stream_create, create, set_stream, set_workspace, set_math } = symbols; + let mut stream = std::ptr::null_mut(); + // SAFETY: current owner Context; actual private NON_BLOCKING stream. + check("cuStreamCreate", unsafe { stream_create(&mut stream, 1) })?; + if stream.is_null() { + return Err(Error::InvalidDriverValue("cuStreamCreate")); + } + self.stream = Some(stream as usize); + crate::compute_drain::register(stream as usize); + let mut h = std::ptr::null_mut(); + // SAFETY: current owner Context, valid writable output. + check("cublasCreate_v2", unsafe { create(&mut h) })?; + if h.is_null() { + return Err(Error::InvalidDriverValue("cublasCreate_v2")); + } + self.handle = Some(h as usize); + // SAFETY: actual owned handle/stream and admitted whole workspace. + check("cublasSetStream_v2", unsafe { set_stream(h, stream) })?; + check("cublasSetWorkspace_v2", unsafe { set_workspace(h, workspace.qwen_address() as *mut c_void, bytes) })?; + check("cublasSetMathMode", unsafe { set_math(h, 0) })?; // CUBLAS_DEFAULT_MATH + Ok(()) + } pub(crate) fn stream(&self) -> usize { self.stream.expect("private live stream") } @@ -71,29 +76,7 @@ impl Blas { alpha: &f32, beta: &f32, ) -> Result<()> { - if !(1..=8192).contains(&t) - || !matches!( - (n, k), - (10240, 2560) - | (2560, 2560) - | (320, 10240) - | (10240, 320) - | (4, 10240) - | (6144, 2560) - | (2560, 6144) - | (48, 2560) - | (12288, 2560) - | (512, 2560) - | (128, 2560) - // Literal Original shared expert and shared-router - // shapes; private typed producers authenticate owners. - | (640, 2560) - | (2560, 640) - | (1, 2560) - ) - || *alpha != 1.0 - || (*beta != 0.0 && *beta != 1.0) - { + if !gemm_shape_admitted((t, n, k), alpha, beta) { return Err(Error::InvalidQwenShape); } x.validate_projection_extent(t as usize * k as usize * 2, 2)?; @@ -103,32 +86,9 @@ impl Blas { InputType::Bf16 => 14, InputType::F16 => 2, }; // CUDA_R_16BF/F - // SAFETY: only closed producers call this private ABI after whole - // owner Context/shape/alias checks. Actual owners and alpha/beta - // command storage remain live through the same stream drain. - check("cublasGemmEx", unsafe { - (self.gemm)( - self.handle.ok_or(Error::ContextPoisoned)? as *mut c_void, - 1, - 0, - n, - t, - k, - (alpha as *const f32).cast(), - w.qwen_address() as *const c_void, - dtype, - k, - x.qwen_address() as *const c_void, - dtype, - k, - (beta as *const f32).cast(), - y.qwen_address() as *mut c_void, - 0, - n, - 68, - -1, - ) - }) // OP_T/OP_N/F32/COMPUTE32F/DEFAULT + // only closed producers call this private ABI after whole owner Context/shape/alias checks + let call = GemmEx { x, w, y, dtype, dims: (t, n, k), ldy: n, alpha, beta }; + self.gemm_ex(call) // OP_T/OP_N/F32/COMPUTE32F/DEFAULT } #[allow(clippy::too_many_arguments)] pub(crate) fn gemm_bf16( @@ -181,31 +141,9 @@ impl Blas { let offset = if beta_role { 48 * 4 } else { 0 }; let bytes = ((t as usize - 1) * 96 + 48) * 4; let y = ab.checked_subspan(whole, offset, bytes)?; - // SAFETY: fixed exact originalABstride; actual owners retained by - // the GDN producer until same-stream drain. No arbitrary ldy API. - check("cublasGemmEx", unsafe { - (self.gemm)( - self.handle.ok_or(Error::ContextPoisoned)? as *mut c_void, - 1, - 0, - 48, - t, - 2560, - (alpha as *const f32).cast(), - w.qwen_address() as *const c_void, - 14, - 2560, - x.qwen_address() as *const c_void, - 14, - 2560, - (beta as *const f32).cast(), - y.qwen_address() as *mut c_void, - 0, - 96, - 68, - -1, - ) - }) + // fixed exact originalABstride; actual owners retained by the GDN producer until same-stream drain + let call = GemmEx { x, w, y, dtype: 14, dims: (t, 48, 2560), ldy: 96, alpha, beta }; + self.gemm_ex(call) } /// Closed Original Option-B layouts. WHOLE owner checks are made by /// NativeGdnGemm before these private admitted addresses reach cuBLAS. @@ -225,22 +163,7 @@ impl Blas { y_offset: usize, beta: &f32, ) -> Result<()> { - if !(1..=8192).contains(&t) { - return Err(Error::InvalidQwenShape); - } - if bf16 { - let interleaved = (n, k, ldy) == (48, 2560, 96) && matches!(y_offset, 0 | 48); - let moe = matches!((n, k), (512, 2560) | (1, 2560)) && ldy == n && y_offset == 0; - if (!interleaved && !moe) || (*beta != 0.0 && *beta != 1.0) { - return Err(Error::InvalidQwenShape); - } - } else if !matches!((n, k), (10240, 2560) | (6144, 2560) | (2560, 6144) | (640, 2560) | (2560, 640)) - || ldy != n - || y_offset != 0 - || *beta != 0.0 - { - return Err(Error::InvalidQwenShape); - } + gdn_shape_admitted(bf16, (t, n, k), (ldy, y_offset), beta)?; x.validate_projection_extent(t as usize * k as usize * 2, 2)?; w.validate_projection_extent(n as usize * k as usize * 2, 2)?; let whole = t as usize * ldy as usize * 4; @@ -249,10 +172,17 @@ impl Blas { let output = y.checked_subspan(whole, y_offset * 4, consumed)?; let dtype = if bf16 { 14 } else { 2 }; let alpha = 1.0f32; - // SAFETY: fixed shapes/stride/offset from authentic WHOLE loans. - // The exclusive actual workspace and producer-owned arguments, - // buffers and weights are retained through its same-stream drain. - // Default cuBLAS HOST scalar mode consumes alpha/beta in this call. + // fixed shapes/stride/offset from authentic WHOLE loans; the exclusive actual workspace and producer-owned + // arguments, buffers and weights are retained through its same-stream drain + self.gemm_ex(GemmEx { x, w, y: output, dtype, dims: (t, n, k), ldy, alpha: &alpha, beta }) + } + /// The one `cublasGemmEx` call of this module: `y[t][n] = alpha * x[t][k] w[n][k]^T + beta * y`, 16-bit inputs, + /// F32 output with leading dimension `ldy`, OP_T/OP_N and COMPUTE32F/DEFAULT. + fn gemm_ex(&self, c: GemmEx<'_>) -> Result<()> { + let (t, n, k) = c.dims; + // SAFETY: the callers admitted the shapes/strides/offsets and the whole owners; the actual owners and the + // alpha/beta command storage remain live through the same stream drain. Default cuBLAS HOST scalar mode + // consumes alpha/beta in this call. check("cublasGemmEx", unsafe { (self.gemm)( self.handle.ok_or(Error::ContextPoisoned)? as *mut c_void, @@ -261,17 +191,17 @@ impl Blas { n, t, k, - (&alpha as *const f32).cast(), - w.qwen_address() as *const c_void, - dtype, + (c.alpha as *const f32).cast(), + c.w.qwen_address() as *const c_void, + c.dtype, k, - x.qwen_address() as *const c_void, - dtype, + c.x.qwen_address() as *const c_void, + c.dtype, k, - (beta as *const f32).cast(), - output.qwen_address() as *mut c_void, + (c.beta as *const f32).cast(), + c.y.qwen_address() as *mut c_void, 0, - ldy, + c.ldy, 68, -1, ) @@ -287,3 +217,71 @@ impl Blas { self.close_inner() } } + +/// The operands and shape of one `cublasGemmEx`: `dims` is `(t, n, k)`. +struct GemmEx<'a> { + x: BufferHandle, + w: BufferHandle, + y: BufferHandle, + dtype: i32, + dims: (i32, i32, i32), + ldy: i32, + alpha: &'a f32, + beta: &'a f32, +} + +/// The literal Original shapes of `Blas::gemm`: `(n, k)` pairs of the Original shared expert and shared router +/// included (private typed producers authenticate owners). +fn gemm_shape_admitted((t, n, k): (i32, i32, i32), alpha: &f32, beta: &f32) -> bool { + (1..=8192).contains(&t) + && matches!( + (n, k), + (10240, 2560) + | (2560, 2560) + | (320, 10240) + | (10240, 320) + | (4, 10240) + | (6144, 2560) + | (2560, 6144) + | (48, 2560) + | (12288, 2560) + | (512, 2560) + | (128, 2560) + | (640, 2560) + | (2560, 640) + | (1, 2560) + ) + && *alpha == 1.0 + && (*beta == 0.0 || *beta == 1.0) +} + +/// The closed Option-B layouts of `Blas::gemm_gdn`: BF16 interleaved Alpha/Beta and router/shared scalar, F16 +/// QKV/Z/Out and shared expert. +fn gdn_shape_admitted(bf16: bool, (t, n, k): (i32, i32, i32), (ldy, y_offset): (i32, usize), beta: &f32) -> Result<()> { + if !(1..=8192).contains(&t) { + return Err(Error::InvalidQwenShape); + } + if bf16 { + let interleaved = (n, k, ldy) == (48, 2560, 96) && matches!(y_offset, 0 | 48); + let moe = matches!((n, k), (512, 2560) | (1, 2560)) && ldy == n && y_offset == 0; + if (!interleaved && !moe) || (*beta != 0.0 && *beta != 1.0) { + return Err(Error::InvalidQwenShape); + } + } else if !matches!((n, k), (10240, 2560) | (6144, 2560) | (2560, 6144) | (640, 2560) | (2560, 640)) + || ldy != n + || y_offset != 0 + || *beta != 0.0 + { + return Err(Error::InvalidQwenShape); + } + Ok(()) +} + +/// The driver and cuBLAS entry points `Blas::init_handle` binds. +struct HandleSymbols { + stream_create: StreamCreate, + create: Create, + set_stream: SetStream, + set_workspace: SetWorkspace, + set_math: SetMath, +} diff --git a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas_2.rs b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas_2.rs index 8aeb10c3..adba0bf0 100644 --- a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas_2.rs +++ b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas_2.rs @@ -48,28 +48,35 @@ impl KernelModule { functions: Vec::new(), }; owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?; - let result = (|| { - let mut m = std::ptr::null_mut(); // SAFETY: actual immutable pinned NUL PTX. - check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; - if m.is_null() { - return Err(Error::InvalidDriverValue("cuModuleLoadData")); - } - owner.module = Some(m as usize); - for entry in entries { - let mut f = std::ptr::null_mut(); // SAFETY: real module, static declared symbol. - check("cuModuleGetFunction", unsafe { function(&mut f, m, entry.as_ptr()) })?; - if f.is_null() { - return Err(Error::InvalidDriverValue("cuModuleGetFunction")); - } - owner.functions.push(f as usize); - } - Ok(()) - })(); + let result = owner.init_functions(ptx, entries, (load, function)); if let Err(e) = result { return combine(Err(e), owner.close()); } Ok(owner) } + /// Loads the module image and resolves every entry; the module and functions stay recorded for `close`. + fn init_functions( + &mut self, + ptx: &'static [u8], + entries: &'static [&'static CStr], + (load, function): (ModuleLoad, ModuleFunction), + ) -> Result<()> { + let mut m = std::ptr::null_mut(); // SAFETY: actual immutable pinned NUL PTX. + check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; + if m.is_null() { + return Err(Error::InvalidDriverValue("cuModuleLoadData")); + } + self.module = Some(m as usize); + for entry in entries { + let mut f = std::ptr::null_mut(); // SAFETY: real module, static declared symbol. + check("cuModuleGetFunction", unsafe { function(&mut f, m, entry.as_ptr()) })?; + if f.is_null() { + return Err(Error::InvalidDriverValue("cuModuleGetFunction")); + } + self.functions.push(f as usize); + } + Ok(()) + } pub(crate) fn launch( &self, index: usize, @@ -82,43 +89,13 @@ impl KernelModule { return Err(Error::InvalidQwenShape); } let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; - args.pointers.clear(); - args.pointers.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?; - args.addresses.clear(); - args.addresses.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?; - args.addresses.resize(args.values.len(), 0); - for (index, arg) in args.values.iter_mut().enumerate() { - args.pointers.push(match arg { - BatchArg::Address(x) => { - // CUDA consumes an actual uint64_t parameter, never - // the unspecified Rust representation of BufferHandle. - args.addresses[index] = x.qwen_address(); - (&mut args.addresses[index] as *mut u64).cast() - } - BatchArg::NullAddress => (&mut args.null as *mut u64).cast(), - BatchArg::I32(x) => (x as *mut i32).cast(), - BatchArg::I64(x) => (x as *mut i64).cast(), - BatchArg::U32(x) => (x as *mut u32).cast(), - BatchArg::F32(x) => (x as *mut f32).cast(), - }); - } + args.pack()?; // SAFETY: owned boxed command fields and exact producer-declared // ABI persist until drain; Driver copies the parameter pointer array // during this call. No pointer/entry escapes to public callers. + let (function, stream, pointers) = (function as *mut c_void, stream as *mut c_void, args.pointers.as_mut_ptr()); check("cuLaunchKernel", unsafe { - (self.launch)( - function as *mut c_void, - grid, - 1, - 1, - block, - 1, - 1, - 0, - stream as *mut c_void, - args.pointers.as_mut_ptr(), - std::ptr::null_mut(), - ) + (self.launch)(function, grid, 1, 1, block, 1, 1, 0, stream, pointers, std::ptr::null_mut()) }) } /// `cuLaunchKernelEx` with a thread-block cluster (sm_90+): grid `[x, y, 1]`, `block` threads, cluster `[cx, 1, 1]`, @@ -134,55 +111,19 @@ impl KernelModule { stream: usize, args: &mut KernelArguments, ) -> Result<()> { - if grid[0] == 0 - || grid[1] == 0 - || block == 0 - || block > 1024 - || cluster_x == 0 - || grid[0] % cluster_x != 0 - || stream == 0 - { + if !cluster_launch_admitted(grid, block, cluster_x, stream) { return Err(Error::InvalidQwenShape); } let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; let library = self._library.as_ref().ok_or(Error::LibraryUnavailable)?; let launch_ex = symbol!(library, c"cuLaunchKernelEx", LaunchEx); let set_attribute = symbol!(library, c"cuFuncSetAttribute", FuncSetAttribute); - args.pointers.clear(); - args.pointers.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?; - args.addresses.clear(); - args.addresses.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?; - args.addresses.resize(args.values.len(), 0); - for (index, arg) in args.values.iter_mut().enumerate() { - args.pointers.push(match arg { - BatchArg::Address(x) => { - args.addresses[index] = x.qwen_address(); - (&mut args.addresses[index] as *mut u64).cast() - } - BatchArg::NullAddress => (&mut args.null as *mut u64).cast(), - BatchArg::I32(x) => (x as *mut i32).cast(), - BatchArg::I64(x) => (x as *mut i64).cast(), - BatchArg::U32(x) => (x as *mut u32).cast(), - BatchArg::F32(x) => (x as *mut f32).cast(), - }); - } + args.pack()?; check("cuFuncSetAttribute", unsafe { set_attribute(function as *mut c_void, crate::launch_ex::FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED, smem as c_int) })?; - let mut attribute = LaunchAttribute::cluster_x(cluster_x); - let config = LaunchConfig { - grid: [grid[0], grid[1], 1], - block: [block, 1, 1], - smem, - stream: stream as *mut c_void, - attrs: &mut attribute, - num_attrs: 1, - }; - // SAFETY: owned argument storage persists until the stream drains (the driver copies the parameters during the call); - // the config and the attribute live across the call; the function belongs to this module. - check("cuLaunchKernelEx", unsafe { - launch_ex(&config, function as *mut c_void, args.pointers.as_mut_ptr(), std::ptr::null_mut()) - }) + let shape = ClusterShape { grid, block, cluster_x, smem }; + launch_cluster_kernel(launch_ex, function, (shape, stream), args) } pub(crate) fn close(mut self) -> Result<()> { self.close_inner() @@ -207,3 +148,71 @@ impl Drop for KernelModule { let _ = self.close_inner(); } } + +/// The grid `[x, y]`, `block` threads, cluster width and dynamic shared memory of one cluster launch. +struct ClusterShape { + grid: [u32; 2], + block: u32, + cluster_x: u32, + smem: u32, +} + +/// A cluster launch needs a non-empty grid whose x extent the cluster width divides, 1..=1024 threads and a stream. +fn cluster_launch_admitted(grid: [u32; 2], block: u32, cluster_x: u32, stream: usize) -> bool { + !(grid[0] == 0 + || grid[1] == 0 + || block == 0 + || block > 1024 + || cluster_x == 0 + || grid[0] % cluster_x != 0 + || stream == 0) +} + +fn launch_cluster_kernel( + launch_ex: LaunchEx, + function: usize, + (shape, stream): (ClusterShape, usize), + args: &mut KernelArguments, +) -> Result<()> { + let mut attribute = LaunchAttribute::cluster_x(shape.cluster_x); + let config = LaunchConfig { + grid: [shape.grid[0], shape.grid[1], 1], + block: [shape.block, 1, 1], + smem: shape.smem, + stream: stream as *mut c_void, + attrs: &mut attribute, + num_attrs: 1, + }; + // SAFETY: owned argument storage persists until the stream drains (the driver copies the parameters during the call); + // the config and the attribute live across the call; the function belongs to this module. + check("cuLaunchKernelEx", unsafe { + launch_ex(&config, function as *mut c_void, args.pointers.as_mut_ptr(), std::ptr::null_mut()) + }) +} + +impl KernelArguments { + /// Points `pointers` at every value in order; addresses are copied into plain `u64` slots first. + fn pack(&mut self) -> Result<()> { + self.pointers.clear(); + self.pointers.try_reserve_exact(self.values.len()).map_err(|_| Error::HostAllocation)?; + self.addresses.clear(); + self.addresses.try_reserve_exact(self.values.len()).map_err(|_| Error::HostAllocation)?; + self.addresses.resize(self.values.len(), 0); + for (index, arg) in self.values.iter_mut().enumerate() { + self.pointers.push(match arg { + BatchArg::Address(x) => { + // CUDA consumes an actual uint64_t parameter, never + // the unspecified Rust representation of BufferHandle. + self.addresses[index] = x.qwen_address(); + (&mut self.addresses[index] as *mut u64).cast() + } + BatchArg::NullAddress => (&mut self.null as *mut u64).cast(), + BatchArg::I32(x) => (x as *mut i32).cast(), + BatchArg::I64(x) => (x as *mut i64).cast(), + BatchArg::U32(x) => (x as *mut u32).cast(), + BatchArg::F32(x) => (x as *mut f32).cast(), + }); + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/ple_closed_queue_gpu.rs b/crates/cuda-driver/src/ple_closed_queue_gpu.rs index 9bb1211e..aace4d54 100644 --- a/crates/cuda-driver/src/ple_closed_queue_gpu.rs +++ b/crates/cuda-driver/src/ple_closed_queue_gpu.rs @@ -1,6 +1,6 @@ //! Changed queue proof only; the actual cached full Key/Value operators run first. use super::*; -use crate::Driver; +use crate::{Device, Driver}; fn upload<'ctx>(context: &'ctx Context<'ctx>, bytes: &[u8]) -> Result> { let mut owner = context.allocate(bytes.len())?; @@ -49,60 +49,7 @@ fn original( history: &[f32], ) -> Result { let mut buffers: [Option>; 13] = std::array::from_fn(|_| None); - let operation = (|| { - for (i, size) in SIZES[..13].iter().enumerate() { - buffers[i] = Some(context.allocate(*size)?); - } - for (slot, values) in [(0, embedding), (1, streams), (2, history)] { - buffers[slot].as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&float_staging(values)?)?; - } - let mut products = Vec::new(); - products.try_reserve_exact(10).map_err(|_| Error::HostAllocation)?; - for role in 0..10 { - // Disjoint true whole outputs; retain all original dependencies. - let index = OUTPUTS[role]; - let (inputs, outputs) = buffers.split_at_mut(index); - let get = |i: usize| inputs[i].as_ref().ok_or(Error::ContextPoisoned); - if role == 7 { - let (conv, next) = outputs.split_at_mut(1); - context.ple_conv_history_f32( - get(2)?, - get(9)?, - weights[5], - conv[0].as_mut().ok_or(Error::ContextPoisoned)?, - next[0].as_mut().ok_or(Error::ContextPoisoned)?, - )?; - } else { - let output = outputs[0].as_mut().ok_or(Error::ContextPoisoned)?; - match role { - 0 => context.bf16_f32( - weights[0], - get(0)?, - output, - crate::Bf16ProjectionShape { rows: 10240, columns: 2560 }, - )?, - 1 => context.bf16_f32( - weights[1], - get(0)?, - output, - crate::Bf16ProjectionShape { rows: 2560, columns: 2560 }, - )?, - 2 => context.ple_grouped_norm_f32(get(3)?, weights[2], output)?, - 3 => context.ple_grouped_norm_f32(get(1)?, weights[3], output)?, - 4 => context.ple_signed_gate_f32(get(5)?, get(6)?, output)?, - 5 => context.ple_broadcast_f32(get(4)?, get(7)?, output)?, - 6 => context.ple_grouped_norm_f32(get(8)?, weights[4], output)?, - 8 => (), - 9 => context.ple_residual_f32(get(1)?, get(8)?, get(10)?, output)?, - _ => unreachable!(), - } - } - if !record(&mut products, buffers[index].as_ref().ok_or(Error::ContextPoisoned)?)? { - return Ok(Reference { products, refusal: Some(REFUSALS[role]) }); - } - } - Ok(Reference { products, refusal: None }) - })(); + let operation = original_products(context, weights, [embedding, streams, history], &mut buffers); let mut cleanup = Ok(()); for slot in &mut buffers { if let Some(buffer) = slot.take() { @@ -112,6 +59,73 @@ fn original( drop(buffers); combine(operation, cleanup) } +/// The ten cached operators in role order; stops at the first role whose product is not finite. +fn original_products<'c>( + context: &'c Context<'_>, + weights: [&DeviceBuffer<'_>; 6], + [embedding, streams, history]: [&[f32]; 3], + buffers: &mut [Option>; 13], +) -> Result { + for (i, size) in SIZES[..13].iter().enumerate() { + buffers[i] = Some(context.allocate(*size)?); + } + for (slot, values) in [(0, embedding), (1, streams), (2, history)] { + buffers[slot].as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&float_staging(values)?)?; + } + let mut products = Vec::new(); + products.try_reserve_exact(10).map_err(|_| Error::HostAllocation)?; + for role in 0..10 { + run_role(context, weights, buffers, role)?; + if !record(&mut products, buffers[OUTPUTS[role]].as_ref().ok_or(Error::ContextPoisoned)?)? { + return Ok(Reference { products, refusal: Some(REFUSALS[role]) }); + } + } + Ok(Reference { products, refusal: None }) +} +/// One operator onto its disjoint true whole output, retaining all original dependencies. +fn run_role( + context: &Context<'_>, + weights: [&DeviceBuffer<'_>; 6], + buffers: &mut [Option>; 13], + role: usize, +) -> Result<()> { + use crate::Bf16ProjectionShape as Shape; + let (inputs, outputs) = buffers.split_at_mut(OUTPUTS[role]); + let get = |i: usize| inputs[i].as_ref().ok_or(Error::ContextPoisoned); + if role == 7 { + return conv_history_role(context, weights[5], (get(2)?, get(9)?), outputs); + } + let output = outputs[0].as_mut().ok_or(Error::ContextPoisoned)?; + match role { + 0 => context.bf16_f32(weights[0], get(0)?, output, Shape { rows: 10240, columns: 2560 })?, + 1 => context.bf16_f32(weights[1], get(0)?, output, Shape { rows: 2560, columns: 2560 })?, + 2 => context.ple_grouped_norm_f32(get(3)?, weights[2], output)?, + 3 => context.ple_grouped_norm_f32(get(1)?, weights[3], output)?, + 4 => context.ple_signed_gate_f32(get(5)?, get(6)?, output)?, + 5 => context.ple_broadcast_f32(get(4)?, get(7)?, output)?, + 6 => context.ple_grouped_norm_f32(get(8)?, weights[4], output)?, + 8 => (), + 9 => context.ple_residual_f32(get(1)?, get(8)?, get(10)?, output)?, + _ => unreachable!(), + } + Ok(()) +} +/// The convolution and the shifted history are two outputs of one operator. +fn conv_history_role<'c>( + context: &Context<'_>, + conv_weight: &DeviceBuffer<'_>, + (history, normed): (&DeviceBuffer<'_>, &DeviceBuffer<'_>), + outputs: &mut [Option>], +) -> Result<()> { + let (conv, next) = outputs.split_at_mut(1); + context.ple_conv_history_f32( + history, + normed, + conv_weight, + conv[0].as_mut().ok_or(Error::ContextPoisoned)?, + next[0].as_mut().ok_or(Error::ContextPoisoned)?, + ) +} fn refs<'a, 'b>(weights: &'a [DeviceBuffer<'b>]) -> [&'a DeviceBuffer<'b>; 6] { [&weights[0], &weights[1], &weights[2], &weights[3], &weights[4], &weights[5]] } @@ -142,6 +156,12 @@ fn queued( } Ok((refusal, products)) } +#[derive(Default)] +struct Tally { + words: usize, + differences: usize, + guards: usize, +} #[test] #[ignore] fn original_first_whole_ple_queue_causal_history_status_reset_and_cleanup() { @@ -155,128 +175,29 @@ fn original_first_whole_ple_queue_causal_history_status_reset_and_cleanup() { let mut weights = Vec::new(); let mut queue = None; let mut foreign_weight = None; - let result = (|| { - weights.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?; - weights.push(upload(&context, &bf16(10240 * 2560, 2))?); - weights.push(upload(&context, &bf16(2560 * 2560, 3))?); - for _ in 0..3 { - weights.push(upload(&context, &float_staging(&vec![1.0; 10240])?)?); - } - weights.push(upload(&context, &bf16(4 * 10240, 4))?); - queue = Some(context.ple_closed_queue()?); - let q = queue.as_mut().ok_or(Error::ContextPoisoned)?; - let mut words = 0usize; - let mut differences = 0usize; - let mut guards = 0usize; - let mut history = values(92160, 5, false); - for case in 0..4 { - let embedding = values(2560, case * 3, case == 2); - let streams = values(10240, case * 5, case == 2); - let old = original(&context, refs(&weights), &embedding, &streams, &history)?; - let (refusal, products) = queued(q, refs(&weights), &embedding, &streams, &history)?; - if old.refusal.is_some() || refusal.is_some() { - differences += 1; - } - for (a, b) in old.products.iter().zip(&products) { - words += a.len(); - differences += a.iter().zip(b).filter(|(a, b)| a != b).count(); - if a.len() != b.len() { - differences += 1; - } - } - // The genuine previous candidate history supplies the next causal - // row; it must equal the original complete history first. - history = products[8].iter().map(|word| f32::from_bits(*word)).collect(); - } - let embedding = values(2560, 3, false); - let streams = values(10240, 5, false); - for (weight, offset, bytes) in [ - (0, 52_428_798, vec![0x80, 0x7f]), - (1, 13_107_198, vec![0x80, 0x7f]), - (2, 40956, f32::NAN.to_le_bytes().to_vec()), - (3, 40956, f32::INFINITY.to_le_bytes().to_vec()), - (4, 40956, f32::NAN.to_le_bytes().to_vec()), - (5, 81918, vec![0xc0, 0x7f]), - ] { - let mut saved = staging(weights[weight].bytes)?; - weights[weight].copy_to(&mut saved)?; - weights[weight].copy_from_range(offset, &bytes)?; - let old = original(&context, refs(&weights), &embedding, &streams, &history)?; - let (refusal, _) = queued(q, refs(&weights), &embedding, &streams, &history)?; - if old.refusal.is_none() || old.refusal != refusal { - differences += 1; - } - guards += 1; - weights[weight].copy_from(&saved)?; - let old = original(&context, refs(&weights), &embedding, &streams, &history)?; - let (refusal, products) = queued(q, refs(&weights), &embedding, &streams, &history)?; - if refusal.is_some() || old.refusal.is_some() { - differences += 1; - } - for (a, b) in old.products.iter().zip(products) { - words += a.len(); - differences += a.iter().zip(b).filter(|(a, b)| **a != *b).count(); - } - guards += 1; - } - let before = read(q.buffer(12)?)?; - let mut invalid = embedding.clone(); - invalid[2559] = f32::NAN; - if q.compose( - PleClosedWeights { - key: &weights[0], - value: &weights[1], - aux: [&weights[2], &weights[3], &weights[4], &weights[5]], - }, - &invalid, - &streams, - &history, - ) - .is_ok() - { - differences += 1; - } - guards += 1; - if q.compose( - PleClosedWeights { - key: &weights[0], - value: &weights[1], - aux: [&weights[2], &weights[3], &weights[4], &weights[5]], - }, - &embedding[..2559], - &streams, - &history, - ) - .is_ok() - { - differences += 1; - } - guards += 1; - foreign_weight = Some(foreign.allocate(1024)?); - if q.compose( - PleClosedWeights { - key: foreign_weight.as_ref().ok_or(Error::ContextPoisoned)?, - value: &weights[1], - aux: [&weights[2], &weights[3], &weights[4], &weights[5]], - }, - &embedding, - &streams, - &history, - ) - .is_ok() - { - differences += 1; - } - guards += 1; - if !matches!(q.weight(q.buffer(0)?, 10240, 4), Err(Error::OutputAliasesInput)) { - differences += 1; - } - guards += 1; - if read(q.buffer(12)?)? != before { - differences += 1; - } - Ok((words, differences, guards)) - })(); + let result = queue_cases(&context, &foreign, (&mut weights, &mut queue, &mut foreign_weight)); + let mut cleanup = release_fixture(weights, queue, foreign_weight); + let allocated = context.allocated_bytes(); + let foreign_allocated = foreign.allocated_bytes(); + cleanup = combine(cleanup, foreign.close()); + cleanup = combine(cleanup, context.close()); + let tally = combine(result, cleanup).expect("original-first PLE and full cleanup"); + assert_eq!(allocated, 0); + assert_eq!(foreign_allocated, 0); + assert_eq!(tally.differences, 0); + assert_eq!(tally.guards, 16); + eprintln!( + "PLE_CLOSED_QUEUE PASS words={} differences={} guards={} original_first=true causal_history=true allocated0=true", + tally.words, tally.differences, tally.guards + ); + tiny_budget_refused(&device); +} +/// The queue, the foreign weight and the weights are released (queue first) whatever the cases returned. +fn release_fixture<'c>( + mut weights: Vec>, + mut queue: Option>, + mut foreign_weight: Option>, +) -> Result<()> { let mut cleanup = Ok(()); if let Some(q) = queue.take() { cleanup = combine(cleanup, q.close()); @@ -290,18 +211,10 @@ fn original_first_whole_ple_queue_causal_history_status_reset_and_cleanup() { cleanup = combine(cleanup, buffer.release()); } drop(weights); - let allocated = context.allocated_bytes(); - let foreign_allocated = foreign.allocated_bytes(); - cleanup = combine(cleanup, foreign.close()); - cleanup = combine(cleanup, context.close()); - let (words, differences, guards) = combine(result, cleanup).expect("original-first PLE and full cleanup"); - assert_eq!(allocated, 0); - assert_eq!(foreign_allocated, 0); - assert_eq!(differences, 0); - assert_eq!(guards, 16); - eprintln!( - "PLE_CLOSED_QUEUE PASS words={words} differences={differences} guards={guards} original_first=true causal_history=true allocated0=true" - ); + cleanup +} +/// A context one byte under the queue's charge plus reserve refuses the queue and keeps nothing. +fn tiny_budget_refused(device: &Device<'_>) { let tiny = device.create_context(CHARGE + RESERVE - 1).expect("actual budget context"); let refused = matches!(tiny.ple_closed_queue(), Err(Error::BudgetExceeded)); let allocated = tiny.allocated_bytes(); @@ -310,3 +223,150 @@ fn original_first_whole_ple_queue_causal_history_status_reset_and_cleanup() { assert_eq!(allocated, 0); assert!(closed.is_ok()); } +/// The weights, the queue and the foreign weight stay owned by the caller so it can release them on any error. +fn queue_cases<'c>( + context: &'c Context<'c>, + foreign: &'c Context<'c>, + (weights, queue, foreign_weight): ( + &mut Vec>, + &mut Option>, + &mut Option>, + ), +) -> Result { + weights.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?; + weights.push(upload(context, &bf16(10240 * 2560, 2))?); + weights.push(upload(context, &bf16(2560 * 2560, 3))?); + for _ in 0..3 { + weights.push(upload(context, &float_staging(&vec![1.0; 10240])?)?); + } + weights.push(upload(context, &bf16(4 * 10240, 4))?); + *queue = Some(context.ple_closed_queue()?); + let q = queue.as_mut().ok_or(Error::ContextPoisoned)?; + let mut tally = Tally::default(); + let history = causal_history_cases(context, q, weights, &mut tally)?; + let embedding = values(2560, 3, false); + let streams = values(10240, 5, false); + let inputs = (&embedding[..], &streams[..], &history[..]); + corrupted_weight_cases(context, q, weights, inputs, &mut tally)?; + let before = read(q.buffer(12)?)?; + invalid_input_cases(q, weights, inputs, &mut tally); + *foreign_weight = Some(foreign.allocate(1024)?); + foreign_weight_case(q, weights, foreign_weight.as_ref().ok_or(Error::ContextPoisoned)?, inputs, &mut tally); + if !matches!(q.weight(q.buffer(0)?, 10240, 4), Err(Error::OutputAliasesInput)) { + tally.differences += 1; + } + tally.guards += 1; + if read(q.buffer(12)?)? != before { + tally.differences += 1; + } + Ok(tally) +} +/// Four causal rows: each candidate history must equal the original complete history first. Returns the last one. +fn causal_history_cases<'c>( + context: &Context<'_>, + q: &mut PleClosedQueue<'c>, + weights: &[DeviceBuffer<'_>], + tally: &mut Tally, +) -> Result> { + let mut history = values(92160, 5, false); + for case in 0..4 { + let embedding = values(2560, case * 3, case == 2); + let streams = values(10240, case * 5, case == 2); + let old = original(context, refs(weights), &embedding, &streams, &history)?; + let (refusal, products) = queued(q, refs(weights), &embedding, &streams, &history)?; + if old.refusal.is_some() || refusal.is_some() { + tally.differences += 1; + } + for (a, b) in old.products.iter().zip(&products) { + tally.words += a.len(); + tally.differences += a.iter().zip(b).filter(|(a, b)| a != b).count(); + if a.len() != b.len() { + tally.differences += 1; + } + } + // The genuine previous candidate history supplies the next causal + // row; it must equal the original complete history first. + history = products[8].iter().map(|word| f32::from_bits(*word)).collect(); + } + Ok(history) +} +/// A non-finite or oversized element in each weight is refused alike by the original and the queue, and the restored +/// weight gives identical products again. +fn corrupted_weight_cases<'c>( + context: &Context<'_>, + q: &mut PleClosedQueue<'c>, + weights: &mut [DeviceBuffer<'_>], + (embedding, streams, history): (&[f32], &[f32], &[f32]), + tally: &mut Tally, +) -> Result<()> { + for (weight, offset, bytes) in [ + (0, 52_428_798, vec![0x80, 0x7f]), + (1, 13_107_198, vec![0x80, 0x7f]), + (2, 40956, f32::NAN.to_le_bytes().to_vec()), + (3, 40956, f32::INFINITY.to_le_bytes().to_vec()), + (4, 40956, f32::NAN.to_le_bytes().to_vec()), + (5, 81918, vec![0xc0, 0x7f]), + ] { + let mut saved = staging(weights[weight].bytes)?; + weights[weight].copy_to(&mut saved)?; + weights[weight].copy_from_range(offset, &bytes)?; + let old = original(context, refs(weights), embedding, streams, history)?; + let (refusal, _) = queued(q, refs(weights), embedding, streams, history)?; + if old.refusal.is_none() || old.refusal != refusal { + tally.differences += 1; + } + tally.guards += 1; + weights[weight].copy_from(&saved)?; + let old = original(context, refs(weights), embedding, streams, history)?; + let (refusal, products) = queued(q, refs(weights), embedding, streams, history)?; + if refusal.is_some() || old.refusal.is_some() { + tally.differences += 1; + } + for (a, b) in old.products.iter().zip(products) { + tally.words += a.len(); + tally.differences += a.iter().zip(b).filter(|(a, b)| **a != *b).count(); + } + tally.guards += 1; + } + Ok(()) +} +/// Whether the queue composes these weights with `key` as the key weight. +fn composes( + q: &mut PleClosedQueue<'_>, + (key, weights): (&DeviceBuffer<'_>, &[DeviceBuffer<'_>]), + (embedding, streams, history): (&[f32], &[f32], &[f32]), +) -> bool { + let aux = [&weights[2], &weights[3], &weights[4], &weights[5]]; + q.compose(PleClosedWeights { key, value: &weights[1], aux }, embedding, streams, history).is_ok() +} +/// A NaN embedding element and a short embedding are refused. +fn invalid_input_cases( + q: &mut PleClosedQueue<'_>, + weights: &[DeviceBuffer<'_>], + (embedding, streams, history): (&[f32], &[f32], &[f32]), + tally: &mut Tally, +) { + let mut invalid = embedding.to_vec(); + invalid[2559] = f32::NAN; + if composes(q, (&weights[0], weights), (&invalid, streams, history)) { + tally.differences += 1; + } + tally.guards += 1; + if composes(q, (&weights[0], weights), (&embedding[..2559], streams, history)) { + tally.differences += 1; + } + tally.guards += 1; +} +/// A key weight of another Context is refused. +fn foreign_weight_case( + q: &mut PleClosedQueue<'_>, + weights: &[DeviceBuffer<'_>], + foreign_key: &DeviceBuffer<'_>, + inputs: (&[f32], &[f32], &[f32]), + tally: &mut Tally, +) { + if composes(q, (foreign_key, weights), inputs) { + tally.differences += 1; + } + tally.guards += 1; +} diff --git a/crates/cuda-driver/src/ple_value_full_gpu.rs b/crates/cuda-driver/src/ple_value_full_gpu.rs index 3b959672..bbdba95f 100644 --- a/crates/cuda-driver/src/ple_value_full_gpu.rs +++ b/crates/cuda-driver/src/ple_value_full_gpu.rs @@ -53,84 +53,137 @@ fn original(ctx: &Context<'_>, input: &DeviceBuffer<'_>) -> Vec { values } +/// The charged buffers of the gate: packed 40-tile weights, the embedding input and the sentinel-filled output. +struct Gate<'c> { + ctx: &'c Context<'c>, + packed: Vec, + weights: DeviceBuffer<'c>, + input: DeviceBuffer<'c>, + out: DeviceBuffer<'c>, + sentinel: Vec, + charged: usize, +} + #[test] #[ignore = "root schedules first exact wholeValue candidate gate before serving admission"] fn whole_value_matches_original_40_tiles_and_refuses_closed_shapes() { let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); let ctx = device.create_context(64 * 1024 * 1024).unwrap(); - let mut packed: Vec = (0..40).flat_map(tile_bytes).collect(); + let packed: Vec = (0..40).flat_map(tile_bytes).collect(); assert_eq!(packed.len(), WEIGHTS); - let mut weights = upload(&ctx, &packed); - let mut input = upload(&ctx, &embedding(false)); + let weights = upload(&ctx, &packed); + let input = upload(&ctx, &embedding(false)); let sentinel = 0xdeadbeefu32.to_le_bytes().repeat(2560); - let mut out = upload(&ctx, &sentinel); + let out = upload(&ctx, &sentinel); let charged = ctx.allocated_bytes(); assert_eq!(charged, WEIGHTS + EMBEDDING + OUTPUT); + let mut g = Gate { ctx: &ctx, packed, weights, input, out, sentinel, charged }; + let ordinary = exact_for_both_inputs(&mut g); + raw_last_row_nan(&mut g, &ordinary); + short_buffers_refused(&mut g); + foreign_context_refused(&device, &mut g); + // This operation uses already charged buffers and zero device scratch. + // The actual allocator enforces precharge; no fake kernel budget mutation. + precharge_enforced(&device); + release_gate(g); + assert_eq!(ctx.allocated_bytes(), 0); + ctx.close().unwrap(); + println!( + "PLE_VALUE_FULL finite_exact_words=5120 negative_unchanged_words=2559 guards=6 raw_last_row_nan=true cleanup=0" + ); +} + +/// The weights and the embedding are unchanged by every case; all three buffers are released. +fn release_gate(g: Gate<'_>) { + assert_eq!(read(&g.weights), g.packed); + assert_eq!(read(&g.input), embedding(false)); + for buffer in [g.out, g.input, g.weights] { + buffer.release().unwrap(); + } +} + +/// The whole-value kernel equals the 40 old tiles for an ordinary and for a signed-zero embedding; returns the +/// ordinary expected output. +fn exact_for_both_inputs(g: &mut Gate<'_>) -> Vec { let mut ordinary = Vec::new(); for zero in [false, true] { let bytes = embedding(zero); - input.copy_from(&bytes).unwrap(); - let expected = original(&ctx, &input); // Qualified old40 kernels FIRST. - assert_eq!(ctx.allocated_bytes(), charged); - out.copy_from(&sentinel).unwrap(); - ctx.ple_value_full_bf16_f32(&input, &weights, &mut out).unwrap(); - exact(&read(&out), &expected); - assert_eq!(read(&input), bytes); - assert_eq!(read(&weights), packed); - assert_eq!(ctx.allocated_bytes(), charged); + g.input.copy_from(&bytes).unwrap(); + let expected = original(g.ctx, &g.input); // Qualified old40 kernels FIRST. + assert_eq!(g.ctx.allocated_bytes(), g.charged); + g.out.copy_from(&g.sentinel).unwrap(); + g.ctx.ple_value_full_bf16_f32(&g.input, &g.weights, &mut g.out).unwrap(); + exact(&read(&g.out), &expected); + assert_eq!(read(&g.input), bytes); + assert_eq!(read(&g.weights), g.packed); + assert_eq!(g.ctx.allocated_bytes(), g.charged); if !zero { ordinary = expected; } println!("PLE_VALUE_FULL zero={zero} exact_words=2560 original_tiles=40 candidate_grid=40"); } - // Native numeric failure is a NaN output, not a fictitious launch refusal. - input.copy_from(&embedding(false)).unwrap(); - let last = packed.len() - 2; - let saved: [u8; 2] = packed[last..].try_into().unwrap(); - packed[last..].copy_from_slice(&0x7fc1u16.to_le_bytes()); - weights.copy_from(&packed).unwrap(); - ctx.ple_value_full_bf16_f32(&input, &weights, &mut out).unwrap(); - let malformed = read(&out); + ordinary +} + +/// Native numeric failure is a NaN output, not a fictitious launch refusal. +fn raw_last_row_nan(g: &mut Gate<'_>, ordinary: &[u8]) { + g.input.copy_from(&embedding(false)).unwrap(); + let last = g.packed.len() - 2; + let saved: [u8; 2] = g.packed[last..].try_into().unwrap(); + g.packed[last..].copy_from_slice(&0x7fc1u16.to_le_bytes()); + g.weights.copy_from(&g.packed).unwrap(); + g.ctx.ple_value_full_bf16_f32(&g.input, &g.weights, &mut g.out).unwrap(); + let malformed = read(&g.out); exact(&malformed[..OUTPUT - 4], &ordinary[..OUTPUT - 4]); assert!(f32::from_le_bytes(malformed[OUTPUT - 4..].try_into().unwrap()).is_nan()); assert!(malformed.as_chunks::<4>().0.iter().any(|word| !f32::from_le_bytes(*word).is_finite())); - assert_eq!(ctx.allocated_bytes(), charged); - packed[last..].copy_from_slice(&saved); - weights.copy_from(&packed).unwrap(); + assert_eq!(g.ctx.allocated_bytes(), g.charged); + g.packed[last..].copy_from_slice(&saved); + g.weights.copy_from(&g.packed).unwrap(); +} + +/// A short embedding, weight or output buffer is refused without touching the output or the charge. +fn short_buffers_refused(g: &mut Gate<'_>) { for case in 0..3 { let bytes = [EMBEDDING - 4, WEIGHTS - 2, OUTPUT - 4][case]; - let mut short = upload(&ctx, &vec![0x27; bytes]); - out.copy_from(&sentinel).unwrap(); - let charge = ctx.allocated_bytes(); + let mut short = upload(g.ctx, &vec![0x27; bytes]); + g.out.copy_from(&g.sentinel).unwrap(); + let charge = g.ctx.allocated_bytes(); let before = read(&short); let result = match case { - 0 => ctx.ple_value_full_bf16_f32(&short, &weights, &mut out), - 1 => ctx.ple_value_full_bf16_f32(&input, &short, &mut out), - 2 => ctx.ple_value_full_bf16_f32(&input, &weights, &mut short), + 0 => g.ctx.ple_value_full_bf16_f32(&short, &g.weights, &mut g.out), + 1 => g.ctx.ple_value_full_bf16_f32(&g.input, &short, &mut g.out), + 2 => g.ctx.ple_value_full_bf16_f32(&g.input, &g.weights, &mut short), _ => unreachable!(), }; assert_eq!(result, Err(Error::InvalidQwenShape)); - assert_eq!(read(&out), sentinel); + assert_eq!(read(&g.out), g.sentinel); assert_eq!(read(&short), before); - assert_eq!(ctx.allocated_bytes(), charge); + assert_eq!(g.ctx.allocated_bytes(), charge); short.release().unwrap(); } +} + +/// Buffers of another Context are refused as input and as output, leaving every buffer and charge unchanged. +fn foreign_context_refused(device: &Device<'_>, g: &mut Gate<'_>) { let foreign = device.create_context(64 * 1024 * 1024).unwrap(); - let mut foreign_out = upload(&foreign, &sentinel); + let mut foreign_out = upload(&foreign, &g.sentinel); let foreign_input = upload(&foreign, &embedding(false)); - out.copy_from(&sentinel).unwrap(); - assert_eq!(ctx.ple_value_full_bf16_f32(&foreign_input, &weights, &mut out), Err(Error::ContextMismatch)); - assert_eq!(ctx.ple_value_full_bf16_f32(&input, &weights, &mut foreign_out), Err(Error::ContextMismatch)); - assert_eq!(read(&out), sentinel); - assert_eq!(read(&foreign_out), sentinel); - assert_eq!(ctx.allocated_bytes(), charged); + g.out.copy_from(&g.sentinel).unwrap(); + assert_eq!(g.ctx.ple_value_full_bf16_f32(&foreign_input, &g.weights, &mut g.out), Err(Error::ContextMismatch)); + assert_eq!(g.ctx.ple_value_full_bf16_f32(&g.input, &g.weights, &mut foreign_out), Err(Error::ContextMismatch)); + assert_eq!(read(&g.out), g.sentinel); + assert_eq!(read(&foreign_out), g.sentinel); + assert_eq!(g.ctx.allocated_bytes(), g.charged); foreign_input.release().unwrap(); foreign_out.release().unwrap(); assert_eq!(foreign.allocated_bytes(), 0); foreign.close().unwrap(); - // This operation uses already charged buffers and zero device scratch. - // The actual allocator enforces precharge; no fake kernel budget mutation. +} + +/// A budget one byte short of weights plus embedding admits the weights only. +fn precharge_enforced(device: &Device<'_>) { let tiny = device.create_context(WEIGHTS + EMBEDDING - 1).unwrap(); let only_weight = tiny.allocate(WEIGHTS).unwrap(); assert!(matches!(tiny.allocate(EMBEDDING), Err(Error::BudgetExceeded))); @@ -138,14 +191,4 @@ fn whole_value_matches_original_40_tiles_and_refuses_closed_shapes() { only_weight.release().unwrap(); assert_eq!(tiny.allocated_bytes(), 0); tiny.close().unwrap(); - assert_eq!(read(&weights), packed); - assert_eq!(read(&input), embedding(false)); - for buffer in [out, input, weights] { - buffer.release().unwrap(); - } - assert_eq!(ctx.allocated_bytes(), 0); - ctx.close().unwrap(); - println!( - "PLE_VALUE_FULL finite_exact_words=5120 negative_unchanged_words=2559 guards=6 raw_last_row_nan=true cleanup=0" - ); } diff --git a/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_recurrence_equals_the_original.rs b/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_recurrence_equals_the_original.rs index ea3b3e19..a9dd6183 100644 --- a/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_recurrence_equals_the_original.rs +++ b/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_recurrence_equals_the_original.rs @@ -4,108 +4,161 @@ #[allow(unused_imports)] use super::*; -#[test] -#[ignore = "Root-only: needs a CUDA device"] -fn gdn_recurrence_equals_the_original_bit_for_bit() { +/// The device, the original kernels' launcher and the staged-kernel module shared by the GDN proofs. +pub(super) struct Rig<'a> { + pub(super) context: &'a Context<'a>, + pub(super) stream: usize, + pub(super) old: Old<'a>, + pub(super) stage: KernelModule, +} + +/// Opens the device with a `context_bytes` budget and a GDN batch for `prompt` rows and runs `body` on the rig. +pub(super) fn with_rig(context_bytes: usize, prompt: usize, body: impl FnOnce(&Rig<'_>)) { assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes")); let driver = crate::Driver::load().expect("driver"); let device = driver.device(0).expect("device"); - let context = device.create_context(6usize << 30).expect("context"); + let context = device.create_context(context_bytes).expect("context"); let workspace = context.native_batch_workspace().expect("workspace"); let stream = workspace.blas().expect("blas").stream(); - let batch = context.gdn_prefill_batch_for_prompt(2048).expect("gdn batch"); + let batch = context.gdn_prefill_batch_for_prompt(prompt).expect("gdn batch"); let funcs = batch.functions.as_ref().expect("functions"); let old = Old { context: &context, stream, funcs }; let guard = context.enter().expect("enter"); let stage = KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES).expect("stage module"); guard.finish().expect("finish"); - let mut rng = Rng(0xfeedfacecafebeef); - let state_len = 128 * 48 * 128; - for (case, t) in [(0, 1usize), (1, 7), (2, 200), (3, 1500), (4, 200)] { - let mut state: Vec = (0..state_len).map(|_| rng.f(0.05)).collect(); + body(&Rig { context: &context, stream, old, stage }); +} + +const STATE_LEN: usize = 128 * 48 * 128; + +/// The inputs and the paired outputs of one recurrence: `_o` the Original's, `_n` the new kernel's. +struct RecBuffers<'c> { + sin: DeviceBuffer<'c>, + h_d: DeviceBuffer<'c>, + gate_d: DeviceBuffer<'c>, + beta_d: DeviceBuffer<'c>, + sout_o: DeviceBuffer<'c>, + sout_n: DeviceBuffer<'c>, + oc_o: DeviceBuffer<'c>, + oc_n: DeviceBuffer<'c>, + wo: DeviceBuffer<'c>, + wn: DeviceBuffer<'c>, +} + +impl<'c> RecBuffers<'c> { + /// `variant`: 0 clean, 1 an infinite state value, 2 a NaN in the input, 3 products that overflow. + fn new(context: &'c Context<'c>, rng: &mut Rng, t: usize, variant: u8) -> Self { + let mut state: Vec = (0..STATE_LEN).map(|_| rng.f(0.05)).collect(); // q/k rows are L2-normalised in the real chain; keep them O(1/sqrt(S)) so the state stays bounded over the // chunk let mut h: Vec = (0..t * 10240).map(|_| rng.f(0.2)).collect(); let gate: Vec = (0..t * 48).map(|_| -rng.f(0.6).abs()).collect(); let beta: Vec = (0..t * 48).map(|_| (rng.f(0.5) + 0.5).abs()).collect(); - if case == 4 { + match variant { + 1 => state[1234] = f32::INFINITY, // a state that overflows: both kernels must raise the witness - state[1234] = 3.0e38; - h[5 * 10240 + 4096 + 300] = 3.0e38; + 3 => { + state[1234] = 3.0e38; + h[5 * 10240 + 4096 + 300] = 3.0e38; + } + 2 => h[100 * 10240 + 2 * 2048 + 777] = f32::NAN, + _ => {} + } + let zero = |bytes: usize| upload(context, &vec![0u8; bytes]); + Self { + sin: upload(context, &f32_bytes(&state)), + h_d: upload(context, &f32_bytes(&h)), + gate_d: upload(context, &f32_bytes(&gate)), + beta_d: upload(context, &f32_bytes(&beta)), + sout_o: zero(STATE_LEN * 4), + sout_n: zero(STATE_LEN * 4), + oc_o: zero(t * 6144 * 4), + oc_n: zero(t * 6144 * 4), + wo: upload(context, &[0u8; 16]), + wn: upload(context, &[0u8; 16]), } - let (sin, h_d, gate_d, beta_d) = ( - upload(&context, &f32_bytes(&state)), - upload(&context, &f32_bytes(&h)), - upload(&context, &f32_bytes(&gate)), - upload(&context, &f32_bytes(&beta)), - ); - let (sout_o, sout_n) = - (upload(&context, &vec![0u8; state_len * 4]), upload(&context, &vec![0u8; state_len * 4])); - let (oc_o, oc_n) = (upload(&context, &vec![0u8; t * 6144 * 4]), upload(&context, &vec![0u8; t * 6144 * 4])); - let (wo, wn) = (upload(&context, &[0u8; 16]), upload(&context, &[0u8; 16])); - old.run(vec![( - Kernel::RecColsPipe, - [192, 1, 1], - [32, 4, 1], - vec![ - ffi::KernelArg::Pointer(hd(&sin)), - ffi::KernelArg::Pointer(hd(&sout_o)), - ffi::KernelArg::Pointer(hd(&h_d)), - ffi::KernelArg::Pointer(hd(&gate_d)), - ffi::KernelArg::Pointer(hd(&beta_d)), - ffi::KernelArg::Pointer(hd(&oc_o)), - ffi::KernelArg::I64(t as i64), - ffi::KernelArg::Pointer(hd(&wo)), - ], - )]); - let guard = context.enter().expect("enter"); - let mut args = KernelArguments::new(vec![ - A::Address(hd(&sin)), - A::Address(hd(&sout_n)), - A::Address(hd(&h_d)), - A::Address(hd(&gate_d)), - A::Address(hd(&beta_d)), - A::Address(hd(&oc_n)), - A::I64(t as i64), - A::Address(hd(&wn)), - ]); - let started = std::time::Instant::now(); - stage.launch(crate::prefill_stage::GDN_REC, 192, 128, stream, &mut args).expect("launch"); - context.driver.api.synchronize().expect("sync"); - let new_ms = started.elapsed().as_secs_f64() * 1e3; - guard.finish().expect("finish"); - assert_eq!(download(&oc_o, t * 6144 * 4), download(&oc_n, t * 6144 * 4), "case {case} (t={t}): readout"); - assert_eq!( - download(&sout_o, state_len * 4), - download(&sout_n, state_len * 4), - "case {case} (t={t}): next state" - ); - assert_eq!(words(&wo, 1), words(&wn, 1), "case {case}: state witness"); - // timing of both, drained - let started = std::time::Instant::now(); - old.run(vec![( - Kernel::RecColsPipe, - [192, 1, 1], - [32, 4, 1], - vec![ - ffi::KernelArg::Pointer(hd(&sin)), - ffi::KernelArg::Pointer(hd(&sout_o)), - ffi::KernelArg::Pointer(hd(&h_d)), - ffi::KernelArg::Pointer(hd(&gate_d)), - ffi::KernelArg::Pointer(hd(&beta_d)), - ffi::KernelArg::Pointer(hd(&oc_o)), - ffi::KernelArg::I64(t as i64), - ffi::KernelArg::Pointer(hd(&wo)), - ], - )]); - let old_ms = started.elapsed().as_secs_f64() * 1e3; - eprintln!( - "PREFILL-GDN rec case {case} t={t}: equal (state {} floats, witness {:?}); \ - original {old_ms:.3} ms, new {new_ms:.3} ms", - state_len, - words(&wn, 1) - ); } + + /// The Original's `gdn_rec_cols_pipe` launch writing `sout`, `oc` and the witness `w`. + fn old_launch( + &self, + t: usize, + (sout, oc, w): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>), + ) -> (Kernel, [u32; 3], [u32; 3], Vec) { + let args = vec![ + ffi::KernelArg::Pointer(hd(&self.sin)), + ffi::KernelArg::Pointer(hd(sout)), + ffi::KernelArg::Pointer(hd(&self.h_d)), + ffi::KernelArg::Pointer(hd(&self.gate_d)), + ffi::KernelArg::Pointer(hd(&self.beta_d)), + ffi::KernelArg::Pointer(hd(oc)), + ffi::KernelArg::I64(t as i64), + ffi::KernelArg::Pointer(hd(w)), + ]; + (Kernel::RecColsPipe, [192, 1, 1], [32, 4, 1], args) + } + + /// The arguments of the new recurrence kernels writing `sout`, `oc` and the witness `w`. + fn new_args( + &self, + t: usize, + (sout, oc, w): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>), + ) -> KernelArguments { + KernelArguments::new(vec![ + A::Address(hd(&self.sin)), + A::Address(hd(sout)), + A::Address(hd(&self.h_d)), + A::Address(hd(&self.gate_d)), + A::Address(hd(&self.beta_d)), + A::Address(hd(oc)), + A::I64(t as i64), + A::Address(hd(w)), + ]) + } + + /// Readout and next state equal word for word (a NaN payload is a value too) and the witnesses agree. + fn assert_equal(&self, label: &str, case: usize, t: usize) { + assert_eq!(download(&self.oc_o, t * 6144 * 4), download(&self.oc_n, t * 6144 * 4), "{label}: readout"); + assert_eq!(download(&self.sout_o, STATE_LEN * 4), download(&self.sout_n, STATE_LEN * 4), "{label}: next state"); + assert_eq!(words(&self.wo, 1), words(&self.wn, 1), "case {case}: state witness"); + } +} + +#[test] +#[ignore = "Root-only: needs a CUDA device"] +fn gdn_recurrence_equals_the_original_bit_for_bit() { + with_rig(6usize << 30, 2048, |rig| { + let mut rng = Rng(0xfeedfacecafebeef); + for (case, t) in [(0, 1usize), (1, 7), (2, 200), (3, 1500), (4, 200)] { + rec_case(rig, &mut rng, (case, t)); + } + }); +} + +/// One token count: the Original, then the new kernel, bit-identical outputs, then the timing of both. +fn rec_case(rig: &Rig<'_>, rng: &mut Rng, (case, t): (usize, usize)) { + let (context, stream) = (rig.context, rig.stream); + let b = RecBuffers::new(context, rng, t, if case == 4 { 3 } else { 0 }); + let outs = (&b.sout_o, &b.oc_o, &b.wo); + rig.old.run(vec![b.old_launch(t, outs)]); + let guard = context.enter().expect("enter"); + let mut args = b.new_args(t, (&b.sout_n, &b.oc_n, &b.wn)); + let started = std::time::Instant::now(); + rig.stage.launch(crate::prefill_stage::GDN_REC, 192, 128, stream, &mut args).expect("launch"); + context.driver.api.synchronize().expect("sync"); + let new_ms = started.elapsed().as_secs_f64() * 1e3; + guard.finish().expect("finish"); + b.assert_equal(&format!("case {case} (t={t})"), case, t); + // timing of both, drained + let started = std::time::Instant::now(); + rig.old.run(vec![b.old_launch(t, outs)]); + let old_ms = started.elapsed().as_secs_f64() * 1e3; + eprintln!( + "PREFILL-GDN rec case {case} t={t}: equal (state {} floats, witness {:?}); \ + original {old_ms:.3} ms, new {new_ms:.3} ms", + STATE_LEN, + words(&b.wn, 1) + ); } /// Row 2.4 (upstream 4e69f974): the recurrence with one thread for the three value heads of a key head @@ -116,148 +169,73 @@ fn gdn_recurrence_equals_the_original_bit_for_bit() { #[test] #[ignore = "Root-only: needs a CUDA device"] fn gdn_recurrence_kh_equals_the_original_bit_for_bit() { - assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes")); - let driver = crate::Driver::load().expect("driver"); - let device = driver.device(0).expect("device"); - let context = device.create_context(10usize << 30).expect("context"); - let workspace = context.native_batch_workspace().expect("workspace"); - let stream = workspace.blas().expect("blas").stream(); - let batch = context.gdn_prefill_batch_for_prompt(2048).expect("gdn batch"); - let funcs = batch.functions.as_ref().expect("functions"); - let old = Old { context: &context, stream, funcs }; - let guard = context.enter().expect("enter"); - let stage = KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES).expect("stage module"); - guard.finish().expect("finish"); - let mut rng = Rng(0x0badc0ffee0ddf00); - let state_len = 128 * 48 * 128; - // (token count, variant): 0 clean, 1 an infinite state value, 2 a NaN in the input, 3 products that overflow - for (case, (t, variant)) in [ - (1usize, 0u8), - (2, 0), - (7, 0), - (8, 0), - (9, 0), - (200, 0), - (200, 1), - (201, 2), - (200, 3), - (1500, 0), - (2048, 0), - (8192, 0), - ] - .into_iter() - .enumerate() - { - let mut state: Vec = (0..state_len).map(|_| rng.f(0.05)).collect(); - let mut h: Vec = (0..t * 10240).map(|_| rng.f(0.2)).collect(); - let gate: Vec = (0..t * 48).map(|_| -rng.f(0.6).abs()).collect(); - let beta: Vec = (0..t * 48).map(|_| (rng.f(0.5) + 0.5).abs()).collect(); - if variant == 1 { - state[1234] = f32::INFINITY; + with_rig(10usize << 30, 2048, |rig| { + let mut rng = Rng(0x0badc0ffee0ddf00); + // (token count, variant): 0 clean, 1 an infinite state value, 2 a NaN in the input, 3 products that overflow + let cases = [(1usize, 0u8), (2, 0), (7, 0), (8, 0), (9, 0), (200, 0), (200, 1), (201, 2), (200, 3)]; + let cases = cases.into_iter().chain([(1500, 0), (2048, 0), (8192, 0)]); + for (case, (t, variant)) in cases.enumerate() { + kh_case(rig, &mut rng, case, (t, variant)); } - if variant == 3 { - state[1234] = 3.0e38; - h[5 * 10240 + 4096 + 300] = 3.0e38; - } - if variant == 2 { - h[100 * 10240 + 2 * 2048 + 777] = f32::NAN; - } - let (sin, h_d, gate_d, beta_d) = ( - upload(&context, &f32_bytes(&state)), - upload(&context, &f32_bytes(&h)), - upload(&context, &f32_bytes(&gate)), - upload(&context, &f32_bytes(&beta)), - ); - let (sout_o, sout_k) = - (upload(&context, &vec![0u8; state_len * 4]), upload(&context, &vec![0u8; state_len * 4])); - let (oc_o, oc_k) = (upload(&context, &vec![0u8; t * 6144 * 4]), upload(&context, &vec![0u8; t * 6144 * 4])); - let (wo, wk) = (upload(&context, &[0u8; 16]), upload(&context, &[0u8; 16])); - let old_launch = |sout: &DeviceBuffer<'_>, oc: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>| { - ( - Kernel::RecColsPipe, - [192u32, 1, 1], - [32u32, 4, 1], - vec![ - ffi::KernelArg::Pointer(hd(&sin)), - ffi::KernelArg::Pointer(hd(sout)), - ffi::KernelArg::Pointer(hd(&h_d)), - ffi::KernelArg::Pointer(hd(&gate_d)), - ffi::KernelArg::Pointer(hd(&beta_d)), - ffi::KernelArg::Pointer(hd(oc)), - ffi::KernelArg::I64(t as i64), - ffi::KernelArg::Pointer(hd(w)), - ], - ) - }; - let kh_args = |sout: &DeviceBuffer<'_>, oc: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>| { - KernelArguments::new(vec![ - A::Address(hd(&sin)), - A::Address(hd(sout)), - A::Address(hd(&h_d)), - A::Address(hd(&gate_d)), - A::Address(hd(&beta_d)), - A::Address(hd(oc)), - A::I64(t as i64), - A::Address(hd(w)), - ]) - }; - old.run(vec![old_launch(&sout_o, &oc_o, &wo)]); - let guard = context.enter().expect("enter"); - let mut args = kh_args(&sout_k, &oc_k, &wk); - stage.launch(crate::prefill_stage::GDN_REC_KH, 64, 128, stream, &mut args).expect("launch kh"); - context.driver.api.synchronize().expect("sync"); - guard.finish().expect("finish"); - // compare the bytes as words: a NaN payload is a value too - assert_eq!( - download(&oc_o, t * 6144 * 4), - download(&oc_k, t * 6144 * 4), - "case {case} (t={t}, variant {variant}): readout" - ); - assert_eq!( - download(&sout_o, state_len * 4), - download(&sout_k, state_len * 4), - "case {case} (t={t}, variant {variant}): next state" - ); - assert_eq!(words(&wo, 1), words(&wk, 1), "case {case}: state witness"); - let w = words(&wk, 1)[0]; - if variant == 1 || variant == 2 { - assert_ne!(w, 0, "case {case}: the witness must be raised for a non-finite state / input"); - } else if variant == 0 { - assert_eq!(w, 0, "case {case}: a clean chunk must not raise the witness"); - } - if t >= 1500 && variant == 0 { - // timing on warm data: 20 launches of each, drained once - let reps = 20; - let t0 = std::time::Instant::now(); - old.run((0..reps).map(|_| old_launch(&sout_o, &oc_o, &wo)).collect()); - let old_ms = t0.elapsed().as_secs_f64() * 1e3 / reps as f64; - let guard = context.enter().expect("enter"); - let mut keep = Vec::new(); - let t1b = std::time::Instant::now(); - for _ in 0..reps { - let mut a = kh_args(&sout_k, &oc_k, &wk); - stage.launch(crate::prefill_stage::GDN_REC_KH, 64, 128, stream, &mut a).expect("launch kh"); - keep.push(a); - } - context.driver.api.synchronize().expect("sync"); - let kh_ms = t1b.elapsed().as_secs_f64() * 1e3 / reps as f64; - let t2 = std::time::Instant::now(); - for _ in 0..reps { - let mut a = kh_args(&sout_k, &oc_k, &wk); - stage.launch(crate::prefill_stage::GDN_REC, 192, 128, stream, &mut a).expect("launch rec"); - keep.push(a); - } - context.driver.api.synchronize().expect("sync"); - let rec_ms = t2.elapsed().as_secs_f64() * 1e3 / reps as f64; - guard.finish().expect("finish"); - eprintln!( - "PREFILL-GDN rec-kh timing t={t}: original gdn_rec_cols_pipe {old_ms:.3} ms, \ - leleka_prefill_gdn_rec {rec_ms:.3} ms, kh {kh_ms:.3} ms per launch (mean of {reps}, warm)" - ); - } - eprintln!( - "PREFILL-GDN rec-kh case {case} t={t} variant {variant}: readout, state and witness ({w}) equal the \ - original" - ); + }); +} + +/// One token count of the key-head recurrence: bit-identical to the Original, the witness raised exactly for a +/// non-finite state or input, and (for long clean chunks) the timing of the three recurrences. +fn kh_case(rig: &Rig<'_>, rng: &mut Rng, case: usize, (t, variant): (usize, u8)) { + let (context, stream) = (rig.context, rig.stream); + let b = RecBuffers::new(context, rng, t, variant); + rig.old.run(vec![b.old_launch(t, (&b.sout_o, &b.oc_o, &b.wo))]); + let guard = context.enter().expect("enter"); + let mut args = b.new_args(t, (&b.sout_n, &b.oc_n, &b.wn)); + rig.stage.launch(crate::prefill_stage::GDN_REC_KH, 64, 128, stream, &mut args).expect("launch kh"); + context.driver.api.synchronize().expect("sync"); + guard.finish().expect("finish"); + // compare the bytes as words: a NaN payload is a value too + b.assert_equal(&format!("case {case} (t={t}, variant {variant})"), case, t); + let w = words(&b.wn, 1)[0]; + if variant == 1 || variant == 2 { + assert_ne!(w, 0, "case {case}: the witness must be raised for a non-finite state / input"); + } else if variant == 0 { + assert_eq!(w, 0, "case {case}: a clean chunk must not raise the witness"); } + if t >= 1500 && variant == 0 { + kh_timing(rig, &b, t); + } + eprintln!( + "PREFILL-GDN rec-kh case {case} t={t} variant {variant}: readout, state and witness ({w}) equal the \ + original" + ); +} + +/// Timing on warm data: 20 launches of each recurrence, drained once. +fn kh_timing(rig: &Rig<'_>, b: &RecBuffers<'_>, t: usize) { + let (context, stream) = (rig.context, rig.stream); + let reps = 20; + let t0 = std::time::Instant::now(); + rig.old.run((0..reps).map(|_| b.old_launch(t, (&b.sout_o, &b.oc_o, &b.wo))).collect()); + let old_ms = t0.elapsed().as_secs_f64() * 1e3 / reps as f64; + let guard = context.enter().expect("enter"); + let mut keep = Vec::new(); + let t1b = std::time::Instant::now(); + for _ in 0..reps { + let mut a = b.new_args(t, (&b.sout_n, &b.oc_n, &b.wn)); + rig.stage.launch(crate::prefill_stage::GDN_REC_KH, 64, 128, stream, &mut a).expect("launch kh"); + keep.push(a); + } + context.driver.api.synchronize().expect("sync"); + let kh_ms = t1b.elapsed().as_secs_f64() * 1e3 / reps as f64; + let t2 = std::time::Instant::now(); + for _ in 0..reps { + let mut a = b.new_args(t, (&b.sout_n, &b.oc_n, &b.wn)); + rig.stage.launch(crate::prefill_stage::GDN_REC, 192, 128, stream, &mut a).expect("launch rec"); + keep.push(a); + } + context.driver.api.synchronize().expect("sync"); + let rec_ms = t2.elapsed().as_secs_f64() * 1e3 / reps as f64; + guard.finish().expect("finish"); + eprintln!( + "PREFILL-GDN rec-kh timing t={t}: original gdn_rec_cols_pipe {old_ms:.3} ms, \ + leleka_prefill_gdn_rec {rec_ms:.3} ms, kh {kh_ms:.3} ms per launch (mean of {reps}, warm)" + ); } diff --git a/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_stage_kernels_equal.rs b/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_stage_kernels_equal.rs index d26bbb8b..8e558a08 100644 --- a/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_stage_kernels_equal.rs +++ b/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_stage_kernels_equal.rs @@ -2,338 +2,345 @@ //! gdn_stage_kernels_equal_the_originals_bit_for_bit. #[allow(unused_imports)] +use super::gdn_recurrence_equals_the_original::{Rig, with_rig}; use super::*; +/// Token rows of the convolution and norm cases: four tiles, the last one partial. +const T: usize = 200; +/// The epsilon of the L2 and output norms. +const EPS: f32 = 1e-6; + +type OldLaunch = (Kernel, [u32; 3], [u32; 3], Vec); + #[test] #[ignore = "Root-only: needs a CUDA device"] fn gdn_stage_kernels_equal_the_originals_bit_for_bit() { - assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes")); - let driver = crate::Driver::load().expect("driver"); - let device = driver.device(0).expect("device"); - let context = device.create_context(6usize << 30).expect("context"); - let workspace = context.native_batch_workspace().expect("workspace"); - let stream = workspace.blas().expect("blas").stream(); - let batch = context.gdn_prefill_batch_for_prompt(512).expect("gdn batch"); - let funcs = batch.functions.as_ref().expect("functions"); - let old = Old { context: &context, stream, funcs }; - let guard = context.enter().expect("enter"); - let stage = KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES).expect("stage module"); - guard.finish().expect("finish"); - let mut rng = Rng(0x1234567890abcdef); - let t = 200usize; // four tiles, the last one partial - - // ------------------------------------------------------------------ dequantization, six formats - for (format, k) in [ - (GdnNativeFormat::Q8_0, 2560usize), - (GdnNativeFormat::Q4K, 2560), - (GdnNativeFormat::Q5K, 2560), - (GdnNativeFormat::Q6K, 2560), - (GdnNativeFormat::Iq4Nl, 2560), - (GdnNativeFormat::Iq4Xs, 2560), - ] { - let n = 100usize; - let (elements, block_bytes) = format.block(); - let row_bytes = k / elements * block_bytes; - let mut blocks = vec![0u8; n * row_bytes]; - blocks.iter_mut().for_each(|b| *b = rng.next() as u8); - // finite f16 scale fields - for block in blocks.chunks_mut(block_bytes) { - let fields: &[usize] = match format { - GdnNativeFormat::Q8_0 | GdnNativeFormat::Iq4Nl | GdnNativeFormat::Iq4Xs => &[0], - GdnNativeFormat::Q4K | GdnNativeFormat::Q5K => &[0, 2], - GdnNativeFormat::Q6K => &[208], - }; - for f in fields { - block[*f..*f + 2].copy_from_slice(&rng.f16().to_le_bytes()); - } + with_rig(6usize << 30, 512, |rig| { + let mut rng = Rng(0x1234567890abcdef); + // ---------------------------------------------------------------- dequantization, six formats + for (format, k) in [ + (GdnNativeFormat::Q8_0, 2560usize), + (GdnNativeFormat::Q4K, 2560), + (GdnNativeFormat::Q5K, 2560), + (GdnNativeFormat::Q6K, 2560), + (GdnNativeFormat::Iq4Nl, 2560), + (GdnNativeFormat::Iq4Xs, 2560), + ] { + dequant_format(rig, &mut rng, format, k); } - let weight = upload(&context, &blocks); - let out_old = upload(&context, &vec![0u8; n * k * 2]); - let out_new = upload(&context, &vec![0u8; n * k * 2]); - let groups = (n * (k / 32)).div_ceil(256) as u32; - old.run(vec![( - format.kernel(), - [groups, 1, 1], - [256, 1, 1], - vec![ - ffi::KernelArg::Pointer(hd(&weight)), - ffi::KernelArg::I64(row_bytes as i64), - ffi::KernelArg::I64(0), - ffi::KernelArg::I64(n as i64), - ffi::KernelArg::I64((k / 32) as i64), - ffi::KernelArg::Pointer(hd(&out_old)), - ], - )]); - let index = crate::prefill_stage::DEQUANT_FIRST - + match format { - GdnNativeFormat::Q8_0 => 0, - GdnNativeFormat::Q4K => 1, - GdnNativeFormat::Q5K => 2, - GdnNativeFormat::Q6K => 3, - GdnNativeFormat::Iq4Nl => 4, - GdnNativeFormat::Iq4Xs => 5, - }; - run_stage( - &context, - stream, - &stage, - vec![( - index, - (n * k).div_ceil(256) as u32, - vec![ - A::Address(hd(&weight)), - A::I64(row_bytes as i64), - A::I64((n * k) as i64), - A::I64((k / 32) as i64), - A::Address(hd(&out_new)), - ], - )], - ); - assert_eq!( - download(&out_old, n * k * 2), - download(&out_new, n * k * 2), - "{format:?}: dequantized FP16 weights" - ); - eprintln!("PREFILL-GDN dequant {format:?}: {} FP16 values equal", n * k); - } - - // ------------------------------------------------------------------ convolution + L2 + output norm - for case in 0..4 { - let hist = f32_bytes(&(0..10240 * 3).map(|_| rng.f(2.0)).collect::>()); - let mut qkv: Vec = (0..t * 10240).map(|_| rng.f(3.0)).collect(); - let w = f32_bytes(&(0..10240 * 4).map(|_| rng.f(1.0)).collect::>()); - match case { - 1 => qkv[150 * 10240 + 77] = f32::NAN, - 2 => qkv[3 * 10240 + 9000] = 3.0e38, - _ => {} + // ---------------------------------------------------------------- convolution + L2 + output norm + for case in 0..4 { + stage_case(rig, &mut rng, case); } - let (hist_d, qkv_d, w_d) = (upload(&context, &hist), upload(&context, &f32_bytes(&qkv)), upload(&context, &w)); - let zero = vec![0u8; t * 10240 * 4]; - let (h_old, h_new) = (upload(&context, &zero), upload(&context, &zero)); - let status_old = upload(&context, &[0u8; 64]); - let status_new = upload(&context, &[0u8; 64]); - let word = |b: &DeviceBuffer<'_>, i: usize| hd(b).checked_subspan(64, i * 4, 4).expect("word"); - let scan = |data: &DeviceBuffer<'_>, count: usize, slot: usize| { - ( - Kernel::FiniteF32, - linear(count).unwrap().0, - [256, 1, 1], - vec![ - ffi::KernelArg::Pointer(hd(data)), - ffi::KernelArg::Pointer(word(&status_old, slot)), - ffi::KernelArg::U32(count as u32), - ], - ) + }); +} + +// ---------------------------------------------------------------------- dequantization + +/// Random blocks of `n` rows with finite f16 scale fields. +fn dequant_blocks( + rng: &mut Rng, + format: GdnNativeFormat, + (n, row_bytes, block_bytes): (usize, usize, usize), +) -> Vec { + let mut blocks = vec![0u8; n * row_bytes]; + blocks.iter_mut().for_each(|b| *b = rng.next() as u8); + // finite f16 scale fields + for block in blocks.chunks_mut(block_bytes) { + let fields: &[usize] = match format { + GdnNativeFormat::Q8_0 | GdnNativeFormat::Iq4Nl | GdnNativeFormat::Iq4Xs => &[0], + GdnNativeFormat::Q4K | GdnNativeFormat::Q5K => &[0, 2], + GdnNativeFormat::Q6K => &[208], }; - old.run(vec![ - ( - Kernel::ConvTiled, - [80, t.div_ceil(64) as u32, 1], - [128, 1, 1], - vec![ - ffi::KernelArg::Pointer(hd(&hist_d)), - ffi::KernelArg::Pointer(hd(&qkv_d)), - ffi::KernelArg::Pointer(hd(&w_d)), - ffi::KernelArg::Pointer(hd(&h_old)), - ffi::KernelArg::I64(t as i64), - ], - ), - scan(&qkv_d, t * 10240, 0), - scan(&h_old, t * 10240, 1), - ]); - run_stage( - &context, - stream, - &stage, - vec![( - crate::prefill_stage::GDN_CONV_TILED, - 40 * t.div_ceil(64) as u32, - vec![ - A::Address(hd(&hist_d)), - A::Address(hd(&qkv_d)), - A::Address(hd(&w_d)), - A::Address(hd(&h_new)), - A::I64(t as i64), - A::Address(word(&status_new, 0)), - A::Address(word(&status_new, 1)), - ], - )], - ); - assert_eq!(download(&h_old, t * 10240 * 4), download(&h_new, t * 10240 * 4), "case {case}: conv output"); - assert_eq!(words(&status_old, 2), words(&status_new, 2), "case {case}: conv status words (qkv, conv)"); - - // L2 over the first 4096 channels of every row, in place - let eps = 1e-6f32; - let status_l2_old = upload(&context, &[0u8; 64]); - let status_l2_new = upload(&context, &[0u8; 64]); - old.run(vec![ - ( - Kernel::L2, - [32, t as u32, 1], - [128, 1, 1], - vec![ffi::KernelArg::Pointer(hd(&h_old)), ffi::KernelArg::F32(eps)], - ), - ( - Kernel::FiniteF32, - linear(t * 10240).unwrap().0, - [256, 1, 1], - vec![ - ffi::KernelArg::Pointer(hd(&h_old)), - ffi::KernelArg::Pointer(hd(&status_l2_old)), - ffi::KernelArg::U32((t * 10240) as u32), - ], - ), - ]); - run_stage( - &context, - stream, - &stage, - vec![( - crate::prefill_stage::GDN_L2, - (32 * t).div_ceil(2) as u32, - vec![A::Address(hd(&h_new)), A::F32(eps), A::I64(t as i64), A::Address(hd(&status_l2_new))], - )], - ); - assert_eq!(download(&h_old, t * 10240 * 4), download(&h_new, t * 10240 * 4), "case {case}: L2 output"); - // the original scans the whole row (including the V channels the convolution guard already covers) - assert_eq!(words(&status_l2_old, 1), words(&status_l2_new, 1), "case {case}: L2 status"); - - // output norm - let z: Vec = (0..t * 6144).map(|_| rng.f(4.0)).collect(); - let mut oc: Vec = (0..t * 6144).map(|_| rng.f(2.0)).collect(); - let gamma: Vec = (0..128).map(|_| rng.f(1.5)).collect(); - match case { - 1 => oc[10 * 6144 + 5] = f32::INFINITY, - 2 => oc[199 * 6144 + 6143] = 3.0e38, - _ => {} + for f in fields { + block[*f..*f + 2].copy_from_slice(&rng.f16().to_le_bytes()); } - let (z_d, g_d) = (upload(&context, &f32_bytes(&z)), upload(&context, &f32_bytes(&gamma))); - let (y_old, y_new) = (upload(&context, &f32_bytes(&oc)), upload(&context, &f32_bytes(&oc))); - let (yh_old, yh_new) = (upload(&context, &vec![0u8; t * 6144 * 2]), upload(&context, &vec![0u8; t * 6144 * 2])); - let (so, sn) = (upload(&context, &[0u8; 64]), upload(&context, &[0u8; 64])); - let wo = |i: usize| word(&so, i); - old.run(vec![ - ( - Kernel::FiniteF32, - linear(t * 6144).unwrap().0, - [256, 1, 1], - vec![ - ffi::KernelArg::Pointer(hd(&y_old)), - ffi::KernelArg::Pointer(wo(1)), - ffi::KernelArg::U32((t * 6144) as u32), - ], - ), - ( - Kernel::OutNorm, - [t as u32, 48, 1], - [128, 1, 1], - vec![ - ffi::KernelArg::Pointer(hd(&z_d)), - ffi::KernelArg::Pointer(hd(&g_d)), - ffi::KernelArg::F32(eps), - ffi::KernelArg::Pointer(hd(&y_old)), - ffi::KernelArg::Pointer(hd(&yh_old)), - ], - ), - ( - Kernel::FiniteF32, - linear(t * 6144).unwrap().0, - [256, 1, 1], - vec![ - ffi::KernelArg::Pointer(hd(&y_old)), - ffi::KernelArg::Pointer(wo(2)), - ffi::KernelArg::U32((t * 6144) as u32), - ], - ), - ( - Kernel::FiniteF16, - linear(t * 6144).unwrap().0, - [256, 1, 1], - vec![ - ffi::KernelArg::Pointer(hd(&yh_old)), - ffi::KernelArg::Pointer(wo(3)), - ffi::KernelArg::U32((t * 6144) as u32), - ], - ), - ( - Kernel::FiniteF32, - linear(t * 6144).unwrap().0, - [256, 1, 1], - vec![ - ffi::KernelArg::Pointer(hd(&z_d)), - ffi::KernelArg::Pointer(wo(0)), - ffi::KernelArg::U32((t * 6144) as u32), - ], - ), - ]); - run_stage( - &context, - stream, - &stage, - vec![( - crate::prefill_stage::GDN_OUT_NORM, - (48 * t).div_ceil(2) as u32, - vec![ - A::Address(hd(&z_d)), - A::Address(hd(&g_d)), - A::F32(eps), - A::Address(hd(&y_new)), - A::Address(hd(&yh_new)), - A::I64(t as i64), - A::Address(word(&sn, 0)), - A::Address(word(&sn, 1)), - A::Address(word(&sn, 2)), - A::Address(word(&sn, 3)), - ], - )], - ); - assert_eq!(download(&y_old, t * 6144 * 4), download(&y_new, t * 6144 * 4), "case {case}: y"); - assert_eq!(download(&yh_old, t * 6144 * 2), download(&yh_new, t * 6144 * 2), "case {case}: y16"); - assert_eq!(words(&so, 4), words(&sn, 4), "case {case}: out-norm status words (z, readout, y, y16)"); - // row 2.4: the variant without the dead FP32 store writes the same y16 and status words and leaves y holding - // the readout - let (y_ns, yh_ns, sns) = ( - upload(&context, &f32_bytes(&oc)), - upload(&context, &vec![0u8; t * 6144 * 2]), - upload(&context, &[0u8; 64]), - ); - run_stage( - &context, - stream, - &stage, - vec![( - crate::prefill_stage::GDN_OUT_NORM_Y16, - (48 * t).div_ceil(2) as u32, - vec![ - A::Address(hd(&z_d)), - A::Address(hd(&g_d)), - A::F32(eps), - A::Address(hd(&y_ns)), - A::Address(hd(&yh_ns)), - A::I64(t as i64), - A::Address(word(&sns, 0)), - A::Address(word(&sns, 1)), - A::Address(word(&sns, 2)), - A::Address(word(&sns, 3)), - ], - )], - ); - assert_eq!( - download(&yh_old, t * 6144 * 2), - download(&yh_ns, t * 6144 * 2), - "case {case}: y16 of the no-store variant" - ); - assert_eq!(words(&so, 4), words(&sns, 4), "case {case}: status words of the no-store variant"); - assert_eq!( - download(&y_ns, t * 6144 * 4), - f32_bytes(&oc), - "case {case}: the no-store variant leaves y untouched" - ); - eprintln!( - "PREFILL-GDN case {case}: conv/L2/out-norm equal; statuses conv {:?} l2 {:?} norm {:?}", - words(&status_new, 2), - words(&status_l2_new, 1), - words(&sn, 4) - ); } + blocks +} + +/// The Original's element-parallel dequantization of `n` rows of `k` values. +fn dequant_old_launch( + format: GdnNativeFormat, + (weight, out): (&DeviceBuffer<'_>, &DeviceBuffer<'_>), + (n, k, row_bytes): (usize, usize, usize), +) -> OldLaunch { + let groups = (n * (k / 32)).div_ceil(256) as u32; + let args = vec![ + ffi::KernelArg::Pointer(hd(weight)), + ffi::KernelArg::I64(row_bytes as i64), + ffi::KernelArg::I64(0), + ffi::KernelArg::I64(n as i64), + ffi::KernelArg::I64((k / 32) as i64), + ffi::KernelArg::Pointer(hd(out)), + ]; + (format.kernel(), [groups, 1, 1], [256, 1, 1], args) +} + +/// The staged dequantization of `n` rows of `k` values: the stage entry index, the grid and the arguments. +fn dequant_new_launch( + format: GdnNativeFormat, + (weight, out): (&DeviceBuffer<'_>, &DeviceBuffer<'_>), + (n, k, row_bytes): (usize, usize, usize), +) -> (usize, u32, Vec) { + let index = crate::prefill_stage::DEQUANT_FIRST + + match format { + GdnNativeFormat::Q8_0 => 0, + GdnNativeFormat::Q4K => 1, + GdnNativeFormat::Q5K => 2, + GdnNativeFormat::Q6K => 3, + GdnNativeFormat::Iq4Nl => 4, + GdnNativeFormat::Iq4Xs => 5, + }; + let args = vec![ + A::Address(hd(weight)), + A::I64(row_bytes as i64), + A::I64((n * k) as i64), + A::I64((k / 32) as i64), + A::Address(hd(out)), + ]; + (index, (n * k).div_ceil(256) as u32, args) +} + +/// One format: the dequantized FP16 weights of the staged kernel equal the Original's. +fn dequant_format(rig: &Rig<'_>, rng: &mut Rng, format: GdnNativeFormat, k: usize) { + let context = rig.context; + let n = 100usize; + let (elements, block_bytes) = format.block(); + let row_bytes = k / elements * block_bytes; + let blocks = dequant_blocks(rng, format, (n, row_bytes, block_bytes)); + let weight = upload(context, &blocks); + let out_old = upload(context, &vec![0u8; n * k * 2]); + let out_new = upload(context, &vec![0u8; n * k * 2]); + rig.old.run(vec![dequant_old_launch(format, (&weight, &out_old), (n, k, row_bytes))]); + let launch = dequant_new_launch(format, (&weight, &out_new), (n, k, row_bytes)); + run_stage(context, rig.stream, &rig.stage, vec![launch]); + assert_eq!(download(&out_old, n * k * 2), download(&out_new, n * k * 2), "{format:?}: dequantized FP16 weights"); + eprintln!("PREFILL-GDN dequant {format:?}: {} FP16 values equal", n * k); +} + +// ---------------------------------------------------------------------- convolution, L2 and output norm + +/// The word `i` of a 64-byte status buffer. +fn status_word(b: &DeviceBuffer<'_>, i: usize) -> ffi::BufferHandle { + hd(b).checked_subspan(64, i * 4, 4).expect("word") +} + +/// The Original's finiteness scan of `count` words of `data` into status word `slot`. +fn scan_launch(data: &DeviceBuffer<'_>, status: &DeviceBuffer<'_>, count: usize, slot: usize) -> OldLaunch { + let args = vec![ + ffi::KernelArg::Pointer(hd(data)), + ffi::KernelArg::Pointer(status_word(status, slot)), + ffi::KernelArg::U32(count as u32), + ]; + (Kernel::FiniteF32, linear(count).unwrap().0, [256, 1, 1], args) +} + +/// What the L2 and output-norm stages read: the convolution outputs of the Original and the staged kernel. +struct ConvOut<'c> { + h_old: DeviceBuffer<'c>, + h_new: DeviceBuffer<'c>, + status_new: DeviceBuffer<'c>, +} + +/// Conv history, a `case`-dependent QKV (0 clean, 1 a NaN, 2 an overflow) and the conv weights. +fn conv_inputs(rng: &mut Rng, case: usize) -> (Vec, Vec, Vec) { + let hist = f32_bytes(&(0..10240 * 3).map(|_| rng.f(2.0)).collect::>()); + let mut qkv: Vec = (0..T * 10240).map(|_| rng.f(3.0)).collect(); + let w = f32_bytes(&(0..10240 * 4).map(|_| rng.f(1.0)).collect::>()); + match case { + 1 => qkv[150 * 10240 + 77] = f32::NAN, + 2 => qkv[3 * 10240 + 9000] = 3.0e38, + _ => {} + } + (hist, qkv, w) +} + +/// The convolution (with its QKV and conv guards) of the staged kernel equals the Original's. +fn conv_stage<'c>(rig: &Rig<'c>, rng: &mut Rng, case: usize) -> ConvOut<'c> { + let (context, t) = (rig.context, T); + let (hist, qkv, w) = conv_inputs(rng, case); + let (hist_d, qkv_d, w_d) = (upload(context, &hist), upload(context, &f32_bytes(&qkv)), upload(context, &w)); + let zero = vec![0u8; t * 10240 * 4]; + let (h_old, h_new) = (upload(context, &zero), upload(context, &zero)); + let status_old = upload(context, &[0u8; 64]); + let status_new = upload(context, &[0u8; 64]); + let args = vec![ + ffi::KernelArg::Pointer(hd(&hist_d)), + ffi::KernelArg::Pointer(hd(&qkv_d)), + ffi::KernelArg::Pointer(hd(&w_d)), + ffi::KernelArg::Pointer(hd(&h_old)), + ffi::KernelArg::I64(t as i64), + ]; + rig.old.run(vec![ + (Kernel::ConvTiled, [80, t.div_ceil(64) as u32, 1], [128, 1, 1], args), + scan_launch(&qkv_d, &status_old, t * 10240, 0), + scan_launch(&h_old, &status_old, t * 10240, 1), + ]); + let args = vec![ + A::Address(hd(&hist_d)), + A::Address(hd(&qkv_d)), + A::Address(hd(&w_d)), + A::Address(hd(&h_new)), + A::I64(t as i64), + A::Address(status_word(&status_new, 0)), + A::Address(status_word(&status_new, 1)), + ]; + let launch = (crate::prefill_stage::GDN_CONV_TILED, 40 * t.div_ceil(64) as u32, args); + run_stage(context, rig.stream, &rig.stage, vec![launch]); + assert_eq!(download(&h_old, t * 10240 * 4), download(&h_new, t * 10240 * 4), "case {case}: conv output"); + assert_eq!(words(&status_old, 2), words(&status_new, 2), "case {case}: conv status words (qkv, conv)"); + ConvOut { h_old, h_new, status_new } +} + +/// L2 over the first 4096 channels of every row, in place; returns the staged kernel's status. +fn l2_stage<'c>(rig: &Rig<'c>, case: usize, conv: &ConvOut<'c>) -> DeviceBuffer<'c> { + let (context, t) = (rig.context, T); + let status_l2_old = upload(context, &[0u8; 64]); + let status_l2_new = upload(context, &[0u8; 64]); + let l2 = ( + Kernel::L2, + [32, t as u32, 1], + [128, 1, 1], + vec![ffi::KernelArg::Pointer(hd(&conv.h_old)), ffi::KernelArg::F32(EPS)], + ); + let scan = ( + Kernel::FiniteF32, + linear(t * 10240).unwrap().0, + [256, 1, 1], + vec![ + ffi::KernelArg::Pointer(hd(&conv.h_old)), + ffi::KernelArg::Pointer(hd(&status_l2_old)), + ffi::KernelArg::U32((t * 10240) as u32), + ], + ); + rig.old.run(vec![l2, scan]); + let args = vec![A::Address(hd(&conv.h_new)), A::F32(EPS), A::I64(t as i64), A::Address(hd(&status_l2_new))]; + run_stage(context, rig.stream, &rig.stage, vec![(crate::prefill_stage::GDN_L2, (32 * t).div_ceil(2) as u32, args)]); + assert_eq!(download(&conv.h_old, t * 10240 * 4), download(&conv.h_new, t * 10240 * 4), "case {case}: L2 output"); + // the original scans the whole row (including the V channels the convolution guard already covers) + assert_eq!(words(&status_l2_old, 1), words(&status_l2_new, 1), "case {case}: L2 status"); + status_l2_new +} + +/// What the no-store variant is compared against: the gate, gamma, the Original's FP16 output and statuses. +struct NormOut<'c> { + z_d: DeviceBuffer<'c>, + g_d: DeviceBuffer<'c>, + yh_old: DeviceBuffer<'c>, + so: DeviceBuffer<'c>, + sn: DeviceBuffer<'c>, + oc: Vec, +} + +/// The Original's output-norm chain: the input scan, the norm, the y/y16/gate scans. +fn out_norm_old_launches( + (z_d, g_d, y_old, yh_old): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>), + so: &DeviceBuffer<'_>, +) -> Vec { + let t = T; + let finite = |kernel: Kernel, data: &DeviceBuffer<'_>, slot: usize| -> OldLaunch { + let args = vec![ + ffi::KernelArg::Pointer(hd(data)), + ffi::KernelArg::Pointer(status_word(so, slot)), + ffi::KernelArg::U32((t * 6144) as u32), + ]; + (kernel, linear(t * 6144).unwrap().0, [256, 1, 1], args) + }; + let norm_args = vec![ + ffi::KernelArg::Pointer(hd(z_d)), + ffi::KernelArg::Pointer(hd(g_d)), + ffi::KernelArg::F32(EPS), + ffi::KernelArg::Pointer(hd(y_old)), + ffi::KernelArg::Pointer(hd(yh_old)), + ]; + vec![ + finite(Kernel::FiniteF32, y_old, 1), + (Kernel::OutNorm, [t as u32, 48, 1], [128, 1, 1], norm_args), + finite(Kernel::FiniteF32, y_old, 2), + finite(Kernel::FiniteF16, yh_old, 3), + finite(Kernel::FiniteF32, z_d, 0), + ] +} + +/// The staged output-norm launch (`entry`: with or without the dead FP32 store) writing `y`, `yh` and four statuses. +fn out_norm_new_launch( + entry: usize, + (z_d, g_d, y, yh): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>), + status: &DeviceBuffer<'_>, +) -> (usize, u32, Vec) { + let t = T; + let args = vec![ + A::Address(hd(z_d)), + A::Address(hd(g_d)), + A::F32(EPS), + A::Address(hd(y)), + A::Address(hd(yh)), + A::I64(t as i64), + A::Address(status_word(status, 0)), + A::Address(status_word(status, 1)), + A::Address(status_word(status, 2)), + A::Address(status_word(status, 3)), + ]; + (entry, (48 * T).div_ceil(2) as u32, args) +} + +/// The output norm of the staged kernel equals the Original's (y, y16, statuses). +fn out_norm_stage<'c>(rig: &Rig<'c>, rng: &mut Rng, case: usize) -> NormOut<'c> { + let (context, t) = (rig.context, T); + let z: Vec = (0..t * 6144).map(|_| rng.f(4.0)).collect(); + let mut oc: Vec = (0..t * 6144).map(|_| rng.f(2.0)).collect(); + let gamma: Vec = (0..128).map(|_| rng.f(1.5)).collect(); + match case { + 1 => oc[10 * 6144 + 5] = f32::INFINITY, + 2 => oc[199 * 6144 + 6143] = 3.0e38, + _ => {} + } + let (z_d, g_d) = (upload(context, &f32_bytes(&z)), upload(context, &f32_bytes(&gamma))); + let (y_old, y_new) = (upload(context, &f32_bytes(&oc)), upload(context, &f32_bytes(&oc))); + let (yh_old, yh_new) = (upload(context, &vec![0u8; t * 6144 * 2]), upload(context, &vec![0u8; t * 6144 * 2])); + let (so, sn) = (upload(context, &[0u8; 64]), upload(context, &[0u8; 64])); + rig.old.run(out_norm_old_launches((&z_d, &g_d, &y_old, &yh_old), &so)); + let launch = out_norm_new_launch(crate::prefill_stage::GDN_OUT_NORM, (&z_d, &g_d, &y_new, &yh_new), &sn); + run_stage(context, rig.stream, &rig.stage, vec![launch]); + assert_eq!(download(&y_old, t * 6144 * 4), download(&y_new, t * 6144 * 4), "case {case}: y"); + assert_eq!(download(&yh_old, t * 6144 * 2), download(&yh_new, t * 6144 * 2), "case {case}: y16"); + assert_eq!(words(&so, 4), words(&sn, 4), "case {case}: out-norm status words (z, readout, y, y16)"); + NormOut { z_d, g_d, yh_old, so, sn, oc } +} + +/// Row 2.4: the variant without the dead FP32 store writes the same y16 and status words and leaves y holding the +/// readout. +fn no_store_stage(rig: &Rig<'_>, case: usize, norm: &NormOut<'_>) { + let (context, t) = (rig.context, T); + let (y_ns, yh_ns, sns) = + (upload(context, &f32_bytes(&norm.oc)), upload(context, &vec![0u8; t * 6144 * 2]), upload(context, &[0u8; 64])); + let launch = + out_norm_new_launch(crate::prefill_stage::GDN_OUT_NORM_Y16, (&norm.z_d, &norm.g_d, &y_ns, &yh_ns), &sns); + run_stage(context, rig.stream, &rig.stage, vec![launch]); + assert_eq!( + download(&norm.yh_old, t * 6144 * 2), + download(&yh_ns, t * 6144 * 2), + "case {case}: y16 of the no-store variant" + ); + assert_eq!(words(&norm.so, 4), words(&sns, 4), "case {case}: status words of the no-store variant"); + assert_eq!( + download(&y_ns, t * 6144 * 4), + f32_bytes(&norm.oc), + "case {case}: the no-store variant leaves y untouched" + ); +} + +/// One case of the convolution, L2 and output-norm chain, then the no-store variant. +fn stage_case(rig: &Rig<'_>, rng: &mut Rng, case: usize) { + let conv = conv_stage(rig, rng, case); + let status_l2_new = l2_stage(rig, case, &conv); + let norm = out_norm_stage(rig, rng, case); + no_store_stage(rig, case, &norm); + eprintln!( + "PREFILL-GDN case {case}: conv/L2/out-norm equal; statuses conv {:?} l2 {:?} norm {:?}", + words(&conv.status_new, 2), + words(&status_l2_new, 1), + words(&norm.sn, 4) + ); } diff --git a/crates/cuda-driver/src/prefill_stage_gpu.rs b/crates/cuda-driver/src/prefill_stage_gpu.rs index 8f10afcf..160f9630 100644 --- a/crates/cuda-driver/src/prefill_stage_gpu.rs +++ b/crates/cuda-driver/src/prefill_stage_gpu.rs @@ -2,6 +2,7 @@ //! (`kar_ple_scatter` / `kar_ple_decode`, 16 rows per call) and against the host assembly of the residual rows. //! Bit-identical required. Enable with `LELEKA_PREFILL_STAGE_GPU=yes` (needs a CUDA device; no model). use super::*; +use crate::original_prefill_arena::OriginalPrefillArena; use crate::{Driver, PrefillKvStage, PrefillLayoutOptions}; const ENABLE: &str = "LELEKA_PREFILL_STAGE_GPU"; @@ -53,26 +54,25 @@ fn read(context: &Context<'_>, handle: BufferHandle, bytes: usize) -> Vec { out } -#[test] -#[ignore = "Root-only: needs a CUDA device"] -fn staged_input_equals_the_per_token_kernels_bit_for_bit() { - assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes")); - let driver = Driver::load().expect("driver"); - let device = driver.device(0).expect("device"); - let context = device.create_context(6usize << 30).expect("context"); - let (capacity, t, pool, unique) = (256usize, 200usize, 1500usize, 40usize); - let mut rng = Rng(0x9e3779b97f4a7c15); +const CAPACITY: usize = 256; +const T: usize = 200; +const POOL: usize = 1500; +const UNIQUE: usize = 40; - // three partitions of four finite book entries +/// Three partitions of four finite book entries. +fn partition_books<'c>(context: &'c Context<'c>, rng: &mut Rng) -> DeviceBuffer<'c> { let books_host: Vec = (0..12).map(|_| rng.f16()).collect(); let mut books_bytes = Vec::new(); books_host.iter().for_each(|b| books_bytes.extend_from_slice(&b.to_le_bytes())); let mut books = context.allocate(24).expect("books"); books.copy_from(&books_bytes).expect("books upload"); + books +} - // a pool of packets (5 f16 scales, two 5-word bit planes, partition) and the 16 rows of every chunk position +/// A pool of packets: slot, 5 f16 scales, two 5-word bit planes, partition (56 bytes each). +fn packet_records(rng: &mut Rng) -> Vec { let mut records: Vec = Vec::new(); - for p in 0..pool { + for p in 0..POOL { records.extend_from_slice(&(p as u32).to_le_bytes()); for _ in 0..5 { records.extend_from_slice(&rng.f16().to_le_bytes()); @@ -82,10 +82,17 @@ fn staged_input_equals_the_per_token_kernels_bit_for_bit() { } records.extend_from_slice(&((rng.next() % 3) as u16).to_le_bytes()); } - assert_eq!(records.len(), pool * 56); - let slots: Vec = (0..t * 16).map(|_| (rng.next() % pool as u64) as u32).collect(); + assert_eq!(records.len(), POOL * 56); + records +} - // reference: the fixed per-token kernels, 16 rows per call +/// The reference: the fixed per-token kernels, 16 rows per call. Returns the decoded values and the scatter cache, +/// which stays allocated for the rest of the test. +fn per_token_reference<'c>( + context: &'c Context<'c>, + books: &DeviceBuffer<'c>, + (records, slots): (&[u8], &[u32]), +) -> (Vec, DeviceBuffer<'c>) { let mut old_cache = context.allocate(64 << 20).expect("old cache"); for group in records.chunks(16 * 56) { let mut updates = context.allocate(16 * 56).expect("updates"); @@ -100,50 +107,112 @@ fn staged_input_equals_the_per_token_kernels_bit_for_bit() { updates.release().expect("release"); } let mut reference = Vec::::new(); - for position in 0..t { + for position in 0..T { let mut slot_bytes = Vec::new(); slots[position * 16..position * 16 + 16].iter().for_each(|s| slot_bytes.extend_from_slice(&s.to_le_bytes())); let mut slot_buf = context.allocate(64).expect("slots"); slot_buf.copy_from(&slot_bytes).expect("slots upload"); let mut out = context.allocate(16 * 160 * 4).expect("out"); - context.kar_ple_decode(&old_cache, &slot_buf, &books, &mut out).expect("old decode"); + context.kar_ple_decode(&old_cache, &slot_buf, books, &mut out).expect("old decode"); let raw = out.copy_to_owned(16 * 160 * 4).expect("old readback"); reference.extend(raw.as_chunks::<4>().0.iter().map(|w| f32::from_le_bytes(*w))); slot_buf.release().expect("release"); out.release().expect("release"); } assert!(reference.iter().all(|v| v.is_finite())); + (reference, old_cache) +} + +/// The host inputs of the staged path. +struct Staged { + embedding: Vec, + embedding_bytes: Vec, + index: Vec, + records: Vec, + slots: Vec, +} + +/// The owners the staged path runs on. +struct StageOwners<'c> { + cache: DeviceBuffer<'c>, + workspace: NativeBatchWorkspace<'c>, + prompt: OriginalPromptDevice<'c>, + arena: OriginalPrefillArena<'c, 'c>, +} + +fn stage_input<'a, 'c>( + (rows, index): (&'a [u8], &'a [u32]), + (cache, books): (&'a mut DeviceBuffer<'c>, &'a DeviceBuffer<'c>), + (records, slots): (&'a [u8], &'a [u32]), +) -> PromptInputStage<'a, 'c> { + PromptInputStage { + embedding_rows: rows, + embedding_index: index, + ple_cache: cache, + ple_books: books, + ple_updates: records, + ple_slots: slots, + } +} + +#[test] +#[ignore = "Root-only: needs a CUDA device"] +fn staged_input_equals_the_per_token_kernels_bit_for_bit() { + assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes")); + let driver = Driver::load().expect("driver"); + let device = driver.device(0).expect("device"); + let context = device.create_context(6usize << 30).expect("context"); + let mut rng = Rng(0x9e3779b97f4a7c15); + let books = partition_books(&context, &mut rng); + let records = packet_records(&mut rng); + let slots: Vec = (0..T * 16).map(|_| (rng.next() % POOL as u64) as u32).collect(); + let (reference, _old_cache) = per_token_reference(&context, &books, (&records, &slots)); // the staged path - let embedding: Vec = (0..unique * 2560).map(|_| (rng.next() % 2001) as f32 / 1000.0 - 1.0).collect(); + let embedding: Vec = (0..UNIQUE * 2560).map(|_| (rng.next() % 2001) as f32 / 1000.0 - 1.0).collect(); let mut embedding_bytes = Vec::new(); embedding.iter().for_each(|v| embedding_bytes.extend_from_slice(&v.to_le_bytes())); - let index: Vec = (0..t).map(|_| (rng.next() % unique as u64) as u32).collect(); - let mut cache = context.allocate(64 << 20).expect("cache"); - let mut prompt = context - .original_prompt_device(capacity, PleBf16Mode::HighOnly, GrNativeProfile::HighOnly) - .expect("prompt device"); - let mut workspace = context.native_batch_workspace().expect("workspace"); - let mut arena = context.original_prefill_arena(options(capacity)).expect("arena"); - let lease = arena.begin_rows(t).expect("rows"); - let mut residual = prompt - .initialize_staged( - lease, - &mut workspace, - PromptInputStage { - embedding_rows: &embedding_bytes, - embedding_index: &index, - ple_cache: &mut cache, - ple_books: &books, - ple_updates: &records, - ple_slots: &slots, - }, - ) - .expect("initialize_staged"); + let index: Vec = (0..T).map(|_| (rng.next() % UNIQUE as u64) as u32).collect(); + let staged = Staged { embedding, embedding_bytes, index, records, slots }; + let mut owners = stage_owners(&context); + check_staged_equals_reference(&context, (&mut owners, &books), &staged, &reference); + check_refusals(&mut owners, &books, &staged); + let StageOwners { cache, workspace, prompt, arena } = owners; + drop(arena); + prompt.close().expect("prompt close"); + drop((workspace, cache)); +} + +fn stage_owners<'c>(context: &'c Context<'c>) -> StageOwners<'c> { + StageOwners { + cache: context.allocate(64 << 20).expect("cache"), + prompt: context + .original_prompt_device(CAPACITY, PleBf16Mode::HighOnly, GrNativeProfile::HighOnly) + .expect("prompt device"), + workspace: context.native_batch_workspace().expect("workspace"), + arena: context.original_prefill_arena(options(CAPACITY)).expect("arena"), + } +} + +/// `initialize_staged` fills R with four copies of the selected embedding row and the PLE span bit-identical to the +/// per-token decode. +fn check_staged_equals_reference<'c>( + context: &Context<'c>, + (owners, books): (&mut StageOwners<'c>, &DeviceBuffer<'c>), + staged: &Staged, + reference: &[f32], +) { + let lease = owners.arena.begin_rows(T).expect("rows"); + let input = stage_input( + (&staged.embedding_bytes, &staged.index), + (&mut owners.cache, books), + (&staged.records, &staged.slots), + ); + let mut residual = owners.prompt.initialize_staged(lease, &mut owners.workspace, input).expect("initialize_staged"); // R rows: four copies of the selected embedding row - for row in [0usize, 1, 57, t - 1] { + for row in [0usize, 1, 57, T - 1] { let streams = residual.read_prompt_row(row).expect("R row"); - let source = &embedding[index[row] as usize * 2560..][..2560]; + let source = &staged.embedding[staged.index[row] as usize * 2560..][..2560]; for stream in 0..4 { for (i, v) in streams[stream * 2560..][..2560].iter().enumerate() { assert_eq!(v.to_bits(), source[i].to_bits(), "row {row} stream {stream} value {i}"); @@ -152,43 +221,33 @@ fn staged_input_equals_the_per_token_kernels_bit_for_bit() { } // PLE embedding span: bit-identical to the per-token decode let (handle, span_bytes) = residual.lease().common_span(S::PleEmbedding).expect("ple span"); - let raw = read(&context, handle, t * 10240); - assert!(span_bytes >= t * 10240); - let staged: Vec = raw.as_chunks::<4>().0.iter().map(|w| f32::from_le_bytes(*w)).collect(); - assert_eq!(staged.len(), reference.len()); - let mismatches = staged.iter().zip(&reference).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); + let raw = read(context, handle, T * 10240); + assert!(span_bytes >= T * 10240); + let values: Vec = raw.as_chunks::<4>().0.iter().map(|w| f32::from_le_bytes(*w)).collect(); + assert_eq!(values.len(), reference.len()); + let mismatches = values.iter().zip(reference).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); assert_eq!(mismatches, 0, "PLE values differ from the per-token decode"); - eprintln!("PREFILL-STAGE equal: {} PLE values, {} R rows", staged.len(), 4); + eprintln!("PREFILL-STAGE equal: {} PLE values, {} R rows", values.len(), 4); drop(residual); +} - // refusals: a non-finite embedding value and a non-finite PLE scale +/// Refusals: a non-finite embedding value and a non-finite PLE scale. +fn check_refusals<'c>(owners: &mut StageOwners<'c>, books: &DeviceBuffer<'c>, staged: &Staged) { for case in 0..2 { - let lease = arena.begin_rows(t).expect("rows"); - let mut bad_embedding = embedding_bytes.clone(); - let mut bad_records = records.clone(); + let lease = owners.arena.begin_rows(T).expect("rows"); + let mut bad_embedding = staged.embedding_bytes.clone(); + let mut bad_records = staged.records.clone(); if case == 0 { bad_embedding[3 * 4..3 * 4 + 4].copy_from_slice(&f32::NAN.to_le_bytes()); } else { bad_records[4..6].copy_from_slice(&0x7c00u16.to_le_bytes()); } - let mut bad_index = index.clone(); + let mut bad_index = staged.index.clone(); bad_index.iter_mut().for_each(|i| *i = 0); - let mut bad_slots = slots.clone(); + let mut bad_slots = staged.slots.clone(); bad_slots.iter_mut().for_each(|s| *s = 0); - let result = prompt.initialize_staged( - lease, - &mut workspace, - PromptInputStage { - embedding_rows: &bad_embedding, - embedding_index: &bad_index, - ple_cache: &mut cache, - ple_books: &books, - ple_updates: &bad_records, - ple_slots: &bad_slots, - }, - ); + let input = stage_input((&bad_embedding, &bad_index), (&mut owners.cache, books), (&bad_records, &bad_slots)); + let result = owners.prompt.initialize_staged(lease, &mut owners.workspace, input); assert!(matches!(result, Err(Error::NonFiniteMmqOutput(_))), "case {case}: {:?}", result.as_ref().err()); } - drop(arena); - prompt.close().expect("prompt close"); } diff --git a/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_fused_guards_equal.rs b/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_fused_guards_equal.rs index 15809ece..83493593 100644 --- a/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_fused_guards_equal.rs +++ b/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_fused_guards_equal.rs @@ -4,6 +4,70 @@ #[allow(unused_imports)] use super::*; +/// Token rows of every case. +const T: usize = 77; +const EPS: f32 = 1e-6; +/// Bytes of the per-row flag words. +const FLAGS_LEN: usize = T * 8 * 4; + +/// The device, the workspace stream and the original (`gr`) and staged (`stage`) kernel modules. +struct GrRig<'a> { + context: &'a Context<'a>, + workspace: &'a NativeBatchWorkspace<'a>, + gr: KernelModule, + stage: KernelModule, +} + +impl GrRig<'_> { + fn run(&self, launches: Vec>) { + run_all(self.context, self.workspace, launches); + } +} + +/// A device address argument. +fn a(b: &DeviceBuffer<'_>) -> A { + A::Address(h(b)) +} + +fn zeros<'c>(context: &'c Context<'c>, n: usize) -> DeviceBuffer<'c> { + upload(context, &vec![0u8; n]) +} + +/// The first `len` bytes of the Original's and the staged kernel's buffers are equal. +fn assert_same(case: usize, what: &str, (old, new): (&DeviceBuffer<'_>, &DeviceBuffer<'_>), len: usize) { + assert_eq!(download(old)[..len], download(new)[..len], "case {case}: {what}"); +} + +fn rnd(rng: &mut Rng, n: usize, scale: f32) -> Vec { + (0..n).map(|_| ((rng.next() % 20001) as f32 / 10000.0 - 1.0) * scale).collect() +} + +/// The host bytes of one case: R, gamma, g, bo and the injection. +struct Host { + rb: Vec, + wb: Vec, + gb: Vec, + bob: Vec, + injb: Vec, +} + +/// Cases: clean, a non-finite R word, a non-finite gate word, an overflowing product. +fn host_inputs(rng: &mut Rng, case: usize) -> Host { + let t = T; + let mut r = rnd(rng, t * 10240, 3.0); + let gamma = rnd(rng, 10240, 2.0); + let mut g = rnd(rng, t * 10240, 4.0); + let bo = rnd(rng, t * 2560, 1.0); + let inj = rnd(rng, t * 4, 2.0); + match case { + 1 => r[5 * 10240 + 777] = f32::INFINITY, + 2 => g[9 * 10240 + 3000] = f32::NAN, + 3 => r[11 * 10240 + 100] = 3.0e38, + _ => {} + } + Host { rb: f32_bytes(&r), wb: f32_bytes(&gamma), gb: f32_bytes(&g), bob: f32_bytes(&bo), injb: f32_bytes(&inj) } +} + #[test] #[ignore = "Root-only: needs a CUDA device"] fn gr_fused_guards_equal_the_separate_guard_kernels_bit_for_bit() { @@ -16,289 +80,151 @@ fn gr_fused_guards_equal_the_separate_guard_kernels_bit_for_bit() { let gr = KernelModule::load(GR_PTX, GR_ENTRIES).expect("gr module"); let stage = KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES).expect("stage module"); guard.finish().expect("finish"); - let t = 77usize; + let rig = GrRig { context: &context, workspace: &workspace, gr, stage }; let mut rng = Rng(0x2545f4914f6cdd1d); - let rnd = |rng: &mut Rng, n: usize, scale: f32| -> Vec { - (0..n).map(|_| ((rng.next() % 20001) as f32 / 10000.0 - 1.0) * scale).collect() - }; - let eps = 1e-6f32; - - // cases: clean, a non-finite R word, a non-finite gate word, an overflowing product for case in 0..4 { - let mut r = rnd(&mut rng, t * 10240, 3.0); - let gamma = rnd(&mut rng, 10240, 2.0); - let mut g = rnd(&mut rng, t * 10240, 4.0); - let bo = rnd(&mut rng, t * 2560, 1.0); - let inj = rnd(&mut rng, t * 4, 2.0); - match case { - 1 => r[5 * 10240 + 777] = f32::INFINITY, - 2 => g[9 * 10240 + 3000] = f32::NAN, - 3 => r[11 * 10240 + 100] = 3.0e38, - _ => {} - } - let flags_len = t * 8 * 4; - let (rb, wb, gb, bob, injb) = - (f32_bytes(&r), f32_bytes(&gamma), f32_bytes(&g), f32_bytes(&bo), f32_bytes(&inj)); - let mk = |n: usize| upload(&context, &vec![0u8; n]); - - // ---- norm - let (r_old, r_new) = (upload(&context, &rb), upload(&context, &rb)); - let w = upload(&context, &wb); - let (rs_o, rs_n, xn_o, xn_n, fl_o, fl_n) = - (mk(t * 16), mk(t * 16), mk(t * 20480), mk(t * 20480), mk(flags_len), mk(flags_len)); - run_all( - &context, - &workspace, - vec![ - ( - &gr, - 0, - t * 4, - 256, - vec![ - A::Address(h(&r_old)), - A::Address(h(&w)), - A::F32(eps), - A::Address(h(&rs_o)), - A::Address(h(&xn_o)), - A::NullAddress, - ], - ), - ( - &gr, - 5, - (t * 10240).div_ceil(256), - 256, - vec![ - A::Address(h(&r_old)), - A::Address(h(&rs_o)), - A::Address(h(&w)), - A::Address(h(&fl_o)), - A::I64(t as i64), - ], - ), - ( - &stage, - 3, - t * 4, - 256, - vec![ - A::Address(h(&r_new)), - A::Address(h(&w)), - A::F32(eps), - A::Address(h(&rs_n)), - A::Address(h(&xn_n)), - A::NullAddress, - A::Address(h(&fl_n)), - ], - ), - ], - ); - assert_eq!(download(&rs_o)[..t * 16], download(&rs_n)[..t * 16], "case {case}: rs"); - assert_eq!(download(&xn_o)[..t * 20480], download(&xn_n)[..t * 20480], "case {case}: xn16"); - assert_eq!(download(&fl_o)[..flags_len], download(&fl_n)[..flags_len], "case {case}: norm flags"); - - // ---- mix (uses the rs above) - let g_dev = upload(&context, &gb); - let (mx_o, mx_n, m16_o, m16_n, mh_o, mh_n) = - (mk(t * 10240), mk(t * 10240), mk(t * 5120), mk(t * 5120), mk(t * 5120), mk(t * 5120)); - let (fl2_o, fl2_n) = (mk(flags_len), mk(flags_len)); - run_all( - &context, - &workspace, - vec![ - ( - &gr, - 2, - (t * 2560).div_ceil(256), - 256, - vec![ - A::Address(h(&r_old)), - A::Address(h(&rs_o)), - A::Address(h(&w)), - A::Address(h(&g_dev)), - A::Address(h(&mx_o)), - A::Address(h(&m16_o)), - A::I64(t as i64), - A::Address(h(&mh_o)), - A::NullAddress, - ], - ), - ( - &gr, - 7, - (t * 10240).div_ceil(256), - 256, - vec![ - A::Address(h(&r_old)), - A::Address(h(&rs_o)), - A::Address(h(&w)), - A::Address(h(&g_dev)), - A::Address(h(&fl2_o)), - A::I64(t as i64), - ], - ), - ( - &gr, - 4, - (t * 10240).div_ceil(256), - 256, - vec![A::Address(h(&g_dev)), A::Address(h(&fl2_o)), A::I64(10240), A::I64(t as i64), A::U32(3)], - ), - ( - &gr, - 4, - (t * 2560).div_ceil(256), - 256, - vec![A::Address(h(&mx_o)), A::Address(h(&fl2_o)), A::I64(2560), A::I64(t as i64), A::U32(5)], - ), - ( - &stage, - 4, - (t * 2560).div_ceil(256), - 256, - vec![ - A::Address(h(&r_new)), - A::Address(h(&rs_n)), - A::Address(h(&w)), - A::Address(h(&g_dev)), - A::Address(h(&mx_n)), - A::Address(h(&m16_n)), - A::I64(t as i64), - A::Address(h(&mh_n)), - A::NullAddress, - A::Address(h(&fl2_n)), - ], - ), - ], - ); - assert_eq!(download(&mx_o)[..t * 10240], download(&mx_n)[..t * 10240], "case {case}: mixed"); - assert_eq!(download(&m16_o)[..t * 5120], download(&m16_n)[..t * 5120], "case {case}: mixed bf16"); - assert_eq!(download(&mh_o)[..t * 5120], download(&mh_n)[..t * 5120], "case {case}: mixed f16"); - assert_eq!(download(&fl2_o)[..flags_len], download(&fl2_n)[..flags_len], "case {case}: mix flags"); - - // ---- fused write + next norm - let (rw_o, rw_n) = (upload(&context, &rb), upload(&context, &rb)); - let (bo_d, inj_d) = (upload(&context, &bob), upload(&context, &injb)); - let (rs2_o, rs2_n, xn2_o, xn2_n, fl3_o, fl3_n) = - (mk(t * 16), mk(t * 16), mk(t * 20480), mk(t * 20480), mk(flags_len), mk(flags_len)); - run_all( - &context, - &workspace, - vec![ - ( - &gr, - 8, - t * 4, - 256, - vec![ - A::Address(h(&rw_o)), - A::Address(h(&bo_d)), - A::Address(h(&inj_d)), - A::I64(4), - A::Address(h(&w)), - A::F32(eps), - A::Address(h(&rs2_o)), - A::Address(h(&xn2_o)), - A::NullAddress, - ], - ), - ( - &gr, - 4, - (t * 10240).div_ceil(256), - 256, - vec![A::Address(h(&rw_o)), A::Address(h(&fl3_o)), A::I64(10240), A::I64(t as i64), A::U32(7)], - ), - ( - &gr, - 5, - (t * 10240).div_ceil(256), - 256, - vec![ - A::Address(h(&rw_o)), - A::Address(h(&rs2_o)), - A::Address(h(&w)), - A::Address(h(&fl3_o)), - A::I64(t as i64), - ], - ), - ( - &stage, - 5, - t * 4, - 256, - vec![ - A::Address(h(&rw_n)), - A::Address(h(&bo_d)), - A::Address(h(&inj_d)), - A::I64(4), - A::Address(h(&w)), - A::F32(eps), - A::Address(h(&rs2_n)), - A::Address(h(&xn2_n)), - A::NullAddress, - A::Address(h(&fl3_n)), - ], - ), - ], - ); - assert_eq!(download(&rw_o)[..t * 40960], download(&rw_n)[..t * 40960], "case {case}: R after fused write"); - assert_eq!(download(&rs2_o)[..t * 16], download(&rs2_n)[..t * 16], "case {case}: rs after write"); - assert_eq!(download(&xn2_o)[..t * 20480], download(&xn2_n)[..t * 20480], "case {case}: xn16 after write"); - assert_eq!(download(&fl3_o)[..flags_len], download(&fl3_n)[..flags_len], "case {case}: write flags"); - - // ---- plain write - let (rp_o, rp_n) = (upload(&context, &rb), upload(&context, &rb)); - let (fl4_o, fl4_n) = (mk(flags_len), mk(flags_len)); - run_all( - &context, - &workspace, - vec![ - ( - &gr, - 3, - (t * 10240).div_ceil(256), - 256, - vec![ - A::Address(h(&rp_o)), - A::Address(h(&bo_d)), - A::Address(h(&inj_d)), - A::I64(4), - A::I64(t as i64), - ], - ), - ( - &gr, - 4, - (t * 10240).div_ceil(256), - 256, - vec![A::Address(h(&rp_o)), A::Address(h(&fl4_o)), A::I64(10240), A::I64(t as i64), A::U32(7)], - ), - ( - &stage, - 6, - (t * 10240).div_ceil(256), - 256, - vec![ - A::Address(h(&rp_n)), - A::Address(h(&bo_d)), - A::Address(h(&inj_d)), - A::I64(4), - A::I64(t as i64), - A::Address(h(&fl4_n)), - ], - ), - ], - ); - assert_eq!(download(&rp_o)[..t * 40960], download(&rp_n)[..t * 40960], "case {case}: R after write"); - assert_eq!(download(&fl4_o)[..flags_len], download(&fl4_n)[..flags_len], "case {case}: plain write flags"); - let raised = [&fl_n, &fl2_n, &fl3_n, &fl4_n].iter().any(|f| download(f).iter().any(|b| *b != 0)); - eprintln!("PREFILL-GR case {case}: outputs and flags equal (flags raised: {raised})"); - if case == 0 { - assert!(!raised, "the clean case must raise nothing"); - } else if case < 3 { - assert!(raised, "case {case} must raise a flag in both arms"); - } + guard_case(&rig, &mut rng, case); } } + +/// One case through the four phases (norm, mix, fused write + next norm, plain write); every phase's outputs and +/// flag words equal the Original's kernels followed by the separate guard kernels. +fn guard_case(rig: &GrRig<'_>, rng: &mut Rng, case: usize) { + let host = host_inputs(rng, case); + let norm = norm_phase(rig, &host, case); + let fl2 = mix_phase(rig, &host, &norm, case); + let (fl3, bo_d, inj_d) = write_phase(rig, &host, &norm.w, case); + let fl4 = plain_write_phase(rig, &host, (&bo_d, &inj_d), case); + let raised = [&norm.fl_n, &fl2, &fl3, &fl4].iter().any(|f| download(f).iter().any(|b| *b != 0)); + eprintln!("PREFILL-GR case {case}: outputs and flags equal (flags raised: {raised})"); + if case == 0 { + assert!(!raised, "the clean case must raise nothing"); + } else if case < 3 { + assert!(raised, "case {case} must raise a flag in both arms"); + } +} + +/// What the later phases reuse from the norm phase: both R copies, gamma, both row scales and the staged flags. +struct NormOut<'c> { + r_old: DeviceBuffer<'c>, + r_new: DeviceBuffer<'c>, + w: DeviceBuffer<'c>, + rs_o: DeviceBuffer<'c>, + rs_n: DeviceBuffer<'c>, + fl_n: DeviceBuffer<'c>, +} + +fn norm_phase<'c>(rig: &GrRig<'c>, host: &Host, case: usize) -> NormOut<'c> { + let (c, t, gr, stage) = (rig.context, T, &rig.gr, &rig.stage); + let (r_old, r_new) = (upload(c, &host.rb), upload(c, &host.rb)); + let w = upload(c, &host.wb); + let (rs_o, rs_n, xn_o, xn_n) = (zeros(c, t * 16), zeros(c, t * 16), zeros(c, t * 20480), zeros(c, t * 20480)); + let (fl_o, fl_n) = (zeros(c, FLAGS_LEN), zeros(c, FLAGS_LEN)); + rig.run(vec![ + (gr, 0, t * 4, 256, vec![a(&r_old), a(&w), A::F32(EPS), a(&rs_o), a(&xn_o), A::NullAddress]), + (gr, 5, (t * 10240).div_ceil(256), 256, vec![a(&r_old), a(&rs_o), a(&w), a(&fl_o), A::I64(t as i64)]), + (stage, 3, t * 4, 256, vec![a(&r_new), a(&w), A::F32(EPS), a(&rs_n), a(&xn_n), A::NullAddress, a(&fl_n)]), + ]); + assert_same(case, "rs", (&rs_o, &rs_n), t * 16); + assert_same(case, "xn16", (&xn_o, &xn_n), t * 20480); + assert_same(case, "norm flags", (&fl_o, &fl_n), FLAGS_LEN); + NormOut { r_old, r_new, w, rs_o, rs_n, fl_n } +} + +/// Mix (uses the row scales of the norm phase); returns the staged flags. +fn mix_phase<'c>(rig: &GrRig<'c>, host: &Host, norm: &NormOut<'c>, case: usize) -> DeviceBuffer<'c> { + let (c, t, gr, stage) = (rig.context, T, &rig.gr, &rig.stage); + let g_dev = upload(c, &host.gb); + let (mx_o, mx_n) = (zeros(c, t * 10240), zeros(c, t * 10240)); + let (m16_o, m16_n, mh_o, mh_n) = (zeros(c, t * 5120), zeros(c, t * 5120), zeros(c, t * 5120), zeros(c, t * 5120)); + let (fl2_o, fl2_n) = (zeros(c, FLAGS_LEN), zeros(c, FLAGS_LEN)); + let NormOut { r_old, r_new, w, rs_o, rs_n, .. } = norm; + let rows = (t * 10240).div_ceil(256); + let mix_old = + vec![a(r_old), a(rs_o), a(w), a(&g_dev), a(&mx_o), a(&m16_o), A::I64(t as i64), a(&mh_o), A::NullAddress]; + let mix_new = vec![ + a(r_new), + a(rs_n), + a(w), + a(&g_dev), + a(&mx_n), + a(&m16_n), + A::I64(t as i64), + a(&mh_n), + A::NullAddress, + a(&fl2_n), + ]; + rig.run(vec![ + (gr, 2, (t * 2560).div_ceil(256), 256, mix_old), + (gr, 7, rows, 256, vec![a(r_old), a(rs_o), a(w), a(&g_dev), a(&fl2_o), A::I64(t as i64)]), + (gr, 4, rows, 256, vec![a(&g_dev), a(&fl2_o), A::I64(10240), A::I64(t as i64), A::U32(3)]), + (gr, 4, (t * 2560).div_ceil(256), 256, vec![a(&mx_o), a(&fl2_o), A::I64(2560), A::I64(t as i64), A::U32(5)]), + (stage, 4, (t * 2560).div_ceil(256), 256, mix_new), + ]); + assert_same(case, "mixed", (&mx_o, &mx_n), t * 10240); + assert_same(case, "mixed bf16", (&m16_o, &m16_n), t * 5120); + assert_same(case, "mixed f16", (&mh_o, &mh_n), t * 5120); + assert_same(case, "mix flags", (&fl2_o, &fl2_n), FLAGS_LEN); + fl2_n +} + +/// Fused write + next norm; returns the staged flags and the uploaded bo and injection the plain write reuses. +fn write_phase<'c>( + rig: &GrRig<'c>, + host: &Host, + w: &DeviceBuffer<'c>, + case: usize, +) -> (DeviceBuffer<'c>, DeviceBuffer<'c>, DeviceBuffer<'c>) { + let (c, t, gr, stage) = (rig.context, T, &rig.gr, &rig.stage); + let (rw_o, rw_n) = (upload(c, &host.rb), upload(c, &host.rb)); + let (bo_d, inj_d) = (upload(c, &host.bob), upload(c, &host.injb)); + let (rs2_o, rs2_n, xn2_o, xn2_n) = (zeros(c, t * 16), zeros(c, t * 16), zeros(c, t * 20480), zeros(c, t * 20480)); + let (fl3_o, fl3_n) = (zeros(c, FLAGS_LEN), zeros(c, FLAGS_LEN)); + let rows = (t * 10240).div_ceil(256); + let write_old = + vec![a(&rw_o), a(&bo_d), a(&inj_d), A::I64(4), a(w), A::F32(EPS), a(&rs2_o), a(&xn2_o), A::NullAddress]; + let write_new = vec![ + a(&rw_n), + a(&bo_d), + a(&inj_d), + A::I64(4), + a(w), + A::F32(EPS), + a(&rs2_n), + a(&xn2_n), + A::NullAddress, + a(&fl3_n), + ]; + rig.run(vec![ + (gr, 8, t * 4, 256, write_old), + (gr, 4, rows, 256, vec![a(&rw_o), a(&fl3_o), A::I64(10240), A::I64(t as i64), A::U32(7)]), + (gr, 5, rows, 256, vec![a(&rw_o), a(&rs2_o), a(w), a(&fl3_o), A::I64(t as i64)]), + (stage, 5, t * 4, 256, write_new), + ]); + assert_same(case, "R after fused write", (&rw_o, &rw_n), t * 40960); + assert_same(case, "rs after write", (&rs2_o, &rs2_n), t * 16); + assert_same(case, "xn16 after write", (&xn2_o, &xn2_n), t * 20480); + assert_same(case, "write flags", (&fl3_o, &fl3_n), FLAGS_LEN); + (fl3_n, bo_d, inj_d) +} + +/// Plain write; returns the staged flags. +fn plain_write_phase<'c>( + rig: &GrRig<'c>, + host: &Host, + (bo_d, inj_d): (&DeviceBuffer<'c>, &DeviceBuffer<'c>), + case: usize, +) -> DeviceBuffer<'c> { + let (c, t, gr, stage) = (rig.context, T, &rig.gr, &rig.stage); + let (rp_o, rp_n) = (upload(c, &host.rb), upload(c, &host.rb)); + let (fl4_o, fl4_n) = (zeros(c, FLAGS_LEN), zeros(c, FLAGS_LEN)); + let rows = (t * 10240).div_ceil(256); + rig.run(vec![ + (gr, 3, rows, 256, vec![a(&rp_o), a(bo_d), a(inj_d), A::I64(4), A::I64(t as i64)]), + (gr, 4, rows, 256, vec![a(&rp_o), a(&fl4_o), A::I64(10240), A::I64(t as i64), A::U32(7)]), + (stage, 6, rows, 256, vec![a(&rp_n), a(bo_d), a(inj_d), A::I64(4), A::I64(t as i64), a(&fl4_n)]), + ]); + assert_same(case, "R after write", (&rp_o, &rp_n), t * 40960); + assert_same(case, "plain write flags", (&fl4_o, &fl4_n), FLAGS_LEN); + fl4_n +} diff --git a/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_kernels_run_near_their.rs b/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_kernels_run_near_their.rs index a6857cf3..d30236d2 100644 --- a/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_kernels_run_near_their.rs +++ b/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_kernels_run_near_their.rs @@ -20,37 +20,82 @@ fn gr_kernels_run_near_their_traffic_floor_at_chunk_size() { guard.finish().expect("finish"); let t = 8192usize; let mut rng = Rng(0x1234_5678_9abc_def0); - let rnd = |rng: &mut Rng, n: usize, scale: f32| -> Vec { - (0..n).map(|_| ((rng.next() % 20001) as f32 / 10000.0 - 1.0) * scale).collect() - }; + let b = traffic_buffers(&context, &mut rng, t); + let mut timer = Timer { context: &context, blas: workspace.blas().expect("blas"), stage: &stage, keep: Vec::new() }; + let r_bytes = (t * 40960) as f64; + time_norm(&mut timer, &b, (t, r_bytes)); + time_mix(&mut timer, &b, (t, r_bytes)); + time_write_norm(&mut timer, &b, (t, r_bytes)); +} + +fn rnd(rng: &mut Rng, n: usize, scale: f32) -> Vec { + (0..n).map(|_| ((rng.next() % 20001) as f32 / 10000.0 - 1.0) * scale).collect() +} + +/// The residual and its inputs at the chunk size, and the output buffers of the three kernels. +struct TrafficBuffers<'c> { + r_d: DeviceBuffer<'c>, + w_d: DeviceBuffer<'c>, + g_d: DeviceBuffer<'c>, + bo_d: DeviceBuffer<'c>, + inj_d: DeviceBuffer<'c>, + rs: DeviceBuffer<'c>, + xn: DeviceBuffer<'c>, + mx: DeviceBuffer<'c>, + m16: DeviceBuffer<'c>, + mh: DeviceBuffer<'c>, + fl: DeviceBuffer<'c>, +} + +fn traffic_buffers<'c>(context: &'c Context<'c>, rng: &mut Rng, t: usize) -> TrafficBuffers<'c> { let (r, gamma, g, bo, inj) = ( - rnd(&mut rng, t * 10240, 3.0), - rnd(&mut rng, 10240, 2.0), - rnd(&mut rng, t * 10240, 4.0), - rnd(&mut rng, t * 2560, 1.0), - rnd(&mut rng, t * 4, 2.0), + rnd(rng, t * 10240, 3.0), + rnd(rng, 10240, 2.0), + rnd(rng, t * 10240, 4.0), + rnd(rng, t * 2560, 1.0), + rnd(rng, t * 4, 2.0), ); - let mk = |n: usize| upload(&context, &vec![0u8; n]); - let (r_d, w_d, g_d, bo_d, inj_d) = ( - upload(&context, &f32_bytes(&r)), - upload(&context, &f32_bytes(&gamma)), - upload(&context, &f32_bytes(&g)), - upload(&context, &f32_bytes(&bo)), - upload(&context, &f32_bytes(&inj)), - ); - let (rs, xn, mx, m16, mh, fl) = - (mk(t * 16), mk(t * 20480), mk(t * 10240), mk(t * 5120), mk(t * 5120), mk(t * 8 * 4)); - let eps = 1e-6f32; - let blas = workspace.blas().expect("blas"); - let time = |what: &str, bytes: f64, launch: &mut dyn FnMut()| { - let guard = context.enter().expect("enter"); - launch(); - blas.synchronize().expect("sync"); + let mk = |n: usize| upload(context, &vec![0u8; n]); + TrafficBuffers { + r_d: upload(context, &f32_bytes(&r)), + w_d: upload(context, &f32_bytes(&gamma)), + g_d: upload(context, &f32_bytes(&g)), + bo_d: upload(context, &f32_bytes(&bo)), + inj_d: upload(context, &f32_bytes(&inj)), + rs: mk(t * 16), + xn: mk(t * 20480), + mx: mk(t * 10240), + m16: mk(t * 5120), + mh: mk(t * 5120), + fl: mk(t * 8 * 4), + } +} + +/// Launches a stage kernel repeatedly on the workspace stream and reports the achieved bandwidth. +struct Timer<'a> { + context: &'a Context<'a>, + blas: &'a crate::ple_batch_ffi::Blas, + stage: &'a KernelModule, + keep: Vec, +} + +impl Timer<'_> { + fn launch(&mut self, (index, grid, args): (usize, usize, Vec)) { + let mut a = KernelArguments::new(args); + self.stage.launch(index, grid as u32, 256, self.blas.stream(), &mut a).expect("launch"); + self.keep.push(a); + } + + /// One warm-up launch, then 20 timed launches of `next()`. + fn time(&mut self, what: &str, bytes: f64, mut next: impl FnMut() -> (usize, usize, Vec)) { + let guard = self.context.enter().expect("enter"); + self.launch(next()); + self.blas.synchronize().expect("sync"); let started = std::time::Instant::now(); for _ in 0..20 { - launch(); + self.launch(next()); } - blas.synchronize().expect("sync"); + self.blas.synchronize().expect("sync"); let us = started.elapsed().as_secs_f64() * 1e6 / 20.0; guard.finish().expect("finish"); eprintln!( @@ -58,71 +103,60 @@ fn gr_kernels_run_near_their_traffic_floor_at_chunk_size() { bytes / 1e6, bytes / us / 1e6 ); - }; - let r_bytes = (t * 40960) as f64; - let mut keep = Vec::new(); - let mut run = |index: usize, grid: usize, args: Vec| { - let mut a = KernelArguments::new(args); - stage.launch(index, grid as u32, 256, blas.stream(), &mut a).expect("launch"); - keep.push(a); - }; - time("norm_rs (R in, xn16 out)", r_bytes + (t * 20480) as f64, &mut || { - run( - 3, - t * 4, - vec![ - A::Address(h(&r_d)), - A::Address(h(&w_d)), - A::F32(eps), - A::Address(h(&rs)), - A::Address(h(&xn)), - A::NullAddress, - A::Address(h(&fl)), - ], - ) - }); - time( - "mix_r (R, g in; mixed f32 + bf16 + f16 out)", - 2.0 * r_bytes + (t * (10240 + 5120 + 5120)) as f64, - &mut || { - run( - 4, - (t * 2560).div_ceil(256), - vec![ - A::Address(h(&r_d)), - A::Address(h(&rs)), - A::Address(h(&w_d)), - A::Address(h(&g_d)), - A::Address(h(&mx)), - A::Address(h(&m16)), - A::I64(t as i64), - A::Address(h(&mh)), - A::NullAddress, - A::Address(h(&fl)), - ], - ) - }, - ); - time( - "write_norm_rs (R in+out, bo in, xn16 out)", - 2.0 * r_bytes + (t * 10240) as f64 + (t * 20480) as f64, - &mut || { - run( - 5, - t * 4, - vec![ - A::Address(h(&r_d)), - A::Address(h(&bo_d)), - A::Address(h(&inj_d)), - A::I64(4), - A::Address(h(&w_d)), - A::F32(eps), - A::Address(h(&rs)), - A::Address(h(&xn)), - A::NullAddress, - A::Address(h(&fl)), - ], - ) - }, - ); + } } + +fn time_norm(timer: &mut Timer<'_>, b: &TrafficBuffers<'_>, (t, r_bytes): (usize, f64)) { + let args = || { + let args = vec![a(&b.r_d), a(&b.w_d), A::F32(EPS), a(&b.rs), a(&b.xn), A::NullAddress, a(&b.fl)]; + (3, t * 4, args) + }; + timer.time("norm_rs (R in, xn16 out)", r_bytes + (t * 20480) as f64, args); +} + +fn time_mix(timer: &mut Timer<'_>, b: &TrafficBuffers<'_>, (t, r_bytes): (usize, f64)) { + let args = || { + let args = vec![ + a(&b.r_d), + a(&b.rs), + a(&b.w_d), + a(&b.g_d), + a(&b.mx), + a(&b.m16), + A::I64(t as i64), + a(&b.mh), + A::NullAddress, + a(&b.fl), + ]; + (4, (t * 2560).div_ceil(256), args) + }; + let bytes = 2.0 * r_bytes + (t * (10240 + 5120 + 5120)) as f64; + timer.time("mix_r (R, g in; mixed f32 + bf16 + f16 out)", bytes, args); +} + +fn time_write_norm(timer: &mut Timer<'_>, b: &TrafficBuffers<'_>, (t, r_bytes): (usize, f64)) { + let args = || { + let args = vec![ + a(&b.r_d), + a(&b.bo_d), + a(&b.inj_d), + A::I64(4), + a(&b.w_d), + A::F32(EPS), + a(&b.rs), + a(&b.xn), + A::NullAddress, + a(&b.fl), + ]; + (5, t * 4, args) + }; + let bytes = 2.0 * r_bytes + (t * 10240) as f64 + (t * 20480) as f64; + timer.time("write_norm_rs (R in+out, bo in, xn16 out)", bytes, args); +} + +/// A device address argument. +fn a(b: &DeviceBuffer<'_>) -> A { + A::Address(h(b)) +} + +const EPS: f32 = 1e-6; diff --git a/crates/cuda-driver/src/q6_k_shape_fn.rs b/crates/cuda-driver/src/q6_k_shape_fn.rs index 3e8ff324..8124fb5b 100644 --- a/crates/cuda-driver/src/q6_k_shape_fn.rs +++ b/crates/cuda-driver/src/q6_k_shape_fn.rs @@ -12,25 +12,12 @@ pub(super) fn q6_k_shape(rows: usize, columns: usize) -> Result { if rows_abi > i32::MAX as u32 || columns_abi > i32::MAX as u32 { return Err(Error::InvalidQ6KProjectionShape); } - let checked_bytes = |elements: usize, width: usize| -> Result { - let bytes = elements.checked_mul(width).ok_or(Error::InvalidQ6KProjectionShape)?; - valid_size(bytes).map_err(|_| Error::InvalidQ6KProjectionShape)?; - Ok(bytes) - }; let weight_blocks = rows.checked_mul(columns / 256).ok_or(Error::InvalidQ6KProjectionShape)?; - let weight_bytes = checked_bytes(weight_blocks, 210)?; - let activation_bytes = checked_bytes(columns, 4)?; - let output_bytes = checked_bytes(rows, 4)?; - let scratch_bytes = checked_bytes(columns / 32, 36)?; - let quant_grid = columns / 256; - if quant_grid == 0 || quant_grid > i32::MAX as usize { - return Err(Error::InvalidQ6KProjectionShape); - } - let small_k = columns / 256 < 4; - let projection_ctas = if small_k { rows.div_ceil(4) } else { rows }; - if projection_ctas == 0 || projection_ctas > i32::MAX as usize { - return Err(Error::InvalidQ6KProjectionShape); - } + let weight_bytes = q6_checked_bytes(weight_blocks, 210)?; + let activation_bytes = q6_checked_bytes(columns, 4)?; + let output_bytes = q6_checked_bytes(rows, 4)?; + let scratch_bytes = q6_checked_bytes(columns / 32, 36)?; + let (quant_grid, projection_ctas) = q6_grids(rows, columns)?; Ok(Q6KShape { weight_bytes, activation_bytes, @@ -42,6 +29,25 @@ pub(super) fn q6_k_shape(rows: usize, columns: usize) -> Result { projection_grid: u32::try_from(projection_ctas).map_err(|_| Error::InvalidQ6KProjectionShape)?, }) } +/// `elements * width` bytes, within the context's size limit. +fn q6_checked_bytes(elements: usize, width: usize) -> Result { + let bytes = elements.checked_mul(width).ok_or(Error::InvalidQ6KProjectionShape)?; + valid_size(bytes).map_err(|_| Error::InvalidQ6KProjectionShape)?; + Ok(bytes) +} +/// The quantize grid and the projection CTA count (four rows per CTA below four K blocks). +fn q6_grids(rows: usize, columns: usize) -> Result<(usize, usize)> { + let quant_grid = columns / 256; + if quant_grid == 0 || quant_grid > i32::MAX as usize { + return Err(Error::InvalidQ6KProjectionShape); + } + let small_k = columns / 256 < 4; + let projection_ctas = if small_k { rows.div_ceil(4) } else { rows }; + if projection_ctas == 0 || projection_ctas > i32::MAX as usize { + return Err(Error::InvalidQ6KProjectionShape); + } + Ok((quant_grid, projection_ctas)) +} pub(super) fn matvec_shape(rows: usize, columns: usize) -> Result { let rows_abi = u32::try_from(rows).map_err(|_| Error::InvalidMatvecShape)?; let columns_abi = u32::try_from(columns).map_err(|_| Error::InvalidMatvecShape)?; diff --git a/crates/cuda-driver/src/q6_layer_preview.rs b/crates/cuda-driver/src/q6_layer_preview.rs index 25c92978..b133c34f 100644 --- a/crates/cuda-driver/src/q6_layer_preview.rs +++ b/crates/cuda-driver/src/q6_layer_preview.rs @@ -42,6 +42,68 @@ mod installed { quant_attempts: Cell, project_attempts: Cell, } + /// The two kernels of the module; a failed lookup unloads the module (poisoning the context when that fails too). + fn resolve_kernels(context: &Context<'_>, module: ffi::ModuleHandle) -> Result<[ffi::FunctionHandle; 2]> { + let resolved = (|| { + Ok([ + context.driver.api.fixed_function(module, FixedOperation::Q6KQuantize)?, + context.driver.api.fixed_function(module, FixedOperation::Q6KProject)?, + ]) + })(); + match resolved { + Ok(v) => Ok(v), + Err(e) => { + let cleanup = context.driver.api.unload(module); + if cleanup.is_err() { + context.poisoned.set(true); + std::mem::forget(Rc::clone(&context.driver.api)); + } + combine(Err(e), cleanup) + } + } + } + /// The quantized scratch and its one-word status; a failed second allocation releases (or, poisoned, forgets) the first. + fn allocate_scratch_and_status<'c>( + context: &'c Context<'c>, + qbytes: usize, + ) -> Result<(DeviceBuffer<'c>, DeviceBuffer<'c>)> { + let scratch = context.allocate(qbytes)?; + let status = match context.allocate(4) { + Ok(v) => v, + Err(e) => { + if context.poisoned.get() { + std::mem::forget(scratch); + return Err(e); + } + return combine(Err(e), scratch.release()); + } + }; + Ok((scratch, status)) + } + /// Releases the temporaries after the quantize `operation`; a poisoned context forgets them instead. + fn settle_quantize<'c>( + context: &Context<'_>, + operation: Result<()>, + scratch: DeviceBuffer<'c>, + status: DeviceBuffer<'c>, + ) -> Result> { + if context.poisoned.get() { + std::mem::forget(scratch); + std::mem::forget(status); + return operation.map(|()| unreachable!()); + } + if let Err(e) = operation { + return context.release_quantized_temporaries(Err(e), scratch, status); + } + if let Err(e) = status.release() { + if context.poisoned.get() { + std::mem::forget(scratch); + return Err(e); + } + return combine(Err(e), scratch.release()); + } + Ok(scratch) + } impl Prepared<'_> { pub fn close(self) -> Result<()> { self.scratch.release() @@ -57,22 +119,9 @@ mod installed { Ok(v) => v, Err(e) => return combine(Err(e), guard.finish()), }; - let resolved = (|| { - Ok([ - context.driver.api.fixed_function(module, FixedOperation::Q6KQuantize)?, - context.driver.api.fixed_function(module, FixedOperation::Q6KProject)?, - ]) - })(); - let kernels = match resolved { + let kernels = match resolve_kernels(context, module) { Ok(v) => v, - Err(e) => { - let cleanup = context.driver.api.unload(module); - if cleanup.is_err() { - context.poisoned.set(true); - std::mem::forget(Rc::clone(&context.driver.api)); - } - return combine(combine(Err(e), cleanup), guard.finish()); - } + Err(e) => return combine(Err(e), guard.finish()), }; if let Err(e) = guard.finish() { context.poisoned.set(true); @@ -102,6 +151,15 @@ mod installed { ) -> Result> { self.live()?; let (s, xbytes, qbytes, _) = shape(rows, columns, tokens)?; + let context = self.context; + let xhandle = self.admit_activation(x, xbytes, qbytes)?; + let (scratch, mut status) = allocate_scratch_and_status(context, qbytes)?; + let operation = self.quantize_into(&s, tokens, xhandle, (&scratch, &mut status)); + let scratch = settle_quantize(context, operation, scratch, status)?; + Ok(Prepared { scratch, rows, columns, tokens }) + } + /// The activation is this context's exact `xbytes` and the scratch plus status fit the budget. + fn admit_activation(&self, x: &DeviceBuffer<'_>, xbytes: usize, qbytes: usize) -> Result { let context = self.context; if !std::ptr::eq(context, x.context) { return Err(Error::ContextMismatch); @@ -118,53 +176,36 @@ mod installed { if needed > context.budget_bytes() { return Err(Error::BudgetExceeded); } - let scratch = context.allocate(qbytes)?; - let mut status = match context.allocate(4) { - Ok(v) => v, - Err(e) => { - if context.poisoned.get() { - std::mem::forget(scratch); - return Err(e); - } - return combine(Err(e), scratch.release()); - } - }; - let operation = (|| { - status.copy_from(&[0; 4])?; - let mut args = ffi::Q8QuantizeArguments::new( - xhandle, - scratch.handle.ok_or(Error::ContextPoisoned)?, - status.handle.ok_or(Error::ContextPoisoned)?, - s.columns, - ); - let guard = context.enter()?; - let launched = - context.driver.api.quantize_q6_batch(self.kernels[0], s.quant_grid, tokens as u32, &mut args); - self.quant_attempts.set(self.quant_attempts.get() + 1); - context.complete_launch(launched, args, guard)?; - let mut bytes = [0; 4]; - status.copy_to(&mut bytes)?; - if u32::from_le_bytes(bytes) != 0 { - return Err(Error::InvalidQ8Activation); - } - Ok(()) - })(); - if context.poisoned.get() { - std::mem::forget(scratch); - std::mem::forget(status); - return operation.map(|()| unreachable!()); + Ok(xhandle) + } + /// Zeroes the status, quantizes the activation into the scratch and reads the status back. + fn quantize_into( + &self, + s: &Q6KShape, + tokens: usize, + xhandle: ffi::BufferHandle, + (scratch, status): (&DeviceBuffer<'ctx>, &mut DeviceBuffer<'ctx>), + ) -> Result<()> { + let context = self.context; + status.copy_from(&[0; 4])?; + let scratch_handle = scratch.handle.ok_or(Error::ContextPoisoned)?; + let mut args = ffi::Q8QuantizeArguments::new( + xhandle, + scratch_handle, + status.handle.ok_or(Error::ContextPoisoned)?, + s.columns, + ); + let guard = context.enter()?; + let launched = + context.driver.api.quantize_q6_batch(self.kernels[0], s.quant_grid, tokens as u32, &mut args); + self.quant_attempts.set(self.quant_attempts.get() + 1); + context.complete_launch(launched, args, guard)?; + let mut bytes = [0; 4]; + status.copy_to(&mut bytes)?; + if u32::from_le_bytes(bytes) != 0 { + return Err(Error::InvalidQ8Activation); } - if let Err(e) = operation { - return context.release_quantized_temporaries(Err(e), scratch, status); - } - if let Err(e) = status.release() { - if context.poisoned.get() { - std::mem::forget(scratch); - return Err(e); - } - return combine(Err(e), scratch.release()); - } - Ok(Prepared { scratch, rows, columns, tokens }) + Ok(()) } pub fn project(&self, w: &DeviceBuffer<'_>, q: &Prepared<'_>, y: &mut DeviceBuffer<'_>) -> Result<()> { self.live()?; diff --git a/crates/cuda-driver/src/qsa_index_ffi.rs b/crates/cuda-driver/src/qsa_index_ffi.rs index 1a7ba05a..37287b70 100644 --- a/crates/cuda-driver/src/qsa_index_ffi.rs +++ b/crates/cuda-driver/src/qsa_index_ffi.rs @@ -172,7 +172,26 @@ impl Launch { fn carries_rope(self) -> bool { matches!(self, Self::First | Self::Blocks(_) | Self::Rope(_) | Self::DecodeAppend | Self::DecodeRope(_)) } + /// Refuses the launches whose extents the Original fixes: the ScoreTC window and the decode norm/rope widths. + fn check_extents(self) -> Result<()> { + match self { + Self::Tc { t, reach } => { + if !(1..=256).contains(&t) + || reach == 0 + || reach as usize > crate::serving_context::geometry().max_blocks() + { + return Err(Error::InvalidQwenShape); + } + } + Self::DecodeRms(n) | Self::DecodeRope(n) if ![2, 4, 24].contains(&n) => { + return Err(Error::InvalidQwenShape); + } + _ => {} + } + Ok(()) + } fn shape(self) -> Result<(Entry, u32, u32, u32, u32)> { + self.check_extents()?; let (entry, x, y, threads, shared) = match self { Self::First => (Entry::First, 1, 1, 256, 0), Self::Blocks(n) => (Entry::Blocks, n, 1, 256, 0), @@ -183,29 +202,11 @@ impl Launch { Self::Round(n) => (Entry::Round, n.div_ceil(256), 1, 256, 0), Self::Scan(n) => (Entry::Scan, n.div_ceil(256), 1, 256, 0), Self::ScoreScan(n) => (Entry::ScoreScan, n.div_ceil(256), 1, 256, 0), - Self::Tc { t, reach } => { - if !(1..=256).contains(&t) - || reach == 0 - || reach as usize > crate::serving_context::geometry().max_blocks() - { - return Err(Error::InvalidQwenShape); - } - (Entry::Tc, reach.div_ceil(128), t.div_ceil(16), 128, 49920) - } + Self::Tc { t, reach } => (Entry::Tc, reach.div_ceil(128), t.div_ceil(16), 128, 49920), Self::ScoreTail(t) => (Entry::ScoreTail, t, 1, 32, 0), Self::Topk(t) => (Entry::Topk, t, 1, 256, 0), - Self::DecodeRms(n) => { - if ![2, 4, 24].contains(&n) { - return Err(Error::InvalidQwenShape); - } - (Entry::DecodeRms, n, 1, 256, 0) - } - Self::DecodeRope(n) => { - if ![2, 4, 24].contains(&n) { - return Err(Error::InvalidQwenShape); - } - (Entry::DecodeRope, 1, n, 128, 0) - } + Self::DecodeRms(n) => (Entry::DecodeRms, n, 1, 256, 0), + Self::DecodeRope(n) => (Entry::DecodeRope, 1, n, 128, 0), Self::DecodeAppend => (Entry::DecodeAppend, 1, 1, 256, 0), Self::DecodeScores => (Entry::DecodeScores, 256, 1, 256, 0), }; diff --git a/crates/cuda-driver/src/qsa_index_ffi/enabled.rs b/crates/cuda-driver/src/qsa_index_ffi/enabled.rs index 003f4899..1f215c23 100644 --- a/crates/cuda-driver/src/qsa_index_ffi/enabled.rs +++ b/crates/cuda-driver/src/qsa_index_ffi/enabled.rs @@ -65,29 +65,13 @@ impl Module { postops: &'static [u8], decode_postops: &'static [u8], ) -> Result { - if index.last() != Some(&0) - || select.last() != Some(&0) - || postops.last() != Some(&0) - || decode_postops.last() != Some(&0) - { + if [index, select, postops, decode_postops].iter().any(|asset| asset.last() != Some(&0)) { return Err(Error::InvalidSize); } - // SAFETY: fixed CUDA library, owned reference. - let ptr = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; - if ptr.is_null() { - return Err(Error::LibraryUnavailable); - } - let library = Library(ptr); + let library = open_cuda_library()?; let current = symbol!(library, c"cuCtxGetDevice", CurrentDevice); let device_attr = symbol!(library, c"cuDeviceGetAttribute", DeviceAttribute); - let mut device = 0; - let mut major = 0; - // SAFETY: actual current Context device, fixed COMPUTE_CAPABILITY_MAJOR75. - check("cuCtxGetDevice", unsafe { current(&mut device) })?; - check("cuDeviceGetAttribute", unsafe { device_attr(&mut major, 75, device) })?; - if major < 8 { - return Err(Error::UnsupportedProjection); - } + require_ampere(current, device_attr)?; let load = symbol!(library, c"cuModuleLoadData", Load); let function = symbol!(library, c"cuModuleGetFunction", Function); let attr = symbol!(library, c"cuFuncSetAttribute", Attribute); @@ -98,88 +82,48 @@ impl Module { modules: [None, None, None, None], functions: [0; 16], }; - let operation = (|| { - for (i, asset) in [index, select, postops, decode_postops].into_iter().enumerate() { - let mut m = std::ptr::null_mut(); - // SAFETY: pinned NUL asset and valid current Context. - check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(asset).as_ptr().cast()) })?; - if m.is_null() { - return Err(Error::InvalidDriverValue("cuModuleLoadData")); - } - owner.modules[i] = Some(m as usize); - } - for e in [ - Entry::First, - Entry::Blocks, - Entry::Tail, - Entry::Rms, - Entry::Rope, - Entry::Split, - Entry::Scan, - Entry::ScoreScan, - Entry::Round, - Entry::Tc, - Entry::ScoreTail, - Entry::Topk, - Entry::DecodeAppend, - Entry::DecodeScores, - Entry::DecodeRms, - Entry::DecodeRope, - ] { - let mut f = std::ptr::null_mut(); - let m = owner.modules[match e { - Entry::DecodeRms | Entry::DecodeRope => 3, - Entry::Rms | Entry::Rope | Entry::Split => 2, - Entry::Tc | Entry::ScoreTail | Entry::Topk | Entry::DecodeScores => 1, - _ => 0, - }] - .ok_or(Error::ContextPoisoned)?; - // SAFETY: real module and fixed export name. - check("cuModuleGetFunction", unsafe { function(&mut f, m as *mut c_void, e.name().as_ptr()) })?; - if f.is_null() { - return Err(Error::InvalidDriverValue("cuModuleGetFunction")); - } - owner.functions[e.index()] = f as usize; - } - // SAFETY: actual ScoreTC function, Original fixed attr max dynamic shared8/49,920. - check("cuFuncSetAttribute", unsafe { attr(owner.functions[Entry::Tc.index()] as *mut c_void, 8, 49920) })?; - Ok(()) - })(); + let operation = owner.init([index, select, postops, decode_postops], (load, function, attr)); if let Err(primary) = operation { return combine(Err(primary), owner.close()); } Ok(owner) } + /// Loads the four assets, resolves every entry and opts ScoreTC into its dynamic shared memory. + fn init(&mut self, assets: [&'static [u8]; 4], (load, function, attr): (Load, Function, Attribute)) -> Result<()> { + for (i, asset) in assets.into_iter().enumerate() { + let mut m = std::ptr::null_mut(); + // SAFETY: pinned NUL asset and valid current Context. + check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(asset).as_ptr().cast()) })?; + if m.is_null() { + return Err(Error::InvalidDriverValue("cuModuleLoadData")); + } + self.modules[i] = Some(m as usize); + } + for e in ENTRIES { + let mut f = std::ptr::null_mut(); + let m = self.modules[module_of(e)].ok_or(Error::ContextPoisoned)?; + // SAFETY: real module and fixed export name. + check("cuModuleGetFunction", unsafe { function(&mut f, m as *mut c_void, e.name().as_ptr()) })?; + if f.is_null() { + return Err(Error::InvalidDriverValue("cuModuleGetFunction")); + } + self.functions[e.index()] = f as usize; + } + // SAFETY: actual ScoreTC function, Original fixed attr max dynamic shared8/49,920. + check("cuFuncSetAttribute", unsafe { attr(self.functions[Entry::Tc.index()] as *mut c_void, 8, 49920) })?; + Ok(()) + } pub(crate) fn launch(&self, shape: Launch, stream: usize, args: &mut Arguments) -> Result<()> { if stream == 0 { return Err(Error::InvalidDriverValue("QSA stream")); } let (e, x, y, block, shared) = shape.shape()?; - args.pointers.clear(); - for a in &mut args.values { - args.pointers.push(match a { - Value::Address(v) => (v as *mut u64).cast(), - Value::I32(v) => (v as *mut i32).cast(), - Value::I64(v) => (v as *mut i64).cast(), - Value::U32(v) => (v as *mut u32).cast(), - Value::F32(v) => (v as *mut f32).cast(), - }); - } + args.pack(); + let (function, stream, pointers) = + (self.functions[e.index()] as *mut c_void, stream as *mut c_void, args.pointers.as_mut_ptr()); // SAFETY: closed fixed topology; boxed ABI fields and genuine owners retained until real drain. check("cuLaunchKernel", unsafe { - (self.launch)( - self.functions[e.index()] as *mut c_void, - x, - y, - 1, - block, - 1, - 1, - shared, - stream as *mut c_void, - args.pointers.as_mut_ptr(), - std::ptr::null_mut(), - ) + (self.launch)(function, x, y, 1, block, 1, 1, shared, stream, pointers, std::ptr::null_mut()) }) } pub(crate) fn close(mut self) -> Result<()> { @@ -206,3 +150,71 @@ impl Drop for Module { let _ = self.close_inner(); } } + +/// Every entry in function-table order of loading. +const ENTRIES: [Entry; 16] = [ + Entry::First, + Entry::Blocks, + Entry::Tail, + Entry::Rms, + Entry::Rope, + Entry::Split, + Entry::Scan, + Entry::ScoreScan, + Entry::Round, + Entry::Tc, + Entry::ScoreTail, + Entry::Topk, + Entry::DecodeAppend, + Entry::DecodeScores, + Entry::DecodeRms, + Entry::DecodeRope, +]; + +/// Which of the four loaded assets exports the entry: index, select, postops or decode postops. +fn module_of(e: Entry) -> usize { + match e { + Entry::DecodeRms | Entry::DecodeRope => 3, + Entry::Rms | Entry::Rope | Entry::Split => 2, + Entry::Tc | Entry::ScoreTail | Entry::Topk | Entry::DecodeScores => 1, + _ => 0, + } +} + +fn open_cuda_library() -> Result { + // SAFETY: fixed CUDA library, owned reference. + let ptr = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; + if ptr.is_null() { + return Err(Error::LibraryUnavailable); + } + Ok(Library(ptr)) +} + +/// The current Context's device must be compute capability 8 or newer. +fn require_ampere(current: CurrentDevice, device_attr: DeviceAttribute) -> Result<()> { + let mut device = 0; + let mut major = 0; + // SAFETY: actual current Context device, fixed COMPUTE_CAPABILITY_MAJOR75. + check("cuCtxGetDevice", unsafe { current(&mut device) })?; + check("cuDeviceGetAttribute", unsafe { device_attr(&mut major, 75, device) })?; + if major < 8 { + return Err(Error::UnsupportedProjection); + } + Ok(()) +} + +impl Arguments { + /// Points `pointers` at every value in order. + fn pack(&mut self) { + self.pointers.clear(); + for a in &mut self.values { + self.pointers.push(match a { + Value::Address(v) => (v as *mut u64).cast(), + Value::I32(v) => (v as *mut i32).cast(), + Value::I64(v) => (v as *mut i64).cast(), + Value::U32(v) => (v as *mut u32).cast(), + Value::F32(v) => (v as *mut f32).cast(), + }); + } + } +} diff --git a/crates/cuda-driver/src/qsa_late_gpu.rs b/crates/cuda-driver/src/qsa_late_gpu.rs index 8228e95d..66803b55 100644 --- a/crates/cuda-driver/src/qsa_late_gpu.rs +++ b/crates/cuda-driver/src/qsa_late_gpu.rs @@ -29,9 +29,8 @@ fn download(b: &DeviceBuffer<'_>, n: usize) -> Vec { b.copy_to_owned(b.len()).expect("download")[..n].to_vec() } -#[test] -#[ignore = "Root-only: needs a CUDA device"] -fn selection_kernels_equal_the_originals_at_long_positions() { +/// Opens the device with a 6 GiB budget and runs `body(context, stream, max_blocks)` on the workspace stream. +fn with_gpu(body: impl FnOnce(&Context<'_>, usize, usize)) { assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes")); let driver = Driver::load().expect("driver"); let device = driver.device(0).expect("device"); @@ -39,141 +38,218 @@ fn selection_kernels_equal_the_originals_at_long_positions() { let workspace = context.native_batch_workspace().expect("workspace"); let stream = workspace.blas().expect("blas").stream(); let max_blocks = crate::serving_context::geometry().max_blocks(); - let guard = context.enter().expect("enter"); - let select = - KernelModule::load(include_bytes!("qsa_prompt_select.ptx"), &[c"qsa_topk_ref"]).expect("select module"); - let index = - KernelModule::load(include_bytes!("qsa_prompt_indexer.ptx"), &[c"qsa_score_scan"]).expect("index module"); - let late = KernelModule::load(PTX, ENTRIES).expect("late module"); - guard.finish().expect("finish"); - let mut rng = Rng(0x243f6a8885a308d3); + body(&context, stream, max_blocks); +} - // (first position of the tile, rows, score style) - let cases: [(usize, usize, u8); 9] = [ - (180_000, 256, 0), // continuous - (180_000, 256, 1), // 16 levels, zeros and ties everywhere - (100_003, 64, 2), // all equal - (261_000, 128, 1), - (5_000, 64, 0), - (2_040, 64, 1), // the identity branch (n_kv <= width) for the first rows, selection after - (100, 32, 0), // identity everywhere - (3_999, 40, 2), // n_kv = 4 * n_bid on some rows (empty last block) - (65_536, 100, 1), - ]; - for (case, (p0, rows, style)) in cases.into_iter().enumerate() { - let mut steps = Vec::new(); - for r in 0..rows { - let pos = p0 + r; - for x in [pos, pos + 1, (pos + 1) / 4, (pos + 1).min(CAP)] { - steps.extend_from_slice(&(x as i32).to_le_bytes()); - } +fn handle(b: &DeviceBuffer<'_>) -> crate::ffi::BufferHandle { + b.handle.expect("handle") +} + +/// The per-row step words: position, position + 1, the block count and the clamped selection width. +fn step_bytes(p0: usize, rows: usize) -> Vec { + let mut steps = Vec::new(); + for r in 0..rows { + let pos = p0 + r; + for x in [pos, pos + 1, (pos + 1) / 4, (pos + 1).min(CAP)] { + steps.extend_from_slice(&(x as i32).to_le_bytes()); } - let mut scores = vec![0f32; rows * max_blocks]; - for r in 0..rows { - let n_bid = (p0 + r + 1) / 4; - for b in 0..=n_bid.min(max_blocks - 1) { - let v = match style { - 0 => (rng.next() % 1_000_003) as f32 / 1000.0, - 1 => ((rng.next() % 16) as f32) * 0.5 * ((rng.next() % 3 != 0) as u32 as f32), - _ => 0.0, - }; - scores[r * max_blocks + b] = v; - } - if style == 1 || style == 0 { - // the tail block of the real scorer: +1e9 when it is partly filled - if (p0 + r + 1) % 4 != 0 { - scores[r * max_blocks + n_bid] += 1e9; - } - } - } - let mut raw = Vec::with_capacity(scores.len() * 4); - scores.iter().for_each(|v| raw.extend_from_slice(&v.to_le_bytes())); - let scores_d = upload(&context, &raw); - let steps_d = upload(&context, &steps); - let out_len = rows * CAP * 4; - let ids_o = upload(&context, &vec![0xffu8; out_len]); - let ids_n = upload(&context, &vec![0xffu8; out_len]); - let h = |b: &DeviceBuffer<'_>| b.handle.expect("handle"); + } + steps +} + +fn f32_raw(values: &[f32]) -> Vec { + let mut raw = Vec::with_capacity(values.len() * 4); + values.iter().for_each(|v| raw.extend_from_slice(&v.to_le_bytes())); + raw +} + +/// The top-k arguments over `scores`/`steps` writing `ids`. +fn topk_args( + max_blocks: usize, + (scores, steps): (&DeviceBuffer<'_>, &DeviceBuffer<'_>), + ids: &DeviceBuffer<'_>, +) -> KernelArguments { + KernelArguments::new(vec![ + A::Address(handle(scores)), + A::Address(handle(steps)), + A::I64(max_blocks as i64), + A::I64(CAP as i64), + A::Address(handle(ids)), + ]) +} + +// ---------------------------------------------------------------------------------------------- selection kernels + +/// The modules of the selection proof: the Original's top-k and score scan, and the late kernels. +struct SelectionRig<'a> { + context: &'a Context<'a>, + stream: usize, + max_blocks: usize, + select: KernelModule, + index: KernelModule, + late: KernelModule, +} + +#[test] +#[ignore = "Root-only: needs a CUDA device"] +fn selection_kernels_equal_the_originals_at_long_positions() { + with_gpu(|context, stream, max_blocks| { let guard = context.enter().expect("enter"); - let mut a_old = KernelArguments::new(vec![ - A::Address(h(&scores_d)), - A::Address(h(&steps_d)), - A::I64(max_blocks as i64), - A::I64(CAP as i64), - A::Address(h(&ids_o)), - ]); - let mut a_new = KernelArguments::new(vec![ - A::Address(h(&scores_d)), - A::Address(h(&steps_d)), - A::I64(max_blocks as i64), - A::I64(CAP as i64), - A::Address(h(&ids_n)), - ]); - let t0 = std::time::Instant::now(); - select.launch(0, rows as u32, 256, stream, &mut a_old).expect("old topk"); - context.driver.api.synchronize().expect("sync"); - let old_ms = t0.elapsed().as_secs_f64() * 1e3; - let t1 = std::time::Instant::now(); - late.launch(TOPK_FAST, rows as u32, 256, stream, &mut a_new).expect("new topk"); - context.driver.api.synchronize().expect("sync"); - let new_ms = t1.elapsed().as_secs_f64() * 1e3; + let select = + KernelModule::load(include_bytes!("qsa_prompt_select.ptx"), &[c"qsa_topk_ref"]).expect("select module"); + let index = + KernelModule::load(include_bytes!("qsa_prompt_indexer.ptx"), &[c"qsa_score_scan"]).expect("index module"); + let late = KernelModule::load(PTX, ENTRIES).expect("late module"); guard.finish().expect("finish"); - let (o, n) = (download(&ids_o, out_len), download(&ids_n, out_len)); - assert!(o == n, "case {case} (p0 {p0}, rows {rows}, style {style}): ids differ"); - eprintln!( - "QSA-LATE topk case {case} p0={p0} rows={rows} style={style}: ids equal ({} bytes); original {old_ms:.3} ms, fast {new_ms:.3} ms", - out_len - ); + let mut rng = Rng(0x243f6a8885a308d3); + let rig = SelectionRig { context, stream, max_blocks, select, index, late }; + // (first position of the tile, rows, score style) + let cases: [(usize, usize, u8); 9] = [ + (180_000, 256, 0), // continuous + (180_000, 256, 1), // 16 levels, zeros and ties everywhere + (100_003, 64, 2), // all equal + (261_000, 128, 1), + (5_000, 64, 0), + (2_040, 64, 1), // the identity branch (n_kv <= width) for the first rows, selection after + (100, 32, 0), // identity everywhere + (3_999, 40, 2), // n_kv = 4 * n_bid on some rows (empty last block) + (65_536, 100, 1), + ]; + for (case, c) in cases.into_iter().enumerate() { + selection_case(&rig, &mut rng, case, c); + } + }); +} - // the score scan: a clean tile, then a NaN inside a row's blocks, then a NaN beyond its last block - let reach = (p0 + rows) / 4 + 1; - for variant in 0..3 { - let mut bad = scores.clone(); - match variant { - 1 => bad[(rows / 2) * max_blocks + ((p0 + rows / 2 + 1) / 4) / 2] = f32::NAN, - 2 => { - let row = rows - 1; - let n_bid = (p0 + row + 1) / 4; - if n_bid + 1 < max_blocks { - bad[row * max_blocks + n_bid + 1] = f32::INFINITY; - } - } - _ => {} - } - let mut braw = Vec::with_capacity(bad.len() * 4); - bad.iter().for_each(|v| braw.extend_from_slice(&v.to_le_bytes())); - let bad_d = upload(&context, &braw); - let (st_o, st_n) = (upload(&context, &[0u8; 16]), upload(&context, &[0u8; 16])); - let guard = context.enter().expect("enter"); - let mut so = KernelArguments::new(vec![ - A::Address(h(&bad_d)), - A::Address(h(&steps_d)), - A::I32(rows as i32), - A::I64(max_blocks as i64), - A::Address(h(&st_o)), - A::U32(1), - ]); - index.launch(0, (rows * max_blocks).div_ceil(256) as u32, 256, stream, &mut so).expect("old scan"); - let mut sn = KernelArguments::new(vec![ - A::Address(h(&bad_d)), - A::Address(h(&steps_d)), - A::I32(rows as i32), - A::I64(max_blocks as i64), - A::I64(reach as i64), - A::Address(h(&st_n)), - A::U32(1), - ]); - late.launch(SCORE_SCAN_FAST, (rows * reach).div_ceil(256) as u32, 256, stream, &mut sn).expect("new scan"); - context.driver.api.synchronize().expect("sync"); - guard.finish().expect("finish"); - assert_eq!(download(&st_o, 8), download(&st_n, 8), "case {case} variant {variant}: scan flags"); - if variant == 1 { - assert_ne!(download(&st_n, 8)[4..8], [0, 0, 0, 0], "a NaN inside the blocks must raise the flag"); +/// Block scores of `rows` rows from position `p0` in `style` (0 continuous, 1 sixteen tied levels, 2 all equal). +fn selection_scores(rng: &mut Rng, max_blocks: usize, (p0, rows, style): (usize, usize, u8)) -> Vec { + let mut scores = vec![0f32; rows * max_blocks]; + for r in 0..rows { + let n_bid = (p0 + r + 1) / 4; + for b in 0..=n_bid.min(max_blocks - 1) { + let v = match style { + 0 => (rng.next() % 1_000_003) as f32 / 1000.0, + 1 => ((rng.next() % 16) as f32) * 0.5 * ((rng.next() % 3 != 0) as u32 as f32), + _ => 0.0, + }; + scores[r * max_blocks + b] = v; + } + if style == 1 || style == 0 { + // the tail block of the real scorer: +1e9 when it is partly filled + if (p0 + r + 1) % 4 != 0 { + scores[r * max_blocks + n_bid] += 1e9; } } } + scores } +fn selection_case(rig: &SelectionRig<'_>, rng: &mut Rng, case: usize, c @ (p0, rows, _): (usize, usize, u8)) { + let steps = step_bytes(p0, rows); + let scores = selection_scores(rng, rig.max_blocks, c); + let scores_d = upload(rig.context, &f32_raw(&scores)); + let steps_d = upload(rig.context, &steps); + topk_matches_original(rig, (&scores_d, &steps_d), (case, c)); + scan_flags_match_original(rig, (&scores, &steps_d), (case, p0, rows)); +} + +/// `leleka_qsa_topk_fast` writes the same ids as `qsa_topk_ref`. +fn topk_matches_original( + rig: &SelectionRig<'_>, + inputs: (&DeviceBuffer<'_>, &DeviceBuffer<'_>), + (case, (p0, rows, style)): (usize, (usize, usize, u8)), +) { + let (context, stream) = (rig.context, rig.stream); + let out_len = rows * CAP * 4; + let ids_o = upload(context, &vec![0xffu8; out_len]); + let ids_n = upload(context, &vec![0xffu8; out_len]); + let guard = context.enter().expect("enter"); + let mut a_old = topk_args(rig.max_blocks, inputs, &ids_o); + let mut a_new = topk_args(rig.max_blocks, inputs, &ids_n); + let t0 = std::time::Instant::now(); + rig.select.launch(0, rows as u32, 256, stream, &mut a_old).expect("old topk"); + context.driver.api.synchronize().expect("sync"); + let old_ms = t0.elapsed().as_secs_f64() * 1e3; + let t1 = std::time::Instant::now(); + rig.late.launch(TOPK_FAST, rows as u32, 256, stream, &mut a_new).expect("new topk"); + context.driver.api.synchronize().expect("sync"); + let new_ms = t1.elapsed().as_secs_f64() * 1e3; + guard.finish().expect("finish"); + let (o, n) = (download(&ids_o, out_len), download(&ids_n, out_len)); + assert!(o == n, "case {case} (p0 {p0}, rows {rows}, style {style}): ids differ"); + eprintln!( + "QSA-LATE topk case {case} p0={p0} rows={rows} style={style}: ids equal ({} bytes); original {old_ms:.3} ms, fast {new_ms:.3} ms", + out_len + ); +} + +/// The score scan: a clean tile, then a NaN inside a row's blocks, then a NaN beyond its last block. +fn scan_flags_match_original( + rig: &SelectionRig<'_>, + (scores, steps_d): (&[f32], &DeviceBuffer<'_>), + (case, p0, rows): (usize, usize, usize), +) { + let (context, stream, max_blocks) = (rig.context, rig.stream, rig.max_blocks); + let reach = (p0 + rows) / 4 + 1; + for variant in 0..3 { + let mut bad = scores.to_vec(); + match variant { + 1 => bad[(rows / 2) * max_blocks + ((p0 + rows / 2 + 1) / 4) / 2] = f32::NAN, + 2 => { + let row = rows - 1; + let n_bid = (p0 + row + 1) / 4; + if n_bid + 1 < max_blocks { + bad[row * max_blocks + n_bid + 1] = f32::INFINITY; + } + } + _ => {} + } + let bad_d = upload(context, &f32_raw(&bad)); + let (st_o, st_n) = (upload(context, &[0u8; 16]), upload(context, &[0u8; 16])); + let guard = context.enter().expect("enter"); + let mut so = KernelArguments::new(vec![ + A::Address(handle(&bad_d)), + A::Address(handle(steps_d)), + A::I32(rows as i32), + A::I64(max_blocks as i64), + A::Address(handle(&st_o)), + A::U32(1), + ]); + rig.index.launch(0, (rows * max_blocks).div_ceil(256) as u32, 256, stream, &mut so).expect("old scan"); + let mut sn = KernelArguments::new(vec![ + A::Address(handle(&bad_d)), + A::Address(handle(steps_d)), + A::I32(rows as i32), + A::I64(max_blocks as i64), + A::I64(reach as i64), + A::Address(handle(&st_n)), + A::U32(1), + ]); + let grid = (rows * reach).div_ceil(256) as u32; + rig.late.launch(SCORE_SCAN_FAST, grid, 256, stream, &mut sn).expect("new scan"); + context.driver.api.synchronize().expect("sync"); + guard.finish().expect("finish"); + assert_eq!(download(&st_o, 8), download(&st_n, 8), "case {case} variant {variant}: scan flags"); + if variant == 1 { + assert_ne!(download(&st_n, 8)[4..8], [0, 0, 0, 0], "a NaN inside the blocks must raise the flag"); + } + } +} + +// ---------------------------------------------------------------------------------------------- top-k variants + +/// The Original's top-k, the late variants and the decode cluster kernel. +struct BenchRig<'a> { + context: &'a Context<'a>, + stream: usize, + max_blocks: usize, + select: KernelModule, + late: KernelModule, + cluster: KernelModule, +} + +type Run<'a> = Box; + /// Row 2.5: every top-k variant (`leleka_qsa_topk_fast`, `_wide`, `_sample` + `_wide_failed`, and the decode cluster kernel) writes the /// same ids as the Original's `qsa_topk_ref` (the whole output, tail included), on prompt-shaped tiles (256 rows) and decode-shaped /// calls (1..5 rows) at positions up to 262,000, with continuous, heavy-tailed, tied and all-equal scores; and the per-launch time of @@ -181,218 +257,205 @@ fn selection_kernels_equal_the_originals_at_long_positions() { #[test] #[ignore = "Root-only: needs a CUDA device"] fn topk_variants_equal_the_original_and_are_timed() { - assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes")); - let driver = Driver::load().expect("driver"); - let device = driver.device(0).expect("device"); - let context = device.create_context(6usize << 30).expect("context"); - let workspace = context.native_batch_workspace().expect("workspace"); - let stream = workspace.blas().expect("blas").stream(); - let max_blocks = crate::serving_context::geometry().max_blocks(); - let guard = context.enter().expect("enter"); - let select = - KernelModule::load(include_bytes!("qsa_prompt_select.ptx"), &[c"qsa_topk_ref"]).expect("select module"); - let late = KernelModule::load(PTX, ENTRIES).expect("late module"); - let cluster = KernelModule::load(crate::qsa_cluster::PTX, crate::qsa_cluster::ENTRIES).expect("cluster module"); - guard.finish().expect("finish"); - let mut rng = Rng(0x9e3779b97f4a7c15); - // (first position, rows, style, label): style 0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy tail (relu-sum like) - let cases: [(usize, usize, u8, &str); 24] = [ - (100, 4, 3, "decode"), - (2_040, 4, 3, "decode"), - (2_049, 5, 1, "decode"), - (3_000, 4, 3, "decode"), - (9_999, 3, 2, "decode"), - (2_040, 256, 3, "prompt"), - (8_000, 256, 3, "prompt"), - (24_000, 256, 3, "prompt"), - (48_000, 256, 3, "prompt"), - (70_000, 256, 3, "prompt"), - (100_003, 256, 0, "prompt"), - (100_003, 256, 3, "prompt"), - (180_000, 256, 0, "prompt"), - (180_000, 256, 3, "prompt"), - (180_000, 256, 1, "prompt"), - (245_000, 256, 3, "prompt"), - (245_000, 256, 2, "prompt"), - (131_072, 1, 3, "decode"), - (131_072, 4, 3, "decode"), - (245_000, 1, 3, "decode"), - (245_000, 4, 3, "decode"), - (245_000, 5, 0, "decode"), - (245_000, 4, 1, "decode"), - (261_500, 4, 2, "decode"), - ]; - let reps = 20; - for (case, (p0, rows, style, label)) in cases.into_iter().enumerate() { - let mut steps = Vec::new(); - for r in 0..rows { - let pos = p0 + r; - for x in [pos, pos + 1, (pos + 1) / 4, (pos + 1).min(CAP)] { - steps.extend_from_slice(&(x as i32).to_le_bytes()); - } - } - let mut scores = vec![0f32; rows * max_blocks]; - for r in 0..rows { - let n_bid = (p0 + r + 1) / 4; - for b in 0..=n_bid.min(max_blocks - 1) { - let u = (rng.next() % 1_000_003) as f32 / 1_000_003.0; - scores[r * max_blocks + b] = match style { - 0 => u * 1000.0, - 1 => ((rng.next() % 16) as f32) * 0.5 * ((rng.next() % 3 != 0) as u32 as f32), - 2 => 0.0, - _ => { - (-(u.max(1e-6)).ln()) * 40.0 * ((rng.next() % 4 != 0) as u32 as f32) + ((b % 977) as f32) * 0.01 - } - }; - } - if style != 2 && (p0 + r + 1) % 4 != 0 { - scores[r * max_blocks + n_bid] += 1e9; - } - } - let mut raw = Vec::with_capacity(scores.len() * 4); - scores.iter().for_each(|v| raw.extend_from_slice(&v.to_le_bytes())); - let scores_d = upload(&context, &raw); - let steps_d = upload(&context, &steps); - let out_len = rows * CAP * 4; - let h = |b: &DeviceBuffer<'_>| b.handle.expect("handle"); - let args_for = |ids: &DeviceBuffer<'_>| { - KernelArguments::new(vec![ - A::Address(h(&scores_d)), - A::Address(h(&steps_d)), - A::I64(max_blocks as i64), - A::I64(CAP as i64), - A::Address(h(ids)), - ]) - }; - let n = rows as u32; - // one runner per variant: (name, closure launching it once) - type Run<'a> = Box; - let smem = crate::qsa_cluster::dynamic_smem(max_blocks); - let variants: Vec<(&str, Run<'_>)> = vec![ - ("ref", Box::new(|a| select.launch(0, n, 256, stream, a).expect("ref"))), - ("fast", Box::new(|a| late.launch(TOPK_FAST, n, 256, stream, a).expect("fast"))), - ("wide", Box::new(|a| late.launch(TOPK_WIDE, n, 1024, stream, a).expect("wide"))), - ( - "sample+failed", - Box::new(|a| { - late.launch(TOPK_SAMPLE, n, 1024, stream, a).expect("sample"); - late.launch(TOPK_WIDE_FAILED, n, 1024, stream, a).expect("failed"); - }), - ), - ( - "cluster", - Box::new(|a| { - cluster - .launch_cluster(crate::qsa_cluster::TOPK_CLUSTER, [8, n], 1024, 8, smem, stream, a) - .expect("cluster") - }), - ), + with_gpu(|context, stream, max_blocks| { + let guard = context.enter().expect("enter"); + let select = + KernelModule::load(include_bytes!("qsa_prompt_select.ptx"), &[c"qsa_topk_ref"]).expect("select module"); + let late = KernelModule::load(PTX, ENTRIES).expect("late module"); + let cluster = KernelModule::load(crate::qsa_cluster::PTX, crate::qsa_cluster::ENTRIES).expect("cluster module"); + guard.finish().expect("finish"); + let mut rng = Rng(0x9e3779b97f4a7c15); + let rig = BenchRig { context, stream, max_blocks, select, late, cluster }; + // (first position, rows, style, label): style 0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy tail + // (relu-sum like) + let cases: [(usize, usize, u8, &str); 24] = [ + (100, 4, 3, "decode"), + (2_040, 4, 3, "decode"), + (2_049, 5, 1, "decode"), + (3_000, 4, 3, "decode"), + (9_999, 3, 2, "decode"), + (2_040, 256, 3, "prompt"), + (8_000, 256, 3, "prompt"), + (24_000, 256, 3, "prompt"), + (48_000, 256, 3, "prompt"), + (70_000, 256, 3, "prompt"), + (100_003, 256, 0, "prompt"), + (100_003, 256, 3, "prompt"), + (180_000, 256, 0, "prompt"), + (180_000, 256, 3, "prompt"), + (180_000, 256, 1, "prompt"), + (245_000, 256, 3, "prompt"), + (245_000, 256, 2, "prompt"), + (131_072, 1, 3, "decode"), + (131_072, 4, 3, "decode"), + (245_000, 1, 3, "decode"), + (245_000, 4, 3, "decode"), + (245_000, 5, 0, "decode"), + (245_000, 4, 1, "decode"), + (261_500, 4, 2, "decode"), ]; - let mut reference: Option> = None; - let mut line = format!("QSA-TOPK-BENCH case {case} {label} p0={p0} rows={rows} style={style}:"); - for (name, run) in &variants { - if *name == "cluster" && rows > 16 { - continue; // the decode kernel (the upstream dispatch uses it for at most 16 queries) - } - let ids = upload(&context, &vec![0xffu8; out_len]); - let mut a = args_for(&ids); - let guard = context.enter().expect("enter"); - // the sample kernel flags its failures in a module global that persists: clear by running sample first inside run - run(&mut a); - context.driver.api.synchronize().expect("sync"); - let t0 = std::time::Instant::now(); - for _ in 0..reps { - run(&mut a); - } - context.driver.api.synchronize().expect("sync"); - let us = t0.elapsed().as_secs_f64() * 1e6 / reps as f64; - guard.finish().expect("finish"); - let got = download(&ids, out_len); - match &reference { - None => reference = Some(got), - Some(r) => assert!( - *r == got, - "case {case} (p0 {p0}, rows {rows}, style {style}): {name} ids differ from the original" - ), - } - line.push_str(&format!(" {name} {us:.1} us;")); + for (case, c) in cases.into_iter().enumerate() { + bench_case(&rig, &mut rng, case, c); } - eprintln!("{line} ids equal"); - } + }); } +/// Block scores of `rows` rows from position `p0` in `style` (0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy +/// tail). +fn bench_scores(rng: &mut Rng, max_blocks: usize, (p0, rows, style): (usize, usize, u8)) -> Vec { + let mut scores = vec![0f32; rows * max_blocks]; + for r in 0..rows { + let n_bid = (p0 + r + 1) / 4; + for b in 0..=n_bid.min(max_blocks - 1) { + let u = (rng.next() % 1_000_003) as f32 / 1_000_003.0; + scores[r * max_blocks + b] = match style { + 0 => u * 1000.0, + 1 => ((rng.next() % 16) as f32) * 0.5 * ((rng.next() % 3 != 0) as u32 as f32), + 2 => 0.0, + _ => (-(u.max(1e-6)).ln()) * 40.0 * ((rng.next() % 4 != 0) as u32 as f32) + ((b % 977) as f32) * 0.01, + }; + } + if style != 2 && (p0 + r + 1) % 4 != 0 { + scores[r * max_blocks + n_bid] += 1e9; + } + } + scores +} + +/// One runner per variant: (name, closure launching it once). +fn topk_variants<'a>(rig: &'a BenchRig<'a>, n: u32) -> Vec<(&'static str, Run<'a>)> { + let (select, late, cluster, stream) = (&rig.select, &rig.late, &rig.cluster, rig.stream); + let smem = crate::qsa_cluster::dynamic_smem(rig.max_blocks); + vec![ + ("ref", Box::new(move |a| select.launch(0, n, 256, stream, a).expect("ref"))), + ("fast", Box::new(move |a| late.launch(TOPK_FAST, n, 256, stream, a).expect("fast"))), + ("wide", Box::new(move |a| late.launch(TOPK_WIDE, n, 1024, stream, a).expect("wide"))), + ( + "sample+failed", + Box::new(move |a| { + late.launch(TOPK_SAMPLE, n, 1024, stream, a).expect("sample"); + late.launch(TOPK_WIDE_FAILED, n, 1024, stream, a).expect("failed"); + }), + ), + ( + "cluster", + Box::new(move |a| { + cluster + .launch_cluster(crate::qsa_cluster::TOPK_CLUSTER, [8, n], 1024, 8, smem, stream, a) + .expect("cluster") + }), + ), + ] +} + +fn bench_case(rig: &BenchRig<'_>, rng: &mut Rng, case: usize, (p0, rows, style, label): (usize, usize, u8, &str)) { + let context = rig.context; + let steps = step_bytes(p0, rows); + let scores = bench_scores(rng, rig.max_blocks, (p0, rows, style)); + let scores_d = upload(context, &f32_raw(&scores)); + let steps_d = upload(context, &steps); + let out_len = rows * CAP * 4; + let reps = 20; + let variants = topk_variants(rig, rows as u32); + let mut reference: Option> = None; + let mut line = format!("QSA-TOPK-BENCH case {case} {label} p0={p0} rows={rows} style={style}:"); + for (name, run) in &variants { + if *name == "cluster" && rows > 16 { + continue; // the decode kernel (the upstream dispatch uses it for at most 16 queries) + } + let ids = upload(context, &vec![0xffu8; out_len]); + let mut a = topk_args(rig.max_blocks, (&scores_d, &steps_d), &ids); + let guard = context.enter().expect("enter"); + // the sample kernel flags its failures in a module global that persists: clear by running sample first inside run + run(&mut a); + context.driver.api.synchronize().expect("sync"); + let t0 = std::time::Instant::now(); + for _ in 0..reps { + run(&mut a); + } + context.driver.api.synchronize().expect("sync"); + let us = t0.elapsed().as_secs_f64() * 1e6 / reps as f64; + guard.finish().expect("finish"); + let got = download(&ids, out_len); + match &reference { + None => reference = Some(got), + Some(r) => assert!( + *r == got, + "case {case} (p0 {p0}, rows {rows}, style {style}): {name} ids differ from the original" + ), + } + line.push_str(&format!(" {name} {us:.1} us;")); + } + eprintln!("{line} ids equal"); +} + +// ---------------------------------------------------------------------------------------------- decode scores + /// Timing only (row 2.5 follow-up): the decode window's block scores (`qsa_decode_scores`, the Original's multi-query kernel, 256 CTAs) next to its /// top-k at the same shape, to see what the select costs per QSA layer at depth. Prints `QSA-DECODE-SCORES`. #[test] #[ignore = "Root-only: needs a CUDA device"] fn decode_scores_are_timed_next_to_the_topk() { - assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes")); - let driver = Driver::load().expect("driver"); - let device = driver.device(0).expect("device"); - let context = device.create_context(6usize << 30).expect("context"); - let workspace = context.native_batch_workspace().expect("workspace"); - let stream = workspace.blas().expect("blas").stream(); - let max_blocks = crate::serving_context::geometry().max_blocks(); - let guard = context.enter().expect("enter"); - let select = KernelModule::load(include_bytes!("qsa_prompt_select.ptx"), &[c"qsa_decode_scores", c"qsa_topk_ref"]) - .expect("select module"); - guard.finish().expect("finish"); - let mut rng = Rng(0x1234_5678_9abc_def1); - for (pos, nq) in [(131_072usize, 4usize), (245_000, 1), (245_000, 4), (245_000, 5)] { - let n_bid_max = (pos + nq) / 4; - let pooled: Vec = - (0..(max_blocks + 1) * 128).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect(); - let dead: Vec = (0..128).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect(); - let qidx: Vec = (0..nq * 4 * 128).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect(); - let mut steps = Vec::new(); - for r in 0..nq { - let p = pos + r; - for x in [p, p + 1, (p + 1) / 4, (p + 1).min(CAP)] { - steps.extend_from_slice(&(x as i32).to_le_bytes()); - } - } - let f = |v: &[f32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::>(); - let (pooled_d, dead_d, qidx_d, steps_d) = ( - upload(&context, &f(&pooled)), - upload(&context, &f(&dead)), - upload(&context, &f(&qidx)), - upload(&context, &steps), - ); - let scores_d = upload(&context, &vec![0u8; nq * max_blocks * 4]); - let ids_d = upload(&context, &vec![0xffu8; nq * CAP * 4]); - let h = |b: &DeviceBuffer<'_>| b.handle.expect("handle"); + with_gpu(|context, stream, max_blocks| { let guard = context.enter().expect("enter"); - let time = |run: &mut dyn FnMut()| -> f64 { - run(); - context.driver.api.synchronize().expect("sync"); - let t0 = std::time::Instant::now(); - for _ in 0..20 { - run(); - } - context.driver.api.synchronize().expect("sync"); - t0.elapsed().as_secs_f64() * 1e6 / 20.0 - }; - let mut sa = KernelArguments::new(vec![ - A::Address(h(&pooled_d)), - A::Address(h(&dead_d)), - A::Address(h(&qidx_d)), - A::Address(h(&steps_d)), - A::I32(nq as i32), - A::I64(max_blocks as i64), - A::Address(h(&scores_d)), - ]); - let scores_us = time(&mut || select.launch(0, 256, 256, stream, &mut sa).expect("scores")); - let mut ta = KernelArguments::new(vec![ - A::Address(h(&scores_d)), - A::Address(h(&steps_d)), - A::I64(max_blocks as i64), - A::I64(CAP as i64), - A::Address(h(&ids_d)), - ]); - let topk_us = time(&mut || select.launch(1, nq as u32, 256, stream, &mut ta).expect("topk")); + let select = + KernelModule::load(include_bytes!("qsa_prompt_select.ptx"), &[c"qsa_decode_scores", c"qsa_topk_ref"]) + .expect("select module"); guard.finish().expect("finish"); - eprintln!( - "QSA-DECODE-SCORES pos={pos} nq={nq} n_bid={n_bid_max}: qsa_decode_scores {scores_us:.1} us, qsa_topk_ref {topk_us:.1} us (per layer, warm)" - ); - } + let mut rng = Rng(0x1234_5678_9abc_def1); + for (pos, nq) in [(131_072usize, 4usize), (245_000, 1), (245_000, 4), (245_000, 5)] { + time_scores_and_topk(context, (&select, stream, max_blocks), &mut rng, (pos, nq)); + } + }); +} + +/// Random pooled/dead/query vectors, the steps, and the scores/ids outputs of one `(pos, nq)` shape. +fn time_scores_and_topk( + context: &Context<'_>, + (select, stream, max_blocks): (&KernelModule, usize, usize), + rng: &mut Rng, + (pos, nq): (usize, usize), +) { + let n_bid_max = (pos + nq) / 4; + let mut random = + |n: usize| -> Vec { (0..n).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect() }; + let pooled = random((max_blocks + 1) * 128); + let dead = random(128); + let qidx = random(nq * 4 * 128); + let steps = step_bytes(pos, nq); + let (pooled_d, dead_d, qidx_d, steps_d) = ( + upload(context, &f32_raw(&pooled)), + upload(context, &f32_raw(&dead)), + upload(context, &f32_raw(&qidx)), + upload(context, &steps), + ); + let scores_d = upload(context, &vec![0u8; nq * max_blocks * 4]); + let ids_d = upload(context, &vec![0xffu8; nq * CAP * 4]); + let guard = context.enter().expect("enter"); + let time = |run: &mut dyn FnMut()| -> f64 { + run(); + context.driver.api.synchronize().expect("sync"); + let t0 = std::time::Instant::now(); + for _ in 0..20 { + run(); + } + context.driver.api.synchronize().expect("sync"); + t0.elapsed().as_secs_f64() * 1e6 / 20.0 + }; + let mut sa = KernelArguments::new(vec![ + A::Address(handle(&pooled_d)), + A::Address(handle(&dead_d)), + A::Address(handle(&qidx_d)), + A::Address(handle(&steps_d)), + A::I32(nq as i32), + A::I64(max_blocks as i64), + A::Address(handle(&scores_d)), + ]); + let scores_us = time(&mut || select.launch(0, 256, 256, stream, &mut sa).expect("scores")); + let mut ta = topk_args(max_blocks, (&scores_d, &steps_d), &ids_d); + let topk_us = time(&mut || select.launch(1, nq as u32, 256, stream, &mut ta).expect("topk")); + guard.finish().expect("finish"); + eprintln!( + "QSA-DECODE-SCORES pos={pos} nq={nq} n_bid={n_bid_max}: qsa_decode_scores {scores_us:.1} us, qsa_topk_ref {topk_us:.1} us (per layer, warm)" + ); } diff --git a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs index 53f98298..7c54e849 100644 --- a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs +++ b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs @@ -12,7 +12,34 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { inputs: &crate::qsa_prompt_index::OriginalQsaResidentScalarSelection<'_, '_, '_, 'ctx>, ) -> Result { let t = 1; - if inputs.first_position() != prior.next_position() { + let end = self.admit_append(workspace, stage, prior, (inputs.first_position(), t))?; + let (kh, vh) = inputs.with_completed_kv(|k, v| { + checked(self.owner.context, k, 2048)?; + checked(self.owner.context, v, 2048)?; + Ok((k.handle.ok_or(Error::ContextPoisoned)?, v.handle.ok_or(Error::ContextPoisoned)?)) + })?; + self.reject_kv_spans(workspace, stage, (kh, vh), t)?; + let table = self.check_prior_and_table(stage, prior)?; + // Whole original mapped storage/staging has fixed addresses. Only new + // cells are written; preceding prefix bytes remain actual owners. + let sa = Self::zero_stage_status(stage, self.owner.context)?; + let rp = self.owner.pools.addresses()?; + self.reset_resolver_once(workspace)?; + let hp = self.owner.host_addresses()?; + let kv = [kh.qwen_address(), vh.qwen_address()]; + let plan = AppendPlan { kv, sa, rp, sp: [0, 0, hp[2], hp[3]], hp, prior_end: prior.end, end, t }; + self.run_append(workspace, stage, &plan)?; + Ok(self.finish_append(&plan, table, None)) + } + /// The prior prefix is the one the new cells extend, and `t` more cells fit the serving context. Returns the new end. + pub(super) fn admit_append( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + stage: &mut OriginalQsaResidentTransport<'ctx>, + prior: &OriginalQsaMappedPrefix, + (first_position, t): (usize, usize), + ) -> Result { + if first_position != prior.next_position() { return Err(Error::InvalidQwenShape); } self.validate_prefix(prior)?; @@ -23,19 +50,29 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { { return Err(Error::InvalidQwenShape); } - let end = prior.end + t; - let (kh, vh) = inputs.with_completed_kv(|k, v| { - checked(self.owner.context, k, 2048)?; - checked(self.owner.context, v, 2048)?; - Ok((k.handle.ok_or(Error::ContextPoisoned)?, v.handle.ok_or(Error::ContextPoisoned)?)) - })?; - let (k, v) = (kh.qwen_address(), vh.qwen_address()); + Ok(prior.end + t) + } + /// The new K and V cells overlap neither the journal, the stage nor the workspace. + pub(super) fn reject_kv_spans( + &self, + workspace: &NativeBatchWorkspace<'ctx>, + stage: &OriginalQsaResidentTransport<'ctx>, + (kh, vh): (crate::ffi::BufferHandle, crate::ffi::BufferHandle), + t: usize, + ) -> Result<()> { self.owner.reject_original_span(kh, t * 512 * 4)?; self.owner.reject_original_span(vh, t * 512 * 4)?; stage.reject_span(kh, t * 512 * 4)?; stage.reject_span(vh, t * 512 * 4)?; workspace.reject_alias(kh, t * 512 * 4)?; - workspace.reject_alias(vh, t * 512 * 4)?; + workspace.reject_alias(vh, t * 512 * 4) + } + /// The prior prefix ends where the journal does, and the stage table is the one the journal already used. + pub(super) fn check_prior_and_table( + &self, + stage: &OriginalQsaResidentTransport<'ctx>, + prior: &OriginalQsaMappedPrefix, + ) -> Result { if prior.end != self.end { return Err(Error::InvalidQwenShape); } @@ -43,64 +80,87 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { if self.stage_table.is_some_and(|old| old != table) { return Err(Error::InvalidQwenShape); } - // Whole original mapped storage/staging has fixed addresses. Only new - // cells are written; preceding prefix bytes remain actual owners. + Ok(table) + } + /// Zeroes the stage's status word and returns its address. + pub(super) fn zero_stage_status( + stage: &mut OriginalQsaResidentTransport<'ctx>, + context: &Context<'_>, + ) -> Result { let status = stage.status()?; status.copy_from(&[0; 4])?; - let sa = checked(self.owner.context, status, 4)?; - let rp = self.owner.pools.addresses()?; - let sp = [0u64; 4]; + checked(context, status, 4) + } + /// Resets the streamed-KV resolver the first time only. + pub(super) fn reset_resolver_once(&mut self, workspace: &mut NativeBatchWorkspace<'ctx>) -> Result<()> { if !self.resolver_ready { self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(workspace, self.owner.pools.table()?)?; self.resolver_ready = true; } - let hp = self.owner.host_addresses()?; - - let guard = Arguments::new(vec![Arg::U64(k), Arg::U64(v), Arg::I32((t * 512) as i32), Arg::U64(sa)])?; - stage.run(workspace, 0, [(t * 512).div_ceil(256) as u32, 1, 1], 256, guard)?; + Ok(()) + } + /// The guard scan, the quantize/append kernel and the scale kernel, each followed by its status check. + pub(super) fn run_append( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + stage: &mut OriginalQsaResidentTransport<'ctx>, + p: &AppendPlan, + ) -> Result<()> { + let [k, v] = p.kv; + let guard = Arguments::new(vec![Arg::U64(k), Arg::U64(v), Arg::I32((p.t * 512) as i32), Arg::U64(p.sa)])?; + stage.run(workspace, 0, [(p.t * 512).div_ceil(256) as u32, 1, 1], 256, guard)?; if stage.flags()? != 0 { return Err(Error::InvalidQ8Activation); } - let args = Arguments::new(vec![ - Arg::U64(k), - Arg::U64(v), - Arg::I64(prior.end as i64), - Arg::U64(self.owner.pools.table()?), - Arg::I64(4), - Arg::U64(rp[0]), - Arg::U64(rp[1]), - Arg::U64(rp[2]), - Arg::U64(rp[3]), - Arg::U64(sp[0]), - Arg::U64(sp[1]), - Arg::U64(hp[2]), - Arg::U64(hp[3]), - Arg::U64(hp[0]), - Arg::U64(hp[1]), - Arg::U64(hp[2]), - Arg::U64(hp[3]), - ])?; + let mut args = vec![Arg::U64(k), Arg::U64(v), Arg::I64(p.prior_end as i64)]; + args.extend([Arg::U64(self.owner.pools.table()?), Arg::I64(4)]); + args.extend(p.rp.map(Arg::U64)); + args.extend(p.sp.map(Arg::U64)); + args.extend(p.hp.map(Arg::U64)); + let args = Arguments::new(args)?; let scales = Arguments::new(vec![ - Arg::U64(hp[2]), - Arg::U64(hp[3]), - Arg::I32(prior.end as i32), - Arg::I32(end as i32), - Arg::U64(sa), + Arg::U64(p.sp[2]), + Arg::U64(p.sp[3]), + Arg::I32(p.prior_end as i32), + Arg::I32(p.end as i32), + Arg::U64(p.sa), ])?; self.owner.current = None; self.owner.mapped_current = None; - stage.run(workspace, 1, [t as u32, 2, 8], 64, args)?; + stage.run(workspace, 1, [p.t as u32, 2, 8], 64, args)?; stage.run(workspace, 2, [1, 1, 1], 256, scales)?; if stage.flags()? != 0 { return Err(Error::InvalidQ8Activation); } - self.end = end; - self.coverage.end.set(end); - self.stage_table = Some(table); - self.stage_addresses = None; - Ok(OriginalQsaMappedAppend { first: prior.end, rows: t, final_prefix: self.prefix() }) + Ok(()) } + /// The journal now ends at the appended cells; `stage_addresses` are the stage spans the append used, if any. + pub(super) fn finish_append( + &mut self, + p: &AppendPlan, + table: u64, + stage_addresses: Option<[u64; 4]>, + ) -> OriginalQsaMappedAppend { + self.end = p.end; + self.coverage.end.set(p.end); + self.stage_table = Some(table); + self.stage_addresses = stage_addresses; + OriginalQsaMappedAppend { first: p.prior_end, rows: p.t, final_prefix: self.prefix() } + } +} + +/// What one append reads and writes: the K and V cells, the status word, the resident, stage (kernel slots 9..13) and +/// host pool addresses, and the cell range `prior_end..end` of `t` new cells. +pub(super) struct AppendPlan { + pub(super) kv: [u64; 2], + pub(super) sa: u64, + pub(super) rp: [u64; 4], + pub(super) sp: [u64; 4], + pub(super) hp: [u64; 4], + pub(super) prior_end: usize, + pub(super) end: usize, + pub(super) t: usize, } /// Prefix-cache transfer of the host K/V image (`docs/prefix-cache.md`). The host image is the authority for every @@ -139,6 +199,44 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { /// bookkeeping). Any written cell may have a stale copy in the VRAM resident window, so the resolver is reset /// (as `QsaPromptKv::restore` does); with no span nothing is written and nothing is reset. The epoch does not /// change: prefixes minted before are fenced by the new coverage, exactly as after `rollback`. + /// Every span is whole pages inside the serving context and below the new end. + fn check_import_spans(spans: &[(usize, &[u8])], end: usize) -> Result<()> { + let page_limit = crate::serving_context::geometry().pages(); + for (first, bytes) in spans { + if bytes.is_empty() + || bytes.len() % Self::HOST_PAGE_BYTES != 0 + || first.checked_add(bytes.len() / Self::HOST_PAGE_BYTES).is_none_or(|e| e > page_limit) + || (first + bytes.len() / Self::HOST_PAGE_BYTES) * 4 > end.div_ceil(4) * 4 + { + return Err(Error::InvalidQwenShape); + } + } + Ok(()) + } + /// Writes the spans into the host image and resets the resolver; any failure marks the journal failed. + fn write_import_spans(&mut self, w: &mut NativeBatchWorkspace<'ctx>, spans: &[(usize, &[u8])]) -> Result<()> { + let offsets = super::super::offsets()?; + let m = self.owner.mapped.as_mut().ok_or(Error::ContextPoisoned)?; + for (first, bytes) in spans { + let pages = bytes.len() / Self::HOST_PAGE_BYTES; + let mut at = 0; + for (i, &page) in super::super::PAGE.iter().enumerate() { + let n = pages * page; + m.write(offsets[i] + first * page, &bytes[at..at + n]).map_err(|e| { + self.failed = true; + e + })?; + at += n; + } + } + let table = self.owner.pools.table()?; + self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(w, table).map_err(|e| { + self.failed = true; + e + })?; + self.resolver_ready = true; + Ok(()) + } pub fn import_pages( &mut self, w: &mut NativeBatchWorkspace<'ctx>, @@ -150,42 +248,14 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { if end > crate::serving_context::geometry().cells() { return Err(Error::InvalidQwenShape); } - let page_limit = crate::serving_context::geometry().pages(); - for (first, bytes) in spans { - if bytes.is_empty() - || bytes.len() % Self::HOST_PAGE_BYTES != 0 - || first.checked_add(bytes.len() / Self::HOST_PAGE_BYTES).is_none_or(|e| e > page_limit) - || (first + bytes.len() / Self::HOST_PAGE_BYTES) * 4 > end.div_ceil(4) * 4 - { - return Err(Error::InvalidQwenShape); - } - } + Self::check_import_spans(spans, end)?; // no CPU host write may race a stream use of the old cells self.owner.context.synchronize().map_err(|e| { self.failed = true; e })?; if !spans.is_empty() { - let offsets = super::super::offsets()?; - let m = self.owner.mapped.as_mut().ok_or(Error::ContextPoisoned)?; - for (first, bytes) in spans { - let pages = bytes.len() / Self::HOST_PAGE_BYTES; - let mut at = 0; - for (i, &page) in super::super::PAGE.iter().enumerate() { - let n = pages * page; - m.write(offsets[i] + first * page, &bytes[at..at + n]).map_err(|e| { - self.failed = true; - e - })?; - at += n; - } - } - let table = self.owner.pools.table()?; - self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(w, table).map_err(|e| { - self.failed = true; - e - })?; - self.resolver_ready = true; + self.write_import_spans(w, spans)?; } self.owner.current = None; self.owner.mapped_current = None; diff --git a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs index baf3b00e..c069395a 100644 --- a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs +++ b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl OriginalQsaMappedJournal (2), impl OriginalQsaMappedJournal. #[allow(unused_imports)] +use super::super::impl_originalqsamappedjournal::AppendPlan; use super::*; impl<'ctx> OriginalQsaMappedJournal<'ctx> { @@ -12,105 +13,48 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { inputs: &crate::qsa_prompt_index::OriginalQsaResidentSelection<'_, '_, '_, '_, '_, 'ctx>, ) -> Result { let t = inputs.rows(); - if inputs.first_position() != prior.next_position() { - return Err(Error::InvalidQwenShape); - } - self.validate_prefix(prior)?; - stage.validate(self.owner.context)?; - workspace.validate_context(self.owner.context)?; - if !(1..=8192).contains(&t) - || prior.end.checked_add(t).is_none_or(|n| n > crate::serving_context::geometry().cells()) - { - return Err(Error::InvalidQwenShape); - } - let end = prior.end + t; + let end = self.admit_append(workspace, stage, prior, (inputs.first_position(), t))?; let (kh, vh) = inputs.kv_spans(self.owner.context)?; - let (k, v) = (kh.qwen_address(), vh.qwen_address()); - self.owner.reject_original_span(kh, t * 512 * 4)?; - self.owner.reject_original_span(vh, t * 512 * 4)?; - stage.reject_span(kh, t * 512 * 4)?; - stage.reject_span(vh, t * 512 * 4)?; - workspace.reject_alias(kh, t * 512 * 4)?; - workspace.reject_alias(vh, t * 512 * 4)?; - if prior.end != self.end { - return Err(Error::InvalidQwenShape); - } - let table = stage.table()?; - if self.stage_table.is_some_and(|old| old != table) { - return Err(Error::InvalidQwenShape); - } + self.reject_kv_spans(workspace, stage, (kh, vh), t)?; + let table = self.check_prior_and_table(stage, prior)?; // Whole original mapped storage/staging has fixed addresses. Only new // cells are written; preceding prefix bytes remain actual owners. - let status = stage.status()?; - status.copy_from(&[0; 4])?; - let sa = checked(self.owner.context, status, 4)?; + let sa = Self::zero_stage_status(stage, self.owner.context)?; let rp = self.owner.pools.addresses()?; let sp = inputs.kv_stage_spans(self.owner.context)?.map(|h| h.qwen_address()); - if !self.resolver_ready { - self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(workspace, self.owner.pools.table()?)?; - self.resolver_ready = true; - } + self.reset_resolver_once(workspace)?; let hp = self.owner.host_addresses()?; - // Original kv_stage_from_host: shared arena stage belongs to another - // layer/chunk until the authoritative real mapped prefix is copied. let stage_spans = inputs.kv_stage_spans(self.owner.context)?; + self.stage_prefix_from_host(workspace, stage, (hp, stage_spans), prior.end)?; + let timed = crate::command_profile::enabled(); + let started = std::time::Instant::now(); + let kv = [kh.qwen_address(), vh.qwen_address()]; + let plan = AppendPlan { kv, sa, rp, sp, hp, prior_end: prior.end, end, t }; + self.run_append(workspace, stage, &plan)?; + if timed { + crate::command_profile::add("qsa-kv", 2, "append kernels (quantize, write, scales)", started.elapsed()); + } + Ok(self.finish_append(&plan, table, Some(sp))) + } + /// Original kv_stage_from_host: shared arena stage belongs to another layer/chunk until the authoritative real + /// mapped prefix is copied. + fn stage_prefix_from_host( + &self, + workspace: &mut NativeBatchWorkspace<'ctx>, + stage: &mut OriginalQsaResidentTransport<'ctx>, + (hp, stage_spans): ([u64; 4], [crate::ffi::BufferHandle; 4]), + prior_end: usize, + ) -> Result<()> { for (i, h) in stage_spans.iter().enumerate() { self.owner.reject_original_span(*h, stage_runs()?[i])?; } let timed = crate::command_profile::enabled(); let started = std::time::Instant::now(); - stage.copy_prefix(workspace, hp, stage_spans, prior.end.div_ceil(4))?; + stage.copy_prefix(workspace, hp, stage_spans, prior_end.div_ceil(4))?; if timed { crate::command_profile::add("qsa-kv", 1, "stage copy_prefix (host -> arena stage)", started.elapsed()); } - let started = std::time::Instant::now(); - let guard = Arguments::new(vec![Arg::U64(k), Arg::U64(v), Arg::I32((t * 512) as i32), Arg::U64(sa)])?; - stage.run(workspace, 0, [(t * 512).div_ceil(256) as u32, 1, 1], 256, guard)?; - if stage.flags()? != 0 { - return Err(Error::InvalidQ8Activation); - } - let args = Arguments::new(vec![ - Arg::U64(k), - Arg::U64(v), - Arg::I64(prior.end as i64), - Arg::U64(self.owner.pools.table()?), - Arg::I64(4), - Arg::U64(rp[0]), - Arg::U64(rp[1]), - Arg::U64(rp[2]), - Arg::U64(rp[3]), - Arg::U64(sp[0]), - Arg::U64(sp[1]), - Arg::U64(sp[2]), - Arg::U64(sp[3]), - Arg::U64(hp[0]), - Arg::U64(hp[1]), - Arg::U64(hp[2]), - Arg::U64(hp[3]), - ])?; - let scales = Arguments::new(vec![ - Arg::U64(sp[2]), - Arg::U64(sp[3]), - Arg::I32(prior.end as i32), - Arg::I32(end as i32), - Arg::U64(sa), - ])?; - - self.owner.current = None; - self.owner.mapped_current = None; - stage.run(workspace, 1, [t as u32, 2, 8], 64, args)?; - stage.run(workspace, 2, [1, 1, 1], 256, scales)?; - if stage.flags()? != 0 { - return Err(Error::InvalidQ8Activation); - } - if timed { - crate::command_profile::add("qsa-kv", 2, "append kernels (quantize, write, scales)", started.elapsed()); - } - self.end = end; - self.coverage.end.set(end); - self.stage_table = Some(table); - self.stage_addresses = Some(sp); - Ok(OriginalQsaMappedAppend { first: prior.end, rows: t, final_prefix: self.prefix() }) + Ok(()) } } @@ -172,18 +116,13 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { let ids = checked(self.owner.context, ids, t * 2051 * 4)?; let steps = checked(self.owner.context, steps, t * 16)?; let host = self.owner.host_addresses()?; - let resident = self.owner.pools.addresses()?; - let table = self.owner.pools.table()?; + let (resident, table) = (self.owner.pools.addresses()?, self.owner.pools.table()?); if !self.resolver_ready { self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(w, table)?; self.resolver_ready = true; } - let result = self - .owner - .resolver - .as_mut() - .ok_or(Error::ContextPoisoned)? - .resolve(w, table, ids, steps, t, host, resident); + let resolver = self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?; + let result = resolver.resolve(w, table, ids, steps, t, host, resident); if result.is_err() && self.owner.context.is_poisoned() { self.failed = true; } diff --git a/crates/cuda-driver/src/qsa_native_batch/impl_qsanativebatchworkspace_2.rs b/crates/cuda-driver/src/qsa_native_batch/impl_qsanativebatchworkspace_2.rs index 8fefdc76..1abb2fe1 100644 --- a/crates/cuda-driver/src/qsa_native_batch/impl_qsanativebatchworkspace_2.rs +++ b/crates/cuda-driver/src/qsa_native_batch/impl_qsanativebatchworkspace_2.rs @@ -17,116 +17,106 @@ impl<'ctx> QsaNativeBatchWorkspace<'ctx> { ) -> Result> { let blas = ws.blas()?; let context = self.context; - let x = self.handle(1, t * k * 4)?; - let packed = self.handle(3, t * k * 2)?; - let high = self.handle(4, t * 2560 * 2)?; - let low = self.handle(5, t * 2560 * 2)?; - let y = self.handle(6, t * n * 4)?; - let scratch = self.handle(0, n * k * 2)?; - let status = self.handle(7, 12)?; - let mut pack = KernelArguments::new(vec![ - A::Address(x), - A::Address(packed), - A::Address(high), - A::Address(low), - A::I64((t * k) as i64), - ]); - let mut gate = KernelArguments::new(vec![ - A::Address(x), - A::Address(self.handle(2, t * 6144 * 4)?), - A::Address(packed), - A::I64((t * 6144) as i64), - ]); - let mut input_scan = KernelArguments::new(vec![ - A::Address(if kind.is_some() { packed } else { high }), - A::Address(status), - A::I64((t * k) as i64), - A::U32(0), - A::U32(if kind.is_some() { 0x7c00 } else { 0x7f80 }), - ]); - let mut low_scan = KernelArguments::new(vec![ - A::Address(low), - A::Address(status), - A::I64((t * k) as i64), - A::U32(0), - A::U32(0x7f80), - ]); - // Exact pinned generic group32 decoder contract; Root binds the asset. - let mut dequant = KernelArguments::new(vec![ - A::Address(weight), - A::I64((k / 256 * kind.map_or(0, QsaNativeKind::block)) as i64), - A::I64(0), - A::I64(n as i64), - A::I64((k / 32) as i64), - A::Address(scratch), - ]); - let mut weight_scan = KernelArguments::new(vec![ - A::Address(scratch), - A::Address(status), - A::I64((n * k) as i64), - A::U32(1), - A::U32(0x7c00), - ]); - let zero = vec![0u8; 12]; - let mut flags = vec![0u8; 12]; + let io = self.project_io((t, n, k))?; + let mut args = ProjectArgs::new(&io, (t, n, k), weight, kind); let guard = context.enter()?; - let operation = (|| { - context.driver.api.copy_from(status, &zero)?; - // Pageable legacy H2D/reset must complete before nonblocking vendor stream. - context.driver.api.synchronize()?; - let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; - module.launch( - if out_gate { 1 } else { 0 }, - (t * k).div_ceil(256) as u32, - 256, - blas.stream(), - if out_gate { &mut gate } else { &mut pack }, - )?; - module.launch(2, (t * k).div_ceil(256) as u32, 256, blas.stream(), &mut input_scan)?; - if kind.is_none() && self.packing == QsaNativePacking::HighAndLow { - module.launch(2, (t * k).div_ceil(256) as u32, 256, blas.stream(), &mut low_scan)?; - } - let [alpha, beta0, beta1] = self.scalars.as_ref(); - if kind.is_some() { - self.dequant.as_ref().ok_or(Error::ContextPoisoned)?.launch( - kind.ok_or(Error::UnsupportedProjection)?.entry(), - (n * k / 32).div_ceil(256) as u32, - 256, - blas.stream(), - &mut dequant, - )?; - module.launch(2, (n * k).div_ceil(256) as u32, 256, blas.stream(), &mut weight_scan)?; - blas.gemm_f16(packed, scratch, y, t as i32, n as i32, k as i32, alpha, beta0)?; - } else { - blas.gemm_bf16(high, weight, y, t as i32, n as i32, k as i32, alpha, beta0)?; - if self.packing == QsaNativePacking::HighAndLow { - blas.gemm_bf16(low, weight, y, t as i32, n as i32, k as i32, alpha, beta1)?; - } - } - Ok(()) - })(); + let operation = self.launch_project(blas, &mut args, &io, ((t, n, k), weight, kind, out_gate)); let sync = blas.synchronize(); - let read = if sync.is_ok() { context.driver.api.copy_to(status, &mut flags) } else { Ok(()) }; + let read = if sync.is_ok() { context.driver.api.copy_to(io.status, &mut args.flags) } else { Ok(()) }; let pop = guard.finish(); + self.settle_project(ws, args, (operation, sync, read, pop))?; + self.download(t, n) + } + /// The device spans of one projection (`t` rows of `k` inputs to `n` outputs), in their fallible lookup order. + fn project_io(&self, (t, n, k): (usize, usize, usize)) -> Result { + Ok(ProjectIo { + x: self.handle(1, t * k * 4)?, + packed: self.handle(3, t * k * 2)?, + high: self.handle(4, t * 2560 * 2)?, + low: self.handle(5, t * 2560 * 2)?, + y: self.handle(6, t * n * 4)?, + scratch: self.handle(0, n * k * 2)?, + status: self.handle(7, 12)?, + gates: self.handle(2, t * 6144 * 4)?, + }) + } + /// Reset, pack (or gate-pack), the finiteness scans, the optional dequantization and the vendor GEMMs. + fn launch_project( + &self, + blas: &crate::ple_batch_ffi::Blas, + args: &mut ProjectArgs, + io: &ProjectIo, + ((t, n, k), weight, kind, out_gate): ((usize, usize, usize), ffi::BufferHandle, Option, bool), + ) -> Result<()> { + let context = self.context; + context.driver.api.copy_from(io.status, &args.zero)?; + // Pageable legacy H2D/reset must complete before nonblocking vendor stream. + context.driver.api.synchronize()?; + let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; + let pack = if out_gate { &mut args.gate } else { &mut args.pack }; + module.launch(if out_gate { 1 } else { 0 }, (t * k).div_ceil(256) as u32, 256, blas.stream(), pack)?; + module.launch(2, (t * k).div_ceil(256) as u32, 256, blas.stream(), &mut args.input_scan)?; + if kind.is_none() && self.packing == QsaNativePacking::HighAndLow { + module.launch(2, (t * k).div_ceil(256) as u32, 256, blas.stream(), &mut args.low_scan)?; + } + let [alpha, beta0, beta1] = self.scalars.as_ref(); + if let Some(kind) = kind { + self.launch_quantized(module, blas, args, ((n, k), kind))?; + return blas.gemm_f16(io.packed, io.scratch, io.y, t as i32, n as i32, k as i32, alpha, beta0); + } + blas.gemm_bf16(io.high, weight, io.y, t as i32, n as i32, k as i32, alpha, beta0)?; + if self.packing == QsaNativePacking::HighAndLow { + blas.gemm_bf16(io.low, weight, io.y, t as i32, n as i32, k as i32, alpha, beta1)?; + } + Ok(()) + } + /// Dequantizes the weight to F16 scratch and scans it for non-finite values. + fn launch_quantized( + &self, + module: &KernelModule, + blas: &crate::ple_batch_ffi::Blas, + args: &mut ProjectArgs, + ((n, k), kind): ((usize, usize), QsaNativeKind), + ) -> Result<()> { + self.dequant.as_ref().ok_or(Error::ContextPoisoned)?.launch( + kind.entry(), + (n * k / 32).div_ceil(256) as u32, + 256, + blas.stream(), + &mut args.dequant, + )?; + module.launch(2, (n * k).div_ceil(256) as u32, 256, blas.stream(), &mut args.weight_scan) + } + /// Marks both owners failed on any error, keeps the operands alive when the stream or the legacy upload may still + /// use them, and refuses unknown, unused or non-finite status words. + fn settle_project( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + args: ProjectArgs, + (operation, sync, read, pop): (Result<()>, Result<()>, Result<()>, Result<()>), + ) -> Result<()> { if operation.is_err() || sync.is_err() || read.is_err() || pop.is_err() { self.failed = true; ws.mark_failed(); - context.poison(); - context.retain_driver(); + self.context.poison(); + self.context.retain_driver(); } if sync.is_err() || read.is_err() || pop.is_err() { - std::mem::forget((pack, gate, input_scan, low_scan, dequant, weight_scan, zero, flags)); + std::mem::forget(args); return combine(combine(combine(operation, sync), read), pop) .map(|()| unreachable!("failed drain remains primary")); } if operation.is_err() { // A failed legacy upload may retain pageable staging even when the // independent vendor stream drained. Preserve primary and operands. - std::mem::forget((pack, gate, input_scan, low_scan, dequant, weight_scan, zero, flags)); + std::mem::forget(args); return combine(combine(combine(operation, sync), read), pop) .map(|()| unreachable!("failed command remains primary")); } combine(combine(combine(operation, sync), read), pop)?; + self.check_status_flags(&args.flags) + } + fn check_status_flags(&mut self, flags: &[u8]) -> Result<()> { if flags[8..].iter().any(|v| *v != 0) { self.failed = true; return Err(Error::InvalidDriverValue("QSA native unused finite status")); @@ -138,7 +128,7 @@ impl<'ctx> QsaNativeBatchWorkspace<'ctx> { if flags[..8].iter().any(|v| *v != 0) { return Err(Error::NonFiniteMmqOutput("QSA native packed input/weight")); } - self.download(t, n) + Ok(()) } pub fn project_inputs( &mut self, @@ -202,33 +192,20 @@ impl<'ctx> QsaNativeBatchWorkspace<'ctx> { } } let guard = self.context.enter(); - if let Ok(guard) = guard { - if !self.context.is_poisoned() { - if let Some(m) = self.module.take() { - result = combine(result, m.close()); - } - if let Some(m) = self.dequant.take() { - result = combine(result, m.close()); - } + let modules = [self.module.take(), self.dequant.take()]; + let Ok(guard) = guard else { + modules.into_iter().flatten().for_each(std::mem::forget); + return combine(result, Err(Error::ContextPoisoned)); + }; + let poisoned = self.context.is_poisoned(); + for m in modules.into_iter().flatten() { + if poisoned { + std::mem::forget(m); } else { - if let Some(m) = self.module.take() { - std::mem::forget(m); - } - if let Some(m) = self.dequant.take() { - std::mem::forget(m); - } + result = combine(result, m.close()); } - result = combine(result, guard.finish()); - } else { - if let Some(m) = self.module.take() { - std::mem::forget(m); - } - if let Some(m) = self.dequant.take() { - std::mem::forget(m); - } - result = combine(result, Err(Error::ContextPoisoned)); } - result + combine(result, guard.finish()) } } impl Drop for QsaNativeBatchWorkspace<'_> { @@ -236,3 +213,80 @@ impl Drop for QsaNativeBatchWorkspace<'_> { let _ = self.close_inner(); } } + +/// The device spans one projection reads and writes: activations, packed halves, output, F16 scratch and the status. +struct ProjectIo { + x: ffi::BufferHandle, + packed: ffi::BufferHandle, + high: ffi::BufferHandle, + low: ffi::BufferHandle, + y: ffi::BufferHandle, + scratch: ffi::BufferHandle, + status: ffi::BufferHandle, + gates: ffi::BufferHandle, +} + +/// The kernel arguments and host scratch of one projection; leaked whole when the stream state is unknown. +struct ProjectArgs { + pack: KernelArguments, + gate: KernelArguments, + input_scan: KernelArguments, + low_scan: KernelArguments, + dequant: KernelArguments, + weight_scan: KernelArguments, + zero: Vec, + flags: Vec, +} + +impl ProjectArgs { + fn new( + io: &ProjectIo, + (t, n, k): (usize, usize, usize), + weight: ffi::BufferHandle, + kind: Option, + ) -> Self { + let (input, limit) = if kind.is_some() { (io.packed, 0x7c00) } else { (io.high, 0x7f80) }; + let pack = vec![A::Address(io.x), A::Address(io.packed), A::Address(io.high), A::Address(io.low)]; + let gate = vec![A::Address(io.x), A::Address(io.gates), A::Address(io.packed), A::I64((t * 6144) as i64)]; + // Exact pinned generic group32 decoder contract; Root binds the asset. + let dequant = vec![ + A::Address(weight), + A::I64((k / 256 * kind.map_or(0, QsaNativeKind::block)) as i64), + A::I64(0), + A::I64(n as i64), + A::I64((k / 32) as i64), + A::Address(io.scratch), + ]; + Self { + pack: KernelArguments::new(with_tail(pack, A::I64((t * k) as i64))), + gate: KernelArguments::new(gate), + input_scan: scan_args(input, io.status, t * k, (0, limit)), + low_scan: scan_args(io.low, io.status, t * k, (0, 0x7f80)), + dequant: KernelArguments::new(dequant), + weight_scan: scan_args(io.scratch, io.status, n * k, (1, 0x7c00)), + zero: vec![0u8; 12], + flags: vec![0u8; 12], + } + } +} + +fn with_tail(mut args: Vec, last: A) -> Vec { + args.push(last); + args +} + +/// A finiteness scan of `count` elements of `buffer`, writing the shared status. +fn scan_args( + buffer: ffi::BufferHandle, + status: ffi::BufferHandle, + count: usize, + (slot, limit): (u32, u32), +) -> KernelArguments { + KernelArguments::new(vec![ + A::Address(buffer), + A::Address(status), + A::I64(count as i64), + A::U32(slot), + A::U32(limit), + ]) +} diff --git a/crates/cuda-driver/src/qsa_native_batch/impl_qsanativekind.rs b/crates/cuda-driver/src/qsa_native_batch/impl_qsanativekind.rs index 5a6204b1..6bc704ec 100644 --- a/crates/cuda-driver/src/qsa_native_batch/impl_qsanativekind.rs +++ b/crates/cuda-driver/src/qsa_native_batch/impl_qsanativekind.rs @@ -53,28 +53,7 @@ impl<'ctx> QsaNativeBatchWorkspace<'ctx> { if !(1..=8192).contains(&capacity) { return Err(Error::InvalidQwenShape); } - let mut sizes = SIZES; - for size in &mut sizes[1..7] { - *size = (*size / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?; - } - // Source-only asset refuses before allocations; no fake dequant producer. - let dequant_ptx = DEQUANT_PTX.ok_or(Error::InvalidDriverValue("QSA native dequant unsealed"))?; - if PTX.starts_with(b"// UNSEALED") { - return Err(Error::InvalidDriverValue("QSA native asset unsealed")); - } - if context.is_poisoned() { - return Err(Error::ContextPoisoned); - } - let required = sizes - .iter() - .try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))? - .checked_add(RESERVE) - .ok_or(Error::BudgetExceeded)?; - if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes()) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } + let (sizes, dequant_ptx) = admit_capacity(context, capacity)?; let mut owner = Self { capacity, sizes, @@ -86,41 +65,44 @@ impl<'ctx> QsaNativeBatchWorkspace<'ctx> { scalars: Box::new([1., 0., 1.]), failed: false, }; - let operation = (|| { - for (i, n) in sizes.into_iter().enumerate() { - owner.buffers[i] = Some(context.allocate(n)?); - } - let guard = context.enter()?; - let loaded = (|| { - owner.module = Some(KernelModule::load(PTX, &[c"qsa_pack", c"qsa_gate_pack", c"qsa_scan_half"])?); - owner.dequant = Some(KernelModule::load( - dequant_ptx, - &[ - c"leleka_native_dequant_f16_q4_k", - c"leleka_native_dequant_f16_q5_k", - c"leleka_native_dequant_f16_q6_k", - c"leleka_native_dequant_f16_iq4_xs", - ], - )?); - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poison(); - context.retain_driver(); - } - combine(loaded, pop)?; - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(primary) = operation { + if let Err(primary) = owner.allocate_and_load(sizes, dequant_ptx) { let _ = owner.close(); return Err(primary); } Ok(owner) } + /// Allocates the eight buffers, loads the pack and dequant modules inside the context and checks the reserve. + fn allocate_and_load(&mut self, sizes: [usize; 8], dequant_ptx: &'static [u8]) -> Result<()> { + let context = self.context; + for (i, n) in sizes.into_iter().enumerate() { + self.buffers[i] = Some(context.allocate(n)?); + } + let guard = context.enter()?; + let loaded = self.load_modules(dequant_ptx); + let pop = guard.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver(); + } + combine(loaded, pop)?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + fn load_modules(&mut self, dequant_ptx: &'static [u8]) -> Result<()> { + self.module = Some(KernelModule::load(PTX, &[c"qsa_pack", c"qsa_gate_pack", c"qsa_scan_half"])?); + self.dequant = Some(KernelModule::load( + dequant_ptx, + &[ + c"leleka_native_dequant_f16_q4_k", + c"leleka_native_dequant_f16_q5_k", + c"leleka_native_dequant_f16_q6_k", + c"leleka_native_dequant_f16_iq4_xs", + ], + )?); + Ok(()) + } pub fn prompt_device_bytes(capacity: usize) -> Result { if !(1..=8192).contains(&capacity) { return Err(Error::InvalidQwenShape); @@ -233,3 +215,31 @@ impl<'ctx> QsaNativeBatchWorkspace<'ctx> { Ok(values.into_boxed_slice()) } } + +/// The per-buffer sizes at `capacity` rows and the dequant asset; the sealed assets, the poison state and the +/// budget (buffers plus reserve) are admitted before anything is allocated. +fn admit_capacity<'c>(context: &Context<'c>, capacity: usize) -> Result<([usize; 8], &'static [u8])> { + let mut sizes = SIZES; + for size in &mut sizes[1..7] { + *size = (*size / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?; + } + // Source-only asset refuses before allocations; no fake dequant producer. + let dequant_ptx = DEQUANT_PTX.ok_or(Error::InvalidDriverValue("QSA native dequant unsealed"))?; + if PTX.starts_with(b"// UNSEALED") { + return Err(Error::InvalidDriverValue("QSA native asset unsealed")); + } + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + let required = sizes + .iter() + .try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))? + .checked_add(RESERVE) + .ok_or(Error::BudgetExceeded)?; + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes()) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + Ok((sizes, dequant_ptx)) +} diff --git a/crates/cuda-driver/src/qsa_native_decode.rs b/crates/cuda-driver/src/qsa_native_decode.rs index ffe72e8a..1efdf71f 100644 --- a/crates/cuda-driver/src/qsa_native_decode.rs +++ b/crates/cuda-driver/src/qsa_native_decode.rs @@ -33,47 +33,24 @@ impl<'ctx> QsaNativeDecode<'ctx> { if c.allocated_bytes().checked_add(n).is_none_or(|x| x > c.budget) || c.memory_info()?.0 < n { return Err(Error::BudgetExceeded); } - let g = c.enter().map_err(|error| { - c.poison(); - c.retain_driver(); - error - })?; - let load = Module::load( - include_bytes!("qsa_native_decode.ptx"), - &[ - c"leleka_qsa_prompt_guard", - c"leleka_qsa_decode_chunk", - c"leleka_qsa_decode_merge", - c"leleka_qsa_prompt_output_guard", - ], - ); - let pop = g.finish(); - let m = match load { - Ok(m) => { - if let Err(e) = pop { - c.poisoned.set(true); - std::mem::forget(m); - return Err(e); - } - m - } - Err(e) => return combine(Err(e), pop), - }; + let m = load_decode_module(c)?; let mut o = Self { context: c, output: None, scratch: None, status: None, module: Some(m), failed: false }; - let r = (|| { - o.output = Some(c.allocate(1_572_864)?); - o.scratch = Some(c.allocate(52_326_400)?); - o.status = Some(c.allocate(4)?); - if c.memory_info()?.0 < 128 * 1024 * 1024 { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = r { + if let Err(e) = o.allocate_buffers() { return combine(Err(e), o.close()); } Ok(o) } + /// The output bank, the split-K scratch and the status word; at least 128 MiB of device memory must stay free. + fn allocate_buffers(&mut self) -> Result<()> { + let c = self.context; + self.output = Some(c.allocate(1_572_864)?); + self.scratch = Some(c.allocate(52_326_400)?); + self.status = Some(c.allocate(4)?); + if c.memory_info()?.0 < 128 * 1024 * 1024 { + return Err(Error::BudgetExceeded); + } + Ok(()) + } pub fn allocated_bytes(&self) -> usize { self.output.as_ref().map_or(0, DeviceBuffer::len) + self.status.as_ref().map_or(0, DeviceBuffer::len) @@ -95,6 +72,27 @@ impl<'ctx> QsaNativeDecode<'ctx> { let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(4)?; Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::InvalidSize)?)) } + /// Enters the context; a failure poisons it, retains the driver and marks both owners failed. + fn enter_or_fail(&mut self, w: &mut NativeBatchWorkspace<'ctx>) -> Result> { + match self.context.enter() { + Ok(guard) => Ok(guard), + Err(error) => { + self.failed = true; + w.mark_failed(); + self.context.poison(); + self.context.retain_driver(); + Err(error) + } + } + } + fn launch_pass( + &self, + w: &NativeBatchWorkspace<'ctx>, + (index, grid, block, shared): (usize, [u32; 3], u32, u32), + a: &mut Arguments, + ) -> Result<()> { + self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(index, grid, block, shared, w.blas()?.stream(), a) + } fn run( &mut self, w: &mut NativeBatchWorkspace<'ctx>, @@ -106,27 +104,9 @@ impl<'ctx> QsaNativeDecode<'ctx> { ) -> Result<()> { self.validate()?; w.validate_context(self.context)?; - let g = match self.context.enter() { - Ok(guard) => guard, - Err(error) => { - self.failed = true; - w.mark_failed(); - self.context.poison(); - self.context.retain_driver(); - return Err(error); - } - }; + let g = self.enter_or_fail(w)?; let dependency = self.context.driver.api.synchronize(); - let op = dependency.and_then(|()| { - self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch( - index, - grid, - block, - shared, - w.blas()?.stream(), - &mut a, - ) - }); + let op = dependency.and_then(|()| self.launch_pass(w, (index, grid, block, shared), &mut a)); let sync = w.blas()?.synchronize(); let pop = g.finish(); if sync.is_err() || pop.is_err() { @@ -149,11 +129,26 @@ impl<'ctx> QsaNativeDecode<'ctx> { snapshot: &'loan QsaKvSnapshot, inputs: &QsaAttentionInputs<'_, '_>, ) -> Result> { - let (q, ids, steps, t) = (inputs.q, inputs.ids, inputs.steps, inputs.t); + let (ids, steps, t) = (inputs.ids, inputs.steps, inputs.t); self.validate()?; w.validate_context(self.context)?; kv.validate_context(self.context)?; kv.validate_snapshot(snapshot)?; + let handles = self.admit_inputs(w, inputs, |b| kv.reject_alias(b))?; + let (status, out) = self.guard_pass(w, handles, (t, snapshot.next_position()))?; + let (pools, table, _) = kv.resolved_addresses(w, snapshot, ids, steps, t)?; + self.attention_passes(w, (pools, table), handles, (status, out, t))?; + Ok(QsaNativeDecodeCompletion { owner: self, _kv: kv, _snapshot: snapshot, t }) + } + /// The 1..=3 query rows and the Q/IDs/steps owners: exact sizes, no alias with the KV, the workspace, this + /// decode's own buffers or each other. Returns the three device addresses. + fn admit_inputs( + &self, + w: &NativeBatchWorkspace<'ctx>, + inputs: &QsaAttentionInputs<'_, '_>, + reject_kv_alias: impl Fn(&DeviceBuffer<'_>) -> Result<()>, + ) -> Result<[u64; 3]> { + let (q, ids, steps, t) = (inputs.q, inputs.ids, inputs.steps, inputs.t); if !(1..=3).contains(&t) { return Err(Error::InvalidQwenShape); } @@ -161,37 +156,38 @@ impl<'ctx> QsaNativeDecode<'ctx> { let ih = checked(self.context, ids, t * 2051 * 4)?; let sh = checked(self.context, steps, t * 4 * 4)?; for b in [q, ids, steps] { - kv.reject_alias(b)?; + reject_kv_alias(b)?; w.reject_alias(b.handle.ok_or(Error::ContextPoisoned)?, b.bytes)?; - for own in self.output.iter().chain(self.status.iter()).chain(self.scratch.iter()) { - if own.handle.ok_or(Error::ContextPoisoned)?.overlaps( - own.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { - return Err(Error::OutputAliasesInput); - } + self.reject_own_alias(b)?; + } + reject_mutual_alias([q, ids, steps])?; + Ok([qh, ih, sh]) + } + /// `b` overlaps none of this decode's output, status or scratch buffers. + fn reject_own_alias(&self, b: &DeviceBuffer<'_>) -> Result<()> { + for own in self.output.iter().chain(self.status.iter()).chain(self.scratch.iter()) { + if own.handle.ok_or(Error::ContextPoisoned)?.overlaps( + own.bytes, + b.handle.ok_or(Error::ContextPoisoned)?, + b.bytes, + ) { + return Err(Error::OutputAliasesInput); } } - for a in [q, ids, steps] { - for b in [q, ids, steps] { - if !std::ptr::eq(a, b) - && a.handle.ok_or(Error::ContextPoisoned)?.overlaps( - a.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) - { - return Err(Error::OutputAliasesInput); - } - } - } - let end = snapshot.next_position(); + Ok(()) + } + /// Pre-admission scan and fence are mandatory before selected IDs can address pools. Returns the status and + /// output addresses. + fn guard_pass( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + [qh, ih, sh]: [u64; 3], + (t, end): (usize, usize), + ) -> Result<(u64, u64)> { self.status.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0; 4])?; let status = checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; let out = self.output.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); - // Pre-admission scan and fence are mandatory before selected IDs can address pools. let guard = Arguments::new(vec![ Arg::U64(qh), Arg::U64(ih), @@ -209,48 +205,35 @@ impl<'ctx> QsaNativeDecode<'ctx> { if flags & 1 != 0 { return Err(Error::InvalidQ8Activation); } - let (pools, table, _) = kv.resolved_addresses(w, snapshot, ids, steps, t)?; + Ok((status, out)) + } + /// Chunk, merge and finiteness passes over the resolved pools. + fn attention_passes( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + (pools, table): ([u64; 4], u64), + [qh, ih, sh]: [u64; 3], + (status, out, t): (u64, u64, usize), + ) -> Result<()> { let scratch = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; let handle = scratch.handle.ok_or(Error::ContextPoisoned)?; let pa = handle.qwen_address(); let pm = handle.checked_subspan(scratch.bytes, 811008, 3168)?.qwen_address(); let pl = handle.checked_subspan(scratch.bytes, 814176, 3168)?.qwen_address(); // Each query owns817600B; internal checked offsets mirror original single scratch layout. - let args = Arguments::new(vec![ - Arg::U64(qh), - Arg::U64(pools[0]), - Arg::U64(pools[1]), - Arg::U64(pools[2]), - Arg::U64(pools[3]), - Arg::U64(table), - Arg::U64(ih), - Arg::U64(sh), - Arg::I32(2), - Arg::I32(4), - Arg::F32(1.0 / 16.0), - Arg::U64(pa), - Arg::U64(pm), - Arg::U64(pl), - Arg::I32(33), - Arg::I32(2051), - Arg::I64(204400), - ])?; - self.run(w, 1, [33, 2, t as u32], 256, 0, args)?; - let merge = Arguments::new(vec![ - Arg::U64(pa), - Arg::U64(pm), - Arg::U64(pl), - Arg::I32(33), - Arg::U64(out), - Arg::I64(204400), - ])?; - self.run(w, 2, [24, t as u32, 1], 256, 0, merge)?; + let mut chunk = vec![Arg::U64(qh)]; + chunk.extend(pools.map(Arg::U64)); + chunk.extend([Arg::U64(table), Arg::U64(ih), Arg::U64(sh), Arg::I32(2), Arg::I32(4), Arg::F32(1.0 / 16.0)]); + chunk.extend([Arg::U64(pa), Arg::U64(pm), Arg::U64(pl), Arg::I32(33), Arg::I32(2051), Arg::I64(204400)]); + self.run(w, 1, [33, 2, t as u32], 256, 0, Arguments::new(chunk)?)?; + let merge = vec![Arg::U64(pa), Arg::U64(pm), Arg::U64(pl), Arg::I32(33), Arg::U64(out), Arg::I64(204400)]; + self.run(w, 2, [24, t as u32, 1], 256, 0, Arguments::new(merge)?)?; let scan = Arguments::new(vec![Arg::U64(out), Arg::I32((t * 6144) as i32), Arg::U64(status)])?; self.run(w, 3, [64, 1, 1], 256, 0, scan)?; if self.flags()? != 0 { return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention")); } - Ok(QsaNativeDecodeCompletion { owner: self, _kv: kv, _snapshot: snapshot, t }) + Ok(()) } pub fn close(mut self) -> Result<()> { self.close_inner() @@ -316,6 +299,54 @@ impl QsaNativeDecodeCompletion<'_, '_> { } } +/// No two of the inputs overlap. +fn reject_mutual_alias(inputs: [&DeviceBuffer<'_>; 3]) -> Result<()> { + for a in inputs { + for b in inputs { + if !std::ptr::eq(a, b) + && a.handle.ok_or(Error::ContextPoisoned)?.overlaps( + a.bytes, + b.handle.ok_or(Error::ContextPoisoned)?, + b.bytes, + ) + { + return Err(Error::OutputAliasesInput); + } + } + } + Ok(()) +} + +/// Enters the context and loads the decode module there; a failed pop poisons the context. +fn load_decode_module(c: &Context<'_>) -> Result { + let g = c.enter().map_err(|error| { + c.poison(); + c.retain_driver(); + error + })?; + let load = Module::load( + include_bytes!("qsa_native_decode.ptx"), + &[ + c"leleka_qsa_prompt_guard", + c"leleka_qsa_decode_chunk", + c"leleka_qsa_decode_merge", + c"leleka_qsa_prompt_output_guard", + ], + ); + let pop = g.finish(); + match load { + Ok(m) => { + if let Err(e) = pop { + c.poisoned.set(true); + std::mem::forget(m); + return Err(e); + } + Ok(m) + } + Err(e) => combine(Err(e), pop), + } +} + #[path = "qsa_resident_decode.rs"] mod resident_decode; pub use resident_decode::OriginalQsaResidentDecodeCompletion; diff --git a/crates/cuda-driver/src/qsa_native_gate.rs b/crates/cuda-driver/src/qsa_native_gate.rs index 35359527..feb74ea8 100644 --- a/crates/cuda-driver/src/qsa_native_gate.rs +++ b/crates/cuda-driver/src/qsa_native_gate.rs @@ -26,34 +26,7 @@ impl<'ctx> QsaNativeGate<'ctx> { { return Err(Error::BudgetExceeded); } - let guard = match context.enter() { - Ok(guard) => guard, - Err(error) => { - context.poison(); - context.retain_driver(); - return Err(error); - } - }; - let loaded = Module::load(include_bytes!("qsa_native_gate.ptx"), &[c"leleka_qsa_native_gate"]); - let pop = guard.finish(); - let module = match loaded { - Ok(module) => { - if let Err(error) = pop { - context.poison(); - context.retain_driver(); - std::mem::forget(module); - return Err(error); - } - module - } - Err(error) => { - if pop.is_err() { - context.poison(); - context.retain_driver(); - } - return combine(Err(error), pop); - } - }; + let module = load_gate_module(context)?; let owner = Self { context, module: Some(module), failed: false }; if context.memory_info()?.0 < RESERVE { return combine(Err(Error::BudgetExceeded), owner.close()); @@ -79,6 +52,36 @@ impl<'ctx> QsaNativeGate<'ctx> { if self.is_failed() { return Err(Error::ContextPoisoned); } + let handles = self.admit_operands(workspace, attention, gate, output)?; + let mut arguments = Arguments::new(Vec::from(handles.map(|h| Arg::U64(h.qwen_address()))))?; + let blas = workspace.blas()?; + let guard = match self.context.enter() { + Ok(guard) => guard, + Err(error) => { + self.failed = true; + workspace.mark_failed(); + self.context.poison(); + self.context.retain_driver(); + return Err(error); + } + }; + let dependency = self.context.driver.api.synchronize(); + let launch = dependency.and_then(|()| self.launch_gate(blas.stream(), &mut arguments)); + let sync = blas.synchronize(); + let pop = guard.finish(); + self.settle_launch(workspace, (launch, sync, pop), arguments) + } + fn launch_gate(&self, stream: usize, arguments: &mut Arguments) -> Result<()> { + self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(0, [24, 1, 1], 256, 0, stream, arguments) + } + /// All three operands are this context's whole 6144-word owners and none aliases the workspace or another operand. + fn admit_operands( + &self, + workspace: &NativeBatchWorkspace<'ctx>, + attention: &DeviceBuffer<'_>, + gate: &DeviceBuffer<'_>, + output: &DeviceBuffer<'_>, + ) -> Result<[crate::ffi::BufferHandle; 3]> { workspace.validate_context(self.context)?; checked(self.context, attention, BYTES)?; checked(self.context, gate, BYTES)?; @@ -96,35 +99,15 @@ impl<'ctx> QsaNativeGate<'ctx> { } } } - let mut arguments = Arguments::new(vec![ - Arg::U64(handles[0].qwen_address()), - Arg::U64(handles[1].qwen_address()), - Arg::U64(handles[2].qwen_address()), - ])?; - let blas = workspace.blas()?; - let guard = match self.context.enter() { - Ok(guard) => guard, - Err(error) => { - self.failed = true; - workspace.mark_failed(); - self.context.poison(); - self.context.retain_driver(); - return Err(error); - } - }; - let dependency = self.context.driver.api.synchronize(); - let launch = dependency.and_then(|()| { - self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch( - 0, - [24, 1, 1], - 256, - 0, - blas.stream(), - &mut arguments, - ) - }); - let sync = blas.synchronize(); - let pop = guard.finish(); + Ok(handles) + } + /// Keeps the arguments alive when the stream or context state is unknown and marks the owners failed on any error. + fn settle_launch( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + (launch, sync, pop): (Result<()>, Result<()>, Result<()>), + arguments: Arguments, + ) -> Result<()> { if sync.is_err() || pop.is_err() { std::mem::forget(arguments); } @@ -171,3 +154,35 @@ impl Drop for QsaNativeGate<'_> { let _ = self.close_inner(); } } + +/// Enters the context and loads the gate module there; a failed pop poisons the context and retains the driver. +fn load_gate_module(context: &Context<'_>) -> Result { + let guard = match context.enter() { + Ok(guard) => guard, + Err(error) => { + context.poison(); + context.retain_driver(); + return Err(error); + } + }; + let loaded = Module::load(include_bytes!("qsa_native_gate.ptx"), &[c"leleka_qsa_native_gate"]); + let pop = guard.finish(); + match loaded { + Ok(module) => { + if let Err(error) = pop { + context.poison(); + context.retain_driver(); + std::mem::forget(module); + return Err(error); + } + Ok(module) + } + Err(error) => { + if pop.is_err() { + context.poison(); + context.retain_driver(); + } + combine(Err(error), pop) + } + } +} diff --git a/crates/cuda-driver/src/qsa_prompt_attention/impl_qsapromptattention.rs b/crates/cuda-driver/src/qsa_prompt_attention/impl_qsapromptattention.rs index 88f10cc9..a1b6df62 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention/impl_qsapromptattention.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention/impl_qsapromptattention.rs @@ -15,49 +15,42 @@ impl<'ctx> QsaPromptAttention<'ctx> { return Err(Error::ContextPoisoned); } let output_bytes = capacity.checked_mul(6144 * 4).ok_or(Error::BudgetExceeded)?; - let n = output_bytes.checked_add(4 + 128 * 1024 * 1024).ok_or(Error::BudgetExceeded)?; - if c.allocated_bytes().checked_add(n).is_none_or(|x| x > c.budget) || c.memory_info()?.0 < n { - return Err(Error::BudgetExceeded); - } - let g = c.enter()?; - let load = Module::load( - include_bytes!("../qsa_prompt_attention.ptx"), + admit_budget(c, output_bytes)?; + let ptx = include_bytes!("../qsa_prompt_attention.ptx"); + let m = crate::qsa_prompt_attention_ffi::load_in_context( + c, + ptx, &[c"leleka_qsa_prompt_guard", c"leleka_qsa_prompt_attn", c"leleka_qsa_prompt_output_guard"], - ); - let pop = g.finish(); - let m = match load { - Ok(m) => { - if let Err(e) = pop { - c.poisoned.set(true); - std::mem::forget(m); - return Err(e); - } - m - } - Err(e) => return combine(Err(e), pop), - }; - let mut o = Self { + )?; + let mut o = Self::with_module(c, capacity, m); + if let Err(e) = o.allocate_buffers(Some(output_bytes)) { + return combine(Err(e), o.close()); + } + Ok(o) + } + pub(super) fn with_module(c: &'ctx Context<'ctx>, capacity: usize, module: Module) -> Self { + Self { capacity, context: c, output: None, status: None, - module: Some(m), + module: Some(module), variants: None, switches: SelectSwitches::default(), failed: false, - }; - let r = (|| { - o.output = Some(c.allocate(output_bytes)?); - o.status = Some(c.allocate(4)?); - if c.memory_info()?.0 < 128 * 1024 * 1024 { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = r { - return combine(Err(e), o.close()); } - Ok(o) + } + /// The status word and, when the owner keeps one, the output bank; 128 MiB of device memory must stay free. + pub(super) fn allocate_buffers(&mut self, output_bytes: Option) -> Result<()> { + let c = self.context; + if let Some(bytes) = output_bytes { + self.output = Some(c.allocate(bytes)?); + } + self.status = Some(c.allocate(4)?); + if c.memory_info()?.0 < 128 * 1024 * 1024 { + return Err(Error::BudgetExceeded); + } + Ok(()) } pub fn prompt_device_bytes(capacity: usize) -> Result { if !(1..=8192).contains(&capacity) { @@ -86,6 +79,23 @@ impl<'ctx> QsaPromptAttention<'ctx> { let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(4)?; Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::InvalidSize)?)) } + /// Launches one entry of the default module, or of the variants module, on the workspace's stream. + pub(super) fn launch_variant( + &self, + variants: bool, + w: &NativeBatchWorkspace<'ctx>, + (index, grid, block, shared): (usize, [u32; 3], u32, u32), + a: &mut Arguments, + ) -> Result<()> { + (if variants { self.variants.as_ref() } else { self.module.as_ref() }).ok_or(Error::ContextPoisoned)?.launch( + index, + grid, + block, + shared, + w.blas()?.stream(), + a, + ) + } #[allow(clippy::too_many_arguments)] pub(super) fn run_in( &mut self, @@ -101,11 +111,7 @@ impl<'ctx> QsaPromptAttention<'ctx> { w.validate_context(self.context)?; let g = self.context.enter()?; let dependency = self.context.driver.api.synchronize(); - let op = dependency.and_then(|()| { - (if variants { self.variants.as_ref() } else { self.module.as_ref() }) - .ok_or(Error::ContextPoisoned)? - .launch(index, grid, block, shared, w.blas()?.stream(), &mut a) - }); + let op = dependency.and_then(|()| self.launch_variant(variants, w, (index, grid, block, shared), &mut a)); let sync = w.blas()?.synchronize(); let pop = g.finish(); if sync.is_err() || pop.is_err() { @@ -189,22 +195,32 @@ impl<'ctx> QsaPromptAttention<'ctx> { snapshot: &'loan QsaKvSnapshot, inputs: &QsaAttentionInputs<'_, '_>, ) -> Result> { - // (module, guard entry, attention entry, output-guard entry, dynamic shared bytes) - let (variants, guard_ix, attn_ix, scan_ix, shared) = match kernel { - PromptAttnKernel::Int8V2 => (false, 0, 1, 2, kernel.smem_bytes()), - // the FP16 / hybrid pools have no Rust owner on this resident INT8 stage - PromptAttnKernel::Int8V1 => (true, 0, 1, 4, kernel.smem_bytes()), - PromptAttnKernel::Fp16 | PromptAttnKernel::HybridK8V4 => { - return Err(Error::UnsupportedQwenOperation); - } - }; - if variants { + let plan = KernelPlan::of(kernel)?; + if plan.variants { self.ensure_variants()?; } - let (q, ids, steps, t) = (inputs.q, inputs.ids, inputs.steps, inputs.t); + let t = inputs.t; self.validate()?; w.validate_context(self.context)?; stage.validate(self.context)?; + let [qh, ih, sh] = self.admit_inputs(w, inputs, |b| stage.reject_alias(b))?; + let (pools, table, end) = stage.completed_addresses(kv, snapshot)?; + let status = self.zero_status()?; + let out = + self.output.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); + let passes = AttnPasses { addrs: [qh, ih, sh, out, status], pools, table, end, t }; + self.run_passes(w, &plan, &passes, Self::run_in)?; + Ok(QsaPromptAttentionCompletion { owner: self, _stage: stage, _snapshot: snapshot, t }) + } + /// The 1..=capacity query rows and the Q/IDs/steps owners: exact sizes, no alias with the stage, the workspace, + /// this attention's own buffers or each other. Returns the three device addresses. + pub(super) fn admit_inputs( + &self, + w: &NativeBatchWorkspace<'ctx>, + inputs: &QsaAttentionInputs<'_, '_>, + reject_stage: impl Fn(&DeviceBuffer<'_>) -> Result<()>, + ) -> Result<[u64; 3]> { + let (q, ids, steps, t) = (inputs.q, inputs.ids, inputs.steps, inputs.t); if !(1..=self.capacity).contains(&t) { return Err(Error::InvalidQwenShape); } @@ -212,7 +228,7 @@ impl<'ctx> QsaPromptAttention<'ctx> { let ih = checked(self.context, ids, t * 2051 * 4)?; let sh = checked(self.context, steps, t * 4 * 4)?; for b in [q, ids, steps] { - stage.reject_alias(b)?; + reject_stage(b)?; w.reject_alias(b.handle.ok_or(Error::ContextPoisoned)?, b.bytes)?; for own in self.output.iter().chain(self.status.iter()) { if own.handle.ok_or(Error::ContextPoisoned)?.overlaps( @@ -224,35 +240,80 @@ impl<'ctx> QsaPromptAttention<'ctx> { } } } - for a in [q, ids, steps] { - for b in [q, ids, steps] { - if !std::ptr::eq(a, b) - && a.handle.ok_or(Error::ContextPoisoned)?.overlaps( - a.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) - { + reject_mutual_alias([q, ids, steps])?; + Ok([qh, ih, sh]) + } + /// The query, IDs, steps and attention spans of the arena do not overlap the stage, the workspace or this + /// attention's own buffers. + pub(super) fn reject_span_aliases( + &self, + w: &NativeBatchWorkspace<'ctx>, + t: usize, + spans: [crate::ffi::BufferHandle; 4], + reject_stage: impl Fn(crate::ffi::BufferHandle, usize) -> Result<()>, + ) -> Result<()> { + let [hq, hi, hs, out_h] = spans; + for (h, n) in [(hq, t * 6144 * 4), (hi, t * 2051 * 4), (hs, t * 16), (out_h, t * 6144 * 4)] { + reject_stage(h, n)?; + w.reject_alias(h, n)?; + for b in self.output.iter().chain(self.status.iter()) { + if h.overlaps(n, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) { return Err(Error::OutputAliasesInput); } } } - let (pools, table, end) = stage.completed_addresses(kv, snapshot)?; + Ok(()) + } + /// Zeroes the status word and returns its address. + pub(super) fn zero_status(&mut self) -> Result { self.status.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0; 4])?; - let status = checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; - let out = - self.output.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); - // Pre-admission scan and fence are mandatory before selected IDs can address pools. + checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4) + } + /// The guard scan and fence, the attention kernel and the output finiteness scan, on `run` (`run_in` or + /// `run_resident`). + pub(super) fn run_passes( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + plan: &KernelPlan, + p: &AttnPasses, + run: Runner<'ctx>, + ) -> Result<()> { + let [qh, ih, sh, out, status] = p.addrs; + let (v, t) = (plan.variants, p.t); + self.guard_pass(w, plan, p, run)?; + let mut args = vec![Arg::U64(qh)]; + args.extend(p.pools.map(Arg::U64)); + args.extend([Arg::U64(p.table), Arg::U64(ih), Arg::U64(sh), Arg::I32(2), Arg::I32(4)]); + args.extend([Arg::F32(1.442_695_0_f32 / 16.0), Arg::U64(out), Arg::I32(2051)]); + run(self, v, w, plan.attn_ix, [t as u32, 2, 1], 128, plan.shared, Arguments::new(args)?)?; + let scan = Arguments::new(vec![Arg::U64(out), Arg::I32((t * 6144) as i32), Arg::U64(status)])?; + run(self, v, w, plan.scan_ix, [guard_grid(t), 1, 1], 256, 0, scan)?; + if self.flags()? != 0 { + return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention")); + } + Ok(()) + } + /// Pre-admission scan and fence are mandatory before selected IDs can address pools. + fn guard_pass( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + plan: &KernelPlan, + p: &AttnPasses, + run: Runner<'ctx>, + ) -> Result<()> { + let [qh, ih, sh, _, status] = p.addrs; + let t = p.t; + let end = Arg::I32(p.end as i32); let guard = Arguments::new(vec![ Arg::U64(qh), Arg::U64(ih), Arg::U64(sh), Arg::I32(t as i32), Arg::I32(2051), - Arg::I32(end as i32), + end, Arg::U64(status), ])?; - self.run_in(variants, w, guard_ix, [guard_grid(t), 1, 1], 256, 0, guard)?; + run(self, plan.variants, w, plan.guard_ix, [guard_grid(t), 1, 1], 256, 0, guard)?; let flags = self.flags()?; if flags & 2 != 0 { return Err(Error::InvalidQwenShape); @@ -260,66 +321,33 @@ impl<'ctx> QsaPromptAttention<'ctx> { if flags & 1 != 0 { return Err(Error::InvalidQ8Activation); } - let args = Arguments::new(vec![ - Arg::U64(qh), - Arg::U64(pools[0]), - Arg::U64(pools[1]), - Arg::U64(pools[2]), - Arg::U64(pools[3]), - Arg::U64(table), - Arg::U64(ih), - Arg::U64(sh), - Arg::I32(2), - Arg::I32(4), - Arg::F32(1.442_695_0_f32 / 16.0), - Arg::U64(out), - Arg::I32(2051), - ])?; - self.run_in(variants, w, attn_ix, [t as u32, 2, 1], 128, shared, args)?; - let scan = Arguments::new(vec![Arg::U64(out), Arg::I32((t * 6144) as i32), Arg::U64(status)])?; - self.run_in(variants, w, scan_ix, [guard_grid(t), 1, 1], 256, 0, scan)?; - if self.flags()? != 0 { - return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention")); - } - Ok(QsaPromptAttentionCompletion { owner: self, _stage: stage, _snapshot: snapshot, t }) + Ok(()) } pub fn close(mut self) -> Result<()> { self.close_inner() } + /// Unloads a module inside the context; a poisoned context keeps it (and reports the poison) instead. + fn close_module(&self, m: Module) -> 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) + } + } + } pub(super) fn close_inner(&mut self) -> Result<()> { self.failed = true; let mut r = Ok(()); if let Some(m) = self.module.take() { - if self.context.is_poisoned() { - std::mem::forget(m); - r = Err(Error::ContextPoisoned); - } else { - match self.context.enter() { - Ok(g) => { - r = combine(m.close(), g.finish()); - } - Err(e) => { - std::mem::forget(m); - r = Err(e); - } - } - } + r = self.close_module(m); } if let Some(m) = self.variants.take() { - if self.context.is_poisoned() { - std::mem::forget(m); - r = combine(r, Err(Error::ContextPoisoned)); - } else { - match self.context.enter() { - Ok(g) => { - r = combine(r, combine(m.close(), g.finish())); - } - Err(e) => { - std::mem::forget(m); - r = combine(r, Err(e)); - } - } - } + r = combine(r, self.close_module(m)); } if let Some(b) = self.status.take() { r = combine(r, b.release()); @@ -330,3 +358,75 @@ impl<'ctx> QsaPromptAttention<'ctx> { r } } + +/// `kernel` as the module, the entries (guard, attention, output guard) and the dynamic shared bytes it launches. +pub(super) struct KernelPlan { + pub(super) variants: bool, + pub(super) guard_ix: usize, + pub(super) attn_ix: usize, + pub(super) scan_ix: usize, + pub(super) shared: u32, +} + +impl KernelPlan { + pub(super) fn of(kernel: PromptAttnKernel) -> Result { + match kernel { + PromptAttnKernel::Int8V2 => { + Ok(Self { variants: false, guard_ix: 0, attn_ix: 1, scan_ix: 2, shared: kernel.smem_bytes() }) + } + PromptAttnKernel::Int8V1 => { + Ok(Self { variants: true, guard_ix: 0, attn_ix: 1, scan_ix: 4, shared: kernel.smem_bytes() }) + } + // the FP16 / hybrid pools have no Rust owner on this resident INT8 stage + PromptAttnKernel::Fp16 | PromptAttnKernel::HybridK8V4 => Err(Error::UnsupportedQwenOperation), + } + } +} + +/// What the three passes address: `addrs` = Q, IDs, steps, output, status; the pools, their table and the cache end. +pub(super) struct AttnPasses { + pub(super) addrs: [u64; 5], + pub(super) pools: [u64; 4], + pub(super) table: u64, + pub(super) end: usize, + pub(super) t: usize, +} + +/// `run_in` or `run_resident`: they differ in their validation and in the failure bookkeeping. +pub(super) type Runner<'ctx> = fn( + &mut QsaPromptAttention<'ctx>, + bool, + &mut NativeBatchWorkspace<'ctx>, + usize, + [u32; 3], + u32, + u32, + Arguments, +) -> Result<()>; + +/// No two of the inputs overlap. +fn reject_mutual_alias(inputs: [&DeviceBuffer<'_>; 3]) -> Result<()> { + for a in inputs { + for b in inputs { + if !std::ptr::eq(a, b) + && a.handle.ok_or(Error::ContextPoisoned)?.overlaps( + a.bytes, + b.handle.ok_or(Error::ContextPoisoned)?, + b.bytes, + ) + { + return Err(Error::OutputAliasesInput); + } + } + } + Ok(()) +} + +/// The output bank, the status word and the 128 MiB reserve must fit the budget and the free device memory. +pub(super) fn admit_budget(c: &Context<'_>, output_bytes: usize) -> Result<()> { + let n = output_bytes.checked_add(4 + 128 * 1024 * 1024).ok_or(Error::BudgetExceeded)?; + if c.allocated_bytes().checked_add(n).is_none_or(|x| x > c.budget) || c.memory_info()?.0 < n { + return Err(Error::BudgetExceeded); + } + Ok(()) +} diff --git a/crates/cuda-driver/src/qsa_prompt_attention_ffi.rs b/crates/cuda-driver/src/qsa_prompt_attention_ffi.rs index 02a11409..81518f9a 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention_ffi.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention_ffi.rs @@ -1,6 +1,6 @@ //! Private fixed-symbol ABI for the literal INT8 prompt and append assets. //! No arbitrary entry, public pointer, or stream ownership escapes this module. -use crate::{Error, Result, combine}; +use crate::{Context, Error, Result, combine}; use std::ffi::{CStr, c_void}; pub(crate) enum Arg { U64(u64), @@ -19,6 +19,27 @@ impl Arguments { Ok(Self { values: values.into_boxed_slice(), pointers }) } } +/// Enters the context, loads `ptx` there and pops; a failed pop poisons the context and forgets the module. +pub(crate) fn load_in_context( + c: &Context<'_>, + ptx: &'static [u8], + entries: &'static [&'static CStr], +) -> Result { + let g = c.enter()?; + let load = Module::load(ptx, entries); + let pop = g.finish(); + match load { + Ok(m) => { + if let Err(e) = pop { + c.poisoned.set(true); + std::mem::forget(m); + return Err(e); + } + Ok(m) + } + Err(e) => combine(Err(e), pop), + } +} #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod enabled { use super::*; @@ -85,52 +106,46 @@ mod enabled { let get = sym!(l, c"cuModuleGetFunction", Function); let dev = sym!(l, c"cuCtxGetDevice", Device); let attr = sym!(l, c"cuDeviceGetAttribute", Attr); - let mut device = 0; - check("cuCtxGetDevice", unsafe { dev(&mut device) })?; - let mut major = 0; - let mut minor = 0; - let mut shared = 0; - let mut optin = 0; - check("cuDeviceGetAttribute", unsafe { attr(&mut major, 75, device) })?; - check("cuDeviceGetAttribute", unsafe { attr(&mut minor, 76, device) })?; - check("cuDeviceGetAttribute", unsafe { attr(&mut shared, 8, device) })?; - // CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN (the Original's smpbo for the opt-in). - check("cuDeviceGetAttribute", unsafe { attr(&mut optin, 97, device) })?; - if major < 8 || shared < 45584 { - return Err(Error::UnsupportedQwenOperation); - } + let caps = device_caps(dev, attr)?; let mut owner = Self { launch: sym!(l, c"cuLaunchKernel", Launch), unload: sym!(l, c"cuModuleUnload", Unload), func_attr: sym!(l, c"cuFuncSetAttribute", FuncAttr), - caps: [major.max(0) as u32, minor.max(0) as u32, optin.max(0) as u32], + caps, library: Some(l), module: None, functions: Vec::new(), }; owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?; - let result = (|| { - let mut m = std::ptr::null_mut(); - check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; - if m.is_null() { - return Err(Error::InvalidDriverValue("cuModuleLoadData")); - } - owner.module = Some(m as usize); - for n in entries { - let mut f = std::ptr::null_mut(); - check("cuModuleGetFunction", unsafe { get(&mut f, m, n.as_ptr()) })?; - if f.is_null() { - return Err(Error::InvalidDriverValue("cuModuleGetFunction")); - } - owner.functions.push(f as usize); - } - Ok(()) - })(); + let result = owner.init_functions((load, get), ptx, entries); if let Err(e) = result { return combine(Err(e), owner.close()); } Ok(owner) } + /// Loads the module image and resolves every entry; the module and functions stay recorded for `close`. + fn init_functions( + &mut self, + (load, get): (Load, Function), + ptx: &'static [u8], + entries: &'static [&'static CStr], + ) -> Result<()> { + let mut m = std::ptr::null_mut(); + check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; + if m.is_null() { + return Err(Error::InvalidDriverValue("cuModuleLoadData")); + } + self.module = Some(m as usize); + for n in entries { + let mut f = std::ptr::null_mut(); + check("cuModuleGetFunction", unsafe { get(&mut f, m, n.as_ptr()) })?; + if f.is_null() { + return Err(Error::InvalidDriverValue("cuModuleGetFunction")); + } + self.functions.push(f as usize); + } + Ok(()) + } /// (compute-capability major, minor, max dynamic shared memory per block with the opt-in). pub(crate) fn caps(&self) -> [u32; 3] { self.caps @@ -157,29 +172,10 @@ mod enabled { // (CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES = 8). check("cuFuncSetAttribute", unsafe { (self.func_attr)(f as *mut c_void, 8, shared as i32) })?; } - args.pointers.clear(); - for v in &mut args.values { - args.pointers.push(match v { - Arg::U64(x) => (x as *mut u64).cast(), - Arg::I32(x) => (x as *mut i32).cast(), - Arg::I64(x) => (x as *mut i64).cast(), - Arg::F32(x) => (x as *mut f32).cast(), - }); - } + args.pack(); + let (f, stream, pointers) = (f as *mut c_void, stream as *mut c_void, args.pointers.as_mut_ptr()); check("cuLaunchKernel", unsafe { - (self.launch)( - f as *mut c_void, - grid[0], - grid[1], - grid[2], - block, - 1, - 1, - shared, - stream as *mut c_void, - args.pointers.as_mut_ptr(), - std::ptr::null_mut(), - ) + (self.launch)(f, grid[0], grid[1], grid[2], block, 1, 1, shared, stream, pointers, std::ptr::null_mut()) }) } pub(crate) fn close(mut self) -> Result<()> { @@ -199,6 +195,38 @@ mod enabled { } } } + /// The current Context's compute capability `[major, minor, opt-in shared]`; it must be sm_80+ with 45584 B of shared. + fn device_caps(dev: Device, attr: Attr) -> Result<[u32; 3]> { + let mut device = 0; + check("cuCtxGetDevice", unsafe { dev(&mut device) })?; + let mut major = 0; + let mut minor = 0; + let mut shared = 0; + let mut optin = 0; + check("cuDeviceGetAttribute", unsafe { attr(&mut major, 75, device) })?; + check("cuDeviceGetAttribute", unsafe { attr(&mut minor, 76, device) })?; + check("cuDeviceGetAttribute", unsafe { attr(&mut shared, 8, device) })?; + // CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN (the Original's smpbo for the opt-in). + check("cuDeviceGetAttribute", unsafe { attr(&mut optin, 97, device) })?; + if major < 8 || shared < 45584 { + return Err(Error::UnsupportedQwenOperation); + } + Ok([major.max(0) as u32, minor.max(0) as u32, optin.max(0) as u32]) + } + impl Arguments { + /// Points `pointers` at every value in order. + fn pack(&mut self) { + self.pointers.clear(); + for v in &mut self.values { + self.pointers.push(match v { + Arg::U64(x) => (x as *mut u64).cast(), + Arg::I32(x) => (x as *mut i32).cast(), + Arg::I64(x) => (x as *mut i64).cast(), + Arg::F32(x) => (x as *mut f32).cast(), + }); + } + } + } impl Drop for Module { fn drop(&mut self) { let _ = self.close_inner(); diff --git a/crates/cuda-driver/src/qsa_prompt_attention_select/impl_poolpresence.rs b/crates/cuda-driver/src/qsa_prompt_attention_select/impl_poolpresence.rs index ddeb8893..a09bea58 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention_select/impl_poolpresence.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention_select/impl_poolpresence.rs @@ -149,6 +149,41 @@ pub const fn smem2_bytes() -> u32 { (kv + sc + part + p + rest) as u32 } +/// The Q4 K pool, a head dimension or head ratio other than the Qwen one, an empty selection and a missing page table +/// are refused before any kernel is chosen. +fn pools_admitted(pools: &PoolPresence, shapes: &Shapes, cap: i64, have_ids_and_steps: bool) -> bool { + !(pools.k_q4 + || shapes.head_dim != HD + || shapes.n_head != G * shapes.n_head_kv + || cap <= 0 + || !have_ids_and_steps + || !pools.page_table) +} + +/// The kernel family of the pools present (`None`: a pool or scale it needs is missing); Turing and the debug arm take v1. +fn kernel_for_pools(pools: &PoolPresence, switches: &SelectSwitches, turing: bool) -> Option { + if pools.k_q && pools.v_q4 { + if !pools.k_scale { + return None; + } + return Some(PromptAttnKernel::HybridK8V4); + } + if pools.k_q { + if !pools.v_q || !pools.k_scale || !pools.v_scale { + return None; + } + return Some(if switches.prompt_attn_v1 || turing { + PromptAttnKernel::Int8V1 + } else { + PromptAttnKernel::Int8V2 + }); + } + if !pools.k_pool || !pools.v_pool { + return None; + } + Some(PromptAttnKernel::Fp16) +} + /// Literal port of `qsa_prompt_attn_batch`'s decision tree for CUDA. `cap` is the selection stride /// (`ids [n_q, cap]`), `have_ids_and_steps` the null test of the two selection arrays. pub fn select( @@ -163,32 +198,10 @@ pub fn select( if cc < 75 { return None; } - let turing = cc < 80; - if pools.k_q4 - || shapes.head_dim != HD - || shapes.n_head != G * shapes.n_head_kv - || cap <= 0 - || !have_ids_and_steps - || !pools.page_table - { + if !pools_admitted(&pools, &shapes, cap, have_ids_and_steps) { return None; } - let kernel = if pools.k_q && pools.v_q4 { - if !pools.k_scale { - return None; - } - PromptAttnKernel::HybridK8V4 - } else if pools.k_q { - if !pools.v_q || !pools.k_scale || !pools.v_scale { - return None; - } - if switches.prompt_attn_v1 || turing { PromptAttnKernel::Int8V1 } else { PromptAttnKernel::Int8V2 } - } else { - if !pools.k_pool || !pools.v_pool { - return None; - } - PromptAttnKernel::Fp16 - }; + let kernel = kernel_for_pools(&pools, &switches, cc < 80)?; // cudaFuncSetAttribute(MaxDynamicSharedMemorySize) refused -> the Original returns false if kernel.smem_bytes() > DEFAULT_SHARED_LIMIT && kernel.smem_bytes() > device.max_shared_optin { return None; diff --git a/crates/cuda-driver/src/qsa_prompt_device_attention.rs b/crates/cuda-driver/src/qsa_prompt_device_attention.rs index e0afa66c..c864fc99 100644 --- a/crates/cuda-driver/src/qsa_prompt_device_attention.rs +++ b/crates/cuda-driver/src/qsa_prompt_device_attention.rs @@ -1,4 +1,5 @@ //! Same literal attention on the real selected query/IDs/steps/attn arena. +use super::impl_qsapromptattention::{AttnPasses, KernelPlan}; use super::*; impl<'ctx> QsaPromptAttention<'ctx> { pub(crate) fn attend_original_arena( @@ -12,12 +13,8 @@ impl<'ctx> QsaPromptAttention<'ctx> { let t = inputs.rows(); // Original qsa_prompt_attn_batch choice over the resident INT8 pools: v2 on every sm_80+ card unless the // STRATA_PROMPT_ATTN_V1 debug arm was requested through `set_switches`. - let (variants, guard_ix, attn_ix, scan_ix, shared) = match self.selected_kernel()? { - PromptAttnKernel::Int8V2 => (false, 0, 1, 2, PromptAttnKernel::Int8V2.smem_bytes()), - PromptAttnKernel::Int8V1 => (true, 0, 1, 4, PromptAttnKernel::Int8V1.smem_bytes()), - PromptAttnKernel::Fp16 | PromptAttnKernel::HybridK8V4 => return Err(Error::UnsupportedQwenOperation), - }; - if variants { + let plan = KernelPlan::of(self.selected_kernel()?)?; + if plan.variants { self.ensure_variants()?; } self.validate()?; @@ -27,59 +24,10 @@ impl<'ctx> QsaPromptAttention<'ctx> { return Err(Error::InvalidQwenShape); } let (hq, hi, hs, out_h) = inputs.attention_spans(self.context)?; - let (qh, ih, sh) = (hq.qwen_address(), hi.qwen_address(), hs.qwen_address()); - for (h, n) in [(hq, t * 6144 * 4), (hi, t * 2051 * 4), (hs, t * 16), (out_h, t * 6144 * 4)] { - stage.reject_original_span(h, n)?; - w.reject_alias(h, n)?; - for b in self.output.iter().chain(self.status.iter()) { - if h.overlaps(n, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) { - return Err(Error::OutputAliasesInput); - } - } - } + self.reject_span_aliases(w, t, [hq, hi, hs, out_h], |h, n| stage.reject_original_span(h, n))?; let (pools, table, end) = stage.completed_addresses(kv, snapshot)?; - self.status.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0; 4])?; - let status = checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; - let out = out_h.qwen_address(); - // Pre-admission scan and fence are mandatory before selected IDs can address pools. - let guard = Arguments::new(vec![ - Arg::U64(qh), - Arg::U64(ih), - Arg::U64(sh), - Arg::I32(t as i32), - Arg::I32(2051), - Arg::I32(end as i32), - Arg::U64(status), - ])?; - self.run_in(variants, w, guard_ix, [crate::qsa_prompt_attention::guard_grid(t), 1, 1], 256, 0, guard)?; - let flags = self.flags()?; - if flags & 2 != 0 { - return Err(Error::InvalidQwenShape); - } - if flags & 1 != 0 { - return Err(Error::InvalidQ8Activation); - } - let args = Arguments::new(vec![ - Arg::U64(qh), - Arg::U64(pools[0]), - Arg::U64(pools[1]), - Arg::U64(pools[2]), - Arg::U64(pools[3]), - Arg::U64(table), - Arg::U64(ih), - Arg::U64(sh), - Arg::I32(2), - Arg::I32(4), - Arg::F32(1.442_695_0_f32 / 16.0), - Arg::U64(out), - Arg::I32(2051), - ])?; - self.run_in(variants, w, attn_ix, [t as u32, 2, 1], 128, shared, args)?; - let scan = Arguments::new(vec![Arg::U64(out), Arg::I32((t * 6144) as i32), Arg::U64(status)])?; - self.run_in(variants, w, scan_ix, [crate::qsa_prompt_attention::guard_grid(t), 1, 1], 256, 0, scan)?; - if self.flags()? != 0 { - return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention")); - } - Ok(()) + let status = self.zero_status()?; + let addrs = [hq.qwen_address(), hi.qwen_address(), hs.qwen_address(), out_h.qwen_address(), status]; + self.run_passes(w, &plan, &AttnPasses { addrs, pools, table, end, t }, Self::run_in) } } diff --git a/crates/cuda-driver/src/qsa_prompt_host_ffi.rs b/crates/cuda-driver/src/qsa_prompt_host_ffi.rs index f1fd261a..19760f75 100644 --- a/crates/cuda-driver/src/qsa_prompt_host_ffi.rs +++ b/crates/cuda-driver/src/qsa_prompt_host_ffi.rs @@ -39,6 +39,14 @@ mod enabled { unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } + fn open_library() -> Result { + // SAFETY: fixed library name and flags; the returned handle (checked non-null next) is owned by `Library`. + let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); + if library.0.is_null() { + return Err(Error::LibraryUnavailable); + } + Ok(library) + } pub(crate) struct MappedAllocation { library: Option, host: Option, @@ -48,11 +56,7 @@ mod enabled { } impl MappedAllocation { pub(crate) fn new() -> Result { - // SAFETY: fixed library name and flags; the returned handle (checked non-null next) is owned by `Library`. - let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); - if library.0.is_null() { - return Err(Error::LibraryUnavailable); - } + let library = open_library()?; let alloc = sym!(library, c"cuMemHostAlloc", Alloc); let address = sym!(library, c"cuMemHostGetDevicePointer_v2", Address); let free = sym!(library, c"cuMemFreeHost", Free); @@ -64,7 +68,11 @@ mod enabled { if ptr.is_null() { return Err(Error::InvalidDriverValue("cuMemHostAlloc")); } - let mut owner = Self { library: Some(library), host: Some(ptr as usize), alias: 0, bytes, free }; + let owner = Self { library: Some(library), host: Some(ptr as usize), alias: 0, bytes, free }; + Self::map_and_zero(owner, address, ptr) + } + /// Maps the allocation to its device alias (page-aligned both ways) and zeroes it; any failure closes it. + fn map_and_zero(mut owner: Self, address: Address, ptr: *mut c_void) -> Result { // SAFETY: `ptr` is the base of the live cuMemHostAlloc allocation above (DEVICEMAP), valid out pointer. let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) }); if let Err(primary) = op { @@ -78,7 +86,7 @@ mod enabled { // SAFETY: `ptr` is the base of the live `bytes`-long host allocation, no other reference to it exists yet and // no GPU work has been enqueued; after this the whole allocation is initialized and never resized. unsafe { - std::ptr::write_bytes(ptr.cast::(), 0, bytes); + std::ptr::write_bytes(ptr.cast::(), 0, owner.bytes); } Ok(owner) } diff --git a/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs b/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs index 96b353e8..ef4f9305 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs @@ -11,23 +11,9 @@ impl Drop for QsaPromptKv<'_> { impl<'ctx> QsaPromptStage<'ctx> { pub(super) fn new(c: &'ctx Context<'ctx>) -> Result { admit(c, geometry().stage_bytes().map_err(|_| Error::BudgetExceeded)?)?; - let g = c.enter()?; - let load = Module::load( - include_bytes!("../qsa_prompt_kv.ptx"), - &[c"leleka_qsa_kv_guard", c"leleka_qsa_kv_append", c"leleka_qsa_kv_scale_guard"], - ); - let pop = g.finish(); - let module = match load { - Ok(m) => { - if let Err(e) = pop { - c.poisoned.set(true); - std::mem::forget(m); - return Err(e); - } - m - } - Err(e) => return combine(Err(e), pop), - }; + let ptx = include_bytes!("../qsa_prompt_kv.ptx"); + let entries = &[c"leleka_qsa_kv_guard", c"leleka_qsa_kv_append", c"leleka_qsa_kv_scale_guard"]; + let module = crate::qsa_prompt_attention_ffi::load_in_context(c, ptx, entries)?; let mut s = Self { context: c, pools: Pools::empty(), @@ -36,24 +22,26 @@ impl<'ctx> QsaPromptStage<'ctx> { current: None, failed: false, }; - let r = (|| { - s.pools.allocate(c, stage_runs()?)?; - s.status = Some(c.allocate(4)?); - s.pools - .table - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from(&bytes_i32((0..geometry().pages()).map(|x| x as i32))?)?; - if c.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = r { + if let Err(e) = s.allocate_all() { return combine(Err(e), s.close()); } Ok(s) } + /// The pools, the status word and the identity page table; the reserve of device memory must stay free. + fn allocate_all(&mut self) -> Result<()> { + let c = self.context; + self.pools.allocate(c, stage_runs()?)?; + self.status = Some(c.allocate(4)?); + self.pools + .table + .as_mut() + .ok_or(Error::ContextPoisoned)? + .copy_from(&bytes_i32((0..geometry().pages()).map(|x| x as i32))?)?; + if c.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + } pub fn allocated_bytes(&self) -> usize { self.pools.bytes() + self.status.as_ref().map_or(0, DeviceBuffer::len) } diff --git a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs index 3ae37bf5..5cb63ba2 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs @@ -127,6 +127,24 @@ impl<'ctx> QsaPromptKv<'ctx> { m.address(offsets[3], runs[3])?, ]) } + /// Writes the pages of `s` that `previous` (the snapshot last written) does not already hold into the mapped host. + fn write_pages(&mut self, previous: Option<&Rc>, s: &QsaKvSnapshot) -> Result<()> { + let m = self.mapped.as_mut().ok_or(Error::ContextPoisoned)?; + let offsets = offsets()?; + for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { + if previous.is_some_and(|old| { + Rc::ptr_eq(&old.origin, &s.0.origin) + && p < old.end.div_ceil(4) + && old.pages.get(p).is_some_and(|q| Rc::ptr_eq(q, page)) + }) { + continue; + } + for i in 0..4 { + m.write(offsets[i] + p * PAGE[i], &page.bytes[i])?; + } + } + Ok(()) + } pub(in super::super) fn restore(&mut self, w: &mut NativeBatchWorkspace<'ctx>, s: &QsaKvSnapshot) -> Result<()> { self.validate_snapshot(s)?; w.validate_context(self.context)?; @@ -140,20 +158,7 @@ impl<'ctx> QsaPromptKv<'ctx> { self.context.synchronize()?; let previous = self.mapped_current.take(); self.current = None; - let m = self.mapped.as_mut().ok_or(Error::ContextPoisoned)?; - let offsets = offsets()?; - for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { - if previous.as_ref().is_some_and(|old| { - Rc::ptr_eq(&old.origin, &s.0.origin) - && p < old.end.div_ceil(4) - && old.pages.get(p).is_some_and(|q| Rc::ptr_eq(q, page)) - }) { - continue; - } - for i in 0..4 { - m.write(offsets[i] + p * PAGE[i], &page.bytes[i])?; - } - } + self.write_pages(previous.as_ref(), s)?; self.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(w, self.pools.table()?)?; self.mapped_current = Some(s.0.clone()); self.current = Some(s.0.clone()); diff --git a/crates/cuda-driver/src/qsa_prompt_resolver.rs b/crates/cuda-driver/src/qsa_prompt_resolver.rs index b6c05f1d..42a7cb64 100644 --- a/crates/cuda-driver/src/qsa_prompt_resolver.rs +++ b/crates/cuda-driver/src/qsa_prompt_resolver.rs @@ -53,23 +53,9 @@ impl<'ctx> Resolver<'ctx> { if n_slots < RESOLVE_BLOCK || n_slots > i32::MAX as usize / 4 { return Err(Error::InvalidQwenShape); } - let g = c.enter()?; - let load = Module::load( - include_bytes!("qsa_prompt_resolver.ptx"), - &[c"leleka_qsa_stream_reset", c"leleka_qsa_resolve", c"leleka_qsa_miss_copy"], - ); - let pop = g.finish(); - let module = match load { - Ok(m) => { - if let Err(e) = pop { - c.poisoned.set(true); - std::mem::forget(m); - return Err(e); - } - m - } - Err(e) => return combine(Err(e), pop), - }; + let ptx = include_bytes!("qsa_prompt_resolver.ptx"); + let entries = &[c"leleka_qsa_stream_reset", c"leleka_qsa_resolve", c"leleka_qsa_miss_copy"]; + let module = crate::qsa_prompt_attention_ffi::load_in_context(c, ptx, entries)?; let mut o = Self { context: c, slots: [None, None, None, None, None], @@ -79,18 +65,20 @@ impl<'ctx> Resolver<'ctx> { n_slots, failed: false, }; - let r = (|| { - for b in &mut o.slots { - *b = Some(c.allocate(n_slots * 4)?); - } - o.ctl = Some(c.allocate(CTL_BYTES)?); - Ok(()) - })(); - if let Err(e) = r { + if let Err(e) = o.allocate_all() { return combine(Err(e), o.close()); } Ok(o) } + /// The five slot arrays and the control block. + fn allocate_all(&mut self) -> Result<()> { + let (c, n_slots) = (self.context, self.n_slots); + for b in &mut self.slots { + *b = Some(c.allocate(n_slots * 4)?); + } + self.ctl = Some(c.allocate(CTL_BYTES)?); + Ok(()) + } pub(crate) fn bytes(&self) -> usize { self.slots.iter().flatten().map(DeviceBuffer::len).sum::() + self.ctl.as_ref().map_or(0, DeviceBuffer::len) @@ -177,6 +165,23 @@ impl<'ctx> Resolver<'ctx> { self.epoch = 0; Ok(()) } + /// The miss-copy kernel arguments: control block, the two newest slot arrays, then the host and resident pools. + fn copy_arguments(&self, host: [u64; 4], resident: [u64; 4]) -> Result> { + let mut copy = Vec::new(); + copy.try_reserve_exact(11).map_err(|_| Error::HostAllocation)?; + copy.push(Arg::U64(checked(self.context, self.ctl.as_ref().ok_or(Error::ContextPoisoned)?, CTL_BYTES)?)); + for i in 3..5 { + copy.push(Arg::U64(checked( + self.context, + self.slots[i].as_ref().ok_or(Error::ContextPoisoned)?, + self.n_slots * 4, + )?)); + } + for x in host.into_iter().chain(resident) { + copy.push(Arg::U64(x)); + } + Ok(copy) + } /// Guarded Q/IDs/steps must already be completed and shape-checked. The selections name whole /// 4-cell blocks plus the partial one, so one query touches at most `BLOCKS_PER_QUERY` blocks and /// T<=3 queries at most 1542 (`kv_stream_resolve`'s `n_q x (cap / page_size + 2)` bound), below the @@ -198,19 +203,7 @@ impl<'ctx> Resolver<'ctx> { let mut a = self.addresses(table)?; a.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; a.extend([Arg::U64(ids), Arg::U64(steps), Arg::I32(t as i32), Arg::I64(self.n_slots as i64)]); - let mut copy = Vec::new(); - copy.try_reserve_exact(11).map_err(|_| Error::HostAllocation)?; - copy.push(Arg::U64(checked(self.context, self.ctl.as_ref().ok_or(Error::ContextPoisoned)?, CTL_BYTES)?)); - for i in 3..5 { - copy.push(Arg::U64(checked( - self.context, - self.slots[i].as_ref().ok_or(Error::ContextPoisoned)?, - self.n_slots * 4, - )?)); - } - for x in host.into_iter().chain(resident) { - copy.push(Arg::U64(x)); - } + let copy = self.copy_arguments(host, resident)?; let a = Arguments::new(a)?; let copy = Arguments::new(copy)?; // all ABI allocations before first table mutation self.run(w, 1, [1, 1, 1], 1024, a)?; diff --git a/crates/cuda-driver/src/qsa_resident_attention.rs b/crates/cuda-driver/src/qsa_resident_attention.rs index c844876b..d83610df 100644 --- a/crates/cuda-driver/src/qsa_resident_attention.rs +++ b/crates/cuda-driver/src/qsa_resident_attention.rs @@ -1,4 +1,5 @@ //! Same literal attention on the real selected query/IDs/steps/attn arena. +use super::impl_qsapromptattention::{AttnPasses, KernelPlan, admit_budget}; use super::*; impl<'ctx> QsaPromptAttention<'ctx> { pub(crate) fn attend_resident_arena( @@ -11,12 +12,8 @@ impl<'ctx> QsaPromptAttention<'ctx> { ) -> Result<()> { let t = inputs.rows(); // Original qsa_prompt_attn_batch kernel choice (see qsa_prompt_attention_select): v2 unless the debug arm. - let (variants, guard_ix, attn_ix, scan_ix, shared) = match self.selected_kernel()? { - PromptAttnKernel::Int8V2 => (false, 0, 1, 2, PromptAttnKernel::Int8V2.smem_bytes()), - PromptAttnKernel::Int8V1 => (true, 0, 1, 4, PromptAttnKernel::Int8V1.smem_bytes()), - PromptAttnKernel::Fp16 | PromptAttnKernel::HybridK8V4 => return Err(Error::UnsupportedQwenOperation), - }; - if variants { + let plan = KernelPlan::of(self.selected_kernel()?)?; + if plan.variants { self.ensure_variants()?; } self.validate_resident()?; @@ -26,60 +23,11 @@ impl<'ctx> QsaPromptAttention<'ctx> { return Err(Error::InvalidQwenShape); } let (hq, hi, hs, out_h) = inputs.attention_spans(self.context)?; - let (qh, ih, sh) = (hq.qwen_address(), hi.qwen_address(), hs.qwen_address()); - for (h, n) in [(hq, t * 6144 * 4), (hi, t * 2051 * 4), (hs, t * 16), (out_h, t * 6144 * 4)] { - stage.reject_span(h, n)?; - w.reject_alias(h, n)?; - for b in self.output.iter().chain(self.status.iter()) { - if h.overlaps(n, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) { - return Err(Error::OutputAliasesInput); - } - } - } + self.reject_span_aliases(w, t, [hq, hi, hs, out_h], |h, n| stage.reject_span(h, n))?; let (pools, table, end) = kv.completed_addresses(stage, snapshot, inputs)?; - self.status.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0; 4])?; - let status = checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; - let out = out_h.qwen_address(); - // Pre-admission scan and fence are mandatory before selected IDs can address pools. - let guard = Arguments::new(vec![ - Arg::U64(qh), - Arg::U64(ih), - Arg::U64(sh), - Arg::I32(t as i32), - Arg::I32(2051), - Arg::I32(end as i32), - Arg::U64(status), - ])?; - self.run_resident(variants, w, guard_ix, [crate::qsa_prompt_attention::guard_grid(t), 1, 1], 256, 0, guard)?; - let flags = self.flags()?; - if flags & 2 != 0 { - return Err(Error::InvalidQwenShape); - } - if flags & 1 != 0 { - return Err(Error::InvalidQ8Activation); - } - let args = Arguments::new(vec![ - Arg::U64(qh), - Arg::U64(pools[0]), - Arg::U64(pools[1]), - Arg::U64(pools[2]), - Arg::U64(pools[3]), - Arg::U64(table), - Arg::U64(ih), - Arg::U64(sh), - Arg::I32(2), - Arg::I32(4), - Arg::F32(1.442_695_0_f32 / 16.0), - Arg::U64(out), - Arg::I32(2051), - ])?; - self.run_resident(variants, w, attn_ix, [t as u32, 2, 1], 128, shared, args)?; - let scan = Arguments::new(vec![Arg::U64(out), Arg::I32((t * 6144) as i32), Arg::U64(status)])?; - self.run_resident(variants, w, scan_ix, [crate::qsa_prompt_attention::guard_grid(t), 1, 1], 256, 0, scan)?; - if self.flags()? != 0 { - return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention")); - } - Ok(()) + let status = self.zero_status()?; + let addrs = [hq.qwen_address(), hi.qwen_address(), hs.qwen_address(), out_h.qwen_address(), status]; + self.run_passes(w, &plan, &AttnPasses { addrs, pools, table, end, t }, Self::run_resident) } } @@ -135,55 +83,24 @@ impl<'ctx> QsaPromptAttention<'ctx> { if c.is_poisoned() { return Err(Error::ContextPoisoned); } - let output_bytes = 0usize; - let n = output_bytes.checked_add(4 + 128 * 1024 * 1024).ok_or(Error::BudgetExceeded)?; - if c.allocated_bytes().checked_add(n).is_none_or(|x| x > c.budget) || c.memory_info()?.0 < n { - return Err(Error::BudgetExceeded); - } - let g = c.enter().map_err(|e| { - c.poison(); - c.retain_driver(); - e - })?; - let load = Module::load( - include_bytes!("qsa_prompt_attention.ptx"), - &[c"leleka_qsa_prompt_guard", c"leleka_qsa_prompt_attn", c"leleka_qsa_prompt_output_guard"], - ); - let pop = g.finish(); - let m = match load { - Ok(m) => { - if let Err(e) = pop { - c.poison(); - c.retain_driver(); - std::mem::forget(m); - return Err(e); - } - m - } - Err(e) => return combine(Err(e), pop), - }; - let mut o = Self { - capacity, - context: c, - output: None, - status: None, - module: Some(m), - variants: None, - switches: Default::default(), - failed: false, - }; - let r = (|| { - o.status = Some(c.allocate(4)?); - if c.memory_info()?.0 < 128 * 1024 * 1024 { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = r { + admit_budget(c, 0)?; + let m = load_resident_module(c)?; + let mut o = Self::with_module(c, capacity, m); + if let Err(e) = o.allocate_buffers(None) { return combine(Err(e), o.close()); } Ok(o) } + /// Enters the context; a failure marks both owners failed, poisons the context and retains the driver. + fn enter_or_fail(&mut self, w: &mut NativeBatchWorkspace<'ctx>) -> Result> { + self.context.enter().map_err(|e| { + self.failed = true; + w.mark_failed(); + self.context.poison(); + self.context.retain_driver(); + e + }) + } #[allow(clippy::too_many_arguments)] fn run_resident( &mut self, @@ -197,19 +114,9 @@ impl<'ctx> QsaPromptAttention<'ctx> { ) -> Result<()> { self.validate_resident()?; w.validate_context(self.context)?; - let g = self.context.enter().map_err(|e| { - self.failed = true; - w.mark_failed(); - self.context.poison(); - self.context.retain_driver(); - e - })?; + let g = self.enter_or_fail(w)?; let dependency = self.context.driver.api.synchronize(); - let op = dependency.and_then(|()| { - (if variants { self.variants.as_ref() } else { self.module.as_ref() }) - .ok_or(Error::ContextPoisoned)? - .launch(index, grid, block, shared, w.blas()?.stream(), &mut a) - }); + let op = dependency.and_then(|()| self.launch_variant(variants, w, (index, grid, block, shared), &mut a)); let sync = w.blas()?.synchronize(); let pop = g.finish(); if sync.is_err() || pop.is_err() { @@ -226,56 +133,38 @@ impl<'ctx> QsaPromptAttention<'ctx> { } impl QsaPromptAttention<'_> { + /// Unloads a module inside the context; any failure poisons the context and retains the driver. + fn close_resident_module(&self, module: Module) -> Result<()> { + if self.context.is_poisoned() { + std::mem::forget(module); + return Err(Error::ContextPoisoned); + } + match self.context.enter() { + Ok(guard) => { + let unload = module.close(); + let pop = guard.finish(); + if unload.is_err() || pop.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + combine(unload, pop) + } + Err(error) => { + self.context.poison(); + self.context.retain_driver(); + std::mem::forget(module); + Err(error) + } + } + } fn close_resident(&mut self) -> Result<()> { self.failed = true; let mut result = Ok(()); if let Some(module) = self.module.take() { - if self.context.is_poisoned() { - std::mem::forget(module); - result = Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(guard) => { - let unload = module.close(); - let pop = guard.finish(); - if unload.is_err() || pop.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - result = combine(unload, pop); - } - Err(error) => { - self.context.poison(); - self.context.retain_driver(); - std::mem::forget(module); - result = Err(error) - } - } - } + result = self.close_resident_module(module); } if let Some(module) = self.variants.take() { - if self.context.is_poisoned() { - std::mem::forget(module); - result = combine(result, Err(Error::ContextPoisoned)) - } else { - match self.context.enter() { - Ok(guard) => { - let unload = module.close(); - let pop = guard.finish(); - if unload.is_err() || pop.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - result = combine(result, combine(unload, pop)); - } - Err(error) => { - self.context.poison(); - self.context.retain_driver(); - std::mem::forget(module); - result = combine(result, Err(error)) - } - } - } + result = combine(result, self.close_resident_module(module)); } for slot in [&mut self.status, &mut self.output] { if let Some(buffer) = slot.take() { @@ -295,3 +184,30 @@ impl Drop for OriginalQsaResidentAttention<'_> { let _ = self.inner.close_resident(); } } + +/// Enters the context and loads the prompt attention module there; any failure poisons the context and retains the +/// driver. +fn load_resident_module(c: &Context<'_>) -> Result { + let g = c.enter().map_err(|e| { + c.poison(); + c.retain_driver(); + e + })?; + let load = Module::load( + include_bytes!("qsa_prompt_attention.ptx"), + &[c"leleka_qsa_prompt_guard", c"leleka_qsa_prompt_attn", c"leleka_qsa_prompt_output_guard"], + ); + let pop = g.finish(); + match load { + Ok(m) => { + if let Err(e) = pop { + c.poison(); + c.retain_driver(); + std::mem::forget(m); + return Err(e); + } + Ok(m) + } + Err(e) => combine(Err(e), pop), + } +} diff --git a/crates/cuda-driver/src/qsa_resident_decode.rs b/crates/cuda-driver/src/qsa_resident_decode.rs index 8ea4af55..2d99d4cf 100644 --- a/crates/cuda-driver/src/qsa_resident_decode.rs +++ b/crates/cuda-driver/src/qsa_resident_decode.rs @@ -16,107 +16,15 @@ impl<'ctx> QsaNativeDecode<'ctx> { snapshot: &'loan OriginalQsaMappedPrefix, inputs: &QsaAttentionInputs<'_, '_>, ) -> Result> { - let (q, ids, steps, t) = (inputs.q, inputs.ids, inputs.steps, inputs.t); + let (ids, steps, t) = (inputs.ids, inputs.steps, inputs.t); self.validate()?; w.validate_context(self.context)?; kv.validate_context(self.context)?; kv.validate_prefix(snapshot)?; - if !(1..=3).contains(&t) { - return Err(Error::InvalidQwenShape); - } - let qh = checked(self.context, q, t * 6144 * 4)?; - let ih = checked(self.context, ids, t * 2051 * 4)?; - let sh = checked(self.context, steps, t * 4 * 4)?; - for b in [q, ids, steps] { - kv.reject_alias(b)?; - w.reject_alias(b.handle.ok_or(Error::ContextPoisoned)?, b.bytes)?; - for own in self.output.iter().chain(self.status.iter()).chain(self.scratch.iter()) { - if own.handle.ok_or(Error::ContextPoisoned)?.overlaps( - own.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - for a in [q, ids, steps] { - for b in [q, ids, steps] { - if !std::ptr::eq(a, b) - && a.handle.ok_or(Error::ContextPoisoned)?.overlaps( - a.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) - { - return Err(Error::OutputAliasesInput); - } - } - } - let end = snapshot.next_position(); - self.status.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0; 4])?; - let status = checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; - let out = - self.output.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); - // Pre-admission scan and fence are mandatory before selected IDs can address pools. - let guard = Arguments::new(vec![ - Arg::U64(qh), - Arg::U64(ih), - Arg::U64(sh), - Arg::I32(t as i32), - Arg::I32(2051), - Arg::I32(end as i32), - Arg::U64(status), - ])?; - self.run(w, 0, [64, 1, 1], 256, 0, guard)?; - let flags = self.flags()?; - if flags & 2 != 0 { - return Err(Error::InvalidQwenShape); - } - if flags & 1 != 0 { - return Err(Error::InvalidQ8Activation); - } + let handles = self.admit_inputs(w, inputs, |b| kv.reject_alias(b))?; + let (status, out) = self.guard_pass(w, handles, (t, snapshot.next_position()))?; let (pools, table, _) = kv.resolved_addresses(w, snapshot, ids, steps, t)?; - let scratch = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; - let handle = scratch.handle.ok_or(Error::ContextPoisoned)?; - let pa = handle.qwen_address(); - let pm = handle.checked_subspan(scratch.bytes, 811008, 3168)?.qwen_address(); - let pl = handle.checked_subspan(scratch.bytes, 814176, 3168)?.qwen_address(); - // Each query owns817600B; internal checked offsets mirror original single scratch layout. - let args = Arguments::new(vec![ - Arg::U64(qh), - Arg::U64(pools[0]), - Arg::U64(pools[1]), - Arg::U64(pools[2]), - Arg::U64(pools[3]), - Arg::U64(table), - Arg::U64(ih), - Arg::U64(sh), - Arg::I32(2), - Arg::I32(4), - Arg::F32(1.0 / 16.0), - Arg::U64(pa), - Arg::U64(pm), - Arg::U64(pl), - Arg::I32(33), - Arg::I32(2051), - Arg::I64(204400), - ])?; - self.run(w, 1, [33, 2, t as u32], 256, 0, args)?; - let merge = Arguments::new(vec![ - Arg::U64(pa), - Arg::U64(pm), - Arg::U64(pl), - Arg::I32(33), - Arg::U64(out), - Arg::I64(204400), - ])?; - self.run(w, 2, [24, t as u32, 1], 256, 0, merge)?; - let scan = Arguments::new(vec![Arg::U64(out), Arg::I32((t * 6144) as i32), Arg::U64(status)])?; - self.run(w, 3, [64, 1, 1], 256, 0, scan)?; - if self.flags()? != 0 { - return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention")); - } + self.attention_passes(w, (pools, table), handles, (status, out, t))?; Ok(OriginalQsaResidentDecodeCompletion { owner: self, _kv: kv, _snapshot: snapshot, t }) } } From d9166c4fb55d928eec722dadd346832cf3eb0679 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 22:52:07 +0100 Subject: [PATCH 2/2] STRA-338 size2 cd6: remaining over-long fns of the slice are cut (gpu proofs, mapped journal append, stage run, late/queue cases) --- .../src/ple_batch_ffi/enabled/impl_blas.rs | 6 +- .../cuda-driver/src/ple_closed_queue_gpu.rs | 82 ++++-- .../gdn_recurrence_equals_the_original.rs | 5 +- .../gdn_stage_kernels_equal.rs | 51 ++-- crates/cuda-driver/src/prefill_stage_gpu.rs | 44 +-- .../gr_fused_guards_equal.rs | 47 ++-- crates/cuda-driver/src/qsa_late_gpu.rs | 259 ++++++++++-------- .../impl_originalqsamappedjournal.rs | 25 +- .../impl_originalqsamappedjournal_2.rs | 4 +- .../impl_drop_for_qsapromptkv.rs | 19 +- 10 files changed, 307 insertions(+), 235 deletions(-) diff --git a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs index 9741d4d5..86c71169 100644 --- a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs +++ b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs @@ -26,10 +26,8 @@ impl Blas { _driver: Some(driver), _vendor: Some(vendor), }; - let result = owner.init_handle( - HandleSymbols { stream_create, create, set_stream, set_workspace, set_math }, - (workspace, bytes), - ); + let symbols = HandleSymbols { stream_create, create, set_stream, set_workspace, set_math }; + let result = owner.init_handle(symbols, (workspace, bytes)); if let Err(e) = result { return combine(Err(e), owner.close()); } diff --git a/crates/cuda-driver/src/ple_closed_queue_gpu.rs b/crates/cuda-driver/src/ple_closed_queue_gpu.rs index aace4d54..68565083 100644 --- a/crates/cuda-driver/src/ple_closed_queue_gpu.rs +++ b/crates/cuda-driver/src/ple_closed_queue_gpu.rs @@ -223,6 +223,17 @@ fn tiny_budget_refused(device: &Device<'_>) { assert_eq!(allocated, 0); assert!(closed.is_ok()); } +/// The six weights: key, value, three aux norms and the convolution. +fn upload_weights<'c>(context: &'c Context<'c>, weights: &mut Vec>) -> Result<()> { + weights.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?; + weights.push(upload(context, &bf16(10240 * 2560, 2))?); + weights.push(upload(context, &bf16(2560 * 2560, 3))?); + for _ in 0..3 { + weights.push(upload(context, &float_staging(&vec![1.0; 10240])?)?); + } + weights.push(upload(context, &bf16(4 * 10240, 4))?); + Ok(()) +} /// The weights, the queue and the foreign weight stay owned by the caller so it can release them on any error. fn queue_cases<'c>( context: &'c Context<'c>, @@ -233,13 +244,7 @@ fn queue_cases<'c>( &mut Option>, ), ) -> Result { - weights.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?; - weights.push(upload(context, &bf16(10240 * 2560, 2))?); - weights.push(upload(context, &bf16(2560 * 2560, 3))?); - for _ in 0..3 { - weights.push(upload(context, &float_staging(&vec![1.0; 10240])?)?); - } - weights.push(upload(context, &bf16(4 * 10240, 4))?); + upload_weights(context, weights)?; *queue = Some(context.ple_closed_queue()?); let q = queue.as_mut().ok_or(Error::ContextPoisoned)?; let mut tally = Tally::default(); @@ -252,6 +257,12 @@ fn queue_cases<'c>( invalid_input_cases(q, weights, inputs, &mut tally); *foreign_weight = Some(foreign.allocate(1024)?); foreign_weight_case(q, weights, foreign_weight.as_ref().ok_or(Error::ContextPoisoned)?, inputs, &mut tally); + alias_refused_and_status_unchanged(q, &before, &mut tally)?; + Ok(tally) +} +/// A weight view of the queue's own buffer is refused, and the status buffer still holds what it held before the +/// refusals. +fn alias_refused_and_status_unchanged(q: &mut PleClosedQueue<'_>, before: &[u32], tally: &mut Tally) -> Result<()> { if !matches!(q.weight(q.buffer(0)?, 10240, 4), Err(Error::OutputAliasesInput)) { tally.differences += 1; } @@ -259,7 +270,7 @@ fn queue_cases<'c>( if read(q.buffer(12)?)? != before { tally.differences += 1; } - Ok(tally) + Ok(()) } /// Four causal rows: each candidate history must equal the original complete history first. Returns the last one. fn causal_history_cases<'c>( @@ -290,8 +301,19 @@ fn causal_history_cases<'c>( } Ok(history) } -/// A non-finite or oversized element in each weight is refused alike by the original and the queue, and the restored -/// weight gives identical products again. +/// A non-finite or oversized element (weight index, byte offset, bytes) in each weight. +fn corruptions() -> [(usize, usize, Vec); 6] { + [ + (0, 52_428_798, vec![0x80, 0x7f]), + (1, 13_107_198, vec![0x80, 0x7f]), + (2, 40956, f32::NAN.to_le_bytes().to_vec()), + (3, 40956, f32::INFINITY.to_le_bytes().to_vec()), + (4, 40956, f32::NAN.to_le_bytes().to_vec()), + (5, 81918, vec![0xc0, 0x7f]), + ] +} +/// A corrupted weight is refused alike by the original and the queue, and the restored weight gives identical +/// products again. fn corrupted_weight_cases<'c>( context: &Context<'_>, q: &mut PleClosedQueue<'c>, @@ -299,14 +321,7 @@ fn corrupted_weight_cases<'c>( (embedding, streams, history): (&[f32], &[f32], &[f32]), tally: &mut Tally, ) -> Result<()> { - for (weight, offset, bytes) in [ - (0, 52_428_798, vec![0x80, 0x7f]), - (1, 13_107_198, vec![0x80, 0x7f]), - (2, 40956, f32::NAN.to_le_bytes().to_vec()), - (3, 40956, f32::INFINITY.to_le_bytes().to_vec()), - (4, 40956, f32::NAN.to_le_bytes().to_vec()), - (5, 81918, vec![0xc0, 0x7f]), - ] { + for (weight, offset, bytes) in corruptions() { let mut saved = staging(weights[weight].bytes)?; weights[weight].copy_to(&mut saved)?; weights[weight].copy_from_range(offset, &bytes)?; @@ -317,19 +332,30 @@ fn corrupted_weight_cases<'c>( } tally.guards += 1; weights[weight].copy_from(&saved)?; - let old = original(context, refs(weights), embedding, streams, history)?; - let (refusal, products) = queued(q, refs(weights), embedding, streams, history)?; - if refusal.is_some() || old.refusal.is_some() { - tally.differences += 1; - } - for (a, b) in old.products.iter().zip(products) { - tally.words += a.len(); - tally.differences += a.iter().zip(b).filter(|(a, b)| **a != *b).count(); - } - tally.guards += 1; + restored_weight_case(context, q, weights, (embedding, streams, history), tally)?; } Ok(()) } +/// With the weight restored the original and the queue give identical, finite products again. +fn restored_weight_case<'c>( + context: &Context<'_>, + q: &mut PleClosedQueue<'c>, + weights: &[DeviceBuffer<'_>], + (embedding, streams, history): (&[f32], &[f32], &[f32]), + tally: &mut Tally, +) -> Result<()> { + let old = original(context, refs(weights), embedding, streams, history)?; + let (refusal, products) = queued(q, refs(weights), embedding, streams, history)?; + if refusal.is_some() || old.refusal.is_some() { + tally.differences += 1; + } + for (a, b) in old.products.iter().zip(products) { + tally.words += a.len(); + tally.differences += a.iter().zip(b).filter(|(a, b)| **a != *b).count(); + } + tally.guards += 1; + Ok(()) +} /// Whether the queue composes these weights with `key` as the key weight. fn composes( q: &mut PleClosedQueue<'_>, diff --git a/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_recurrence_equals_the_original.rs b/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_recurrence_equals_the_original.rs index a9dd6183..7cbfae34 100644 --- a/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_recurrence_equals_the_original.rs +++ b/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_recurrence_equals_the_original.rs @@ -46,11 +46,10 @@ struct RecBuffers<'c> { } impl<'c> RecBuffers<'c> { - /// `variant`: 0 clean, 1 an infinite state value, 2 a NaN in the input, 3 products that overflow. + /// `variant`: 0 clean, 1 an infinite state value, 2 a NaN in the input, 3 products that overflow. The q/k rows are + /// L2-normalised in the real chain; they are kept O(1/sqrt(S)) here so the state stays bounded over the chunk. fn new(context: &'c Context<'c>, rng: &mut Rng, t: usize, variant: u8) -> Self { let mut state: Vec = (0..STATE_LEN).map(|_| rng.f(0.05)).collect(); - // q/k rows are L2-normalised in the real chain; keep them O(1/sqrt(S)) so the state stays bounded over the - // chunk let mut h: Vec = (0..t * 10240).map(|_| rng.f(0.2)).collect(); let gate: Vec = (0..t * 48).map(|_| -rng.f(0.6).abs()).collect(); let beta: Vec = (0..t * 48).map(|_| (rng.f(0.5) + 0.5).abs()).collect(); diff --git a/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_stage_kernels_equal.rs b/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_stage_kernels_equal.rs index 8e558a08..34f11c76 100644 --- a/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_stage_kernels_equal.rs +++ b/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_stage_kernels_equal.rs @@ -156,6 +156,37 @@ fn conv_inputs(rng: &mut Rng, case: usize) -> (Vec, Vec, Vec) { (hist, qkv, w) } +/// The Original's tiled convolution of `qkv` through the history `hist` with weights `w` into `out`. +fn conv_old_launch( + (hist_d, qkv_d, w_d, out): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>), +) -> OldLaunch { + let args = vec![ + ffi::KernelArg::Pointer(hd(hist_d)), + ffi::KernelArg::Pointer(hd(qkv_d)), + ffi::KernelArg::Pointer(hd(w_d)), + ffi::KernelArg::Pointer(hd(out)), + ffi::KernelArg::I64(T as i64), + ]; + (Kernel::ConvTiled, [80, T.div_ceil(64) as u32, 1], [128, 1, 1], args) +} + +/// The staged convolution with its QKV and conv guards writing two status words. +fn conv_new_launch( + (hist_d, qkv_d, w_d, out): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>), + status: &DeviceBuffer<'_>, +) -> (usize, u32, Vec) { + let args = vec![ + A::Address(hd(hist_d)), + A::Address(hd(qkv_d)), + A::Address(hd(w_d)), + A::Address(hd(out)), + A::I64(T as i64), + A::Address(status_word(status, 0)), + A::Address(status_word(status, 1)), + ]; + (crate::prefill_stage::GDN_CONV_TILED, 40 * T.div_ceil(64) as u32, args) +} + /// The convolution (with its QKV and conv guards) of the staged kernel equals the Original's. fn conv_stage<'c>(rig: &Rig<'c>, rng: &mut Rng, case: usize) -> ConvOut<'c> { let (context, t) = (rig.context, T); @@ -165,28 +196,12 @@ fn conv_stage<'c>(rig: &Rig<'c>, rng: &mut Rng, case: usize) -> ConvOut<'c> { let (h_old, h_new) = (upload(context, &zero), upload(context, &zero)); let status_old = upload(context, &[0u8; 64]); let status_new = upload(context, &[0u8; 64]); - let args = vec![ - ffi::KernelArg::Pointer(hd(&hist_d)), - ffi::KernelArg::Pointer(hd(&qkv_d)), - ffi::KernelArg::Pointer(hd(&w_d)), - ffi::KernelArg::Pointer(hd(&h_old)), - ffi::KernelArg::I64(t as i64), - ]; rig.old.run(vec![ - (Kernel::ConvTiled, [80, t.div_ceil(64) as u32, 1], [128, 1, 1], args), + conv_old_launch((&hist_d, &qkv_d, &w_d, &h_old)), scan_launch(&qkv_d, &status_old, t * 10240, 0), scan_launch(&h_old, &status_old, t * 10240, 1), ]); - let args = vec![ - A::Address(hd(&hist_d)), - A::Address(hd(&qkv_d)), - A::Address(hd(&w_d)), - A::Address(hd(&h_new)), - A::I64(t as i64), - A::Address(status_word(&status_new, 0)), - A::Address(status_word(&status_new, 1)), - ]; - let launch = (crate::prefill_stage::GDN_CONV_TILED, 40 * t.div_ceil(64) as u32, args); + let launch = conv_new_launch((&hist_d, &qkv_d, &w_d, &h_new), &status_new); run_stage(context, rig.stream, &rig.stage, vec![launch]); assert_eq!(download(&h_old, t * 10240 * 4), download(&h_new, t * 10240 * 4), "case {case}: conv output"); assert_eq!(words(&status_old, 2), words(&status_new, 2), "case {case}: conv status words (qkv, conv)"); diff --git a/crates/cuda-driver/src/prefill_stage_gpu.rs b/crates/cuda-driver/src/prefill_stage_gpu.rs index 160f9630..698b5cc3 100644 --- a/crates/cuda-driver/src/prefill_stage_gpu.rs +++ b/crates/cuda-driver/src/prefill_stage_gpu.rs @@ -86,13 +86,8 @@ fn packet_records(rng: &mut Rng) -> Vec { records } -/// The reference: the fixed per-token kernels, 16 rows per call. Returns the decoded values and the scatter cache, -/// which stays allocated for the rest of the test. -fn per_token_reference<'c>( - context: &'c Context<'c>, - books: &DeviceBuffer<'c>, - (records, slots): (&[u8], &[u32]), -) -> (Vec, DeviceBuffer<'c>) { +/// The fixed per-token scatter of all records, 16 per call, into a fresh 64 MiB cache. +fn scatter_records<'c>(context: &'c Context<'c>, records: &[u8]) -> DeviceBuffer<'c> { let mut old_cache = context.allocate(64 << 20).expect("old cache"); for group in records.chunks(16 * 56) { let mut updates = context.allocate(16 * 56).expect("updates"); @@ -106,6 +101,17 @@ fn per_token_reference<'c>( context.kar_ple_scatter(&mut old_cache, &updates, 16).expect("old scatter"); updates.release().expect("release"); } + old_cache +} + +/// The reference: the fixed per-token kernels, 16 rows per call. Returns the decoded values and the scatter cache, +/// which stays allocated for the rest of the test. +fn per_token_reference<'c>( + context: &'c Context<'c>, + books: &DeviceBuffer<'c>, + (records, slots): (&[u8], &[u32]), +) -> (Vec, DeviceBuffer<'c>) { + let old_cache = scatter_records(context, records); let mut reference = Vec::::new(); for position in 0..T { let mut slot_bytes = Vec::new(); @@ -194,6 +200,19 @@ fn stage_owners<'c>(context: &'c Context<'c>) -> StageOwners<'c> { } } +/// R rows: four copies of the selected embedding row. +fn assert_r_rows(residual: &mut OriginalDeviceResidual<'_, '_, '_>, staged: &Staged) { + for row in [0usize, 1, 57, T - 1] { + let streams = residual.read_prompt_row(row).expect("R row"); + let source = &staged.embedding[staged.index[row] as usize * 2560..][..2560]; + for stream in 0..4 { + for (i, v) in streams[stream * 2560..][..2560].iter().enumerate() { + assert_eq!(v.to_bits(), source[i].to_bits(), "row {row} stream {stream} value {i}"); + } + } + } +} + /// `initialize_staged` fills R with four copies of the selected embedding row and the PLE span bit-identical to the /// per-token decode. fn check_staged_equals_reference<'c>( @@ -209,16 +228,7 @@ fn check_staged_equals_reference<'c>( (&staged.records, &staged.slots), ); let mut residual = owners.prompt.initialize_staged(lease, &mut owners.workspace, input).expect("initialize_staged"); - // R rows: four copies of the selected embedding row - for row in [0usize, 1, 57, T - 1] { - let streams = residual.read_prompt_row(row).expect("R row"); - let source = &staged.embedding[staged.index[row] as usize * 2560..][..2560]; - for stream in 0..4 { - for (i, v) in streams[stream * 2560..][..2560].iter().enumerate() { - assert_eq!(v.to_bits(), source[i].to_bits(), "row {row} stream {stream} value {i}"); - } - } - } + assert_r_rows(&mut residual, staged); // PLE embedding span: bit-identical to the per-token decode let (handle, span_bytes) = residual.lease().common_span(S::PleEmbedding).expect("ple span"); let raw = read(context, handle, T * 10240); diff --git a/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_fused_guards_equal.rs b/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_fused_guards_equal.rs index 83493593..596acce8 100644 --- a/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_fused_guards_equal.rs +++ b/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_fused_guards_equal.rs @@ -131,6 +131,13 @@ fn norm_phase<'c>(rig: &GrRig<'c>, host: &Host, case: usize) -> NormOut<'c> { NormOut { r_old, r_new, w, rs_o, rs_n, fl_n } } +/// `mix_r` arguments over R, the row scales, gamma, g and the three mixed outputs; the fused flags word when `flags`. +fn mix_args([r, rs, w, g, mx, m16, mh]: [&DeviceBuffer<'_>; 7], flags: Option<&DeviceBuffer<'_>>) -> Vec { + let mut args = vec![a(r), a(rs), a(w), a(g), a(mx), a(m16), A::I64(T as i64), a(mh), A::NullAddress]; + args.extend(flags.map(a)); + args +} + /// Mix (uses the row scales of the norm phase); returns the staged flags. fn mix_phase<'c>(rig: &GrRig<'c>, host: &Host, norm: &NormOut<'c>, case: usize) -> DeviceBuffer<'c> { let (c, t, gr, stage) = (rig.context, T, &rig.gr, &rig.stage); @@ -140,20 +147,8 @@ fn mix_phase<'c>(rig: &GrRig<'c>, host: &Host, norm: &NormOut<'c>, case: usize) let (fl2_o, fl2_n) = (zeros(c, FLAGS_LEN), zeros(c, FLAGS_LEN)); let NormOut { r_old, r_new, w, rs_o, rs_n, .. } = norm; let rows = (t * 10240).div_ceil(256); - let mix_old = - vec![a(r_old), a(rs_o), a(w), a(&g_dev), a(&mx_o), a(&m16_o), A::I64(t as i64), a(&mh_o), A::NullAddress]; - let mix_new = vec![ - a(r_new), - a(rs_n), - a(w), - a(&g_dev), - a(&mx_n), - a(&m16_n), - A::I64(t as i64), - a(&mh_n), - A::NullAddress, - a(&fl2_n), - ]; + let mix_old = mix_args([r_old, rs_o, w, &g_dev, &mx_o, &m16_o, &mh_o], None); + let mix_new = mix_args([r_new, rs_n, w, &g_dev, &mx_n, &m16_n, &mh_n], Some(&fl2_n)); rig.run(vec![ (gr, 2, (t * 2560).div_ceil(256), 256, mix_old), (gr, 7, rows, 256, vec![a(r_old), a(rs_o), a(w), a(&g_dev), a(&fl2_o), A::I64(t as i64)]), @@ -168,6 +163,14 @@ fn mix_phase<'c>(rig: &GrRig<'c>, host: &Host, norm: &NormOut<'c>, case: usize) fl2_n } +/// Fused write + next norm arguments over R, bo, the injection, gamma, the row scales and xn16; the fused flags word +/// when `flags`. +fn write_args([r, bo, inj, w, rs, xn]: [&DeviceBuffer<'_>; 6], flags: Option<&DeviceBuffer<'_>>) -> Vec { + let mut args = vec![a(r), a(bo), a(inj), A::I64(4), a(w), A::F32(EPS), a(rs), a(xn), A::NullAddress]; + args.extend(flags.map(a)); + args +} + /// Fused write + next norm; returns the staged flags and the uploaded bo and injection the plain write reuses. fn write_phase<'c>( rig: &GrRig<'c>, @@ -181,20 +184,8 @@ fn write_phase<'c>( let (rs2_o, rs2_n, xn2_o, xn2_n) = (zeros(c, t * 16), zeros(c, t * 16), zeros(c, t * 20480), zeros(c, t * 20480)); let (fl3_o, fl3_n) = (zeros(c, FLAGS_LEN), zeros(c, FLAGS_LEN)); let rows = (t * 10240).div_ceil(256); - let write_old = - vec![a(&rw_o), a(&bo_d), a(&inj_d), A::I64(4), a(w), A::F32(EPS), a(&rs2_o), a(&xn2_o), A::NullAddress]; - let write_new = vec![ - a(&rw_n), - a(&bo_d), - a(&inj_d), - A::I64(4), - a(w), - A::F32(EPS), - a(&rs2_n), - a(&xn2_n), - A::NullAddress, - a(&fl3_n), - ]; + let write_old = write_args([&rw_o, &bo_d, &inj_d, w, &rs2_o, &xn2_o], None); + let write_new = write_args([&rw_n, &bo_d, &inj_d, w, &rs2_n, &xn2_n], Some(&fl3_n)); rig.run(vec![ (gr, 8, t * 4, 256, write_old), (gr, 4, rows, 256, vec![a(&rw_o), a(&fl3_o), A::I64(10240), A::I64(t as i64), A::U32(7)]), diff --git a/crates/cuda-driver/src/qsa_late_gpu.rs b/crates/cuda-driver/src/qsa_late_gpu.rs index 66803b55..03cbb294 100644 --- a/crates/cuda-driver/src/qsa_late_gpu.rs +++ b/crates/cuda-driver/src/qsa_late_gpu.rs @@ -189,46 +189,9 @@ fn scan_flags_match_original( (scores, steps_d): (&[f32], &DeviceBuffer<'_>), (case, p0, rows): (usize, usize, usize), ) { - let (context, stream, max_blocks) = (rig.context, rig.stream, rig.max_blocks); - let reach = (p0 + rows) / 4 + 1; for variant in 0..3 { - let mut bad = scores.to_vec(); - match variant { - 1 => bad[(rows / 2) * max_blocks + ((p0 + rows / 2 + 1) / 4) / 2] = f32::NAN, - 2 => { - let row = rows - 1; - let n_bid = (p0 + row + 1) / 4; - if n_bid + 1 < max_blocks { - bad[row * max_blocks + n_bid + 1] = f32::INFINITY; - } - } - _ => {} - } - let bad_d = upload(context, &f32_raw(&bad)); - let (st_o, st_n) = (upload(context, &[0u8; 16]), upload(context, &[0u8; 16])); - let guard = context.enter().expect("enter"); - let mut so = KernelArguments::new(vec![ - A::Address(handle(&bad_d)), - A::Address(handle(steps_d)), - A::I32(rows as i32), - A::I64(max_blocks as i64), - A::Address(handle(&st_o)), - A::U32(1), - ]); - rig.index.launch(0, (rows * max_blocks).div_ceil(256) as u32, 256, stream, &mut so).expect("old scan"); - let mut sn = KernelArguments::new(vec![ - A::Address(handle(&bad_d)), - A::Address(handle(steps_d)), - A::I32(rows as i32), - A::I64(max_blocks as i64), - A::I64(reach as i64), - A::Address(handle(&st_n)), - A::U32(1), - ]); - let grid = (rows * reach).div_ceil(256) as u32; - rig.late.launch(SCORE_SCAN_FAST, grid, 256, stream, &mut sn).expect("new scan"); - context.driver.api.synchronize().expect("sync"); - guard.finish().expect("finish"); + let bad = scores_with_variant(scores, rig.max_blocks, (p0, rows), variant); + let (st_o, st_n) = scan_both(rig, (&bad, steps_d), (p0, rows)); assert_eq!(download(&st_o, 8), download(&st_n, 8), "case {case} variant {variant}: scan flags"); if variant == 1 { assert_ne!(download(&st_n, 8)[4..8], [0, 0, 0, 0], "a NaN inside the blocks must raise the flag"); @@ -236,6 +199,48 @@ fn scan_flags_match_original( } } +/// `scores` with a NaN inside a row's blocks (variant 1) or an infinity beyond a row's last block (variant 2). +fn scores_with_variant(scores: &[f32], max_blocks: usize, (p0, rows): (usize, usize), variant: usize) -> Vec { + let mut bad = scores.to_vec(); + match variant { + 1 => bad[(rows / 2) * max_blocks + ((p0 + rows / 2 + 1) / 4) / 2] = f32::NAN, + 2 => { + let row = rows - 1; + let n_bid = (p0 + row + 1) / 4; + if n_bid + 1 < max_blocks { + bad[row * max_blocks + n_bid + 1] = f32::INFINITY; + } + } + _ => {} + } + bad +} + +/// The Original's score scan and the late fast scan over the same scores; returns both status buffers. +fn scan_both<'c>( + rig: &SelectionRig<'c>, + (bad, steps_d): (&[f32], &DeviceBuffer<'_>), + (p0, rows): (usize, usize), +) -> (DeviceBuffer<'c>, DeviceBuffer<'c>) { + let (context, stream, max_blocks) = (rig.context, rig.stream, rig.max_blocks); + let reach = (p0 + rows) / 4 + 1; + let ad = |b: &DeviceBuffer<'_>| A::Address(handle(b)); + let bad_d = upload(context, &f32_raw(bad)); + let (st_o, st_n) = (upload(context, &[0u8; 16]), upload(context, &[0u8; 16])); + let guard = context.enter().expect("enter"); + let old = vec![ad(&bad_d), ad(steps_d), A::I32(rows as i32), A::I64(max_blocks as i64), ad(&st_o), A::U32(1)]; + let mut so = KernelArguments::new(old); + rig.index.launch(0, (rows * max_blocks).div_ceil(256) as u32, 256, stream, &mut so).expect("old scan"); + let mut new = vec![ad(&bad_d), ad(steps_d), A::I32(rows as i32), A::I64(max_blocks as i64)]; + new.extend([A::I64(reach as i64), ad(&st_n), A::U32(1)]); + let mut sn = KernelArguments::new(new); + let grid = (rows * reach).div_ceil(256) as u32; + rig.late.launch(SCORE_SCAN_FAST, grid, 256, stream, &mut sn).expect("new scan"); + context.driver.api.synchronize().expect("sync"); + guard.finish().expect("finish"); + (st_o, st_n) +} + // ---------------------------------------------------------------------------------------------- top-k variants /// The Original's top-k, the late variants and the decode cluster kernel. @@ -266,40 +271,44 @@ fn topk_variants_equal_the_original_and_are_timed() { guard.finish().expect("finish"); let mut rng = Rng(0x9e3779b97f4a7c15); let rig = BenchRig { context, stream, max_blocks, select, late, cluster }; - // (first position, rows, style, label): style 0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy tail - // (relu-sum like) - let cases: [(usize, usize, u8, &str); 24] = [ - (100, 4, 3, "decode"), - (2_040, 4, 3, "decode"), - (2_049, 5, 1, "decode"), - (3_000, 4, 3, "decode"), - (9_999, 3, 2, "decode"), - (2_040, 256, 3, "prompt"), - (8_000, 256, 3, "prompt"), - (24_000, 256, 3, "prompt"), - (48_000, 256, 3, "prompt"), - (70_000, 256, 3, "prompt"), - (100_003, 256, 0, "prompt"), - (100_003, 256, 3, "prompt"), - (180_000, 256, 0, "prompt"), - (180_000, 256, 3, "prompt"), - (180_000, 256, 1, "prompt"), - (245_000, 256, 3, "prompt"), - (245_000, 256, 2, "prompt"), - (131_072, 1, 3, "decode"), - (131_072, 4, 3, "decode"), - (245_000, 1, 3, "decode"), - (245_000, 4, 3, "decode"), - (245_000, 5, 0, "decode"), - (245_000, 4, 1, "decode"), - (261_500, 4, 2, "decode"), - ]; + let cases = bench_cases(); for (case, c) in cases.into_iter().enumerate() { bench_case(&rig, &mut rng, case, c); } }); } +/// (first position, rows, style, label): style 0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy tail (relu-sum +/// like). +fn bench_cases() -> [(usize, usize, u8, &'static str); 24] { + [ + (100, 4, 3, "decode"), + (2_040, 4, 3, "decode"), + (2_049, 5, 1, "decode"), + (3_000, 4, 3, "decode"), + (9_999, 3, 2, "decode"), + (2_040, 256, 3, "prompt"), + (8_000, 256, 3, "prompt"), + (24_000, 256, 3, "prompt"), + (48_000, 256, 3, "prompt"), + (70_000, 256, 3, "prompt"), + (100_003, 256, 0, "prompt"), + (100_003, 256, 3, "prompt"), + (180_000, 256, 0, "prompt"), + (180_000, 256, 3, "prompt"), + (180_000, 256, 1, "prompt"), + (245_000, 256, 3, "prompt"), + (245_000, 256, 2, "prompt"), + (131_072, 1, 3, "decode"), + (131_072, 4, 3, "decode"), + (245_000, 1, 3, "decode"), + (245_000, 4, 3, "decode"), + (245_000, 5, 0, "decode"), + (245_000, 4, 1, "decode"), + (261_500, 4, 2, "decode"), + ] +} + /// Block scores of `rows` rows from position `p0` in `style` (0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy /// tail). fn bench_scores(rng: &mut Rng, max_blocks: usize, (p0, rows, style): (usize, usize, u8)) -> Vec { @@ -355,7 +364,6 @@ fn bench_case(rig: &BenchRig<'_>, rng: &mut Rng, case: usize, (p0, rows, style, let scores_d = upload(context, &f32_raw(&scores)); let steps_d = upload(context, &steps); let out_len = rows * CAP * 4; - let reps = 20; let variants = topk_variants(rig, rows as u32); let mut reference: Option> = None; let mut line = format!("QSA-TOPK-BENCH case {case} {label} p0={p0} rows={rows} style={style}:"); @@ -363,20 +371,7 @@ fn bench_case(rig: &BenchRig<'_>, rng: &mut Rng, case: usize, (p0, rows, style, if *name == "cluster" && rows > 16 { continue; // the decode kernel (the upstream dispatch uses it for at most 16 queries) } - let ids = upload(context, &vec![0xffu8; out_len]); - let mut a = topk_args(rig.max_blocks, (&scores_d, &steps_d), &ids); - let guard = context.enter().expect("enter"); - // the sample kernel flags its failures in a module global that persists: clear by running sample first inside run - run(&mut a); - context.driver.api.synchronize().expect("sync"); - let t0 = std::time::Instant::now(); - for _ in 0..reps { - run(&mut a); - } - context.driver.api.synchronize().expect("sync"); - let us = t0.elapsed().as_secs_f64() * 1e6 / reps as f64; - guard.finish().expect("finish"); - let got = download(&ids, out_len); + let (got, us) = time_variant(rig, run, (&scores_d, &steps_d), out_len); match &reference { None => reference = Some(got), Some(r) => assert!( @@ -389,6 +384,30 @@ fn bench_case(rig: &BenchRig<'_>, rng: &mut Rng, case: usize, (p0, rows, style, eprintln!("{line} ids equal"); } +/// Runs one variant warm, then 20 launches drained once; returns the ids it wrote and the per-launch microseconds. +fn time_variant( + rig: &BenchRig<'_>, + run: &Run<'_>, + inputs: (&DeviceBuffer<'_>, &DeviceBuffer<'_>), + out_len: usize, +) -> (Vec, f64) { + let (context, reps) = (rig.context, 20); + let ids = upload(context, &vec![0xffu8; out_len]); + let mut a = topk_args(rig.max_blocks, inputs, &ids); + let guard = context.enter().expect("enter"); + // the sample kernel flags its failures in a module global that persists: clear by running sample first inside run + run(&mut a); + context.driver.api.synchronize().expect("sync"); + let t0 = std::time::Instant::now(); + for _ in 0..reps { + run(&mut a); + } + context.driver.api.synchronize().expect("sync"); + let us = t0.elapsed().as_secs_f64() * 1e6 / reps as f64; + guard.finish().expect("finish"); + (download(&ids, out_len), us) +} + // ---------------------------------------------------------------------------------------------- decode scores /// Timing only (row 2.5 follow-up): the decode window's block scores (`qsa_decode_scores`, the Original's multi-query kernel, 256 CTAs) next to its @@ -409,7 +428,28 @@ fn decode_scores_are_timed_next_to_the_topk() { }); } -/// Random pooled/dead/query vectors, the steps, and the scores/ids outputs of one `(pos, nq)` shape. +/// Random pooled, dead and query vectors and the steps of one `(pos, nq)` shape, uploaded in that order. +fn decode_inputs<'c>( + context: &'c Context<'c>, + rng: &mut Rng, + max_blocks: usize, + (pos, nq): (usize, usize), +) -> [DeviceBuffer<'c>; 4] { + let mut random = + |n: usize| -> Vec { (0..n).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect() }; + let pooled = random((max_blocks + 1) * 128); + let dead = random(128); + let qidx = random(nq * 4 * 128); + let steps = step_bytes(pos, nq); + [ + upload(context, &f32_raw(&pooled)), + upload(context, &f32_raw(&dead)), + upload(context, &f32_raw(&qidx)), + upload(context, &steps), + ] +} + +/// Times the decode scores kernel and the top-k at one `(pos, nq)` shape, 20 warm launches each. fn time_scores_and_topk( context: &Context<'_>, (select, stream, max_blocks): (&KernelModule, usize, usize), @@ -417,45 +457,32 @@ fn time_scores_and_topk( (pos, nq): (usize, usize), ) { let n_bid_max = (pos + nq) / 4; - let mut random = - |n: usize| -> Vec { (0..n).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect() }; - let pooled = random((max_blocks + 1) * 128); - let dead = random(128); - let qidx = random(nq * 4 * 128); - let steps = step_bytes(pos, nq); - let (pooled_d, dead_d, qidx_d, steps_d) = ( - upload(context, &f32_raw(&pooled)), - upload(context, &f32_raw(&dead)), - upload(context, &f32_raw(&qidx)), - upload(context, &steps), - ); + let [pooled_d, dead_d, qidx_d, steps_d] = decode_inputs(context, rng, max_blocks, (pos, nq)); let scores_d = upload(context, &vec![0u8; nq * max_blocks * 4]); let ids_d = upload(context, &vec![0xffu8; nq * CAP * 4]); let guard = context.enter().expect("enter"); - let time = |run: &mut dyn FnMut()| -> f64 { - run(); - context.driver.api.synchronize().expect("sync"); - let t0 = std::time::Instant::now(); - for _ in 0..20 { - run(); - } - context.driver.api.synchronize().expect("sync"); - t0.elapsed().as_secs_f64() * 1e6 / 20.0 - }; - let mut sa = KernelArguments::new(vec![ - A::Address(handle(&pooled_d)), - A::Address(handle(&dead_d)), - A::Address(handle(&qidx_d)), - A::Address(handle(&steps_d)), - A::I32(nq as i32), - A::I64(max_blocks as i64), - A::Address(handle(&scores_d)), - ]); - let scores_us = time(&mut || select.launch(0, 256, 256, stream, &mut sa).expect("scores")); + let ad = |b: &DeviceBuffer<'_>| A::Address(handle(b)); + let (nq_arg, blocks_arg) = (A::I32(nq as i32), A::I64(max_blocks as i64)); + let mut sa: Vec = [&pooled_d, &dead_d, &qidx_d, &steps_d].into_iter().map(|b| ad(b)).collect(); + sa.extend([nq_arg, blocks_arg, ad(&scores_d)]); + let mut sa = KernelArguments::new(sa); + let scores_us = time_warm(context, &mut || select.launch(0, 256, 256, stream, &mut sa).expect("scores")); let mut ta = topk_args(max_blocks, (&scores_d, &steps_d), &ids_d); - let topk_us = time(&mut || select.launch(1, nq as u32, 256, stream, &mut ta).expect("topk")); + let topk_us = time_warm(context, &mut || select.launch(1, nq as u32, 256, stream, &mut ta).expect("topk")); guard.finish().expect("finish"); eprintln!( "QSA-DECODE-SCORES pos={pos} nq={nq} n_bid={n_bid_max}: qsa_decode_scores {scores_us:.1} us, qsa_topk_ref {topk_us:.1} us (per layer, warm)" ); } + +/// One warm-up run, then 20 timed runs drained once; microseconds per run. +fn time_warm(context: &Context<'_>, run: &mut dyn FnMut()) -> f64 { + run(); + context.driver.api.synchronize().expect("sync"); + let t0 = std::time::Instant::now(); + for _ in 0..20 { + run(); + } + context.driver.api.synchronize().expect("sync"); + t0.elapsed().as_secs_f64() * 1e6 / 20.0 +} diff --git a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs index 7c54e849..4ea2012e 100644 --- a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs +++ b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs @@ -99,8 +99,8 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { } Ok(()) } - /// The guard scan, the quantize/append kernel and the scale kernel, each followed by its status check. - pub(super) fn run_append( + /// The guard scan and fence: the new K and V cells must be finite and in range before they are written. + fn guard_append( &mut self, workspace: &mut NativeBatchWorkspace<'ctx>, stage: &mut OriginalQsaResidentTransport<'ctx>, @@ -112,19 +112,26 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { if stage.flags()? != 0 { return Err(Error::InvalidQ8Activation); } + Ok(()) + } + /// The guard scan, the quantize/append kernel and the scale kernel, each followed by its status check. + pub(super) fn run_append( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + stage: &mut OriginalQsaResidentTransport<'ctx>, + p: &AppendPlan, + ) -> Result<()> { + self.guard_append(workspace, stage, p)?; + let [k, v] = p.kv; let mut args = vec![Arg::U64(k), Arg::U64(v), Arg::I64(p.prior_end as i64)]; args.extend([Arg::U64(self.owner.pools.table()?), Arg::I64(4)]); args.extend(p.rp.map(Arg::U64)); args.extend(p.sp.map(Arg::U64)); args.extend(p.hp.map(Arg::U64)); let args = Arguments::new(args)?; - let scales = Arguments::new(vec![ - Arg::U64(p.sp[2]), - Arg::U64(p.sp[3]), - Arg::I32(p.prior_end as i32), - Arg::I32(p.end as i32), - Arg::U64(p.sa), - ])?; + let mut scales = vec![Arg::U64(p.sp[2]), Arg::U64(p.sp[3])]; + scales.extend([Arg::I32(p.prior_end as i32), Arg::I32(p.end as i32), Arg::U64(p.sa)]); + let scales = Arguments::new(scales)?; self.owner.current = None; self.owner.mapped_current = None; diff --git a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs index c069395a..9505b102 100644 --- a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs +++ b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs @@ -5,6 +5,8 @@ use super::super::impl_originalqsamappedjournal::AppendPlan; use super::*; impl<'ctx> OriginalQsaMappedJournal<'ctx> { + /// Whole original mapped storage/staging has fixed addresses. Only new cells are written; preceding prefix bytes + /// remain actual owners. pub(crate) fn append_resident_arena( &mut self, workspace: &mut NativeBatchWorkspace<'ctx>, @@ -17,8 +19,6 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { let (kh, vh) = inputs.kv_spans(self.owner.context)?; self.reject_kv_spans(workspace, stage, (kh, vh), t)?; let table = self.check_prior_and_table(stage, prior)?; - // Whole original mapped storage/staging has fixed addresses. Only new - // cells are written; preceding prefix bytes remain actual owners. let sa = Self::zero_stage_status(stage, self.owner.context)?; let rp = self.owner.pools.addresses()?; let sp = inputs.kv_stage_spans(self.owner.context)?.map(|h| h.qwen_address()); diff --git a/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs b/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs index ef4f9305..1240f6b3 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs @@ -93,6 +93,14 @@ impl<'ctx> QsaPromptStage<'ctx> { let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(4)?; Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::InvalidSize)?)) } + fn launch_pass( + &self, + w: &NativeBatchWorkspace<'ctx>, + (index, grid, block): (usize, [u32; 3], u32), + a: &mut Arguments, + ) -> Result<()> { + self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(index, grid, block, 0, w.blas()?.stream(), a) + } pub(super) fn run( &mut self, w: &mut NativeBatchWorkspace<'ctx>, @@ -105,16 +113,7 @@ impl<'ctx> QsaPromptStage<'ctx> { w.validate_context(self.context)?; let g = self.context.enter()?; let dependency = self.context.driver.api.synchronize(); - let op = dependency.and_then(|()| { - self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch( - index, - grid, - block, - 0, - w.blas()?.stream(), - &mut a, - ) - }); + let op = dependency.and_then(|()| self.launch_pass(w, (index, grid, block), &mut a)); let sync = w.blas()?.synchronize(); let pop = g.finish(); if sync.is_err() || pop.is_err() {