diff --git a/crates/cuda-driver/ptx-sm86/MANIFEST.json b/crates/cuda-driver/ptx-sm86/MANIFEST.json index 10d40ba7..1a7141ec 100644 --- a/crates/cuda-driver/ptx-sm86/MANIFEST.json +++ b/crates/cuda-driver/ptx-sm86/MANIFEST.json @@ -2763,6 +2763,13 @@ ] }, { + "name": "sm120_combine_hits.ptx", + "sm120_path": "crates/cuda-driver/src/sm120_combine_hits.ptx", + "problems": [ + "not built for sm_86 by design (claude/ffn-hits-combine): LELEKA_SM120_HITS_IN_COMBINE is an opt-in 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" + ] + }, + { "name": "sm120_gr_down_fused.ptx", "sm120_path": "crates/cuda-driver/src/sm120_gr_down_fused.ptx", "problems": [ diff --git a/crates/cuda-driver/src/original_verify_window_ops/all_window_assets.rs b/crates/cuda-driver/src/original_verify_window_ops/all_window_assets.rs index ec1c6793..a046ecc3 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/all_window_assets.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/all_window_assets.rs @@ -166,6 +166,7 @@ impl<'ctx> OriginalVerifyWindowResources<'ctx> { assets.extend(chain::assets()); // D1 DOWN_SUB16: a requested switch whose asset is unsealed refuses the recording assets.extend(down::assets(policy.ffn.down_sub16)); + assets.extend(hits_combine::assets(policy.ffn)); // D2 HITS_IN_COMBINE assets } /// Pre-capture work: load the sealed modules, read the card's fused-GR decisions, raise the dynamic diff --git a/crates/cuda-driver/src/original_verify_window_ops/hits_combine.rs b/crates/cuda-driver/src/original_verify_window_ops/hits_combine.rs index 1c282478..6d294081 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/hits_combine.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/hits_combine.rs @@ -1,15 +1,52 @@ //! D2 `LELEKA_SM120_HITS_IN_COMBINE`: `add_hits` folded into the combine kernel (upstream `combine_k10_vec4_hits`, //! `native_moe_combine_multi_hits_added`), one launch less per layer. //! -//! Scaffold only (claude/ffn-scaffold). With the switch on, `hit_add` records nothing and `combine` calls -//! `ffn_hits_combine` for every combine, batched or not, so the method must add the CPU hit rows in all cases. +//! With the switch on, `hit_add` records nothing and `combine` calls `ffn_hits_combine` for every combine, batched or +//! not. The method records ONE `leleka_verify_combine_k10_vec4_hits` launch over all rows of the group +//! (`plan_hits_combine.rs`): it adds the CPU hit rows listed in the plan (`part + hit`, as `add_hits_kernel` does) and +//! then computes the combine with the arithmetic of `sm120_combine_vec4`, which is the arithmetic of the scalar +//! `mtp_full_combine`. So the switch covers the plain combine and the `LELEKA_SM120_COMBINE_VEC4` combine alike, and +//! it needs no other switch. When the shape does not fit the vector kernel (k != 10, `n_embd % 4 != 0`, an unaligned +//! row, the legacy double-precision combine) the method records the two launches it replaces, `add_hits` then the +//! combine the planner would have chosen, so the hit rows are added in every case. +#[path = "hits_combine/plan_hits_combine.rs"] +mod plan_hits_combine; #[allow(unused_imports)] use super::*; +pub(crate) use plan_hits_combine::{E_COMBINE_HITS, HITS_COMBINE}; +use plan_hits_combine::{HitsCombineSite, plan_hits_combine}; + +/// The assets the window preloads before capture for the FFN switches: the folded combine when it is on. +pub(super) fn assets(ffn: ffn::FfnSwitches) -> Vec<&'static AssetSpec> { + if ffn.hits_in_combine { vec![&HITS_COMBINE] } else { Vec::new() } +} impl OriginalVerifyWindowOps<'_, '_, '_> { /// The combine of a layer with the CPU hit rows added inside it (replaces `hit_add` + `combine`). - pub(super) fn ffn_hits_combine(&mut self, _rows: Rows, _batched: bool) -> Result<()> { - Err(Error::UnsupportedQwenOperation) + pub(super) fn ffn_hits_combine(&mut self, rows: Rows, batched: bool) -> Result<()> { + match self.folded_combine(rows)? { + Some(launch) => self.launch(vec![launch]), + None => { + self.plan_launch(|p| p.hit_add(rows))?; + self.plan_launch(|p| p.combine(rows, batched)) + } + } + } + + /// The single folded launch of `rows`, or `None` when the shape needs the two scalar launches. + fn folded_combine(&self, rows: Rows) -> Result> { + let layout = self.plan(); + let site = HitsCombineSite { + rows, + native_combine: Planner::moe_knobs_of(&self.policy).native_combine, + hit_rows: self.plan_word(rows.group, layout.dst)?, + hit_count: self.plan_word(rows.group, layout.counts + 1)?, + }; + plan_hits_combine(self.journal(), &self.geometry(), site) } } + +#[cfg(test)] +#[path = "hits_combine/tests.rs"] +mod tests; diff --git a/crates/cuda-driver/src/original_verify_window_ops/hits_combine/plan_hits_combine.rs b/crates/cuda-driver/src/original_verify_window_ops/hits_combine/plan_hits_combine.rs new file mode 100644 index 00000000..36c886cd --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_ops/hits_combine/plan_hits_combine.rs @@ -0,0 +1,99 @@ +//! The sealed asset and the planner of D2 `LELEKA_SM120_HITS_IN_COMBINE` (`sm120_combine_hits.cu`). +//! +//! One launch replaces `moe_hit_add` (`add_hits_kernel`, 48 per graph) and the combine (`mtp_full_combine` or +//! `leleka_verify_combine_k10_vec4`) of a layer. It is planned for ALL rows of the group in one launch whether the +//! recorder calls the combine batched or per row: every token is an independent block row (`grid.y`), the hit list is +//! relative to the group's first row exactly as in `plan_hit_add` (whose launch takes `parts` and `hit_out` at the +//! group's first row), and the arithmetic per element does not depend on the grouping. +use crate::original_verify::OriginalVerifyGeometry; +use crate::original_verify::kernels::{A, ArenaMap, AssetSpec, Launch, LaunchExtent}; +use crate::original_verify::window_record::Rows; +use crate::{Error, Result}; + +pub(crate) const E_COMBINE_HITS: &str = "leleka_verify_combine_k10_vec4_hits"; +/// The routed experts per token the 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_hits.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 HITS_COMBINE: AssetSpec = AssetSpec { + name: "sm120_combine_hits.ptx", + ptx: concat!(include_str!("../../sm120_combine_hits.ptx"), "\0").as_bytes(), + sha: [ + 167, 221, 5, 153, 20, 187, 51, 255, 103, 227, 166, 6, 169, 179, 141, 180, 228, 225, 133, 121, 209, 86, 86, 50, + 6, 143, 132, 170, 183, 52, 112, 247, + ], + entries: &[E_COMBINE_HITS], + unsealed: "Original verifier asset unsealed: sm120_combine_hits.ptx (HITS_IN_COMBINE folded combine)", +}; + +/// What the folded combine needs from the window: the rows, whether the Original's native combine is the one being +/// replaced (`MoeKnobs::native_combine`; the legacy combine is double precision), and the addresses of the group's hit +/// list (`PlanLayout::dst`) and hit count (`PlanLayout::counts + 1`) words. +#[derive(Clone, Copy, Debug)] +pub(crate) struct HitsCombineSite { + pub rows: Rows, + pub native_combine: bool, + pub hit_rows: u64, + pub hit_count: u64, +} + +/// The device addresses of the five spans of the rows the kernel reads and writes. +struct Spans { + parts: u64, + hits: u64, + weights: u64, + shared: u64, + out: u64, +} +impl Spans { + /// The spans of `rows` (a contiguous run of tokens from `rows.begin`). + fn of(arena: &(impl ArenaMap + ?Sized), g: &OriginalVerifyGeometry, rows: Rows) -> Result { + let (n, k, tokens) = (g.n, g.k, rows.len()); + let floats = |name: &str, per: usize| arena.span(name, rows.begin * per * 4, tokens * per * 4); + Ok(Self { + parts: floats("parts", k * n)?, + hits: floats("hit_out", k * n)?, + weights: floats("w", k)?, + shared: floats("shared", n)?, + out: floats("bo", n)?, + }) + } + /// The float4 loads and the store need 16-byte aligned parts, hit, shared and output rows. + fn vector_aligned(&self) -> bool { + [self.parts, self.hits, self.shared, self.out].iter().all(|a| a % VECTOR_ALIGN == 0) + } + /// The kernel arguments in declaration order. + fn args(&self, site: HitsCombineSite, n4: usize) -> Vec { + let (hit_rows, hit_count) = (site.hit_rows, site.hit_count); + let spans = [self.parts, self.hits, hit_rows, hit_count, self.weights, self.shared, self.out]; + spans.into_iter().map(A::P).chain([A::I64(n4 as i64)]).collect() + } +} + +/// The launch of `leleka_verify_combine_k10_vec4_hits` over `site.rows`; `None` when the shape or an address does not +/// fit the kernel and the caller keeps `add_hits` + the scalar combine, which compute the same words. +pub(crate) fn plan_hits_combine( + arena: &(impl ArenaMap + ?Sized), + g: &OriginalVerifyGeometry, + site: HitsCombineSite, +) -> Result> { + let rows = site.rows; + if rows.begin >= rows.end || rows.end > g.max_t || rows.group > 1 { + return Err(Error::InvalidQwenShape); + } + if !site.native_combine || g.k != ROUTED_EXPERTS || g.n % 4 != 0 { + return Ok(None); + } + let spans = Spans::of(arena, g, rows)?; + if !spans.vector_aligned() { + return Ok(None); + } + let n4 = g.n / 4; + let grid = [n4.div_ceil(QUARTETS_PER_BLOCK) as u32, rows.len() as u32, 1]; + let extent = LaunchExtent::new(grid, [QUARTETS_PER_BLOCK as u32, 1, 1], 0); + Launch::new(&HITS_COMBINE, E_COMBINE_HITS, extent, spans.args(site, n4)).map(Some) +} diff --git a/crates/cuda-driver/src/original_verify_window_ops/hits_combine/tests.rs b/crates/cuda-driver/src/original_verify_window_ops/hits_combine/tests.rs new file mode 100644 index 00000000..f8a906c1 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_ops/hits_combine/tests.rs @@ -0,0 +1,234 @@ +//! Unit tests of `hits_combine.rs` and `plan_hits_combine.rs`: the asset is sealed and only loaded with the switch, the +//! PTX has the arithmetic shape of the two launches it replaces, the planned launch binds the Original cells, and a +//! host model of the kernel gives the bytes of `add_hits` followed by the combine (the GPU comparison is +//! `tools/decode-sm120/sm120_probe_hits.cpp`). + +use super::*; +use crate::original_verify::kernels::{ArenaMap, LayoutMap, test_geometry}; +use crate::original_verify::moe; + +const BASE: u64 = 0x7000_0000_0000; +const HIT_ROWS: u64 = 0x1000; +const HIT_COUNT: u64 = 0x2000; + +fn arena() -> LayoutMap { + LayoutMap::new(BASE, test_geometry()) +} +fn site(begin: usize, end: usize) -> HitsCombineSite { + HitsCombineSite { + rows: Rows { begin, end, group: 0 }, + native_combine: true, + hit_rows: HIT_ROWS, + hit_count: HIT_COUNT, + } +} +fn at(m: &LayoutMap, name: &str, offset: usize) -> u64 { + BASE + (m.layout.span(name).unwrap().offset + offset) as u64 +} +fn plan(m: &impl ArenaMap, site: HitsCombineSite) -> Option { + plan_hits_combine(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 the_asset_is_loaded_only_with_the_switch() { + assert!(assets(ffn::FfnSwitches::NONE).is_empty()); + let others = ffn::FfnSwitches { down_sub16: true, hits_in_combine: false, wait_m_rows: true }; + assert!(assets(others).is_empty()); + let on = assets(ffn::FfnSwitches { hits_in_combine: true, ..ffn::FfnSwitches::NONE }); + assert_eq!(on.len(), 1); + assert!(std::ptr::eq(on[0], &HITS_COMBINE)); +} + +#[test] +fn the_folded_combine_asset_is_sealed_and_exports_its_entry() { + HITS_COMBINE.assert_sealed_and_fail_closed(); + assert_eq!(HITS_COMBINE.entries, [E_COMBINE_HITS]); +} + +/// `add_hits_kernel` is one rounded `add.f32` of `part + hit` (no fused multiply-add, no flush to zero); the folded +/// kernel adds the hit rows with `add.f32` in front of the multiply-add chain of `leleka_verify_combine_k10_vec4`. +#[test] +fn the_folded_kernel_has_the_arithmetic_shape_of_the_two_launches_it_replaces() { + let s2 = std::str::from_utf8(moe::S2_HITS.ptx).unwrap(); + let add_hits = entry_text(s2, moe::S2_HITS.entries[0]); + assert_eq!((count(add_hits, "add.f32"), count(add_hits, "fma.rn.f32"), count(add_hits, "mul.f32")), (1, 0, 0)); + assert!(!add_hits.contains(".ftz") && !add_hits.contains("approx")); + let text = std::str::from_utf8(HITS_COMBINE.ptx).unwrap(); + let folded = entry_text(text, E_COMBINE_HITS); + // four columns: four rounded first products, 9 x 4 fused multiply-adds, 10 x 4 hit adds, four shared adds + assert_eq!((count(folded, "mul.f32"), count(folded, "fma.rn.f32"), count(folded, "add.f32")), (4, 36, 44)); + assert!(!folded.contains(".ftz") && !folded.contains("approx") && !folded.contains("div.")); + // the hit mask: an atomic or in shared memory between two barriers; float4 loads of ten parts rows, ten hit + // rows and the shared row, one float4 store of the output + assert_eq!((count(folded, "atom.shared.or.b32"), count(folded, "bar.sync")), (1, 2)); + assert_eq!(folded.matches("ld.global.nc.v4.b32").count(), 21); + assert_eq!(folded.matches("st.global.v4.b32").count(), 1); +} + +#[test] +fn a_group_is_one_launch_with_the_token_on_grid_y() { + let m = arena(); + let l = plan(&m, site(0, 4)).unwrap(); + assert_eq!((l.entry, l.grid, l.block, l.shared), (E_COMBINE_HITS, [5, 4, 1], [128, 1, 1], 0)); + let (parts, hits) = (at(&m, "parts", 0), at(&m, "hit_out", 0)); + let (w, shared, bo) = (at(&m, "w", 0), at(&m, "shared", 0), at(&m, "bo", 0)); + let args = + vec![A::P(parts), A::P(hits), A::P(HIT_ROWS), A::P(HIT_COUNT), A::P(w), A::P(shared), A::P(bo), A::I64(640)]; + assert_eq!(l.args, args); + assert_eq!(plan(&m, site(0, 1)).unwrap().grid, [5, 1, 1], "a single row is one launch of one token"); +} + +#[test] +fn a_group_that_starts_late_binds_its_own_rows() { + let m = arena(); + let l = plan(&m, site(2, 5)).unwrap(); + assert_eq!(l.grid, [5, 3, 1]); + let row = 2 * 10 * 2560 * 4; + let args = vec![ + A::P(at(&m, "parts", row)), + A::P(at(&m, "hit_out", row)), + A::P(HIT_ROWS), + A::P(HIT_COUNT), + 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 what_does_not_fit_the_vector_kernel_keeps_add_hits_and_the_scalar_combine() { + let m = arena(); + let not_native = HitsCombineSite { native_combine: false, ..site(0, 4) }; + 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_hits_combine(&m, &eight, site(0, 4)).unwrap().is_none()); + let mut odd = test_geometry(); + odd.n = 2562; + assert!(plan_hits_combine(&m, &odd, site(0, 1)).unwrap().is_none()); + assert!(plan(&Skewed(&m, 4), site(0, 4)).is_none()); + assert!(plan(&Skewed(&m, 16), site(0, 4)).is_some()); +} + +#[test] +fn the_row_ranges_the_scalar_planners_refuse_are_refused() { + let m = arena(); + let wrong_group = HitsCombineSite { rows: Rows { begin: 0, end: 2, group: 2 }, ..site(0, 2) }; + for bad in [site(2, 2), site(0, 9), site(4, 3), wrong_group] { + assert_eq!(plan_hits_combine(&m, &test_geometry(), bad).unwrap_err(), Error::InvalidQwenShape); + } +} +// ---- a host model of the kernel: the bytes of `add_hits` followed by the combine, element by element + +const COLUMNS: usize = 4; +const EXPERTS: usize = 10; +type Rows10 = [[f32; COLUMNS]; EXPERTS]; + +/// `add_hits_kernel`: `parts[row] += hit_out[row]` in place for every listed row. +fn add_hits_in_place(parts: &mut Rows10, hit_out: &Rows10, list: &[i32]) { + for &row in list { + for c in 0..COLUMNS { + parts[row as usize][c] += hit_out[row as usize][c]; + } + } +} + +/// The kernel's reading of the parts of token 0: a mask of the listed experts, `part + hit` for those in registers, +/// the part itself for every other expert, nothing written back. +fn parts_with_hits(parts: &Rows10, hit_out: &Rows10, list: &[i32]) -> Rows10 { + let mask = list.iter().filter(|&&r| r >= 0 && r / 10 == 0).fold(0u32, |m, &r| m | 1 << (r % 10)); + let mut seen = *parts; + for e in (0..EXPERTS).filter(|e| (mask >> e) & 1 == 1) { + for c in 0..COLUMNS { + seen[e][c] = parts[e][c] + hit_out[e][c]; + } + } + seen +} + +/// The combine of one token: the first product rounded, nine fused multiply-adds in expert order, the shared add. +fn combine(parts: &Rows10, w: &[f32], shared: f32) -> Vec { + (0..COLUMNS) + .map(|c| { + let sum = (1..EXPERTS).fold(parts[0][c] * w[0], |sum, e| parts[e][c].mul_add(w[e], sum)); + sum + shared + }) + .collect() +} + +fn same_bits(a: f32, b: f32) -> bool { + a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan()) +} + +/// The same pseudo-random sequence of awkward values on every run. +struct Picker(u32); +impl Picker { + const VALUES: [f32; 9] = [0.0, -0.0, 1e-40, -1e-40, 1.5, -2.25, 3e30, f32::INFINITY, -7.0e-3]; + fn next(&mut self) -> f32 { + self.0 = self.0.wrapping_mul(1664525).wrapping_add(1013904223); + Self::VALUES[(self.0 >> 16) as usize % Self::VALUES.len()] + } + fn rows(&mut self) -> Rows10 { + let mut rows = [[0.0f32; COLUMNS]; EXPERTS]; + rows.iter_mut().flatten().for_each(|v| *v = self.next()); + rows + } +} + +#[test] +fn the_model_of_the_kernel_gives_the_bytes_of_add_hits_and_the_combine() { + let mut picker = Picker(12345); + for case in 0..200 { + let (mut parts, hits) = (picker.rows(), picker.rows()); + let list: Vec = (0..EXPERTS as i32).filter(|e| (case + e) % 3 == 0).collect(); + if case % 2 == 0 { + // the CPU leg zeroes the listed rows (+0.0) before the hit is added + list.iter().for_each(|&r| parts[r as usize] = [0.0; COLUMNS]); + } + let folded = parts_with_hits(&parts, &hits, &list); + let mut old = parts; + add_hits_in_place(&mut old, &hits, &list); + for (a, b) in old.iter().flatten().zip(folded.iter().flatten()) { + assert!(same_bits(*a, *b), "case {case}: part {a:e} vs {b:e}"); + } + let w: Vec = (0..EXPERTS).map(|_| picker.next()).collect(); + let shared = picker.next(); + for (a, b) in combine(&old, &w, shared).iter().zip(combine(&folded, &w, shared)) { + assert!(same_bits(*a, b), "case {case}: combine {a:e} vs {b:e}"); + } + } +} + +#[test] +fn signed_zeros_follow_the_add_of_add_hits_and_an_unlisted_row_is_not_touched() { + let (mut parts, mut hits) = ([[0.0f32; COLUMNS]; EXPERTS], [[0.0f32; COLUMNS]; EXPERTS]); + hits[3] = [-0.0; COLUMNS]; // listed, zeroed part: +0.0 + -0.0 = +0.0 + parts[5] = [-0.0; COLUMNS]; + hits[5] = [-0.0; COLUMNS]; // listed, part -0.0: -0.0 + -0.0 = -0.0 + parts[7] = [-0.0; COLUMNS]; // not listed: adding +0.0 would turn it into +0.0, so it stays -0.0 + let seen = parts_with_hits(&parts, &hits, &[3, 5]); + assert_eq!(seen[3].map(f32::to_bits), [0.0f32.to_bits(); COLUMNS]); + assert_eq!(seen[5].map(f32::to_bits), [(-0.0f32).to_bits(); COLUMNS]); + assert_eq!(seen[7].map(f32::to_bits), [(-0.0f32).to_bits(); COLUMNS]); + // a hit list entry of another token or a negative entry marks nothing of token 0 + assert_eq!(parts_with_hits(&parts, &hits, &[13, -1]), parts); +} diff --git a/crates/cuda-driver/src/sm120_combine_hits.cu b/crates/cuda-driver/src/sm120_combine_hits.cu new file mode 100644 index 00000000..21f44695 --- /dev/null +++ b/crates/cuda-driver/src/sm120_combine_hits.cu @@ -0,0 +1,87 @@ +// verify window, routed-expert combine with the hit rows added inside it (docs/experiments/ffn-phase-loss-design.md, +// D2): LELEKA_SM120_HITS_IN_COMBINE. +// +// Upstream's `combine_k10_vec4_hits` (native_moe.cu, `native_moe_combine_multi_hits_added`) as an sm_120 entry of its +// own, on top of `leleka_verify_combine_k10_vec4` (sm120_combine_vec4.cu). The window launches, per layer, +// moe_hit_add: parts[row] += hit_out[row] for the rows h < count listed in dst (add_hits_kernel) +// combine: output = ((p0 * w0) fma p1 w1 ... fma p9 w9) + shared (mtp_full_combine or the vec4 entry) +// and this kernel is the two in one launch. `parts` is NOT written back: the combine is its only reader, and +// `add_hits` is the only writer of those rows after the CPU leg zeroed them. +// +// Same value of every output element, element by element: +// * the hit row is added as `part + hit` (add_hits_kernel: `parts[row + i] += hit_out[row + i]`, one `add.f32` in +// the sealed mtp_original_full_s2.ptx), in the same order relative to the multiply-add chain (before the part is +// used as a multiplicand), so a zeroed part (+0.0) plus a hit of -0.0 gives +0.0 here exactly as there. The add is +// done for a row that is in the hit list and never for another row (a row outside the list keeps its part +// unchanged: adding +0.0 would turn a part of -0.0 into +0.0); +// * the rest is leleka_verify_combine_k10_vec4: the first product rounded, nine explicit `fmaf` in expert order, one +// add of the shared row. It equals the scalar `mtp_full_combine` per element (COMBINE_VEC4's argument), so this +// kernel replaces the combine whether or not LELEKA_SM120_COMBINE_VEC4 is on. +// +// One block computes the hit mask of its token (bit e = expert slot e of the token is in the hit list): every thread +// scans a share of the list, `atomicOr` into shared memory. The list holds the window's (token * 10 + expert) rows +// RELATIVE to the first row of the launch, as in add_hits_kernel (which is launched with the group's first row as the +// base of `parts` and `hit_out`). +// +// Compile: nvcc --ptx -O3 -arch=sm_120 -std=c++17 --fmad=true --ftz=false (the recipe of original_verify.cu). +// Preconditions (checked by the host planner, which keeps the add_hits + combine launches otherwise): k = 10, +// n_embd % 4 == 0, the parts, hit, shared and output rows 16-byte aligned, a hit list without duplicate rows (as +// moe_hit_select builds it; the old kernel would add a duplicated row twice, this one once). +#include +#include + +extern "C" __global__ void __launch_bounds__(128) leleka_verify_combine_k10_vec4_hits( + const float4* __restrict__ parts4, const float4* __restrict__ hits4, const int32_t* __restrict__ dst, + const int32_t* __restrict__ count, const float* __restrict__ weights, const float4* __restrict__ shared4, + float4* __restrict__ output4, int64_t n4) { + const int64_t tk = blockIdx.y; // the token of the launch + __shared__ int hit_mask; + if (threadIdx.x == 0) hit_mask = 0; + __syncthreads(); + const int hits = *count; + for (int h = threadIdx.x; h < hits; h += blockDim.x) { + const int row = dst[h]; + if (row >= 0 && row / 10 == (int) tk) atomicOr(&hit_mask, 1 << (row % 10)); + } + __syncthreads(); + const int mask = hit_mask; + parts4 += tk * 10 * n4; + hits4 += 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]; + float4 p0 = parts4[c4]; + if (mask & 1) { + const float4 hit = hits4[c4]; + p0.x += hit.x; + p0.y += hit.y; + p0.z += hit.z; + p0.w += hit.w; + } + 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]; + float4 p = parts4[int64_t(expert) * n4 + c4]; + if ((mask >> expert) & 1) { + const float4 hit = hits4[int64_t(expert) * n4 + c4]; + p.x += hit.x; + p.y += hit.y; + p.z += hit.z; + p.w += hit.w; + } + 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_hits.ptx b/crates/cuda-driver/src/sm120_combine_hits.ptx new file mode 100644 index 00000000..a18753d9 --- /dev/null +++ b/crates/cuda-driver/src/sm120_combine_hits.ptx @@ -0,0 +1,304 @@ +// +// 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_hits +// _ZZ35leleka_verify_combine_k10_vec4_hitsE8hit_mask has been demoted + +.visible .entry leleka_verify_combine_k10_vec4_hits( + .param .u64 .ptr .align 1 leleka_verify_combine_k10_vec4_hits_param_0, + .param .u64 .ptr .align 1 leleka_verify_combine_k10_vec4_hits_param_1, + .param .u64 .ptr .align 1 leleka_verify_combine_k10_vec4_hits_param_2, + .param .u64 .ptr .align 1 leleka_verify_combine_k10_vec4_hits_param_3, + .param .u64 .ptr .align 1 leleka_verify_combine_k10_vec4_hits_param_4, + .param .u64 .ptr .align 1 leleka_verify_combine_k10_vec4_hits_param_5, + .param .u64 .ptr .align 1 leleka_verify_combine_k10_vec4_hits_param_6, + .param .u64 leleka_verify_combine_k10_vec4_hits_param_7 +) +.maxntid 128 +{ + .reg .pred %p<19>; + .reg .b32 %r<170>; + .reg .b64 %rd<71>; + // demoted variable + .shared .align 4 .u32 _ZZ35leleka_verify_combine_k10_vec4_hitsE8hit_mask; + ld.param.b64 %rd26, [leleka_verify_combine_k10_vec4_hits_param_0]; + ld.param.b64 %rd27, [leleka_verify_combine_k10_vec4_hits_param_1]; + ld.param.b64 %rd28, [leleka_verify_combine_k10_vec4_hits_param_2]; + ld.param.b64 %rd29, [leleka_verify_combine_k10_vec4_hits_param_3]; + ld.param.b64 %rd30, [leleka_verify_combine_k10_vec4_hits_param_4]; + ld.param.b64 %rd31, [leleka_verify_combine_k10_vec4_hits_param_5]; + ld.param.b64 %rd32, [leleka_verify_combine_k10_vec4_hits_param_6]; + ld.param.b64 %rd33, [leleka_verify_combine_k10_vec4_hits_param_7]; + mov.u32 %r39, %ctaid.y; + cvt.u64.u32 %rd1, %r39; + mov.u32 %r1, %tid.x; + setp.ne.b32 %p1, %r1, 0; + @%p1 bra $L__BB0_2; + st.shared.b32 [_ZZ35leleka_verify_combine_k10_vec4_hitsE8hit_mask], 0; +$L__BB0_2: + bar.sync 0; + cvta.to.global.u64 %rd34, %rd29; + ld.global.nc.b32 %r2, [%rd34]; + setp.ge.s32 %p2, %r1, %r2; + @%p2 bra $L__BB0_7; + mov.u32 %r3, %ntid.x; + cvta.to.global.u64 %rd2, %rd28; + cvt.u32.u64 %r40, %rd1; + mov.b32 %r129, %r1; +$L__BB0_4: + mul.wide.s32 %rd35, %r129, 4; + add.s64 %rd36, %rd2, %rd35; + ld.global.nc.b32 %r4, [%rd36]; + setp.lt.s32 %p3, %r4, 0; + mul.hi.s32 %r41, %r4, 1717986919; + shr.u32 %r42, %r41, 31; + shr.s32 %r43, %r41, 2; + add.s32 %r44, %r43, %r42; + setp.ne.b32 %p4, %r44, %r40; + or.pred %p5, %p3, %p4; + @%p5 bra $L__BB0_6; + mul.hi.u32 %r45, %r4, -858993459; + shr.u32 %r46, %r45, 3; + mul.lo.s32 %r47, %r46, 10; + sub.s32 %r48, %r4, %r47; + mov.b32 %r49, 1; + shl.b32 %r50, %r49, %r48; + atom.shared.or.b32 %r51, [_ZZ35leleka_verify_combine_k10_vec4_hitsE8hit_mask], %r50; +$L__BB0_6: + add.s32 %r129, %r129, %r3; + setp.lt.s32 %p6, %r129, %r2; + @%p6 bra $L__BB0_4; +$L__BB0_7: + bar.sync 0; + ld.shared.b32 %r5, [_ZZ35leleka_verify_combine_k10_vec4_hitsE8hit_mask]; + mul.lo.s64 %rd37, %rd1, %rd33; + cvta.to.global.u64 %rd38, %rd26; + mul.lo.s64 %rd39, %rd37, 160; + add.s64 %rd3, %rd38, %rd39; + cvta.to.global.u64 %rd40, %rd27; + add.s64 %rd4, %rd40, %rd39; + cvta.to.global.u64 %rd41, %rd30; + mad.lo.s64 %rd5, %rd1, 40, %rd41; + mov.u32 %r52, %ctaid.x; + mov.u32 %r53, %ntid.x; + mul.wide.u32 %rd42, %r52, %r53; + cvt.u64.u32 %rd43, %r1; + add.s64 %rd6, %rd42, %rd43; + setp.ge.s64 %p7, %rd6, %rd33; + @%p7 bra $L__BB0_29; + shl.b64 %rd44, %rd6, 4; + add.s64 %rd7, %rd3, %rd44; + ld.global.nc.v4.b32 {%r130, %r131, %r132, %r133}, [%rd7]; + and.b32 %r54, %r5, 1; + setp.ne.b32 %p8, %r54, 0; + not.pred %p9, %p8; + @%p9 bra $L__BB0_10; + add.s64 %rd45, %rd4, %rd44; + ld.global.nc.v4.b32 {%r55, %r56, %r57, %r58}, [%rd45]; + add.f32 %r130, %r130, %r55; + add.f32 %r131, %r131, %r56; + add.f32 %r132, %r132, %r57; + add.f32 %r133, %r133, %r58; +$L__BB0_10: + add.s64 %rd8, %rd33, %rd6; + shl.b64 %rd9, %rd33, 4; + add.s64 %rd10, %rd7, %rd9; + ld.global.nc.v4.b32 {%r137, %r136, %r135, %r134}, [%rd10]; + and.b32 %r59, %r5, 2; + setp.eq.b32 %p10, %r59, 0; + @%p10 bra $L__BB0_12; + shl.b64 %rd46, %rd8, 4; + add.s64 %rd47, %rd4, %rd46; + ld.global.nc.v4.b32 {%r60, %r61, %r62, %r63}, [%rd47]; + add.f32 %r137, %r137, %r60; + add.f32 %r136, %r136, %r61; + add.f32 %r135, %r135, %r62; + add.f32 %r134, %r134, %r63; +$L__BB0_12: + ld.global.nc.b32 %r64, [%rd5]; + ld.global.nc.b32 %r65, [%rd5+4]; + mul.f32 %r66, %r64, %r130; + fma.rn.f32 %r6, %r137, %r65, %r66; + mul.f32 %r67, %r64, %r131; + fma.rn.f32 %r7, %r136, %r65, %r67; + mul.f32 %r68, %r64, %r132; + fma.rn.f32 %r8, %r135, %r65, %r68; + mul.f32 %r69, %r64, %r133; + fma.rn.f32 %r9, %r134, %r65, %r69; + add.s64 %rd11, %rd8, %rd33; + add.s64 %rd12, %rd10, %rd9; + ld.global.nc.v4.b32 {%r141, %r140, %r139, %r138}, [%rd12]; + and.b32 %r70, %r5, 4; + setp.eq.b32 %p11, %r70, 0; + @%p11 bra $L__BB0_14; + shl.b64 %rd48, %rd11, 4; + add.s64 %rd49, %rd4, %rd48; + ld.global.nc.v4.b32 {%r71, %r72, %r73, %r74}, [%rd49]; + add.f32 %r141, %r141, %r71; + add.f32 %r140, %r140, %r72; + add.f32 %r139, %r139, %r73; + add.f32 %r138, %r138, %r74; +$L__BB0_14: + ld.global.nc.b32 %r75, [%rd5+8]; + fma.rn.f32 %r10, %r141, %r75, %r6; + fma.rn.f32 %r11, %r140, %r75, %r7; + fma.rn.f32 %r12, %r139, %r75, %r8; + fma.rn.f32 %r13, %r138, %r75, %r9; + add.s64 %rd13, %rd11, %rd33; + add.s64 %rd14, %rd12, %rd9; + ld.global.nc.v4.b32 {%r145, %r144, %r143, %r142}, [%rd14]; + and.b32 %r76, %r5, 8; + setp.eq.b32 %p12, %r76, 0; + @%p12 bra $L__BB0_16; + shl.b64 %rd50, %rd13, 4; + add.s64 %rd51, %rd4, %rd50; + ld.global.nc.v4.b32 {%r77, %r78, %r79, %r80}, [%rd51]; + add.f32 %r145, %r145, %r77; + add.f32 %r144, %r144, %r78; + add.f32 %r143, %r143, %r79; + add.f32 %r142, %r142, %r80; +$L__BB0_16: + ld.global.nc.b32 %r81, [%rd5+12]; + fma.rn.f32 %r14, %r145, %r81, %r10; + fma.rn.f32 %r15, %r144, %r81, %r11; + fma.rn.f32 %r16, %r143, %r81, %r12; + fma.rn.f32 %r17, %r142, %r81, %r13; + add.s64 %rd15, %rd13, %rd33; + add.s64 %rd16, %rd14, %rd9; + ld.global.nc.v4.b32 {%r149, %r148, %r147, %r146}, [%rd16]; + and.b32 %r82, %r5, 16; + setp.eq.b32 %p13, %r82, 0; + @%p13 bra $L__BB0_18; + shl.b64 %rd52, %rd15, 4; + add.s64 %rd53, %rd4, %rd52; + ld.global.nc.v4.b32 {%r83, %r84, %r85, %r86}, [%rd53]; + add.f32 %r149, %r149, %r83; + add.f32 %r148, %r148, %r84; + add.f32 %r147, %r147, %r85; + add.f32 %r146, %r146, %r86; +$L__BB0_18: + ld.global.nc.b32 %r87, [%rd5+16]; + fma.rn.f32 %r18, %r149, %r87, %r14; + fma.rn.f32 %r19, %r148, %r87, %r15; + fma.rn.f32 %r20, %r147, %r87, %r16; + fma.rn.f32 %r21, %r146, %r87, %r17; + add.s64 %rd17, %rd15, %rd33; + add.s64 %rd18, %rd16, %rd9; + ld.global.nc.v4.b32 {%r153, %r152, %r151, %r150}, [%rd18]; + and.b32 %r88, %r5, 32; + setp.eq.b32 %p14, %r88, 0; + @%p14 bra $L__BB0_20; + shl.b64 %rd54, %rd17, 4; + add.s64 %rd55, %rd4, %rd54; + ld.global.nc.v4.b32 {%r89, %r90, %r91, %r92}, [%rd55]; + add.f32 %r153, %r153, %r89; + add.f32 %r152, %r152, %r90; + add.f32 %r151, %r151, %r91; + add.f32 %r150, %r150, %r92; +$L__BB0_20: + ld.global.nc.b32 %r93, [%rd5+20]; + fma.rn.f32 %r22, %r153, %r93, %r18; + fma.rn.f32 %r23, %r152, %r93, %r19; + fma.rn.f32 %r24, %r151, %r93, %r20; + fma.rn.f32 %r25, %r150, %r93, %r21; + add.s64 %rd19, %rd17, %rd33; + add.s64 %rd20, %rd18, %rd9; + ld.global.nc.v4.b32 {%r157, %r156, %r155, %r154}, [%rd20]; + and.b32 %r94, %r5, 64; + setp.eq.b32 %p15, %r94, 0; + @%p15 bra $L__BB0_22; + shl.b64 %rd56, %rd19, 4; + add.s64 %rd57, %rd4, %rd56; + ld.global.nc.v4.b32 {%r95, %r96, %r97, %r98}, [%rd57]; + add.f32 %r157, %r157, %r95; + add.f32 %r156, %r156, %r96; + add.f32 %r155, %r155, %r97; + add.f32 %r154, %r154, %r98; +$L__BB0_22: + ld.global.nc.b32 %r99, [%rd5+24]; + fma.rn.f32 %r26, %r157, %r99, %r22; + fma.rn.f32 %r27, %r156, %r99, %r23; + fma.rn.f32 %r28, %r155, %r99, %r24; + fma.rn.f32 %r29, %r154, %r99, %r25; + add.s64 %rd21, %rd19, %rd33; + add.s64 %rd22, %rd20, %rd9; + ld.global.nc.v4.b32 {%r161, %r160, %r159, %r158}, [%rd22]; + and.b32 %r100, %r5, 128; + setp.eq.b32 %p16, %r100, 0; + @%p16 bra $L__BB0_24; + shl.b64 %rd58, %rd21, 4; + add.s64 %rd59, %rd4, %rd58; + ld.global.nc.v4.b32 {%r101, %r102, %r103, %r104}, [%rd59]; + add.f32 %r161, %r161, %r101; + add.f32 %r160, %r160, %r102; + add.f32 %r159, %r159, %r103; + add.f32 %r158, %r158, %r104; +$L__BB0_24: + ld.global.nc.b32 %r105, [%rd5+28]; + fma.rn.f32 %r30, %r161, %r105, %r26; + fma.rn.f32 %r31, %r160, %r105, %r27; + fma.rn.f32 %r32, %r159, %r105, %r28; + fma.rn.f32 %r33, %r158, %r105, %r29; + add.s64 %rd23, %rd21, %rd33; + add.s64 %rd24, %rd22, %rd9; + ld.global.nc.v4.b32 {%r165, %r164, %r163, %r162}, [%rd24]; + and.b32 %r106, %r5, 256; + setp.eq.b32 %p17, %r106, 0; + @%p17 bra $L__BB0_26; + shl.b64 %rd60, %rd23, 4; + add.s64 %rd61, %rd4, %rd60; + ld.global.nc.v4.b32 {%r107, %r108, %r109, %r110}, [%rd61]; + add.f32 %r165, %r165, %r107; + add.f32 %r164, %r164, %r108; + add.f32 %r163, %r163, %r109; + add.f32 %r162, %r162, %r110; +$L__BB0_26: + ld.global.nc.b32 %r111, [%rd5+32]; + fma.rn.f32 %r34, %r165, %r111, %r30; + fma.rn.f32 %r35, %r164, %r111, %r31; + fma.rn.f32 %r36, %r163, %r111, %r32; + fma.rn.f32 %r37, %r162, %r111, %r33; + ld.global.nc.b32 %r38, [%rd5+36]; + add.s64 %rd25, %rd23, %rd33; + add.s64 %rd62, %rd24, %rd9; + ld.global.nc.v4.b32 {%r169, %r168, %r167, %r166}, [%rd62]; + and.b32 %r112, %r5, 512; + setp.eq.b32 %p18, %r112, 0; + @%p18 bra $L__BB0_28; + shl.b64 %rd63, %rd25, 4; + add.s64 %rd64, %rd4, %rd63; + ld.global.nc.v4.b32 {%r113, %r114, %r115, %r116}, [%rd64]; + add.f32 %r169, %r169, %r113; + add.f32 %r168, %r168, %r114; + add.f32 %r167, %r167, %r115; + add.f32 %r166, %r166, %r116; +$L__BB0_28: + fma.rn.f32 %r117, %r169, %r38, %r34; + fma.rn.f32 %r118, %r168, %r38, %r35; + fma.rn.f32 %r119, %r167, %r38, %r36; + fma.rn.f32 %r120, %r166, %r38, %r37; + mad.lo.s64 %rd65, %rd33, %rd1, %rd6; + cvta.to.global.u64 %rd66, %rd31; + shl.b64 %rd67, %rd65, 4; + add.s64 %rd68, %rd66, %rd67; + ld.global.nc.v4.b32 {%r121, %r122, %r123, %r124}, [%rd68]; + add.f32 %r125, %r117, %r121; + add.f32 %r126, %r118, %r122; + add.f32 %r127, %r119, %r123; + add.f32 %r128, %r120, %r124; + cvta.to.global.u64 %rd69, %rd32; + add.s64 %rd70, %rd69, %rd67; + st.global.v4.b32 [%rd70], {%r125, %r126, %r127, %r128}; +$L__BB0_29: + ret; + +} diff --git a/scripts/gpu-bringup/extra-seal-plan.json b/scripts/gpu-bringup/extra-seal-plan.json index dbbadd64..34239273 100644 --- a/scripts/gpu-bringup/extra-seal-plan.json +++ b/scripts/gpu-bringup/extra-seal-plan.json @@ -1062,6 +1062,31 @@ "group": "sm120-decode", "optional": false }, + { + "cu": "crates/cuda-driver/src/sm120_combine_hits.cu", + "ptx": "crates/cuda-driver/src/sm120_combine_hits.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; claude/ffn-hits-combine: upstream combine_k10_vec4_hits = add_hits_kernel's `part + hit` on the listed rows, then the arithmetic of sm120_combine_vec4: first product rounded, nine explicit fmaf in expert order, the shared add)", + "entries": [ + "leleka_verify_combine_k10_vec4_hits" + ], + "encoding": "concat_include_str", + "rust_fields_to_fill": { + "plan_hits_combine.rs": [ + "HITS_COMBINE.sha" + ] + }, + "group": "sm120-decode", + "optional": false + }, { "cu": "crates/cuda-driver/src/sm120_gr_down_fused.cu", "ptx": "crates/cuda-driver/src/sm120_gr_down_fused.ptx", diff --git a/tools/decode-sm120/build_hits.sh b/tools/decode-sm120/build_hits.sh new file mode 100644 index 00000000..572cd747 --- /dev/null +++ b/tools/decode-sm120/build_hits.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Build the HITS_IN_COMBINE probe in WSL (never on the server) and collect the PTX it compares. +# tools/decode-sm120/build_hits.sh [OUTDIR] default OUTDIR=$HOME/sm120-hits-bin ; then: OUTDIR/sm120_probe_hits OUTDIR/ptx +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/../.." && pwd)" +out="${1:-$HOME/sm120-hits-bin}" +nvcc="${NVCC:-$HOME/cuda-toolkits/13.2.2/bin/nvcc}" +mkdir -p "$out/ptx" +"$nvcc" -O2 -std=c++17 "$here/sm120_probe_hits.cpp" -lcuda -o "$out/sm120_probe_hits" +for f in mtp_original_full_s2 mtp_original_full_combine sm120_combine_vec4 sm120_combine_hits; do + cp "$root/crates/cuda-driver/src/$f.ptx" "$out/ptx/$f.ptx" +done +sha256sum "$out"/sm120_probe_hits "$out"/ptx/* > "$out/SHA256SUMS" +ls -la "$out" "$out/ptx" diff --git a/tools/decode-sm120/sm120_probe_hits.cpp b/tools/decode-sm120/sm120_probe_hits.cpp new file mode 100644 index 00000000..c8517460 --- /dev/null +++ b/tools/decode-sm120/sm120_probe_hits.cpp @@ -0,0 +1,173 @@ +// claude/ffn-hits-combine: model-free probe of LELEKA_SM120_HITS_IN_COMBINE (docs/experiments/ffn-phase-loss-design.md, D2). +// The window's two launches per layer +// add_hits_kernel parts[row] += hit_out[row] for the rows listed in dst[0..count) (mtp_original_full_s2.ptx) +// combine mtp_full_combine (scalar, the literal Original) or leleka_verify_combine_k10_vec4 +// are run against the one launch of leleka_verify_combine_k10_vec4_hits (sm120_combine_hits.ptx) on real-size random inputs +// and EVERY output byte of the combine is compared, for T = 1..8 rows from a first row 0 and from the last possible first +// row (the hit list is relative to the group's first row), with hit lists that are empty, partial, full, in any order, at +// the edges of the expert range, with the CPU leg convention (listed parts rows zeroed to +0.0) and without it, and with +// -0.0, denormal, inf and nan values in the hit and part rows. The folded kernel must also leave `parts` unchanged. +// Prints "RESULT name key=value" lines; exits 1 if any comparison differs. Never touches the model. Written without a GPU: +// compiled (tools/decode-sm120/build_hits.sh), not run. +// sm120_probe_hits PTXDIR PTXDIR holds mtp_original_full_s2.ptx, mtp_original_full_combine.ptx, sm120_combine_vec4.ptx, +// sm120_combine_hits.ptx (build_hits.sh [OUTDIR] collects them). +#include +#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 const int N = 2560, K = 10, MAXT = 8; +static const char* ADD_HITS = "_ZN6strata7kernels56_GLOBAL__N__2b3d023b_23_mtp_original_full_s2_cu_9e2602a815add_hits_kernelEPfPKfPKiS6_i"; + +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 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, size_t bytes) const { + 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; +} +static void launch(CUfunction f, unsigned gx, unsigned gy, unsigned bx, void** args) { + CU(cuLaunchKernel(f, gx, gy, 1, bx, 1, 1, 0, nullptr, args, nullptr)); +} + +// What a case puts in the inputs. +struct Case { + const char* name; + int hits; // 0 = none, 1 = a random half of the T*K rows, 2 = every row, 3 = expert 0 and 9 of the last token only + bool zero_listed; // the CPU leg convention: the listed parts rows are +0.0 before the hit is added + bool specials; // -0.0, denormal, inf and nan in the parts and hit rows +}; +static const Case CASES[] = { + {"none", 0, true, false}, {"none_specials", 0, false, true}, {"half_zeroed", 1, true, false}, + {"half_free", 1, false, false}, {"all_zeroed", 2, true, true}, {"all_free_specials", 2, false, true}, + {"edges_zeroed", 3, true, true}, {"half_zeroed_specials", 1, true, true}, +}; + +static float special(uint32_t pick) { + switch (pick % 6) { case 0: return -0.0f; case 1: return 0.0f; case 2: return 1e-40f; case 3: return -1e-40f; case 4: return INFINITY; default: return NAN; } +} +// The hit list of a case for `tokens` rows (relative row = token * K + expert), in a random order. +static std::vector hit_list(const Case& c, int tokens) { + std::vector rows; + for (int r = 0; r < tokens * K; ++r) { + const bool listed = c.hits == 2 || (c.hits == 1 && (rnd() & 1)) || (c.hits == 3 && r >= (tokens - 1) * K && (r % K == 0 || r % K == K - 1)); + if (listed) rows.push_back(r); + } + for (size_t i = rows.size(); i > 1; --i) std::swap(rows[i - 1], rows[rnd() % i]); + return rows; +} + +static void run_case(const Case& c, int seed, int tokens, int first, CUfunction f_add, CUfunction f_scalar, CUfunction f_vec4, CUfunction f_hits) { + const size_t rows = (size_t)MAXT * K * N; + std::vector parts(rows), hit_out(rows), w((size_t)MAXT * K), shared((size_t)MAXT * N); + for (auto& v : parts) v = rndf() * (seed == 1 ? 1e6f : 3.0f); + for (auto& v : hit_out) v = rndf() * (seed == 1 ? 1e6f : 3.0f); + for (auto& v : w) v = rndf(); + for (auto& v : shared) v = rndf(); + if (c.specials) { + for (size_t i = 0; i < rows - 8; i += 61) { parts[i] = special(rnd()); hit_out[i + (i % 7)] = special(rnd()); } + for (size_t i = 0; i < shared.size(); i += 131) shared[i] = -0.0f; + } + std::vector list = hit_list(c, tokens); + if (c.zero_listed) // the CPU leg zeroes the rows whose expert ran on the hit path + for (int32_t r : list) std::fill_n(parts.begin() + ((size_t)first * K + r) * N, N, 0.0f); + int32_t count = (int32_t)list.size(); + list.resize((size_t)MAXT * K, -1); + const size_t at = (size_t)first * K * N * 4, bytes = (size_t)tokens * K * N * 4, row_at = (size_t)first * N * 4, row_bytes = (size_t)tokens * N * 4; + Dev dp_a, dp_b, dp_c, dh, dw, ds, dd, dn, o_a, o_b, o_c; + for (Dev* d : {&dp_a, &dp_b, &dp_c, &dh}) d->alloc(rows * 4); + dw.alloc(w.size() * 4); ds.alloc(shared.size() * 4); dd.alloc(list.size() * 4); dn.alloc(4); + for (Dev* d : {&o_a, &o_b, &o_c}) d->alloc(shared.size() * 4); + for (Dev* d : {&dp_a, &dp_b, &dp_c}) d->put(parts.data(), rows * 4); + dh.put(hit_out.data(), rows * 4); dw.put(w.data(), w.size() * 4); ds.put(shared.data(), shared.size() * 4); + dd.put(list.data(), list.size() * 4); dn.put(&count, 4); + int n_embd = N; int64_t n = N, n4 = N / 4; int k = K; + // add_hits_kernel over the group's parts and hit_out base (grid (min(ceil(N/256), 8), cap = tokens * K), 256 threads) + for (Dev* dp : {&dp_a, &dp_b}) { + CUdeviceptr pa = dp->p + at, ha = dh.p + at; + void* args[] = {&pa, &ha, &dd.p, &dn.p, &n_embd}; + launch(f_add, std::min((N + 255) / 256, 8), (unsigned)(tokens * K), 256, args); + } + CUdeviceptr w0 = dw.p + (size_t)first * K * 4, s0 = ds.p + row_at; + CUdeviceptr pa = dp_a.p + at, pb = dp_b.p + at, pc = dp_c.p + at, hc = dh.p + at; + CUdeviceptr oa = o_a.p + row_at, ob = o_b.p + row_at, oc = o_c.p + row_at; + void* a_scalar[] = {&pa, &w0, &s0, &oa, &n, &k}; + void* a_vec4[] = {&pb, &w0, &s0, &ob, &n4}; + void* a_hits[] = {&pc, &hc, &dd.p, &dn.p, &w0, &s0, &oc, &n4}; + launch(f_scalar, (N + 255) / 256, (unsigned)tokens, 256, a_scalar); + launch(f_vec4, (unsigned)((n4 + 127) / 128), (unsigned)tokens, 128, a_vec4); + launch(f_hits, (unsigned)((n4 + 127) / 128), (unsigned)tokens, 128, a_hits); + const auto out_a = o_a.get(row_at, row_bytes), out_b = o_b.get(row_at, row_bytes), out_c = o_c.get(row_at, row_bytes); + const bool scalar_ok = same("add_hits + mtp_full_combine vs folded", out_a, out_c); + const bool vec4_ok = same("add_hits + combine_vec4 vs folded", out_b, out_c); + // rows outside the launch are untouched (0xCD) by the folded kernel, and it does not write `parts` back + const size_t after = shared.size() * 4 - row_at - row_bytes; + const bool tail_ok = same("outside the rows", o_c.get(0, row_at), std::vector(row_at, 0xCD)) && + same("after the rows", o_c.get(row_at + row_bytes, after), std::vector(after, 0xCD)); + std::vector before(bytes); memcpy(before.data(), (const uint8_t*)parts.data() + at, bytes); + const bool parts_ok = same("parts after the folded kernel", dp_c.get(at, bytes), before); + printf("RESULT hits case=%s seed=%d T=%d first=%d count=%d identical_scalar=%d identical_vec4=%d tail=%d parts_unchanged=%d\n", c.name, seed, tokens, first, + (int)count, scalar_ok, vec4_ok, tail_ok, parts_ok); + for (Dev* d : {&dp_a, &dp_b, &dp_c, &dh, &dw, &ds, &dd, &dn, &o_a, &o_b, &o_c}) CU(cuMemFree(d->p)); +} + +int main(int argc, char** argv) { + if (argc < 2) { fprintf(stderr, "usage: %s PTXDIR\n", argv[0]); return 2; } + const std::string dir = argv[1]; + CU(cuInit(0)); CUdevice dev; CU(cuDeviceGet(&dev, 0)); CUcontext ctx; CU(cuDevicePrimaryCtxRetain(&ctx, dev)); CU(cuCtxSetCurrent(ctx)); + CUfunction f_add = get_fn(load_module(dir + "/mtp_original_full_s2.ptx"), ADD_HITS); + CUfunction f_scalar = get_fn(load_module(dir + "/mtp_original_full_combine.ptx"), "mtp_full_combine"); + CUfunction f_vec4 = get_fn(load_module(dir + "/sm120_combine_vec4.ptx"), "leleka_verify_combine_k10_vec4"); + CUfunction f_hits = get_fn(load_module(dir + "/sm120_combine_hits.ptx"), "leleka_verify_combine_k10_vec4_hits"); + for (const Case& c : CASES) + for (int seed = 0; seed < 3; ++seed) + for (int tokens = 1; tokens <= MAXT; ++tokens) { + run_case(c, seed, tokens, 0, f_add, f_scalar, f_vec4, f_hits); + if (tokens < MAXT) run_case(c, seed, tokens, MAXT - tokens, f_add, f_scalar, f_vec4, f_hits); + } + printf("SUMMARY failures=%d\n", g_fail); + return g_fail ? 1 : 0; +}