From d1ad19e765ed70f063c7961e17d80d1938437ea3 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 11 Nov 2026 17:27:58 +0100 Subject: [PATCH] Tail fusion: LELEKA_SM120_HEAD_CHAIN_BATCH (off), residual write and head mix of all rows in 6 launches Analysis (docs/experiments/verify-tail-and-gaps.md, CUPTI windows CP.1 / CL.2 / CY.1 against VANL): R6 is the single-stream control (2035 gaps, 211 us) against VANL (1194, 119 us); with the side streams LEL has 1124 / 123.7 us, residual +0.006 ms. R7 has no gap. R8 (+86.5 us at LEL's T mix) is the hyper-connection chain 31.2, the head matmul at T >= 3 38.4 and the greedy pick 18.0. The switch batches the 6 T launches of the tail (mtp_full_native_write plus the five lm_head_mix kernels a row) into 6: new sealed sm120_head_chain.cu/.ptx (final write, head norm, pre-final mix with the row as grid.y, compiled with the --use_fast_math flags of the originals), the existing multi-column bf16 gemv, mtp_full_down_silu over the contiguous rows. Bitwise by construction (same bodies, same per-column fma chain). Flag in GrConfig::head_chain_batch like U5a; HEAD_MIX_MULTI untouched. Model-free probe tools/decode-sm120/sm120_probe_head_chain.cpp (built, not run), report script scripts/e2e/codex/speed/verify_tail_report.py, 15 unit tests (288 original_verify tests pass). Co-Authored-By: Claude Sonnet 5.5 --- crates/cuda-driver/ptx-sm86/MANIFEST.json | 7 + .../src/original_verify_window_gr.rs | 5 + .../src/original_verify_window_gr/assets.rs | 1 + .../original_verify_window_gr/head_chain.rs | 148 +++++ .../original_verify_window_gr/plan_hc_read.rs | 6 + .../src/original_verify_window_gr/tests.rs | 2 + .../tests/head_chain_launches.rs | 230 +++++++ .../all_window_assets.rs | 3 + .../original_verify_window_planner/tests.rs | 2 + .../tests/head_chain_batch.rs | 96 +++ .../src/original_verify_window_sm120.rs | 7 + crates/cuda-driver/src/sm120_head_chain.cu | 117 ++++ crates/cuda-driver/src/sm120_head_chain.ptx | 582 ++++++++++++++++++ docs/experiments/verify-tail-and-gaps.md | 182 ++++++ scripts/e2e/codex/speed/verify_tail_report.py | 157 +++++ scripts/gpu-bringup/extra-seal-plan.json | 26 + tools/decode-sm120/build_head_chain.sh | 15 + tools/decode-sm120/sm120_probe_head_chain.cpp | 198 ++++++ 18 files changed, 1784 insertions(+) create mode 100644 crates/cuda-driver/src/original_verify_window_gr/head_chain.rs create mode 100644 crates/cuda-driver/src/original_verify_window_gr/tests/head_chain_launches.rs create mode 100644 crates/cuda-driver/src/original_verify_window_planner/tests/head_chain_batch.rs create mode 100644 crates/cuda-driver/src/sm120_head_chain.cu create mode 100644 crates/cuda-driver/src/sm120_head_chain.ptx create mode 100644 docs/experiments/verify-tail-and-gaps.md create mode 100644 scripts/e2e/codex/speed/verify_tail_report.py create mode 100644 tools/decode-sm120/build_head_chain.sh create mode 100644 tools/decode-sm120/sm120_probe_head_chain.cpp diff --git a/crates/cuda-driver/ptx-sm86/MANIFEST.json b/crates/cuda-driver/ptx-sm86/MANIFEST.json index 9f91b3af..7834ed73 100644 --- a/crates/cuda-driver/ptx-sm86/MANIFEST.json +++ b/crates/cuda-driver/ptx-sm86/MANIFEST.json @@ -2789,6 +2789,13 @@ "problems": [ "not built for sm_86 by design (claude/u5a-gr-down-fused): LELEKA_SM120_GR_DOWN_FUSED 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" ] + }, + { + "name": "sm120_head_chain.ptx", + "sm120_path": "crates/cuda-driver/src/sm120_head_chain.ptx", + "problems": [ + "not built for sm_86 by design (claude/tail-fusion): LELEKA_SM120_HEAD_CHAIN_BATCH 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" + ] } ], "portable_no_companion_needed": [ diff --git a/crates/cuda-driver/src/original_verify_window_gr.rs b/crates/cuda-driver/src/original_verify_window_gr.rs index 046c3afe..a4d11499 100644 --- a/crates/cuda-driver/src/original_verify_window_gr.rs +++ b/crates/cuda-driver/src/original_verify_window_gr.rs @@ -166,6 +166,9 @@ pub(crate) struct GrConfig { /// `LELEKA_SM120_GR_DOWN_FUSED`, resolved by `fused_down::resolve` (off in `from_device`): the split and the tiled /// chain down kernel of the staged read as one launch. pub down_fused: bool, + /// `LELEKA_SM120_HEAD_CHAIN_BATCH`, resolved by `head_chain::resolve` (off in `from_device`): the residual write + /// and the head mix of all window rows in a handful of launches instead of `6 T`. + pub head_chain_batch: bool, } /// What every gated-residual (GR) planner reads: the arena the spans come from, the window geometry and the @@ -349,6 +352,8 @@ pub(crate) use assets::shared_attributes; pub(crate) use assets::tiled_down_geometry; #[path = "original_verify_window_gr/fused_down.rs"] pub(crate) mod fused_down; +#[path = "original_verify_window_gr/head_chain.rs"] +pub(crate) mod head_chain; #[path = "original_verify_window_gr/plan_hc_read.rs"] mod plan_hc_read; pub(crate) use fused_down::plan_hc_read_launches; diff --git a/crates/cuda-driver/src/original_verify_window_gr/assets.rs b/crates/cuda-driver/src/original_verify_window_gr/assets.rs index a07c7861..be4c771a 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/assets.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/assets.rs @@ -51,6 +51,7 @@ impl GrConfig { attr_down: (cc_major >= 7 && optin > 0).then_some(want), attr_staged: (cc_major >= 7 && optin > 0).then_some(want_staged), down_fused: false, + head_chain_batch: false, } } diff --git a/crates/cuda-driver/src/original_verify_window_gr/head_chain.rs b/crates/cuda-driver/src/original_verify_window_gr/head_chain.rs new file mode 100644 index 00000000..b4345125 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_gr/head_chain.rs @@ -0,0 +1,148 @@ +//! `LELEKA_SM120_HEAD_CHAIN_BATCH` (design note `docs/experiments/verify-tail-and-gaps.md`): the graph tail after the +//! last layer, for all window rows at once. The literal tail launches, per row `t`, the residual write of the last +//! layer (`mtp_full_native_write`) and the five kernels of `lm_head_mix` (norm, down gemv, down-silu, up gemv, +//! pre-final): `6 T` dependent launches, each a latency-bound kernel of a few microseconds. With the switch: +//! +//! * the residual write of a group is ONE launch (`leleka_verify_final_write_rows`, grid.y = row); +//! * the head mix is FIVE launches whatever `T`: `leleka_verify_head_norm_rows`, the sealed multi-column +//! `bf16_f32_mmvf_multi_kernel` (down), `mtp_full_down_silu` over the contiguous `lo` slots of the rows, +//! `bf16_f32_mmvf_multi_kernel` (up), `leleka_verify_head_pre_final_rows`. +//! +//! Bitwise by construction, not by a tolerance: the three new kernels are the bodies of the kernels they batch with the +//! row as `blockIdx.y` (`sm120_head_chain.cu`), and the multi-column gemv runs the per-column fma chain and warp tree +//! of `mtp_full_mmvf256|160` (the same chain the multi-token projections of the layers already rely on). Nothing here +//! touches the arithmetic of the hyper-connection read of the head: `LELEKA_SM120_HEAD_MIX_MULTI` changed it (another +//! summation order, 25 of 2057 top-16 rows moved) and stays a separate, lossy-class switch; when both are on the +//! planner takes `plan_head_mix_multi` and only the residual write is batched. A window of one row keeps the literal +//! launches. +//! +//! The switch is resolved before capture (`resolve`, like `fused_down`) and carried in `GrConfig::head_chain_batch`; +//! the asset is sm_120 only (`Sm120Switches`: a card below 12.x never takes it) and loaded only when it is on. +use super::super::sm120::Sm120Switches; +#[allow(unused_imports)] +use super::*; + +pub(crate) const E_FINAL_WRITE_ROWS: &str = "leleka_verify_final_write_rows"; +pub(crate) const E_HEAD_NORM_ROWS: &str = "leleka_verify_head_norm_rows"; +pub(crate) const E_HEAD_PRE_FINAL_ROWS: &str = "leleka_verify_head_pre_final_rows"; +/// Threads of the norm kernel (`mtp_full_gr_norm`); the element-wise kernels use `THREADS`. +const NORM_THREADS: u32 = 1024; + +/// `sm120_head_chain.cu` (nvcc 13.2.86, `--fmad=true --use_fast_math`, the flags `mtp_original_full_gr_norm` and +/// `mtp_original_full_gr_post` were sealed with); plan entry in `scripts/gpu-bringup/extra-seal-plan.json` (group +/// `sm120-decode`). +pub(crate) static HEAD_CHAIN: AssetSpec = AssetSpec { + name: "sm120_head_chain.ptx", + ptx: concat!(include_str!("../sm120_head_chain.ptx"), "\0").as_bytes(), + sha: [ + 108, 159, 128, 249, 97, 125, 144, 237, 99, 113, 100, 98, 16, 147, 170, 163, 30, 214, 120, 146, 251, 203, 3, 73, + 31, 110, 176, 118, 251, 64, 94, 168, + ], + entries: &[E_FINAL_WRITE_ROWS, E_HEAD_NORM_ROWS, E_HEAD_PRE_FINAL_ROWS], + unsealed: "Original verifier asset unsealed: sm120_head_chain.ptx (HEAD_CHAIN_BATCH tail kernels)", +}; + +/// Resolves the switch for the card and the environment, before the assets are loaded. Said once per process. +pub(crate) fn resolve(journal: &OriginalVerifyGdnJournal<'_>, cfg: &GrConfig) -> Result { + let major = journal.window_device_attribute(ATTR_COMPUTE_CAPABILITY_MAJOR)?; + let minor = journal.window_device_attribute(ATTR_COMPUTE_CAPABILITY_MINOR)?; + let on = Sm120Switches::from_env(major, minor).head_chain_batch && cfg.native_mmvf; + if on { + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| eprintln!("leleka-serve head chain batch: on (compute capability {major}.{minor})")); + } + Ok(on) +} + +/// The asset the window preloads before capture (none when the switch is off). +pub(crate) fn assets(on: bool) -> Vec<&'static AssetSpec> { + if on { vec![&HEAD_CHAIN] } else { Vec::new() } +} + +impl GrConfig { + /// This configuration with the switch resolved by `resolve`. + pub(crate) fn with_head_chain_batch(self, on: bool) -> Self { + Self { head_chain_batch: on, ..self } + } +} + +/// The residual write of the rows `rows` as one launch: `mtp_full_native_write` of every row in place, the row as +/// grid.y. The caller checked the rows and `cfg.native_mmvf`. +pub(super) fn final_write_rows(arena: &(impl ArenaMap + ?Sized), rows: Rows) -> Result { + let n = rows.len(); + let span = |name: &str, row_bytes: usize| arena.span(name, rows.begin * row_bytes, n * row_bytes); + let (r, bo, inject) = (span("R", D * 4)?, span("bo", N * 4)?, span("inj2", HC * 4)?); + let grid = [(D as u32).div_ceil(THREADS), n as u32, 1]; + let args = [A::P(r), A::P(bo), A::P(inject), A::I32(N as i32), A::I32(HC as i32), A::F32(QUARTER)]; + let strides = [A::I64(D as i64), A::I64(N as i64), A::I64(HC as i64)]; + Launch::new( + &HEAD_CHAIN, + E_FINAL_WRITE_ROWS, + LaunchExtent::new(grid, [THREADS, 1, 1], 0), + args.into_iter().chain(strides).collect(), + ) +} + +/// The first addresses of the per-row buffers of the head mix and the row stride of `parts`, in floats. +struct HeadRows { + r: u64, + xn: u64, + lo: u64, + gated: u64, + mixed: u64, + gated_stride: usize, +} + +impl HeadRows { + /// The spans of the first `rows` rows of the window; `gated` is the first `D` floats of each `parts` slot. + fn of(arena: &(impl ArenaMap + ?Sized), geo: &OriginalVerifyGeometry, mixed: u64, rows: usize) -> Result { + let gated_stride = geo.k * N; + Ok(Self { + r: arena.span("R", 0, rows * D * 4)?, + xn: arena.span("xn", 0, rows * D * 4)?, + lo: arena.span("lo", 0, rows * LR * 4)?, + gated: arena.span("parts", 0, ((rows - 1) * gated_stride + D) * 4)?, + mixed, + gated_stride, + }) + } +} + +/// The five launches of the head mix over the first `rows >= 2` rows of the window, writing the mixed vector of row +/// `t` at `mixed_base + t * N * 4`. The caller checked the rows, the geometry and `cfg.native_mmvf`. +pub(super) fn head_mix_rows( + arena: &(impl ArenaMap + ?Sized), + geo: &OriginalVerifyGeometry, + w: &HeadAddrs, + (mixed_base, rows): (u64, usize), +) -> Result> { + let h = HeadRows::of(arena, geo, mixed_base, rows)?; + let (x_rows, lo_rows) = (StridedRows::new(h.xn, D), StridedRows::new(h.lo, LR)); + let down = plan_bf16_gemv(x_rows, w.down, lo_rows, Bf16GemvExtents::new(D, LR, rows))?; + let gated_rows = StridedRows::new(h.gated, h.gated_stride); + let up = plan_bf16_gemv(lo_rows, w.up, gated_rows, Bf16GemvExtents::new(LR, D, rows))?; + Ok(vec![norm_rows(&h, w.norm, rows)?, down, down_silu_rows(&h, rows)?, up, pre_final_rows(&h, rows)?]) +} + +/// `mtp_full_gr_norm` of every row as one launch: grid (hc, rows), the weight rows shared by the rows. +fn norm_rows(h: &HeadRows, weight: u64, rows: usize) -> Result { + let args = [A::P(h.r), A::P(weight), A::P(h.xn), A::I32(N as i32), A::F32(EPS), A::I64(D as i64), A::I64(D as i64)]; + let extent = LaunchExtent::new([HC as u32, rows as u32, 1], [NORM_THREADS, 1, 1], 0); + Launch::new(&HEAD_CHAIN, E_HEAD_NORM_ROWS, extent, args.to_vec()) +} + +/// `mtp_full_down_silu` over the `rows * LR` contiguous floats of the `lo` slots of the rows: element-wise, so one +/// launch of the sealed kernel computes every element as its own launch did. +fn down_silu_rows(h: &HeadRows, rows: usize) -> Result { + let count = rows * LR; + let extent = LaunchExtent::new([(count as u32).div_ceil(THREADS), 1, 1], [THREADS, 1, 1], 0); + Launch::new(&GR_POST, "mtp_full_down_silu", extent, vec![A::P(h.lo), A::I32(count as i32), A::F32(QUARTER)]) +} + +/// `mtp_full_pre_final` of every row as one launch. +fn pre_final_rows(h: &HeadRows, rows: usize) -> Result { + let args = [A::P(h.xn), A::P(h.gated), A::P(h.mixed), A::I32(N as i32), A::I32(HC as i32), A::F32(QUARTER)]; + let strides = [A::I64(D as i64), A::I64(h.gated_stride as i64), A::I64(N as i64)]; + let extent = LaunchExtent::new([(N as u32).div_ceil(THREADS), rows as u32, 1], [THREADS, 1, 1], 0); + Launch::new(&HEAD_CHAIN, E_HEAD_PRE_FINAL_ROWS, extent, args.into_iter().chain(strides).collect()) +} 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 3e1df2e4..84335c1d 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 @@ -202,6 +202,9 @@ pub(crate) fn plan_final_write( rows: Rows, ) -> Result> { check_rows(geo, rows)?; + if cfg.head_chain_batch && rows.len() > 1 && cfg.native_mmvf { + return Ok(vec![super::head_chain::final_write_rows(arena, rows)?]); + } (rows.begin..rows.end).map(|t| write_row(arena, cfg, t, "final_write")).collect() } @@ -233,6 +236,9 @@ pub(crate) fn plan_head_mix( if !cfg.native_mmvf { return Err(refuse("head")); } + if cfg.head_chain_batch && rows > 1 { + return super::head_chain::head_mix_rows(arena, geo, w, (mixed_out_base, rows)); + } let mut out = Vec::with_capacity(rows * 5); for t in 0..rows { out.extend(head_mix_row(arena, geo, w, mixed_out_base, t)?); 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 0daed27a..37d5641a 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/tests.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/tests.rs @@ -60,6 +60,8 @@ fn ple_addrs(key: PleKey) -> PleAddrs { #[path = "tests/fused_down_launches.rs"] mod fused_down_launches; +#[path = "tests/head_chain_launches.rs"] +mod head_chain_launches; #[path = "tests/head_mix_is_the_native.rs"] mod head_mix_is_the_native; #[path = "tests/head_mix_multi.rs"] diff --git a/crates/cuda-driver/src/original_verify_window_gr/tests/head_chain_launches.rs b/crates/cuda-driver/src/original_verify_window_gr/tests/head_chain_launches.rs new file mode 100644 index 00000000..5874d1e0 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_gr/tests/head_chain_launches.rs @@ -0,0 +1,230 @@ +//! `LELEKA_SM120_HEAD_CHAIN_BATCH` (`head_chain.rs`, `sm120_head_chain.cu`): the plan, the decision, the asset and the +//! arithmetic the batched kernels share with the kernels they replace. + +use super::super::super::sm120::{DEFAULT_ON_HEAD_CHAIN_BATCH, Sm120Switches}; +use super::head_chain::{ + E_FINAL_WRITE_ROWS, E_HEAD_NORM_ROWS, E_HEAD_PRE_FINAL_ROWS, HEAD_CHAIN, assets as head_chain_assets, +}; +#[allow(unused_imports)] +use super::*; + +const MIXED_BASE: u64 = 0x9999_0000; +const HEAD: HeadAddrs = HeadAddrs { norm: 0xA000, down: 0xB000, up: 0xC000 }; + +fn batch_card() -> GrConfig { + sm120(GrVariant::Staged).with_head_chain_batch(true) +} +fn write_launches(cfg: &GrConfig, r: Rows) -> Vec { + let (m, g) = (arena(), test_geometry()); + plan_final_write(&m, &g, cfg, r).unwrap() +} +fn mix_launches(cfg: &GrConfig, rows: usize) -> Vec { + let (m, g) = (arena(), test_geometry()); + plan_head_mix(window(&m, &g, cfg), &HEAD, MIXED_BASE, rows).unwrap() +} +fn entries(l: &[Launch]) -> Vec<&'static str> { + l.iter().map(|x| x.entry).collect() +} +/// The address argument `k` of a launch. +fn address(l: &Launch, k: usize) -> u64 { + match l.args[k] { + A::P(a) => a, + ref other => panic!("argument {k} is {other:?}, not an address"), + } +} + +#[test] +fn the_switch_is_off_in_every_config_the_card_derives_and_loads_its_asset_only_when_on() { + assert!(!sm120(GrVariant::Staged).head_chain_batch); + assert!(!from_card(GrVariant::Staged, (8, 6), 101_376, 49_152).head_chain_batch); + assert!(batch_card().head_chain_batch && !batch_card().with_head_chain_batch(false).head_chain_batch); + assert!(head_chain_assets(false).is_empty()); + assert!(std::ptr::eq(head_chain_assets(true)[0], &HEAD_CHAIN)); +} + +#[test] +fn the_switch_is_off_by_default_follows_its_own_variable_and_no_other_switch_follows_it() { + const VAR: &str = "LELEKA_SM120_HEAD_CHAIN_BATCH"; + let resolve = |major, minor, pairs: &'static [(&'static str, &'static str)]| { + Sm120Switches::resolve(major, minor, move |k| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string())) + }; + assert!(!DEFAULT_ON_HEAD_CHAIN_BATCH && !resolve(12, 0, &[]).head_chain_batch); + assert!(resolve(12, 0, &[(VAR, "1")]).head_chain_batch); + assert!(!resolve(12, 0, &[(VAR, "0")]).head_chain_batch); + assert!(!resolve(8, 6, &[(VAR, "1")]).head_chain_batch, "below 12.x the sm_120 PTX is never taken"); + assert!(resolve(12, 0, &[("LELEKA_SM120_PERF", "0"), (VAR, "1")]).head_chain_batch); + let only = Sm120Switches { head_chain_batch: true, ..Sm120Switches::default() }; + assert_eq!(resolve(12, 0, &[(VAR, "1")]), only); +} + +#[test] +fn the_asset_is_sealed_and_exports_the_three_kernels() { + HEAD_CHAIN.assert_sealed_and_fail_closed(); + assert_eq!(HEAD_CHAIN.entries, &[E_FINAL_WRITE_ROWS, E_HEAD_NORM_ROWS, E_HEAD_PRE_FINAL_ROWS]); + let ptx = std::str::from_utf8(HEAD_CHAIN.ptx).unwrap(); + assert!(HEAD_CHAIN.entries.iter().all(|e| entry_declared(ptx, e))); + assert!(ptx.contains(".target sm_120")); +} + +#[test] +fn switch_off_is_the_literal_tail_six_launches_a_row() { + for rows in 1..=8usize { + let write = write_launches(&sm120(GrVariant::Staged), rows_of(0, rows)); + assert_eq!(entries(&write), vec!["mtp_full_native_write"; rows]); + let mix = mix_launches(&sm120(GrVariant::Staged), rows); + assert_eq!(mix.len(), 5 * rows); + assert!(mix.iter().all(|l| !std::ptr::eq(l.asset, &HEAD_CHAIN)), "rows {rows}"); + } +} + +#[test] +fn one_row_keeps_the_literal_launches_with_the_switch_on() { + let off = (write_launches(&sm120(GrVariant::Staged), rows_of(0, 1)), mix_launches(&sm120(GrVariant::Staged), 1)); + let on = (write_launches(&batch_card(), rows_of(0, 1)), mix_launches(&batch_card(), 1)); + assert_eq!(off, on); +} + +#[test] +fn the_residual_write_of_a_group_is_one_launch_with_the_row_as_grid_y() { + for (begin, end) in [(0, 2), (0, 8), (3, 5), (1, 8)] { + let l = write_launches(&batch_card(), rows_of(begin, end)); + assert_eq!(l.len(), 1); + let n = end - begin; + assert_eq!((l[0].entry, l[0].grid, l[0].block), (E_FINAL_WRITE_ROWS, [40, n as u32, 1], [256, 1, 1])); + assert!(std::ptr::eq(l[0].asset, &HEAD_CHAIN)); + // the literal launches of the same rows, per row, against the batched base plus the row stride + let literal = write_launches(&sm120(GrVariant::Staged), rows_of(begin, end)); + for (t, row) in literal.iter().enumerate() { + for (k, stride) in [(0usize, 40_960u64), (1, 10_240), (2, 16)] { + assert_eq!(address(row, k), address(&l[0], k) + t as u64 * stride, "rows {begin}..{end} t {t} arg {k}"); + } + assert_eq!(address(row, 3), address(row, 0), "the literal write is in place"); + } + let tail = [A::I32(2560), A::I32(4), A::F32(0.25), A::I64(10_240), A::I64(2560), A::I64(4)]; + assert_eq!(l[0].args[3..], tail); + } +} + +#[test] +fn the_head_mix_is_five_launches_whatever_the_window_width() { + for rows in 2..=8usize { + let l = mix_launches(&batch_card(), rows); + let nt = if rows <= 4 { "ELi4EE" } else { "ELi8EE" }; + assert_eq!(l.len(), 5, "rows {rows}"); + assert_eq!((l[0].entry, l[0].grid, l[0].block), (E_HEAD_NORM_ROWS, [4, rows as u32, 1], [1024, 1, 1])); + assert!(l[1].entry.contains("mmvf_multi_kernelILi256") && l[1].entry.contains(nt), "{}", l[1].entry); + assert_eq!((l[1].grid, l[1].block), ([320, 1, 1], [256, 1, 1])); + let silu_grid = [(rows as u32 * 320).div_ceil(256), 1, 1]; + assert_eq!((l[2].entry, l[2].grid, l[2].block), ("mtp_full_down_silu", silu_grid, [256, 1, 1])); + assert!(l[3].entry.contains("mmvf_multi_kernelILi160") && l[3].entry.contains(nt), "{}", l[3].entry); + assert_eq!((l[3].grid, l[3].block), ([10_240, 1, 1], [160, 1, 1])); + assert_eq!((l[4].entry, l[4].grid, l[4].block), (E_HEAD_PRE_FINAL_ROWS, [10, rows as u32, 1], [256, 1, 1])); + } +} + +/// The addresses of the literal launches of row `t` equal the batched base plus `t` strides, stage by stage. +fn assert_row_addresses(k: &[Launch], batch: &[Launch], t: usize) { + let step = |stride_bytes: u64| t as u64 * stride_bytes; + // norm: R -> xn, gamma shared + assert_eq!(address(&k[0], 0), address(&batch[0], 0) + step(40_960)); + assert_eq!(address(&k[0], 1), address(&batch[0], 1)); + assert_eq!(address(&k[0], 2), address(&batch[0], 2) + step(40_960)); + // down gemv: xn -> lo (multi kernel args: x, ldx, w, y, ldy, n_in, n_tok) + assert_eq!(address(&k[1], 0), address(&batch[1], 0) + step(40_960)); + assert_eq!(address(&k[1], 1), address(&batch[1], 2)); + assert_eq!(address(&k[1], 2), address(&batch[1], 3) + step(1280)); + // down-silu over lo + assert_eq!(address(&k[2], 0), address(&batch[2], 0) + step(1280)); + // up gemv: lo -> gated (a slot of `parts` each) + assert_eq!(address(&k[3], 0), address(&batch[3], 0) + step(1280)); + assert_eq!(address(&k[3], 2), address(&batch[3], 3) + step(102_400)); + // pre-final: xn, gated -> mixed + assert_eq!(address(&k[4], 0), address(&batch[4], 0) + step(40_960)); + assert_eq!(address(&k[4], 1), address(&batch[4], 1) + step(102_400)); + assert_eq!(address(&k[4], 2), address(&batch[4], 2) + step(10_240)); +} + +#[test] +fn every_row_has_the_addresses_the_literal_chain_gave_it() { + for rows in 2..=8usize { + let (literal, batch) = (mix_launches(&sm120(GrVariant::Staged), rows), mix_launches(&batch_card(), rows)); + for t in 0..rows { + assert_row_addresses(&literal[t * 5..t * 5 + 5], &batch, t); + } + } +} + +#[test] +fn the_strides_and_extents_are_the_row_pitches_of_the_arena() { + for rows in 2..=8usize { + let batch = mix_launches(&batch_card(), rows); + let n = rows as i32; + let ints = |l: &Launch| (l.args[1].clone(), l.args[4].clone(), l.args[5].clone(), l.args[6].clone()); + assert_eq!(ints(&batch[1]), (A::I64(10_240), A::I64(320), A::I32(10_240), A::I32(n))); + assert_eq!(ints(&batch[3]), (A::I64(320), A::I64(25_600), A::I32(320), A::I32(n))); + assert_eq!(batch[2].args[1..], [A::I32(n * 320), A::F32(0.25)]); + let pre = [A::I32(2560), A::I32(4), A::F32(0.25), A::I64(10_240), A::I64(25_600), A::I64(2560)]; + assert_eq!(batch[4].args[3..], pre); + assert_eq!(batch[0].args[3..], [A::I32(2560), A::F32(1e-6), A::I64(10_240), A::I64(10_240)]); + } +} + +#[test] +fn the_head_chain_refuses_what_the_literal_chain_refuses() { + let (m, g) = (arena(), test_geometry()); + let cfg = batch_card(); + assert!(plan_head_mix(window(&m, &g, &cfg), &HEAD, MIXED_BASE, 9).is_err()); + assert!(plan_head_mix(window(&m, &g, &cfg), &HEAD, MIXED_BASE, 0).is_err()); + let non_native = GrConfig { native_mmvf: false, ..batch_card() }; + assert!(plan_head_mix(window(&m, &g, &non_native), &HEAD, MIXED_BASE, 3).is_err()); + assert!(plan_final_write(&m, &g, &non_native, rows_of(0, 3)).is_err()); + assert!(plan_final_write(&m, &g, &cfg, rows_of(0, 9)).is_err()); +} + +fn rows_of(begin: usize, end: usize) -> Rows { + rows(begin, end, 0) +} + +// ------------------------------------------------------------------------------------ arithmetic +/// The mnemonics of the floating point, shuffle, barrier and special-function instructions of one entry, in order. +fn float_ops(ptx: &[u8], entry: &str) -> Vec { + let text = std::str::from_utf8(ptx).unwrap(); + let start = text.find(&format!(".visible .entry {entry}(")).unwrap_or_else(|| panic!("{entry} missing")); + let body = &text[start..]; + let body = &body[..body.find("\n}\n").unwrap()]; + let kinds = [".f32", "shfl", "bar.sync", "ex2", "rcp", "rsqrt", "sqrt"]; + let is_float = |op: &str| kinds.iter().any(|k| op.contains(k)); + let mut ops = Vec::new(); + for line in body.lines().map(str::trim) { + let mut words = line.split_whitespace(); + let mut op = words.next().unwrap_or(""); + if op.starts_with('@') { + op = words.next().unwrap_or(""); + } + if !op.is_empty() && !op.starts_with(['.', '$', '/']) && is_float(op) { + ops.push(op.to_string()); + } + } + ops +} + +/// The three kernels run the floating point instructions of the kernels they batch, in the same order (the norm and +/// the residual write instruction for instruction; the pre-final mix per loop iteration, whose unrolling differs +/// between two compilations of the same source). +#[test] +fn the_batched_kernels_use_the_arithmetic_of_the_kernels_they_batch() { + let ops = |a: &AssetSpec, e: &str| float_ops(a.ptx, e); + assert_eq!(ops(&HEAD_CHAIN, E_FINAL_WRITE_ROWS), ops(&GR_POST, "mtp_full_native_write")); + assert_eq!(ops(&HEAD_CHAIN, E_HEAD_NORM_ROWS), ops(&GR_NORM, "mtp_full_gr_norm")); + let (new, old) = (ops(&HEAD_CHAIN, E_HEAD_PRE_FINAL_ROWS), ops(&GR_POST, "mtp_full_pre_final")); + let iteration = |v: &[String]| v[..v.iter().position(|o| o == "selp.f32").unwrap() + 1].to_vec(); + assert_eq!(iteration(&new), iteration(&old)); + assert_eq!(new.last(), old.last()); + let distinct = |v: &[String]| v.iter().cloned().collect::>(); + assert_eq!(distinct(&new), distinct(&old)); + // the fast-math lowering of the originals, not the precise one + for op in ["ex2.approx.ftz.f32", "rcp.approx.ftz.f32", "fma.rn.ftz.f32"] { + assert!(new.iter().any(|o| o == op), "{op}"); + } + assert!(ops(&HEAD_CHAIN, E_HEAD_NORM_ROWS).iter().any(|o| o.starts_with("rsqrt.approx"))); +} 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 8c0dbae8..9ab1580b 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 @@ -176,8 +176,11 @@ impl<'ctx> OriginalVerifyWindowResources<'ctx> { let cfg = GrConfig::query(&self.base.journal, policy.gr_variant, policy.native_mmvf)?; // claude/u5a-gr-down-fused: LELEKA_SM120_GR_DOWN_FUSED, decided before the assets are loaded let cfg = cfg.with_fused_down(gr::fused_down::resolve(&self.base.journal, &cfg)?); + // claude/tail-fusion: LELEKA_SM120_HEAD_CHAIN_BATCH, decided before the assets are loaded + let cfg = cfg.with_head_chain_batch(gr::head_chain::resolve(&self.base.journal, &cfg)?); let mut assets = self.required_assets(policy); assets.extend(gr::fused_down::assets(cfg.down_fused)); + assets.extend(gr::head_chain::assets(cfg.head_chain_batch)); self.base.journal.ensure_window_assets(&assets)?; let mut attributes = Vec::new(); if self.gr.is_some() { 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 dbe07db4..95ff9f2a 100644 --- a/crates/cuda-driver/src/original_verify_window_planner/tests.rs +++ b/crates/cuda-driver/src/original_verify_window_planner/tests.rs @@ -347,3 +347,5 @@ mod every_window_size_and_group; mod fused_gr_down; #[path = "tests/fused_qsa_prelude.rs"] mod fused_qsa_prelude; +#[path = "tests/head_chain_batch.rs"] +mod head_chain_batch; diff --git a/crates/cuda-driver/src/original_verify_window_planner/tests/head_chain_batch.rs b/crates/cuda-driver/src/original_verify_window_planner/tests/head_chain_batch.rs new file mode 100644 index 00000000..cf4c8dcf --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_planner/tests/head_chain_batch.rs @@ -0,0 +1,96 @@ +//! `LELEKA_SM120_HEAD_CHAIN_BATCH` through the recorder: with the switch off the window is the literal one; with it on +//! only the residual write of the last layer and the head mix change, and the launch counts fall as the design note +//! says (`docs/experiments/verify-tail-and-gaps.md`). + +use super::super::super::combine_head::CombineHeadKernels; +use super::super::super::gr::head_chain::{E_FINAL_WRITE_ROWS, E_HEAD_NORM_ROWS, E_HEAD_PRE_FINAL_ROWS}; +#[allow(unused_imports)] +use super::*; + +fn record_batched(cfg: GrConfig, t: usize, groups: usize, multi: bool) -> Vec { + let (m, fake) = geometry_and_fake(false); + let policy = WindowPolicy::mode17(); + let kernels = CombineHeadKernels { combine_vec4: false, head_mix_multi: multi }; + let planner = Planner::new(&m, test_geometry(), policy, cfg, &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 on(t: usize, groups: usize, multi: bool) -> Vec { + record_batched(sm120().with_head_chain_batch(true), t, groups, multi) +} +fn off(t: usize, groups: usize, multi: bool) -> Vec { + record_batched(sm120(), t, groups, multi) +} +/// The log without the sections the producers `names` planned (``), and those sections apart. +fn split_sections(log: &[String], names: &[&str]) -> (Vec, Vec>) { + let (mut rest, mut cut, mut open): (Vec, Vec>, Option) = (Vec::new(), Vec::new(), None); + for line in log { + match open { + None if names.iter().any(|n| *line == format!("<{n}")) => { + open = Some(cut.len()); + cut.push(Vec::new()); + } + Some(i) => { + if names.iter().any(|n| *line == format!("{n}>")) { + open = None; + } else { + cut[i].push(line.clone()); + } + } + None => rest.push(line.clone()), + } + } + (rest, cut) +} +fn count_in(sections: &[Vec], name: &str) -> usize { + sections.iter().flatten().filter(|s| *s == name).count() +} +const TAIL: [&str; 2] = ["final_write", "head_mix"]; + +#[test] +fn switch_off_is_the_literal_window() { + for (t, groups) in [(1, 1), (3, 1), (8, 1), (6, 2)] { + assert_eq!(off(t, groups, false), record(t, groups, false), "T {t} groups {groups}"); + } +} + +#[test] +fn only_the_residual_write_and_the_head_mix_change_and_the_launches_fall_to_six() { + for (t, groups) in [(2, 1), (3, 1), (5, 1), (8, 1), (6, 2), (4, 2), (3, 2)] { + let (rest_off, tail_off) = split_sections(&off(t, groups, false), &TAIL); + let (rest_on, tail_on) = split_sections(&on(t, groups, false), &TAIL); + assert_eq!(rest_on, rest_off, "T {t} groups {groups}: nothing outside the tail changes"); + let first = t.div_ceil(2); + let group_sizes = if groups == 2 { vec![first, t - first] } else { vec![t] }; + let batched_writes = group_sizes.iter().filter(|n| **n > 1).count(); + let single_writes = group_sizes.iter().filter(|n| **n == 1).count(); + assert_eq!(count_in(&tail_off, "mtp_full_native_write"), t); + assert_eq!(count_in(&tail_on, E_FINAL_WRITE_ROWS), batched_writes, "T {t} groups {groups}"); + assert_eq!(count_in(&tail_on, "mtp_full_native_write"), single_writes, "T {t} groups {groups}"); + assert_eq!(count_in(&tail_off, "mtp_full_pre_final"), t); + assert_eq!(count_in(&tail_on, "mtp_full_pre_final") + count_in(&tail_on, "mtp_full_gr_norm"), 0); + assert_eq!(count_in(&tail_on, E_HEAD_NORM_ROWS) + count_in(&tail_on, E_HEAD_PRE_FINAL_ROWS), 2); + let launches = |s: &[Vec]| s.iter().map(Vec::len).sum::(); + assert_eq!(launches(&tail_off), 6 * t, "T {t}: a write and five kernels a row"); + assert_eq!(launches(&tail_on), 5 + batched_writes + single_writes, "T {t} groups {groups}"); + } +} + +#[test] +fn a_window_of_one_row_is_unchanged() { + assert_eq!(on(1, 1, false), off(1, 1, false)); +} + +#[test] +fn with_the_multi_head_mix_only_the_residual_write_is_batched() { + for t in [2usize, 4, 7] { + let (rest_off, tail_off) = split_sections(&off(t, 1, true), &TAIL); + let (rest_on, tail_on) = split_sections(&on(t, 1, true), &TAIL); + assert_eq!(rest_on, rest_off, "T {t}"); + assert_eq!(count_in(&tail_on, E_FINAL_WRITE_ROWS), 1); + assert_eq!(count_in(&tail_on, E_HEAD_NORM_ROWS) + count_in(&tail_on, E_HEAD_PRE_FINAL_ROWS), 0); + let launches = |s: &[Vec]| s.iter().map(Vec::len).sum::(); + assert_eq!(launches(&tail_off) - launches(&tail_on), t - 1, "T {t}: the head mix launches are the multi read"); + } +} diff --git a/crates/cuda-driver/src/original_verify_window_sm120.rs b/crates/cuda-driver/src/original_verify_window_sm120.rs index e69419fb..c79be8ae 100644 --- a/crates/cuda-driver/src/original_verify_window_sm120.rs +++ b/crates/cuda-driver/src/original_verify_window_sm120.rs @@ -95,6 +95,8 @@ pub(crate) const DEFAULT_ON_GR_DOWN_FUSED: bool = false; pub(crate) const DEFAULT_ON_DOWN_SUB16: bool = false; pub(crate) const DEFAULT_ON_HITS_IN_COMBINE: bool = false; pub(crate) const DEFAULT_ON_WAIT_M_ROWS: bool = false; +// claude/tail-fusion (original_verify_window_gr/head_chain.rs): off until its identity run and a paired A/B +pub(crate) const DEFAULT_ON_HEAD_CHAIN_BATCH: 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 @@ -154,6 +156,9 @@ pub struct Sm120Switches { pub hits_in_combine: bool, /// `LELEKA_SM120_WAIT_M_ROWS`: the wait on flag M and the copy of the CPU rows as one launch. pub wait_m_rows: bool, + // ---- claude/tail-fusion + /// `LELEKA_SM120_HEAD_CHAIN_BATCH`: the residual write and the head mix of all window rows, 6 launches not `6 T`. + pub head_chain_batch: bool, } fn one(get: &impl Fn(&str) -> Option, var: &str, default: bool) -> bool { @@ -206,6 +211,7 @@ impl Sm120Switches { down_sub16: switch("LELEKA_SM120_DOWN_SUB16", DEFAULT_ON_DOWN_SUB16), hits_in_combine: switch("LELEKA_SM120_HITS_IN_COMBINE", DEFAULT_ON_HITS_IN_COMBINE), wait_m_rows: switch("LELEKA_SM120_WAIT_M_ROWS", DEFAULT_ON_WAIT_M_ROWS), + head_chain_batch: switch("LELEKA_SM120_HEAD_CHAIN_BATCH", DEFAULT_ON_HEAD_CHAIN_BATCH), } } /// The side-stream parts these switches ask for. @@ -230,6 +236,7 @@ impl Sm120Switches { down_sub16: s.down_sub16, hits_in_combine: s.hits_in_combine, wait_m_rows: s.wait_m_rows, + head_chain_batch: s.head_chain_batch, } } } diff --git a/crates/cuda-driver/src/sm120_head_chain.cu b/crates/cuda-driver/src/sm120_head_chain.cu new file mode 100644 index 00000000..fa5acd94 --- /dev/null +++ b/crates/cuda-driver/src/sm120_head_chain.cu @@ -0,0 +1,117 @@ +// verify window, the graph tail after the last layer: the final residual write and the head's hyper-connection mix of +// ALL window rows in a handful of launches (docs/experiments/verify-tail-and-gaps.md): LELEKA_SM120_HEAD_CHAIN_BATCH. +// +// The literal tail launches, per window row t, `mtp_full_native_write` (the last layer's residual write) and the five +// kernels of `lm_head_mix`: `mtp_full_gr_norm`, `mtp_full_mmvf256`, `mtp_full_down_silu`, `mtp_full_mmvf160`, +// `mtp_full_pre_final` = 6 T launches, one dependent chain per row. The three kernels below are those kernels with the +// row as `blockIdx.y` and the per-row base offsets as launch arguments; the two gemv kernels and the silu are not +// here: the existing sealed `bf16_f32_mmvf_multi_kernel` runs the per-column fma chain of +// `mtp_full_mmvf256|160` (`acc[k] = fma(w, x, acc[k])` over the same pairs, the same warp tree) for 2..8 columns, and +// `mtp_full_down_silu` is element-wise over the rows' contiguous `lo` slots. +// +// Same value of every output element, element by element: each body below is the body of the kernel it batches, token +// by token, with `blockIdx.y` selecting the row and no other change. The row bases add `tk * stride` (in floats) to the +// pointers; everything else, including the order of the sums of the norm and the helper functions, is the text of +// mtp_original_full_gr_norm.cu / mtp_original_full_gr_post.cu (closed literal Original MTP exports). Compile with the +// flags those two were sealed with (extra-seal-plan.json, group reseal-fastmath): --fmad=true --use_fast_math, so +// `expf`, `rsqrtf` and the divisions lower to the same approximate PTX as the originals' (checked by the unit test +// `the_batched_kernels_use_the_arithmetic_of_the_kernels_they_batch`). +// +// Compile: nvcc --ptx -O3 -arch=sm_120 -std=c++17 --fmad=true --use_fast_math +#include +#include +#include + +namespace { +__device__ __forceinline__ float norm_warp_sum(float value) { +#pragma unroll + for (int offset = 16; offset > 0; offset >>= 1) { + value += __shfl_xor_sync(0xffffffffu, value, offset, 32); + } + return value; +} +__device__ __forceinline__ float sigmoid(float x) { return 1.0f / (1.0f + expf(-x)); } +// ggml SCALE uses scale*x+bias, including its +0 bias. Retain this operation explicitly so compile-time zero does not +// change signed-zero behavior. +__device__ __forceinline__ float scale_zero_bias(float x, float scale) { + return __fmaf_rn(scale, x, 0.0f); +} +} // namespace + +// mtp_full_native_write over `gridDim.y` rows: output = block_out * (2 * sigmoid(scale * inject[c])) + residual, in +// place (residual and output are the same row). Strides in floats. +extern "C" __global__ void leleka_verify_final_write_rows(float* residual_output, const float* __restrict__ block_out, + const float* __restrict__ inject, int n_embd, int hc, + float scale, int64_t residual_stride, int64_t block_stride, + int64_t inject_stride) { + const int64_t tk = blockIdx.y; + const float* residual = residual_output + tk * residual_stride; + float* output = residual_output + tk * residual_stride; + block_out += tk * block_stride; + inject += tk * inject_stride; + const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= std::size_t(n_embd) * hc) return; + const int c = int(i / n_embd), d = int(i % n_embd); + const float weight = scale_zero_bias(sigmoid(scale_zero_bias(inject[c], scale)), 2.0f); + // Exact residual/output alias is supported; no other thread reads residual[i]. + output[i] = __fmaf_rn(block_out[d], weight, residual[i]); +} + +// mtp_full_gr_norm over `gridDim.y` rows (grid.x = hc rows of the row's state): weighted RMS norm of block x of row +// tk. `gamma` is the head's norm weight, the same for every row. 1024 threads. +extern "C" __global__ void leleka_verify_head_norm_rows(const float* __restrict__ input, + const float* __restrict__ gamma, float* __restrict__ output, + int n_cols, float epsilon, int64_t input_stride, + int64_t output_stride) { + const int tid = threadIdx.x; + const int64_t tk = blockIdx.y; + const std::size_t row_offset = std::size_t(blockIdx.x) * n_cols; + input += tk * input_stride + row_offset; + gamma += row_offset; + output += tk * output_stride + row_offset; + float partial = 0.0f; + for (int col = tid; col < n_cols; col += 1024) { + const float value = input[col]; + partial += value * value; + } + + // Pinned block_reduce: every warp repeats the final XOR + // reduction. There is no warp-0-only broadcast or downward-shuffle tree. + __shared__ float sums[32]; + partial = norm_warp_sum(partial); + const int lane = tid % 32; + if (lane == 0) sums[tid / 32] = partial; + __syncthreads(); + partial = 0.0f; + if (lane < 1024 / 32) partial = sums[lane]; + partial = norm_warp_sum(partial); + + const float mean = partial / n_cols; + const float scale = rsqrtf(mean + epsilon); + for (int col = tid; col < n_cols; col += 1024) { + output[col] = scale * input[col] * gamma[col]; + } +} + +// mtp_full_pre_final over `gridDim.y` rows: gate = xn * sigmoid(gate) per channel, mixed = scale * (the channel sum), +// as the final mixer (not the layer form). Strides in floats. +extern "C" __global__ void leleka_verify_head_pre_final_rows(const float* __restrict__ xn, float* __restrict__ gate, + float* __restrict__ mixed, int n_embd, int hc, float scale, + int64_t xn_stride, int64_t gate_stride, + int64_t mixed_stride) { + const int64_t tk = blockIdx.y; + xn += tk * xn_stride; + gate += tk * gate_stride; + mixed += tk * mixed_stride; + const std::size_t d = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (d >= std::size_t(n_embd)) return; + float sum = 0.0f; + for (int c = 0; c < hc; ++c) { + const std::size_t i = std::size_t(c) * n_embd + d; + const float x = xn[i], w = sigmoid(gate[i]); + const float product = __fmul_rn(x, w); + gate[i] = product; + sum = c == 0 ? product : __fadd_rn(sum, product); + } + mixed[d] = scale_zero_bias(sum, scale); +} diff --git a/crates/cuda-driver/src/sm120_head_chain.ptx b/crates/cuda-driver/src/sm120_head_chain.ptx new file mode 100644 index 00000000..96a32173 --- /dev/null +++ b/crates/cuda-driver/src/sm120_head_chain.ptx @@ -0,0 +1,582 @@ +// +// 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_final_write_rows +// _ZZ28leleka_verify_head_norm_rowsE4sums has been demoted + +.visible .entry leleka_verify_final_write_rows( + .param .u64 .ptr .align 1 leleka_verify_final_write_rows_param_0, + .param .u64 .ptr .align 1 leleka_verify_final_write_rows_param_1, + .param .u64 .ptr .align 1 leleka_verify_final_write_rows_param_2, + .param .u32 leleka_verify_final_write_rows_param_3, + .param .u32 leleka_verify_final_write_rows_param_4, + .param .f32 leleka_verify_final_write_rows_param_5, + .param .u64 leleka_verify_final_write_rows_param_6, + .param .u64 leleka_verify_final_write_rows_param_7, + .param .u64 leleka_verify_final_write_rows_param_8 +) +{ + .reg .pred %p<3>; + .reg .b32 %r<23>; + .reg .b64 %rd<32>; + + ld.param.b64 %rd3, [leleka_verify_final_write_rows_param_0]; + ld.param.b64 %rd4, [leleka_verify_final_write_rows_param_1]; + ld.param.b64 %rd5, [leleka_verify_final_write_rows_param_2]; + ld.param.b32 %r2, [leleka_verify_final_write_rows_param_3]; + ld.param.b32 %r3, [leleka_verify_final_write_rows_param_4]; + ld.param.b32 %r1, [leleka_verify_final_write_rows_param_5]; + ld.param.b64 %rd6, [leleka_verify_final_write_rows_param_6]; + ld.param.b64 %rd7, [leleka_verify_final_write_rows_param_7]; + ld.param.b64 %rd8, [leleka_verify_final_write_rows_param_8]; + mov.u32 %r4, %ctaid.x; + mov.u32 %r5, %ntid.x; + mul.wide.u32 %rd9, %r4, %r5; + mov.u32 %r6, %tid.x; + cvt.u64.u32 %rd10, %r6; + add.s64 %rd1, %rd9, %rd10; + cvt.s64.s32 %rd2, %r2; + mul.wide.s32 %rd11, %r3, %r2; + setp.ge.u64 %p1, %rd1, %rd11; + @%p1 bra $L__BB0_5; + or.b64 %rd12, %rd1, %rd2; + and.b64 %rd13, %rd12, -4294967296; + setp.ne.b64 %p2, %rd13, 0; + @%p2 bra $L__BB0_3; + cvt.u32.u64 %r7, %rd2; + cvt.u32.u64 %r8, %rd1; + div.u32 %r9, %r8, %r7; + mul.lo.s32 %r10, %r9, %r7; + sub.s32 %r11, %r8, %r10; + cvt.u64.u32 %rd30, %r9; + cvt.u64.u32 %rd31, %r11; + bra.uni $L__BB0_4; +$L__BB0_3: + div.u64 %rd30, %rd1, %rd2; + mul.lo.s64 %rd14, %rd30, %rd2; + sub.s64 %rd31, %rd1, %rd14; +$L__BB0_4: + mov.u32 %r12, %ctaid.y; + cvt.u64.u32 %rd15, %r12; + cvt.s64.s32 %rd16, %rd30; + mad.lo.s64 %rd17, %rd8, %rd15, %rd16; + cvta.to.global.u64 %rd18, %rd5; + shl.b64 %rd19, %rd17, 2; + add.s64 %rd20, %rd18, %rd19; + ld.global.nc.b32 %r13, [%rd20]; + fma.rn.ftz.f32 %r14, %r1, %r13, 0f00000000; + mul.ftz.f32 %r15, %r14, 0fBFB8AA3B; + ex2.approx.ftz.f32 %r16, %r15; + add.ftz.f32 %r17, %r16, 0f3F800000; + rcp.approx.ftz.f32 %r18, %r17; + fma.rn.ftz.f32 %r19, %r18, 0f40000000, 0f00000000; + cvt.s64.s32 %rd21, %rd31; + mad.lo.s64 %rd22, %rd7, %rd15, %rd21; + cvta.to.global.u64 %rd23, %rd4; + shl.b64 %rd24, %rd22, 2; + add.s64 %rd25, %rd23, %rd24; + ld.global.nc.b32 %r20, [%rd25]; + mad.lo.s64 %rd26, %rd6, %rd15, %rd1; + cvta.to.global.u64 %rd27, %rd3; + shl.b64 %rd28, %rd26, 2; + add.s64 %rd29, %rd27, %rd28; + ld.global.b32 %r21, [%rd29]; + fma.rn.ftz.f32 %r22, %r20, %r19, %r21; + st.global.b32 [%rd29], %r22; +$L__BB0_5: + ret; + +} + // .globl leleka_verify_head_norm_rows +.visible .entry leleka_verify_head_norm_rows( + .param .u64 .ptr .align 1 leleka_verify_head_norm_rows_param_0, + .param .u64 .ptr .align 1 leleka_verify_head_norm_rows_param_1, + .param .u64 .ptr .align 1 leleka_verify_head_norm_rows_param_2, + .param .u32 leleka_verify_head_norm_rows_param_3, + .param .f32 leleka_verify_head_norm_rows_param_4, + .param .u64 leleka_verify_head_norm_rows_param_5, + .param .u64 leleka_verify_head_norm_rows_param_6 +) +{ + .reg .pred %p<26>; + .reg .b32 %r<133>; + .reg .b64 %rd<54>; + // demoted variable + .shared .align 4 .b8 _ZZ28leleka_verify_head_norm_rowsE4sums[128]; + ld.param.b64 %rd8, [leleka_verify_head_norm_rows_param_0]; + ld.param.b64 %rd9, [leleka_verify_head_norm_rows_param_1]; + ld.param.b64 %rd10, [leleka_verify_head_norm_rows_param_2]; + ld.param.b32 %r9, [leleka_verify_head_norm_rows_param_3]; + ld.param.b32 %r10, [leleka_verify_head_norm_rows_param_4]; + ld.param.b64 %rd11, [leleka_verify_head_norm_rows_param_5]; + ld.param.b64 %rd12, [leleka_verify_head_norm_rows_param_6]; + cvta.to.global.u64 %rd1, %rd10; + cvta.to.global.u64 %rd2, %rd9; + cvta.to.global.u64 %rd3, %rd8; + mov.u32 %r132, %tid.x; + mov.u32 %r11, %ctaid.y; + cvt.u64.u32 %rd13, %r11; + mov.u32 %r12, %ctaid.x; + cvt.u64.u32 %rd14, %r12; + cvt.s64.s32 %rd15, %r9; + mul.lo.s64 %rd4, %rd15, %rd14; + mad.lo.s64 %rd5, %rd11, %rd13, %rd4; + mul.lo.s64 %rd6, %rd12, %rd13; + setp.ge.s32 %p1, %r132, %r9; + mov.b32 %r128, 0f00000000; + @%p1 bra $L__BB1_11; + not.b32 %r13, %r132; + add.s32 %r14, %r9, %r13; + shr.u32 %r15, %r14, 10; + add.s32 %r1, %r15, 1; + and.b32 %r2, %r1, 15; + setp.lt.u32 %p2, %r14, 15360; + mov.b32 %r128, 0f00000000; + mov.b32 %r127, %r132; + @%p2 bra $L__BB1_5; + and.b32 %r16, %r1, 8388592; + neg.s32 %r130, %r16; + shl.b64 %rd16, %rd5, 2; + mul.wide.u32 %rd17, %r132, 4; + add.s64 %rd18, %rd16, %rd17; + add.s64 %rd19, %rd18, %rd3; + add.s64 %rd47, %rd19, 32768; + mov.b32 %r128, 0f00000000; + mov.b32 %r127, %r132; +$L__BB1_3: + .pragma "nounroll"; + ld.global.nc.b32 %r17, [%rd47+-32768]; + fma.rn.ftz.f32 %r18, %r17, %r17, %r128; + ld.global.nc.b32 %r19, [%rd47+-28672]; + fma.rn.ftz.f32 %r20, %r19, %r19, %r18; + ld.global.nc.b32 %r21, [%rd47+-24576]; + fma.rn.ftz.f32 %r22, %r21, %r21, %r20; + ld.global.nc.b32 %r23, [%rd47+-20480]; + fma.rn.ftz.f32 %r24, %r23, %r23, %r22; + ld.global.nc.b32 %r25, [%rd47+-16384]; + fma.rn.ftz.f32 %r26, %r25, %r25, %r24; + ld.global.nc.b32 %r27, [%rd47+-12288]; + fma.rn.ftz.f32 %r28, %r27, %r27, %r26; + ld.global.nc.b32 %r29, [%rd47+-8192]; + fma.rn.ftz.f32 %r30, %r29, %r29, %r28; + ld.global.nc.b32 %r31, [%rd47+-4096]; + fma.rn.ftz.f32 %r32, %r31, %r31, %r30; + ld.global.nc.b32 %r33, [%rd47]; + fma.rn.ftz.f32 %r34, %r33, %r33, %r32; + ld.global.nc.b32 %r35, [%rd47+4096]; + fma.rn.ftz.f32 %r36, %r35, %r35, %r34; + ld.global.nc.b32 %r37, [%rd47+8192]; + fma.rn.ftz.f32 %r38, %r37, %r37, %r36; + ld.global.nc.b32 %r39, [%rd47+12288]; + fma.rn.ftz.f32 %r40, %r39, %r39, %r38; + ld.global.nc.b32 %r41, [%rd47+16384]; + fma.rn.ftz.f32 %r42, %r41, %r41, %r40; + ld.global.nc.b32 %r43, [%rd47+20480]; + fma.rn.ftz.f32 %r44, %r43, %r43, %r42; + ld.global.nc.b32 %r45, [%rd47+24576]; + fma.rn.ftz.f32 %r46, %r45, %r45, %r44; + ld.global.nc.b32 %r47, [%rd47+28672]; + fma.rn.ftz.f32 %r128, %r47, %r47, %r46; + add.s32 %r127, %r127, 16384; + add.s32 %r130, %r130, 16; + add.s64 %rd47, %rd47, 65536; + setp.eq.b32 %p3, %r130, 0; + @%p3 bra $L__BB1_4; + bra.uni $L__BB1_3; +$L__BB1_4: + setp.eq.b32 %p4, %r2, 0; + @%p4 bra $L__BB1_11; +$L__BB1_5: + shl.b64 %rd20, %rd5, 2; + add.s64 %rd7, %rd3, %rd20; + and.b32 %r3, %r1, 7; + setp.lt.u32 %p5, %r2, 8; + @%p5 bra $L__BB1_7; + mul.wide.u32 %rd21, %r127, 4; + add.s64 %rd22, %rd7, %rd21; + ld.global.nc.b32 %r48, [%rd22]; + fma.rn.ftz.f32 %r49, %r48, %r48, %r128; + ld.global.nc.b32 %r50, [%rd22+4096]; + fma.rn.ftz.f32 %r51, %r50, %r50, %r49; + ld.global.nc.b32 %r52, [%rd22+8192]; + fma.rn.ftz.f32 %r53, %r52, %r52, %r51; + ld.global.nc.b32 %r54, [%rd22+12288]; + fma.rn.ftz.f32 %r55, %r54, %r54, %r53; + ld.global.nc.b32 %r56, [%rd22+16384]; + fma.rn.ftz.f32 %r57, %r56, %r56, %r55; + ld.global.nc.b32 %r58, [%rd22+20480]; + fma.rn.ftz.f32 %r59, %r58, %r58, %r57; + ld.global.nc.b32 %r60, [%rd22+24576]; + fma.rn.ftz.f32 %r61, %r60, %r60, %r59; + ld.global.nc.b32 %r62, [%rd22+28672]; + fma.rn.ftz.f32 %r128, %r62, %r62, %r61; + add.s32 %r127, %r127, 8192; + setp.eq.b32 %p6, %r3, 0; + @%p6 bra $L__BB1_11; +$L__BB1_7: + and.b32 %r4, %r1, 3; + setp.lt.u32 %p7, %r3, 4; + @%p7 bra $L__BB1_9; + mul.wide.u32 %rd23, %r127, 4; + add.s64 %rd24, %rd7, %rd23; + ld.global.nc.b32 %r63, [%rd24]; + fma.rn.ftz.f32 %r64, %r63, %r63, %r128; + ld.global.nc.b32 %r65, [%rd24+4096]; + fma.rn.ftz.f32 %r66, %r65, %r65, %r64; + ld.global.nc.b32 %r67, [%rd24+8192]; + fma.rn.ftz.f32 %r68, %r67, %r67, %r66; + ld.global.nc.b32 %r69, [%rd24+12288]; + fma.rn.ftz.f32 %r128, %r69, %r69, %r68; + add.s32 %r127, %r127, 4096; + setp.eq.b32 %p8, %r4, 0; + @%p8 bra $L__BB1_11; +$L__BB1_9: + mul.wide.u32 %rd25, %r127, 4; + add.s64 %rd26, %rd20, %rd25; + add.s64 %rd46, %rd3, %rd26; + neg.s32 %r129, %r4; +$L__BB1_10: + .pragma "nounroll"; + ld.global.nc.b32 %r70, [%rd46]; + fma.rn.ftz.f32 %r128, %r70, %r70, %r128; + add.s64 %rd46, %rd46, 4096; + add.s32 %r129, %r129, 1; + setp.eq.b32 %p9, %r129, 0; + @%p9 bra $L__BB1_11; + bra.uni $L__BB1_10; +$L__BB1_11: + shfl.sync.bfly.b32 %r71|%p10, %r128, 16, 31, -1; + add.ftz.f32 %r72, %r128, %r71; + shfl.sync.bfly.b32 %r73|%p11, %r72, 8, 31, -1; + add.ftz.f32 %r74, %r72, %r73; + shfl.sync.bfly.b32 %r75|%p12, %r74, 4, 31, -1; + add.ftz.f32 %r76, %r74, %r75; + shfl.sync.bfly.b32 %r77|%p13, %r76, 2, 31, -1; + add.ftz.f32 %r78, %r76, %r77; + shfl.sync.bfly.b32 %r79|%p14, %r78, 1, 31, -1; + add.ftz.f32 %r5, %r78, %r79; + and.b32 %r6, %r132, 31; + setp.ne.b32 %p15, %r6, 0; + @%p15 bra $L__BB1_13; + shr.u32 %r80, %r132, 3; + mov.b32 %r81, _ZZ28leleka_verify_head_norm_rowsE4sums; + add.s32 %r82, %r81, %r80; + st.shared.b32 [%r82], %r5; +$L__BB1_13: + setp.ge.s32 %p16, %r132, %r9; + bar.sync 0; + shl.b32 %r83, %r6, 2; + mov.b32 %r84, _ZZ28leleka_verify_head_norm_rowsE4sums; + add.s32 %r85, %r84, %r83; + ld.shared.b32 %r86, [%r85]; + shfl.sync.bfly.b32 %r87|%p17, %r86, 16, 31, -1; + add.ftz.f32 %r88, %r86, %r87; + shfl.sync.bfly.b32 %r89|%p18, %r88, 8, 31, -1; + add.ftz.f32 %r90, %r88, %r89; + shfl.sync.bfly.b32 %r91|%p19, %r90, 4, 31, -1; + add.ftz.f32 %r92, %r90, %r91; + shfl.sync.bfly.b32 %r93|%p20, %r92, 2, 31, -1; + add.ftz.f32 %r94, %r92, %r93; + shfl.sync.bfly.b32 %r95|%p21, %r94, 1, 31, -1; + add.ftz.f32 %r96, %r94, %r95; + cvt.rn.f32.s32 %r97, %r9; + div.approx.ftz.f32 %r98, %r96, %r97; + add.ftz.f32 %r99, %r10, %r98; + rsqrt.approx.ftz.f32 %r7, %r99; + @%p16 bra $L__BB1_20; + not.b32 %r100, %r132; + add.s32 %r8, %r9, %r100; + and.b32 %r101, %r8, 3072; + setp.eq.b32 %p22, %r101, 3072; + @%p22 bra $L__BB1_17; + shr.u32 %r102, %r8, 10; + add.s32 %r103, %r102, 1; + and.b32 %r104, %r103, 3; + cvt.u64.u32 %rd27, %r132; + add.s64 %rd28, %rd4, %rd27; + add.s64 %rd29, %rd28, %rd6; + shl.b64 %rd30, %rd29, 2; + add.s64 %rd50, %rd1, %rd30; + shl.b64 %rd31, %rd28, 2; + add.s64 %rd49, %rd2, %rd31; + shl.b64 %rd32, %rd5, 2; + mul.wide.u32 %rd33, %r132, 4; + add.s64 %rd34, %rd32, %rd33; + add.s64 %rd48, %rd3, %rd34; + neg.s32 %r131, %r104; + shl.b32 %r105, %r103, 10; + and.b32 %r106, %r105, 3072; + or.b32 %r132, %r132, %r106; +$L__BB1_16: + .pragma "nounroll"; + ld.global.nc.b32 %r107, [%rd48]; + mul.ftz.f32 %r108, %r7, %r107; + ld.global.nc.b32 %r109, [%rd49]; + mul.ftz.f32 %r110, %r108, %r109; + st.global.b32 [%rd50], %r110; + add.s64 %rd50, %rd50, 4096; + add.s64 %rd49, %rd49, 4096; + add.s64 %rd48, %rd48, 4096; + add.s32 %r131, %r131, 1; + setp.ne.b32 %p23, %r131, 0; + @%p23 bra $L__BB1_16; +$L__BB1_17: + setp.lt.u32 %p24, %r8, 3072; + @%p24 bra $L__BB1_20; + shl.b64 %rd35, %rd5, 2; + cvt.u64.u32 %rd36, %r132; + mul.wide.u32 %rd37, %r132, 4; + add.s64 %rd38, %rd35, %rd37; + add.s64 %rd39, %rd38, %rd3; + add.s64 %rd53, %rd39, 8192; + add.s64 %rd40, %rd4, %rd36; + shl.b64 %rd41, %rd40, 2; + add.s64 %rd42, %rd41, %rd2; + add.s64 %rd52, %rd42, 8192; + add.s64 %rd43, %rd40, %rd6; + shl.b64 %rd44, %rd43, 2; + add.s64 %rd45, %rd44, %rd1; + add.s64 %rd51, %rd45, 8192; +$L__BB1_19: + ld.global.nc.b32 %r111, [%rd53+-8192]; + mul.ftz.f32 %r112, %r7, %r111; + ld.global.nc.b32 %r113, [%rd52+-8192]; + mul.ftz.f32 %r114, %r112, %r113; + st.global.b32 [%rd51+-8192], %r114; + ld.global.nc.b32 %r115, [%rd53+-4096]; + mul.ftz.f32 %r116, %r7, %r115; + ld.global.nc.b32 %r117, [%rd52+-4096]; + mul.ftz.f32 %r118, %r116, %r117; + st.global.b32 [%rd51+-4096], %r118; + ld.global.nc.b32 %r119, [%rd53]; + mul.ftz.f32 %r120, %r7, %r119; + ld.global.nc.b32 %r121, [%rd52]; + mul.ftz.f32 %r122, %r120, %r121; + st.global.b32 [%rd51], %r122; + ld.global.nc.b32 %r123, [%rd53+4096]; + mul.ftz.f32 %r124, %r7, %r123; + ld.global.nc.b32 %r125, [%rd52+4096]; + mul.ftz.f32 %r126, %r124, %r125; + st.global.b32 [%rd51+4096], %r126; + add.s32 %r132, %r132, 4096; + add.s64 %rd53, %rd53, 16384; + add.s64 %rd52, %rd52, 16384; + add.s64 %rd51, %rd51, 16384; + setp.lt.s32 %p25, %r132, %r9; + @%p25 bra $L__BB1_19; +$L__BB1_20: + ret; + +} + // .globl leleka_verify_head_pre_final_rows +.visible .entry leleka_verify_head_pre_final_rows( + .param .u64 .ptr .align 1 leleka_verify_head_pre_final_rows_param_0, + .param .u64 .ptr .align 1 leleka_verify_head_pre_final_rows_param_1, + .param .u64 .ptr .align 1 leleka_verify_head_pre_final_rows_param_2, + .param .u32 leleka_verify_head_pre_final_rows_param_3, + .param .u32 leleka_verify_head_pre_final_rows_param_4, + .param .f32 leleka_verify_head_pre_final_rows_param_5, + .param .u64 leleka_verify_head_pre_final_rows_param_6, + .param .u64 leleka_verify_head_pre_final_rows_param_7, + .param .u64 leleka_verify_head_pre_final_rows_param_8 +) +{ + .reg .pred %p<12>; + .reg .b32 %r<70>; + .reg .b64 %rd<73>; + + ld.param.b64 %rd16, [leleka_verify_head_pre_final_rows_param_0]; + ld.param.b64 %rd17, [leleka_verify_head_pre_final_rows_param_1]; + ld.param.s32 %rd9, [leleka_verify_head_pre_final_rows_param_3]; + ld.param.b32 %r2, [leleka_verify_head_pre_final_rows_param_4]; + ld.param.b32 %r3, [leleka_verify_head_pre_final_rows_param_5]; + ld.param.b64 %rd18, [leleka_verify_head_pre_final_rows_param_6]; + ld.param.b64 %rd19, [leleka_verify_head_pre_final_rows_param_7]; + ld.param.b64 %rd20, [leleka_verify_head_pre_final_rows_param_8]; + cvta.to.global.u64 %rd1, %rd17; + cvta.to.global.u64 %rd2, %rd16; + mov.u32 %r4, %ctaid.y; + cvt.u64.u32 %rd21, %r4; + mul.lo.s64 %rd3, %rd18, %rd21; + mul.lo.s64 %rd4, %rd19, %rd21; + mul.lo.s64 %rd5, %rd20, %rd21; + mov.u32 %r5, %ctaid.x; + mov.u32 %r6, %ntid.x; + mul.wide.u32 %rd6, %r5, %r6; + mov.u32 %r7, %tid.x; + cvt.u64.u32 %rd7, %r7; + add.s64 %rd8, %rd6, %rd7; + setp.ge.u64 %p1, %rd8, %rd9; + @%p1 bra $L__BB2_10; + setp.lt.s32 %p2, %r2, 1; + mov.b32 %r69, 0f00000000; + @%p2 bra $L__BB2_9; + and.b32 %r1, %r2, 3; + setp.lt.u32 %p3, %r2, 4; + mov.b32 %r69, 0f00000000; + mov.b32 %r68, 0; + @%p3 bra $L__BB2_6; + shl.b64 %rd22, %rd4, 2; + shl.b64 %rd23, %rd9, 2; + add.s64 %rd24, %rd22, %rd23; + add.s64 %rd10, %rd1, %rd24; + shl.b64 %rd25, %rd6, 2; + shl.b64 %rd26, %rd7, 2; + add.s64 %rd72, %rd25, %rd26; + shl.b64 %rd27, %rd9, 3; + add.s64 %rd28, %rd22, %rd27; + add.s64 %rd11, %rd1, %rd28; + mul.lo.s64 %rd29, %rd9, 12; + add.s64 %rd30, %rd22, %rd29; + add.s64 %rd12, %rd1, %rd30; + shl.b64 %rd31, %rd3, 2; + add.s64 %rd32, %rd31, %rd23; + add.s64 %rd13, %rd2, %rd32; + add.s64 %rd33, %rd31, %rd27; + add.s64 %rd14, %rd2, %rd33; + add.s64 %rd34, %rd31, %rd29; + add.s64 %rd15, %rd2, %rd34; + and.b32 %r8, %r2, 2147483644; + neg.s32 %r67, %r8; + mov.b32 %r69, 0f00000000; + mov.b32 %r68, 0; +$L__BB2_4: + .pragma "nounroll"; + shl.b64 %rd35, %rd3, 2; + add.s64 %rd36, %rd2, %rd35; + add.s64 %rd37, %rd36, %rd72; + ld.global.nc.b32 %r9, [%rd37]; + shl.b64 %rd38, %rd4, 2; + add.s64 %rd39, %rd1, %rd38; + add.s64 %rd40, %rd39, %rd72; + ld.global.b32 %r10, [%rd40]; + mul.ftz.f32 %r11, %r10, 0fBFB8AA3B; + ex2.approx.ftz.f32 %r12, %r11; + add.ftz.f32 %r13, %r12, 0f3F800000; + rcp.approx.ftz.f32 %r14, %r13; + mul.rn.ftz.f32 %r15, %r9, %r14; + st.global.b32 [%rd40], %r15; + setp.eq.b32 %p4, %r68, 0; + add.rn.ftz.f32 %r16, %r69, %r15; + selp.f32 %r17, %r15, %r16, %p4; + add.s64 %rd41, %rd13, %rd72; + ld.global.nc.b32 %r18, [%rd41]; + add.s64 %rd42, %rd10, %rd72; + ld.global.b32 %r19, [%rd42]; + mul.ftz.f32 %r20, %r19, 0fBFB8AA3B; + ex2.approx.ftz.f32 %r21, %r20; + add.ftz.f32 %r22, %r21, 0f3F800000; + rcp.approx.ftz.f32 %r23, %r22; + mul.rn.ftz.f32 %r24, %r18, %r23; + st.global.b32 [%rd42], %r24; + add.rn.ftz.f32 %r25, %r17, %r24; + add.s64 %rd43, %rd14, %rd72; + ld.global.nc.b32 %r26, [%rd43]; + add.s64 %rd44, %rd11, %rd72; + ld.global.b32 %r27, [%rd44]; + mul.ftz.f32 %r28, %r27, 0fBFB8AA3B; + ex2.approx.ftz.f32 %r29, %r28; + add.ftz.f32 %r30, %r29, 0f3F800000; + rcp.approx.ftz.f32 %r31, %r30; + mul.rn.ftz.f32 %r32, %r26, %r31; + st.global.b32 [%rd44], %r32; + add.rn.ftz.f32 %r33, %r25, %r32; + add.s64 %rd45, %rd15, %rd72; + ld.global.nc.b32 %r34, [%rd45]; + add.s64 %rd46, %rd12, %rd72; + ld.global.b32 %r35, [%rd46]; + mul.ftz.f32 %r36, %r35, 0fBFB8AA3B; + ex2.approx.ftz.f32 %r37, %r36; + add.ftz.f32 %r38, %r37, 0f3F800000; + rcp.approx.ftz.f32 %r39, %r38; + mul.rn.ftz.f32 %r40, %r34, %r39; + st.global.b32 [%rd46], %r40; + add.rn.ftz.f32 %r69, %r33, %r40; + add.s32 %r68, %r68, 4; + shl.b64 %rd47, %rd9, 4; + add.s64 %rd72, %rd72, %rd47; + add.s32 %r67, %r67, 4; + setp.ne.b32 %p5, %r67, 0; + @%p5 bra $L__BB2_4; + setp.eq.b32 %p6, %r1, 0; + @%p6 bra $L__BB2_9; +$L__BB2_6: + setp.eq.b32 %p7, %r1, 1; + @%p7 bra $L__BB2_8; + cvt.u64.u32 %rd48, %r68; + mad.lo.s64 %rd49, %rd48, %rd9, %rd8; + add.s64 %rd50, %rd49, %rd3; + shl.b64 %rd51, %rd50, 2; + add.s64 %rd52, %rd2, %rd51; + ld.global.nc.b32 %r41, [%rd52]; + add.s64 %rd53, %rd49, %rd4; + shl.b64 %rd54, %rd53, 2; + add.s64 %rd55, %rd1, %rd54; + ld.global.b32 %r42, [%rd55]; + mul.ftz.f32 %r43, %r42, 0fBFB8AA3B; + ex2.approx.ftz.f32 %r44, %r43; + add.ftz.f32 %r45, %r44, 0f3F800000; + rcp.approx.ftz.f32 %r46, %r45; + mul.rn.ftz.f32 %r47, %r41, %r46; + st.global.b32 [%rd55], %r47; + setp.eq.b32 %p8, %r68, 0; + add.rn.ftz.f32 %r48, %r69, %r47; + selp.f32 %r49, %r47, %r48, %p8; + shl.b64 %rd56, %rd9, 2; + add.s64 %rd57, %rd52, %rd56; + ld.global.nc.b32 %r50, [%rd57]; + add.s64 %rd58, %rd55, %rd56; + ld.global.b32 %r51, [%rd58]; + mul.ftz.f32 %r52, %r51, 0fBFB8AA3B; + ex2.approx.ftz.f32 %r53, %r52; + add.ftz.f32 %r54, %r53, 0f3F800000; + rcp.approx.ftz.f32 %r55, %r54; + mul.rn.ftz.f32 %r56, %r50, %r55; + st.global.b32 [%rd58], %r56; + add.rn.ftz.f32 %r69, %r49, %r56; + add.s32 %r68, %r68, 2; + and.b32 %r57, %r2, 1; + setp.ne.b32 %p9, %r57, 0; + not.pred %p10, %p9; + @%p10 bra $L__BB2_9; +$L__BB2_8: + cvt.u64.u32 %rd59, %r68; + mad.lo.s64 %rd60, %rd59, %rd9, %rd8; + add.s64 %rd61, %rd60, %rd3; + shl.b64 %rd62, %rd61, 2; + add.s64 %rd63, %rd2, %rd62; + ld.global.nc.b32 %r58, [%rd63]; + add.s64 %rd64, %rd60, %rd4; + shl.b64 %rd65, %rd64, 2; + add.s64 %rd66, %rd1, %rd65; + ld.global.b32 %r59, [%rd66]; + mul.ftz.f32 %r60, %r59, 0fBFB8AA3B; + ex2.approx.ftz.f32 %r61, %r60; + add.ftz.f32 %r62, %r61, 0f3F800000; + rcp.approx.ftz.f32 %r63, %r62; + mul.rn.ftz.f32 %r64, %r58, %r63; + st.global.b32 [%rd66], %r64; + setp.eq.b32 %p11, %r68, 0; + add.rn.ftz.f32 %r65, %r69, %r64; + selp.f32 %r69, %r64, %r65, %p11; +$L__BB2_9: + ld.param.b64 %rd71, [leleka_verify_head_pre_final_rows_param_2]; + fma.rn.ftz.f32 %r66, %r3, %r69, 0f00000000; + add.s64 %rd67, %rd5, %rd8; + cvta.to.global.u64 %rd68, %rd71; + shl.b64 %rd69, %rd67, 2; + add.s64 %rd70, %rd68, %rd69; + st.global.b32 [%rd70], %r66; +$L__BB2_10: + ret; + +} diff --git a/docs/experiments/verify-tail-and-gaps.md b/docs/experiments/verify-tail-and-gaps.md new file mode 100644 index 00000000..aabd4c5a --- /dev/null +++ b/docs/experiments/verify-tail-and-gaps.md @@ -0,0 +1,182 @@ +# Verify graph: the tail after the last layer and the idle gaps (ledger rows R6, R7, R8; switch HEAD_CHAIN_BATCH) + +Branch `claude/tail-fusion`. Analysis first (CUPTI windows, read-only on `rnr5090`), then one opt-in switch, +`LELEKA_SM120_HEAD_CHAIN_BATCH` (default off). Nothing was run on a GPU: every claim below is either read from the +CUPTI traces (marked with the window) or from code, and the expected section delta is arithmetic, not a measurement. + +## 0. Answer first + +| ledger row | what the windows show | verdict | +| --- | --- | --- | +| R6 idle inside the verify graph, 2052 against 1193 gaps, +0.094 ms | The numbers are the **verify graph only**, counted as union gaps (no kernel of the graph runs), and they reproduce exactly: control `CL.2` (one stream) 2035 gaps / 211.0 us, VANL 1194 / 119.3 us. With the side streams of the profile set (`CP.1`, `CY.1`) LEL has **1124 / 123.7 us and 1070 / 118.4 us**, i.e. +5.8 us a graph at LEL's own T mix (+2.3 .. +13.1 us at equal T). Every gap is 0.10-0.11 us in both. The loss of R6 was the single stream; the side-stream switches (V1, V3a, V3b, V4a) removed it. | closed by the side streams; residual +0.006 ms, nothing to build | +| R7 first doorbell after graph start, +0.015 ms | 21-23 kernels precede the first doorbell in both; LEL 95.6 / 105.6 / 112.5 / 121.9 / 137.4 / 149.5 us at T 1..6, VANL 93.3 / 98.6 / 114.7 / 125.8 / - / 135.3 us. | no gap to remove (-3.9 .. +14.2 us, mixed signs) | +| R8 tail after the last `add_hits`, +0.090 ms | At LEL's T mix the tail is **86.5 us** longer than VANL's (table in 3.3): hyper-connection chain of the head **31.2 us**, language-model head matmul at T >= 3 **38.4 us**, greedy pick + finite scan **18.0 us**, one extra VANL kernel -1.0 us. | the chain is a launch-count loss and is removed bitwise by the switch; matmul and pick are not launch fusion (3.4) | +| the 2052 / 1193 "per round" | not per round: per verify graph. The non-verify graphs of a round are separate: LEL 4.23 graphs, 426 kernels, 409 union gaps, 43.5 us idle; VANL 3.48 graphs, 148 kernels, 108 gaps, 11.6 us (`CP.1` and VANL windows; draft graph 113 kernels against 53, 2.2 a round). That is the draft/commit side (rows O1, O9), not the tail. | out of scope here | + +## 1. Data and method + +* LEL: `/data/leleka-e2e/spd-gap/runs/verify-ffn-d1-d2-d3-cupti-windows/CP.1/win-r29.lct` (profile set: side mixer / QSA / + shared expert, fused QSA prelude; no COMBINE_VEC4, no D1/D2/D3, so the tail is the literal one). 785 verify graphs, + T 1..8 (28 / 206 / 253 / 40 / 231 / 22 / 4 / 1). Control for R6: `verify-new-switches-cupti-windows/CL.2/win-r29.lct` + (833 graphs, one stream) and `CY.1` (profile set + new switches, 894 graphs). +* VANL: `/data/leleka-e2e/spd-gap/runs/cupti/VANL/win-r29.lct`, 893 verify graphs (T 1 / 2 / 3 / 4 / 6 = 127 / 94 / 92 / + 569 / 11; no T = 5, its row below is the mean of T = 4 and 6, marked). +* Script `scripts/e2e/codex/speed/verify_tail_report.py` (`extract`, then `compare`; stdlib, reads `lct.py`). Verify graph = + at least 900 kernels per correlation id, first and last two dropped; T = grid of the CPU-row copy kernel / 10; tail = + every kernel that starts at or after the end of the last `add_hits`; the head matmul is the longest kernel of the tail. + Every number is a p50 per T unless it says weighted. "Weighted" = the per-T difference summed over LEL's own T mix + (780 graphs), the only mix both sides can be compared at. + +## 2. The idle gaps (R6, R7) + +Union gaps and idle time inside one verify graph (p50 per T): + +| T | LEL `CP.1` gaps / idle us | VANL gaps / idle us | difference idle us | +| --- | --- | --- | --- | +| 1 | 1135 / 124.8 | 1203 / 122.0 | +2.8 | +| 2 | 1069 / 118.2 | 1167 / 115.9 | +2.3 | +| 3 | 1095 / 120.3 | 1166 / 115.7 | +4.6 | +| 4 | 1156 / 126.6 | 1200 / 119.8 | +6.7 | +| 5 | 1175 / 128.9 | - (mean of T 4, 6: 119.2) | +9.7 (interpolated) | +| 6 | 1194 / 131.6 | 1198 / 118.6 | +13.1 | +| all graphs (mean) | 1124 / 123.7 | 1194 / 119.3 | weighted +5.8 | +| control `CL.2`, one stream | 2035 / 211.0 | | R6's LEL column | + +The R6 cell (0.213 against 0.119 ms) is the single-stream control against VANL. The profile windows have three streams in +the verify graph for LEL (`CP.1`, `CY.1`), like VANL, and the gap time of a graph is then the time the critical path waits +for a dependent launch: about 0.10 us per serial edge. What is left (+0.006 ms weighted) grows with T, i.e. with the number +of serial edges of the per-token head chain below; it is not a separate loss. + +First doorbell (R7), kernels before it and its start from the graph start, p50: LEL 23 kernels and 95.6 / 105.6 / 112.5 / +121.9 / 137.4 / 149.5 us at T 1..6; VANL 21-23 kernels and 93.3 / 98.6 / 114.7 / 125.8 / - / 135.3 us. The difference is +inside the T-dependent embedding and mixer work of the first layer, with mixed signs: nothing to fuse. + +## 3. The tail (R8) + +### 3.1 Kernel sequence after the last `add_hits` (T = 3, p50 duration us, gap before us) + +LEL (22 launches, 415.6 us) and VANL (10 launches, 352.9 us): + +| LEL | dur | gap | VANL | dur | gap | +| --- | ---: | ---: | --- | ---: | ---: | +| `mtp_full_combine` | 1.44 | 0.48 | combine (vec4) | 1.12 | 0.48 | +| `mtp_full_native_write` x 3 | 0.83 / 0.77 / 0.74 | 0.10 | `post` (all rows) | 0.90 | 0.10 | +| `mtp_full_gr_norm`, `mmvf256`, `down_silu`, `mmvf160`, `pre_final` **x 3** | 17.5 + 13.3 + 13.3 | 0.10 each | hyper-connection split, down, up (three `GrMulti` kernels, one multi-token read) | 2.69 + 10.11 + 7.94 | 0.10 | +| `head_quant` | 0.86 | 0.10 | quantize | 0.86 | 0.10 | +| | | | an extra kernel (`Q81Block const*, int*, int*, float*`) | 0.96 | 0.10 | +| `head_n14_t3_large` | 338.5 | 0.10 | head matmul `F::Block` | 319.9 | 0.10 | +| `chain_sampler_greedy_kernel` (grid T, 1024 threads) | 25.9 | -0.10 | `sampler_greedy_cluster_kernel` (grid 8 x T) + `logits_nonfinite` | 4.5 + 2.8 | -0.10 | + +Launches in the tail by T: LEL 10 / 16 / 22 / 28 / 34 / 40 at T 1..6 (6 T + 4), VANL 9 / 10 / 10 / 10 / - / 10. Gaps inside +the tail are 0.10 us per launch: 1.3 .. 4.1 us in LEL, 1.1 .. 1.3 us in VANL. At T = 1 the hyper-connection chain and the matmul are the same (20.5 against 21.8 us, 310.2 against 310.5); the +tail differs there only by the pick (24.5 against 6.8 us). + +### 3.2 Why the LEL head chain is per token + +`plan_head_mix` (`original_verify_window_gr/plan_hc_read.rs`) launches the native `lm_head_mix` once per row: `mtp_full_gr_norm`, +`bf16_gemv` (down, `mtp_full_mmvf256`), `mtp_full_down_silu`, `bf16_gemv` (up, `mtp_full_mmvf160`), `mtp_full_pre_final`, and +the last layer's `plan_final_write` adds one `mtp_full_native_write` a row: **6 T launches**, each 0.7 .. 7 us and latency +bound. VANL does one multi-token hyper-connection read (`output_hc_*` read as three launches), which is what +`LELEKA_SM120_HEAD_MIX_MULTI` ports; that switch changes the summation order and is not bitwise (25 of 2057 rows moved), so +it stays off. The loss is therefore the launch count of a per-token chain, not the arithmetic. + +### 3.3 Where the 86.5 us go (LEL minus VANL, p50 per T, weighted at LEL's T mix; `compare` output) + +| section | T1 | T2 | T3 | T4 | T5 (VANL mean of 4, 6) | T6 | weighted | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| tail total | +16.2 | +23.4 | +62.7 | +88.8 | +162.0 | +246.2 | **86.5** | +| hyper-connection chain (last `add_hits` to the head quantize) | -1.3 | +12.7 | +26.6 | +38.9 | +52.2 | +64.8 | **31.2** | +| head matmul (`head_n14_tN_large` against VANL's kernel) | -0.3 | -6.6 | +18.6 | +32.5 | +93.8 | +165.8 | **38.4** | +| greedy pick + finite scan | +17.7 | +18.2 | +18.6 | +18.3 | +17.3 | +16.2 | **18.0** | +| the extra VANL kernel before the matmul | 0 | -0.9 | -1.0 | -1.0 | -1.2 | -1.3 | -1.0 | +| head quantize | +0.1 | 0 | 0 | 0 | 0 | 0 | 0 | + +The sum of the sections reproduces R8's +0.090 ms (86.5 us). LEL's weighted tail is 453.9 us, VANL's at that mix 367.3 us. + +### 3.4 What can be removed, and how + +| part | weighted | bitwise route | done here | +| --- | ---: | --- | --- | +| hyper-connection chain, `6 T` launches | 31.2 us | yes: same per-row kernels, row as `blockIdx.y`; the multi-column gemv has the same per-column fma chain | **yes, the switch** | +| greedy pick: `chain_sampler_greedy_kernel` is one block of 1024 threads a token (25 us, 1 MB read at ~40 GB/s); VANL splits a token over 8 blocks (4.2-6.6 us) | up to 20 us (25.3 -> ~5 plus a merge) | yes: argmax with lowest-index ties is independent of the split, NaN never wins (`s > bv`), penalties are not used in the verify graph (`Address(0)` history). Needs a small scratch for the partials in `OriginalNativeHeadRows` (native_head, outside this scope) | no | +| head matmul at T >= 3: LEL uses the "exact" multi-column layout (1 row a block, 4 warps; `multi_exact`, Original mode17), so 248,320 blocks; VANL 15,520 .. 62,080 blocks | 38.4 us | the existing `_upstream` kernels are NOT bitwise (the cross-warp reduction groups the sums differently). The sealed `head_n14_tN_small` kernels (4 rows a block, the per-row program unchanged by the source comment of `native_head_native.cu`) are the cheap experiment: a dispatch change in `native_head/dispatch.rs` for kind 14, T >= 3; unmeasured | no | +| 2.8 us finite scan | in the 18.0 | `LELEKA_SM120_ACCEPT_ON_DEVICE` already puts it in the graph (off; no sign in CA.1) | no | + +## 4. The switch `LELEKA_SM120_HEAD_CHAIN_BATCH` + +Resolved in `original_verify_window_sm120.rs` (`Sm120Switches::head_chain_batch`, `DEFAULT_ON_HEAD_CHAIN_BATCH = false`, below +12.x never taken), carried to the planners in `GrConfig::head_chain_batch` (like U5a's `down_fused`; decided in +`prepare` before the assets load, so a requested switch whose PTX is not sealed fails the recording by name). + +* **Final residual write.** `plan_final_write` of a group with >= 2 rows is ONE launch of `leleka_verify_final_write_rows` + (grid `[40, rows]`), in place, instead of `mtp_full_native_write` a row. +* **Head mix.** `plan_head_mix` with >= 2 rows is FIVE launches, whatever T: + `leleka_verify_head_norm_rows` (grid `[4, T]`, 1024 threads) -> sealed `bf16_f32_mmvf_multi_kernel<256, 4|8>` (down) -> + existing `mtp_full_down_silu` over the T x 320 contiguous `lo` floats -> sealed `bf16_f32_mmvf_multi_kernel<160, 4|8>` (up) + -> `leleka_verify_head_pre_final_rows` (grid `[10, T]`). +* One row keeps the literal launches. With `HEAD_MIX_MULTI` also on, the planner takes `plan_head_mix_multi` and only the + residual write is batched. `head_quant`, the head matmul and the pick are unchanged. +* Launches a graph: `6 T` -> `6` (one group; with two groups the writes are 2): `-(6 T - 6)`, 12 / 18 / 24 / 30 at T = 3 / 4 / + 5 / 6, about 15 at the mean T = 3.6 of the replay. + +**Why it is bitwise.** The three new kernels are the bodies of `mtp_full_native_write`, `mtp_full_gr_norm` and +`mtp_full_pre_final` with `blockIdx.y` as the row and the per-row bases added as arguments; no instruction order changes. They +are compiled with `--fmad=true --use_fast_math`, the flags the two originals were resealed with (extra-seal-plan group +`reseal-fastmath`), so `expf`, `rsqrtf` and the divisions lower to the same approximate PTX. The unit test +`the_batched_kernels_use_the_arithmetic_of_the_kernels_they_batch` compares the float instruction sequence of each new entry with +the sealed original: identical for the write (7 instructions) and the norm (64), per loop iteration for the pre-final mix (the +originals' loop is unrolled differently, the iteration `mul.ftz, ex2.approx.ftz, add.ftz, rcp.approx.ftz, mul.rn.ftz, add.rn.ftz, +selp` is the same). The gemv is the existing multi-column kernel: `acc[k] = fma(w1, x1, fma(w0, x0, acc[k]))` over the same +pairs, the same shared-memory reset and the same warp tree as the single-column kernel, for each column k < T. The silu is +element-wise on contiguous slots. All of these are the facts the model-free probe checks on the GPU (section 6). + +**Not touched.** The arithmetic of the head's hyper-connection read (the thing `HEAD_MIX_MULTI` changed), `head_quant`, the matmul, +the argmax, `executor_prefill*`, the profile JSONs, `original_verify_window_gpu_plan*`. + +### Files + +New: `crates/cuda-driver/src/sm120_head_chain.{cu,ptx}` (nvcc 13.2.86 in WSL: `--ptx -O3 -arch=sm_120 -std=c++17 --fmad=true +--use_fast_math`, sha256 `6c9f80f9617d90ed637164621093aaa31ed67892fbcb03491f6eb076fb405ea8`), +`original_verify_window_gr/head_chain.rs` (asset, resolve, the two plans), `original_verify_window_gr/tests/head_chain_launches.rs`, +`original_verify_window_planner/tests/head_chain_batch.rs`, `tools/decode-sm120/sm120_probe_head_chain.cpp` + +`build_head_chain.sh`, `scripts/e2e/codex/speed/verify_tail_report.py`. Edited (a few lines each): `original_verify_window_sm120.rs` (switch, own +block), `original_verify_window_gr.rs` (field, module), `.../gr/assets.rs`, `.../gr/plan_hc_read.rs` (two dispatch lines), +`.../ops/all_window_assets.rs` (resolve + asset), `scripts/gpu-bringup/extra-seal-plan.json`, `ptx-sm86/MANIFEST.json` ("not built +for sm_86 by design"). + +## 5. Expected section delta (arithmetic, not a claim) + +Per extra row the literal chain pays (p50 of `CP.1`): write 0.8 + norm 1.9 + down gemv 3.7 + silu 0.7 + up gemv 5.8 + pre-final +1.2 = 14.1 us of kernels and 6 x 0.10 us of gaps = **14.7 us**. The batched chain pays for the first row what T = 1 pays (20.5 us +from the last `add_hits` to the head quantize) plus the wider kernels. Upper bound of the saving of the section "hyper-connection +chain" is therefore 14.7 x (T - 1) = 14.7 / 29.4 / 44.1 / 58.8 / 73.5 us at T 2..6, **35 us weighted at LEL's T mix** (mean T - 1 = +2.39); the lower bound is what the wider kernels give back (the up gemv has T x 10,240 block-rows of work and is throughput +bound, so not all of its 5.8 us per row disappears). My expectation is 0.02 .. 0.035 ms a graph, which would close 22 .. 39 % of +R8's 0.090 ms. VANL parity for this section would be 31.2 us weighted. The matmul (38.4) and pick (18.0) stay. + +## 6. What the orchestrator should look at + +* **Probe** (model-free, on the GPU; built in WSL, not run): + `tools/decode-sm120/build_head_chain.sh [OUTDIR]` then `OUTDIR/sm120_probe_head_chain OUTDIR/ptx`. It runs the literal six + kernels a row against the batched launches for T = 1..8, three seeds (small, large, special values: -0.0, denormals, inf, + nan), the write also for groups starting at row 1..7; every byte of R, xn, lo, gated and mixed is compared (buffers start + as 0xCD, so a stray write shows). Expected: `SUMMARY failures=0`. +* **Identity**: set only `LELEKA_SM120_HEAD_CHAIN_BATCH=1` (alone, then with the profile set) and run the teacher-forced + top-16 + draft trace job: rows must be bit-identical, A/A first. +* **CUPTI window**, per T within one variant (the tail section of `verify_tail_report.py`): launches in the tail 6 T + 4 -> 10 + (one group); kernels `mtp_full_native_write`, `mtp_full_gr_norm`, `mtp_full_mmvf256`, `mtp_full_down_silu`, `mtp_full_mmvf160`, + `mtp_full_pre_final` drop to 0 (they stay elsewhere: `mmvf256` / `down_silu` in the PLE and projection paths), and + `leleka_verify_final_write_rows` 1, `leleka_verify_head_norm_rows` 1, `leleka_verify_head_pre_final_rows` 1, + `bf16_f32_mmvf_multi_kernel<256, 4|8>` +1, `bf16_f32_mmvf_multi_kernel<160, 4|8>` +1 come. The section to compare is "last + `add_hits` end to the start of `head_quant`" (`hc` in the report): 35.7 / 50.4 / 65.8 / 81.3 / 96.1 us at T 2..6 in `CP.1`, + 20.5 at T 1. Note the window of the control and of the variant must be separate sessions with their own T mix: compare per T. +* The engine log prints `leleka-serve head chain batch: on` once when the switch resolved. + +## 7. Not finished / next + +* Greedy pick (18.0 us weighted, bitwise, needs a scratch buffer in `OriginalNativeHeadRows`) and the head matmul at T >= 3 + (38.4 us, first experiment: the `_small` 4-rows-a-block kernels of kind 14) are the larger remaining parts of R8 and + are not launch-count fusion; both are outside the files of this step. +* The probe and the identity run need the GPU; the PTX is built (nvcc 13.2.86 in WSL) and byte-pinned. +* Ledger rows to update after the orchestrator's windows: R6 (closed by side streams, residual +0.006 ms), R7 (no gap), R8 (this + decomposition; the switch as the fix for the 31.2 us part). diff --git a/scripts/e2e/codex/speed/verify_tail_report.py b/scripts/e2e/codex/speed/verify_tail_report.py new file mode 100644 index 00000000..4d4cf33e --- /dev/null +++ b/scripts/e2e/codex/speed/verify_tail_report.py @@ -0,0 +1,157 @@ +"""The tail of the verify graph and the idle gaps inside it (ledger rows R6, R7, R8; docs/experiments/verify-tail-and-gaps.md). + +Offline analysis of CUPTI trace directories (tools/cupti-trace, `lct.py`); host-side Python, stdlib only, no GPU. + + extract TRACE_DIR LABEL [--lct DIR] (python3 -B; reads the trace, writes JSON on stdout) + per window row count T (the grid of the CPU-row copy kernel / 10) of every verify graph (>= 900 kernels per + correlation id, first and last two dropped): graphs, union gaps and idle, first doorbell, and the tail after the + last `add_hits` end split into the hyper-connection part (to the head quantize), the quantize, what sits between it and the + language-model head matmul (the longest kernel of the tail), the matmul and what follows it (greedy pick, finite scan); the kernel sequence + of the tail (p50 duration and gap before each launch); the non-verify graphs per round. + compare LEL.json VANL.json (markdown on stdout) + per T the differences of the tail sections, and the sum over LEL's own T mix (VANL's T without graphs, here T=5, is + the mean of its neighbours). + +A union gap is an interval inside a graph where no kernel of the graph runs (first start to last end). `--lct` defaults +to /data/leleka-e2e/decode/tools (read only). +""" +import argparse +import collections +import json +import sys + +SECTIONS = ("total", "hc", "quant", "misc", "matmul", "post") + + +def p50(values): + v = sorted(values) + return v[len(v) // 2] if v else float("nan") + + +def union_gaps(ks): + cur, gaps = ks[0].end, [] + for k in ks[1:]: + if k.start > cur: + gaps.append(k.start - cur) + cur = max(cur, k.end) + return gaps + + +def window_rows(ks, name): + rows = collections.Counter(k.gx // 10 for k in ks if "copy_rows" in name(k)) + return rows.most_common(1)[0][0] if rows else -1 + + +def tail_of(ks, name): + """(anchor end, kernels from the last add_hits end on); with HITS_IN_COMBINE the anchor is the last combine.""" + hits = [k for k in ks if "add_hi" in name(k)] + if hits: + a = max(hits, key=lambda k: k.end).end + else: + a = max((k for k in ks if "combine" in name(k)), key=lambda k: k.start).start - 1 + return a, [k for k in ks if k.start >= a] + + +def sections(ks, name): + a, tail = tail_of(ks, name) + end = max(k.end for k in ks) + mm = max(range(len(tail)), key=lambda i: tail[i].end - tail[i].start) + q = next((i for i in range(mm - 1, max(mm - 4, -1), -1) if "quant" in name(tail[i])), mm - 1) + dur = lambda k: (k.end - k.start) / 1e3 # noqa: E731 + return {"total": (end - a) / 1e3, "hc": (tail[q].start - a) / 1e3, "quant": dur(tail[q]), + "misc": (tail[mm].start - tail[q].end) / 1e3, "matmul": dur(tail[mm]), "post": (end - tail[mm].end) / 1e3} + + +def sequence(graphs, name): + """The p50 duration and gap before each launch of the most common tail length.""" + tails = [tail_of(ks, name) for ks in graphs] + length = collections.Counter(len(t) for _, t in tails).most_common(1)[0][0] + good = [(a, t) for a, t in tails if len(t) == length] + out = [] + for i in range(length): + d = [(t[i].end - t[i].start) / 1e3 for _, t in good] + g = [(t[i].start - (t[i - 1].end if i else a)) / 1e3 for a, t in good] + out.append({"name": name(good[0][1][i])[-60:], "dur": p50(d), "gap": p50(g), "grid": [good[0][1][i].gx, good[0][1][i].gy]}) + return out + + +def per_t(graphs, name): + d = {"n": len(graphs), "kernels": p50([len(ks) for ks in graphs]), "streams": p50([len({k.stream for k in ks}) for ks in graphs])} + gaps = [union_gaps(ks) for ks in graphs] + d["union_gaps"] = p50([len(g) for g in gaps]) + d["idle_us"] = p50([sum(g) / 1e3 for g in gaps]) + doors = [(db[0].start - ks[0].start) / 1e3 for ks in graphs for db in [[k for k in ks if "doorbell" in name(k)]] if db] + d["first_doorbell_us"] = p50(doors) + secs = [sections(ks, name) for ks in graphs] + d.update({s: round(p50([x[s] for x in secs]), 2) for s in SECTIONS}) + d["tail_launches"] = collections.Counter(len(tail_of(ks, name)[1]) for ks in graphs).most_common(1)[0][0] + d["sequence"] = sequence(graphs, name) + return d + + +def extract(path, label, lct_dir): + sys.path.insert(0, lct_dir) + sys.dont_write_bytecode = True + import lct + t = lct.Trace(path) + name = lambda k: t.names.get(k.name, "?") # noqa: E731 + by = collections.defaultdict(list) + for k in t.kernels: + by[k.corr].append(k) + big = sorted((c for c, v in by.items() if len(v) >= 900), key=lambda c: min(k.start for k in by[c])) + kept = [sorted(by[c], key=lambda k: k.start) for c in big[2:-2]] + groups = collections.defaultdict(list) + for ks in kept: + groups[window_rows(ks, name)].append(ks) + rest = [union_gaps(sorted(v, key=lambda k: k.start)) for c, v in by.items() if 2 <= len(v) < 900] + return {"label": label, "graphs": len(kept), "T": {str(T): per_t(g, name) for T, g in sorted(groups.items())}, + "non_verify_per_round": {"graphs": len(rest) / len(kept), "union_gaps": sum(map(len, rest)) / len(kept), + "idle_us": sum(sum(g) for g in rest) / 1e3 / len(kept)}} + + +def filled(vanl): + """VANL per T with the missing Ts filled by the mean of the neighbours that exist.""" + have = sorted(int(t) for t in vanl["T"]) + out = {} + for T in range(1, 9): + if str(T) in vanl["T"]: + out[T] = vanl["T"][str(T)] + elif have[0] < T < have[-1]: + lo, hi = max(t for t in have if t < T), min(t for t in have if t > T) + a, b = vanl["T"][str(lo)], vanl["T"][str(hi)] + out[T] = {s: (a[s] + b[s]) / 2 for s in SECTIONS + ("idle_us", "union_gaps")} + return out + + +def compare(lel, vanl): + v = filled(vanl) + mix = {int(T): d["n"] for T, d in lel["T"].items() if int(T) in v} + total = sum(mix.values()) + print("| section (LEL - VANL, us) | " + " | ".join("T%d" % T for T in mix) + " | weighted at LEL's T mix |") + print("| --- |" + " ---: |" * (len(mix) + 1)) + for s in SECTIONS + ("idle_us", "union_gaps"): + diffs = {T: lel["T"][str(T)][s] - v[T][s] for T in mix} + w = sum(mix[T] * diffs[T] for T in mix) / total + print("| %s | %s | %.1f |" % (s, " | ".join("%+.1f" % diffs[T] for T in mix), w)) + print("graphs per T (LEL): %s" % mix) + + +def main(): + ap = argparse.ArgumentParser() + sub = ap.add_subparsers(dest="cmd", required=True) + e = sub.add_parser("extract") + e.add_argument("trace") + e.add_argument("label") + e.add_argument("--lct", default="/data/leleka-e2e/decode/tools") + c = sub.add_parser("compare") + c.add_argument("lel") + c.add_argument("vanl") + a = ap.parse_args() + if a.cmd == "extract": + json.dump(extract(a.trace, a.label, a.lct), sys.stdout, indent=1) + else: + compare(json.load(open(a.lel)), json.load(open(a.vanl))) + + +if __name__ == "__main__": + main() diff --git a/scripts/gpu-bringup/extra-seal-plan.json b/scripts/gpu-bringup/extra-seal-plan.json index 7eb39823..606f5e92 100644 --- a/scripts/gpu-bringup/extra-seal-plan.json +++ b/scripts/gpu-bringup/extra-seal-plan.json @@ -1183,6 +1183,32 @@ }, "group": "sm120-decode", "optional": false + }, + { + "cu": "crates/cuda-driver/src/sm120_head_chain.cu", + "ptx": "crates/cuda-driver/src/sm120_head_chain.ptx", + "flags": [ + "--ptx", + "-O3", + "-arch=sm_120", + "-std=c++17", + "--fmad=true", + "--use_fast_math" + ], + "policy": "fast-math (--fmad=true --use_fast_math: the flags mtp_original_full_gr_norm.cu and mtp_original_full_gr_post.cu were resealed with, extra-seal-plan group reseal-fastmath, because the batched kernels are their bodies and expf, rsqrtf and the divisions must lower to the same approximate PTX; claude/tail-fusion: LELEKA_SM120_HEAD_CHAIN_BATCH, the residual write, the head norm and the pre-final mix of all window rows as grid.y = row). Self-contained: cuda_runtime.h only, so it takes no include profile", + "entries": [ + "leleka_verify_final_write_rows", + "leleka_verify_head_norm_rows", + "leleka_verify_head_pre_final_rows" + ], + "encoding": "concat_include_str", + "rust_fields_to_fill": { + "crates/cuda-driver/src/original_verify_window_gr/head_chain.rs": [ + "HEAD_CHAIN.sha" + ] + }, + "group": "sm120-decode", + "optional": false } ] } diff --git a/tools/decode-sm120/build_head_chain.sh b/tools/decode-sm120/build_head_chain.sh new file mode 100644 index 00000000..3e44b096 --- /dev/null +++ b/tools/decode-sm120/build_head_chain.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Build the HEAD_CHAIN_BATCH probe in WSL (never on the server) and collect the PTX it compares. +# tools/decode-sm120/build_head_chain.sh [OUTDIR] default OUTDIR=$HOME/sm120-head-chain-bin ; then: OUTDIR/sm120_probe_head_chain OUTDIR/ptx +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/../.." && pwd)" +out="${1:-$HOME/sm120-head-chain-bin}" +nvcc="${NVCC:-$HOME/cuda-toolkits/13.2.2/bin/nvcc}" +mkdir -p "$out/ptx" +"$nvcc" -O2 -std=c++17 "$here/sm120_probe_head_chain.cpp" -lcuda -o "$out/sm120_probe_head_chain" +for f in mtp_original_full_gr_post mtp_original_full_gr_norm mtp_original_full_bf16 sm120_head_chain; do + cp "$root/crates/cuda-driver/src/$f.ptx" "$out/ptx/$f.ptx" +done +sha256sum "$out"/sm120_probe_head_chain "$out"/ptx/* > "$out/SHA256SUMS" +ls -la "$out" "$out/ptx" diff --git a/tools/decode-sm120/sm120_probe_head_chain.cpp b/tools/decode-sm120/sm120_probe_head_chain.cpp new file mode 100644 index 00000000..39795590 --- /dev/null +++ b/tools/decode-sm120/sm120_probe_head_chain.cpp @@ -0,0 +1,198 @@ +// claude/tail-fusion: model-free probe of LELEKA_SM120_HEAD_CHAIN_BATCH (docs/experiments/verify-tail-and-gaps.md). +// The literal tail of the verify graph, per window row t, +// mtp_full_native_write R_t = bo_t * (2 sigmoid(inject)) + R_t (mtp_original_full_gr_post.ptx) +// mtp_full_gr_norm xn_t = norm(R_t) * gamma (mtp_original_full_gr_norm.ptx) +// mtp_full_mmvf256 lo_t = down . xn_t (mtp_original_full_bf16.ptx) +// mtp_full_down_silu lo_t = silu(lo_t / 4) (mtp_original_full_gr_post.ptx) +// mtp_full_mmvf160 gated_t = up . lo_t (mtp_original_full_bf16.ptx) +// mtp_full_pre_final gated_t = xn_t * sigmoid(gated_t); mixed_t = sum / 4 +// is run against the batched launches of the switch (sm120_head_chain.ptx: leleka_verify_final_write_rows, +// leleka_verify_head_norm_rows, leleka_verify_head_pre_final_rows; the sealed bf16_f32_mmvf_multi_kernel<256|160, 4|8>; +// mtp_full_down_silu over the T * 320 contiguous floats) on real-size random inputs, for T = 1..8 rows, three seeds +// (small, large and special values: -0.0, denormals, inf, nan in the residual, block output and weights), the write also +// for a group that starts at row 1..7 of the arena. EVERY byte of R, xn, lo, gated (the parts slots) and mixed is +// compared, so a stray write outside the rows shows too (buffers start as 0xCD). 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_head_chain.sh), not run. +// sm120_probe_head_chain PTXDIR PTXDIR holds mtp_original_full_gr_post.ptx, mtp_original_full_gr_norm.ptx, +// mtp_original_full_bf16.ptx and sm120_head_chain.ptx (build_head_chain.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, HC = 4, LR = 320, D = N * HC, K = 10, MAXT = 8; +static const float QUARTER = 0.25f, EPS = 1e-6f; +static const char* MULTI_FMT = "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi%dELi%dEEEvPKflPKtPflii"; + +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)); CU(cuMemsetD8(p, 0xCD, bytes)); } + void put(const void* h, size_t bytes) { CU(cuMemcpyHtoD(p, h, bytes)); } + std::vector get() const { std::vector v(n); CU(cuCtxSynchronize()); CU(cuMemcpyDtoH(v.data(), p, n)); return v; } +}; +static bool same(const char* what, const std::vector& a, const std::vector& b) { + 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)); +} +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; } +} + +struct Fns { + CUfunction write, norm, mmvf256, mmvf160, silu, pre_final; // the literal kernels + CUfunction write_rows, norm_rows, pre_final_rows, multi256[2], multi160[2]; // the batched ones (multi: NT 4, 8) +}; + +// One case: T rows, the write for rows [first, first + T) of an 8-row arena, the head chain for rows [0, T). +static void run_case(const Fns& f, int seed, int tokens, int first) { + const float mag = seed == 1 ? 1e3f : 1.0f; + const bool specials = seed == 2; + std::vector r((size_t)MAXT * D), bo((size_t)MAXT * N), inj((size_t)MAXT * HC), gamma(D); + std::vector down((size_t)LR * D), up((size_t)D * LR); + for (auto& v : r) v = rndf() * mag; + for (auto& v : bo) v = rndf() * mag; + for (auto& v : inj) v = rndf() * 4.0f; + for (auto& v : gamma) v = rndf() * 2.0f; + for (auto& v : down) v = (uint16_t)(((rnd() & 0x7f00) | (rnd() & 0xff)) | ((rnd() & 1) << 15)); // bf16, small exponents + for (auto& v : up) v = (uint16_t)(((rnd() & 0x3f00) | (rnd() & 0xff)) | ((rnd() & 1) << 15)); + if (specials) { + for (size_t i = 0; i < r.size(); i += 997) r[i] = special(rnd()); + for (size_t i = 0; i < bo.size(); i += 389) bo[i] = special(rnd()); + for (size_t i = 0; i < gamma.size(); i += 211) gamma[i] = special(rnd()); + for (size_t i = 0; i < inj.size(); i += 5) inj[i] = special(rnd()) * 3.0f; + } + Dev dr[2], dbo, dinj, dgamma, ddown, dup, dxn[2], dlo[2], dgate[2], dmix[2]; + for (int a = 0; a < 2; ++a) { + dr[a].alloc(r.size() * 4); dxn[a].alloc((size_t)MAXT * D * 4); dlo[a].alloc((size_t)MAXT * LR * 4); + dgate[a].alloc((size_t)MAXT * K * N * 4); dmix[a].alloc((size_t)MAXT * N * 4); + dr[a].put(r.data(), r.size() * 4); + } + dbo.alloc(bo.size() * 4); dbo.put(bo.data(), bo.size() * 4); + dinj.alloc(inj.size() * 4); dinj.put(inj.data(), inj.size() * 4); + dgamma.alloc(gamma.size() * 4); dgamma.put(gamma.data(), gamma.size() * 4); + ddown.alloc(down.size() * 2); ddown.put(down.data(), down.size() * 2); + dup.alloc(up.size() * 2); dup.put(up.data(), up.size() * 2); + int n = N, hc = HC, lr = LR, d = D, count = tokens * LR; + float quarter = QUARTER, eps = EPS; + + // literal arm: the write of the group's rows, then the five kernels per row from row 0 + for (int t = first; t < first + tokens; ++t) { + CUdeviceptr R = dr[0].p + (size_t)t * D * 4, B = dbo.p + (size_t)t * N * 4, I = dinj.p + (size_t)t * HC * 4; + void* a[] = {&R, &B, &I, &R, &n, &hc, &quarter}; + launch(f.write, (D + 255) / 256, 1, 256, a); + } + for (int t = 0; t < tokens; ++t) { + CUdeviceptr R = dr[0].p + (size_t)t * D * 4, XN = dxn[0].p + (size_t)t * D * 4, LO = dlo[0].p + (size_t)t * LR * 4; + CUdeviceptr G = dgate[0].p + (size_t)t * K * N * 4, M = dmix[0].p + (size_t)t * N * 4; + void* a_norm[] = {&R, &dgamma.p, &XN, &n, &eps}; + launch(f.norm, HC, 1, 1024, a_norm); + void* a_down[] = {&XN, &ddown.p, &LO, &d}; + launch(f.mmvf256, LR, 1, 256, a_down); + void* a_silu[] = {&LO, &lr, &quarter}; + launch(f.silu, (LR + 255) / 256, 1, 256, a_silu); + void* a_up[] = {&LO, &dup.p, &G, &lr}; + launch(f.mmvf160, D, 1, 160, a_up); + void* a_pre[] = {&XN, &G, &M, &n, &hc, &quarter}; + launch(f.pre_final, (N + 255) / 256, 1, 256, a_pre); + } + + // batched arm + { + CUdeviceptr R = dr[1].p + (size_t)first * D * 4, B = dbo.p + (size_t)first * N * 4, I = dinj.p + (size_t)first * HC * 4; + int64_t rs = D, bs = N, is = HC; + void* a[] = {&R, &B, &I, &n, &hc, &quarter, &rs, &bs, &is}; + launch(f.write_rows, (D + 255) / 256, (unsigned)tokens, 256, a); + } + { + CUdeviceptr R = dr[1].p, XN = dxn[1].p, LO = dlo[1].p, G = dgate[1].p, M = dmix[1].p; + int64_t ds = D, ls = LR, gs = (int64_t)K * N, ms = N; + int nt = tokens; + const int slot = tokens <= 4 ? 0 : 1; + void* a_norm[] = {&R, &dgamma.p, &XN, &n, &eps, &ds, &ds}; + launch(f.norm_rows, HC, (unsigned)tokens, 1024, a_norm); + void* a_down[] = {&XN, &ds, &ddown.p, &LO, &ls, &d, &nt}; + launch(f.multi256[slot], LR, 1, 256, a_down); + void* a_silu[] = {&LO, &count, &quarter}; + launch(f.silu, (unsigned)((count + 255) / 256), 1, 256, a_silu); + void* a_up[] = {&LO, &ls, &dup.p, &G, &gs, &lr, &nt}; + launch(f.multi160[slot], D, 1, 160, a_up); + void* a_pre[] = {&XN, &G, &M, &n, &hc, &quarter, &ds, &gs, &ms}; + launch(f.pre_final_rows, (N + 255) / 256, (unsigned)tokens, 256, a_pre); + } + const bool ok_r = same("R (residual write)", dr[0].get(), dr[1].get()); + const bool ok_xn = same("xn (head norm)", dxn[0].get(), dxn[1].get()); + const bool ok_lo = same("lo (down gemv + silu)", dlo[0].get(), dlo[1].get()); + const bool ok_g = same("gated (up gemv + pre-final gate)", dgate[0].get(), dgate[1].get()); + const bool ok_m = same("mixed", dmix[0].get(), dmix[1].get()); + printf("RESULT head_chain seed=%d T=%d first=%d identical_R=%d identical_xn=%d identical_lo=%d identical_gated=%d identical_mixed=%d\n", seed, tokens, first, + ok_r, ok_xn, ok_lo, ok_g, ok_m); + for (int a = 0; a < 2; ++a) for (Dev* x : {&dr[a], &dxn[a], &dlo[a], &dgate[a], &dmix[a]}) CU(cuMemFree(x->p)); + for (Dev* x : {&dbo, &dinj, &dgamma, &ddown, &dup}) CU(cuMemFree(x->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)); + CUmodule post = load_module(dir + "/mtp_original_full_gr_post.ptx"), norm = load_module(dir + "/mtp_original_full_gr_norm.ptx"); + CUmodule bf16 = load_module(dir + "/mtp_original_full_bf16.ptx"), chain = load_module(dir + "/sm120_head_chain.ptx"); + Fns f; + f.write = get_fn(post, "mtp_full_native_write"); f.silu = get_fn(post, "mtp_full_down_silu"); f.pre_final = get_fn(post, "mtp_full_pre_final"); + f.norm = get_fn(norm, "mtp_full_gr_norm"); + f.mmvf256 = get_fn(bf16, "mtp_full_mmvf256"); f.mmvf160 = get_fn(bf16, "mtp_full_mmvf160"); + f.write_rows = get_fn(chain, "leleka_verify_final_write_rows"); f.norm_rows = get_fn(chain, "leleka_verify_head_norm_rows"); + f.pre_final_rows = get_fn(chain, "leleka_verify_head_pre_final_rows"); + for (int s = 0; s < 2; ++s) { + char name[256]; + snprintf(name, sizeof name, MULTI_FMT, 256, s ? 8 : 4); f.multi256[s] = get_fn(bf16, name); + snprintf(name, sizeof name, MULTI_FMT, 160, s ? 8 : 4); f.multi160[s] = get_fn(bf16, name); + } + for (int seed = 0; seed < 3; ++seed) + for (int tokens = 1; tokens <= MAXT; ++tokens) { + run_case(f, seed, tokens, 0); + if (tokens < MAXT) run_case(f, seed, tokens, MAXT - tokens); + } + printf("SUMMARY failures=%d\n", g_fail); + return g_fail ? 1 : 0; +}