From b8a74d01ddfa71ae0605d226935ef9f28627fcd0 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 10 Nov 2026 19:08:30 +0100 Subject: [PATCH] Verify window: LELEKA_SM120_COMBINE_VEC4 (float4 routed-expert combine) and LELEKA_SM120_HEAD_MIX_MULTI (one multi-token head mix), both off by default COMBINE_VEC4: new sealed sm_120 asset sm120_combine_vec4.ptx (nvcc 13.2.86), entry leleka_verify_combine_k10_vec4, upstream combine_k10_vec4 (non-hits form). Same per-element operations as the sealed mtp_full_combine: first product rounded, nine fmaf in expert order, one add of the shared row. Falls back to the scalar launch when k != 10, n % 4 != 0 or a row base is not 16-byte aligned. Same launch count as the scalar path. HEAD_MIX_MULTI: upstream STRATA_HEAD_MIX_MULTI. The final mixer as one multi-token hc read over output_hc_* (the layer read kernels, apply = false, no inject), 3 launches instead of 5 per token. No new PTX. Switch DTO CombineHeadKernels (original_verify_window_combine_head.rs) travels beside the GDN policy; the shared switch file gets two fields. Unit tests (asset seal, PTX arithmetic shape, launch plans, whole-window launch order with both switches). Model-free byte-compare probe tools/combine-head written, compiled, not run (no GPU). Design and CUPTI names: docs/experiments/verify-combine-and-head-mix.md Co-Authored-By: Claude Sonnet 5.5 --- crates/cuda-driver/ptx-sm86/MANIFEST.json | 7 + crates/cuda-driver/src/original_verify.rs | 2 + .../original_verify_window_combine_head.rs | 141 +++++++++++++ .../tests.rs | 163 +++++++++++++++ .../src/original_verify_window_gr.rs | 4 + .../original_verify_window_gr/plan_hc_read.rs | 16 +- .../plan_head_mix_multi.rs | 51 +++++ .../src/original_verify_window_gr/tests.rs | 2 + .../tests/head_mix_multi.rs | 91 +++++++++ .../src/original_verify_window_ops.rs | 2 + .../original_verifier.rs | 8 +- .../original_verify_window_ops_methods.rs | 3 +- .../src/original_verify_window_planner.rs | 21 +- .../original_verify_window_planner/tests.rs | 2 + .../tests/combine_head_switches.rs | 78 ++++++++ .../src/original_verify_window_sm120.rs | 12 ++ crates/cuda-driver/src/sm120_combine_vec4.cu | 52 +++++ crates/cuda-driver/src/sm120_combine_vec4.ptx | 136 +++++++++++++ .../verify-combine-and-head-mix.md | 74 +++++++ scripts/gpu-bringup/extra-seal-plan.json | 25 +++ tools/combine-head/build.sh | 15 ++ tools/combine-head/combine_head_probe.cpp | 185 ++++++++++++++++++ 22 files changed, 1080 insertions(+), 10 deletions(-) create mode 100644 crates/cuda-driver/src/original_verify/original_verify_window_combine_head.rs create mode 100644 crates/cuda-driver/src/original_verify/original_verify_window_combine_head/tests.rs create mode 100644 crates/cuda-driver/src/original_verify_window_gr/plan_head_mix_multi.rs create mode 100644 crates/cuda-driver/src/original_verify_window_gr/tests/head_mix_multi.rs create mode 100644 crates/cuda-driver/src/original_verify_window_planner/tests/combine_head_switches.rs create mode 100644 crates/cuda-driver/src/sm120_combine_vec4.cu create mode 100644 crates/cuda-driver/src/sm120_combine_vec4.ptx create mode 100644 docs/experiments/verify-combine-and-head-mix.md create mode 100644 tools/combine-head/build.sh create mode 100644 tools/combine-head/combine_head_probe.cpp diff --git a/crates/cuda-driver/ptx-sm86/MANIFEST.json b/crates/cuda-driver/ptx-sm86/MANIFEST.json index ed40f283..7dd1b6e3 100644 --- a/crates/cuda-driver/ptx-sm86/MANIFEST.json +++ b/crates/cuda-driver/ptx-sm86/MANIFEST.json @@ -2747,6 +2747,13 @@ "problems": [ "not built for sm_86 by design (claude/verify-gdn-fused-kernels): LELEKA_SM120_FUSED_GDN and LELEKA_SM120_GDN_AB_UNROLL are compute capability 12.0 decode switches; original_verify_window_sm120.rs enables them only on a 12.x card, so an sm_86 build never loads this module" ] + }, + { + "name": "sm120_combine_vec4.ptx", + "sm120_path": "crates/cuda-driver/src/sm120_combine_vec4.ptx", + "problems": [ + "not built for sm_86 by design (claude/s11-s9-combine-headmix): LELEKA_SM120_COMBINE_VEC4 is a compute capability 12.0 decode switch; original_verify_window_sm120.rs enables it only on a 12.x card, so an sm_86 build never loads this module" + ] } ], "portable_no_companion_needed": [ diff --git a/crates/cuda-driver/src/original_verify.rs b/crates/cuda-driver/src/original_verify.rs index fd2fcf76..1cf366f2 100644 --- a/crates/cuda-driver/src/original_verify.rs +++ b/crates/cuda-driver/src/original_verify.rs @@ -9,6 +9,8 @@ pub(crate) mod chain; #[path = "original_verify_diag.rs"] #[allow(unsafe_code)] mod diag; +#[path = "original_verify/original_verify_window_combine_head.rs"] +pub(crate) mod combine_head; #[path = "original_verify_window_draft.rs"] pub(crate) mod draft; pub(crate) mod finite_verdict; diff --git a/crates/cuda-driver/src/original_verify/original_verify_window_combine_head.rs b/crates/cuda-driver/src/original_verify/original_verify_window_combine_head.rs new file mode 100644 index 00000000..203ce0a9 --- /dev/null +++ b/crates/cuda-driver/src/original_verify/original_verify_window_combine_head.rs @@ -0,0 +1,141 @@ +//! claude/s11-s9-combine-headmix: two kernel-count switches of the verify window's FFN end and graph tail +//! (design note `docs/experiments/verify-combine-and-head-mix.md`). Both are off by default, independent, and compute +//! every output word with the operations of the launches they replace, in the same order. +//! +//! * `LELEKA_SM120_COMBINE_VEC4` (step S11): the routed-expert combine as upstream's `combine_k10_vec4` +//! (`sm120_combine_vec4.cu`, one thread a column quartet, float4 loads and stores) instead of `mtp_full_combine` +//! (one thread a column). One launch a layer either way; k = 10, `n_embd % 4 == 0` and 16-byte aligned rows or the +//! scalar launch stays. +//! * `LELEKA_SM120_HEAD_MIX_MULTI` (step S9): the final mixer of the window's tokens as one `fused_gr_read_multi` +//! call (3 launches) instead of five launches per token. Pure planning over kernels the layers already load +//! (`original_verify_window_gr/plan_head_mix_multi.rs`); no asset of its own. +// `ptx` below is read from `../sm120_combine_vec4.ptx` (this file lives one directory below the sealed assets) +use super::kernels::{A, ArenaMap, AssetSpec, Launch, LaunchExtent}; +use super::layout::OriginalVerifyGeometry; +use super::sm120::Sm120Switches; +use super::window_record::Rows; +use crate::{Error, Result}; + +pub(crate) const E_COMBINE_VEC4: &str = "leleka_verify_combine_k10_vec4"; +/// The routed experts per token the vector kernel is written for (Qwen3.5-122B-A10B: top-10). +const ROUTED_EXPERTS: usize = 10; +/// Column quartets a block covers (`__launch_bounds__(128)` of the kernel). +const QUARTETS_PER_BLOCK: usize = 128; +const VECTOR_ALIGN: u64 = 16; + +/// `sm120_combine_vec4.cu` (nvcc 13.2.86, `--fmad=true --ftz=false`); plan entry in +/// `scripts/gpu-bringup/extra-seal-plan.json` (group `sm120-decode`). +pub(crate) static COMBINE_VEC4: AssetSpec = AssetSpec { + name: "sm120_combine_vec4.ptx", + ptx: concat!(include_str!("../sm120_combine_vec4.ptx"), "\0").as_bytes(), + sha: [ + 11, 118, 103, 100, 100, 251, 45, 239, 83, 193, 186, 163, 167, 9, 251, 154, 241, 101, 148, 174, 235, 40, 95, 57, + 157, 6, 224, 156, 91, 69, 120, 162, + ], + entries: &[E_COMBINE_VEC4], + unsealed: "Original verifier asset unsealed: sm120_combine_vec4.ptx (COMBINE_VEC4 float4 routed-expert combine)", +}; + +/// The resolved switches of one window recording. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct CombineHeadKernels { + pub combine_vec4: bool, + pub head_mix_multi: bool, +} +impl CombineHeadKernels { + pub(crate) fn from_switches(s: &Sm120Switches) -> Self { + Self { combine_vec4: s.combine_vec4, head_mix_multi: s.head_mix_multi } + } + /// The asset the window preloads before capture (none when `COMBINE_VEC4` is off). + pub(crate) fn assets(self) -> Vec<&'static AssetSpec> { + if self.combine_vec4 { vec![&COMBINE_VEC4] } else { Vec::new() } + } +} + +/// Resolves the switches for the card and loads the asset before capture (module loading is not capturable). A +/// requested switch whose asset is not sealed refuses the recording, so a paired A/B never runs the default path under +/// the name of the switch. +pub(crate) fn prepare(journal: &super::OriginalVerifyGdnJournal<'_>) -> Result { + let major = journal.window_device_attribute(super::gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?; + let minor = journal.window_device_attribute(super::gr::ATTR_COMPUTE_CAPABILITY_MINOR)?; + let kernels = CombineHeadKernels::from_switches(&Sm120Switches::from_env(major, minor)); + journal.ensure_window_assets(&kernels.assets())?; + if kernels != CombineHeadKernels::default() { + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| { + eprintln!("leleka-serve combine/head-mix kernels: {kernels:?} (compute capability {major}.{minor})") + }); + } + Ok(kernels) +} + +/// What the vector combine needs from the window: the geometry, whether the Original's native combine is the scalar +/// path being replaced (`MoeKnobs::native_combine`), and the recorder's `batched` flag. +#[derive(Clone, Copy, Debug)] +pub(crate) struct CombineSite { + pub rows: Rows, + pub batched: bool, + pub native_combine: bool, +} + +/// The launches of `plan_combine` as `leleka_verify_combine_k10_vec4`: ONE launch over all rows of the group when +/// `batched` (grid.y = token), else one per row. `None` when the shape or an address does not fit the vector kernel; +/// the caller then plans the scalar launches, which compute the same words. +pub(crate) fn plan_combine_vec4( + arena: &(impl ArenaMap + ?Sized), + g: &OriginalVerifyGeometry, + site: CombineSite, +) -> Result>> { + let rows = site.rows; + check_rows(g, site)?; + if !site.native_combine || g.k != ROUTED_EXPERTS || g.n % 4 != 0 { + return Ok(None); + } + let groups: Vec<(usize, usize)> = + if site.batched { vec![(rows.begin, rows.len())] } else { (rows.begin..rows.end).map(|t| (t, 1)).collect() }; + let mut launches = Vec::with_capacity(groups.len()); + for (first, tokens) in groups { + match combine_launch(arena, g, first, tokens)? { + Some(launch) => launches.push(launch), + None => return Ok(None), + } + } + Ok(Some(launches)) +} + +/// The rows the scalar planner accepts: a non-empty range inside the window, one of two groups, two rows when batched. +fn check_rows(g: &OriginalVerifyGeometry, site: CombineSite) -> Result<()> { + let rows = site.rows; + if rows.begin >= rows.end || rows.end > g.max_t || rows.group > 1 || (site.batched && rows.len() < 2) { + return Err(Error::InvalidQwenShape); + } + Ok(()) +} + +/// One launch over `tokens` rows from row `first`; `None` when a row base is not 16-byte aligned. +fn combine_launch( + arena: &(impl ArenaMap + ?Sized), + g: &OriginalVerifyGeometry, + first: usize, + tokens: usize, +) -> Result> { + let (n, k) = (g.n, g.k); + let floats = |name: &str, per_token: usize| arena.span(name, first * per_token * 4, tokens * per_token * 4); + let (parts, weights, shared, out) = + (floats("parts", k * n)?, floats("w", k)?, floats("shared", n)?, floats("bo", n)?); + if [parts, shared, out].iter().any(|a| a % VECTOR_ALIGN != 0) { + return Ok(None); + } + let n4 = n / 4; + let extent = LaunchExtent::new( + [n4.div_ceil(QUARTETS_PER_BLOCK) as u32, tokens as u32, 1], + [QUARTETS_PER_BLOCK as u32, 1, 1], + 0, + ); + let args = vec![A::P(parts), A::P(weights), A::P(shared), A::P(out), A::I64(n4 as i64)]; + Launch::new(&COMBINE_VEC4, E_COMBINE_VEC4, extent, args).map(Some) +} + +#[cfg(test)] +#[path = "original_verify_window_combine_head/tests.rs"] +mod tests; diff --git a/crates/cuda-driver/src/original_verify/original_verify_window_combine_head/tests.rs b/crates/cuda-driver/src/original_verify/original_verify_window_combine_head/tests.rs new file mode 100644 index 00000000..7f4389d4 --- /dev/null +++ b/crates/cuda-driver/src/original_verify/original_verify_window_combine_head/tests.rs @@ -0,0 +1,163 @@ +//! Unit tests of `original_verify_window_combine_head.rs`: the switches resolve per variable, the asset is sealed, the +//! PTX has the arithmetic shape of the kernel it replaces, and the planned launches bind the Original cells. + +use super::super::kernels::{ArenaMap, LayoutMap, test_geometry}; +use super::*; + +const BASE: u64 = 0x7000_0000_0000; + +fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option { + move |k| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string()) +} +fn arena() -> LayoutMap { + LayoutMap::new(BASE, test_geometry()) +} +fn site(begin: usize, end: usize, batched: bool) -> CombineSite { + CombineSite { rows: Rows { begin, end, group: 0 }, batched, native_combine: true } +} +fn at(m: &LayoutMap, name: &str, offset: usize) -> u64 { + BASE + (m.layout.span(name).unwrap().offset + offset) as u64 +} +fn plan(m: &LayoutMap, site: CombineSite) -> Option> { + plan_combine_vec4(m, &test_geometry(), site).unwrap() +} +/// An arena that shifts every span by a number of bytes (an unaligned allocation). +struct Skewed<'a>(&'a LayoutMap, u64); +impl ArenaMap for Skewed<'_> { + fn span(&self, name: &str, offset: usize, bytes: usize) -> Result { + self.0.span(name, offset, bytes).map(|a| a + self.1) + } +} +/// The text of one `.entry` of a PTX file (up to the next `.entry` or the end). +fn entry_text<'a>(ptx: &'a str, entry: &str) -> &'a str { + let from = ptx.find(&format!(".entry {entry}(")).unwrap_or_else(|| panic!("{entry} missing")); + let rest = &ptx[from + 1..]; + let to = rest.find(".entry ").map_or(ptx.len(), |i| from + 1 + i); + &ptx[from..to] +} +fn count(text: &str, op: &str) -> usize { + text.lines().filter(|l| l.trim_start().split_whitespace().next() == Some(op)).count() +} + +#[test] +fn both_switches_are_off_by_default_and_follow_their_own_variables() { + let on = |maj, min, e| CombineHeadKernels::from_switches(&Sm120Switches::resolve(maj, min, e)); + assert_eq!(on(12, 0, env(&[])), CombineHeadKernels::default()); + assert_eq!(on(12, 0, env(&[("LELEKA_SM120_PERF", "1")])), CombineHeadKernels::default()); + let vec4 = on(12, 0, env(&[("LELEKA_SM120_COMBINE_VEC4", "1")])); + assert_eq!(vec4, CombineHeadKernels { combine_vec4: true, head_mix_multi: false }); + let head = on(12, 0, env(&[("LELEKA_SM120_HEAD_MIX_MULTI", "1")])); + assert_eq!(head, CombineHeadKernels { combine_vec4: false, head_mix_multi: true }); + // an explicit off wins, a card below 12.x never takes either, and neither is a side-stream part + assert_eq!(on(12, 0, env(&[("LELEKA_SM120_COMBINE_VEC4", "0")])), CombineHeadKernels::default()); + const BOTH: [(&str, &str); 2] = [("LELEKA_SM120_COMBINE_VEC4", "1"), ("LELEKA_SM120_HEAD_MIX_MULTI", "1")]; + assert_eq!(on(8, 6, env(&BOTH)), CombineHeadKernels::default()); + let both = Sm120Switches::resolve(12, 0, env(&BOTH)); + assert!(both.combine_vec4 && both.head_mix_multi && !both.side_branches().any()); + // no other switch follows them + assert_eq!(Sm120Switches { combine_vec4: false, head_mix_multi: false, ..both }, Sm120Switches::default()); +} + +#[test] +fn only_the_vector_combine_needs_an_asset() { + assert!(CombineHeadKernels::default().assets().is_empty()); + assert!(CombineHeadKernels { combine_vec4: false, head_mix_multi: true }.assets().is_empty()); + let assets = CombineHeadKernels { combine_vec4: true, head_mix_multi: false }.assets(); + assert_eq!(assets.len(), 1); + assert!(std::ptr::eq(assets[0], &COMBINE_VEC4)); +} + +#[test] +fn the_vector_combine_asset_is_sealed_and_exports_its_entry() { + COMBINE_VEC4.assert_sealed_and_fail_closed(); + assert_eq!(COMBINE_VEC4.entries, [E_COMBINE_VEC4]); +} + +/// The Original column is `p0 * w0` rounded, nine fused multiply-adds in expert order, one add of the shared row +/// (mtp_original_full_combine.ptx, entry mtp_full_combine); the vector kernel is that, four columns at a time. +#[test] +fn the_vector_kernel_has_the_arithmetic_shape_of_the_scalar_one() { + let original = std::str::from_utf8(super::super::moe::COMBINE.ptx).unwrap(); + let scalar = entry_text(original, "mtp_full_combine"); + assert_eq!((count(scalar, "mul.f32"), count(scalar, "add.f32")), (1, 1)); + assert!(count(scalar, "fma.rn.f32") >= 9, "the sealed scalar kernel fuses every product after the first"); + assert!(!scalar.contains(".ftz") && !scalar.contains("approx") && !scalar.contains("add.rn.f32")); + let text = std::str::from_utf8(COMBINE_VEC4.ptx).unwrap(); + let vector = entry_text(text, E_COMBINE_VEC4); + // four columns: four rounded first products, 9 x 4 fused multiply-adds, four adds of the shared row + assert_eq!((count(vector, "mul.f32"), count(vector, "fma.rn.f32"), count(vector, "add.f32")), (4, 36, 4)); + assert!(!vector.contains(".ftz") && !vector.contains("approx") && !vector.contains("div.")); + // float4 loads of the ten parts rows and of the shared row, one float4 store + assert_eq!(vector.matches("ld.global.nc.v4.b32").count(), 11); + assert_eq!(vector.matches("st.global.v4.b32").count(), 1); + // 36 distinct fused results: four independent chains of nine + let results: std::collections::HashSet<&str> = vector + .lines() + .filter(|l| l.trim_start().starts_with("fma.rn.f32")) + .map(|l| l.split_whitespace().nth(1).unwrap().trim_end_matches(',')) + .collect(); + assert_eq!(results.len(), 36); +} + +#[test] +fn a_batched_group_is_one_launch_with_the_token_on_grid_y() { + let m = arena(); + let launches = plan(&m, site(0, 4, true)).unwrap(); + assert_eq!(launches.len(), 1); + let l = &launches[0]; + assert_eq!((l.entry, l.grid, l.block, l.shared), (E_COMBINE_VEC4, [5, 4, 1], [128, 1, 1], 0)); + let (parts, w) = (at(&m, "parts", 0), at(&m, "w", 0)); + let (shared, bo) = (at(&m, "shared", 0), at(&m, "bo", 0)); + assert_eq!(l.args, vec![A::P(parts), A::P(w), A::P(shared), A::P(bo), A::I64(640)]); +} + +#[test] +fn a_group_that_starts_late_binds_its_own_rows() { + let m = arena(); + let l = &plan(&m, site(2, 5, true)).unwrap()[0]; + assert_eq!(l.grid, [5, 3, 1]); + let 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::I64(640), + ]; + assert_eq!(l.args, args); +} + +#[test] +fn rows_not_batched_get_one_launch_each() { + let m = arena(); + let launches = plan(&m, site(1, 4, false)).unwrap(); + assert_eq!(launches.len(), 3); + for (i, l) in launches.iter().enumerate() { + assert_eq!((l.grid, l.block), ([5, 1, 1], [128, 1, 1])); + assert_eq!(l.args[3], A::P(at(&m, "bo", (1 + i) * 2560 * 4))); + } +} + +#[test] +fn what_does_not_fit_the_vector_kernel_keeps_the_scalar_launches() { + let m = arena(); + let not_native = CombineSite { native_combine: false, ..site(0, 4, true) }; + assert!(plan(&m, not_native).is_none(), "the legacy double-precision combine is another kernel"); + let mut eight = test_geometry(); + eight.k = 8; + assert!(plan_combine_vec4(&m, &eight, site(0, 4, true)).unwrap().is_none()); + let mut odd = test_geometry(); + odd.n = 2562; + assert!(plan_combine_vec4(&m, &odd, site(0, 1, false)).unwrap().is_none()); + assert!(plan_combine_vec4(&Skewed(&m, 4), &test_geometry(), site(0, 4, true)).unwrap().is_none()); + assert!(plan_combine_vec4(&Skewed(&m, 16), &test_geometry(), site(0, 4, true)).unwrap().is_some()); +} + +#[test] +fn the_row_ranges_the_scalar_planner_refuses_are_refused() { + let m = arena(); + let g = test_geometry(); + let wrong_group = CombineSite { rows: Rows { begin: 0, end: 2, group: 2 }, ..site(0, 2, true) }; + for bad in [site(2, 2, false), site(0, 9, true), site(3, 4, true), wrong_group] { + assert!(plan_combine_vec4(&m, &g, bad).is_err(), "{bad:?}"); + } +} diff --git a/crates/cuda-driver/src/original_verify_window_gr.rs b/crates/cuda-driver/src/original_verify_window_gr.rs index a9be585f..78075835 100644 --- a/crates/cuda-driver/src/original_verify_window_gr.rs +++ b/crates/cuda-driver/src/original_verify_window_gr.rs @@ -354,6 +354,10 @@ pub(crate) use plan_hc_read::plan_hc_read; pub(crate) use plan_hc_read::plan_head_mix; #[allow(unused_imports)] use plan_hc_read::write_row; +#[path = "original_verify_window_gr/plan_head_mix_multi.rs"] +mod plan_head_mix_multi; +#[allow(unused_imports)] +pub(crate) use plan_head_mix_multi::plan_head_mix_multi; #[path = "original_verify_window_gr/plan_ple_row.rs"] mod plan_ple_row; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/original_verify_window_gr/plan_hc_read.rs b/crates/cuda-driver/src/original_verify_window_gr/plan_hc_read.rs index e1831069..bc627ca1 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/plan_hc_read.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/plan_hc_read.rs @@ -18,11 +18,21 @@ pub(crate) fn plan_hc_read( ) -> Result { let GrWindow { arena, geo, cfg } = window; 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 xn = arena.span("xn", rows.begin * D * 4, rows.len() * D * 4)?; + hc_read_of_rows(cfg, w, apply, (&per_row, xn)) +} +/// The three kernel groups of one `fused_gr_read_multi` call over `(per-row addresses, the xn staging span)`; shared by +/// the layer reads and the head mix of `LELEKA_SM120_HEAD_MIX_MULTI`. +pub(super) fn hc_read_of_rows( + cfg: &GrConfig, + w: &HcAddrs, + apply: bool, + (per_row, xn): (&[RowArgs], u64), +) -> Result { + let n = per_row.len(); + 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)?; diff --git a/crates/cuda-driver/src/original_verify_window_gr/plan_head_mix_multi.rs b/crates/cuda-driver/src/original_verify_window_gr/plan_head_mix_multi.rs new file mode 100644 index 00000000..e64048f2 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_gr/plan_head_mix_multi.rs @@ -0,0 +1,51 @@ +//! `LELEKA_SM120_HEAD_MIX_MULTI`: upstream's `STRATA_HEAD_MIX_MULTI` (verify.cpp 301-316 and 2327-2345, default on for +//! CUDA there). The final mixer of the window's tokens as ONE `fused_gr_read_multi` call (norm, down, up: three +//! launches for any window of up to the chunk limit of the card) instead of the five launches per token of +//! `plan_head_mix` (norm, down gemv, down-silu, up gemv, pre-final: 5 T launches). +//! +//! It is the layer read (`plan_hc_read`, the very same kernels and the very same variant and chunk decisions) over the +//! head's weights `output_hc_*`, without the pending write (`apply = false`: the last layer's write is +//! `plan_final_write`) and without an inject projection (`w_inject = 0`: the down kernels skip the inject block, the +//! up kernel never reads it). The multi kernels compute the sums of the native per-token `gr_read` in the same order +//! (the Original's `fused_gr_check` asserts it per card); the per-token rows `R`, `xn`, `lo`, `rs` are the arena slots +//! the per-token path used, and the mixed rows are the head rows' `mixed` buffer, so everything after (quantize, MMVQ, +//! argmax) is unchanged. + +use super::plan_hc_read::hc_read_of_rows; +#[allow(unused_imports)] +use super::*; + +/// The per-row addresses of head row `t`: no pending write (`bo_prev`, `inj_prev`), no inject output. +fn head_row(arena: &(impl ArenaMap + ?Sized), mixed_out_base: u64, t: usize) -> Result { + Ok(RowArgs { + r: arena.span("R", t * D * 4, D * 4)?, + bo_prev: 0, + inj_prev: 0, + lo: arena.span("lo", t * LR * 4, LR * 4)?, + rs: arena.span("rs", t * HC * 4, HC * 4)?, + inject_out: 0, + mixed: mixed_out_base + (t * N * 4) as u64, + }) +} + +/// The launches of `fused_gr_read_multi` over the head weights for the window's first `rows` rows, writing row `t`'s +/// mixed vector at `mixed_out_base + t * N * 4`. Refuses what `plan_head_mix` refuses (a non-native MMVF card). +pub(crate) fn plan_head_mix_multi( + window: GrWindow<'_>, + w: &HeadAddrs, + mixed_out_base: u64, + rows: usize, +) -> Result> { + let GrWindow { arena, geo, cfg } = window; + check_geometry(geo)?; + if !(1..=geo.max_t).contains(&rows) { + return Err(Error::InvalidQwenShape); + } + if !cfg.native_mmvf { + return Err(refuse("head")); + } + let per_row = (0..rows).map(|t| head_row(arena, mixed_out_base, t)).collect::>>()?; + let xn = arena.span("xn", 0, rows * D * 4)?; + let hc = HcAddrs { norm: w.norm, down: w.down, up: w.up, inject: 0 }; + Ok(hc_read_of_rows(cfg, &hc, false, (&per_row, xn))?.launches()) +} diff --git a/crates/cuda-driver/src/original_verify_window_gr/tests.rs b/crates/cuda-driver/src/original_verify_window_gr/tests.rs index 5cf68c33..59757c85 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/tests.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/tests.rs @@ -60,5 +60,7 @@ fn ple_addrs(key: PleKey) -> PleAddrs { #[path = "tests/head_mix_is_the_native.rs"] mod head_mix_is_the_native; +#[path = "tests/head_mix_multi.rs"] +mod head_mix_multi; #[path = "tests/tiled_down_projection_covers.rs"] mod tiled_down_projection_covers; diff --git a/crates/cuda-driver/src/original_verify_window_gr/tests/head_mix_multi.rs b/crates/cuda-driver/src/original_verify_window_gr/tests/head_mix_multi.rs new file mode 100644 index 00000000..e2ddfefb --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_gr/tests/head_mix_multi.rs @@ -0,0 +1,91 @@ +//! `plan_head_mix_multi` (`LELEKA_SM120_HEAD_MIX_MULTI`): the final mixer of the window as one multi-token hc read over +//! the head weights, with the addresses the per-token path used. + +#[allow(unused_imports)] +use super::*; + +const MIXED_BASE: u64 = 0x9999_0000; +const HEAD: HeadAddrs = HeadAddrs { norm: 0xA000, down: 0xB000, up: 0xC000 }; + +/// The words of row `k` in the `GrMulti` struct: `FusedGrArgs` is 14 words. +fn row_words(w: &[u64], k: usize) -> &[u64] { + &w[k * 14..(k + 1) * 14] +} + +#[test] +fn the_head_mix_is_one_layer_style_read_whatever_the_window_width() { + let m = arena(); + let g = test_geometry(); + let cfg = sm120(GrVariant::Staged); + for rows in 1..=8usize { + let multi = plan_head_mix_multi(window(&m, &g, &cfg), &HEAD, MIXED_BASE, rows).unwrap(); + let per_token = plan_head_mix(window(&m, &g, &cfg), &HEAD, MIXED_BASE, rows).unwrap(); + assert_eq!(per_token.len(), 5 * rows); + // the same kernels and chunking as a layer's read of `rows` rows (the head weights, no pending write) + let hc = HcAddrs { norm: HEAD.norm, down: HEAD.down, up: HEAD.up, inject: 0 }; + let read = plan_hc_read(window(&m, &g, &cfg), &hc, HcHalf::Ffn, false, rows_of(0, rows)).unwrap().launches(); + let entries = |l: &[Launch]| l.iter().map(|x| (x.entry, x.grid, x.block, x.shared)).collect::>(); + assert_eq!(entries(&multi), entries(&read), "rows {rows}"); + assert!(multi.len() < per_token.len(), "rows {rows}: {} against {}", multi.len(), per_token.len()); + } +} + +#[test] +fn the_chain_kernels_of_the_layers_take_the_head_mix_too() { + use super::super::super::chain::{self, ChainFlags}; + let m = arena(); + let g = test_geometry(); + let cfg = sm120(GrVariant::Staged); + let launches = chain::with_flags(ChainFlags { gr: true, ..ChainFlags::default() }, || { + plan_head_mix_multi(window(&m, &g, &cfg), &HEAD, MIXED_BASE, 4).unwrap() + }); + let entries: Vec<&str> = launches.iter().map(|l| l.entry).collect(); + assert_eq!(entries.first(), Some(&chain::E_GR_SPLIT)); + assert!(entries.last().is_some_and(|e| e.starts_with("chain_gr_up")), "{entries:?}"); + assert_eq!(launches.len(), 3, "norm, one down launch of four tokens, up: {entries:?}"); + // the split norm is one block a token and stream, the down kernel reads the same 4 xn rows + assert_eq!(launches[0].grid, [4, 4, 1]); +} + +#[test] +fn each_row_reads_its_residual_and_writes_its_mixed_row_with_no_pending_write() { + let m = arena(); + let g = test_geometry(); + let l = plan_head_mix_multi(window(&m, &g, &sm120(GrVariant::Staged)), &HEAD, MIXED_BASE, 3).unwrap(); + let w = words(&l[0]); + assert_eq!(w.len(), 114); + for k in 0..3usize { + let a = row_words(w, k); + let r = at(&m, "R", k * 40_960); + assert_eq!((a[0], a[1]), (r, r), "row {k}: in place"); + assert_eq!(a[2], 0, "row {k}: apply = false, the final write was its own launch"); + assert_eq!((a[3], a[4], a[8], a[12]), (0, 0, 0, 0), "row {k}: no bo_prev, inj_prev, inject, inject_out"); + assert_eq!((a[5], a[6], a[7]), (HEAD.norm, HEAD.down, HEAD.up)); + assert_eq!(a[9], u64::from(1e-6f32.to_bits())); + assert_eq!((a[10], a[11]), (at(&m, "lo", k * 1280), at(&m, "rs", k * 16))); + assert_eq!(a[13], MIXED_BASE + (k * 10_240) as u64, "row {k}: the head rows' mixed buffer"); + } + assert_eq!(w[14 * 8], at(&m, "xn", 0)); + assert_eq!(w[14 * 8 + 1], 3); + // the rows after the window are untouched + assert!(w[14 * 3..14 * 8].iter().all(|x| *x == 0)); +} + +#[test] +fn the_same_bounds_and_refusals_as_the_per_token_head_mix() { + let m = arena(); + let g = test_geometry(); + assert!(plan_head_mix_multi(window(&m, &g, &sm120(GrVariant::Staged)), &HEAD, MIXED_BASE, 8).is_ok()); + assert!(plan_head_mix_multi(window(&m, &g, &sm120(GrVariant::Staged)), &HEAD, MIXED_BASE, 9).is_err()); + assert!(plan_head_mix_multi(window(&m, &g, &sm120(GrVariant::Staged)), &HEAD, MIXED_BASE, 0).is_err()); + let mut non_native = sm120(GrVariant::Staged); + non_native.native_mmvf = false; + assert!(matches!( + plan_head_mix_multi(window(&m, &g, &non_native), &HEAD, MIXED_BASE, 1), + Err(Error::InvalidDriverValue(s)) if s.contains("head") + )); +} + +fn rows_of(begin: usize, end: usize) -> Rows { + rows(begin, end, 0) +} diff --git a/crates/cuda-driver/src/original_verify_window_ops.rs b/crates/cuda-driver/src/original_verify_window_ops.rs index ab997ac2..8b37b0dd 100644 --- a/crates/cuda-driver/src/original_verify_window_ops.rs +++ b/crates/cuda-driver/src/original_verify_window_ops.rs @@ -90,6 +90,8 @@ pub(crate) struct OriginalVerifyWindowOps<'c, 's, 'ctx> { policy: WindowPolicy, /// The GDN kernel switches (`original_verify_window_gdn_fused.rs`). gdn: gdn_fused::GdnFusedPolicy, + /// The combine and head-mix kernel switches (`original_verify_window_combine_head.rs`). + combine_head: combine_head::CombineHeadKernels, } #[cfg(test)] diff --git a/crates/cuda-driver/src/original_verify_window_ops/original_verifier.rs b/crates/cuda-driver/src/original_verify_window_ops/original_verifier.rs index b074e63d..fb6312cc 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/original_verifier.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/original_verifier.rs @@ -9,7 +9,7 @@ impl<'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'ctx>> { pub fn record_literal_window( &mut self, t: usize, - resources: OriginalVerifyWindowResources<'ctx>, + mut resources: OriginalVerifyWindowResources<'ctx>, policy: WindowPolicy, ) -> Result<()> { policy.validate_selected()?; @@ -23,14 +23,14 @@ impl<'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'ctx>> { 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; resources.prepare(&policy)?; - let gdn = gdn_fused::prepare(resources.verifier_journal())?; + let journal = resources.verifier_journal(); + let (gdn, combine_head) = (gdn_fused::prepare(journal)?, combine_head::prepare(journal)?); // SIDE_MIXER: this recording's capture creates the two side streams (a split window just leaves them unused) crate::original_gpu_schedule::set_side_streams_wanted(policy.side.any()); let recorded = self.record_window(t, resources, |capture, resources, groups| { // The recorder re-validates the shape; the groups come from `set_split`. - let mut ops = OriginalVerifyWindowOps { capture, resources, t, groups, policy, gdn }; + let mut ops = OriginalVerifyWindowOps { capture, resources, t, groups, policy, gdn, combine_head }; record_window(&mut ops, &policy, t, groups, ple) }); crate::original_gpu_schedule::set_side_streams_wanted(false); diff --git a/crates/cuda-driver/src/original_verify_window_ops/original_verify_window_ops_methods.rs b/crates/cuda-driver/src/original_verify_window_ops/original_verify_window_ops_methods.rs index 3d2e6946..1d0d14d4 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/original_verify_window_ops_methods.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/original_verify_window_ops_methods.rs @@ -77,7 +77,8 @@ impl<'ctx> OriginalVerifyWindowOps<'_, '_, 'ctx> { .resources .gr_cfg .ok_or(Error::InvalidDriverValue("Original verifier window: resources were not prepared before capture"))?; - Ok(Planner::new(&self.resources.base.journal, self.geometry(), self.policy, cfg, &*self.resources)) + let planner = Planner::new(&self.resources.base.journal, self.geometry(), self.policy, cfg, &*self.resources); + Ok(planner.with_combine_head(self.combine_head)) } /// Plan with the planner, then record the launches. pub(super) fn plan_launch(&mut self, plan: impl FnOnce(&Planner<'_>) -> Result>) -> Result<()> { diff --git a/crates/cuda-driver/src/original_verify_window_planner.rs b/crates/cuda-driver/src/original_verify_window_planner.rs index aed6406e..a0f96ecb 100644 --- a/crates/cuda-driver/src/original_verify_window_planner.rs +++ b/crates/cuda-driver/src/original_verify_window_planner.rs @@ -6,6 +6,7 @@ //! capture stream; the tests run the whole recorder through `PlanOps` (no driver) to pin //! the complete launch order of a window against verify.cpp. use super::OriginalVerifyGeometry; +use super::combine_head::{self, CombineHeadKernels, CombineSite}; use super::gr::{self, GrConfig, HcAddrs, HeadAddrs, PleAddrs, PleConfig}; use super::kernels::{ArenaMap, Launch}; use super::moe::{self, MoeKnobs, MoeLayerAddrs, OriginalVerifyExpertFormats}; @@ -39,6 +40,8 @@ pub(crate) struct Planner<'p> { pub policy: WindowPolicy, pub gr: GrConfig, pub weights: &'p dyn WindowWeights, + /// `LELEKA_SM120_COMBINE_VEC4` / `LELEKA_SM120_HEAD_MIX_MULTI` (off: the literal Original launches). + pub combine_head: CombineHeadKernels, } impl<'p> Planner<'p> { @@ -49,7 +52,11 @@ impl<'p> Planner<'p> { gr: GrConfig, weights: &'p dyn WindowWeights, ) -> Self { - Self { arena, geo, policy, gr, weights } + Self { arena, geo, policy, gr, weights, combine_head: CombineHeadKernels::default() } + } + pub(crate) fn with_combine_head(mut self, combine_head: CombineHeadKernels) -> Self { + self.combine_head = combine_head; + self } pub(crate) fn moe_knobs_of(policy: &WindowPolicy) -> MoeKnobs { MoeKnobs { @@ -91,6 +98,9 @@ impl<'p> Planner<'p> { /// The per-token `lm_head_mix` launches writing the head rows' `mixed` buffer at `mixed_out_base`. pub(crate) fn head_mix(&self, mixed_out_base: u64, rows: usize) -> Result> { let w = self.weights.head()?; + if self.combine_head.head_mix_multi { + return gr::plan_head_mix_multi(self.gr_window(), &w, mixed_out_base, rows); + } gr::plan_head_mix(self.gr_window(), &w, mixed_out_base, rows) } /// One entry per window row: that row's launches, to be followed by the PLE history snapshot copy of the row. @@ -183,7 +193,14 @@ impl<'p> Planner<'p> { moe::plan_hit_add(self.arena, &self.geo, rows) } pub(crate) fn combine(&self, rows: Rows, batched: bool) -> Result> { - moe::plan_combine(self.arena, &self.geo, &self.moe_knobs(), rows, batched) + let knobs = self.moe_knobs(); + if self.combine_head.combine_vec4 { + let site = CombineSite { rows, batched, native_combine: knobs.native_combine }; + if let Some(launches) = combine_head::plan_combine_vec4(self.arena, &self.geo, site)? { + return Ok(launches); + } + } + moe::plan_combine(self.arena, &self.geo, &knobs, rows, batched) } } 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 f6277e07..1d2fd66b 100644 --- a/crates/cuda-driver/src/original_verify_window_planner/tests.rs +++ b/crates/cuda-driver/src/original_verify_window_planner/tests.rs @@ -339,6 +339,8 @@ fn names(log: &[String]) -> Vec<&str> { log.iter().map(String::as_str).collect() } +#[path = "tests/combine_head_switches.rs"] +mod combine_head_switches; #[path = "tests/every_window_size_and_group.rs"] mod every_window_size_and_group; #[path = "tests/fused_qsa_prelude.rs"] diff --git a/crates/cuda-driver/src/original_verify_window_planner/tests/combine_head_switches.rs b/crates/cuda-driver/src/original_verify_window_planner/tests/combine_head_switches.rs new file mode 100644 index 00000000..72e9d4e3 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_planner/tests/combine_head_switches.rs @@ -0,0 +1,78 @@ +//! `LELEKA_SM120_COMBINE_VEC4` and `LELEKA_SM120_HEAD_MIX_MULTI` through the recorder: with both off the window is the +//! literal one, each switch alone changes only its own launches, and the launch counts fall as the design note says. + +use super::super::super::combine_head::{CombineHeadKernels, E_COMBINE_VEC4}; +#[allow(unused_imports)] +use super::*; + +const OFF: CombineHeadKernels = CombineHeadKernels { combine_vec4: false, head_mix_multi: false }; +const VEC4: CombineHeadKernels = CombineHeadKernels { combine_vec4: true, head_mix_multi: false }; +const HEAD: CombineHeadKernels = CombineHeadKernels { combine_vec4: false, head_mix_multi: true }; + +fn record_with(kernels: CombineHeadKernels, t: usize, groups: usize) -> Vec { + let (m, fake) = geometry_and_fake(false); + let policy = WindowPolicy::mode17(); + let planner = Planner::new(&m, test_geometry(), policy, sm120(), &fake).with_combine_head(kernels); + let mut ops = PlanOps { planner, log: Vec::new(), t }; + record_window(&mut ops, &policy, t, groups, false).unwrap(); + ops.log +} +fn count(log: &[String], name: &str) -> usize { + log.iter().filter(|s| *s == name).count() +} +fn tail(log: &[String]) -> &[String] { + section(log, "stamp 48.0", "stamp 48.1") +} + +#[test] +fn both_off_is_the_literal_window() { + for (t, groups) in [(1, 1), (3, 1), (8, 1), (6, 2)] { + assert_eq!(record_with(OFF, t, groups), record(t, groups, false), "T {t} groups {groups}"); + } +} + +#[test] +fn the_vector_combine_replaces_the_scalar_combine_launch_for_launch() { + for (t, groups) in [(1, 1), (3, 1), (8, 1), (6, 2)] { + let off = record_with(OFF, t, groups); + let on = record_with(VEC4, t, groups); + let renamed: Vec = + off.iter().map(|s| if s == "mtp_full_combine" { E_COMBINE_VEC4.to_string() } else { s.clone() }).collect(); + assert_eq!(on, renamed, "T {t} groups {groups}: nothing but the combine kernel changes"); + assert_eq!(count(&on, "mtp_full_combine"), 0); + assert_eq!(count(&on, E_COMBINE_VEC4), count(&off, "mtp_full_combine")); + assert!(count(&on, E_COMBINE_VEC4) >= 48); + } +} + +#[test] +fn the_multi_head_mix_replaces_five_launches_a_token_with_one_read() { + for t in 1..=8usize { + let off = record_with(OFF, t, 1); + let on = record_with(HEAD, t, 1); + let (before, after) = (tail(&off), tail(&on)); + assert_eq!(count(before, "mtp_full_pre_final"), t); + assert_eq!(count(after, "mtp_full_pre_final") + count(after, "mtp_full_gr_norm"), 0, "T {t}"); + assert!(after.len() < before.len(), "T {t}: {} launches against {}", after.len(), before.len()); + assert_eq!(before.len() - after.len(), 5 * t - hc_read_launches(t), "T {t}"); + assert_eq!(on.len() + 5 * t - hc_read_launches(t), off.len(), "T {t}: nothing outside the tail changes"); + assert_eq!(after.last(), before.last(), "the head owner finishes the tail as before"); + } +} + +/// The launches of one multi-token read of `t` rows on the planner's card. +fn hc_read_launches(t: usize) -> usize { + let (m, fake) = geometry_and_fake(false); + let planner = Planner::new(&m, test_geometry(), WindowPolicy::mode17(), sm120(), &fake).with_combine_head(HEAD); + planner.head_mix(0x7f_0000_0000, t).unwrap().len() +} + +#[test] +fn both_on_changes_both_and_nothing_else() { + let both = CombineHeadKernels { combine_vec4: true, head_mix_multi: true }; + let (off, on) = (record_with(OFF, 4, 1), record_with(both, 4, 1)); + assert_eq!(count(&on, "mtp_full_combine"), 0); + assert_eq!(count(&on, "mtp_full_pre_final"), 0); + assert_eq!(count(&on, E_COMBINE_VEC4), count(&off, "mtp_full_combine")); + assert_eq!(on.len() + 5 * 4 - hc_read_launches(4), off.len()); +} diff --git a/crates/cuda-driver/src/original_verify_window_sm120.rs b/crates/cuda-driver/src/original_verify_window_sm120.rs index 6a335bf0..3e94bfa1 100644 --- a/crates/cuda-driver/src/original_verify_window_sm120.rs +++ b/crates/cuda-driver/src/original_verify_window_sm120.rs @@ -86,6 +86,9 @@ pub(crate) const DEFAULT_ON_FUSED_QSA_PRELUDE: bool = false; // claude/verify-gdn-fused-kernels (original_verify_window_gdn_fused.rs): both off until a paired A/B and identity pub(crate) const DEFAULT_ON_FUSED_GDN: bool = false; pub(crate) const DEFAULT_ON_GDN_AB_UNROLL: bool = false; +// claude/s11-s9-combine-headmix (original_verify_window_combine_head.rs): both off until identity and a paired A/B +pub(crate) const DEFAULT_ON_COMBINE_VEC4: bool = false; +pub(crate) const DEFAULT_ON_HEAD_MIX_MULTI: bool = false; /// Which parts of the verify graph run on the two side streams: the GDN gates and gate projection, the QSA indexer and /// query chains (upstream `STRATA_SIDE_MIXER=2`), and the shared expert beside the routed experts (upstream's shared @@ -130,6 +133,11 @@ pub struct Sm120Switches { pub fused_gdn: bool, /// `LELEKA_SM120_GDN_AB_UNROLL`: upstream `STRATA_SMALL_UNR` bit 1, the unrolled a/b projection kernel. pub gdn_ab_unroll: bool, + // ---- claude/s11-s9-combine-headmix + /// `LELEKA_SM120_COMBINE_VEC4`: the routed-expert combine as upstream's float4 `combine_k10_vec4`. + pub combine_vec4: bool, + /// `LELEKA_SM120_HEAD_MIX_MULTI`: the final mixer of the window's tokens as one multi-token hc read. + pub head_mix_multi: bool, } fn one(get: &impl Fn(&str) -> Option, var: &str, default: bool) -> bool { @@ -176,6 +184,8 @@ impl Sm120Switches { fused_qsa_prelude: switch("LELEKA_SM120_FUSED_QSA_PRELUDE", DEFAULT_ON_FUSED_QSA_PRELUDE), fused_gdn: switch("LELEKA_SM120_FUSED_GDN", DEFAULT_ON_FUSED_GDN), gdn_ab_unroll: switch("LELEKA_SM120_GDN_AB_UNROLL", DEFAULT_ON_GDN_AB_UNROLL), + combine_vec4: switch("LELEKA_SM120_COMBINE_VEC4", DEFAULT_ON_COMBINE_VEC4), + head_mix_multi: switch("LELEKA_SM120_HEAD_MIX_MULTI", DEFAULT_ON_HEAD_MIX_MULTI), } } /// The side-stream parts these switches ask for. @@ -194,6 +204,8 @@ impl Sm120Switches { fused_qsa_prelude: s.fused_qsa_prelude, fused_gdn: s.fused_gdn, gdn_ab_unroll: s.gdn_ab_unroll, + combine_vec4: s.combine_vec4, + head_mix_multi: s.head_mix_multi, } } } diff --git a/crates/cuda-driver/src/sm120_combine_vec4.cu b/crates/cuda-driver/src/sm120_combine_vec4.cu new file mode 100644 index 00000000..33785b5e --- /dev/null +++ b/crates/cuda-driver/src/sm120_combine_vec4.cu @@ -0,0 +1,52 @@ +// verify window, routed-expert combine (docs/experiments/verify-combine-and-head-mix.md): LELEKA_SM120_COMBINE_VEC4. +// +// Upstream's `combine_k10_vec4` (native_moe.cu 66-93, the non-hits form: our window adds the hits in their own launch, +// `moe_hit_add`) as an sm_120 entry of its own. It replaces `mtp_full_combine` (mtp_original_full_combine.cu, the +// literal Original `combine`: one thread a column, grid (n_embd / 256, tokens)) for k = 10 routed experts and a shared +// expert: one thread a COLUMN QUARTET, grid (n_embd / 4 / 128, tokens), float4 loads of the ten parts rows and of the +// shared row, one float4 store. +// +// Same value of every output element, element by element. The Original's loop per column is +// sum = parts[0] * w[0]; for e in 1..10: sum += parts[e] * w[e]; sum += shared; +// and its sealed PTX (mtp_original_full_combine.ptx, entry mtp_full_combine) is: one `mul.f32` for the first product +// (rounded), then `fma.rn.f32` per expert in ascending order (the compiler contracted `sum += p * w`), then one +// `add.f32` of the shared row. This kernel spells exactly that, per component: the first product rounded, nine +// `fmaf` in expert order, one add. The four float4 components are independent columns, so the vector width changes +// no per-element arithmetic. The weights are the same ten floats of the token's row, read once per thread. +// +// Compile: nvcc --ptx -O3 -arch=sm_120 -std=c++17 --fmad=true --ftz=false (the recipe of original_verify.cu). The +// `mul.f32` of the first product feeds the addend of an explicit `fma.rn.f32`, which ptxas does not contract. +// Preconditions (checked by the host planner, which keeps the scalar kernel otherwise): k = 10, n_embd % 4 == 0, the +// parts, shared and output rows 16-byte aligned. +#include +#include + +extern "C" __global__ void __launch_bounds__(128) leleka_verify_combine_k10_vec4( + const float4* __restrict__ parts4, const float* __restrict__ weights, const float4* __restrict__ shared4, + float4* __restrict__ output4, int64_t n4) { + const int64_t tk = blockIdx.y; // the token of the window + parts4 += tk * 10 * n4; + weights += tk * 10; + shared4 += tk * n4; + output4 += tk * n4; + const int64_t c4 = int64_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (c4 >= n4) return; + const float w0 = weights[0]; + const float4 p0 = parts4[c4]; + float4 sum = make_float4(p0.x * w0, p0.y * w0, p0.z * w0, p0.w * w0); +#pragma unroll + for (int expert = 1; expert < 10; ++expert) { + const float w = weights[expert]; + const float4 p = parts4[int64_t(expert) * n4 + c4]; + sum.x = fmaf(p.x, w, sum.x); + sum.y = fmaf(p.y, w, sum.y); + sum.z = fmaf(p.z, w, sum.z); + sum.w = fmaf(p.w, w, sum.w); + } + const float4 sh = shared4[c4]; + sum.x += sh.x; + sum.y += sh.y; + sum.z += sh.z; + sum.w += sh.w; + output4[c4] = sum; +} diff --git a/crates/cuda-driver/src/sm120_combine_vec4.ptx b/crates/cuda-driver/src/sm120_combine_vec4.ptx new file mode 100644 index 00000000..33f8d0cd --- /dev/null +++ b/crates/cuda-driver/src/sm120_combine_vec4.ptx @@ -0,0 +1,136 @@ +// +// Generated by NVIDIA NVVM Compiler +// +// Compiler Build ID: UNKNOWN +// Cuda compilation tools, release 13.2, V13.2.86 +// Based on NVVM 22.0.0 +// + +.version 9.2 +.target sm_120 +.address_size 64 + + // .globl leleka_verify_combine_k10_vec4 + +.visible .entry leleka_verify_combine_k10_vec4( + .param .u64 .ptr .align 1 leleka_verify_combine_k10_vec4_param_0, + .param .u64 .ptr .align 1 leleka_verify_combine_k10_vec4_param_1, + .param .u64 .ptr .align 1 leleka_verify_combine_k10_vec4_param_2, + .param .u64 .ptr .align 1 leleka_verify_combine_k10_vec4_param_3, + .param .u64 leleka_verify_combine_k10_vec4_param_4 +) +.maxntid 128 +{ + .reg .pred %p<2>; + .reg .b32 %r<103>; + .reg .b64 %rd<34>; + + ld.param.b64 %rd7, [leleka_verify_combine_k10_vec4_param_0]; + ld.param.b64 %rd8, [leleka_verify_combine_k10_vec4_param_1]; + ld.param.b64 %rd4, [leleka_verify_combine_k10_vec4_param_2]; + ld.param.b64 %rd5, [leleka_verify_combine_k10_vec4_param_3]; + ld.param.b64 %rd6, [leleka_verify_combine_k10_vec4_param_4]; + cvta.to.global.u64 %rd1, %rd7; + cvta.to.global.u64 %rd2, %rd8; + mov.u32 %r1, %ctaid.x; + mov.u32 %r2, %ntid.x; + mul.wide.u32 %rd9, %r1, %r2; + mov.u32 %r3, %tid.x; + cvt.u64.u32 %rd10, %r3; + add.s64 %rd3, %rd9, %rd10; + setp.ge.s64 %p1, %rd3, %rd6; + @%p1 bra $L__BB0_2; + mov.u32 %r4, %ctaid.y; + cvt.u64.u32 %rd11, %r4; + mul.wide.u32 %rd12, %r4, 40; + add.s64 %rd13, %rd2, %rd12; + cvta.to.global.u64 %rd14, %rd4; + cvta.to.global.u64 %rd15, %rd5; + ld.global.nc.b32 %r5, [%rd13]; + mul.lo.s64 %rd16, %rd6, %rd11; + mad.lo.s64 %rd17, %rd16, 160, %rd1; + shl.b64 %rd18, %rd3, 4; + add.s64 %rd19, %rd17, %rd18; + ld.global.nc.v4.b32 {%r6, %r7, %r8, %r9}, [%rd19]; + mul.f32 %r10, %r5, %r6; + mul.f32 %r11, %r5, %r7; + mul.f32 %r12, %r5, %r8; + mul.f32 %r13, %r5, %r9; + ld.global.nc.b32 %r14, [%rd13+4]; + shl.b64 %rd20, %rd6, 4; + add.s64 %rd21, %rd19, %rd20; + ld.global.nc.v4.b32 {%r15, %r16, %r17, %r18}, [%rd21]; + fma.rn.f32 %r19, %r15, %r14, %r10; + fma.rn.f32 %r20, %r16, %r14, %r11; + fma.rn.f32 %r21, %r17, %r14, %r12; + fma.rn.f32 %r22, %r18, %r14, %r13; + ld.global.nc.b32 %r23, [%rd13+8]; + add.s64 %rd22, %rd21, %rd20; + ld.global.nc.v4.b32 {%r24, %r25, %r26, %r27}, [%rd22]; + fma.rn.f32 %r28, %r24, %r23, %r19; + fma.rn.f32 %r29, %r25, %r23, %r20; + fma.rn.f32 %r30, %r26, %r23, %r21; + fma.rn.f32 %r31, %r27, %r23, %r22; + ld.global.nc.b32 %r32, [%rd13+12]; + add.s64 %rd23, %rd22, %rd20; + ld.global.nc.v4.b32 {%r33, %r34, %r35, %r36}, [%rd23]; + fma.rn.f32 %r37, %r33, %r32, %r28; + fma.rn.f32 %r38, %r34, %r32, %r29; + fma.rn.f32 %r39, %r35, %r32, %r30; + fma.rn.f32 %r40, %r36, %r32, %r31; + ld.global.nc.b32 %r41, [%rd13+16]; + add.s64 %rd24, %rd23, %rd20; + ld.global.nc.v4.b32 {%r42, %r43, %r44, %r45}, [%rd24]; + fma.rn.f32 %r46, %r42, %r41, %r37; + fma.rn.f32 %r47, %r43, %r41, %r38; + fma.rn.f32 %r48, %r44, %r41, %r39; + fma.rn.f32 %r49, %r45, %r41, %r40; + ld.global.nc.b32 %r50, [%rd13+20]; + add.s64 %rd25, %rd24, %rd20; + ld.global.nc.v4.b32 {%r51, %r52, %r53, %r54}, [%rd25]; + fma.rn.f32 %r55, %r51, %r50, %r46; + fma.rn.f32 %r56, %r52, %r50, %r47; + fma.rn.f32 %r57, %r53, %r50, %r48; + fma.rn.f32 %r58, %r54, %r50, %r49; + ld.global.nc.b32 %r59, [%rd13+24]; + add.s64 %rd26, %rd25, %rd20; + ld.global.nc.v4.b32 {%r60, %r61, %r62, %r63}, [%rd26]; + fma.rn.f32 %r64, %r60, %r59, %r55; + fma.rn.f32 %r65, %r61, %r59, %r56; + fma.rn.f32 %r66, %r62, %r59, %r57; + fma.rn.f32 %r67, %r63, %r59, %r58; + ld.global.nc.b32 %r68, [%rd13+28]; + add.s64 %rd27, %rd26, %rd20; + ld.global.nc.v4.b32 {%r69, %r70, %r71, %r72}, [%rd27]; + fma.rn.f32 %r73, %r69, %r68, %r64; + fma.rn.f32 %r74, %r70, %r68, %r65; + fma.rn.f32 %r75, %r71, %r68, %r66; + fma.rn.f32 %r76, %r72, %r68, %r67; + ld.global.nc.b32 %r77, [%rd13+32]; + add.s64 %rd28, %rd27, %rd20; + ld.global.nc.v4.b32 {%r78, %r79, %r80, %r81}, [%rd28]; + fma.rn.f32 %r82, %r78, %r77, %r73; + fma.rn.f32 %r83, %r79, %r77, %r74; + fma.rn.f32 %r84, %r80, %r77, %r75; + fma.rn.f32 %r85, %r81, %r77, %r76; + ld.global.nc.b32 %r86, [%rd13+36]; + add.s64 %rd29, %rd28, %rd20; + ld.global.nc.v4.b32 {%r87, %r88, %r89, %r90}, [%rd29]; + fma.rn.f32 %r91, %r87, %r86, %r82; + fma.rn.f32 %r92, %r88, %r86, %r83; + fma.rn.f32 %r93, %r89, %r86, %r84; + fma.rn.f32 %r94, %r90, %r86, %r85; + add.s64 %rd30, %rd16, %rd3; + shl.b64 %rd31, %rd30, 4; + add.s64 %rd32, %rd14, %rd31; + ld.global.nc.v4.b32 {%r95, %r96, %r97, %r98}, [%rd32]; + add.f32 %r99, %r91, %r95; + add.f32 %r100, %r92, %r96; + add.f32 %r101, %r93, %r97; + add.f32 %r102, %r94, %r98; + add.s64 %rd33, %rd15, %rd31; + st.global.v4.b32 [%rd33], {%r99, %r100, %r101, %r102}; +$L__BB0_2: + ret; + +} diff --git a/docs/experiments/verify-combine-and-head-mix.md b/docs/experiments/verify-combine-and-head-mix.md new file mode 100644 index 00000000..20a75a56 --- /dev/null +++ b/docs/experiments/verify-combine-and-head-mix.md @@ -0,0 +1,74 @@ +# Verify window: vector combine (S11) and multi-token head mix (S9) + +Branch `claude/s11-s9-combine-headmix`. Two independent opt-in switches, both off by default, resolved in +`original_verify_window_sm120.rs` (`Sm120Switches`): `LELEKA_SM120_COMBINE_VEC4` and `LELEKA_SM120_HEAD_MIX_MULTI`. +Ledger rows S11, S9 (and R8 for the tail). Nothing was run on a GPU; every claim below is either read from code or marked +"not measured". + +## S11: `LELEKA_SM120_COMBINE_VEC4` + +* Replaces `mtp_full_combine` (`mtp_original_full_combine.cu`, one thread a column, grid `(n/256, T)`, 256 threads) with + upstream's `combine_k10_vec4` (`native_moe.cu` 66-93, the non-hits form: our window adds the hits in their own launch) + as `leleka_verify_combine_k10_vec4` (`sm120_combine_vec4.cu`, one thread a column quartet, grid `(n/4/128, T)`, 128 + threads, float4 loads of ten parts rows and the shared row, one float4 store). +* Arithmetic. The sealed scalar PTX of a column is one `mul.f32` (first product, rounded), nine `fma.rn.f32` in expert + order (the compiler contracted `sum += p * w`), one `add.f32` of the shared row. The vector kernel spells exactly that + per component (`p0 * w0`, nine `fmaf`, one add). The four components of a float4 are four independent columns, so the + vector width changes no per-element operation. The PTX has 4 `mul.f32`, 36 `fma.rn.f32`, 4 `add.f32`, no `.ftz`, no + approximate or divide ops (unit test `the_vector_kernel_has_the_arithmetic_shape_of_the_scalar_one`). +* Shape guard (`plan_combine_vec4`): `k == 10`, `n_embd % 4 == 0`, native combine, and parts / shared / output row bases + 16-byte aligned; otherwise the scalar launches are planned, which compute the same words. `batched` keeps its meaning + (one launch over the group, grid.y = token, else one per row). +* **No launch saving.** The scalar and the vector path are both one launch per layer and group (about 48 per graph), so + the whole effect is the kernel's own time. The ledger estimate 0.05-0.10 ms would need about 1-2 us saved on each of + 48 launches; the kernel moves about 0.45 MB (T = 4) that was just written into L2, so it is latency bound, and my + expectation (unmeasured) is a few tenths of a microsecond per launch, 0.01-0.02 ms per graph. The table of `ledger.md` + has no CUPTI time for `mtp_full_combine` of ours; read it first: if its mean is about 1.2 us, there is nothing to gain. +* Asset: `sm120_combine_vec4.ptx`, nvcc 13.2.86 (`~/cuda-toolkits/13.2.2` in WSL), `--ptx -O3 -arch=sm_120 -std=c++17 + --fmad=true --ftz=false`; sha256 `0b76676464fb2def53c1baa3a709fb9af16594aeeb285f399d06e09c5b4578a2`; pinned in + `COMBINE_VEC4.sha`, plan entry in `scripts/gpu-bringup/extra-seal-plan.json` (group `sm120-decode`), sm_86 note in + `ptx-sm86/MANIFEST.json` ("not built for sm_86 by design"). The recording fails closed with `Original verifier asset + unsealed: sm120_combine_vec4.ptx` when the pin does not match. + +## S9: `LELEKA_SM120_HEAD_MIX_MULTI` + +* Upstream `STRATA_HEAD_MIX_MULTI` (`verify.cpp` 301-316, 2327-2345; default on for CUDA there): the final mixer of the + window's T tokens as one `fused_gr_read_multi` call over `output_hc_*` with `apply = false` and no inject weight, + instead of the per-token native `gr_read`. +* Ours (`plan_head_mix_multi`, `original_verify_window_gr/plan_head_mix_multi.rs`): the layer read + (`plan_hc_read`, the very same kernels, variant and chunk decisions) over the head weights, three launches for a + window within the chunk limit (`chain_gr_split`, one `chain_gr_down_t2w8_nb4`, `chain_gr_up8` on the chain path; + `mtp_scalar_gr_split`, `mtp_scalar_gr_staged`, `mtp_scalar_gr_up` otherwise) in place of `5 T` launches + (`mtp_full_gr_norm`, `mtp_full_mmvf256`, `mtp_full_down_silu`, `mtp_full_mmvf160`, `mtp_full_pre_final` per token). + The head's weights are read once instead of T times (13 MB of bf16 `down` and `up`). No new PTX, no asset, no change to + `plan_final_write`, quantize, MMVQ or the argmax: `R`, `xn`, `lo`, `rs` use the arena slots of the per-token path and + `mixed` is the head rows' buffer. +* **Bitwise: by the Original's claim, not by anything I could run.** The multi kernels compute the sums of the native + per-token `gr_read` in the same order (the Original's `fused_gr_check` asserts it per card; upstream states "bitwise the + same sums" for this switch). Our layers already use these kernels, with `apply = false` where no pending write exists (layer 0, the PLE layer). What is NOT shown + on this machine is the byte compare of the multi read against our native per-token chain (the staged down kernel + against `mtp_full_mmvf256`, `__expf` silu against `mtp_full_down_silu`). `tools/combine-head/combine_head_probe.cpp` + does exactly that, model-free (T = 1..8, three seeds, chain and fused variants, `mixed`, `lo`, `xn` and the untouched + tail compared byte for byte). Run it before the identity job. +* Expected section delta: tail after the last layer's `add_hits` (ledger R8 +0.090 ms against vanilla): `5 T - 3` + launches fewer (about 15 at T 3.6), and T times fewer weight bytes read. Estimate 0.03-0.09 ms, unmeasured. + +## What the orchestrator should look at + +CUPTI window, per T inside one variant (the same method as `verify-new-switches-cupti-windows`): + +| switch | before (kernel names, launches per graph) | after | +| --- | --- | --- | +| COMBINE_VEC4 | `mtp_full_combine` ~48 | `leleka_verify_combine_k10_vec4` ~48 (same count; compare the mean time per launch and the FFN phase) | +| HEAD_MIX_MULTI | `mtp_full_gr_norm`, `mtp_full_mmvf256`, `mtp_full_down_silu`, `mtp_full_mmvf160`, `mtp_full_pre_final`: T each | `chain_gr_split` +1, `chain_gr_down_t2w8_nb4` +1, `chain_gr_up8` +1 (these names also occur 96 times per graph in the layers); the five names above drop to zero for the head. Total launches per graph `-(5 T - 3)`. Section: gap from the last `add_hits` to the head quantize | + +Identity: set the env switch only (`LELEKA_SM120_COMBINE_VEC4=1`, `LELEKA_SM120_HEAD_MIX_MULTI=1`, alone and together); +the teacher-forced top-16 rows and the draft trace must be bit-identical, A/A first. + +## Files + +`sm120_combine_vec4.{cu,ptx}`, `original_verify/original_verify_window_combine_head.rs` (switch DTO `CombineHeadKernels`, +asset, `plan_combine_vec4`, `prepare`), `original_verify_window_gr/plan_head_mix_multi.rs`, +`original_verify_window_gr/plan_hc_read.rs` (`hc_read_of_rows` extracted from `plan_hc_read`), +`original_verify_window_planner.rs` (`Planner::with_combine_head`), `original_verify_window_ops*.rs` (the DTO travels +beside `gdn`), `original_verify_window_sm120.rs` (two fields, two constants), tests beside each, `tools/combine-head/`. \ No newline at end of file diff --git a/scripts/gpu-bringup/extra-seal-plan.json b/scripts/gpu-bringup/extra-seal-plan.json index cf7e56c3..06fc18d8 100644 --- a/scripts/gpu-bringup/extra-seal-plan.json +++ b/scripts/gpu-bringup/extra-seal-plan.json @@ -1009,6 +1009,31 @@ }, "group": "sm120-decode", "optional": false + }, + { + "cu": "crates/cuda-driver/src/sm120_combine_vec4.cu", + "ptx": "crates/cuda-driver/src/sm120_combine_vec4.ptx", + "flags": [ + "-ptx", + "-O3", + "-arch=sm_120", + "-std=c++17", + "--fmad=true", + "--ftz=false" + ], + "include_profile": "standard", + "policy": "precise (--fmad=true --ftz=false: the recipe of original_verify.cu; s11-s9-combine-headmix: upstream combine_k10_vec4, the first product rounded then one explicit fmaf per expert in order then the shared add, as the sealed mtp_full_combine does per column)", + "entries": [ + "leleka_verify_combine_k10_vec4" + ], + "encoding": "concat_include_str", + "rust_fields_to_fill": { + "original_verify_window_combine_head.rs": [ + "COMBINE_VEC4.sha" + ] + }, + "group": "sm120-decode", + "optional": false } ] } diff --git a/tools/combine-head/build.sh b/tools/combine-head/build.sh new file mode 100644 index 00000000..d0312127 --- /dev/null +++ b/tools/combine-head/build.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Build the combine / head-mix probe in WSL (never on the server GPU queue by its author) and collect the PTX it compares. +# tools/combine-head/build.sh [OUTDIR] default OUTDIR=$HOME/combine-head-bin ; then: OUTDIR/combine_head_probe OUTDIR/ptx +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/../.." && pwd)" +out="${1:-$HOME/combine-head-bin}" +nvcc="${NVCC:-$HOME/cuda-toolkits/13.2.2/bin/nvcc}" +mkdir -p "$out/ptx" +"$nvcc" -O2 -std=c++17 "$here/combine_head_probe.cpp" -lcuda -o "$out/combine_head_probe" +for f in mtp_original_full_combine sm120_combine_vec4 mtp_original_full_gr_norm mtp_original_full_gr_post mtp_original_full_bf16 mtp_original_full_fused_gr chain_window; do + cp "$root/crates/cuda-driver/src/$f.ptx" "$out/ptx/$f.ptx" +done +sha256sum "$out"/combine_head_probe "$out"/ptx/* > "$out/SHA256SUMS" +ls -la "$out" "$out/ptx" \ No newline at end of file diff --git a/tools/combine-head/combine_head_probe.cpp b/tools/combine-head/combine_head_probe.cpp new file mode 100644 index 00000000..5f7ea97a --- /dev/null +++ b/tools/combine-head/combine_head_probe.cpp @@ -0,0 +1,185 @@ +// claude/s11-s9-combine-headmix: model-free probe of LELEKA_SM120_COMBINE_VEC4 and LELEKA_SM120_HEAD_MIX_MULTI. Each switch launches are run next to the +// launches of the current window that they replace, on real-size random inputs (including non-finite values), and EVERY output byte is compared. Prints +// "RESULT name key=value" lines; exits 1 if any comparison differs. Never touches the model. Written without a GPU: compiled, not run. +// combine_head_probe PTXDIR [combine|head ...] default: both. PTXDIR holds mtp_original_full_combine.ptx, sm120_combine_vec4.ptx, +// mtp_original_full_gr_norm.ptx, mtp_original_full_gr_post.ptx, mtp_original_full_bf16.ptx, mtp_original_full_fused_gr.ptx, chain_window.ptx (tools/combine-head/build.sh). +#include +#include +#include +#include +#include +#include +#include +#include + +#define CU(x) do { CUresult r_ = (x); if (r_ != CUDA_SUCCESS) { const char* s_ = nullptr; cuGetErrorString(r_, &s_); fprintf(stderr, "CUDA error %s at %s:%d: %s\n", #x, __FILE__, __LINE__, s_ ? s_ : "?"); exit(2); } } while (0) + +static int g_fail = 0; +static uint64_t g_rng = 0x9e3779b97f4a7c15ull; +static uint32_t rnd() { g_rng ^= g_rng << 13; g_rng ^= g_rng >> 7; g_rng ^= g_rng << 17; return (uint32_t)(g_rng >> 16); } +static float rndf() { return (float)(rnd() & 0xffffff) / 16777216.0f * 2.0f - 1.0f; } // [-1, 1) +static uint16_t bf16_of(float x) { uint32_t u; memcpy(&u, &x, 4); return (uint16_t)(u >> 16); } + +static std::string read_file(const std::string& p) { + FILE* f = fopen(p.c_str(), "rb"); + if (!f) { fprintf(stderr, "cannot open %s\n", p.c_str()); exit(2); } + std::string s; char buf[1 << 16]; size_t n; + while ((n = fread(buf, 1, sizeof buf, f)) > 0) s.append(buf, n); + fclose(f); + return s; +} +static CUmodule load_module(const std::string& p) { + std::string s = read_file(p); + s.push_back('\0'); + CUmodule m; char log[8192] = {}; + CUjit_option opt[] = {CU_JIT_ERROR_LOG_BUFFER, CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES}; + void* val[] = {log, (void*)(uintptr_t)sizeof log}; + CUresult r = cuModuleLoadDataEx(&m, s.data(), 2, opt, val); + if (r != CUDA_SUCCESS) { fprintf(stderr, "load %s failed: %d %s\n", p.c_str(), (int)r, log); exit(2); } + return m; +} +static CUfunction get_fn(CUmodule m, const char* name) { + CUfunction f; CUresult r = cuModuleGetFunction(&f, m, name); + if (r != CUDA_SUCCESS) { fprintf(stderr, "no entry %s\n", name); exit(2); } + return f; +} + +struct Dev { + CUdeviceptr p = 0; size_t n = 0; + void alloc(size_t bytes) { n = bytes; CU(cuMemAlloc(&p, bytes ? bytes : 1)); CU(cuMemsetD8(p, 0xCD, bytes ? bytes : 1)); } + void put(const void* h, size_t bytes) { CU(cuMemcpyHtoD(p, h, bytes)); } + std::vector get(size_t off = 0, size_t bytes = (size_t)-1) const { + if (bytes == (size_t)-1) bytes = n - off; + std::vector v(bytes); CU(cuCtxSynchronize()); CU(cuMemcpyDtoH(v.data(), p + off, bytes)); return v; + } +}; +static bool same(const char* what, const std::vector& a, const std::vector& b) { + if (a.size() != b.size()) { printf("MISMATCH %s: size %zu vs %zu\n", what, a.size(), b.size()); g_fail++; return false; } + size_t bad = 0, first = (size_t)-1; + for (size_t i = 0; i < a.size(); ++i) if (a[i] != b[i]) { if (first == (size_t)-1) first = i; ++bad; } + if (bad) { printf("MISMATCH %s: %zu of %zu bytes differ (first at %zu)\n", what, bad, a.size(), first); g_fail++; return false; } + return true; +} +// one launch; args points at the kernel parameters in declaration order +static void launch(CUfunction f, unsigned gx, unsigned gy, unsigned bx, unsigned shared, void** args) { + CU(cuLaunchKernel(f, gx, gy, 1, bx, 1, 1, shared, nullptr, args, nullptr)); +} + +// ---- combine: mtp_full_combine (grid (n/256, T), 256 threads, one thread a column) against leleka_verify_combine_k10_vec4 (grid (n/4/128, T), 128 threads) +static void test_combine(const std::string& dir) { + CUmodule mo = load_module(dir + "/mtp_original_full_combine.ptx"), mv = load_module(dir + "/sm120_combine_vec4.ptx"); + CUfunction fo = get_fn(mo, "mtp_full_combine"), fv = get_fn(mv, "leleka_verify_combine_k10_vec4"); + const int N = 2560, K = 10, MAXT = 8; + for (int seed = 0; seed < 4; ++seed) { + std::vector parts((size_t)MAXT * K * N), w((size_t)MAXT * K), shared((size_t)MAXT * N); + for (auto& v : parts) v = rndf() * (seed == 1 ? 1e6f : seed == 2 ? 1e-30f : 3.0f); + for (auto& v : w) v = rndf(); + for (auto& v : shared) v = rndf() * (seed == 1 ? 1e6f : 1.0f); + if (seed == 3) { // non-finite and signed-zero values: the same bytes must come out of both kernels + for (size_t i = 0; i < parts.size(); i += 97) parts[i] = (i % 3 == 0) ? INFINITY : (i % 3 == 1) ? NAN : -0.0f; + for (size_t i = 0; i < shared.size(); i += 131) shared[i] = -0.0f; + } + Dev dp, dw, ds, o_orig, o_vec; + dp.alloc(parts.size() * 4); dw.alloc(w.size() * 4); ds.alloc(shared.size() * 4); + o_orig.alloc(shared.size() * 4); o_vec.alloc(shared.size() * 4); + dp.put(parts.data(), parts.size() * 4); dw.put(w.data(), w.size() * 4); ds.put(shared.data(), shared.size() * 4); + for (int T = 1; T <= MAXT; ++T) { + CU(cuMemsetD8(o_orig.p, 0xCD, o_orig.n)); CU(cuMemsetD8(o_vec.p, 0xCD, o_vec.n)); + int64_t n = N, n4 = N / 4; int k = K; + void* ao[] = {&dp.p, &dw.p, &ds.p, &o_orig.p, &n, &k}; + void* av[] = {&dp.p, &dw.p, &ds.p, &o_vec.p, &n4}; + launch(fo, (N + 255) / 256, T, 256, 0, ao); + launch(fv, (unsigned)((n4 + 127) / 128), T, 128, 0, av); + const bool ok = same("combine", o_orig.get(0, (size_t)T * N * 4), o_vec.get(0, (size_t)T * N * 4)); + // rows past T are untouched (0xCD) by both + const bool tail = same("combine tail", o_orig.get((size_t)T * N * 4), o_vec.get((size_t)T * N * 4)); + printf("RESULT combine seed=%d T=%d identical=%d\n", seed, T, ok && tail); + } + } +} + +// ---- head mix: the five launches per token of plan_head_mix against one multi-token hc read (plan_head_mix_multi), chain kernels and the fused ones of the Original +static const int N = 2560, HC = 4, D = N * HC, LR = 320, MAXT = 8; +struct Fused { uint64_t a[14 * MAXT + 2]; }; // GrMulti: eight 14-word FusedGrArgs, then xn and T (912 bytes) +static void set_row(Fused& m, int t, CUdeviceptr R, CUdeviceptr norm, CUdeviceptr down, CUdeviceptr up, CUdeviceptr lo, CUdeviceptr rs, CUdeviceptr mixed) { + uint64_t* a = m.a + 14 * t; + a[0] = R; a[1] = R; a[2] = 0; // apply = false: the final write is its own launch + a[3] = 0; a[4] = 0; // bo_prev, inj_prev + a[5] = norm; a[6] = down; a[7] = up; a[8] = 0; // no inject projection + float eps = 1e-6f; uint32_t eb; memcpy(&eb, &eps, 4); a[9] = eb; + a[10] = lo; a[11] = rs; a[12] = 0; a[13] = mixed; +} +static void test_head(const std::string& dir) { + CUmodule mn = load_module(dir + "/mtp_original_full_gr_norm.ptx"), mp = load_module(dir + "/mtp_original_full_gr_post.ptx"); + CUmodule mb = load_module(dir + "/mtp_original_full_bf16.ptx"), mf = load_module(dir + "/mtp_original_full_fused_gr.ptx"); + CUmodule mc = load_module(dir + "/chain_window.ptx"); + CUfunction f_norm = get_fn(mn, "mtp_full_gr_norm"), f_silu = get_fn(mp, "mtp_full_down_silu"), f_pre = get_fn(mp, "mtp_full_pre_final"); + CUfunction f_mm256 = get_fn(mb, "mtp_full_mmvf256"), f_mm160 = get_fn(mb, "mtp_full_mmvf160"); + CUfunction f_csplit = get_fn(mc, "chain_gr_split"), f_cdown = get_fn(mc, "chain_gr_down_t2w8_nb4"), f_cup = get_fn(mc, "chain_gr_up8"); + CUfunction f_ssplit = get_fn(mf, "mtp_scalar_gr_split"), f_sdown = get_fn(mf, "mtp_scalar_gr_staged"), f_sup = get_fn(mf, "mtp_scalar_gr_up"); + CU(cuFuncSetAttribute(f_sdown, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, MAXT * 2 * 1280 * 4)); + for (int seed = 0; seed < 3; ++seed) { + std::vector R((size_t)MAXT * D), norm(D); + std::vector down((size_t)LR * D), up((size_t)D * LR); + for (auto& v : R) v = rndf() * (seed == 1 ? 40.0f : 2.0f); + for (auto& v : norm) v = 1.0f + 0.5f * rndf(); + for (auto& v : down) v = bf16_of(rndf() * 0.03f); + for (auto& v : up) v = bf16_of(rndf() * 0.08f); + Dev dR, dnorm, ddown, dup, xn_a, lo_a, gated_a, mixed_a, xn_b, lo_b, rs_b, mixed_b; + dR.alloc(R.size() * 4); dnorm.alloc(norm.size() * 4); ddown.alloc(down.size() * 2); dup.alloc(up.size() * 2); + for (Dev* d : {&xn_a, &xn_b}) d->alloc((size_t)MAXT * D * 4); + for (Dev* d : {&lo_a, &lo_b}) d->alloc((size_t)MAXT * LR * 4); + gated_a.alloc((size_t)MAXT * D * 4); rs_b.alloc((size_t)MAXT * HC * 4); + for (Dev* d : {&mixed_a, &mixed_b}) d->alloc((size_t)MAXT * N * 4); + dR.put(R.data(), R.size() * 4); dnorm.put(norm.data(), norm.size() * 4); ddown.put(down.data(), down.size() * 2); dup.put(up.data(), up.size() * 2); + for (int T = 1; T <= MAXT; ++T) { + // reference: five launches per token (plan_head_mix) + CU(cuMemsetD8(mixed_a.p, 0xCD, mixed_a.n)); + for (int t = 0; t < T; ++t) { + CUdeviceptr r = dR.p + (size_t)t * D * 4, xn = xn_a.p + (size_t)t * D * 4, lo = lo_a.p + (size_t)t * LR * 4; + CUdeviceptr gated = gated_a.p + (size_t)t * D * 4, mixed = mixed_a.p + (size_t)t * N * 4; + int n = N, hcn = HC, k_in = D, k_up = LR, lr = LR; float eps = 1e-6f, quarter = 0.25f; + void* a1[] = {&r, &dnorm.p, &xn, &n, &eps}; + launch(f_norm, HC, 1, 1024, 0, a1); + void* a2[] = {&xn, &ddown.p, &lo, &k_in}; + launch(f_mm256, LR, 1, 256, 0, a2); + void* a3[] = {&lo, &lr, &quarter}; + launch(f_silu, (LR + 255) / 256, 1, 256, 0, a3); + void* a4[] = {&lo, &dup.p, &gated, &k_up}; + launch(f_mm160, D, 1, 160, 0, a4); + void* a5[] = {&xn, &gated, &mixed, &n, &hcn, &quarter}; + launch(f_pre, (N + 255) / 256, 1, 256, 0, a5); + } + auto ref_mixed = mixed_a.get(0, (size_t)T * N * 4), ref_lo = lo_a.get(0, (size_t)T * LR * 4), ref_xn = xn_a.get(0, (size_t)T * D * 4); + for (int variant = 0; variant < 2; ++variant) { // 0: the chain kernels, 1: the fused ones of the Original + CU(cuMemsetD8(mixed_b.p, 0xCD, mixed_b.n)); CU(cuMemsetD8(lo_b.p, 0xCD, lo_b.n)); CU(cuMemsetD8(xn_b.p, 0xCD, xn_b.n)); + Fused m; memset(&m, 0, sizeof m); + for (int t = 0; t < T; ++t) + set_row(m, t, dR.p + (size_t)t * D * 4, dnorm.p, ddown.p, dup.p, lo_b.p + (size_t)t * LR * 4, rs_b.p + (size_t)t * HC * 4, mixed_b.p + (size_t)t * N * 4); + m.a[14 * MAXT] = xn_b.p; m.a[14 * MAXT + 1] = T; + void* args[] = {&m}; + const unsigned tiles = (unsigned)((T + 1) / 2), tok2 = T < 2 ? T : 2; + launch(variant == 0 ? f_csplit : f_ssplit, T, HC, 256, 0, args); + if (variant == 0) launch(f_cdown, 41, tiles, 256, 4 * tok2 * 1280 * 4, args); + else launch(f_sdown, 41, 1, 256, T * 2 * 1280 * 4, args); + launch(variant == 0 ? f_cup : f_sup, variant == 0 ? 320 : 160, 1, 256, 0, args); + const bool a = same("head mixed", ref_mixed, mixed_b.get(0, (size_t)T * N * 4)); + const bool b = same("head lo", ref_lo, lo_b.get(0, (size_t)T * LR * 4)); + const bool c = same("head xn", ref_xn, xn_b.get(0, (size_t)T * D * 4)); + const bool d = same("head tail", mixed_a.get((size_t)T * N * 4), mixed_b.get((size_t)T * N * 4)); + printf("RESULT head seed=%d T=%d variant=%s identical=%d\n", seed, T, variant == 0 ? "chain" : "fused", a && b && c && d); + } + } + } +} + +int main(int argc, char** argv) { + if (argc < 2) { fprintf(stderr, "usage: %s PTXDIR [combine|head ...]\n", argv[0]); return 2; } + CU(cuInit(0)); CUdevice dev; CU(cuDeviceGet(&dev, 0)); CUcontext ctx; CU(cuDevicePrimaryCtxRetain(&ctx, dev)); CU(cuCtxSetCurrent(ctx)); + bool all = argc == 2, combine = all, head = all; + for (int i = 2; i < argc; ++i) { combine |= !strcmp(argv[i], "combine"); head |= !strcmp(argv[i], "head"); } + if (combine) test_combine(argv[1]); + if (head) test_head(argv[1]); + printf("SUMMARY failures=%d\n", g_fail); + return g_fail ? 1 : 0; +} \ No newline at end of file