verify window: LELEKA_SM120_GR_DOWN_FUSED (hc split + tiled down projection as one launch, step U5a), off by default

New sealed sm_120 asset sm120_gr_down_fused.ptx (nvcc 13.2.86): leleka_gr_down_fused_t2w8 replaces
chain_gr_split + chain_gr_down_t2w8_nb4 (96 launches fewer per verify graph). The block stages R' * w_norm of
its two tokens into shared memory, adds the sum of squares in the split kernel's order, scales with rs and
runs the down kernel's dots; the operations and their order are those of the two kernels (bitwise by
construction; upstream's gr_down_v3 sums in another order). A no-op, said once, without the chain gr pair.
Planner, switch resolution (Sm120Switches, GrConfig.down_fused), unit tests, model-free probe
tools/gr-down-fused (not run: no GPU). Not measured. Microbench harness: the NaN outputs were a stream race
between the poison memsets and the kernels, fixed; inputs are checked finite.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-10 19:14:46 +01:00
co-authored by Claude Sonnet 5.5
parent b56e5afb58
commit 0518311567
20 changed files with 6687 additions and 5 deletions
@@ -2747,6 +2747,13 @@
"problems": [
"not built for sm_86 by design (claude/verify-gdn-fused-kernels): LELEKA_SM120_FUSED_GDN and LELEKA_SM120_GDN_AB_UNROLL are compute capability 12.0 decode switches; original_verify_window_sm120.rs enables them only on a 12.x card, so an sm_86 build never loads this module"
]
},
{
"name": "sm120_gr_down_fused.ptx",
"sm120_path": "crates/cuda-driver/src/sm120_gr_down_fused.ptx",
"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"
]
}
],
"portable_no_companion_needed": [
@@ -163,6 +163,9 @@ pub(crate) struct GrConfig {
pub attr_down: Option<u32>,
/// The same for `gr_down_staged_kernel`.
pub attr_staged: Option<u32>,
/// `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,
}
/// What every gated-residual (GR) planner reads: the arena the spans come from, the window geometry and the
@@ -344,8 +347,11 @@ use assets::row_span;
pub(crate) use assets::shared_attributes;
#[allow(unused_imports)]
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/plan_hc_read.rs"]
mod plan_hc_read;
pub(crate) use fused_down::plan_hc_read_launches;
#[allow(unused_imports)]
pub(crate) use plan_hc_read::plan_final_write;
#[allow(unused_imports)]
@@ -50,6 +50,7 @@ impl GrConfig {
// by the Original), so no attribute is emitted there
attr_down: (cc_major >= 7 && optin > 0).then_some(want),
attr_staged: (cc_major >= 7 && optin > 0).then_some(want_staged),
down_fused: false,
}
}
@@ -0,0 +1,138 @@
//! claude/u5a-gr-down-fused (step-ledger row U5a): `LELEKA_SM120_GR_DOWN_FUSED`, the hyper-connection split and the
//! tiled chain down projection of a staged read as ONE launch (`sm120_gr_down_fused.cu`).
//!
//! The chain read of a layer half is `chain_gr_split` (grid `[T, 4]`: R', sum of squares, `rs`, `xn`), then
//! `chain_gr_down_t2w8_nb4` (grid `[41, ceil(T / 2)]`: the dots on `xn`), then `chain_gr_up8`. With the switch the
//! first two are `leleka_gr_down_fused_t2w8` (the grid of the down kernel): the block stages the rows itself, adds up
//! the sum of squares of its two tokens and runs the dots, like upstream's `gr_down_v3_kernel` (mask 133). Every output
//! word is computed by the operations of the two kernels in their order (bitwise, unlike upstream's v3, which sums in
//! another order); `rs` is written by the blocks of column 0, `xn` is no longer written. 96 launches fewer in a
//! verify graph (48 layers x 2 halves).
//!
//! The switch is a no-op, and says so once, where there is no chain pair to replace: the read is not the staged
//! variant, `LELEKA_CHAIN` has no `gr` group, `LELEKA_CHAIN_DOWN=w8` is set, or the card's dynamic shared memory limit
//! is below the 81,920 bytes of two tokens. The asset is sm_120 only (`Sm120Switches`: a card below 12.x never takes
//! it) and is loaded before capture only when the switch resolved on; a requested switch whose asset is not sealed
//! fails the recording by name.
use super::super::chain;
use super::super::sm120::Sm120Switches;
use super::plan_hc_read::{hc_read_rows, hc_read_up};
#[allow(unused_imports)]
use super::*;
pub(crate) const E_GR_DOWN_FUSED: &str = "leleka_gr_down_fused_t2w8";
/// `sm120_gr_down_fused.cu` (nvcc 13.2.86, `--fmad=true --ftz=false`), sealed by `scripts/gpu-bringup/seal_pins.py`
/// (extra-seal-plan.json, group sm120-decode).
pub(crate) static GR_DOWN_FUSED: AssetSpec = AssetSpec {
name: "sm120_gr_down_fused.ptx",
ptx: concat!(include_str!("../sm120_gr_down_fused.ptx"), "\0").as_bytes(),
sha: [
199, 142, 148, 149, 154, 181, 122, 105, 95, 156, 68, 210, 189, 80, 52, 231, 101, 198, 246, 184, 110, 221, 185,
78, 195, 163, 231, 255, 127, 207, 23, 127,
],
entries: &[E_GR_DOWN_FUSED],
unsealed: "Original verifier asset unsealed: sm120_gr_down_fused.ptx (fused hc split + down projection)",
};
/// Bytes of one token's activations (`hc * n_embd` floats), all of which the fused kernel keeps in shared memory.
const TOKEN_BYTES: u32 = (D * 4) as u32;
/// Two tokens a block: the dynamic shared memory the kernel is launched with, and the limit it asks the driver for.
pub(crate) const FUSED_DOWN_MAX_SHARED: u32 = 2 * TOKEN_BYTES;
/// Grid and dynamic shared bytes of `leleka_gr_down_fused_t2w8` for `tokens` rows: the grid of the tiled down kernel
/// (41 blocks of 8 rows, grid.y = ceil(tokens / 2)), `min(tokens, 2)` tokens of activations in shared memory.
pub(crate) fn fused_down_geometry(tokens: usize) -> ([u32; 3], u32) {
([DOWN_BLOCKS, tokens.div_ceil(2) as u32, 1], tokens.min(2) as u32 * TOKEN_BYTES)
}
/// The chain pair this kernel replaces is in use: `LELEKA_CHAIN` has the `gr` group, the down kernel is the tiled one.
fn chain_pair_in_use() -> bool {
chain::flags().gr && chain::down_tiled()
}
/// What the switch comes to on this card and configuration.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum FusedDownDecision {
Off,
On,
/// Wanted, but there is nothing to replace or no room for it: the default launches run.
Refused(&'static str),
}
/// The decision for a wanted switch, from the card's GR configuration and whether the chain pair is in use.
pub(crate) fn decide(wanted: bool, cfg: &GrConfig, chain_pair: bool) -> FusedDownDecision {
if !wanted {
return FusedDownDecision::Off;
}
if cfg.variant != GrVariant::Staged {
return FusedDownDecision::Refused("the hc read is not the staged variant (STRATA_HC_SPLIT)");
}
if !chain_pair {
return FusedDownDecision::Refused("no chain split + tiled down pair (LELEKA_CHAIN gr, LELEKA_CHAIN_DOWN=w8)");
}
if cfg.usable_shared < FUSED_DOWN_MAX_SHARED {
return FusedDownDecision::Refused("the card's dynamic shared memory is below 81920 bytes");
}
FusedDownDecision::On
}
/// 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<bool> {
let major = journal.window_device_attribute(ATTR_COMPUTE_CAPABILITY_MAJOR)?;
let minor = journal.window_device_attribute(ATTR_COMPUTE_CAPABILITY_MINOR)?;
let wanted = Sm120Switches::from_env(major, minor).gr_down_fused;
let decision = decide(wanted, cfg, chain_pair_in_use());
if decision != FusedDownDecision::Off {
static SAID: std::sync::Once = std::sync::Once::new();
SAID.call_once(|| eprintln!("leleka-serve gr down fused: {decision:?} (compute capability {major}.{minor})"));
}
Ok(decision == FusedDownDecision::On)
}
/// The asset the window preloads before capture (none when the switch is off or refused).
pub(crate) fn assets(on: bool) -> Vec<&'static AssetSpec> {
if on { vec![&GR_DOWN_FUSED] } else { Vec::new() }
}
/// The `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE)` call the kernel needs once per device, to apply before capture.
pub(crate) fn shared_attributes(cfg: &GrConfig) -> Vec<(&'static AssetSpec, &'static str, usize)> {
if cfg.down_fused { vec![(&GR_DOWN_FUSED, E_GR_DOWN_FUSED, FUSED_DOWN_MAX_SHARED as usize)] } else { Vec::new() }
}
impl GrConfig {
/// This configuration with the switch resolved by `resolve`.
pub(crate) fn with_fused_down(self, on: bool) -> Self {
Self { down_fused: on, ..self }
}
}
/// The fused launch replaces the split and the down launches of a read of `n` rows.
fn uses_fused_down(cfg: &GrConfig, n: usize) -> bool {
cfg.down_fused
&& cfg.variant == GrVariant::Staged
&& chain_pair_in_use()
&& fused_down_geometry(n).1 <= cfg.usable_shared
}
/// The launches of one hc read, in graph order: `[fused down, up]` when the switch is on and applies, else the launches
/// of `plan_hc_read` (`[norm, down..., up]`). The by-value argument is the same `GrMulti` either way.
pub(crate) fn plan_hc_read_launches(
window: GrWindow<'_>,
w: &HcAddrs,
half: HcHalf,
apply: bool,
rows: Rows,
) -> Result<Vec<Launch>> {
check_rows(window.geo, rows)?;
if !uses_fused_down(window.cfg, rows.len()) {
return Ok(plan_hc_read(window, w, half, apply, rows)?.launches());
}
let n = rows.len();
let per_row = hc_read_rows(window.arena, half, rows)?;
let xn = window.arena.span("xn", rows.begin * D * 4, n * D * 4)?;
let full = multi_words(&per_row, w, apply, xn);
let (grid, shared) = fused_down_geometry(n);
let extent = LaunchExtent::new(grid, [THREADS, 1, 1], shared);
let fused = Launch::new(&GR_DOWN_FUSED, E_GR_DOWN_FUSED, extent, vec![A::Words(full.clone())])?;
Ok(vec![fused, hc_read_up(true, full)?])
}
@@ -32,7 +32,7 @@ pub(crate) fn plan_hc_read(
/// The per-row argument spans of the window rows; the attention half reads `inj2` and writes `inj`, the FFN the
/// reverse.
fn hc_read_rows(arena: &dyn ArenaMap, half: HcHalf, rows: Rows) -> Result<Vec<RowArgs>> {
pub(super) fn hc_read_rows(arena: &dyn ArenaMap, half: HcHalf, rows: Rows) -> Result<Vec<RowArgs>> {
let (inj_prev_name, inj_out_name) = match half {
HcHalf::Attention => ("inj2", "inj"),
HcHalf::Ffn => ("inj", "inj2"),
@@ -144,7 +144,7 @@ fn hc_read_down_buffered(cfg: &GrConfig, ct: usize, words: impl FnOnce() -> Vec<
Launch::new(&chain::CHAIN, entry, LaunchExtent::new(blocks, [THREADS, 1, 1], shared), vec![A::Words(words())])
}
fn hc_read_up(chain_gr: bool, full: Vec<u64>) -> Result<Launch> {
pub(super) fn hc_read_up(chain_gr: bool, full: Vec<u64>) -> Result<Launch> {
if chain_gr {
// 16 columns per block (160 blocks) with every load of the block's rows hoisted; chain_gr_up8 (320 blocks)
// is the alternative shape
@@ -58,6 +58,8 @@ fn ple_addrs(key: PleKey) -> PleAddrs {
}
}
#[path = "tests/fused_down_launches.rs"]
mod fused_down_launches;
#[path = "tests/head_mix_is_the_native.rs"]
mod head_mix_is_the_native;
#[path = "tests/tiled_down_projection_covers.rs"]
@@ -0,0 +1,259 @@
//! `LELEKA_SM120_GR_DOWN_FUSED` (`fused_down.rs`, `sm120_gr_down_fused.cu`): the plan, the decision, the asset and the
//! layout the kernel assumes.
use super::super::super::chain::{self, ChainFlags};
use super::super::fused_down::{
E_GR_DOWN_FUSED, FUSED_DOWN_MAX_SHARED, FusedDownDecision, GR_DOWN_FUSED, decide, fused_down_geometry,
plan_hc_read_launches, shared_attributes,
};
#[allow(unused_imports)]
use super::*;
const E_SPLIT_CHAIN: &str = "chain_gr_split";
const E_DOWN_TILED: &str = "chain_gr_down_t2w8_nb4";
const E_UP8: &str = "chain_gr_up8";
fn chain_gr() -> ChainFlags {
ChainFlags { gr: true, ..ChainFlags::default() }
}
fn fused_card() -> GrConfig {
sm120(GrVariant::Staged).with_fused_down(true)
}
fn launches(cfg: &GrConfig, half: HcHalf, apply: bool, r: Rows) -> Vec<Launch> {
let m = arena();
let g = test_geometry();
plan_hc_read_launches(window(&m, &g, cfg), &weights(), half, apply, r).unwrap()
}
fn entries(l: &[Launch]) -> Vec<&'static str> {
l.iter().map(|x| x.entry).collect()
}
#[test]
fn the_geometry_is_the_down_kernels_with_the_activations_of_two_tokens_in_shared_memory() {
for tokens in 1..=8usize {
let (grid, shared) = fused_down_geometry(tokens);
assert_eq!(grid, [41, tokens.div_ceil(2) as u32, 1]);
assert_eq!(grid, tiled_down_geometry(tokens).0, "same grid as chain_gr_down_t2w8_nb4");
assert_eq!(shared, tokens.min(2) as u32 * 40_960);
}
assert_eq!(FUSED_DOWN_MAX_SHARED, 81_920);
assert!(FUSED_DOWN_MAX_SHARED <= sm120(GrVariant::Staged).usable_shared);
}
#[test]
fn the_switch_is_off_in_every_config_the_card_derives() {
assert!(!sm120(GrVariant::Staged).down_fused);
assert!(!from_card(GrVariant::Staged, (8, 6), 101_376, 49_152).down_fused);
assert!(fused_card().down_fused && !fused_card().with_fused_down(false).down_fused);
assert!(shared_attributes(&sm120(GrVariant::Staged)).is_empty());
}
#[test]
fn a_fused_read_is_the_fused_launch_then_the_unchanged_up_launch_with_the_same_struct() {
let (off, on) = chain::with_flags(chain_gr(), || {
let r = rows(0, 8, 0);
(
launches(&sm120(GrVariant::Staged), HcHalf::Attention, true, r),
launches(&fused_card(), HcHalf::Attention, true, r),
)
});
assert_eq!(entries(&off), [E_SPLIT_CHAIN, E_DOWN_TILED, E_UP8]);
assert_eq!(entries(&on), [E_GR_DOWN_FUSED, E_UP8]);
let fused = &on[0];
assert!(std::ptr::eq(fused.asset, &GR_DOWN_FUSED));
assert_eq!((fused.grid, fused.block, fused.shared), ([41, 4, 1], [256, 1, 1], 81_920));
// the by-value struct is the one the split and the down kernel get, and the up launch is the same launch
assert_eq!(words(fused), words(&off[0]));
assert_eq!(words(fused), words(&off[1]));
assert_eq!(on[1], off[2]);
}
#[test]
fn every_window_size_and_group_gets_its_rows_grid_and_shared_bytes() {
chain::with_flags(chain_gr(), || {
for t in 1..=8usize {
let first = t.div_ceil(2);
let groups = if t >= 2 { vec![(0, first), (first, t)] } else { vec![(0, t)] };
for (gi, (b, e)) in groups.into_iter().enumerate() {
let l = launches(&fused_card(), HcHalf::Ffn, false, rows(b, e, gi));
let n = e - b;
assert_eq!((l[0].grid, l[0].shared), fused_down_geometry(n), "t={t}");
assert_eq!(words(&l[0])[113], n as u64);
assert_eq!(words(&l[1])[113], n as u64);
}
}
});
}
#[test]
fn without_the_chain_pair_or_the_staged_variant_or_the_room_the_default_launches_run() {
let default = |cfg: &GrConfig| launches(cfg, HcHalf::Attention, false, rows(0, 4, 0));
// no chain group: the Original kernels, whatever the switch says
assert_eq!(default(&fused_card()), default(&sm120(GrVariant::Staged)));
chain::with_flags(chain_gr(), || {
// the 8-row kernels of LELEKA_CHAIN_DOWN=w8 are not the pair this replaces
chain::set_down_override(0);
let w8 = default(&fused_card());
chain::set_down_override(-1);
assert!(!entries(&w8).contains(&E_GR_DOWN_FUSED));
// the plain and split variants have no chain kernels
for variant in [GrVariant::Plain, GrVariant::Split] {
let l = default(&sm120(variant).with_fused_down(true));
assert!(!entries(&l).contains(&E_GR_DOWN_FUSED), "{variant:?}");
}
// a card without 81,920 bytes
let small = from_card(GrVariant::Staged, (12, 0), 49_152, 49_152).with_fused_down(true);
assert!(!entries(&default(&small)).contains(&E_GR_DOWN_FUSED));
});
}
#[test]
fn bad_rows_are_refused_as_before() {
let m = arena();
let g = test_geometry();
let cfg = fused_card();
chain::with_flags(chain_gr(), || {
for bad in [rows(3, 3, 0), rows(0, 9, 0), rows(7, 9, 1)] {
assert!(plan_hc_read_launches(window(&m, &g, &cfg), &weights(), HcHalf::Ffn, true, bad).is_err());
}
});
}
#[test]
fn the_switch_is_off_by_default_and_follows_its_own_variable_on_a_12_x_card_only() {
use super::super::super::sm120::{DEFAULT_ON_GR_DOWN_FUSED, Sm120Switches};
let resolve = |cc: (i32, i32), pairs: &'static [(&'static str, &'static str)]| {
Sm120Switches::resolve(cc.0, cc.1, move |k| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string()))
};
const VAR: &str = "LELEKA_SM120_GR_DOWN_FUSED";
assert!(!DEFAULT_ON_GR_DOWN_FUSED && !resolve((12, 0), &[]).gr_down_fused);
assert!(resolve((12, 0), &[(VAR, "1")]).gr_down_fused && resolve((12, 1), &[(VAR, "on")]).gr_down_fused);
assert!(!resolve((12, 0), &[(VAR, "0")]).gr_down_fused);
// the kernel is sm_120 PTX: a card below 12.x never takes it
assert!(!resolve((8, 6), &[(VAR, "1")]).gr_down_fused);
// no other switch follows it, and it follows no other
let only = resolve((12, 0), &[(VAR, "1")]);
assert_eq!(Sm120Switches { gr_down_fused: false, ..only }, Sm120Switches::default());
assert!(!resolve((12, 0), &[("LELEKA_SM120_FUSED_GDN", "1")]).gr_down_fused);
assert!(!only.side_branches().any());
}
#[test]
fn the_decision_names_why_a_wanted_switch_does_nothing() {
let staged = sm120(GrVariant::Staged);
assert_eq!(decide(false, &staged, true), FusedDownDecision::Off);
assert_eq!(decide(true, &staged, true), FusedDownDecision::On);
assert!(matches!(decide(true, &staged, false), FusedDownDecision::Refused(why) if why.contains("chain")));
assert!(matches!(decide(true, &sm120(GrVariant::Split), true), FusedDownDecision::Refused(_)));
let small = from_card(GrVariant::Staged, (12, 0), 49_152, 49_152);
assert!(matches!(decide(true, &small, true), FusedDownDecision::Refused(why) if why.contains("shared")));
}
#[test]
fn the_kernel_asks_the_driver_for_two_tokens_of_shared_memory() {
let attrs = shared_attributes(&fused_card());
assert_eq!(attrs.len(), 1);
assert!(std::ptr::eq(attrs[0].0, &GR_DOWN_FUSED));
assert_eq!((attrs[0].1, attrs[0].2), (E_GR_DOWN_FUSED, 81_920));
}
// ------------------------------------------------------------------------------------------------ the asset
fn fused_ptx() -> String {
String::from_utf8_lossy(GR_DOWN_FUSED.ptx).into_owned()
}
fn entry_body<'a>(ptx: &'a str, entry: &str) -> &'a str {
let from = ptx.find(&format!(".entry {entry}(")).expect("entry");
let to = ptx[from + 1..].find(".entry ").map_or(ptx.len(), |i| from + 1 + i);
&ptx[from..to]
}
#[test]
fn the_asset_is_sealed_exports_its_entry_and_takes_one_912_byte_struct() {
GR_DOWN_FUSED.assert_sealed_and_fail_closed();
let text = fused_ptx();
assert!(entry_declared(&text, E_GR_DOWN_FUSED));
assert!(text.contains(&format!("{E_GR_DOWN_FUSED}_param_0[912]")), "one GrMulti by value");
assert!(text.contains(".target sm_120"));
assert_eq!(text.matches(".entry ").count(), 1);
}
/// The chains of the split kernel's sum of squares as nvcc contracts them: `mul.f32 s, y, y`, then three
/// `fma.rn.f32 s', a, a, s` (`x * x`, `z * z`, `w * w` in that order).
fn square_chains(ptx: &str) -> usize {
let words = |l: &str| -> Vec<String> {
l.trim().trim_end_matches(';').split([' ', ',', '\t']).filter(|w| !w.is_empty()).map(String::from).collect()
};
let lines: Vec<Vec<String>> = ptx.lines().map(words).collect();
let mut found = 0;
for w in lines.windows(4) {
if w[0].len() != 4 || w[0][0] != "mul.f32" || w[0][2] != w[0][3] {
continue;
}
let mut prev = &w[0][1];
let mut contracted = true;
for fma in &w[1..] {
contracted &= fma.len() == 5 && fma[0] == "fma.rn.f32" && fma[2] == fma[3] && fma[4] == *prev;
prev = &fma[1];
}
found += usize::from(contracted);
}
found
}
#[test]
fn the_sum_of_squares_has_the_fma_chain_of_the_split_kernel() {
let chain_ptx = String::from_utf8_lossy(chain::CHAIN.ptx).into_owned();
// one chain per round of the split kernel's loop; the fused kernel has one for every round a thread can have in a
// stream, for each of its two tokens
assert_eq!(square_chains(entry_body(&chain_ptx, "chain_gr_split")), 10);
let text = fused_ptx();
assert!(square_chains(&text) >= 20, "{} chains", square_chains(&text));
// the same single-precision operations around it: rsqrt.approx of (sum / 2560 + eps), the sigmoid and the silu
assert_eq!(text.matches("rsqrt.approx.f32").count(), 1);
assert!(text.contains("div.rn.f32") && text.contains("0f45200000"), "division by 2560, not a reciprocal multiply");
assert!(!text.contains(".ftz") && !text.contains("div.full"), "no fast-math forms");
}
// ------------------------------------------------------------------------------ the layout the kernel assumes
/// `slot_of` of the kernel: where float4 number `f4` of a token sits in shared memory (the staging layout of
/// `chain_gr_down_t2w8_nb4`: the two float4 of a lane's eight columns 160 apart).
fn slot_of(f4: usize) -> usize {
let (h, s4) = (f4 / 320, f4 % 320);
h * 320 + (s4 & 1) * 160 + (s4 >> 1)
}
#[test]
fn the_shared_slots_are_a_permutation_and_a_lane_reads_its_eight_weight_columns() {
let mut seen = vec![false; 2560];
for f4 in 0..2560 {
assert!(!std::mem::replace(&mut seen[slot_of(f4)], true), "slot of float4 {f4} used twice");
}
// the dot of tile h, chunk q, lane l reads slots h * 320 + j and h * 320 + 160 + j (j = l + 32 q) and multiplies
// them with weight uint4 number h * 160 + j: columns 8 (h * 160 + j) .. + 8 of the row
for (h, q, lane) in [(0usize, 0usize, 0usize), (3, 4, 31), (7, 2, 17), (5, 1, 9)] {
let j = lane + 32 * q;
let column = (h * 160 + j) * 8;
assert_eq!(slot_of(column / 4), h * 320 + j, "first four columns");
assert_eq!(slot_of(column / 4 + 1), h * 320 + 160 + j, "last four columns");
}
}
#[test]
fn every_element_is_staged_once_in_the_stream_the_split_kernel_gives_it() {
// thread t, round mm: elements 4 t + 1024 mm .. + 4, of stream (4 t + 1024 mm) / 2560; rounds ascend per thread
let mut count = vec![0u8; 10_240];
for t in 0..256usize {
let mut last_round = [None::<usize>; 4];
for mm in 0..10usize {
let i = 4 * t + 1024 * mm;
let c = i / 2560;
assert_eq!((i + 3) / 2560, c, "four floats never straddle two streams");
assert!(last_round[c].is_none_or(|p| p < mm));
last_round[c] = Some(mm);
for e in 0..4 {
count[i + e] += 1;
}
}
}
assert!(count.iter().all(|&c| c == 1));
}
@@ -169,11 +169,16 @@ impl<'ctx> OriginalVerifyWindowResources<'ctx> {
/// Pre-capture work: load the sealed modules, read the card's fused-GR decisions, raise the dynamic
/// shared-memory limits Original raises once. Any failure leaves the window unrecorded.
pub(super) fn prepare(&mut self, policy: &WindowPolicy) -> Result<()> {
self.base.journal.ensure_window_assets(&self.required_assets(policy))?;
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)?);
let mut assets = self.required_assets(policy);
assets.extend(gr::fused_down::assets(cfg.down_fused));
self.base.journal.ensure_window_assets(&assets)?;
let mut attributes = Vec::new();
if self.gr.is_some() {
attributes.extend(gr::shared_attributes(&cfg));
attributes.extend(gr::fused_down::shared_attributes(&cfg));
}
if self.qsa.is_some() {
attributes.extend(qsa::shared_attributes(&policy.qsa, &self.base.journal.geometry()));
@@ -83,7 +83,7 @@ impl<'p> Planner<'p> {
// ---- GR
pub(crate) fn hc_read(&self, layer: usize, half: HcHalf, apply: bool, rows: Rows) -> Result<Vec<Launch>> {
let w = self.weights.hc(layer, half)?;
Ok(gr::plan_hc_read(self.gr_window(), &w, half, apply, rows)?.launches())
gr::plan_hc_read_launches(self.gr_window(), &w, half, apply, rows)
}
pub(crate) fn final_write(&self, rows: Rows) -> Result<Vec<Launch>> {
gr::plan_final_write(self.arena, &self.geo, &self.gr, rows)
@@ -341,5 +341,7 @@ fn names(log: &[String]) -> Vec<&str> {
#[path = "tests/every_window_size_and_group.rs"]
mod every_window_size_and_group;
#[path = "tests/fused_gr_down.rs"]
mod fused_gr_down;
#[path = "tests/fused_qsa_prelude.rs"]
mod fused_qsa_prelude;
@@ -0,0 +1,55 @@
//! `LELEKA_SM120_GR_DOWN_FUSED` through the recorder: with the chain gr group the split and the tiled down launch of
//! every hc read become one launch; without it the switch changes nothing.
use super::super::super::chain::{self, ChainFlags};
#[allow(unused_imports)]
use super::*;
const SPLIT: &str = "chain_gr_split";
const DOWN: &str = "chain_gr_down_t2w8_nb4";
const FUSED: &str = "leleka_gr_down_fused_t2w8";
const UP: &str = "chain_gr_up8";
fn record_with(fused: bool, t: usize, groups: usize) -> Vec<String> {
let (m, fake) = geometry_and_fake(false);
let cfg = GrConfig { down_fused: fused, ..sm120() };
let planner = Planner::new(&m, test_geometry(), WindowPolicy::mode17(), cfg, &fake);
let mut ops = PlanOps { planner, log: Vec::new(), t };
record_window(&mut ops, &WindowPolicy::mode17(), t, groups, false).unwrap();
ops.log
}
fn count(log: &[String], entry: &str) -> usize {
log.iter().filter(|s| *s == entry).count()
}
fn chain_gr() -> ChainFlags {
ChainFlags { gr: true, ..ChainFlags::default() }
}
#[test]
fn the_switch_replaces_the_split_and_the_down_launch_of_every_hc_read() {
for groups in [1usize, 2] {
for t in groups..=8 {
let off = chain::with_flags(chain_gr(), || record_with(false, t, groups));
let on = chain::with_flags(chain_gr(), || record_with(true, t, groups));
let reads = 96 * groups;
assert_eq!((count(&off, SPLIT), count(&off, DOWN), count(&off, FUSED)), (reads, reads, 0), "t={t}");
assert_eq!((count(&on, SPLIT), count(&on, DOWN), count(&on, FUSED)), (0, 0, reads), "t={t}");
assert_eq!((count(&on, UP), count(&off, UP)), (reads, reads), "the up projection is unchanged");
// the launches that are not the split or the down kernel are the same, in the same order
let rest = |l: &[String]| {
l.iter().filter(|s| ![SPLIT, DOWN, FUSED].contains(&s.as_str())).cloned().collect::<Vec<_>>()
};
assert_eq!(rest(&on), rest(&off), "t={t}");
}
}
}
#[test]
fn the_switch_is_a_no_op_without_the_chain_pair_it_replaces() {
for t in [1usize, 4, 8] {
let base = record(t, 1, false);
assert_eq!(record_with(true, t, 1), base, "no chain group: the Original kernels run");
let w8 = chain::with_flags(chain_gr(), || record_with(false, t, 1));
assert_eq!(count(&w8, FUSED), 0);
}
}
@@ -86,6 +86,8 @@ pub(crate) const DEFAULT_ON_FUSED_QSA_PRELUDE: bool = false;
// claude/verify-gdn-fused-kernels (original_verify_window_gdn_fused.rs): both off until a paired A/B and identity
pub(crate) const DEFAULT_ON_FUSED_GDN: bool = false;
pub(crate) const DEFAULT_ON_GDN_AB_UNROLL: bool = false;
// claude/u5a-gr-down-fused (original_verify_window_gr/fused_down.rs): off until its identity run and a paired A/B
pub(crate) const DEFAULT_ON_GR_DOWN_FUSED: bool = false;
/// Which parts of the verify graph run on the two side streams: the GDN gates and gate projection, the QSA indexer and
/// query chains (upstream `STRATA_SIDE_MIXER=2`), and the shared expert beside the routed experts (upstream's shared
@@ -130,6 +132,9 @@ pub struct Sm120Switches {
pub fused_gdn: bool,
/// `LELEKA_SM120_GDN_AB_UNROLL`: upstream `STRATA_SMALL_UNR` bit 1, the unrolled a/b projection kernel.
pub gdn_ab_unroll: bool,
// ---- claude/u5a-gr-down-fused
/// `LELEKA_SM120_GR_DOWN_FUSED`: the hc split and down projection as one launch (`sm120_gr_down_fused.cu`).
pub gr_down_fused: bool,
}
fn one(get: &impl Fn(&str) -> Option<String>, var: &str, default: bool) -> bool {
@@ -176,6 +181,7 @@ impl Sm120Switches {
fused_qsa_prelude: switch("LELEKA_SM120_FUSED_QSA_PRELUDE", DEFAULT_ON_FUSED_QSA_PRELUDE),
fused_gdn: switch("LELEKA_SM120_FUSED_GDN", DEFAULT_ON_FUSED_GDN),
gdn_ab_unroll: switch("LELEKA_SM120_GDN_AB_UNROLL", DEFAULT_ON_GDN_AB_UNROLL),
gr_down_fused: switch("LELEKA_SM120_GR_DOWN_FUSED", DEFAULT_ON_GR_DOWN_FUSED),
}
}
/// The side-stream parts these switches ask for.
@@ -194,6 +200,7 @@ impl Sm120Switches {
fused_qsa_prelude: s.fused_qsa_prelude,
fused_gdn: s.fused_gdn,
gdn_ab_unroll: s.gdn_ab_unroll,
gr_down_fused: s.gr_down_fused,
}
}
}
@@ -0,0 +1,259 @@
// claude/u5a-gr-down-fused (step-ledger row U5a): the hyper-connection split and the down projection of the verify window as ONE launch.
//
// LELEKA_SM120_GR_DOWN_FUSED replaces, per layer half and window group,
// chain_gr_split (grid [T, 4], one block per token and stream) + chain_gr_down_t2w8_nb4 (grid [41, ceil(T / 2)])
// by `leleka_gr_down_fused_t2w8` (grid [41, ceil(T / 2)], 256 threads), the shape of upstream's gr_down_v3_kernel (mask 133): the block stages
// the activation rows itself (R' = R + bo_prev * 2 sigmoid(inj_prev / hc), times w_norm), adds up the sum of squares of its two tokens and
// runs the dots in the same launch. The next kernel, chain_gr_up8, is unchanged: it reads `rs` (written here by the blocks with blockIdx.x == 0),
// `lo` and `inject_out`.
//
// Bitwise identity with the two kernels it replaces is the contract, so, unlike upstream's v3 (partial dots per stream, scaled afterwards, "ANOTHER
// SUMMATION ORDER"), every number is computed by the operations of chain_window.cu in the same order:
// * R', the per-thread sum of squares (thread t, round mm, element i = 4 t + 1024 mm, one chain per stream, rounds ascending), the warp XOR
// sum, the sequential sum over the 8 warps, rs = rsqrtf(sum / 2560 + eps): `chain_gr_split`;
// * xn = (R' * w_norm) * rs, with the two roundings of chain_gr_split (the product is stored first and scaled when rs is known; this thread
// scales exactly the elements it stored);
// * the dot of a row with a token: acc += dot8v(...) over the 8 tiles of 1280 columns, 5 chunks of 32 lanes each, ascending, then the XOR
// warp sum, silu(x / 4): `chain_gr_down_t2w8_nb4` (gr_down_tp_body<8, 4, 2>), reading the same float from shared memory instead of from xn.
// What changes is where xn lives (all 2 tokens x 10240 floats in shared memory, 81,920 B, instead of four cp.async tile buffers of 10,240 B), that
// every block recomputes the norm of its two tokens (41 blocks per token pair) and that nothing is written to `xn` any more.
//
// Written with the plain expressions of chain_window.cu on purpose: the contraction of mul + add into FFMA is decided from the expression, so the
// same text gives the same PTX shape (checked by a unit test that looks for the FMA chain of the sum of squares in the sealed PTX).
//
// Compile: nvcc -ptx -O3 -arch=sm_120 -std=c++17 --fmad=true --ftz=false (the recipe of chain_window.cu). Self-contained: the 112-byte FusedGrArgs
// layout the sealed chain kernels use is repeated here (the header in engine/strata/include has later fields and is 168 bytes).
#include <cuda_runtime.h>
#include <stdint.h>
#include <stddef.h>
namespace {
constexpr int N = 2560;
constexpr int HC = 4;
constexpr int D = N * HC;
constexpr int LR = 320;
constexpr int THREADS = 256;
constexpr int WARPS = THREADS / 32;
constexpr int MAX_T = 8;
constexpr int TPB = 2; // tokens per block
// The Original's FusedGrArgs, 14 words (112 bytes), and GrMulti as chain_window.cu declares them: the host fills the same words
// (original_verify_window_gr/assets.rs `multi_words`).
struct FusedGrArgs {
const float* R;
float* R_out;
bool apply;
const float* bo_prev;
const float* inj_prev;
const float* w_norm;
const uint16_t* w_down;
const uint16_t* w_up;
const uint16_t* w_inject;
float eps;
float* lo;
float* rs;
float* inject_out;
float* mixed;
};
struct GrMulti {
FusedGrArgs a[MAX_T];
float* xn; // not used by this kernel
int T;
};
static_assert(sizeof(FusedGrArgs) == 112, "Original FusedGrArgs ABI");
static_assert(sizeof(GrMulti) == 912, "Original GrMulti ABI");
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
return v;
}
__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + __expf(-x)); }
__device__ __forceinline__ float dot8v(const uint4 w, const float4 x0, const float4 x1) {
float acc = 0.0f;
acc = fmaf(__uint_as_float(w.x << 16), x0.x, acc);
acc = fmaf(__uint_as_float(w.x & 0xffff0000u), x0.y, acc);
acc = fmaf(__uint_as_float(w.y << 16), x0.z, acc);
acc = fmaf(__uint_as_float(w.y & 0xffff0000u), x0.w, acc);
acc = fmaf(__uint_as_float(w.z << 16), x1.x, acc);
acc = fmaf(__uint_as_float(w.z & 0xffff0000u), x1.y, acc);
acc = fmaf(__uint_as_float(w.w << 16), x1.z, acc);
acc = fmaf(__uint_as_float(w.w & 0xffff0000u), x1.w, acc);
return acc;
}
constexpr int H_TILE = 1280;
constexpr int N_HTILES = D / H_TILE; // 8
constexpr int HQ = H_TILE / 8 / 32; // 5 chunks per lane per tile
constexpr int DOWN_ROWS = LR + HC; // 320 down rows + 4 inject rows
constexpr int TILE_F4 = H_TILE / 4; // 320 float4 per tile
constexpr int TOKEN_F4 = D / 4; // 2560 float4 per token
constexpr int ROUNDS = D / (THREADS * 4); // 10 rounds of the split's loop
// Where float4 number `f4` of a token (0..2559) sits in shared memory: the tile layout of the cp.async staging of chain_gr_down_t2w8_nb4 (the two
// float4 of a lane's 8 columns 160 apart, so that the 32 lanes of a warp read consecutive 16-byte words).
__device__ __forceinline__ int slot_of(int f4) {
const int h = f4 / TILE_F4, s4 = f4 - h * TILE_F4;
return h * TILE_F4 + (s4 & 1) * (H_TILE / 8) + (s4 >> 1);
}
// The element of thread `t` in round `mm`, when it belongs to stream `c` (the split kernel's `if (i / N != c) continue;`).
__device__ __forceinline__ bool in_stream(int t, int mm, int c) { return (t * 4 + mm * (THREADS * 4)) / N == c; }
// R' of one token's 4 elements (chain_gr_split): R + bo_prev * gw when the previous half's write is folded in.
__device__ __forceinline__ float4 folded_row(const FusedGrArgs& a, int i, int d, float gw) {
float4 r = *reinterpret_cast<const float4*>(a.R + i);
if (a.apply) {
const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + d);
r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y);
r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w);
}
return r;
}
// One element round of one token (chain_gr_split's loop body): R' of 4 elements, its sum of squares added to `ss`, and R' * w_norm to shared memory
// (unscaled until rs is known).
__device__ __forceinline__ void stage_round(const FusedGrArgs& a, int i, int d, float gw, float4 g, float4* row, float& ss) {
const float4 r = folded_row(a, i, d, gw);
const float sq = r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w;
ss += sq;
row[slot_of(i >> 2)] = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w);
}
__device__ __forceinline__ float folded_weight(const FusedGrArgs& a, int c) {
return a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;
}
// Phase 1: for every stream c, the block's tokens' rows to shared memory and the per-thread sum of squares of (token, stream), the warp XOR sum of it,
// written to part[warp][token * HC + c] (chain_gr_split: warp_sum of the thread sums, lane 0 stores). A thread's rounds of one stream ascend, one
// chain per (token, stream); all lanes of a warp are in the same stream in a round (the stream boundaries fall on warp boundaries), so the
// shuffles are executed by whole warps.
__device__ __forceinline__ void stage_rows_and_square(const GrMulti& m, int k0, int Tn, float4* xs4, float (*part)[TPB * HC]) {
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const FusedGrArgs& a0 = m.a[k0];
const FusedGrArgs& a1 = m.a[k0 + (Tn > 1 ? 1 : 0)];
#pragma unroll
for (int c = 0; c < HC; ++c) {
const float gw0 = folded_weight(a0, c), gw1 = folded_weight(a1, c);
float ss0 = 0.0f, ss1 = 0.0f;
#pragma unroll
for (int mm = 0; mm < ROUNDS; ++mm) {
if (!in_stream(t, mm, c)) continue;
const int i = t * 4 + mm * (THREADS * 4), d = i - c * N;
stage_round(a0, i, d, gw0, *reinterpret_cast<const float4*>(a0.w_norm + i), xs4, ss0);
if (Tn > 1) stage_round(a1, i, d, gw1, *reinterpret_cast<const float4*>(a1.w_norm + i), xs4 + TOKEN_F4, ss1);
}
const float v0 = warp_sum(ss0), v1 = warp_sum(ss1);
if (lane == 0) {
part[warp][c] = v0;
part[warp][HC + c] = v1;
}
}
}
// Phase 2: rs of every (token, stream) of the block (chain_gr_split: the 8 warps in order); the blocks of column 0 publish it.
__device__ __forceinline__ void reduce_rs(const GrMulti& m, int k0, int Tn, float (*part)[TPB * HC], float* rs_s) {
const int t = threadIdx.x;
if (t < TPB * HC && t / HC < Tn) {
float s = 0.0f;
for (int w = 0; w < WARPS; ++w) s += part[w][t];
const float r = rsqrtf(s / (float) N + m.a[k0 + t / HC].eps);
rs_s[t] = r;
if (blockIdx.x == 0) m.a[k0 + t / HC].rs[t % HC] = r;
}
__syncthreads();
}
// Phase 3: xn = (R' * w_norm) * rs, over the elements this thread stored in phase 1 (chain_gr_split's second loop).
__device__ __forceinline__ void scale_rows(int Tn, float4* xs4, const float* rs_s) {
const int t = threadIdx.x;
#pragma unroll
for (int c = 0; c < HC; ++c)
#pragma unroll
for (int mm = 0; mm < ROUNDS; ++mm) {
if (!in_stream(t, mm, c)) continue;
const int slot = slot_of((t * 4 + mm * (THREADS * 4)) >> 2);
#pragma unroll
for (int k = 0; k < TPB; ++k) {
if (k >= Tn) continue;
const float rs = rs_s[k * HC + c];
float4 p = xs4[k * TOKEN_F4 + slot];
p.x = p.x * rs; p.y = p.y * rs; p.z = p.z * rs; p.w = p.w * rs;
xs4[k * TOKEN_F4 + slot] = p;
}
}
__syncthreads();
}
// The first row of this warp (one row a warp, 8 warps a block) and its weights: the whole weight row in registers before any staging.
struct RowWeights {
int row;
bool inject, active;
};
__device__ __forceinline__ RowWeights row_of_warp(const GrMulti& m) {
RowWeights r;
r.row = blockIdx.x * WARPS + (threadIdx.x >> 5);
r.inject = r.row >= LR;
r.active = r.row < DOWN_ROWS && !(r.inject && m.a[0].w_inject == nullptr);
return r;
}
__device__ __forceinline__ void leleka_gr_down_fused_body(const GrMulti& m) {
extern __shared__ __align__(16) float4 xs4[]; // [Tn][2560] float4, tile layout
__shared__ float part[WARPS][TPB * HC];
__shared__ float rs_s[TPB * HC];
const int lane = threadIdx.x & 31;
const int k0 = blockIdx.y * TPB;
const int Tn = min(TPB, m.T - k0);
const RowWeights rw = row_of_warp(m);
const uint16_t* wrow = (rw.inject ? m.a[0].w_inject : m.a[0].w_down) +
(size_t) (rw.active ? (rw.inject ? rw.row - LR : rw.row) : 0) * D;
const uint4* w4 = reinterpret_cast<const uint4*>(wrow);
uint4 wv[N_HTILES][HQ];
if (rw.active) {
#pragma unroll
for (int h = 0; h < N_HTILES; ++h)
#pragma unroll
for (int q = 0; q < HQ; ++q) wv[h][q] = __ldg(w4 + h * (H_TILE / 8) + lane + 32 * q);
}
stage_rows_and_square(m, k0, Tn, xs4, part);
__syncthreads();
reduce_rs(m, k0, Tn, part, rs_s);
scale_rows(Tn, xs4, rs_s);
if (!rw.active) return;
float acc[TPB];
#pragma unroll
for (int k = 0; k < TPB; ++k) acc[k] = 0.0f;
#pragma unroll
for (int h = 0; h < N_HTILES; ++h)
#pragma unroll
for (int q = 0; q < HQ; ++q) {
const int j = lane + 32 * q;
#pragma unroll
for (int k = 0; k < TPB; ++k) {
if (k < Tn) {
const float4* pk = xs4 + k * TOKEN_F4 + h * TILE_F4;
acc[k] += dot8v(wv[h][q], pk[j], pk[H_TILE / 8 + j]);
}
}
}
float s[TPB];
#pragma unroll
for (int k = 0; k < TPB; ++k) s[k] = k < Tn ? warp_sum(acc[k]) : 0.0f;
#pragma unroll
for (int k = 0; k < TPB; ++k) {
if (k >= Tn || lane != k) continue;
if (rw.inject) {
m.a[k0 + k].inject_out[rw.row - LR] = s[k];
} else {
const float x = s[k] / (float) HC;
m.a[k0 + k].lo[rw.row] = x / (1.0f + __expf(-x));
}
}
}
} // namespace
// grid (41, ceil(T / 2)), 256 threads, dynamic shared memory Tn * 40,960 B (81,920 B for two tokens: the host raises the limit).
extern "C" __global__ void __launch_bounds__(THREADS) leleka_gr_down_fused_t2w8(GrMulti m) { leleka_gr_down_fused_body(m); }
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -125,7 +125,7 @@ These are in upstream `strata-upstream/main` (October 31 to November 1) and not
| verify: unrolled GDN a/b projection (U3) | `STRATA_SMALL_UNR` bit 1 (`gdn_ab_body`; ours `verify_gdn_ab_multi_kernel`) | no | same A/B as U2 (bits 0 and 1 together) | not measured; part of the GDN role K7 | upstream commit | device | open (switch `LELEKA_SM120_GDN_AB_UNROLL` built, identity PASS (P6, P8: `verify-new-switches-identity`: top-16 rows 2057/2057 identical, draft trace 1036/1036 identical, argmax flips 0, A/A identical), OFF in the profiles. Section `verify-new-switches-cupti-windows` (2026-11-10, windows of request 29, 15 s, new binary `bin-verify-switches`, per-T within one variant: T 2..6 have 77-376 graphs; the control CL.2 and each variant ran in separate sessions, so the expert-tier (FFN) phase differs between them and is NOT compared) without side streams (CV.1 against CL.2): GDN kernel time per graph -63 / -93 / -137 / -177 / -168 us at T 2..6 (`chain_gdn_ab_multi_kernel` 7.72 us x 36 -> `leleka_gdn_ab_unrolled_t1..t8` 2.97 .. 15.56 us), mixer phase -1.3 / -1.8 / -2.8 / -3.3 / -3.7 us per layer = -0.06 .. -0.17 ms per graph. With SIDE_MIXER on (CY.1) the unrolled kernel does not run at all (the side stream keeps `chain_gdn_ab_multi_kernel`), so the profile set does not take it. Next step: use the unrolled a/b kernel on the side stream and check whether the join then waits less) |
| verify: batched staging and read loads of the HC read (U4) | `STRATA_GR_V3_PF` bits 0 and 2 of `gr_down_v3`/`gr_up_v3` (`08b20b104`) | no `GR_V3` port (`upstream-port-plan.md` 5.7); our HC kernels are the chain kernels (`chain_gr_down_t2w8_nb4` 11.1 us, `chain_gr_up8` 8.5 us), ahead of vanilla 0.2.6 by K8/K9 | no number of its own | not measured against the chain kernels | upstream commit | device | open (needs the same-T kernel table of upstream's variant against the chain kernel) |
| verify: HC down kernel, two rows a warp for windows of 5+ rows (U5) | `STRATA_GR_V3_PF` bit 7, default mask 133 on sm_120 (`4ab81c796`, `5f24b96db`, merged as `27a3e056a`; bitwise, same dots in the same order) | not present; chain down kernel by window rows in `CL.1` (gy = rows/2): T 1-2 9.35 us, T 3-4 10.65 us, T 5-6 13.11 us, T 7-8 15.33 us (vanilla 0.2.6 `VANL` by its own grid-y 1/2/3/4/6: 8.80 / 9.04 / 10.18 / 12.54 / 15.92 us; a different row mapping) | down kernel 16.1 / 16.2 / 17.6 / 19.5 -> 13.3 / 14.1 / 14.7 / 15.6 us at T 5-8 (upstream's own table); serve A/B spec 6 +1.21 %, spec 8 +1.4 %, ids identical 96/96 | RTX 5090 micro-benchmark `verify-hc-down-kernel-microbench-vs-upstream` (2026-11-10, upstream 504b1433, ours 6b2a69f1d; 64-node graph, 7 rounds x 40 replays, weights cold from DRAM): the whole read, ours (split + down + up8) against upstream (down + up, mask 133), is slower by 3.9 / 4.4 / 3.4 / 3.1 / 3.9 / 5.2 / 5.9 / 5.2 us per layer half at T 1..8 (+15..+29 %, every point above the round spread); against mask 0 by 3.2 / 3.1 / 2.5 / 1.3 / 0.8 / 1.1 / 0.2 / -0.9 us. Our down kernel alone is slower by 2.8..5.1 us (warm); the split kernel adds 2.3..2.6 us that upstream's down kernel does itself (norm sum of squares and staging). At 96 launches a graph (48 layers x 2 halves, `docs/experiments/verify-hc-down-kernel-microbench-vs-upstream.md`) that is 0.30 (T 4) .. 0.56 ms (T 7) per verify graph. Bitwise: NOT established, the harness inputs give NaN in most outputs (`nonfinite` in the DIFF lines), so the byte compare says nothing; the finite rows show `rs` differing by 1 ulp from upstream. | upstream commit | device | fixing (measured: upstream faster at every T, so the earlier "level within 1 us" reading was wrong; steps: U5a. Section delta to confirm in the CUPTI window: `chain_gr_down_t2w8_nb4` + `chain_gr_split` -> one fused down kernel, per-layer-half time) |
| verify: HC down plus split fused into one upstream-style kernel (U5a) | `gr_down_v3_kernel` mask 133: staging, norm sum of squares and the dots in one launch, no `chain_gr_split` | `chain_gr_split` + `chain_gr_down_t2w8_nb4` (+ `chain_gr_up8`): two launches, split 2.3..2.6 us (warm) | microbench (U5): ours slower by 3.1..5.9 us per layer half cold, 96 launches a graph = 0.30..0.56 ms a graph | not measured on the engine | microbench `verify-hc-down-kernel-microbench-vs-upstream` | device | open (port or tune our down kernel to read the staged rows like upstream and fold the norm sum of squares in; first make the microbench inputs finite so the byte compare is valid, then write the kernel behind `LELEKA_SM120_GR_DOWN_FUSED` (off); section = `chain_gr_split` + `chain_gr_down_t2w8_nb4` time per graph in CUPTI; identity by the teacher-forced harness) |
| verify: HC down plus split fused into one upstream-style kernel (U5a) | `gr_down_v3_kernel` mask 133: staging, norm sum of squares and the dots in one launch, no `chain_gr_split` | `chain_gr_split` + `chain_gr_down_t2w8_nb4` (+ `chain_gr_up8`): two launches, split 2.3..2.6 us (warm) | microbench (U5): ours slower by 3.1..5.9 us per layer half cold, 96 launches a graph = 0.30..0.56 ms a graph | not measured on the engine | microbench `verify-hc-down-kernel-microbench-vs-upstream` | device | built, off (branch `claude/u5a-gr-down-fused`; not run on a GPU: identity, CUPTI section and A/B open). `LELEKA_SM120_GR_DOWN_FUSED=1` (needs `LELEKA_CHAIN` with `gr`, staged read, 81,920 B shared) records `leleka_gr_down_fused_t2w8` (`sm120_gr_down_fused.cu`, sealed PTX, 191 registers, no spill) in place of `chain_gr_split` + `chain_gr_down_t2w8_nb4`: the block stages R' * w_norm of its two tokens into shared memory, adds the sum of squares in the split kernel's order, scales, and runs the down kernel's dots; `rs` is written by the blocks of column 0; the arithmetic order is the two kernels' (bitwise by construction, unlike upstream's v3), so the weights' DRAM fetch (about 4 us cold) overlaps the staging instead of waiting behind the split launch. Probe `tools/gr-down-fused/gr_down_fused_probe.cpp` compares every output byte against the pair for T 1..8. Microbench inputs were finite all along; its NaN came from a race between the poison memsets (legacy default stream) and the kernels (non-blocking stream), fixed with a device synchronize; the byte compare of the earlier run is invalid and the microbench has to be re-run. Section to look at: `chain_gr_split` + `chain_gr_down_t2w8_nb4` (96 + 96 launches a graph) -> `leleka_gr_down_fused_t2w8` (96 a graph)) |
## C2v. CUPTI windows of the new verify switches (`verify-new-switches-cupti-windows`, 2026-11-10)
@@ -6,6 +6,8 @@ upstream `strata-upstream/main` = `504b143342a9fe1aa8320a7b31e11f5c0ac265c3`. Le
11.1 us against `gr_down_staged` 11.5 us), U4 (batched staging/read loads, `STRATA_GR_V3_PF` bits 0 and 2), U5 (bit 7, two rows a warp for
windows of 5+ rows, mask 133, upstream commits `4ab81c796`, `5f24b96db`, `08b20b104`).
**Correction (claude/u5a-gr-down-fused, 2026-11-10): the byte compare of the first run is invalid, and not because of the input values.** The generated inputs are finite (normal distributions, bf16 weights; the harness now counts non-finite input values and prints `inputs: 0 non-finite values`). The NaN words in the `DIFF` lines are the 0xff poison that `reset_work` and `new_work` write with `cudaMemset`/`cudaMemcpy` on the legacy default stream while the kernels run on `s`, a non-blocking stream: the runtime does not order the two, so a poison memset could land after (or beside) the kernel that was meant to overwrite it. `reset_work` and `new_work` now end with `cudaDeviceSynchronize()`. The timing loops are unlikely to be affected (their memsets, at creation, finish long before the two seconds of warm-up are over), but the harness has to be re-run to get a valid correctness section.
## 1. Question
Per window rows T = 1..8 on the RTX 5090: is upstream's down kernel (mask 133 = 128 + 4 + 1, and for reference mask 5 and the plain mask 0) faster
@@ -54,6 +54,7 @@ static Work new_work(const Inputs& in) {
Work w{dev_floats((size_t) kTokensMax * D), dev_floats((size_t) kTokensMax * LR), dev_floats((size_t) kTokensMax * HC), dev_floats((size_t) kTokensMax * HC),
dev_floats((size_t) kTokensMax * N), dev_floats((size_t) kTokensMax * D * 4)};
CU_RT(cudaMemcpy(w.R, in.R0.data(), in.R0.size() * 4, cudaMemcpyHostToDevice));
CU_RT(cudaDeviceSynchronize()); // see reset_work: the memsets of dev_floats are on the default stream
return w;
}
static void reset_work(const Work& w, const Inputs& in) {
@@ -61,6 +62,10 @@ static void reset_work(const Work& w, const Inputs& in) {
CU_RT(cudaMemset(w.lo, 0xff, kTokensMax * LR * 4)); CU_RT(cudaMemset(w.rs, 0xff, kTokensMax * HC * 4));
CU_RT(cudaMemset(w.inject_out, 0xff, kTokensMax * HC * 4)); CU_RT(cudaMemset(w.mixed, 0xff, (size_t) kTokensMax * N * 4));
CU_RT(cudaMemset(w.scratch, 0xff, (size_t) kTokensMax * D * 4 * 4));
// The copies and memsets above run on the legacy default stream and the kernels on `s`, a non-blocking stream: the two are NOT ordered by the
// runtime, so a poison memset could land after (or beside) the kernel that was meant to overwrite it. That race, not the input values, made the
// first run's outputs NaN (0xffffffff). Wait for the poison before any launch.
CU_RT(cudaDeviceSynchronize());
}
static FusedGrArgs upstream_args(int t, const Work& w, const WeightSet& ws, const Inputs& in) {
@@ -288,6 +293,14 @@ static int run(int argc, char** argv) {
for (auto& x : wd) x = bf16_bits(0.02f * nd(rng));
for (auto& x : wu) x = bf16_bits(0.05f * nd(rng));
for (auto& x : wi) x = bf16_bits(0.02f * nd(rng));
// the inputs are finite by construction (normal distributions, weights rounded to bf16); say so in the log, so a NaN in an output can only be a bug
{
size_t bad = 0;
for (const auto* v : {&bo, &inj, &wn, &c.in.R0}) for (float x : *v) bad += !std::isfinite(x);
for (const auto* v : {&wd, &wu, &wi}) for (uint16_t x : *v) bad += ((x & 0x7f80u) == 0x7f80u);
std::printf("inputs: %zu non-finite values (must be 0)\n", bad);
if (bad != 0) return 2;
}
CU_RT(cudaMalloc((void**) &c.in.bo, bo.size() * 4)); CU_RT(cudaMemcpy(c.in.bo, bo.data(), bo.size() * 4, cudaMemcpyHostToDevice));
CU_RT(cudaMalloc((void**) &c.in.inj, inj.size() * 4)); CU_RT(cudaMemcpy(c.in.inj, inj.data(), inj.size() * 4, cudaMemcpyHostToDevice));
for (int i = 0; i < o.sets; ++i) {
+24
View File
@@ -1009,6 +1009,30 @@
},
"group": "sm120-decode",
"optional": false
},
{
"cu": "crates/cuda-driver/src/sm120_gr_down_fused.cu",
"ptx": "crates/cuda-driver/src/sm120_gr_down_fused.ptx",
"flags": [
"-ptx",
"-O3",
"-arch=sm_120",
"-std=c++17",
"--fmad=true",
"--ftz=false"
],
"policy": "precise (--fmad=true --ftz=false: the recipe of chain_window.cu, whose chain_gr_split + chain_gr_down_t2w8_nb4 this replaces bit for bit; claude/u5a-gr-down-fused: LELEKA_SM120_GR_DOWN_FUSED; plain C++ expressions on purpose, the contraction of mul + add is decided from the expression). Self-contained: it declares the 112-byte FusedGrArgs of the sealed chain kernels itself, so it takes no include profile",
"entries": [
"leleka_gr_down_fused_t2w8"
],
"encoding": "concat_include_str",
"rust_fields_to_fill": {
"crates/cuda-driver/src/original_verify_window_gr/fused_down.rs": [
"GR_DOWN_FUSED.sha"
]
},
"group": "sm120-decode",
"optional": false
}
]
}
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# Build the probe of the fused hyper-connection split + down kernel (never run on a GPU by its author) and collect the PTX it loads.
# tools/gr-down-fused/build.sh [OUTDIR] default OUTDIR=$HOME/gr-down-fused-bin ; then: OUTDIR/gr_down_fused_probe OUTDIR/ptx
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
root="$(cd "$here/../.." && pwd)"
out="${1:-$HOME/gr-down-fused-bin}"
nvcc="${NVCC:-$HOME/cuda-toolkits/13.2.2/bin/nvcc}"
mkdir -p "$out/ptx"
"$nvcc" -O2 -std=c++17 "$here/gr_down_fused_probe.cpp" -lcuda -o "$out/gr_down_fused_probe"
for f in chain_window sm120_gr_down_fused; do
cp "$root/crates/cuda-driver/src/$f.ptx" "$out/ptx/$f.ptx"
done
sha256sum "$out"/gr_down_fused_probe "$out"/ptx/* > "$out/SHA256SUMS"
ls -la "$out" "$out/ptx"
+199
View File
@@ -0,0 +1,199 @@
// claude/u5a-gr-down-fused: model-free probe of crates/cuda-driver/src/sm120_gr_down_fused.ptx. NOT RUN by its author (no GPU access in that task): the orchestrator runs it.
//
// The fused kernel `leleka_gr_down_fused_t2w8` is run next to the two kernels it replaces (`chain_gr_split` + `chain_gr_down_t2w8_nb4` of chain_window.ptx, both
// launched exactly as the product launches them) on real-size random FINITE inputs, for every window width T = 1..8, with and without the folded previous
// half (apply), on three input scales (the third has a large dynamic range, so a different order of summation or of rounding would show), each followed by the
// unchanged `chain_gr_up8`. EVERY byte of lo, rs, inject_out, mixed and R (updated in place by the up kernel) is compared, and the fused launch must leave `xn`
// untouched (it no longer writes it). Prints "RESULT name key=value" lines and exits 1 if any comparison differs or any compared output is not finite.
// gr_down_fused_probe PTXDIR PTXDIR holds chain_window.ptx and sm120_gr_down_fused.ptx (copies of crates/cuda-driver/src/)
// With the exact check passed, it times (CUDA events over graphs of 64 launches, the weights rotating over 12 sets of 13 MB so that none is in L2 at its next
// use) the pair against the fused launch, per T: `RESULT time T=.. pair_us=.. fused_us=..` (per split + down pair and per fused launch, launch gaps inside the graph included; the layer-half time
// of the whole read is the thing to look at in CUPTI, not this).
#include <cuda.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <functional>
#include <string>
#include <vector>
#define CU(x) do { CUresult r_ = (x); if (r_ != CUDA_SUCCESS) { const char* s_ = nullptr; cuGetErrorString(r_, &s_); fprintf(stderr, "CUDA error %s at %s:%d: %s\n", #x, __FILE__, __LINE__, s_ ? s_ : "?"); exit(2); } } while (0)
static int g_fail = 0;
static uint64_t g_rng = 0x9e3779b97f4a7c15ull;
static uint32_t rnd() { g_rng ^= g_rng << 13; g_rng ^= g_rng >> 7; g_rng ^= g_rng << 17; return (uint32_t)(g_rng >> 16); }
static float rndf() { return (float)(rnd() & 0xffffff) / 16777216.0f * 2.0f - 1.0f; } // [-1, 1)
static uint16_t bf16_of(float f) { uint32_t u; memcpy(&u, &f, 4); return (uint16_t)((u + 0x7fff + ((u >> 16) & 1)) >> 16); }
static std::string read_file(const std::string& p) {
FILE* f = fopen(p.c_str(), "rb");
if (!f) return std::string();
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);
if (s.empty()) { fprintf(stderr, "cannot read %s\n", p.c_str()); exit(2); }
while (!s.empty() && s.back() == '\0') s.pop_back();
s.push_back('\0'); // the product appends one NUL to the PTX text
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, 0xff, bytes)); } // 0xff: a word nobody wrote is a NaN
void put(const void* h, size_t bytes) { CU(cuMemcpyHtoD(p, h, bytes)); }
std::vector<uint8_t> get() const { std::vector<uint8_t> v(n); CU(cuMemcpyDtoH(v.data(), p, n)); return v; }
};
static CUstream g_s;
static void launch(CUfunction f, unsigned gx, unsigned gy, unsigned bx, unsigned shared, void** params) {
CU(cuLaunchKernel(f, gx, gy, 1, bx, 1, 1, shared, g_s, params, nullptr));
}
static bool all_finite(const std::vector<uint8_t>& b) {
for (size_t i = 0; i + 4 <= b.size(); i += 4) { float f; memcpy(&f, &b[i], 4); if (!std::isfinite(f)) return false; }
return true;
}
static bool same(const char* what, int t, int apply, int scale, const std::vector<uint8_t>& a, const std::vector<uint8_t>& b) {
bool eq = a.size() == b.size() && memcmp(a.data(), b.data(), a.size()) == 0;
bool fin = all_finite(a) && all_finite(b);
size_t diff = 0;
for (size_t i = 0; i < std::min(a.size(), b.size()); ++i) diff += a[i] != b[i];
if (!eq || !fin) { printf("DIFF %s T=%d apply=%d scale=%d bytes=%zu differing_bytes=%zu finite=%d\n", what, t, apply, scale, a.size(), diff, (int)fin); ++g_fail; }
return eq && fin;
}
struct State { Dev R, bo, inj, injo, lo, rs, mixed, xn; int T; };
struct Weights { Dev norm, down, up, inject; };
static void alloc_state(State& s, int T) {
s.T = T; s.R.alloc((size_t)T * 10240 * 4); s.bo.alloc((size_t)T * 2560 * 4); s.inj.alloc((size_t)T * 16); s.injo.alloc((size_t)T * 16); s.lo.alloc((size_t)T * 320 * 4);
s.rs.alloc((size_t)T * 16); s.mixed.alloc((size_t)T * 2560 * 4); s.xn.alloc((size_t)T * 10240 * 4);
}
// the 114 words of GrMulti (original_verify_window_gr/assets.rs `multi_words`)
static std::vector<uint64_t> multi_words(const State& s, const Weights& w, bool apply) {
std::vector<uint64_t> words(114, 0);
for (int k = 0; k < s.T; ++k) {
uint64_t* a = &words[k * 14];
a[0] = s.R.p + (uint64_t)k * 10240 * 4; a[1] = a[0]; a[2] = apply ? 1 : 0;
a[3] = s.bo.p + (uint64_t)k * 2560 * 4; a[4] = s.inj.p + (uint64_t)k * 16; a[5] = w.norm.p; a[6] = w.down.p; a[7] = w.up.p; a[8] = w.inject.p;
float eps = 1e-6f; uint32_t eb; memcpy(&eb, &eps, 4); a[9] = eb;
a[10] = s.lo.p + (uint64_t)k * 320 * 4; a[11] = s.rs.p + (uint64_t)k * 16; a[12] = s.injo.p + (uint64_t)k * 16; a[13] = s.mixed.p + (uint64_t)k * 2560 * 4;
}
words[112] = s.xn.p; words[113] = s.T;
return words;
}
static void reset(State& dst, const State& base) {
CU(cuMemcpyDtoD(dst.R.p, base.R.p, base.R.n)); CU(cuMemcpyDtoD(dst.bo.p, base.bo.p, base.bo.n)); CU(cuMemcpyDtoD(dst.inj.p, base.inj.p, base.inj.n));
for (Dev* d : {&dst.injo, &dst.lo, &dst.rs, &dst.mixed, &dst.xn}) CU(cuMemsetD8(d->p, 0xff, d->n));
CU(cuCtxSynchronize());
}
struct Kernels { CUfunction split, down, up8, fused; };
static unsigned down_shared(int T) { return 4u * (unsigned)std::min(T, 2) * 5120u; }
static unsigned fused_shared(int T) { return (unsigned)std::min(T, 2) * 40960u; }
static void run_pair(const Kernels& k, int T, void** p) {
launch(k.split, T, 4, 256, 0, p);
launch(k.down, 41, (T + 1) / 2, 256, down_shared(T), p);
}
static void run_fused(const Kernels& k, int T, void** p) { launch(k.fused, 41, (T + 1) / 2, 256, fused_shared(T), p); }
static double time_graph(const std::function<void(int)>& body, int nodes) {
CUgraph g; CUgraphExec ge; CU(cuStreamBeginCapture(g_s, CU_STREAM_CAPTURE_MODE_THREAD_LOCAL));
for (int i = 0; i < nodes; ++i) body(i);
CU(cuStreamEndCapture(g_s, &g)); CU(cuGraphInstantiateWithFlags(&ge, g, 0));
CUevent e0, e1; CU(cuEventCreate(&e0, 0)); CU(cuEventCreate(&e1, 0));
std::vector<double> t;
for (int rep = 0; rep < 12; ++rep) {
CU(cuGraphLaunch(ge, g_s)); CU(cuEventRecord(e0, g_s)); CU(cuGraphLaunch(ge, g_s)); CU(cuGraphLaunch(ge, g_s)); CU(cuEventRecord(e1, g_s)); CU(cuStreamSynchronize(g_s));
float ms; CU(cuEventElapsedTime(&ms, e0, e1)); if (rep >= 2) t.push_back(1000.0 * ms / (2.0 * nodes));
}
std::sort(t.begin(), t.end());
CU(cuGraphExecDestroy(ge)); CU(cuGraphDestroy(g));
return t[t.size() / 2];
}
int main(int argc, char** argv) {
if (argc < 2) { fprintf(stderr, "usage: gr_down_fused_probe PTXDIR\n"); 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));
char name[256]; cuDeviceGetName(name, sizeof name, dev);
int maj, min; cuDeviceGetAttribute(&maj, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, dev); cuDeviceGetAttribute(&min, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, dev);
printf("# %s sm_%d%d\n", name, maj, min);
CU(cuStreamCreate(&g_s, CU_STREAM_NON_BLOCKING));
CUmodule mChain = load_module(dir + "/chain_window.ptx"), mFused = load_module(dir + "/sm120_gr_down_fused.ptx");
Kernels k{get_fn(mChain, "chain_gr_split"), get_fn(mChain, "chain_gr_down_t2w8_nb4"), get_fn(mChain, "chain_gr_up8"), get_fn(mFused, "leleka_gr_down_fused_t2w8")};
CU(cuFuncSetAttribute(k.fused, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, 81920));
CU(cuFuncSetAttribute(k.down, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, 81920));
const int NS = 12;
std::vector<Weights> W(NS);
{
std::vector<float> nh(10240); for (auto& v : nh) v = 0.5f + fabsf(rndf());
std::vector<uint16_t> dh((size_t)320 * 10240), uh((size_t)10240 * 320), ih((size_t)4 * 10240);
for (auto& v : dh) v = bf16_of(rndf() * 0.02f);
for (auto& v : uh) v = bf16_of(rndf() * 0.2f);
for (auto& v : ih) v = bf16_of(rndf() * 0.02f);
for (int s = 0; s < NS; ++s) {
W[s].norm.alloc(10240 * 4); W[s].down.alloc(dh.size() * 2); W[s].up.alloc(uh.size() * 2); W[s].inject.alloc(ih.size() * 2);
W[s].norm.put(nh.data(), 10240 * 4); W[s].down.put(dh.data(), dh.size() * 2); W[s].up.put(uh.data(), uh.size() * 2); W[s].inject.put(ih.data(), ih.size() * 2);
}
}
// scale 0: unit; 1: small activations; 2: a large dynamic range (every 7th element x 1e3, every 11th x 1e-3)
const float scales[3] = {3.0f, 1e-2f, 3.0f};
for (int T = 1; T <= 8; ++T) {
for (int apply = 0; apply < 2; ++apply) {
for (int sc = 0; sc < 3; ++sc) {
State base, a, b; alloc_state(base, T); alloc_state(a, T); alloc_state(b, T);
std::vector<float> rh((size_t)T * 10240), bh((size_t)T * 2560), ih((size_t)T * 4);
for (size_t i = 0; i < rh.size(); ++i) { rh[i] = rndf() * scales[sc]; if (sc == 2) { if (i % 7 == 0) rh[i] *= 1e3f; if (i % 11 == 0) rh[i] *= 1e-3f; } }
for (auto& v : bh) v = rndf() * (sc == 1 ? 1e-2f : 1.0f);
for (auto& v : ih) v = rndf() * 2;
base.R.put(rh.data(), rh.size() * 4); base.bo.put(bh.data(), bh.size() * 4); base.inj.put(ih.data(), ih.size() * 4);
reset(a, base); reset(b, base);
auto wa = multi_words(a, W[0], apply), wb = multi_words(b, W[0], apply);
void* pa[] = {wa.data()}; void* pb[] = {wb.data()};
run_pair(k, T, pa); launch(k.up8, 320, 1, 256, 0, pa);
run_fused(k, T, pb); launch(k.up8, 320, 1, 256, 0, pb);
CU(cuStreamSynchronize(g_s));
bool ok = same("lo", T, apply, sc, a.lo.get(), b.lo.get());
ok &= same("rs", T, apply, sc, a.rs.get(), b.rs.get());
ok &= same("inject_out", T, apply, sc, a.injo.get(), b.injo.get());
ok &= same("mixed", T, apply, sc, a.mixed.get(), b.mixed.get());
ok &= same("R", T, apply, sc, a.R.get(), b.R.get());
// the fused launch writes no xn: it must still hold the poison, every byte
const std::vector<uint8_t> xn = b.xn.get();
bool xn_untouched = std::all_of(xn.begin(), xn.end(), [](uint8_t c) { return c == 0xff; });
if (!xn_untouched) { printf("DIFF xn written by the fused launch T=%d apply=%d scale=%d\n", T, apply, sc); ++g_fail; }
printf("RESULT exact T=%d apply=%d scale=%d ok=%d\n", T, apply, sc, (int)(ok && xn_untouched));
for (Dev* d : {&base.R, &base.bo, &base.inj, &base.injo, &base.lo, &base.rs, &base.mixed, &base.xn, &a.R, &a.bo, &a.inj, &a.injo, &a.lo, &a.rs, &a.mixed, &a.xn,
&b.R, &b.bo, &b.inj, &b.injo, &b.lo, &b.rs, &b.mixed, &b.xn}) cuMemFree(d->p);
}
}
}
if (g_fail == 0) {
for (int T = 1; T <= 8; ++T) {
State s; alloc_state(s, T);
std::vector<float> rh((size_t)T * 10240); for (auto& v : rh) v = rndf() * 3; s.R.put(rh.data(), rh.size() * 4);
std::vector<std::vector<uint64_t>> ws(NS);
for (int i = 0; i < NS; ++i) ws[i] = multi_words(s, W[i], false);
double pair = time_graph([&](int i) { void* p[] = {ws[i % NS].data()}; run_pair(k, T, p); }, 64); // a node is the two launches
double fused = time_graph([&](int i) { void* p[] = {ws[i % NS].data()}; run_fused(k, T, p); }, 64);
printf("RESULT time T=%d pair_us=%.3f fused_us=%.3f\n", T, pair, fused);
}
}
printf("RESULT summary failures=%d\n", g_fail);
return g_fail ? 1 : 0;
}