diff --git a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2.rs b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2.rs index 398ddfe8..94804aaf 100644 --- a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2.rs +++ b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2.rs @@ -4,7 +4,8 @@ use super::*; impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> { - /// The device history image the window rows advance (and the commit graph sets from `hist_snap`): the one buffer all aggregates share. + /// The device history image the window rows advance (and the commit graph sets from `hist_snap`): the one buffer + /// all aggregates share. pub(crate) fn ple_buffer(&self) -> Option<&DeviceBuffer<'ctx>> { self.ple } diff --git a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2_2.rs b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2_2.rs index d47861f4..8d0bf2fe 100644 --- a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2_2.rs +++ b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2_2.rs @@ -201,12 +201,14 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> { ], ) } - /// Load the sealed `draft_commit.ptx` module before the commit graph is captured (module loading is not capturable). + /// Load the sealed `draft_commit.ptx` module before the commit graph is captured (module loading is not + /// capturable). pub(crate) fn load_draft_commit_asset(&self) -> Result<()> { self.physical.ensure_window_assets(&[&draft::DRAFT_COMMIT, &draft::DRAFT_COMMIT_QSA]) } - /// draft-round (`LELEKA_DRAFT_FUSED_COMMIT=on`): the 36 GDN layers' conv history commit and recurrence replay of `capture_commit_layer` in ONE launch - /// (`draft_commit_gdn_layers`: grid (48 heads + 20 conv blocks, 36 layers)). The per-layer operands are affine in the layer (checked against the per-layer spans below). + /// draft-round (`LELEKA_DRAFT_FUSED_COMMIT=on`): the 36 GDN layers' conv history commit and recurrence replay of + /// `capture_commit_layer` in ONE launch (`draft_commit_gdn_layers`: grid (48 heads + 20 conv blocks, 36 layers)). + /// The per-layer operands are affine in the layer (checked against the per-layer spans below). pub(crate) fn capture_commit_gdn_fused(&self, capture: &mut OriginalCapture<'_, 'ctx>) -> Result<()> { self.validate_context(self.physical.context)?; let spans = self.fused_spans(self.physical.layout.geometry.max_t)?; diff --git a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_3.rs b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_3.rs index 200b4c0a..1f96a711 100644 --- a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_3.rs +++ b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_3.rs @@ -1,4 +1,6 @@ -//! Moved out of the parent module by STRA-338: impl OriginalVerifyGdnJournal (3), impl OriginalVerifyResources, impl resources_Sealed_for, impl OriginalGraphResources_for_OriginalVerifyResources, impl OriginalVerifyGraphResources_for_OriginalVerifyResources, impl crate_OriginalNativeHeadGraphResources_for .... +//! Moved out of the parent module by STRA-338: impl OriginalVerifyGdnJournal (3), impl OriginalVerifyResources, impl +//! resources_Sealed_for, impl OriginalGraphResources_for_OriginalVerifyResources, impl +//! OriginalVerifyGraphResources_for_OriginalVerifyResources, impl crate_OriginalNativeHeadGraphResources_for .... #[allow(unused_imports)] use super::*; @@ -109,7 +111,8 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> { } Ok(()) } - /// Admits and launches the scan on `stream` and drains it; a failed drain poisons the context and retains the commands. + /// Admits and launches the scan on `stream` and drains it; a failed drain poisons the context and retains the + /// commands. fn run_logits_scan(&self, stream: &mut crate::OriginalGpuStream<'ctx>, mut commands: Vec) -> Result<()> { let module = self.physical.module.as_ref().ok_or(Error::ContextPoisoned)?; for c in &commands { diff --git a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifywindow.rs b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifywindow.rs index ce5efa64..1549c3b0 100644 --- a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifywindow.rs +++ b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifywindow.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl OriginalVerifyWindow, impl OriginalVerifyWindow, fn verify_assets_sealed. +//! Moved out of the parent module by STRA-338: impl OriginalVerifyWindow, impl OriginalVerifyWindow, fn +//! verify_assets_sealed. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/original_verify/share_window_modules_fn.rs b/crates/cuda-driver/src/original_verify/share_window_modules_fn.rs index 4bb0887d..39720f24 100644 --- a/crates/cuda-driver/src/original_verify/share_window_modules_fn.rs +++ b/crates/cuda-driver/src/original_verify/share_window_modules_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn share_window_modules, fn admission, fn handle, fn admit, fn poison, fn transport .... +//! Moved out of the parent module by STRA-338: fn share_window_modules, fn admission, fn handle, fn admit, fn poison, +//! fn transport .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_originalverifybank_2.rs b/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_originalverifybank_2.rs index 216438a1..25d5b028 100644 --- a/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_originalverifybank_2.rs +++ b/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_originalverifybank_2.rs @@ -1,4 +1,6 @@ -//! Moved out of the parent module by STRA-338: impl OriginalVerifyBank (2), impl OriginalVerifyRow, impl OriginalVerifyWindow, impl kernels_ArenaMap_for, impl resources_Sealed_for, impl OriginalGraphResources_for_OriginalVerifyGdnJournal. +//! Moved out of the parent module by STRA-338: impl OriginalVerifyBank (2), impl OriginalVerifyRow, impl +//! OriginalVerifyWindow, impl kernels_ArenaMap_for, impl resources_Sealed_for, impl +//! OriginalGraphResources_for_OriginalVerifyGdnJournal. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_physical.rs b/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_physical.rs index 1dc30941..c8987c08 100644 --- a/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_physical.rs +++ b/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_physical.rs @@ -116,8 +116,8 @@ impl Physical<'_> { } combine(result, pop) } - /// `cuDeviceGetAttribute` of the verifier context's device (compute capability and shared-memory limits that Original - /// reads when it picks kernel variants). + /// `cuDeviceGetAttribute` of the verifier context's device (compute capability and shared-memory limits that + /// Original reads when it picks kernel variants). pub(in super::super) fn window_device_attribute(&self, attribute: i32) -> Result { self.validate(self.context)?; let guard = self.context.enter()?; diff --git a/crates/cuda-driver/src/original_verify/share_window_modules_fn/share_window_modules_fn_2.rs b/crates/cuda-driver/src/original_verify/share_window_modules_fn/share_window_modules_fn_2.rs index ad414dd9..9ce702fd 100644 --- a/crates/cuda-driver/src/original_verify/share_window_modules_fn/share_window_modules_fn_2.rs +++ b/crates/cuda-driver/src/original_verify/share_window_modules_fn/share_window_modules_fn_2.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn share_window_modules, fn admission, fn handle, fn admit, fn poison, fn transport .... +//! Moved out of the parent module by STRA-338: fn share_window_modules, fn admission, fn handle, fn admit, fn poison, +//! fn transport .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/original_verify_diag.rs b/crates/cuda-driver/src/original_verify_diag.rs index 74572d79..98fef468 100644 --- a/crates/cuda-driver/src/original_verify_diag.rs +++ b/crates/cuda-driver/src/original_verify_diag.rs @@ -238,23 +238,30 @@ mod tests { (b, w) } + fn snapshot_after_a_window(r: &Registration, cells: &[AtomicU32; 4]) -> OriginalVerifyDiag { + r.begin_window(4, 1234); + r.layer_step(7); + cells[0].store(6, Ordering::SeqCst); + cells[1].store(5, Ordering::SeqCst); + r.snapshot() + } + #[test] fn diag_line_matches_original_format_and_tracks_window() { let _serial = serial(); let (cells, w) = words(); let r = Registration::new(w); - r.begin_window(4, 1234); - r.layer_step(7); - cells[0].store(6, Ordering::SeqCst); - cells[1].store(5, Ordering::SeqCst); - let d = r.snapshot(); + let d = snapshot_after_a_window(&r, &cells); assert_eq!((d.rows, d.first_position, d.host_layer_step, d.gpu_rang), (4, 1234, 7, 6)); assert!(d.current); let mut out = Vec::new(); d.write_to(&mut out).unwrap(); assert_eq!( String::from_utf8(out).unwrap(), - " verify window: 4 tokens at position 1234, host at layer step 7; the GPU rang 6; flags: served 5, plan (A) 0, copies (B) 0\n" + concat!( + " verify window: 4 tokens at position 1234, host at layer step 7; the GPU rang 6; ", + "flags: served 5, plan (A) 0, copies (B) 0\n" + ) ); r.end_window(); let mut out = Vec::new(); diff --git a/crates/cuda-driver/src/original_verify_expert_probe.rs b/crates/cuda-driver/src/original_verify_expert_probe.rs index 97bbeb86..cb06f980 100644 --- a/crates/cuda-driver/src/original_verify_expert_probe.rs +++ b/crates/cuda-driver/src/original_verify_expert_probe.rs @@ -203,7 +203,8 @@ impl<'ctx> OriginalExpertTierProbe<'ctx> { hit_add: moe::plan_hit_add(&arena, g, group)?, }) } - /// quantize_expert_input | wait A | plan copy | VRAM groups | wait B | PCIe groups | wait M | copy cpu rows | hit add + /// quantize_expert_input | wait A | plan copy | VRAM groups | wait B | PCIe groups | wait M | copy cpu rows | hit + /// add fn enqueue_group( &mut self, physical: &Physical<'ctx>, diff --git a/crates/cuda-driver/src/original_verify_ffi.rs b/crates/cuda-driver/src/original_verify_ffi.rs index 08180dac..b758a13d 100644 --- a/crates/cuda-driver/src/original_verify_ffi.rs +++ b/crates/cuda-driver/src/original_verify_ffi.rs @@ -30,7 +30,8 @@ impl Arg { } } } -/// `cluster` > 0: launched with `cuLaunchKernelEx` as a thread-block cluster of that many CTAs along x (sm_90+, row 2.5); 0: `cuLaunchKernel`. +/// `cluster` > 0: launched with `cuLaunchKernelEx` as a thread-block cluster of that many CTAs along x (sm_90+, row +/// 2.5); 0: `cuLaunchKernel`. pub(crate) struct Command { pub name: &'static str, pub grid: [u32; 3], @@ -221,7 +222,8 @@ impl Module { (self.set_attr)(f as Handle, 8, i32::try_from(bytes).map_err(|_| Error::InvalidSize)?) }) } - /// `cuDeviceGetAttribute` of the context's current device (97 = max shared per block opt-in, 8 = per block, 75/76 = cc). + /// `cuDeviceGetAttribute` of the context's current device (97 = max shared per block opt-in, 8 = per block, 75/76 + /// = cc). pub(crate) fn device_attribute(&self, attribute: i32) -> Result { let mut device = 0; check("cuCtxGetDevice", unsafe { (self.device)(&mut device) })?; diff --git a/crates/cuda-driver/src/original_verify_gpu_plan.rs b/crates/cuda-driver/src/original_verify_gpu_plan.rs index 42217687..3d1f73a2 100644 --- a/crates/cuda-driver/src/original_verify_gpu_plan.rs +++ b/crates/cuda-driver/src/original_verify_gpu_plan.rs @@ -37,7 +37,8 @@ pub struct OriginalVerifyPcieSource<'s, 'ctx> { pub spans: &'s [[ResidentExpertBankSpan; 3]], } -// Model-free GPU smoke of the PCIe staging copy: pageable / page-locked / mixed sources, one call per piece and the batch call. +// Model-free GPU smoke of the PCIe staging copy: pageable / page-locked / mixed sources, one call per piece and the +// batch call. #[cfg(all( test, feature = "cuda-driver", diff --git a/crates/cuda-driver/src/original_verify_gpu_plan/dma_options_for_fn.rs b/crates/cuda-driver/src/original_verify_gpu_plan/dma_options_for_fn.rs index 4247ae7e..ea8c18d6 100644 --- a/crates/cuda-driver/src/original_verify_gpu_plan/dma_options_for_fn.rs +++ b/crates/cuda-driver/src/original_verify_gpu_plan/dma_options_for_fn.rs @@ -3,8 +3,8 @@ #[allow(unused_imports)] use super::*; -/// `dma_options` for a platform and an environment: `wsl` (WSL2 passthrough) makes the batch copy and the stream write opt-in, -/// `windows` (native) the batch copy only. +/// `dma_options` for a platform and an environment: `wsl` (WSL2 passthrough) makes the batch copy and the stream +/// write opt-in, `windows` (native) the batch copy only. pub(super) fn dma_options_for(wsl: bool, windows: bool, env: impl Fn(&str) -> String) -> (bool, bool, bool) { let default = |name: &str, off_by_default: bool| match env(name).as_str() { "on" | "write" => true, diff --git a/crates/cuda-driver/src/original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs b/crates/cuda-driver/src/original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs index 22610dbe..d7f98fac 100644 --- a/crates/cuda-driver/src/original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs +++ b/crates/cuda-driver/src/original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs @@ -55,15 +55,17 @@ impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> { } } -/// DMA staging options (`--pcie-mode dma`), read once. All three are on by default except where noted (job 981: +6 % over the -/// per-piece path on the 5090): `LELEKA_PCIE_DMA_MANY=off` goes back to one driver entry per piece, `LELEKA_PCIE_DMA_BATCH=off` to one -/// `cuMemcpyBatchAsync`-free loop inside the entry, `LELEKA_PCIE_FLAGB=host` raises flag B with a host callback instead of -/// `cuStreamWriteValue32`. A driver without the batch / write calls takes the loop / host callback by itself. +/// DMA staging options (`--pcie-mode dma`), read once. All three are on by default except where noted (job 981: +6 % +/// over the per-piece path on the 5090): `LELEKA_PCIE_DMA_MANY=off` goes back to one driver entry per piece, +/// `LELEKA_PCIE_DMA_BATCH=off` to one `cuMemcpyBatchAsync`-free loop inside the entry, `LELEKA_PCIE_FLAGB=host` +/// raises flag B with a host callback instead of `cuStreamWriteValue32`. A driver without the batch / write calls +/// takes the loop / host callback by itself. /// -/// The batch call is off by default on native Windows and under WSL2: on the RTX 3080 laptop `cuMemcpyBatchAsync_v2` from page-locked -/// host memory raises CUDA error 700 for any piece, source access order or registration flag, which killed the first decode window -/// of every request with a PCIe share (docs/windows.md, "PCIe tier on the laptop"; `pcie_copy_gpu_raw_batch_page_locked` repeats the -/// check). The stream write of flag B is also opt-in under WSL2 only. `=on` / `=write` force either call. +/// The batch call is off by default on native Windows and under WSL2: on the RTX 3080 laptop `cuMemcpyBatchAsync_v2` +/// from page-locked host memory raises CUDA error 700 for any piece, source access order or registration flag, which +/// killed the first decode window of every request with a PCIe share (docs/windows.md, "PCIe tier on the laptop"; +/// `pcie_copy_gpu_raw_batch_page_locked` repeats the check). The stream write of flag B is also opt-in under WSL2 +/// only. `=on` / `=write` force either call. pub(crate) fn dma_options() -> (bool, bool, bool) { static OPTIONS: std::sync::OnceLock<(bool, bool, bool)> = std::sync::OnceLock::new(); *OPTIONS.get_or_init(|| { diff --git a/crates/cuda-driver/src/original_verify_mapped.rs b/crates/cuda-driver/src/original_verify_mapped.rs index 7f3c8542..697aa96b 100644 --- a/crates/cuda-driver/src/original_verify_mapped.rs +++ b/crates/cuda-driver/src/original_verify_mapped.rs @@ -30,10 +30,10 @@ mod enabled { unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } - /// Every value finite (no infinity, no NaN): the same predicate as `!any(|v| !v.is_finite())`, written as a branch-free - /// fold over the exponent bits so it vectorizes (the per-element early exit of `any` does not); it runs over a whole - /// verify group's CPU output (rows x top-10 x hidden floats) once per layer on the decode critical path. - /// `LELEKA_SINK_SCAN=legacy` (A/B arm) keeps the element-wise `any` scan. + /// Every value finite (no infinity, no NaN): the same predicate as `!any(|v| !v.is_finite())`, written as a + /// branch-free fold over the exponent bits so it vectorizes (the per-element early exit of `any` does not); it + /// runs over a whole verify group's CPU output (rows x top-10 x hidden floats) once per layer on the decode + /// critical path. `LELEKA_SINK_SCAN=legacy` (A/B arm) keeps the element-wise `any` scan. pub(crate) fn all_finite(rows: &[f32]) -> bool { static LEGACY: std::sync::OnceLock = std::sync::OnceLock::new(); if *LEGACY.get_or_init(|| std::env::var("LELEKA_SINK_SCAN").as_deref() == Ok("legacy")) { diff --git a/crates/cuda-driver/src/original_verify_schedule/commit_sync_forced_fn.rs b/crates/cuda-driver/src/original_verify_schedule/commit_sync_forced_fn.rs index 614e0414..9d1cd74c 100644 --- a/crates/cuda-driver/src/original_verify_schedule/commit_sync_forced_fn.rs +++ b/crates/cuda-driver/src/original_verify_schedule/commit_sync_forced_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn commit_sync_forced, impl OriginalVerifyCpuSink, impl OriginalVerifier. +//! Moved out of the parent module by STRA-338: fn commit_sync_forced, impl OriginalVerifyCpuSink, impl +//! OriginalVerifier. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_3.rs b/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_3.rs index 38a76743..178b7aad 100644 --- a/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_3.rs +++ b/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_3.rs @@ -36,13 +36,14 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour self.commits = self.commits.checked_add(1).ok_or(Error::InvalidSize)?; Ok(()) } - /// Take back a completed window that no commit was enqueued for, so that `run` can stage the same rows again (the serve loop's - /// NaN guard: the window read as non-finite, both checkpoints were restored, the round starts over). The GDN canonical state is not - /// written before a commit (the commit graph recomputes it from the journal); the QSA journal writes back the index state and the PLE - /// history (the window advances it row by row) as they were when the window began (`discard_window` there, which needs - /// `OriginalVerifyQsaJournal::set_window_snapshots(true)`). No window outstanding is - /// not an error unless the verifier already failed or was released (then there is nothing to run the rows on). After an error - /// here the verifier is failed. + /// Take back a completed window that no commit was enqueued for, so that `run` can stage the same rows again (the + /// serve loop's NaN guard: the window read as non-finite, both checkpoints were restored, the round starts over). + /// The GDN canonical state is not written before a commit (the commit graph recomputes it from the journal); the + /// QSA journal writes back the index state and the PLE history (the window advances it row by row) as they were + /// when the window began (`discard_window` there, which needs + /// `OriginalVerifyQsaJournal::set_window_snapshots(true)`). No window outstanding is not an error unless the + /// verifier already failed or was released (then there is nothing to run the rows on). After an error here the + /// verifier is failed. pub fn discard_window(&mut self) -> Result<()> { if self.failed || self.released || self.active || self.commit_pending { return Err(Error::InvalidQwenShape); 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 8e3a9143..858a05c3 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 @@ -84,8 +84,8 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour .map_err(|_| Error::InvalidDriverValue("window_logprobs output")) }) } - /// Bring-up diagnostic: the final residual R (`hc*n` f32 per row, all rows) of the last completed window and its first - /// position. Read-only; same completion guard as the logits readers. + /// Bring-up diagnostic: the final residual R (`hc*n` f32 per row, all rows) of the last completed window and its + /// first position. Read-only; same completion guard as the logits readers. pub fn window_residual_rows(&self) -> Result<(usize, usize, Vec)> { self.require_completed_window()?; let bank = self.bank()?; @@ -98,8 +98,8 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour let bytes = read_device_bytes(bank.physical.context, span, bytes_len)?; Ok((t, bank.last_position, decode_f32s(&bytes, bytes_len / 4)?)) } - /// Bring-up diagnostic: the `dbg_ladder` frames (96 x rows x hc*n f32, frame = 2*layer + half) of the last completed window, - /// `None` when the region was not laid out (LELEKA_TRACE_LADDER unset at bank creation). + /// Bring-up diagnostic: the `dbg_ladder` frames (96 x rows x hc*n f32, frame = 2*layer + half) of the last + /// completed window, `None` when the region was not laid out (LELEKA_TRACE_LADDER unset at bank creation). pub fn window_ladder_rows(&self) -> Result>> { self.require_completed_window()?; let bank = self.bank()?; diff --git a/crates/cuda-driver/src/original_verify_window_chain.rs b/crates/cuda-driver/src/original_verify_window_chain.rs index a9495b6d..49dad54d 100644 --- a/crates/cuda-driver/src/original_verify_window_chain.rs +++ b/crates/cuda-driver/src/original_verify_window_chain.rs @@ -4,15 +4,17 @@ //! computes every output with the same operations in the same order (bit-identical; probed model-free by //! `tools/chain-probe/chain_probe.cpp`). They are OFF unless selected, so the default window is the Original's: //! -//! * `LELEKA_CHAIN=all` (or `1`, `on`) turns every group on except `qsa` (measured slower, section 6 of docs/chain-kernels.md); a comma list (`glue,ab,gr,qsa`) selects some; -//! `LELEKA_CHAIN_=0|1` overrides one group (`GLUE`, `AB`, `GR`, `QSA`, `TINY`, `HEAD`, `MTP`). +//! * `LELEKA_CHAIN=all` (or `1`, `on`) turns every group on except `qsa` (measured slower, section 6 of +//! docs/chain-kernels.md); a comma list (`glue,ab,gr,qsa`) selects some; `LELEKA_CHAIN_=0|1` overrides one +//! group (`GLUE`, `AB`, `GR`, `QSA`, `TINY`, `HEAD`, `MTP`). //! * `glue`: plan copy (`wait flag A` + `copy_i32_from_mapped` in one launch), CPU-row copy, doorbell publish. //! * `ab`: GDN alpha/beta gates with the weight loads hoisted. //! * `gr`: hyper-connection read: norm with the R' values kept in registers, up projection with all loads hoisted. //! * `qsa`: decode attention chunk with the key/value loads of a round issued together. -//! * `head`: the greedy argmax (and the MTP draft's top-probability sum) with the logit loads of a round issued together. -//! * `mtp`: the MTP draft chain step: staged hyper-connection read, the load-hoisted attention chunk, a merge over the used chunks only -//! (with `head`: the load-hoisted greedy argmax and top-probability sum). +//! * `head`: the greedy argmax (and the MTP draft's top-probability sum) with the logit loads of a round issued +//! together. +//! * `mtp`: the MTP draft chain step: staged hyper-connection read, the load-hoisted attention chunk, a merge over +//! the used chunks only (with `head`: the load-hoisted greedy argmax and top-probability sum). //! * `tiny`: dead `to_bf16` of the shared expert dropped, sigmoid + row scale and swiglu + q8_1 quantization fused. use super::kernels::AssetSpec; @@ -129,16 +131,17 @@ pub(crate) fn with_flags(flags: ChainFlags, f: impl FnOnce() -> R) -> R { r } -/// The hyper-connection up projection with 8 columns per block (320 blocks, 5.7 us at 4 rows against 7.7 us for 16 columns and 8.9 us for -/// the Original's, job 9c1); `LELEKA_CHAIN_UP8=0` selects the 16-column shape. +/// The hyper-connection up projection with 8 columns per block (320 blocks, 5.7 us at 4 rows against 7.7 us for 16 +/// columns and 8.9 us for the Original's, job 9c1); `LELEKA_CHAIN_UP8=0` selects the 16-column shape. pub(crate) fn up8() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var("LELEKA_CHAIN_UP8").map_or(true, |v| v != "0")) } -/// The hyper-connection down projection tiled over rows AND tokens (8 rows x 2 tokens per block, `ceil(T / 2)` x 41 blocks, four tile buffers of -/// two tokens): 9.7 / 11.3 / 15.0 us at 4 / 6 / 8 rows against 16.6 / 19.7 / 29.9 us for the 8-row x all-tokens shape (job p33); same arithmetic -/// per (row, token), so bit-identical. `LELEKA_CHAIN_DOWN=w8` selects the previous shape (the A arm of the paired A/B). +/// The hyper-connection down projection tiled over rows AND tokens (8 rows x 2 tokens per block, `ceil(T / 2)` x 41 +/// blocks, four tile buffers of two tokens): 9.7 / 11.3 / 15.0 us at 4 / 6 / 8 rows against 16.6 / 19.7 / 29.9 us for +/// the 8-row x all-tokens shape (job p33); same arithmetic per (row, token), so bit-identical. `LELEKA_CHAIN_DOWN=w8` +/// selects the previous shape (the A arm of the paired A/B). pub(crate) fn down_tiled() -> bool { match DOWN_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { 0 => return false, @@ -149,8 +152,8 @@ pub(crate) fn down_tiled() -> bool { *ON.get_or_init(|| std::env::var("LELEKA_CHAIN_DOWN").map_or(true, |v| v != "w8")) } -/// Per-arm override of the down-projection shape for paired A/B arms inside one process (-1: none, 0: the 8-row x all-tokens kernels, 1: tiled); -/// read when a window graph is recorded (every request records its own). +/// Per-arm override of the down-projection shape for paired A/B arms inside one process (-1: none, 0: the 8-row x +/// all-tokens kernels, 1: tiled); read when a window graph is recorded (every request records its own). static DOWN_OVERRIDE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1); pub fn set_down_override(value: i8) { DOWN_OVERRIDE.store(value, std::sync::atomic::Ordering::Relaxed); @@ -199,10 +202,11 @@ mod tests { ChainFlags { glue: false, ab: true, gr: false, qsa: false, tiny: false, head: false, mtp: false } ); } - // ---- q8_1 division flavour of the SwiGLU + quantize fusion (upstream 7d1016f3). `chain_swiglu_quant_kernel` replaces the pair - // `swiglu_entries_kernel` + `quantize_q8_1_kernel` of mtp_original_full_head_iq (the window's routed-expert path, moe.rs). A fused - // producer and the kernels it replaces must divide the same way: `div.rn.f32` (IEEE) against `div.approx.ftz.f32` / `div.full.f32` - // (`--use_fast_math`) gives a different q8_1 code at about one element in 10^6. These tests read the sealed PTX text on the CPU. + // ---- q8_1 division flavour of the SwiGLU + quantize fusion (upstream 7d1016f3). `chain_swiglu_quant_kernel` + // replaces the pair `swiglu_entries_kernel` + `quantize_q8_1_kernel` of mtp_original_full_head_iq (the window's + // routed-expert path, moe.rs). A fused producer and the kernels it replaces must divide the same way: + // `div.rn.f32` (IEEE) against `div.approx.ftz.f32` / `div.full.f32` (`--use_fast_math`) gives a different q8_1 + // code at about one element in 10^6. These tests read the sealed PTX text on the CPU. /// The body of the one `.entry` whose mangled or plain name contains `name`. fn entry_body<'t>(ptx: &'t str, name: &str) -> &'t str { @@ -227,8 +231,9 @@ mod tests { found.unwrap_or_else(|| panic!("no entry {name}")) } - /// Opcode (with its modifiers) -> count, over the instructions that decide a q8_1 code: float arithmetic, rounding, conversions, - /// comparisons and warp shuffles. Loads, stores, address arithmetic and branches differ between a fused and a split producer. + /// Opcode (with its modifiers) -> count, over the instructions that decide a q8_1 code: float arithmetic, + /// rounding, conversions, comparisons and warp shuffles. Loads, stores, address arithmetic and branches differ + /// between a fused and a split producer. fn numeric_ops(body: &str) -> std::collections::BTreeMap { let mut ops = std::collections::BTreeMap::new(); for line in body.lines() { @@ -293,7 +298,8 @@ mod tests { #[test] fn the_parity_check_flags_a_fast_math_quantizer() { - // the fast-math quantizer copy (native_head_iq, `--use_fast_math`) is a different flavour: this check must tell them apart + // the fast-math quantizer copy (native_head_iq, `--use_fast_math`) is a different flavour: this check must + // tell them apart let fast = numeric_ops(entry_body( &String::from_utf8_lossy(include_bytes!("native_head_iq.ptx")), "quantize_q8_1_kernel", diff --git a/crates/cuda-driver/src/original_verify_window_draft.rs b/crates/cuda-driver/src/original_verify_window_draft.rs index d5ed705b..b19d5331 100644 --- a/crates/cuda-driver/src/original_verify_window_draft.rs +++ b/crates/cuda-driver/src/original_verify_window_draft.rs @@ -1,15 +1,18 @@ //! claude/draft-round: the fused verifier commit graph (`draft_commit.cu`, `draft_commit_qsa.cu`). //! -//! The commit graph of the Original-literal verifier is 182 serial kernel nodes (36 GDN layers x conv commit + recurrence replay, 12 QSA layers x tail restore + 8 row appends, -//! the PLE history copy, the first mapped copy). `LELEKA_DRAFT_FUSED_COMMIT=on` records it as the same first and last node plus one launch for all GDN layers and one for all QSA -//! layers (`draft_commit_gdn_layers`, `draft_commit_qsa_layers`): every state word is computed by the same operations in the same order (proved by the model-free probe -//! `tools/draft-round/commit_probe.cpp` and the replay identity gate, docs/experiments/draft-round-5090.md). Off by default until its paired A/B. +//! The commit graph of the Original-literal verifier is 182 serial kernel nodes (36 GDN layers x conv commit + +//! recurrence replay, 12 QSA layers x tail restore + 8 row appends, the PLE history copy, the first mapped copy). +//! `LELEKA_DRAFT_FUSED_COMMIT=on` records it as the same first and last node plus one launch for all GDN layers and +//! one for all QSA layers (`draft_commit_gdn_layers`, `draft_commit_qsa_layers`): every state word is computed by the +//! same operations in the same order (proved by the model-free probe `tools/draft-round/commit_probe.cpp` and the +//! replay identity gate, docs/experiments/draft-round-5090.md). Off by default until its paired A/B. use super::kernels::AssetSpec; pub(crate) const E_GDN: &str = "draft_commit_gdn_layers"; pub(crate) const E_QSA: &str = "draft_commit_qsa_layers"; -/// `draft_commit.cu` (GDN layers, precise math), sealed by `scripts/gpu-bringup/seal_pins.py` (extra-seal-plan.json, group draft-round). +/// `draft_commit.cu` (GDN layers, precise math), sealed by `scripts/gpu-bringup/seal_pins.py` (extra-seal-plan.json, +/// group draft-round). pub(crate) static DRAFT_COMMIT: AssetSpec = AssetSpec { name: "draft_commit.ptx", ptx: concat!(include_str!("draft_commit.ptx"), "\0").as_bytes(), @@ -33,7 +36,8 @@ pub(crate) static DRAFT_COMMIT_QSA: AssetSpec = AssetSpec { unsealed: "Original verifier asset unsealed: draft_commit_qsa.ptx (fused verifier commit graph, QSA layers)", }; -/// `LELEKA_DRAFT_FUSED_COMMIT=on|1`: record the commit graph with the fused kernels. Read once per process (it decides which kernels the commit graph records). +/// `LELEKA_DRAFT_FUSED_COMMIT=on|1`: record the commit graph with the fused kernels. Read once per process (it +/// decides which kernels the commit graph records). pub(crate) fn fused_commit() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| fused_commit_from(std::env::var("LELEKA_DRAFT_FUSED_COMMIT").ok().as_deref())) 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 9eb1cf50..4c13124b 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 @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn assets, impl GrVariant, impl GrConfig, fn shared_attributes, fn tiled_down_geometry, impl PleConfig .... +//! Moved out of the parent module by STRA-338: fn assets, impl GrVariant, impl GrConfig, fn shared_attributes, fn +//! tiled_down_geometry, impl PleConfig .... #[allow(unused_imports)] use super::*; @@ -109,8 +110,9 @@ pub(crate) fn shared_attributes(cfg: &GrConfig) -> Vec<(&'static AssetSpec, &'st out } -/// Grid and dynamic shared bytes of `chain_gr_down_t2w8_nb4` for a launch of `tokens` rows: 41 blocks of 8 rows per pair of tokens (grid.y = ceil(tokens / 2)), -/// four tile buffers of two tokens (`tools/chain-probe/chain_probe.cpp` launches it with the same formulas). +/// Grid and dynamic shared bytes of `chain_gr_down_t2w8_nb4` for a launch of `tokens` rows: 41 blocks of 8 rows per +/// pair of tokens (grid.y = ceil(tokens / 2)), four tile buffers of two tokens (`tools/chain-probe/chain_probe.cpp` +/// launches it with the same formulas). pub(crate) fn tiled_down_geometry(tokens: usize) -> ([u32; 3], u32) { ([DOWN_BLOCKS, tokens.div_ceil(2) as u32, 1], 4 * tokens.min(2) as u32 * (STAGED_TILE * 4)) } 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 44c00315..f1e161f5 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 @@ -31,7 +31,8 @@ pub(crate) fn plan_hc_read( 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. +/// 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"), diff --git a/crates/cuda-driver/src/original_verify_window_gr/tests/head_mix_is_the_native.rs b/crates/cuda-driver/src/original_verify_window_gr/tests/head_mix_is_the_native.rs index 5cafe3c5..d2473db6 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/tests/head_mix_is_the_native.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/tests/head_mix_is_the_native.rs @@ -1,9 +1,50 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): head_mix_is_the_native_unfused_gr_read_per_token, ple_scratch_matches_ple_block_workspace_carving, ple_row_with_a_bf16_key_follows_ple_block_native_order, ple_row_with_a_native_key_quantizes_into_the_arena_and_runs_mmvq .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! head_mix_is_the_native_unfused_gr_read_per_token, ple_scratch_matches_ple_block_workspace_carving, +//! ple_row_with_a_bf16_key_follows_ple_block_native_order, +//! ple_row_with_a_native_key_quantizes_into_the_arena_and_runs_mmvq .... #[allow(unused_imports)] use super::*; // ------------------------------------------------------------------------------------ head +/// The five launches of head row `t`, against the native unfused gr read. +fn assert_head_mix_row(m: &LayoutMap, k: &[Launch], t: usize, mixed_base: u64) { + let r = at(m, "R", t * 40_960); + let xn = at(m, "xn", t * 40_960); + let lo = at(m, "lo", t * 1280); + let gated = at(m, "parts", t * 10 * 2560 * 4); + let mixed = mixed_base + (t * 10_240) as u64; + // 1. native_gr_rms_norm_weighted: hc blocks of 1024 threads + assert_eq!((k[0].entry, k[0].grid, k[0].block), ("mtp_full_gr_norm", [4, 1, 1], [1024, 1, 1])); + assert_eq!(k[0].args, vec![A::P(r), A::P(0xA000), A::P(xn), A::I32(2560), A::F32(1e-6)]); + // 2. bf16_gemv_fp32_mmvf(xn, down -> lo, 10240 -> 320): mmvf block 256 + assert_eq!((k[1].entry, k[1].grid, k[1].block), ("mtp_full_mmvf256", [320, 1, 1], [256, 1, 1])); + assert_eq!(k[1].args, vec![A::P(xn), A::P(0xB000), A::P(lo), A::I32(10_240)]); + // 3. native_gr_down_silu(lo, 320, 1/4): ceil(320/256) = 2 blocks + assert_eq!((k[2].entry, k[2].grid, k[2].block), ("mtp_full_down_silu", [2, 1, 1], [256, 1, 1])); + assert_eq!(k[2].args, vec![A::P(lo), A::I32(320), A::F32(0.25)]); + // 4. bf16_gemv_fp32_mmvf(lo, up -> gated, 320 -> 10240): mmvf block 160 (ceil(320/320) = 1 iteration) + assert_eq!((k[3].entry, k[3].grid, k[3].block), ("mtp_full_mmvf160", [10_240, 1, 1], [160, 1, 1])); + assert_eq!(k[3].args, vec![A::P(lo), A::P(0xC000), A::P(gated), A::I32(320)]); + // 5. native_gr_pre_gated(xn, gated, mixed, n, hc, 1/4): 10 blocks + assert_eq!((k[4].entry, k[4].grid, k[4].block), ("mtp_full_pre_final", [10, 1, 1], [256, 1, 1])); + assert_eq!(k[4].args, vec![A::P(xn), A::P(gated), A::P(mixed), A::I32(2560), A::I32(4), A::F32(0.25)]); +} + +/// The whole window: 1..=8 rows; none beyond max_t; the non-native mmvf refuses. +fn assert_head_mix_row_bounds(m: &LayoutMap, w: &HeadAddrs, mixed_base: u64) { + let g = test_geometry(); + assert!(plan_head_mix(m, &g, w, &sm120(GrVariant::Staged), mixed_base, 8).is_ok()); + assert!(plan_head_mix(m, &g, w, &sm120(GrVariant::Staged), mixed_base, 9).is_err()); + assert!(plan_head_mix(m, &g, w, &sm120(GrVariant::Staged), mixed_base, 0).is_err()); + let mut non_native = sm120(GrVariant::Staged); + non_native.native_mmvf = false; + assert!(matches!( + plan_head_mix(m, &g, w, &non_native, mixed_base, 1), + Err(Error::InvalidDriverValue(s)) if s.contains("head") + )); +} + #[test] fn head_mix_is_the_native_unfused_gr_read_per_token() { let m = arena(); @@ -13,38 +54,9 @@ fn head_mix_is_the_native_unfused_gr_read_per_token() { let l = plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 3).unwrap(); assert_eq!(l.len(), 15); for t in 0..3usize { - let k = &l[t * 5..t * 5 + 5]; - let r = at(&m, "R", t * 40_960); - let xn = at(&m, "xn", t * 40_960); - let lo = at(&m, "lo", t * 1280); - let gated = at(&m, "parts", t * 10 * 2560 * 4); - let mixed = mixed_base + (t * 10_240) as u64; - // 1. native_gr_rms_norm_weighted: hc blocks of 1024 threads - assert_eq!((k[0].entry, k[0].grid, k[0].block), ("mtp_full_gr_norm", [4, 1, 1], [1024, 1, 1])); - assert_eq!(k[0].args, vec![A::P(r), A::P(0xA000), A::P(xn), A::I32(2560), A::F32(1e-6)]); - // 2. bf16_gemv_fp32_mmvf(xn, down -> lo, 10240 -> 320): mmvf block 256 - assert_eq!((k[1].entry, k[1].grid, k[1].block), ("mtp_full_mmvf256", [320, 1, 1], [256, 1, 1])); - assert_eq!(k[1].args, vec![A::P(xn), A::P(0xB000), A::P(lo), A::I32(10_240)]); - // 3. native_gr_down_silu(lo, 320, 1/4): ceil(320/256) = 2 blocks - assert_eq!((k[2].entry, k[2].grid, k[2].block), ("mtp_full_down_silu", [2, 1, 1], [256, 1, 1])); - assert_eq!(k[2].args, vec![A::P(lo), A::I32(320), A::F32(0.25)]); - // 4. bf16_gemv_fp32_mmvf(lo, up -> gated, 320 -> 10240): mmvf block 160 (ceil(320/320) = 1 iteration) - assert_eq!((k[3].entry, k[3].grid, k[3].block), ("mtp_full_mmvf160", [10_240, 1, 1], [160, 1, 1])); - assert_eq!(k[3].args, vec![A::P(lo), A::P(0xC000), A::P(gated), A::I32(320)]); - // 5. native_gr_pre_gated(xn, gated, mixed, n, hc, 1/4): 10 blocks - assert_eq!((k[4].entry, k[4].grid, k[4].block), ("mtp_full_pre_final", [10, 1, 1], [256, 1, 1])); - assert_eq!(k[4].args, vec![A::P(xn), A::P(gated), A::P(mixed), A::I32(2560), A::I32(4), A::F32(0.25)]); + assert_head_mix_row(&m, &l[t * 5..t * 5 + 5], t, mixed_base); } - // the whole window: 1..=8 rows; none beyond max_t - assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 8).is_ok()); - assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 9).is_err()); - assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 0).is_err()); - let mut non_native = sm120(GrVariant::Staged); - non_native.native_mmvf = false; - assert!(matches!( - plan_head_mix(&m, &g, &w, &non_native, mixed_base, 1), - Err(Error::InvalidDriverValue(s)) if s.contains("head") - )); + assert_head_mix_row_bounds(&m, &w, mixed_base); } #[test] @@ -60,12 +72,8 @@ fn ple_scratch_matches_ple_block_workspace_carving() { assert_eq!(SCRATCH_GATE + 16, PLE_SCRATCH_BYTES as u64); } -#[test] -fn ple_row_with_a_bf16_key_follows_ple_block_native_order() { - let m = arena(); - let g = test_geometry(); - let a = ple_addrs(PleKey::Bf16(0x7000_0000)); - let l = plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &a, 2).unwrap(); +/// The ten launches of a bf16-key PLE row, by entry name. +fn assert_ple_bf16_row_names(l: &[Launch]) { let names: Vec<&str> = l.iter().map(|x| x.entry).collect(); assert_eq!( names, @@ -82,8 +90,10 @@ fn ple_row_with_a_bf16_key_follows_ple_block_native_order() { "ple_history", ] ); - let r = at(&m, "R", 2 * 40_960); - let emb = at(&m, "ple", 2 * 10_240); +} + +/// The write, the two projections and the two norms of the row (`r` = the residual row, `s` = the scratch). +fn assert_ple_bf16_row_projections(l: &[Launch], r: u64, emb: u64) { let s = 0x6000_0000u64; assert_eq!(l[0].args[0], A::P(r)); assert_eq!(l[0].args[3], A::P(r)); @@ -97,6 +107,11 @@ fn ple_row_with_a_bf16_key_follows_ple_block_native_order() { assert_eq!(l[3].args, vec![A::P(s), A::P(0x5100_0000), A::P(s + 40_960)]); assert_eq!(l[4].args, vec![A::P(r), A::P(0x5200_0000), A::P(s + 81_920)]); assert_eq!((l[3].grid, l[3].block), ([4, 1, 1], [1024, 1, 1])); +} + +/// The gate, broadcast, norm, conv and history launches of the row. +fn assert_ple_bf16_row_postops(l: &[Launch], r: u64) { + let s = 0x6000_0000u64; assert_eq!((l[5].grid, l[5].block), ([4, 1, 1], [512, 1, 1])); assert_eq!(l[5].args, vec![A::P(s + 40_960), A::P(s + 81_920), A::P(s + 215_040), A::F32(1.0 / 2560f32.sqrt())]); assert_eq!((l[6].grid, l[6].block), ([40, 1, 1], [256, 1, 1])); @@ -119,6 +134,19 @@ fn ple_row_with_a_bf16_key_follows_ple_block_native_order() { // history advance reads the normalized row from the workspace assert_eq!(l[9].args, vec![A::P(0x6100_0000), A::P(s + 81_920), A::I32(1)]); assert_eq!((l[9].grid, l[9].block), ([40, 1, 1], [256, 1, 1])); +} + +#[test] +fn ple_row_with_a_bf16_key_follows_ple_block_native_order() { + let m = arena(); + let g = test_geometry(); + let a = ple_addrs(PleKey::Bf16(0x7000_0000)); + let l = plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &a, 2).unwrap(); + assert_ple_bf16_row_names(&l); + let r = at(&m, "R", 2 * 40_960); + let emb = at(&m, "ple", 2 * 10_240); + assert_ple_bf16_row_projections(&l, r, emb); + assert_ple_bf16_row_postops(&l, r); for launch in &l[3..] { assert!(std::ptr::eq(launch.asset, &PLE_BATCH)); } diff --git a/crates/cuda-driver/src/original_verify_window_gr/tests/tiled_down_projection_covers.rs b/crates/cuda-driver/src/original_verify_window_gr/tests/tiled_down_projection_covers.rs index 68871425..92d3bbaf 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/tests/tiled_down_projection_covers.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/tests/tiled_down_projection_covers.rs @@ -1,4 +1,7 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): the_tiled_down_projection_covers_every_row_and_token_with_four_two_token_tile_buffers, assets_are_pinned_and_export_every_named_entry, struct_layout_constants_match_fused_gr_args, down_chunk_on_big_cards_runs_the_2560_tile_with_all_eight_tokens .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! the_tiled_down_projection_covers_every_row_and_token_with_four_two_token_tile_buffers, +//! assets_are_pinned_and_export_every_named_entry, struct_layout_constants_match_fused_gr_args, +//! down_chunk_on_big_cards_runs_the_2560_tile_with_all_eight_tokens .... #[allow(unused_imports)] use super::*; @@ -117,12 +120,8 @@ fn variant_follows_strata_hc_split() { } // ------------------------------------------------------------------------------- hc_read -#[test] -fn staged_read_of_eight_rows_is_three_launch_kinds_with_the_multi_struct() { - let m = arena(); - let g = test_geometry(); - let w = weights(); - let plan = plan_hc_read(&m, &g, &w, &sm120(GrVariant::Staged), HcHalf::Attention, true, rows(0, 8, 0)).unwrap(); +/// The three launch kinds of a staged eight-row read, and the multi-struct all three carry. +fn assert_staged_read_launch_kinds(plan: &HcReadPlan) -> Vec { // norm: split, one block per token and stream assert_eq!( (plan.norm.entry, plan.norm.grid, plan.norm.block, plan.norm.shared), @@ -137,6 +136,16 @@ fn staged_read_of_eight_rows_is_three_launch_kinds_with_the_multi_struct() { let full = words(&plan.norm).to_vec(); assert_eq!(words(&plan.up), &full[..]); assert_eq!(words(d), &full[..]); + full +} + +#[test] +fn staged_read_of_eight_rows_is_three_launch_kinds_with_the_multi_struct() { + let m = arena(); + let g = test_geometry(); + let w = weights(); + let plan = plan_hc_read(&m, &g, &w, &sm120(GrVariant::Staged), HcHalf::Attention, true, rows(0, 8, 0)).unwrap(); + let full = assert_staged_read_launch_kinds(&plan); assert_eq!(full.len(), 114); // trailer: xn = xn_ + tb*HC*N*4, T = 8 assert_eq!(full[112], at(&m, "xn", 0)); @@ -266,6 +275,27 @@ fn hc_read_validates_rows_and_geometry() { } // ----------------------------------------------------------------------------- final write +/// One final-write launch of row `t`: native post, in place on `R`. +fn assert_final_write_launch(m: &LayoutMap, launch: &Launch, t: usize) { + assert!(std::ptr::eq(launch.asset, &GR_POST)); + assert_eq!( + (launch.entry, launch.grid, launch.block, launch.shared), + ("mtp_full_native_write", [40, 1, 1], [256, 1, 1], 0) + ); + assert_eq!( + launch.args, + vec![ + A::P(at(m, "R", t * 40_960)), + A::P(at(m, "bo", t * 10_240)), + A::P(at(m, "inj2", t * 16)), + A::P(at(m, "R", t * 40_960)), + A::I32(2560), + A::I32(4), + A::F32(0.25), + ] + ); +} + #[test] fn final_write_is_native_post_in_place_per_row() { let m = arena(); @@ -273,24 +303,7 @@ fn final_write_is_native_post_in_place_per_row() { let l = plan_final_write(&m, &g, &sm120(GrVariant::Staged), rows(2, 5, 0)).unwrap(); assert_eq!(l.len(), 3); for (i, launch) in l.iter().enumerate() { - let t = 2 + i; - assert!(std::ptr::eq(launch.asset, &GR_POST)); - assert_eq!( - (launch.entry, launch.grid, launch.block, launch.shared), - ("mtp_full_native_write", [40, 1, 1], [256, 1, 1], 0) - ); - assert_eq!( - launch.args, - vec![ - A::P(at(&m, "R", t * 40_960)), - A::P(at(&m, "bo", t * 10_240)), - A::P(at(&m, "inj2", t * 16)), - A::P(at(&m, "R", t * 40_960)), - A::I32(2560), - A::I32(4), - A::F32(0.25), - ] - ); + assert_final_write_launch(&m, launch, 2 + i); } let mut non_native = sm120(GrVariant::Staged); non_native.native_mmvf = false; diff --git a/crates/cuda-driver/src/original_verify_window_moe.rs b/crates/cuda-driver/src/original_verify_window_moe.rs index 69b557bd..f8ed38e8 100644 --- a/crates/cuda-driver/src/original_verify_window_moe.rs +++ b/crates/cuda-driver/src/original_verify_window_moe.rs @@ -75,7 +75,10 @@ pub(crate) static ROUTER: AssetSpec = AssetSpec { unsealed: "Original verifier asset unsealed: mtp_original_full_router.ptx (native router top-10)", }; -const E_ROUTER_TOP10: &str = "_ZN6strata7kernels67_GLOBAL__N__bb863e17_34_mtp_original_full_router_legacy_cu_731ba72319router_top10_kernelEPKfiiiPiPf"; +const E_ROUTER_TOP10: &str = concat!( + "_ZN6strata7kernels67_GLOBAL__N__bb863e17_34_mtp_original_full_router_legacy_cu_731ba72319router_top10_", + "kernelEPKfiiiPiPf" +); /// `router_top10.cu` (`router_top10`, the generic router when the native one is off). pub(crate) static ROUTER_LEGACY: AssetSpec = AssetSpec { name: "mtp_original_full_router_legacy.ptx", @@ -94,10 +97,16 @@ const E_SCALAR_GATE: &str = "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f18scalar_gate_kernelEPKtS3_Pfi"; const E_SIGMOID: &str = "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f28native_scalar_sigmoid_kernelEPf"; -const E_SIGMOID_MULTI: &str = "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f34native_scalar_sigmoid_multi_kernelEPf"; +const E_SIGMOID_MULTI: &str = concat!( + "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f34native_scalar_sigmoid_multi_", + "kernelEPf" +); const E_SCALE_ROWS: &str = "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f17scale_rows_kernelEPfPKfi"; -const E_MOE_COMBINE: &str = "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f18moe_combine_kernelEPKfS3_S3_Pfiii"; +const E_MOE_COMBINE: &str = concat!( + "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f18moe_combine_kernelEPKfS3_S3_", + "Pfiii" +); /// `shared_expert.cu` (the Original TU: `shared_expert_multi`'s kernels and `moe_combine`). pub(crate) static SHARED: AssetSpec = AssetSpec { name: "mtp_original_full_shared.ptx", @@ -110,8 +119,14 @@ pub(crate) static SHARED: AssetSpec = AssetSpec { unsealed: "Original verifier asset unsealed: mtp_original_full_shared.ptx (shared expert)", }; -const E_SWIGLU_ENTRIES: &str = "_ZN6strata7kernels65_GLOBAL__N__a184a76c_28_mtp_original_full_head_iq_cu_934c6f21_28421swiglu_entries_kernelEPKfS3_Pfx"; -const E_QUANTIZE_Q8_1: &str = "_ZN6strata7kernels65_GLOBAL__N__a184a76c_28_mtp_original_full_head_iq_cu_934c6f21_28420quantize_q8_1_kernelEPKfP10block_q8_1x"; +const E_SWIGLU_ENTRIES: &str = concat!( + "_ZN6strata7kernels65_GLOBAL__N__a184a76c_28_mtp_original_full_head_iq_cu_934c6f21_28421swiglu_entries_", + "kernelEPKfS3_Pfx" +); +const E_QUANTIZE_Q8_1: &str = concat!( + "_ZN6strata7kernels65_GLOBAL__N__a184a76c_28_mtp_original_full_head_iq_cu_934c6f21_28420quantize_q8_1_", + "kernelEPKfP10block_q8_1x" +); /// `iq_kernels.cu`: the entry-wise SwiGLU and the q8_1 quantizer of `native_expert_grouped` / /// `quantize_q8_1_rows`. The same PTX file as `proj::HEAD_IQ` (same pin); `proj` names only the MMVQ heads, /// so the window's MoE owns this entry list under a distinct asset name (the lead's loader must key modules by @@ -205,7 +220,10 @@ pub(crate) static EXPERTS: AssetSpec = AssetSpec { 72, 140, 6, 238, 35, 130, 17, 87, ], entries: EXPERT_ENTRIES, - unsealed: "Original verifier asset unsealed: original_verify_window_moe_experts.ptx (grouped native expert gate/up and down)", + unsealed: concat!( + "Original verifier asset unsealed: original_verify_window_moe_experts.ptx (grouped native expert gate/up and ", + "down)" + ), }; /// The verify window's PCIe staging copy over the three-span expert source (`original_verify_window_pcie.cu`: @@ -263,7 +281,8 @@ pub(crate) struct MoeKnobs { pub native_bf16_extra: bool, /// `native_mmvq` dispatch of the shared expert's projections. pub dispatch: NativeHeadDispatch, - /// sm_120 `GU_SWIGLU` (`original_verify_window_sm120.rs`): the fused gate/up + SwiGLU + q8_1 kernel for the formats that have one. + /// sm_120 `GU_SWIGLU` (`original_verify_window_sm120.rs`): the fused gate/up + SwiGLU + q8_1 kernel for the + /// formats that have one. pub gu_swiglu: bool, } diff --git a/crates/cuda-driver/src/original_verify_window_moe/pcie_fast_kernel_fn.rs b/crates/cuda-driver/src/original_verify_window_moe/pcie_fast_kernel_fn.rs index 2b8f395d..55eae8bc 100644 --- a/crates/cuda-driver/src/original_verify_window_moe/pcie_fast_kernel_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_moe/pcie_fast_kernel_fn.rs @@ -1,11 +1,12 @@ -//! Moved out of the parent module by STRA-338: fn pcie_fast_kernel, fn assets, fn shared_attributes, impl MoeKnobs, fn gu_qk, fn d_qk .... +//! Moved out of the parent module by STRA-338: fn pcie_fast_kernel, fn assets, fn shared_attributes, impl MoeKnobs, +//! fn gu_qk, fn d_qk .... #[allow(unused_imports)] use super::*; -/// `LELEKA_PCIE_KERNEL` = `k1u4|k1u8|k1u16|k2u4|k2u8|k2u16` selects an alternative staging copy kernel of the copy-kernel -/// PCIe mode (default: the sealed `verify_fetch_spans_kernel`); `LELEKA_PCIE_GRID=BLOCKSxTHREADS` its launch shape -/// (default 384x256, the Original's `48 * 8` blocks of 256). +/// `LELEKA_PCIE_KERNEL` = `k1u4|k1u8|k1u16|k2u4|k2u8|k2u16` selects an alternative staging copy kernel of the +/// copy-kernel PCIe mode (default: the sealed `verify_fetch_spans_kernel`); `LELEKA_PCIE_GRID=BLOCKSxTHREADS` its +/// launch shape (default 384x256, the Original's `48 * 8` blocks of 256). pub(crate) fn pcie_fast_kernel() -> Option<(&'static str, [u32; 3], [u32; 3])> { static CHOICE: std::sync::OnceLock> = std::sync::OnceLock::new(); *CHOICE.get_or_init(|| { 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 f97e5d6d..87bca9f8 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 @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn plan_f32_to_bf16, fn plan_route, fn plan_router, fn plan_shared_expert, fn plan_quantize_expert_input, fn expert_scratch. +//! Moved out of the parent module by STRA-338: fn plan_f32_to_bf16, fn plan_route, fn plan_router, fn +//! plan_shared_expert, fn plan_quantize_expert_input, fn expert_scratch. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/original_verify_window_moe/tests/alternative_pcie_staging_copy.rs b/crates/cuda-driver/src/original_verify_window_moe/tests/alternative_pcie_staging_copy.rs index 1f546723..ab85bcf2 100644 --- a/crates/cuda-driver/src/original_verify_window_moe/tests/alternative_pcie_staging_copy.rs +++ b/crates/cuda-driver/src/original_verify_window_moe/tests/alternative_pcie_staging_copy.rs @@ -1,4 +1,7 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): the_alternative_pcie_staging_copy_kernels_are_sealed, sealed_assets_are_pinned_and_export_every_named_entry, expert_asset_is_sealed_and_a_corrupted_copy_still_refuses_to_load, expert_entries_match_the_cu_source_and_the_original_format_lists .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! the_alternative_pcie_staging_copy_kernels_are_sealed, sealed_assets_are_pinned_and_export_every_named_entry, +//! expert_asset_is_sealed_and_a_corrupted_copy_still_refuses_to_load, +//! expert_entries_match_the_cu_source_and_the_original_format_lists .... #[allow(unused_imports)] use super::*; @@ -31,20 +34,18 @@ fn expert_asset_is_sealed_and_a_corrupted_copy_still_refuses_to_load() { assert!(EXPERTS.unsealed.contains("original_verify_window_moe_experts.ptx")); } -#[test] -fn expert_entries_match_the_cu_source_and_the_original_format_lists() { - let cu = include_str!("../../original_verify_window_moe_experts.cu"); - assert!(cu.contains("window_moe_gu_##T") && cu.contains("window_moe_down_##T")); - assert!(cu.contains("STRATA_GU_FMTS(STRATA_WINDOW_GU)") && cu.contains("STRATA_D_FMTS(STRATA_WINDOW_DOWN)")); - let iq = include_str!("../../mtp_original_full_head_iq.cu"); - let parse = |macro_name: &str| -> Vec { - let line = iq.lines().find(|l| l.starts_with(&format!("#define {macro_name}(X)"))).expect(macro_name); - line.split("X(").skip(1).map(|s| s.split(')').next().unwrap().parse().unwrap()).collect() - }; +/// The format ids of a `#define (X) X(a) X(b) ...` line of the Original's head_iq source. +fn parse_format_macro(iq: &str, macro_name: &str) -> Vec { + let line = iq.lines().find(|l| l.starts_with(&format!("#define {macro_name}(X)"))).expect(macro_name); + line.split("X(").skip(1).map(|s| s.split(')').next().unwrap().parse().unwrap()).collect() +} + +/// The entry tables list the formats of the Original, and every entry is exported and non-trivial. +fn assert_expert_entry_tables(iq: &str) { let gu: Vec = GU_ENTRIES.iter().map(|e| e.0).collect(); let d: Vec = DOWN_ENTRIES.iter().map(|e| e.0).collect(); - assert_eq!(gu, parse("STRATA_GU_FMTS")); - assert_eq!(d, parse("STRATA_D_FMTS")); + assert_eq!(gu, parse_format_macro(iq, "STRATA_GU_FMTS")); + assert_eq!(d, parse_format_macro(iq, "STRATA_D_FMTS")); for (t, name) in GU_ENTRIES { assert_eq!(*name, format!("window_moe_gu_{t}")); assert!(EXPERTS.has_entry(name) && gu_qk(*t) > 0); @@ -54,7 +55,10 @@ fn expert_entries_match_the_cu_source_and_the_original_format_lists() { assert!(EXPERTS.has_entry(name) && d_qk(*t) > 0); } assert_eq!(EXPERTS.entries.len(), GU_ENTRIES.len() + DOWN_ENTRIES.len()); - // the Original's per-type values-per-block (Fmt::qk) used by native_expert_supported +} + +/// The Original's per-type values-per-block (`Fmt::qk`) used by `native_expert_supported`. +fn assert_expert_format_qk(iq: &str) { for (t, _) in GU_ENTRIES { let want = format!("template<> struct Fmt<{t}> {{ static constexpr int qk = {},", gu_qk(*t)); assert!(iq.contains(&want), "{want}"); @@ -63,6 +67,17 @@ fn expert_entries_match_the_cu_source_and_the_original_format_lists() { let want = format!("template<> struct Fmt<{t}> {{ static constexpr int qk = {},", d_qk(*t)); assert!(iq.contains(&want), "{want}"); } +} + +#[test] +fn expert_entries_match_the_cu_source_and_the_original_format_lists() { + let cu = include_str!("../../original_verify_window_moe_experts.cu"); + assert!(cu.contains("window_moe_gu_##T") && cu.contains("window_moe_down_##T")); + assert!(cu.contains("STRATA_GU_FMTS(STRATA_WINDOW_GU)") && cu.contains("STRATA_D_FMTS(STRATA_WINDOW_DOWN)")); + let iq = include_str!("../../mtp_original_full_head_iq.cu"); + assert_expert_entry_tables(iq); + // the Original's per-type values-per-block (Fmt::qk) used by native_expert_supported + assert_expert_format_qk(iq); assert_eq!((gu_qk(20), gu_qk(7), d_qk(16), d_qk(12), d_qk(0)), (0, 0, 0, 0, 0)); } @@ -192,26 +207,18 @@ fn router_fails_closed_precisely_without_native_bf16_and_on_bad_shapes() { // ---- shared expert ----------------------------------------------------------------------- -#[test] -fn batched_shared_expert_runs_the_shared_expert_multi_sequence_in_order() { - let m = map(); - let g = test_geometry(); - let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(2, 6, 1), true).unwrap(); - // f32_to_bf16_bulk(4 rows), quantize x, MMVQ gate, MMVQ up, swiglu, quantize h, MMVQ down, - // gate GEMV (multi), sigmoid (multi), scale rows - assert_eq!(l.len(), 10); +/// The shared expert's bf16 conversion, activation quantize, gate/up projections and swiglu (launches 0..=5). +fn assert_shared_expert_up_to_swiglu(m: &LayoutMap, l: &[Launch]) { assert!(l[0].entry.ends_with("to_bf16_kernelEPKfPtl")); assert_eq!((l[0].grid, l[0].block), ([40, 1, 1], [256, 1, 1])); // 4*2560 = 10240 elements assert_eq!( l[0].args, - vec![A::P(at(&m, "mixed", 2 * 2560 * 4)), A::P(at(&m, "sh_bf16", 2 * 2560 * 2)), A::I64(10240)] + vec![A::P(at(m, "mixed", 2 * 2560 * 4)), A::P(at(m, "sh_bf16", 2 * 2560 * 2)), A::I64(10240)] ); - let xq = at(&m, "xq", 0); - let xm = at(&m, "mixed", 2 * 2560 * 4); - let gate = at(&m, "sh_gate", 2 * 640 * 4); - let up = at(&m, "sh_up", 2 * 640 * 4); - let shared = at(&m, "shared", 2 * 2560 * 4); - let gs = at(&m, "sh_g", 2 * 4); + let xq = at(m, "xq", 0); + let xm = at(m, "mixed", 2 * 2560 * 4); + let gate = at(m, "sh_gate", 2 * 640 * 4); + let up = at(m, "sh_up", 2 * 640 * 4); assert_eq!(l[1].entry, "head_quant"); assert_eq!(l[1].args, vec![A::P(xm), A::P(xq), A::I32(4 * 2560)]); // gate/up: Q8_0, 4 columns: head_n8_t4_large, y rows n_ff floats apart @@ -225,6 +232,14 @@ fn batched_shared_expert_runs_the_shared_expert_multi_sequence_in_order() { assert_eq!(l[4].args, vec![A::P(gate), A::P(up), A::P(gate), A::I32(2560)]); // quantize the activated gate (640 elements per row) in place into xq, then the down projection assert_eq!(l[5].args, vec![A::P(gate), A::P(xq), A::I32(4 * 640)]); +} + +/// The shared expert's down projection, scalar gate, sigmoid and row scale (launches 6..=9). +fn assert_shared_expert_down_and_gate(m: &LayoutMap, l: &[Launch]) { + let xq = at(m, "xq", 0); + let xm = at(m, "mixed", 2 * 2560 * 4); + let shared = at(m, "shared", 2 * 2560 * 4); + let gs = at(m, "sh_g", 2 * 4); // down: n_in = 640 values is "small" for Q8_0 (640/32 < 32 blocks per iteration) assert_eq!(l[6].entry, "head_n8_t4_small"); assert_eq!(l[6].args, vec![A::P(0x9400_0000), A::P(xq), A::P(shared), A::I32(640), A::I32(2560)]); @@ -241,6 +256,18 @@ fn batched_shared_expert_runs_the_shared_expert_multi_sequence_in_order() { assert!(l[9].entry.ends_with("scale_rows_kernelEPfPKfi")); assert_eq!((l[9].grid, l[9].block), ([20, 4, 1], [128, 1, 1])); assert_eq!(l[9].args, vec![A::P(shared), A::P(gs), A::I32(2560)]); +} + +#[test] +fn batched_shared_expert_runs_the_shared_expert_multi_sequence_in_order() { + let m = map(); + let g = test_geometry(); + let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(2, 6, 1), true).unwrap(); + // f32_to_bf16_bulk(4 rows), quantize x, MMVQ gate, MMVQ up, swiglu, quantize h, MMVQ down, + // gate GEMV (multi), sigmoid (multi), scale rows + assert_eq!(l.len(), 10); + assert_shared_expert_up_to_swiglu(&m, &l); + assert_shared_expert_down_and_gate(&m, &l); assert_abi(&l); } diff --git a/crates/cuda-driver/src/original_verify_window_moe/tests/hit_add_scans_the_cpu.rs b/crates/cuda-driver/src/original_verify_window_moe/tests/hit_add_scans_the_cpu.rs index 292f23cd..a5566481 100644 --- a/crates/cuda-driver/src/original_verify_window_moe/tests/hit_add_scans_the_cpu.rs +++ b/crates/cuda-driver/src/original_verify_window_moe/tests/hit_add_scans_the_cpu.rs @@ -1,4 +1,7 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): hit_add_scans_the_cpu_and_gpu_hits_of_the_group, batched_combine_is_one_launch_with_the_token_on_grid_y, per_row_combine_is_native_combine_per_token_or_the_legacy_kernel, plan_word_stays_inside_the_plan_span_and_the_two_groups. +//! Tests of tests by topic (moved out of the test file by STRA-338): hit_add_scans_the_cpu_and_gpu_hits_of_the_group, +//! batched_combine_is_one_launch_with_the_token_on_grid_y, +//! per_row_combine_is_native_combine_per_token_or_the_legacy_kernel, +//! plan_word_stays_inside_the_plan_span_and_the_two_groups. #[allow(unused_imports)] use super::*; @@ -56,28 +59,33 @@ fn batched_combine_is_one_launch_with_the_token_on_grid_y() { assert_eq!(b[0].args[3], A::P(at(&m, "bo", 4 * 2560 * 4))); } -#[test] -fn per_row_combine_is_native_combine_per_token_or_the_legacy_kernel() { - let m = map(); - let g = test_geometry(); - let l = plan_combine(&m, &g, &MoeKnobs::mode17(), rows(1, 3, 0), false).unwrap(); +/// The native per-token combine of rows 1..3 (the second launch is row 2's), and a single-row window. +fn assert_native_per_row_combine(m: &LayoutMap, g: &OriginalVerifyGeometry) { + let l = plan_combine(m, g, &MoeKnobs::mode17(), rows(1, 3, 0), false).unwrap(); assert_eq!(l.len(), 2); assert_eq!((l[1].grid, l[1].block), ([10, 1, 1], [256, 1, 1])); assert_eq!( l[1].args, vec![ - A::P(at(&m, "parts", 2 * 10 * 2560 * 4)), - A::P(at(&m, "w", 2 * 10 * 4)), - A::P(at(&m, "shared", 2 * 2560 * 4)), - A::P(at(&m, "bo", 2 * 2560 * 4)), + A::P(at(m, "parts", 2 * 10 * 2560 * 4)), + A::P(at(m, "w", 2 * 10 * 4)), + A::P(at(m, "shared", 2 * 2560 * 4)), + A::P(at(m, "bo", 2 * 2560 * 4)), A::I64(2560), A::I32(10) ] ); assert_abi(&l); // a single-row window is never batched, even with native combine on - let one = plan_combine(&m, &g, &MoeKnobs::mode17(), rows(0, 1, 0), false).unwrap(); + let one = plan_combine(m, g, &MoeKnobs::mode17(), rows(0, 1, 0), false).unwrap(); assert_eq!((one[0].entry, one[0].grid), ("mtp_full_combine", [10, 1, 1])); +} + +#[test] +fn per_row_combine_is_native_combine_per_token_or_the_legacy_kernel() { + let m = map(); + let g = test_geometry(); + assert_native_per_row_combine(&m, &g); // moe_combine<<>>(parts, w, shared, y, N, K, has_shared = 1) let mut legacy = MoeKnobs::mode17(); legacy.native_combine = false; diff --git a/crates/cuda-driver/src/original_verify_window_moe/tests/shared_gate_without_native_bf16.rs b/crates/cuda-driver/src/original_verify_window_moe/tests/shared_gate_without_native_bf16.rs index 6235cb50..215cf0f3 100644 --- a/crates/cuda-driver/src/original_verify_window_moe/tests/shared_gate_without_native_bf16.rs +++ b/crates/cuda-driver/src/original_verify_window_moe/tests/shared_gate_without_native_bf16.rs @@ -1,4 +1,6 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): shared_gate_without_native_bf16_extra_reads_the_bf16_activation, shared_expert_covers_every_window_size, expert_input_is_the_q8_1_row_quantizer_into_nat_xq, expert_blob_layout_matches_native_expert_layout .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! shared_gate_without_native_bf16_extra_reads_the_bf16_activation, shared_expert_covers_every_window_size, +//! expert_input_is_the_q8_1_row_quantizer_into_nat_xq, expert_blob_layout_matches_native_expert_layout .... #[allow(unused_imports)] use super::*; @@ -103,23 +105,20 @@ fn expert_scratch_follows_native_expert_scratch_bytes() { assert_eq!(expert_scratch(1, 100), (512, 3 * 512 + 256)); } -#[test] -fn vram_tier_reads_the_first_plan_arrays() { - let m = map(); - let g = test_geometry(); - let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 5, rows(0, 3, 0), ExpertTier::Vram); - // the plan itself is pure data - let l = l.unwrap(); - assert_eq!(entries(&l).len(), 4); - // PlanLayout(capx = 80): start 4, dst 85, tok 165, ptr 246, ptr2 406, start2 566; device stride 664 words - let plan = |word: usize| at(&m, "plan", word * 4); - let scratch = at(&m, "hit_scratch", 0); - let xq = at(&m, "nat_xq", 0); +/// PlanLayout(capx = 80): start 4, dst 85, tok 165, ptr 246, ptr2 406, start2 566; device stride 664 words. +fn plan_word_addr(m: &LayoutMap, word: usize) -> u64 { + at(m, "plan", word * 4) +} + +/// The gate/up launch of the Vram tier: grid ((2*640+7)/8 = 160, cap = 30), 256 threads. +fn assert_vram_gate_up_launch(m: &LayoutMap, l: &Launch) { + let plan = |word: usize| plan_word_addr(m, word); + let scratch = at(m, "hit_scratch", 0); + let xq = at(m, "nat_xq", 0); let fa = 3 * 10 * 640 * 4; - // gate/up: grid ((2*640+7)/8 = 160, cap = 30), 256 threads - assert_eq!((l[0].entry, l[0].grid, l[0].block, l[0].shared), ("window_moe_gu_16", [160, 30, 1], [256, 1, 1], 0)); + assert_eq!((l.entry, l.grid, l.block, l.shared), ("window_moe_gu_16", [160, 30, 1], [256, 1, 1], 0)); assert_eq!( - l[0].args, + l.args, vec![ A::P(plan(246)), A::P(plan(4)), @@ -131,6 +130,13 @@ fn vram_tier_reads_the_first_plan_arrays() { A::P(scratch + fa as u64) ] ); +} + +/// The swiglu, quantize and down launches (1..=3) of the whole Vram-tier plan `l`. +fn assert_vram_swiglu_quantize_down(m: &LayoutMap, l: &[Launch]) { + let plan = |word: usize| plan_word_addr(m, word); + let scratch = at(m, "hit_scratch", 0); + let fa = 3 * 10 * 640 * 4; // swiglu_entries and quantize over cap * n_ff = 19200 values assert!(l[1].entry.ends_with("swiglu_entries_kernelEPKfS3_Pfx")); assert_eq!((l[1].grid, l[1].block), ([75, 1, 1], [256, 1, 1])); @@ -151,12 +157,25 @@ fn vram_tier_reads_the_first_plan_arrays() { A::P(plan(85)), A::P(scratch + 3 * fa as u64), A::Words(vec![16 | (20 << 32), 2560, 640, 660, 360, 422_400, 844_800, 1_766_400]), - A::P(at(&m, "hit_out", 0)) + A::P(at(m, "hit_out", 0)) ] ); assert_abi(&l[1..3]); } +#[test] +fn vram_tier_reads_the_first_plan_arrays() { + let m = map(); + let g = test_geometry(); + let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 5, rows(0, 3, 0), ExpertTier::Vram); + // the plan itself is pure data + let l = l.unwrap(); + assert_eq!(entries(&l).len(), 4); + // PlanLayout(capx = 80): start 4, dst 85, tok 165, ptr 246, ptr2 406, start2 566; device stride 664 words + assert_vram_gate_up_launch(&m, &l[0]); + assert_vram_swiglu_quantize_down(&m, &l); +} + #[test] fn pcie_tier_uses_the_second_pointer_start_and_count_of_the_group() { let m = map(); @@ -200,21 +219,9 @@ fn expert_groups_pick_the_kernels_of_the_layers_formats() { } } -#[test] -fn gu_swiglu_replaces_gate_up_swiglu_and_quantize_by_one_launch_and_keeps_the_down_kernel() { - let m = map(); - let g = test_geometry(); - let mut fmts = [(16, 20); WINDOW_LAYERS]; - fmts[7] = (12, 8); - fmts[8] = (22, 20); - let f = OriginalVerifyExpertFormats::new(fmts, 2560, 640).unwrap(); - let mut on = MoeKnobs::mode17(); - on.gu_swiglu = true; - let off = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, 0, rows(0, 3, 0), ExpertTier::Vram).unwrap(); - let fused = plan_expert_groups(&m, &g, &on, &f, 0, rows(0, 3, 0), ExpertTier::Vram).unwrap(); - assert_eq!(entries(&fused), ["sm120_moe_gu_swiglu_16", "window_moe_down_20"]); - assert_eq!((fused[0].grid, fused[0].block, fused[0].shared), ([20, 30, 1], [512, 1, 1], 0)); - // the arguments: the same group tables, activations and q8_1 output as the three kernels, upstream's 88-byte layout +/// The fused launch's arguments: the same group tables, activations and q8_1 output as the three kernels, +/// upstream's 88-byte layout; the down kernel untouched. +fn assert_gu_swiglu_arguments(fused: &[Launch], off: &[Launch]) { let gu = &off[0].args; let scratch_hq = match &off[2].args[1] { A::P(p) => *p, @@ -233,15 +240,42 @@ fn gu_swiglu_replaces_gate_up_swiglu_and_quantize_by_one_launch_and_keeps_the_do // the down kernel is untouched (same arguments, reading the same hq) assert_eq!(fused[1].args, off[3].args); assert_eq!(fused[1].entry, off[3].entry); - // layers whose gate/up format has no fused kernel keep the three-kernel plan; so does a knobs set without the switch +} + +/// Layers whose gate/up format has no fused kernel keep the three-kernel plan; so does a knobs set without the +/// switch. +fn assert_gu_swiglu_layer_fallbacks( + m: &LayoutMap, + g: &OriginalVerifyGeometry, + on: &MoeKnobs, + f: &OriginalVerifyExpertFormats, +) { assert_eq!( - entries(&plan_expert_groups(&m, &g, &on, &f, 7, rows(0, 3, 0), ExpertTier::Vram).unwrap())[0], + entries(&plan_expert_groups(m, g, on, f, 7, rows(0, 3, 0), ExpertTier::Vram).unwrap())[0], "window_moe_gu_12" ); assert_eq!( - entries(&plan_expert_groups(&m, &g, &on, &f, 8, rows(0, 3, 0), ExpertTier::Pcie).unwrap())[0], + entries(&plan_expert_groups(m, g, on, f, 8, rows(0, 3, 0), ExpertTier::Pcie).unwrap())[0], "sm120_moe_gu_swiglu_22" ); +} + +#[test] +fn gu_swiglu_replaces_gate_up_swiglu_and_quantize_by_one_launch_and_keeps_the_down_kernel() { + let m = map(); + let g = test_geometry(); + let mut fmts = [(16, 20); WINDOW_LAYERS]; + fmts[7] = (12, 8); + fmts[8] = (22, 20); + let f = OriginalVerifyExpertFormats::new(fmts, 2560, 640).unwrap(); + let mut on = MoeKnobs::mode17(); + on.gu_swiglu = true; + let off = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, 0, rows(0, 3, 0), ExpertTier::Vram).unwrap(); + let fused = plan_expert_groups(&m, &g, &on, &f, 0, rows(0, 3, 0), ExpertTier::Vram).unwrap(); + assert_eq!(entries(&fused), ["sm120_moe_gu_swiglu_16", "window_moe_down_20"]); + assert_eq!((fused[0].grid, fused[0].block, fused[0].shared), ([20, 30, 1], [512, 1, 1], 0)); + assert_gu_swiglu_arguments(&fused, &off); + assert_gu_swiglu_layer_fallbacks(&m, &g, &on, &f); assert_eq!(entries(&off).len(), 4); } diff --git a/crates/cuda-driver/src/original_verify_window_ops/all_window_assets_fn.rs b/crates/cuda-driver/src/original_verify_window_ops/all_window_assets_fn.rs index d80a937f..58c8f2ab 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/all_window_assets_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/all_window_assets_fn.rs @@ -1,4 +1,6 @@ -//! Moved out of the parent module by STRA-338: fn all_window_assets, fn unsealed_window_assets, fn unsealed_keys, impl OriginalVerifyExpertLayout, impl OriginalVerifyWindowResources, impl WindowWeights_for_OriginalVerifyWindowResources .... +//! Moved out of the parent module by STRA-338: fn all_window_assets, fn unsealed_window_assets, fn unsealed_keys, +//! impl OriginalVerifyExpertLayout, impl OriginalVerifyWindowResources, impl +//! WindowWeights_for_OriginalVerifyWindowResources .... #[allow(unused_imports)] use super::*; 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 23132f96..57a03b72 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 @@ -107,8 +107,9 @@ fn pcie_role_bytes( 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. +/// 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 { if crate::original_gpu_schedule::is_graph_out_of_memory(&error) { Error::GraphOutOfMemory { window } diff --git a/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifywindowops.rs b/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifywindowops.rs index ce916973..f51c53b4 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifywindowops.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifywindowops.rs @@ -4,14 +4,15 @@ use super::*; impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> { - /// SIDE_MIXER (upstream `STRATA_SIDE_MIXER=2`, GDN part): the GDN gates and the gate projection run on side streams of the window's graph. Not in a - /// split window (two row groups), as upstream. + /// SIDE_MIXER (upstream `STRATA_SIDE_MIXER=2`, GDN part): the GDN gates and the gate projection run on side + /// streams of the window's graph. Not in a split window (two row groups), as upstream. pub(super) fn side_gdn(&self) -> bool { self.policy.side_mixer && self.groups == 1 && self.capture.has_side() } - /// The branch of one GDN layer. The gates (`gdn_alpha_beta`) read only the mixed activations, the gate projection only their q8_1 blocks; both - /// are complete before the qkv projection starts, and the qkv projection, the conv and the recurrence's other inputs do not touch their outputs, - /// so they fork right here and join before the recurrence. + /// The branch of one GDN layer. The gates (`gdn_alpha_beta`) read only the mixed activations, the gate projection + /// only their q8_1 blocks; both are complete before the qkv projection starts, and the qkv projection, the conv + /// and the recurrence's other inputs do not touch their outputs, so they fork right here and join before the + /// recurrence. pub(super) fn issue_gdn_side(&mut self, layer: usize, rows: Rows) -> Result<()> { let g = gdn_index(layer).ok_or(Error::InvalidQwenShape)?; self.capture.side_fork(0)?; diff --git a/crates/cuda-driver/src/original_verify_window_planner/tests.rs b/crates/cuda-driver/src/original_verify_window_planner/tests.rs index 14461ace..3bb6b50c 100644 --- a/crates/cuda-driver/src/original_verify_window_planner/tests.rs +++ b/crates/cuda-driver/src/original_verify_window_planner/tests.rs @@ -18,6 +18,38 @@ struct Fake { fn w(a: u64) -> NativeWeight { NativeWeight { ty: 14, data: a } } +fn fake_qsa_weights(b: u64) -> QsaWeightAddrs { + QsaWeightAddrs { + q_norm: b, + k_norm: b + 0x1_0000, + index_q_norm: b + 0x2_0000, + index_k_proj: b + 0x100_0000, + index_q_proj: b + 0x200_0000, + } +} + +fn fake_qsa_kv(b: u64) -> OriginalVerifyQsaKvBinding { + OriginalVerifyQsaKvBinding { + resident: [b + 0x1000_0000, b + 0x1100_0000, b + 0x1200_0000, b + 0x1210_0000], + table: b + 0x1300_0000, + host: [b + 0x2000_0000, b + 0x2100_0000, b + 0x2200_0000, b + 0x2210_0000], + resolver: [ + b + 0x1300_0000, + b + 0x1310_0000, + b + 0x1320_0000, + b + 0x1330_0000, + b + 0x1340_0000, + b + 0x1350_0000, + b + 0x1360_0000, + ], + slots: 8192, + pooled: b + 0x1400_0000, + pooled_bytes: 1026 * 512, + dead: b + 0x1410_0000, + dead_bytes: 512, + } +} + impl WindowWeights for Fake { fn gdn_projections(&self, g: usize) -> Result { let b = 0x10_0000_0000u64 + g as u64 * 0x1000_0000; @@ -57,34 +89,7 @@ impl WindowWeights for Fake { } fn qsa(&self, q: usize) -> Result { let b = 0x50_0000_0000u64 + q as u64 * 0x1_0000_0000; - Ok(QsaLayerAddrs { - weights: QsaWeightAddrs { - q_norm: b, - k_norm: b + 0x1_0000, - index_q_norm: b + 0x2_0000, - index_k_proj: b + 0x100_0000, - index_q_proj: b + 0x200_0000, - }, - kv: OriginalVerifyQsaKvBinding { - resident: [b + 0x1000_0000, b + 0x1100_0000, b + 0x1200_0000, b + 0x1210_0000], - table: b + 0x1300_0000, - host: [b + 0x2000_0000, b + 0x2100_0000, b + 0x2200_0000, b + 0x2210_0000], - resolver: [ - b + 0x1300_0000, - b + 0x1310_0000, - b + 0x1320_0000, - b + 0x1330_0000, - b + 0x1340_0000, - b + 0x1350_0000, - b + 0x1360_0000, - ], - slots: 8192, - pooled: b + 0x1400_0000, - pooled_bytes: 1026 * 512, - dead: b + 0x1410_0000, - dead_bytes: 512, - }, - }) + Ok(QsaLayerAddrs { weights: fake_qsa_weights(b), kv: fake_qsa_kv(b) }) } fn rope(&self) -> Result { QsaRope::new(0.7498942, 1.0, 0.0, 0.0, 0.0, 1.0) diff --git a/crates/cuda-driver/src/original_verify_window_planner/tests/every_window_size_and_group.rs b/crates/cuda-driver/src/original_verify_window_planner/tests/every_window_size_and_group.rs index d03887f8..4fc7fd5b 100644 --- a/crates/cuda-driver/src/original_verify_window_planner/tests/every_window_size_and_group.rs +++ b/crates/cuda-driver/src/original_verify_window_planner/tests/every_window_size_and_group.rs @@ -1,4 +1,8 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): every_window_size_and_group_split_plans_without_error, a_gdn_layer_records_verify_cpp_order_with_the_sealed_kernels, a_qsa_layer_records_the_kv_chain_between_the_projections, post_records_vram_then_pcie_experts_hit_add_and_combine .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! every_window_size_and_group_split_plans_without_error, +//! a_gdn_layer_records_verify_cpp_order_with_the_sealed_kernels, +//! a_qsa_layer_records_the_kv_chain_between_the_projections, post_records_vram_then_pcie_experts_hit_add_and_combine +//! .... #[allow(unused_imports)] use super::*; @@ -21,14 +25,14 @@ fn every_window_size_and_group_split_plans_without_error() { } } -#[test] -fn a_gdn_layer_records_verify_cpp_order_with_the_sealed_kernels() { - let log = record(3, 1, false); - // layer 0 up to the ring: hc read (staged variant: split norm, staged down, up), q8_1 + qkv, conv, alpha/beta, - // z projection, recurrence, y quantization + out projection, FFN hc read, router, doorbell, shared expert - let pre = section(&log, "stamp 0.0", "stamp 0.18"); - let k = names(pre); - let pos = |needle: &str| k.iter().position(|s| *s == needle).unwrap_or_else(|| panic!("{needle} missing in {k:?}")); +/// Index of the first record named `needle`; a missing record fails the test. +fn position_of(k: &[&str], needle: &str) -> usize { + k.iter().position(|s| *s == needle).unwrap_or_else(|| panic!("{needle} missing in {k:?}")) +} + +/// The records of a GDN layer's first half come in the order of verify.cpp: hc read, projections, ring, experts. +fn assert_gdn_layer_order(k: &[&str]) { + let pos = |needle: &str| position_of(k, needle); assert!(pos(""); assert_eq!(names(router).iter().filter(|s| s.contains("mmvf_multi_kernel") || **s == "mtp_full_route").count(), 2); // the projections are the native MMVQ of the bound weight types at three rows @@ -56,7 +70,22 @@ fn a_qsa_layer_records_the_kv_chain_between_the_projections() { let log = record(4, 1, false); let layer = section(&log, "stamp 3.0", "stamp 3.16"); let k = names(layer); - let pos = |needle: &str| k.iter().position(|s| *s == needle).unwrap_or_else(|| panic!("{needle} missing in {k:?}")); + assert_qsa_kv_chain_order(&k); + // four rows are batched: one index-k multi gemv, one mmvq per projection at four columns + assert!(k.iter().any(|s| s.contains("mmvf_multi_kernel"))); + assert!(k.contains(&"head_n12_t4_large") && k.contains(&"head_n14_t4_large")); + assert!(k.contains(&"verify_window_qsa_gate")); + assert!(k.contains(&"leleka_qsa_decode_chunk") && k.contains(&"leleka_qsa_decode_merge")); + // the single-row window keeps the per-token (unbatched) kernels + let one = record(1, 1, false); + let one_k = names(section(&one, "stamp 3.0", "stamp 3.16")); + assert!(one_k.iter().any(|s| s.contains("mtp_full_mmvf"))); + assert!(!one_k.iter().any(|s| s.contains("mmvf_multi_kernel"))); +} + +/// The QSA layer's records come in the order of the kv chain between the projections. +fn assert_qsa_kv_chain_order(k: &[&str]) { + let pos = |needle: &str| position_of(k, needle); let order = [ " = order.iter().map(|n| pos(n)).collect(); assert!(at.windows(2).all(|w| w[0] < w[1]), "{order:?} -> {at:?}"); - // four rows are batched: one index-k multi gemv, one mmvq per projection at four columns - assert!(k.iter().any(|s| s.contains("mmvf_multi_kernel"))); - assert!(k.contains(&"head_n12_t4_large") && k.contains(&"head_n14_t4_large")); - assert!(k.contains(&"verify_window_qsa_gate")); - assert!(k.contains(&"leleka_qsa_decode_chunk") && k.contains(&"leleka_qsa_decode_merge")); - // the single-row window keeps the per-token (unbatched) kernels - let one = record(1, 1, false); - let one_k = names(section(&one, "stamp 3.0", "stamp 3.16")); - assert!(one_k.iter().any(|s| s.contains("mtp_full_mmvf"))); - assert!(!one_k.iter().any(|s| s.contains("mmvf_multi_kernel"))); } #[test] @@ -113,7 +132,8 @@ fn post_records_vram_then_pcie_experts_hit_add_and_combine() { #[test] fn split_windows_interleave_groups_but_keep_each_group_in_order() { let log = record(5, 2, false); - // pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) ...: group B's first read follows A's FFN prep, then A's experts + // pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) ...: group B's first read follows A's FFN prep, then A's + // experts let hcs: Vec = log.iter().enumerate().filter(|(_, s)| s.starts_with("