verify window: LELEKA_SM120_FUSED_GDN (GDN conv + gates + step in one launch) and LELEKA_SM120_GDN_AB_UNROLL (upstream SMALL_UNR bit 1), both off by default

New sealed sm_120 asset sm120_gdn_fused.ptx (nvcc 13.2.86): leleka_verify_gdn_fused_step
(the Original's step loop over shared memory, conv prologue, gates in two warps or joined from the
SIDE_MIXER branch, split-window replay) and leleka_gdn_ab_unrolled_t1..t8. Written with the Original's
plain expressions on purpose: ptxas contracts a plain mul+sub into one FFMA, so __f*_rn intrinsics
would not be bitwise equal after the driver JIT. PTX shape compared with original_verify.ptx in unit
tests; model-free probe tools/gdn-fused written, not run (no GPU). Design: docs/experiments/verify-gdn-fused-kernels.md

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-09 23:38:50 +01:00
co-authored by Claude Sonnet 5.5
parent 91a130da6a
commit 62fd0f88a8
19 changed files with 12342 additions and 42 deletions
@@ -2726,6 +2726,13 @@
"problems": [
"not built for sm_86 by design (claude/draft-round): LELEKA_DRAFT_FUSED_COMMIT is opt-in and original_verify_schedule.rs::record_commit fuses only on a compute capability 12 card, so an sm_86 build never loads this module"
]
},
{
"name": "sm120_gdn_fused.ptx",
"sm120_path": "crates/cuda-driver/src/sm120_gdn_fused.ptx",
"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"
]
}
],
"portable_no_companion_needed": [
@@ -11,6 +11,8 @@ pub(crate) mod chain;
mod diag;
#[path = "original_verify_window_draft.rs"]
pub(crate) mod draft;
#[path = "original_verify/original_verify_window_gdn_fused.rs"]
pub(crate) mod gdn_fused;
#[path = "original_verify_window_gr.rs"]
pub(crate) mod gr;
#[path = "original_verify_window_kernels.rs"]
@@ -6,6 +6,7 @@
use super::*;
mod original_verify_window;
mod verify_gdn_fused_step;
mod verify_gdn_journal_ladder_logits_scan;
mod verify_gdn_journal_stage_and_commit;
mod verify_gdn_journal_window_launches;
@@ -0,0 +1,86 @@
//! claude/verify-gdn-fused-kernels: the journal side of the fused GDN launch and of the unrolled a/b kernel
//! (`original_verify_window_gdn_fused.rs`, `sm120_gdn_fused.cu`). The operand spans are the ones
//! `capture_layer_stage` binds for the three Original kernels.
use super::super::gdn_fused::{AbUnrolledStep, FusedGdnBuffers, FusedGdnStep, GateSource, GdnGateOperands, RowSpan};
use super::verify_gdn_journal_stage_and_commit::StageOperands;
#[allow(unused_imports)]
use super::*;
impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
/// One launch for the conv, the gates (computed inside unless `gates` says they are joined) and the recurrence of
/// layer `layer` over `rows`. Writes `h`, `gate`, `beta` and `y` of those rows exactly as the three kernels do.
pub(crate) fn capture_fused_recurrence(
&self,
capture: &mut OriginalCapture<'_, 'ctx>,
layer: usize,
rows: std::ops::Range<usize>,
gates: GateSource,
) -> Result<()> {
self.validate_context(self.physical.context)?;
let op = self.stage_operands(layer, rows.start, rows.end)?;
let gate_operands = match gates {
GateSource::InKernel => self.gate_operands(&op)?,
GateSource::Joined => GdnGateOperands::JOINED,
};
let step = FusedGdnStep {
buffers: self.fused_buffers(&op)?,
gates: gate_operands,
rows: RowSpan { begin: op.begin, end: op.end },
eps: EPS,
};
self.submit_launches(capture, vec![step.launch()?])
}
/// The alpha/beta gates of layer `layer` over `rows` by the unrolled kernel of `LELEKA_SM120_GDN_AB_UNROLL`.
pub(crate) fn capture_ab_unrolled(
&self,
capture: &mut OriginalCapture<'_, 'ctx>,
layer: usize,
rows: std::ops::Range<usize>,
) -> Result<()> {
self.validate_context(self.physical.context)?;
let op = self.stage_operands(layer, rows.start, rows.end)?;
let first_row = (op.begin * 48 * 4) as u64;
let step = AbUnrolledStep {
gates: self.gate_operands(&op)?,
gate: op.gate + first_row,
beta: op.beta + first_row,
rows: op.end - op.begin,
};
self.submit_launches(capture, vec![step.launch()?])
}
/// The buffers the three Original kernels share, by their arena spans and weights.
fn fused_buffers(&self, op: &StageOperands) -> Result<FusedGdnBuffers> {
let (g, c, w) = (self.physical.layout.geometry, self.physical.context, &self.weights[op.layer]);
Ok(FusedGdnBuffers {
state: self.canonical.span(op.layer, false)?,
hist: self.canonical.span(op.layer, true)?,
qkv: op.qkv,
conv_w: admit(c, w.conv, 10240 * 4 * 4)?,
h: op.h,
gate: op.gate,
beta: op.beta,
z: self.physical.span("z", 0, g.max_t * 6144 * 4)?,
gamma: admit(c, w.norm, 128 * 4)?,
y: self.physical.span("y", 0, g.max_t * 6144 * 4)?,
})
}
/// The a/b projection operands: the mixed rows of the stage and the layer's alpha/beta weights.
fn gate_operands(&self, op: &StageOperands) -> Result<GdnGateOperands> {
let (g, c, w) = (self.physical.layout.geometry, self.physical.context, &self.weights[op.layer]);
let n = op.end - op.begin;
if g.n != 2560 || g.value_heads != 48 {
return Err(Error::InvalidQwenShape);
}
Ok(GdnGateOperands {
x: self.physical.span("mixed", op.begin * g.n * 4, n * g.n * 4)?,
alpha_w: admit(c, w.alpha, 48 * 2560 * 2)?,
beta_w: admit(c, w.beta, 48 * 2560 * 2)?,
dt: admit(c, w.dt, 48 * 4)?,
a: admit(c, w.a, 48 * 4)?,
})
}
}
@@ -22,7 +22,7 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
self.submit(capture, single_command(commands.swap_remove(stage as usize))?)
}
/// The range check and the arena spans one layer stage works on.
fn stage_operands(&self, layer: usize, begin: usize, end: usize) -> Result<StageOperands> {
pub(super) fn stage_operands(&self, layer: usize, begin: usize, end: usize) -> Result<StageOperands> {
let g = self.physical.layout.geometry;
if layer >= 36 || begin >= end || end > g.max_t {
return Err(Error::InvalidQwenShape);
@@ -260,14 +260,14 @@ impl FusedSpans {
}
/// The arena spans and range of one GDN layer stage.
struct StageOperands {
layer: usize,
begin: usize,
end: usize,
qkv: u64,
h: u64,
gate: u64,
beta: u64,
pub(super) struct StageOperands {
pub(super) layer: usize,
pub(super) begin: usize,
pub(super) end: usize,
pub(super) qkv: u64,
pub(super) h: u64,
pub(super) gate: u64,
pub(super) beta: u64,
}
/// The base spans of the fused commit: layer `i` of every operand is `base + i * stride`.
@@ -0,0 +1,273 @@
//! claude/verify-gdn-fused-kernels: the GDN layers of the verify window as fewer launches (`sm120_gdn_fused.cu`,
//! design note `docs/experiments/verify-gdn-fused-kernels.md`).
//!
//! Two independent opt-in switches (`original_verify_window_sm120.rs`, both off by default), one sealed sm_120-only
//! asset:
//!
//! * `LELEKA_SM120_FUSED_GDN`: a GDN layer's `verify_gdn_conv_l2_multi_kernel` + `verify_gdn_ab_multi_kernel` (or
//! `chain_gdn_ab_multi_kernel`) + `verify_gdn_step_norm_multi_kernel` are recorded as ONE launch,
//! `leleka_verify_gdn_fused_step`, at the place of the recurrence. With the side-stream GDN branch
//! (`LELEKA_SM120_SIDE_MIXER`) only the conv is fused: the gates stay on side stream 0 and are read.
//! * `LELEKA_SM120_GDN_AB_UNROLL`: upstream `STRATA_SMALL_UNR` bit 1 (`gdn_ab_body`), the a/b projection with constant
//! trip counts, as its own kernel (`leleka_gdn_ab_unrolled_t*`) wherever the a/b projection runs as a kernel of its
//! own (no `FUSED_GDN`, or the side-stream branch).
//!
//! Both compute every output word with the operations of the kernels they replace, in the same order.
use super::kernels::{A, AssetSpec, Launch, LaunchExtent};
use super::sm120::Sm120Switches;
// `ptx` below is read from `../sm120_gdn_fused.ptx` (this file lives one directory below the sealed assets)
use crate::{Error, Result};
pub(crate) const E_FUSED_STEP: &str = "leleka_verify_gdn_fused_step";
/// Unrolled a/b kernels: constant token count for T = 1..=6, the run time count for T = 7 and 8 (upstream's split).
pub(crate) const E_AB_UNROLLED: [&str; 7] = [
"leleka_gdn_ab_unrolled_t1",
"leleka_gdn_ab_unrolled_t2",
"leleka_gdn_ab_unrolled_t3",
"leleka_gdn_ab_unrolled_t4",
"leleka_gdn_ab_unrolled_t5",
"leleka_gdn_ab_unrolled_t6",
"leleka_gdn_ab_unrolled_t8",
];
const ENTRIES: [&str; 8] = [
E_FUSED_STEP,
E_AB_UNROLLED[0],
E_AB_UNROLLED[1],
E_AB_UNROLLED[2],
E_AB_UNROLLED[3],
E_AB_UNROLLED[4],
E_AB_UNROLLED[5],
E_AB_UNROLLED[6],
];
/// `sm120_gdn_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 GDN_FUSED: AssetSpec = AssetSpec {
name: "sm120_gdn_fused.ptx",
ptx: concat!(include_str!("../sm120_gdn_fused.ptx"), "\0").as_bytes(),
sha: [
157, 163, 62, 130, 23, 193, 228, 218, 162, 210, 111, 151, 57, 135, 73, 120, 233, 194, 6, 235, 95, 48, 249, 65,
127, 93, 248, 181, 38, 227, 127, 23,
],
entries: &ENTRIES,
unsealed: "Original verifier asset unsealed: sm120_gdn_fused.ptx (fused GDN layer step, unrolled GDN alpha/beta)",
};
/// The window's rows of the verify graph and the width of the a/b projection input.
pub(crate) const MAX_ROWS: usize = 8;
const N_EMBD: i32 = 2560;
const VALUE_HEADS: u32 = 48;
/// What one `WindowOps` call of a GDN layer records.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum GdnStep {
/// Nothing: another call covers it.
Skip,
/// The Original's kernel of this stage (or the chain kernel when `LELEKA_CHAIN_AB` is on).
Original,
/// The unrolled a/b kernel of `LELEKA_SM120_GDN_AB_UNROLL`.
AbUnrolled,
/// The fused launch (conv, gates and step), with the gates computed inside or read.
Fused(GateSource),
}
/// Where the fused launch gets gate and beta.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum GateSource {
/// Computed by two warps of every block and written to `gate` / `beta`.
InKernel,
/// Already in `gate` / `beta` (the side-stream branch computed them and joined before the launch).
Joined,
}
/// The three `WindowOps` calls of a GDN layer, in graph order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct GdnStages {
pub conv: GdnStep,
pub alpha_beta: GdnStep,
pub recurrence: GdnStep,
}
impl GdnStages {
/// Kernel launches the layer records on the capture stream, without the side-stream branch.
#[cfg(test)]
pub(crate) fn launches(&self) -> usize {
[self.conv, self.alpha_beta, self.recurrence].iter().filter(|s| **s != GdnStep::Skip).count()
}
}
/// The resolved switches of one window recording.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct GdnFusedPolicy {
pub fused_step: bool,
pub ab_unroll: bool,
}
impl GdnFusedPolicy {
pub(crate) fn from_switches(s: &Sm120Switches) -> Self {
Self { fused_step: s.fused_gdn, ab_unroll: s.gdn_ab_unroll }
}
/// The asset the window preloads before capture (none when both switches are off).
pub(crate) fn assets(self) -> Vec<&'static AssetSpec> {
if self.fused_step || self.ab_unroll { vec![&GDN_FUSED] } else { Vec::new() }
}
/// The a/b stage as a kernel of its own (a graph without `FUSED_GDN`, and the side-stream branch).
pub(crate) fn separate_ab(self) -> GdnStep {
if self.ab_unroll { GdnStep::AbUnrolled } else { GdnStep::Original }
}
/// What the three calls of a GDN layer record; `side_gdn`: the gates run on side stream 0.
pub(crate) fn stages(self, side_gdn: bool) -> GdnStages {
if self.fused_step {
let gates = if side_gdn { GateSource::Joined } else { GateSource::InKernel };
return GdnStages { conv: GdnStep::Skip, alpha_beta: GdnStep::Skip, recurrence: GdnStep::Fused(gates) };
}
let alpha_beta = if side_gdn { GdnStep::Skip } else { self.separate_ab() };
GdnStages { conv: GdnStep::Original, alpha_beta, recurrence: GdnStep::Original }
}
}
/// Resolves the switches for the card and loads the asset before capture (module loading is not capturable). A
/// requested switch whose asset is not sealed refuses the recording, so a paired A/B never runs the default path
/// under the name of the switch.
pub(crate) fn prepare(journal: &super::OriginalVerifyGdnJournal<'_, '_>) -> Result<GdnFusedPolicy> {
let major = journal.window_device_attribute(super::gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?;
let minor = journal.window_device_attribute(super::gr::ATTR_COMPUTE_CAPABILITY_MINOR)?;
let policy = GdnFusedPolicy::from_switches(&Sm120Switches::from_env(major, minor));
journal.ensure_window_assets(&policy.assets())?;
if policy != GdnFusedPolicy::default() {
static SAID: std::sync::Once = std::sync::Once::new();
SAID.call_once(|| eprintln!("leleka-serve gdn kernels: {policy:?} (compute capability {major}.{minor})"));
}
Ok(policy)
}
/// Device addresses of the buffers of one GDN layer the fused launch reads and writes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct FusedGdnBuffers {
/// Canonical recurrence state of the layer (read only: the window never writes it).
pub state: u64,
/// Canonical conv history of the layer (read only).
pub hist: u64,
pub qkv: u64,
pub conv_w: u64,
/// Conv + L2 rows: written for the new tokens (q and k by the blocks of value heads 0..16, v by every block).
pub h: u64,
pub gate: u64,
pub beta: u64,
pub z: u64,
pub gamma: u64,
pub y: u64,
}
/// The a/b projection operands: the activation row of the first new token (0: gate and beta are already computed).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct GdnGateOperands {
pub x: u64,
pub alpha_w: u64,
pub beta_w: u64,
pub dt: u64,
pub a: u64,
}
impl GdnGateOperands {
pub(crate) const JOINED: Self = Self { x: 0, alpha_w: 0, beta_w: 0, dt: 0, a: 0 };
}
/// The rows a stage works on: the new tokens `begin..end`; the tokens before `begin` are replayed from the buffers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct RowSpan {
pub begin: usize,
pub end: usize,
}
/// One launch of `leleka_verify_gdn_fused_step`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct FusedGdnStep {
pub buffers: FusedGdnBuffers,
pub gates: GdnGateOperands,
pub rows: RowSpan,
pub eps: f32,
}
impl FusedGdnStep {
/// The by-value kernel argument `FusedGdnArgs` of `sm120_gdn_fused.cu`, in declaration order.
pub(crate) fn words(&self) -> Vec<u64> {
let (b, g) = (&self.buffers, &self.gates);
vec![
b.state,
b.hist,
b.qkv,
b.conv_w,
b.h,
b.gate,
b.beta,
b.z,
b.gamma,
b.y,
g.x,
g.alpha_w,
g.beta_w,
g.dt,
g.a,
u64::from(self.eps.to_bits()),
self.rows.begin as u64,
self.rows.end as u64,
]
}
/// 48 blocks (one per value head) of 128 x 4 threads, as the Original's step kernel.
pub(crate) fn launch(&self) -> Result<Launch> {
if self.rows.begin >= self.rows.end || self.rows.end > MAX_ROWS {
return Err(Error::InvalidQwenShape);
}
Launch::new(
&GDN_FUSED,
E_FUSED_STEP,
LaunchExtent::new([VALUE_HEADS, 1, 1], [128, 4, 1], 0),
vec![A::Words(self.words())],
)
}
}
/// One launch of the unrolled a/b projection: the Original's arguments, `rows` tokens.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct AbUnrolledStep {
pub gates: GdnGateOperands,
/// `gate` and `beta` of the first token of the stage.
pub gate: u64,
pub beta: u64,
pub rows: usize,
}
impl AbUnrolledStep {
/// The entry for `rows` tokens: constant count up to 6, the run time count above (upstream's `kVerifyNarrowT`).
pub(crate) fn entry(rows: usize) -> Result<&'static str> {
match rows {
1..=6 => Ok(E_AB_UNROLLED[rows - 1]),
7 | 8 => Ok(E_AB_UNROLLED[6]),
_ => Err(Error::InvalidQwenShape),
}
}
/// One warp a row of the 96 (alpha, then beta): 96 blocks of 32 threads, the shape of `chain_gdn_ab_multi_kernel`
/// (what `LELEKA_CHAIN=all` records), so the unrolled loop is the only difference to the shipped kernel. Upstream's
/// own shape, 48 blocks of 64 threads, runs the same kernel.
pub(crate) fn launch(&self) -> Result<Launch> {
let g = &self.gates;
let args = vec![
A::P(g.x),
A::P(g.alpha_w),
A::P(g.beta_w),
A::P(g.dt),
A::P(g.a),
A::P(self.gate),
A::P(self.beta),
A::I32(N_EMBD),
A::I32(VALUE_HEADS as i32),
A::I32(self.rows as i32),
];
Launch::new(
&GDN_FUSED,
Self::entry(self.rows)?,
LaunchExtent::new([2 * VALUE_HEADS, 1, 1], [32, 1, 1], 0),
args,
)
}
}
#[cfg(test)]
#[path = "original_verify_window_gdn_fused/tests.rs"]
mod tests;
@@ -0,0 +1,311 @@
use super::*;
use crate::original_verify::sm120::{DEFAULT_ON_FUSED_GDN, DEFAULT_ON_GDN_AB_UNROLL};
const FUSED_PTX: &str = include_str!("../../sm120_gdn_fused.ptx");
const FUSED_CU: &str = include_str!("../../sm120_gdn_fused.cu");
const ORIGINAL_PTX: &str = include_str!("../../original_verify.ptx");
const CHAIN_PTX: &str = include_str!("../../chain_window.ptx");
fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
move |k| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string())
}
fn policy(major: i32, minor: i32, pairs: &'static [(&'static str, &'static str)]) -> GdnFusedPolicy {
GdnFusedPolicy::from_switches(&Sm120Switches::resolve(major, minor, env(pairs)))
}
#[test]
fn both_switches_are_off_by_default() {
assert!(!DEFAULT_ON_FUSED_GDN && !DEFAULT_ON_GDN_AB_UNROLL);
assert_eq!(policy(12, 0, &[]), GdnFusedPolicy::default());
assert_eq!(policy(12, 0, &[("LELEKA_SM120_PERF", "0")]), GdnFusedPolicy::default());
assert!(policy(12, 0, &[]).assets().is_empty());
}
#[test]
fn each_variable_turns_on_its_own_switch_and_nothing_else() {
let fused = policy(12, 0, &[("LELEKA_SM120_FUSED_GDN", "1")]);
assert_eq!(fused, GdnFusedPolicy { fused_step: true, ab_unroll: false });
let unroll = policy(12, 0, &[("LELEKA_SM120_GDN_AB_UNROLL", "on")]);
assert_eq!(unroll, GdnFusedPolicy { fused_step: false, ab_unroll: true });
let both = policy(12, 1, &[("LELEKA_SM120_FUSED_GDN", "1"), ("LELEKA_SM120_GDN_AB_UNROLL", "1")]);
assert_eq!(both, GdnFusedPolicy { fused_step: true, ab_unroll: true });
assert!(!policy(12, 0, &[("LELEKA_SM120_FUSED_GDN", "0")]).fused_step);
for p in [fused, unroll, both] {
assert_eq!(p.assets().len(), 1);
assert!(std::ptr::eq(p.assets()[0], &GDN_FUSED));
}
}
#[test]
fn a_card_below_compute_capability_12_never_takes_a_switch() {
let on = &[("LELEKA_SM120_FUSED_GDN", "1"), ("LELEKA_SM120_GDN_AB_UNROLL", "1")];
assert_eq!(policy(8, 6, on), GdnFusedPolicy::default());
assert_eq!(policy(9, 0, on), GdnFusedPolicy::default());
}
#[test]
fn the_asset_is_sealed_and_exports_every_entry() {
GDN_FUSED.assert_sealed_and_fail_closed();
assert_eq!(GDN_FUSED.entries.len(), 1 + E_AB_UNROLLED.len());
assert!(GDN_FUSED.has_entry(E_FUSED_STEP));
}
#[test]
fn a_default_layer_records_the_original_three_kernels() {
let off = GdnFusedPolicy::default();
let stages = off.stages(false);
let original = GdnStep::Original;
assert_eq!(stages, GdnStages { conv: original, alpha_beta: original, recurrence: original });
assert_eq!(stages.launches(), 3);
// side-stream branch: the gates are another stream's launch, three kernels in all
let side = off.stages(true);
assert_eq!(side.alpha_beta, GdnStep::Skip);
assert_eq!(side.launches() + 1, 3);
}
#[test]
fn the_fused_switch_records_one_launch_per_layer() {
let on = GdnFusedPolicy { fused_step: true, ab_unroll: false };
let stages = on.stages(false);
assert_eq!(stages.conv, GdnStep::Skip);
assert_eq!(stages.alpha_beta, GdnStep::Skip);
assert_eq!(stages.recurrence, GdnStep::Fused(GateSource::InKernel));
assert_eq!(stages.launches(), 1);
// 36 layers: 108 launches against 36
assert_eq!(36 * GdnFusedPolicy::default().stages(false).launches(), 108);
assert_eq!(36 * stages.launches(), 36);
}
#[test]
fn with_the_side_branch_only_the_conv_is_fused() {
let on = GdnFusedPolicy { fused_step: true, ab_unroll: false };
let side = on.stages(true);
assert_eq!(side.recurrence, GdnStep::Fused(GateSource::Joined));
assert_eq!((side.conv, side.alpha_beta), (GdnStep::Skip, GdnStep::Skip));
// the fused launch and the gates on side stream 0: two launches against the side branch's three
assert_eq!(side.launches() + 1, 2);
assert_eq!(GdnFusedPolicy::default().stages(true).launches() + 1, 3);
}
#[test]
fn the_unrolled_gates_replace_only_the_ab_kernel() {
let on = GdnFusedPolicy { fused_step: false, ab_unroll: true };
let stages = on.stages(false);
assert_eq!(stages.alpha_beta, GdnStep::AbUnrolled);
assert_eq!((stages.conv, stages.recurrence), (GdnStep::Original, GdnStep::Original));
assert_eq!(stages.launches(), 3);
// the side branch still issues the gates, as the unrolled kernel
assert_eq!(on.stages(true).alpha_beta, GdnStep::Skip);
assert_eq!(on.separate_ab(), GdnStep::AbUnrolled);
assert_eq!(GdnFusedPolicy::default().separate_ab(), GdnStep::Original);
// fused + unroll: the gates are inside the fused launch, the unrolled kernel is only for the side branch
let both = GdnFusedPolicy { fused_step: true, ab_unroll: true };
assert_eq!(both.stages(false).launches(), 1);
assert_eq!(both.separate_ab(), GdnStep::AbUnrolled);
}
fn step(begin: usize, end: usize, gates: GdnGateOperands) -> FusedGdnStep {
FusedGdnStep {
buffers: FusedGdnBuffers {
state: 0x100,
hist: 0x200,
qkv: 0x300,
conv_w: 0x400,
h: 0x500,
gate: 0x600,
beta: 0x700,
z: 0x800,
gamma: 0x900,
y: 0xa00,
},
gates,
rows: RowSpan { begin, end },
eps: 1e-6,
}
}
#[rustfmt::skip]
const KERNEL_ARGUMENT_MEMBERS: [&str; 18] = [
"state", "hist", "qkv", "conv_w", "h", "gate", "beta", "z", "gamma", "y",
"ab_x", "ab_alpha_w", "ab_beta_w", "ab_dt", "ab_a", "eps_bits", "t_begin", "t_end",
];
const GATES: GdnGateOperands = GdnGateOperands { x: 0xb00, alpha_w: 0xc00, beta_w: 0xd00, dt: 0xe00, a: 0xf00 };
#[test]
fn the_fused_launch_is_one_block_per_value_head_like_the_originals_step() {
let launch = step(0, 4, GATES).launch().unwrap();
assert_eq!((launch.grid, launch.block, launch.shared), ([48, 1, 1], [128, 4, 1], 0));
assert_eq!(launch.entry, E_FUSED_STEP);
assert!(std::ptr::eq(launch.asset, &GDN_FUSED));
assert_eq!(launch.args.len(), 1);
}
#[test]
fn the_argument_words_follow_the_struct_of_the_kernel_source() {
let words = step(2, 5, GATES).words();
assert_eq!(
words,
vec![0x100, 0x200, 0x300, 0x400, 0x500, 0x600, 0x700, 0x800, 0x900, 0xa00, 0xb00, 0xc00, 0xd00, 0xe00, 0xf00]
.into_iter()
.chain([u64::from(1e-6f32.to_bits()), 2, 5])
.collect::<Vec<u64>>()
);
let (_, body) = FUSED_CU.split_once("struct FusedGdnArgs {").expect("struct in the source");
let body = body.split_once("};").expect("end of the struct").0;
let members: Vec<&str> = body
.lines()
.filter_map(|l| l.trim().strip_prefix("uint64_t "))
.map(|l| l.split(';').next().unwrap().trim())
.collect();
assert_eq!(members, KERNEL_ARGUMENT_MEMBERS);
assert_eq!(members.len(), words.len());
}
#[test]
fn the_fused_launch_writes_what_the_three_kernels_write() {
// conv -> h, ab -> gate and beta, step -> y: the fused launch is given exactly these four (state and history are
// read only: the window never writes them), and a joined launch carries no activation row, so it computes no gate
let words = step(0, 3, GATES).words();
assert_eq!([words[4], words[5], words[6], words[9]], [0x500, 0x600, 0x700, 0xa00]);
assert_ne!(words[10], 0);
let joined = step(0, 3, GdnGateOperands::JOINED).words();
assert_eq!(joined[10..15], [0; 5]);
assert_eq!(joined[..10], words[..10]);
}
#[test]
fn the_fused_launch_refuses_empty_and_oversized_row_ranges() {
assert!(step(0, 8, GATES).launch().is_ok());
assert!(step(7, 8, GATES).launch().is_ok());
assert_eq!(step(3, 3, GATES).launch().unwrap_err(), Error::InvalidQwenShape);
assert_eq!(step(0, 9, GATES).launch().unwrap_err(), Error::InvalidQwenShape);
}
#[test]
fn the_unrolled_entry_follows_the_token_count_like_upstream() {
for rows in 1..=6 {
assert_eq!(AbUnrolledStep::entry(rows).unwrap(), format!("leleka_gdn_ab_unrolled_t{rows}"));
}
assert_eq!(AbUnrolledStep::entry(7).unwrap(), "leleka_gdn_ab_unrolled_t8");
assert_eq!(AbUnrolledStep::entry(8).unwrap(), "leleka_gdn_ab_unrolled_t8");
assert!(AbUnrolledStep::entry(0).is_err() && AbUnrolledStep::entry(9).is_err());
}
#[test]
fn the_unrolled_launch_takes_the_arguments_of_the_original_ab_kernel() {
let unrolled = AbUnrolledStep { gates: GATES, gate: 0x1100, beta: 0x1200, rows: 4 };
let launch = unrolled.launch().unwrap();
// verify_gdn_ab_multi_kernel(x, wa, wb, dt, ssm_a, gate, beta, n = 2560, h_v = 48, T)
assert_eq!(
launch.args,
vec![
A::P(0xb00),
A::P(0xc00),
A::P(0xd00),
A::P(0xe00),
A::P(0xf00),
A::P(0x1100),
A::P(0x1200),
A::I32(2560),
A::I32(48),
A::I32(4)
]
);
assert_eq!((launch.grid, launch.block), ([96, 1, 1], [32, 1, 1]));
assert!(AbUnrolledStep { rows: 0, ..unrolled }.launch().is_err());
}
// ---- the sealed PTX against the Original's: same operations in the same order (CPU-side, no GPU) ----
/// The body of the `.entry` whose name is exactly `name`.
fn entry_body<'t>(ptx: &'t str, name: &str) -> &'t str {
let start = ptx.find(&format!(".entry {name}(")).unwrap_or_else(|| panic!("no entry {name}"));
let end = ptx[start..].find("\n}\n").map_or(ptx.len(), |e| start + e);
&ptx[start..end]
}
/// Float arithmetic, shuffles and barriers of an entry, in program order (loads, stores, moves and address
/// arithmetic differ between a fused and a split producer).
fn numeric_sequence(body: &str) -> Vec<String> {
let numeric = |op: &str| {
let float = ["add", "sub", "mul", "fma", "div", "rcp", "rsqrt", "ex2"].iter().any(|p| op.starts_with(p));
(float && op.contains(".f32")) || op.starts_with("shfl.") || op.starts_with("bar.sync")
};
body.lines()
.map(str::trim)
.map(|l| if l.starts_with('@') { l.split_once(' ').map_or("", |(_, rest)| rest.trim()) } else { l })
.filter_map(|l| l.split_whitespace().next())
.map(|op| op.trim_end_matches(';'))
.filter(|op| numeric(op))
.map(str::to_owned)
.collect()
}
fn ops(names: &[&str]) -> Vec<String> {
names.iter().map(|s| s.to_string()).collect()
}
fn contains_run(hay: &[String], needle: &[String]) -> bool {
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
}
fn distinct(seq: &[String]) -> std::collections::BTreeSet<&str> {
seq.iter().map(String::as_str).collect()
}
#[test]
fn the_fused_conv_is_the_originals_conv_instruction_for_instruction() {
let original = numeric_sequence(entry_body(ORIGINAL_PTX, "verify_gdn_conv_l2_multi_kernel"));
let fused = numeric_sequence(entry_body(FUSED_PTX, E_FUSED_STEP));
// mul + 3 fma (the four taps), silu by div.rn, y * y, five butterfly adds, the barrier, the L2 sum, rsqrt, scale
assert_eq!(original.len(), 26, "{original:?}");
assert!(contains_run(&fused, &original), "the conv of the Original is not a run of the fused kernel");
}
#[test]
fn the_fused_step_keeps_the_originals_unfused_delta_and_its_output_tail() {
let original = numeric_sequence(entry_body(ORIGINAL_PTX, "verify_gdn_step_norm_multi_kernel"));
let fused = numeric_sequence(entry_body(FUSED_PTX, E_FUSED_STEP));
// kv_col (three adds), then delta = beta * (v - g * kv): mul, sub, mul and no fma (ptxas contracts a plain
// mul + sub into one FFMA at load time, in the Original and in this kernel alike)
let delta = ops(&["add.f32", "add.f32", "add.f32", "mul.f32", "sub.f32", "mul.f32"]);
assert!(contains_run(&original, &delta) && contains_run(&fused, &delta));
// oc = sum * rsqrt(128) (evaluated at run time), the five butterfly adds, ss/128 + eps as one fma, rsqrt, three
// multiplies, the sigmoid by rcp.rn
#[rustfmt::skip]
let tail = ops(&[
"add.f32", "add.f32", "add.f32", "rsqrt.approx.f32", "mul.f32", "mul.f32",
"shfl.sync.bfly.b32", "add.f32", "shfl.sync.bfly.b32", "add.f32", "shfl.sync.bfly.b32", "add.f32",
"shfl.sync.bfly.b32", "add.f32", "shfl.sync.bfly.b32", "add.f32", "bar.sync",
"add.f32", "add.f32", "add.f32", "fma.rn.f32", "rsqrt.approx.f32", "mul.f32", "mul.f32", "mul.f32",
"ex2.approx.f32", "add.f32", "rcp.rn.f32", "mul.f32",
]);
assert!(contains_run(&original, &tail), "the Original's tail changed");
assert!(contains_run(&fused, &tail), "the fused output tail differs from the Original's");
}
#[test]
fn the_fused_kernel_has_no_flavour_the_original_kernels_do_not_have() {
let mut union: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
for name in ["verify_gdn_conv_l2_multi_kernel", "verify_gdn_ab_multi_kernel", "verify_gdn_step_norm_multi_kernel"] {
union.extend(distinct(&numeric_sequence(entry_body(ORIGINAL_PTX, name))).into_iter().map(str::to_owned));
}
let fused = numeric_sequence(entry_body(FUSED_PTX, E_FUSED_STEP));
let fused_set: std::collections::BTreeSet<String> = distinct(&fused).into_iter().map(str::to_owned).collect();
assert_eq!(fused_set, union);
// no explicit-rounding intrinsic, no flush to zero, no approximate division: plain contractible forms only
assert!(fused.iter().all(|op| !op.contains(".ftz") && !op.contains("div.approx") && !op.contains("div.full")));
assert!(fused.iter().all(|op| !matches!(op.as_str(), "add.rn.f32" | "mul.rn.f32" | "sub.rn.f32")));
}
#[test]
fn every_unrolled_ab_kernel_has_the_original_ab_kernels_flavours() {
let original = numeric_sequence(entry_body(ORIGINAL_PTX, "verify_gdn_ab_multi_kernel"));
let chain = numeric_sequence(entry_body(CHAIN_PTX, "chain_gdn_ab_multi_kernel"));
assert_eq!(distinct(&original), distinct(&chain));
for entry in E_AB_UNROLLED {
let unrolled = numeric_sequence(entry_body(FUSED_PTX, entry));
assert_eq!(distinct(&unrolled), distinct(&original), "{entry}");
// the multiply-adds of the dot product: eight per weight word and token, ten passes
let fmas = |seq: &[String]| seq.iter().filter(|op| *op == "fma.rn.f32").count();
let tokens: usize = entry.rsplit('t').next().unwrap().parse().unwrap();
assert!(fmas(&unrolled) >= 8 * 10 * tokens, "{entry}: {} fmas", fmas(&unrolled));
}
}
@@ -88,6 +88,8 @@ pub(crate) struct OriginalVerifyWindowOps<'c, 's, 'a, 'ctx> {
t: usize,
groups: usize,
policy: WindowPolicy,
/// The GDN kernel switches (`original_verify_window_gdn_fused.rs`).
gdn: gdn_fused::GdnFusedPolicy,
}
#[cfg(test)]
@@ -102,6 +104,8 @@ pub(super) use all_window_assets::all_window_assets;
use all_window_assets::unsealed_keys;
#[allow(unused_imports)]
pub use all_window_assets::unsealed_window_assets;
#[path = "original_verify_window_ops/gdn_stages.rs"]
mod gdn_stages;
#[path = "original_verify_window_ops/original_verifier.rs"]
mod original_verifier;
#[path = "original_verify_window_ops/original_verify_window_ops_methods.rs"]
@@ -0,0 +1,57 @@
//! claude/verify-gdn-fused-kernels: what the three GDN `WindowOps` calls of a layer record
//! (`GdnFusedPolicy::stages`, `original_verify_window_gdn_fused.rs`). With both switches off every call records the
//! Original's kernel as before.
use super::gdn_fused::{GdnStages, GdnStep};
#[allow(unused_imports)]
use super::*;
impl OriginalVerifyWindowOps<'_, '_, '_, '_> {
fn gdn_stages(&self) -> GdnStages {
self.gdn.stages(self.side_gdn())
}
/// The Original's kernel (or the chain kernel) of one GDN stage.
fn gdn_original_stage(&mut self, stage: OriginalVerifyGdnStage, layer: usize, rows: Rows) -> Result<()> {
self.resources.base.journal.capture_layer_stage(stage, self.capture, layer, rows.begin..rows.end)
}
/// The a/b gates as a kernel of their own: the Original's, or the unrolled one of `GDN_AB_UNROLL`. Used by the
/// ordinary call and by the side-stream branch.
pub(super) fn gdn_alpha_beta_kernel(&mut self, layer: usize, rows: Rows) -> Result<()> {
match self.gdn.separate_ab() {
GdnStep::AbUnrolled => {
self.resources.base.journal.capture_ab_unrolled(self.capture, layer, rows.begin..rows.end)
}
_ => self.gdn_original_stage(OriginalVerifyGdnStage::AlphaBeta, layer, rows),
}
}
pub(super) fn gdn_conv_stage(&mut self, layer: usize, rows: Rows) -> Result<()> {
match self.gdn_stages().conv {
GdnStep::Skip => Ok(()), // the fused launch convolves
_ => self.gdn_original_stage(OriginalVerifyGdnStage::Conv, layer, rows),
}
}
pub(super) fn gdn_alpha_beta_stage(&mut self, layer: usize, rows: Rows) -> Result<()> {
match self.gdn_stages().alpha_beta {
GdnStep::Skip => Ok(()), // issued on side stream 0 by `issue_gdn_side`, or computed by the fused launch
_ => self.gdn_alpha_beta_kernel(layer, rows),
}
}
pub(super) fn gdn_recurrence_stage(&mut self, layer: usize, rows: Rows) -> Result<()> {
if self.side_gdn() {
// the recurrence reads the gates and the gate projection: the capture stream joins both branches
self.capture.side_join(0)?;
self.capture.side_join(1)?;
}
match self.gdn_stages().recurrence {
GdnStep::Fused(gates) => {
self.resources.base.journal.capture_fused_recurrence(self.capture, layer, rows.begin..rows.end, gates)
}
_ => self.gdn_original_stage(OriginalVerifyGdnStage::Recurrence, layer, rows),
}
}
}
@@ -25,11 +25,12 @@ impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> {
// Sealed modules load before capture begins (cuModuleLoadData is not a capturable call).
let mut resources = resources;
resources.prepare(&policy)?;
let gdn = gdn_fused::prepare(resources.verifier_journal())?;
// SIDE_MIXER: this recording's capture creates the two side streams (a split window just leaves them unused)
crate::original_gpu_schedule::set_side_streams_wanted(policy.side.any());
let recorded = self.record_window(t, resources, |capture, resources, groups| {
// The recorder re-validates the shape; the groups come from `set_split`.
let mut ops = OriginalVerifyWindowOps { capture, resources, t, groups, policy };
let mut ops = OriginalVerifyWindowOps { capture, resources, t, groups, policy, gdn };
record_window(&mut ops, &policy, t, groups, ple)
});
crate::original_gpu_schedule::set_side_streams_wanted(false);
@@ -16,12 +16,7 @@ impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> {
pub(super) fn issue_gdn_side(&mut self, layer: usize, rows: Rows) -> Result<()> {
let g = gdn_index(layer).ok_or(Error::InvalidQwenShape)?;
self.capture.side_fork(0)?;
self.resources.base.journal.capture_layer_stage(
OriginalVerifyGdnStage::AlphaBeta,
self.capture,
g,
rows.begin..rows.end,
)?;
self.gdn_alpha_beta_kernel(g, rows)?;
self.capture.side_end(0)?;
self.capture.side_fork(1)?;
self.plan_launch(|p| p.mmvq(layer, Projection::GdnGate, rows))?;
@@ -51,36 +51,13 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
self.plan_launch(|p| p.mmvq(layer, projection, rows))
}
fn gdn_conv(&mut self, layer: usize, rows: Rows) -> Result<()> {
self.resources.base.journal.capture_layer_stage(
OriginalVerifyGdnStage::Conv,
self.capture,
layer,
rows.begin..rows.end,
)
self.gdn_conv_stage(layer, rows)
}
fn gdn_alpha_beta(&mut self, layer: usize, rows: Rows) -> Result<()> {
if self.side_gdn() {
return Ok(()); // issued on side stream 0 by `issue_gdn_side`
}
self.resources.base.journal.capture_layer_stage(
OriginalVerifyGdnStage::AlphaBeta,
self.capture,
layer,
rows.begin..rows.end,
)
self.gdn_alpha_beta_stage(layer, rows)
}
fn gdn_recurrence(&mut self, layer: usize, rows: Rows) -> Result<()> {
if self.side_gdn() {
// the recurrence reads the gates and the gate projection: the capture stream joins both branches
self.capture.side_join(0)?;
self.capture.side_join(1)?;
}
self.resources.base.journal.capture_layer_stage(
OriginalVerifyGdnStage::Recurrence,
self.capture,
layer,
rows.begin..rows.end,
)
self.gdn_recurrence_stage(layer, rows)
}
fn qsa_index_k(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> {
if self.side_qsa() {
@@ -78,6 +78,9 @@ pub(crate) const DEFAULT_ON_GU_SWIGLU: bool = false;
pub(crate) const DEFAULT_ON_SIDE_MIXER: bool = false;
pub(crate) const DEFAULT_ON_SIDE_QSA: bool = false;
pub(crate) const DEFAULT_ON_SIDE_SHARED: 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;
/// 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
@@ -113,6 +116,11 @@ pub struct Sm120Switches {
pub side_qsa: bool,
/// The shared expert on a side stream, beside the routed experts.
pub side_shared: bool,
// ---- claude/verify-gdn-fused-kernels
/// `LELEKA_SM120_FUSED_GDN`: a GDN layer's conv, a/b gates and step as one launch (`sm120_gdn_fused.cu`).
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,
}
fn one(get: &impl Fn(&str) -> Option<String>, var: &str, default: bool) -> bool {
@@ -155,6 +163,8 @@ impl Sm120Switches {
side_mixer: switch("LELEKA_SM120_SIDE_MIXER", DEFAULT_ON_SIDE_MIXER),
side_qsa: switch("LELEKA_SM120_SIDE_QSA", DEFAULT_ON_SIDE_QSA),
side_shared: switch("LELEKA_SM120_SIDE_SHARED", DEFAULT_ON_SIDE_SHARED),
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),
}
}
/// The side-stream parts these switches ask for.
@@ -169,6 +179,8 @@ impl Sm120Switches {
side_mixer: overridden(&OVERRIDE_SIDE_MIXER, s.side_mixer),
side_qsa: s.side_qsa,
side_shared: s.side_shared,
fused_gdn: s.fused_gdn,
gdn_ab_unroll: s.gdn_ab_unroll,
}
}
}
+310
View File
@@ -0,0 +1,310 @@
// verify window, GDN layers (docs/experiments/verify-gdn-fused-kernels.md). Two switches, one asset, sm_120 only.
//
// LELEKA_SM120_FUSED_GDN: the three kernels of a GDN layer of the Original-literal verify window
// verify_gdn_conv_l2_multi_kernel (grid 80 x T) -> verify_gdn_ab_multi_kernel / chain_gdn_ab_multi_kernel -> verify_gdn_step_norm_multi_kernel (48 blocks of 128 x 4)
// as ONE launch of the Original's step loop (`leleka_verify_gdn_fused_step`, 48 blocks of 128 x 4, one block per value head):
// * the conv prologue: the block convolves its head's q, k and v channels (three chunks of 128) for the NEW tokens [t_begin, t_end) into shared memory. The blocks of heads < 16 write q and k to `h`
// (one writer per q/k chunk), every block writes its v chunk, because the commit graph (draft_commit.cu) and a later split-window group read `h`;
// * the gates: with ab_x != 0 two warps (alpha row `head`, beta row `head`) compute gate and beta of the new tokens and write them to `gate` / `beta`; with ab_x == 0 (SIDE_MIXER: they came from
// side stream 0 and the stream joined before this launch) they are read;
// * the tokens before t_begin (a split window's earlier group) are read from h / gate / beta, as the Original reads them;
// * the step loop: the Original's loop with its loads redirected to shared memory. A replayed token (t < t_begin) needs the state update only: its o dot product and the output path
// never feed the state and are not computed (as draft_commit.cu).
// Every output word is computed by the same operations in the same order as by the kernels above. The arithmetic is written with the SAME plain C++ expressions as original_verify.cu
// and NOT with __fmul_rn / __fadd_rn intrinsics: ptxas contracts a plain `mul.f32` feeding an `add.f32` / `sub.f32` into one FFMA (checked with ptxas 13.2 on a two instruction kernel),
// the `.rn` forms it never contracts, so the loader's JIT of original_verify.ptx fuses `v - g * kv` (the sealed PTX has a plain mul.f32 + sub.f32) and an intrinsic version would not.
// The same expression shape gives the same PTX, hence the same contraction decisions (the PTX of every phase is compared with the sealed one by a unit test).
//
// LELEKA_SM120_GDN_AB_UNROLL: upstream STRATA_SMALL_UNR bit 1 (08b20b104, gdn_ab_body): the same a/b projection with the weight/activation loop at constant trip counts (ten passes of 32 lanes, a
// constant number of tokens for T <= 6), as its own entries `leleka_gdn_ab_unrolled_t*`. One warp a row (96 rows: alpha 0..47, beta 48..95), any block of 1 or 2 warps: the host launches
// 96 blocks of 32 threads (the shape of chain_gdn_ab_multi_kernel, which `LELEKA_CHAIN=all` records) or upstream's 48 blocks of 64.
//
// Compile: nvcc --ptx -O3 -arch=sm_120 -std=c++17 --fmad=true --ftz=false (the recipe of original_verify.cu / draft_commit.cu, which are not on the fast-math list).
#include <cuda_runtime.h>
#include <cstdint>
#include <cstddef>
constexpr int S = 128, RG = 4, RPG = S / RG;
constexpr int H_K = 16, H_V = 48, C_QKV = 10240, QK = S * H_K, VALUE_DIM = S * H_V;
constexpr int MAX_N = 8; // window rows (max_t)
constexpr int N_EMBD = 2560, AB_CHUNKS = N_EMBD / 8 / 32; // ten passes of 32 lanes over a weight row of 320 uint4
// by-value kernel argument: u64 words (the host side is FusedGdnStep::words in original_verify_window_gdn_fused.rs)
struct FusedGdnArgs {
uint64_t state; // canonical state of the layer, f32 [128][48][128] (read only: the window never writes it)
uint64_t hist; // canonical conv history of the layer, f32 [10240][3] (read only)
uint64_t qkv; // qkv rows of the layer, f32 [max_t][10240]
uint64_t conv_w; // conv weights, f32 [10240][4]
uint64_t h; // conv + L2 rows of the layer, f32 [max_t][10240] (written for the new tokens)
uint64_t gate; // f32 [max_t][48]
uint64_t beta; // f32 [max_t][48]
uint64_t z; // gate projection rows, f32 [max_t][6144]
uint64_t gamma; // norm weights, f32 [128]
uint64_t y; // output rows, f32 [max_t][6144]
uint64_t ab_x; // activation row of token t_begin, f32 [m][2560]; 0: gate and beta are already in `gate` / `beta`
uint64_t ab_alpha_w; // bf16 [48][2560]
uint64_t ab_beta_w; // bf16 [48][2560]
uint64_t ab_dt; // f32 [48]
uint64_t ab_a; // f32 [48]
uint64_t eps_bits; // the f32 epsilon, bits in the low word
uint64_t t_begin; // first new token
uint64_t t_end; // window rows so far (<= 8)
};
struct FusedShared {
float q[MAX_N][S], k[MAX_N][S], v[MAX_N][S]; // conv + L2 output (new tokens) or h rows (replayed tokens)
float red_kv[2][RG][S]; // double buffered by token parity: a replayed token has one barrier
float red_o[RG][S];
float l2[2][RG][S / 32]; // per conv group, double buffered by iteration
float wsum[S / 32];
float gate[MAX_N], beta[MAX_N];
};
// ---- the conv of verify_gdn_conv_l2_multi_kernel for channel c of token t (the Original's expression) ----
__device__ __forceinline__ float conv_silu(const FusedGdnArgs& a, int c, int t) {
const float* hist = reinterpret_cast<const float*>(a.hist);
const float* qkv = reinterpret_cast<const float*>(a.qkv);
const float* w = reinterpret_cast<const float*>(a.conv_w);
float win[3];
#pragma unroll
for (int j = 0; j < 3; ++j) {
const int src = t + j; // index into [hist(3) | x...]
win[j] = src < 3 ? hist[c * 3 + src] : qkv[(size_t) (src - 3) * C_QKV + c];
}
const float v0 = win[0], v1 = win[1], v2 = win[2], x = qkv[(size_t) t * C_QKV + c];
float sum = v0 * w[c * 4] + v1 * w[c * 4 + 1] + v2 * w[c * 4 + 2] + x * w[c * 4 + 3];
return sum / (1.0f + __expf(-sum));
}
// ---- one conv task: (kind 0 q, 1 k, 2 v) x (new token). The barrier count is the same for every thread of the block. ----
__device__ __forceinline__ void conv_new_tokens(const FusedGdnArgs& a, FusedShared& sh, int head) {
const int col = threadIdx.x, rg = threadIdx.y, lane = col & 31, warp = col >> 5;
const int tb = (int) a.t_begin, tasks = 3 * ((int) a.t_end - tb), qh = head % H_K;
const float eps = __uint_as_float((uint32_t) a.eps_bits);
float* h = reinterpret_cast<float*>(a.h);
for (int it = 0; it * RG < tasks; ++it) {
const int task = it * RG + rg, kind = task % 3, t = tb + task / 3;
const bool valid = task < tasks, l2 = valid && kind < 2;
const int c = (kind == 0 ? qh : (kind == 1 ? H_K + qh : 2 * H_K + head)) * S + col;
float y = valid ? conv_silu(a, c, t) : 0.0f;
float sq = y * y; // the partials of a v task or an idle task are never read
for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, o);
if (lane == 0) sh.l2[it & 1][rg][warp] = sq;
__syncthreads();
if (l2) {
const float ss = sh.l2[it & 1][rg][0] + sh.l2[it & 1][rg][1] + sh.l2[it & 1][rg][2] + sh.l2[it & 1][rg][3];
y *= rsqrtf(ss + eps);
}
if (!valid) continue;
(kind == 0 ? sh.q : (kind == 1 ? sh.k : sh.v))[t][col] = y;
if (kind == 2 || head < H_K) h[(size_t) t * C_QKV + c] = y;
}
__syncthreads();
}
// ---- the tokens before t_begin come from h / gate / beta, as the Original reads them ----
__device__ __forceinline__ void load_replayed_tokens(const FusedGdnArgs& a, FusedShared& sh, int head) {
const int tid = threadIdx.y * S + threadIdx.x, qh = head % H_K;
const float* h = reinterpret_cast<const float*>(a.h);
for (int t = 0; t < (int) a.t_begin; ++t) {
if (tid < S) {
sh.k[t][tid] = h[(size_t) t * C_QKV + QK + qh * S + tid];
sh.v[t][tid] = h[(size_t) t * C_QKV + 2 * QK + head * S + tid];
}
}
}
__device__ __forceinline__ void load_gate_rows(const FusedGdnArgs& a, FusedShared& sh, int head) {
const int tid = threadIdx.y * S + threadIdx.x;
const int last = a.ab_x != 0 ? (int) a.t_begin : (int) a.t_end; // the rows from t_begin on are written by the ab warps
if (tid < last) {
sh.gate[tid] = reinterpret_cast<const float*>(a.gate)[(size_t) tid * H_V + head];
sh.beta[tid] = reinterpret_cast<const float*>(a.beta)[(size_t) tid * H_V + head];
}
}
// ---- the alpha / beta projection of one row (verify_gdn_ab_multi_kernel / chain_gdn_ab_multi_kernel arithmetic) ----
struct AbRow { uint4 w[AB_CHUNKS]; };
__device__ __forceinline__ AbRow ab_load_row(const uint16_t* wa, const uint16_t* wb, int head, bool is_beta, int lane) {
const uint4* w4 = reinterpret_cast<const uint4*>((is_beta ? wb : wa) + (size_t) head * N_EMBD);
AbRow row;
#pragma unroll
for (int q = 0; q < AB_CHUNKS; ++q) row.w[q] = __ldg(w4 + lane + 32 * q);
return row;
}
// per-lane partial dot products: chunk ascending, token independent (the Original's order)
__device__ __forceinline__ void ab_partials(const AbRow& row, const float* x, int lane, int m, float (&acc)[MAX_N]) {
#pragma unroll
for (int t = 0; t < MAX_N; ++t) acc[t] = 0.0f;
#pragma unroll
for (int q = 0; q < AB_CHUNKS; ++q) {
const int j = lane + 32 * q;
#pragma unroll
for (int t = 0; t < MAX_N; ++t) {
if (t >= m) break;
const float* xt = x + (size_t) t * N_EMBD;
const float4 xa = *reinterpret_cast<const float4*>(xt + j * 8);
const float4 xb = *reinterpret_cast<const float4*>(xt + j * 8 + 4);
float v = acc[t];
v = fmaf(__uint_as_float(row.w[q].x << 16), xa.x, v); v = fmaf(__uint_as_float(row.w[q].x & 0xffff0000u), xa.y, v);
v = fmaf(__uint_as_float(row.w[q].y << 16), xa.z, v); v = fmaf(__uint_as_float(row.w[q].y & 0xffff0000u), xa.w, v);
v = fmaf(__uint_as_float(row.w[q].z << 16), xb.x, v); v = fmaf(__uint_as_float(row.w[q].z & 0xffff0000u), xb.y, v);
v = fmaf(__uint_as_float(row.w[q].w << 16), xb.z, v); v = fmaf(__uint_as_float(row.w[q].w & 0xffff0000u), xb.w, v);
acc[t] = v;
}
}
}
// the gate (alpha row) or beta (beta row) of a reduced dot product
__device__ __forceinline__ float ab_value(float a, bool is_beta, float dt, float ssm_a) {
if (is_beta) return 1.0f / (1.0f + __expf(-a));
const float v = a + dt;
const float sp = v > 20.0f ? v : log1pf(__expf(v));
return sp * ssm_a;
}
__device__ __forceinline__ void ab_new_tokens(const FusedGdnArgs& a, FusedShared& sh, int head, const AbRow& row) {
const int lane = threadIdx.x & 31, tb = (int) a.t_begin, m = (int) a.t_end - tb;
const bool is_beta = (threadIdx.x >> 5) == 1;
float acc[MAX_N];
ab_partials(row, reinterpret_cast<const float*>(a.ab_x), lane, m, acc);
#pragma unroll
for (int t = 0; t < MAX_N; ++t) {
if (t >= m) break;
float sum = acc[t];
for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
if (lane != 0) continue;
const float v = ab_value(sum, is_beta, reinterpret_cast<const float*>(a.ab_dt)[head], reinterpret_cast<const float*>(a.ab_a)[head]);
(is_beta ? sh.beta : sh.gate)[tb + t] = v;
(is_beta ? reinterpret_cast<float*>(a.beta) : reinterpret_cast<float*>(a.gate))[(size_t) (tb + t) * H_V + head] = v;
}
}
// ---- the Original's step loop (verify_gdn_step_norm_multi_kernel) over shared memory ----
__device__ __forceinline__ void output_token(const FusedGdnArgs& a, FusedShared& sh, int head, int t, float o) {
const int col = threadIdx.x, rg = threadIdx.y, tid = rg * S + col;
const float eps = __uint_as_float((uint32_t) a.eps_bits);
sh.red_o[rg][col] = o;
__syncthreads();
float oc = 0.0f, sq_part = 0.0f;
if (rg == 0) {
oc = (sh.red_o[0][col] + sh.red_o[1][col] + sh.red_o[2][col] + sh.red_o[3][col]) * rsqrtf((float) S);
sq_part = oc * oc;
for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2);
if ((tid & 31) == 0) sh.wsum[tid >> 5] = sq_part;
}
__syncthreads();
if (rg != 0) return;
const float ss = sh.wsum[0] + sh.wsum[1] + sh.wsum[2] + sh.wsum[3];
const float scale = rsqrtf(ss / (float) S + eps);
const float zz = reinterpret_cast<const float*>(a.z)[(size_t) t * VALUE_DIM + head * S + col];
reinterpret_cast<float*>(a.y)[(size_t) t * VALUE_DIM + head * S + col] =
oc * scale * reinterpret_cast<const float*>(a.gamma)[col] * (1.0f / (1.0f + __expf(-zz)));
}
__device__ __forceinline__ void recurrence(const FusedGdnArgs& a, FusedShared& sh, int head) {
const int col = threadIdx.x, rg = threadIdx.y, n = (int) a.t_end, tb = (int) a.t_begin;
const float* state = reinterpret_cast<const float*>(a.state) + ((size_t) (rg * RPG) * H_V + head) * S + col;
float s[RPG];
#pragma unroll
for (int r = 0; r < RPG; ++r) s[r] = state[(size_t) r * H_V * S];
for (int t = 0; t < n; ++t) {
const float g = __expf(sh.gate[t]);
float kv = 0.0f;
#pragma unroll
for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sh.k[t][rg * RPG + r], kv);
sh.red_kv[t & 1][rg][col] = kv;
__syncthreads();
const float kv_col = sh.red_kv[t & 1][0][col] + sh.red_kv[t & 1][1][col] + sh.red_kv[t & 1][2][col] + sh.red_kv[t & 1][3][col];
const float delta = (sh.v[t][col] - g * kv_col) * sh.beta[t];
if (t < tb) { // a replayed token: its state update is needed, its output is not
#pragma unroll
for (int r = 0; r < RPG; ++r) s[r] = fmaf(g, s[r], sh.k[t][rg * RPG + r] * delta);
continue;
}
float o = 0.0f;
#pragma unroll
for (int r = 0; r < RPG; ++r) {
s[r] = fmaf(g, s[r], sh.k[t][rg * RPG + r] * delta);
o = fmaf(s[r], sh.q[t][rg * RPG + r], o);
}
output_token(a, sh, head, t, o);
}
}
// grid (48), block (128, 4): one block per value head
extern "C" __global__ void __launch_bounds__(S * RG) leleka_verify_gdn_fused_step(FusedGdnArgs a) {
__shared__ FusedShared sh;
const int head = blockIdx.x, warp = (threadIdx.y * S + threadIdx.x) >> 5;
AbRow row;
if (a.ab_x != 0 && warp < 2) { // the weight loads are in flight while the whole block convolves
row = ab_load_row(reinterpret_cast<const uint16_t*>(a.ab_alpha_w), reinterpret_cast<const uint16_t*>(a.ab_beta_w), head, warp == 1,
threadIdx.x & 31);
}
load_replayed_tokens(a, sh, head);
load_gate_rows(a, sh, head);
conv_new_tokens(a, sh, head);
if (a.ab_x != 0 && warp < 2) ab_new_tokens(a, sh, head, row);
__syncthreads();
recurrence(a, sh, head);
}
// ------------------------------------------------------------------------------------------------------------------
// LELEKA_SM120_GDN_AB_UNROLL: upstream gdn_ab_body (STRATA_SMALL_UNR bit 1) on the Original's arguments.
// ------------------------------------------------------------------------------------------------------------------
template <int MAX_T, bool EXACT_T>
__device__ __forceinline__ void ab_unrolled_body(const float* __restrict__ x, const uint16_t* __restrict__ wa, const uint16_t* __restrict__ wb,
const float* __restrict__ dt, const float* __restrict__ ssm_a, float* __restrict__ gate,
float* __restrict__ beta, int h_v, int T) {
const int row = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5), lane = threadIdx.x & 31;
if (row >= 2 * h_v) return;
const bool is_beta = row >= h_v;
const int r = is_beta ? row - h_v : row;
const uint4* w4 = reinterpret_cast<const uint4*>((is_beta ? wb : wa) + (size_t) r * N_EMBD);
float acc[MAX_T];
#pragma unroll
for (int t = 0; t < MAX_T; ++t) acc[t] = 0.0f;
#pragma unroll
for (int jj = 0; jj < AB_CHUNKS; ++jj) { // the ten passes, j = lane + 32 jj, all < 320
const int j = lane + 32 * jj;
const uint4 wv = __ldg(w4 + j);
#pragma unroll
for (int t = 0; t < MAX_T; ++t) {
if (!EXACT_T && t >= T) break;
const float* xt = x + (size_t) t * N_EMBD;
const float4 xa = __ldg(reinterpret_cast<const float4*>(xt + j * 8));
const float4 xb = __ldg(reinterpret_cast<const float4*>(xt + j * 8 + 4));
float v = acc[t];
v = fmaf(__uint_as_float(wv.x << 16), xa.x, v); v = fmaf(__uint_as_float(wv.x & 0xffff0000u), xa.y, v);
v = fmaf(__uint_as_float(wv.y << 16), xa.z, v); v = fmaf(__uint_as_float(wv.y & 0xffff0000u), xa.w, v);
v = fmaf(__uint_as_float(wv.z << 16), xb.x, v); v = fmaf(__uint_as_float(wv.z & 0xffff0000u), xb.y, v);
v = fmaf(__uint_as_float(wv.w << 16), xb.z, v); v = fmaf(__uint_as_float(wv.w & 0xffff0000u), xb.w, v);
acc[t] = v;
}
}
#pragma unroll
for (int t = 0; t < MAX_T; ++t) {
if (!EXACT_T && t >= T) break;
float sum = acc[t];
#pragma unroll
for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
if (lane != 0) continue;
const float v = ab_value(sum, is_beta, dt[r], ssm_a[r]);
(is_beta ? beta : gate)[(size_t) t * h_v + r] = v;
}
}
// the Original's argument list (x, wa, wb, dt, ssm_a, gate, beta, n, h_v, T); 2 h_v rows, one warp each
#define LELEKA_AB_UNROLLED(NAME, MAX_T, EXACT_T) \
extern "C" __global__ void __launch_bounds__(64) NAME(const float* __restrict__ x, const uint16_t* __restrict__ wa, \
const uint16_t* __restrict__ wb, const float* __restrict__ dt, \
const float* __restrict__ ssm_a, float* __restrict__ gate, \
float* __restrict__ beta, int n, int h_v, int T) { \
(void) n; /* n == 2560: the host refuses any other width */ \
ab_unrolled_body<MAX_T, EXACT_T>(x, wa, wb, dt, ssm_a, gate, beta, h_v, T); \
}
LELEKA_AB_UNROLLED(leleka_gdn_ab_unrolled_t1, 1, true)
LELEKA_AB_UNROLLED(leleka_gdn_ab_unrolled_t2, 2, true)
LELEKA_AB_UNROLLED(leleka_gdn_ab_unrolled_t3, 3, true)
LELEKA_AB_UNROLLED(leleka_gdn_ab_unrolled_t4, 4, true)
LELEKA_AB_UNROLLED(leleka_gdn_ab_unrolled_t5, 5, true)
LELEKA_AB_UNROLLED(leleka_gdn_ab_unrolled_t6, 6, true)
LELEKA_AB_UNROLLED(leleka_gdn_ab_unrolled_t8, 8, false) // T = 7 and 8: upstream's kVerifyNarrowT loop, the token count a run time argument
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,182 @@
# Verify window, GDN layers: one launch instead of three, and the unrolled a/b projection
Branch `claude/verify-gdn-fused-kernels` (base `91a130da6`, branch `claude/speed-vs-strata-08143a`). Ledger rows
`docs/experiments/step-ledger.md`: K7 (GDN role in total, +0.155 ms per round against vanilla), K7a (GDN step/norm in
the verify graph, +0.029 ms, 36 against 30.9 launches), U3 (upstream `STRATA_SMALL_UNR` bit 1, the unrolled GDN a/b
projection). Nothing here was measured on a GPU: this note states what the code does, how it was checked without one,
and what the orchestrator should look at.
## What a GDN layer records today
`record_window` calls `gdn_conv`, `gdn_alpha_beta`, `gdn_recurrence` for each of the 36 GDN layers
(`original_verify_window_record.rs`, `pre_gdn_front` / `pre_gdn_back`). Each one is one kernel of `original_verify.ptx`:
| call | kernel | grid x block |
| --- | --- | --- |
| `gdn_conv` | `verify_gdn_conv_l2_multi_kernel` | 80 x T, 128 |
| `gdn_alpha_beta` | `verify_gdn_ab_multi_kernel`, or `chain_gdn_ab_multi_kernel` with `LELEKA_CHAIN_AB` (`LELEKA_CHAIN=all`, the 5090 profile) | 12 x 256, or 96 x 32 |
| `gdn_recurrence` | `verify_gdn_step_norm_multi_kernel` | 48, 128 x 4 |
That is 108 launches per verify graph. Vanilla also runs conv, ab and step as three kernels, so the gap K7 is launch count
and the conv (grid 80 x T of 128 threads for a 10240 x 4 tap convolution, one launch of its own).
## `LELEKA_SM120_FUSED_GDN` (default off)
One new kernel, `leleka_verify_gdn_fused_step` (`crates/cuda-driver/src/sm120_gdn_fused.cu`), 48 blocks of 128 x 4,
one block per value head: the Original's step loop with its loads redirected to shared memory, preceded by:
* **conv prologue.** The block convolves the q chunk (`head % 16`), the k chunk (`16 + head % 16`) and its own v chunk
(`32 + head`), 128 channels each, for the new tokens `[t_begin, t_end)`. The 3 x m tasks are dealt to the four 128-thread
groups (`threadIdx.y`); every group runs the same number of rounds and one barrier per round, an idle task computes zeros.
q, k and v go to shared memory (`FusedShared`, 18.6 KB). The blocks of heads < 16 write q and k to `h`, every block writes
its v chunk to `h`: the commit graph (`draft_commit.cu`, `verify_gdn_step_norm_multi_kernel` with `n_keep`) and a later
group of a split window read `h`, so each of the 80 chunks of a row still has exactly one writer. The q/k conv of a head
pair is computed by the three heads that share it (the redundancy of this design; only the heads < 16 store it).
* **gates.** With `ab_x != 0` warp 0 and warp 1 of the block compute alpha row `head` and beta row `head` for the new
tokens (the ten weight chunks are loaded first, so they are in flight during the conv; the dot products then run per
lane in the Original's order) and write `gate` / `beta` to global (the commit reads them) and to shared memory. With
`ab_x == 0` they are read (see SIDE_MIXER below).
* **replayed tokens.** Tokens before `t_begin` (the earlier group of a split window) are read from `h` / `gate` / `beta`
into shared memory, as the Original reads them. Their state update is done; their o dot product and output path never
feed the state and are not computed (as `draft_commit.cu`).
* **step loop.** `s = fma(g, s, k * delta)` etc. over shared `q`, `k`, `v`, `gate`, `beta`. Barriers per token: one for
`kv` (double buffered by token parity, so a replayed token has only this one), and for an output token one for `o` and
one for the squared-sum partials. The Original had six per token.
The state is not written (the window passes `n_keep = 0`), as before.
### Dispatch (`original_verify_window_ops/gdn_stages.rs`, `GdnFusedPolicy::stages`)
| switches | `gdn_conv` | `gdn_alpha_beta` | `gdn_recurrence` | GDN launches per layer |
| --- | --- | --- | --- | --- |
| off | conv | ab | step | 3 |
| `FUSED_GDN` | nothing | nothing | fused (gates in kernel) | 1 |
| `SIDE_MIXER` | conv | nothing (side stream 0) | step | 3 (one on the side stream) |
| `FUSED_GDN` + `SIDE_MIXER` | nothing | nothing (side stream 0) | fused (gates read, after the side joins) | 2 (one on the side stream) |
So 108 launches per verify graph become 36 (72 on the main stream with SIDE_MIXER). Only the conv is fused with
SIDE_MIXER, as designed: the gates stay on side stream 0 and the fused launch comes after both joins. The conv no longer
overlaps the side-stream gates in that combination; that is a cost to read off the CUPTI window, not a measured one.
Split windows (`groups == 2`) fuse with the gates in the kernel.
## `LELEKA_SM120_GDN_AB_UNROLL` (default off, independent)
Upstream commit `08b20b104` (`gdn_ab_body`, `STRATA_SMALL_UNR` bit 1): the same a/b projection with the loop over the ten
32-lane passes (`j = lane + 32 jj`, all below 320) and over the tokens at constant trip counts, so the loads of several
passes can be issued before the first FMA chain. Its own entries in the same asset: `leleka_gdn_ab_unrolled_t1..t6`
(exact token count) and `_t8` (T = 7 and 8, run time count, upstream's `kVerifyNarrowT` split). It replaces the a/b kernel
wherever that runs as a kernel of its own (no `FUSED_GDN`, and the side-stream gates).
Geometry: one warp per row, 96 blocks of 32 threads, the shape of `chain_gdn_ab_multi_kernel` that `LELEKA_CHAIN=all`
records, so the unrolled loop is the only difference to the shipped kernel. Upstream's own shape (48 blocks of 64
threads, two rows a block) runs the same entries (`row = blockIdx.x * (blockDim.x / 32) + warp`); the probe covers both.
Expectation to keep honest: the shipped chain kernel already hoists the ten weight loads (K7b: 8.5 us, ahead of
vanilla's 10.5 us), so the unroll may add little over it; with `FUSED_GDN` the gates are inside the fused launch and this
switch only affects the side-stream branch.
## Bitwise argument
The target is "identical to the three kernels", after the driver's JIT, which loads `cuModuleLoadData` with default
options (`original_verify_ffi.rs`).
1. **Same expressions, same PTX shape, not intrinsics.** The brief suggested `__fmul_rn` / `__fsub_rn` to forbid
contraction. That is wrong for these kernels. ptxas contracts a plain `mul.f32` that feeds an `add.f32` / `sub.f32`
into one FFMA (checked on `rnr5090` with ptxas 13.2.86 `-arch=sm_120`: a two-instruction kernel with `mul.f32` +
`sub.f32` assembles to a single FFMA, the `.rn` forms to FMUL + FADD; `--fmad=false` makes the plain form behave like
`.rn`). The sealed `original_verify.ptx` has a plain `mul.f32`, `sub.f32`, `mul.f32` for `delta = beta * (v - g * kv)`,
so the Original *executes* `beta * fma(-g, kv, v)`. An intrinsic version would not. The kernel therefore uses the
same plain C++ expressions as `original_verify.cu` (and explicit `fmaf` where the Original has `fmaf`), and a unit test
compares the PTX.
2. **PTX comparison (CPU, unit tests `original_verify_window_gdn_fused::tests`):** the numeric instruction sequence of the
Original's conv kernel (26 instructions: `mul`, 3 `fma`, silu by `div.rn`, `y * y`, five butterfly adds, barrier, the
four-partial sum, `rsqrt.approx`, `mul`) is a contiguous run of the fused kernel; the delta (`add add add mul sub mul`)
and the whole output tail (`rsqrt.approx` of 128 at run time, `ss / 128 + eps` as one `fma.rn`, `rcp.rn` for the
sigmoid) are runs of both; the set of numeric opcodes of the fused kernel equals the union of the three Originals', with
no `.rn`-suffixed `add` / `mul` / `sub`, no `.ftz`, no approximate division; each unrolled entry has the Original a/b
kernel's opcode set. The ten `log1pf` polynomial constants are the same in 13.0.88 (`original_verify.ptx`) and 13.2.86
(`chain_window.ptx`, this asset).
3. **Arithmetic order.** Conv: `((v1*w1 -> fma v0 -> fma v2 -> fma x)`, silu `div.rn`, L2 partials by xor butterfly over
a warp then `((p0+p1)+p2)+p3`. Gates: per-lane chunk-ascending fma chains, xor butterfly, the Original's gate/beta
formulas. Step: `kv` fma chain from 0, `((r0+r1)+r2)+r3`, `s = fma(g, s, k*delta)`, `o = fma(s, q, o)` in `r` order,
`oc = sum * rsqrt(128)`, `scale = rsqrt(ss/128 + eps)`, `y = oc * scale * gamma * rcp(1 + exp(-z))`.
4. **Model-free probe, not run by this task (no GPU):** `tools/gdn-fused/gdn_fused_probe.cpp` runs the fused launch next
to the three Original kernels for T = 1..8, every split of the window into two groups, gates in the kernel and joined,
three seeds, and compares every byte of `h`, `gate`, `beta`, `y`, state and history; it also compares every unrolled entry
(both geometries) with the Original and the chain a/b kernel. Build: `tools/gdn-fused/build.sh` (nvcc 13.2.2), run
`gdn_fused_probe OUTDIR/ptx`. It compiles (`nvcc -c`, checked on the server) and has not been executed.
## Asset and sealing
* Source `crates/cuda-driver/src/sm120_gdn_fused.cu`, PTX `sm120_gdn_fused.ptx` beside it, sm_120 only
(`ptx-sm86/MANIFEST.json`: "not built for sm_86 by design"; the switches take effect on a 12.x card only).
* Built on `rnr5090` (compile only, no GPU) with `~/cuda-toolkits/13.2.2/bin/nvcc --ptx -O3 -arch=sm_120 -std=c++17
--fmad=true --ftz=false` (13.2.86, the recipe of `original_verify.cu` / `draft_commit.cu`). sha256 `.cu`
`f46a3c59dd2e203d1ba1b997f5e2f5aeaa40185d72468bce2ceb12d1ecbdb95f`, `.ptx`
`9da33e8217c1e4daa2d26f9739874978e9c206eb5f30f9417f5df8b526e37f17`.
* Pinned in `GDN_FUSED.sha` (`original_verify/original_verify_window_gdn_fused.rs`); plan entry in
`scripts/gpu-bringup/extra-seal-plan.json` (group `sm120-decode`). The pin was filled by hand from the digest (the
`seal_pins.py` flow needs a compile manifest); `assert_sealed_and_fail_closed` checks pin, structure and the refusals.
* Fails closed: a requested switch whose asset is not sealed refuses the recording with `Original verifier asset
unsealed: sm120_gdn_fused.ptx (...)` (`gdn_fused::prepare`), instead of silently running the default path under the name
of the switch (the `ATTN_DAILY` precedent falls back silently, which would mislabel a paired A/B arm).
* `ptxas -v` (sm_120): fused step 64 registers, 18640 bytes shared, 20 bytes of spill; unrolled `t1..t6, t8`: 39, 48, 48,
52, 50, 56, 44 registers, no spill.
* Server path created (orchestrator may move it to garbage):
`/data/leleka-e2e/spd-gap/ptx-build/verify-gdn-fused-kernels/` (the `.cu`, `.ptx`, test PTX of the contraction check,
cubins, `ptxas-v.txt`, probe object).
## Where the code is
| file | change |
| --- | --- |
| `crates/cuda-driver/src/sm120_gdn_fused.cu`, `.ptx` | new asset |
| `crates/cuda-driver/src/original_verify/original_verify_window_gdn_fused.rs` (+ `/tests.rs`) | switches resolution, asset, launch DTOs, stage plan (`GdnFusedPolicy::stages`), 18 tests |
| `crates/cuda-driver/src/original_verify/original_verify_gdn_journal/verify_gdn_fused_step.rs` | `capture_fused_recurrence`, `capture_ab_unrolled` (operand spans as `capture_layer_stage`) |
| `crates/cuda-driver/src/original_verify_window_ops/gdn_stages.rs` | the three `WindowOps` GDN calls (moved out of `window_ops_kernels_and_pcie_plan.rs`) |
| `original_verify_window_sm120.rs` | `fused_gdn`, `gdn_ab_unroll` in `Sm120Switches`, `DEFAULT_ON_*` (separate block) |
| `original_verify.rs`, `original_verify_gdn_journal.rs`, `original_verify_window_ops.rs`, `original_verifier.rs` | one `mod` line each, the `gdn` field of the ops struct and its resolution |
| `verify_gdn_journal_stage_and_commit.rs` | `StageOperands` / `stage_operands` `pub(super)` |
| `ptx-sm86/MANIFEST.json`, `scripts/gpu-bringup/extra-seal-plan.json` | not-built-for-sm_86 note, plan entry |
| `tools/gdn-fused/` | probe and build script |
## Tests and gates (no GPU)
* `test -p leleka-cuda-driver --features cuda-driver --lib original_verify`: 179 passed (161 on the base commit + 18 new),
11 ignored (GPU). Whole crate (`--features cuda-driver`): lib 397 passed, 78 ignored, the integration tests as before.
* New tests: default off; each variable turns on its own switch and nothing else, 12.0 and 12.1 take it, below 12 never;
asset sealed and exports every entry; launches per layer with the switch (3 -> 1; with the side branch 3 -> 2; 108 ->
36 per graph); the unrolled gates replace only the a/b kernel; the argument words follow `FusedGdnArgs` of the kernel
source (parsed from the `.cu`); the fused launch writes `h`, `gate`, `beta`, `y` and carries no activation row when
joined; row range refusals; unrolled entry by token count; the unrolled launch takes the Original's arguments; the four
PTX comparisons above.
* `python3 scripts/check-architecture.py`: 0 errors (the new files use `dir/name.rs` paths, so the `path-include`
ratchet does not rise). `scripts/check-limits.py --base claude/speed-vs-strata-08143a`: 0 errors.
## For the orchestrator
Identity (teacher-forced replay, top-16 rows + draft trace): arm A default, arm B `LELEKA_SM120_FUSED_GDN=1`, arm C
`LELEKA_SM120_GDN_AB_UNROLL=1`, arm D `FUSED_GDN=1` + `LELEKA_SM120_SIDE_MIXER=1` (the joined path), each with the
shipped `LELEKA_CHAIN=all`. Only the env switch is needed. Look for a split window in the replay (`groups == 2`) and for
T = 1..8; the probe covers them without a model.
CUPTI window, kernel names:
* before: `verify_gdn_conv_l2_multi_kernel`, `chain_gdn_ab_multi_kernel` (or `verify_gdn_ab_multi_kernel`),
`verify_gdn_step_norm_multi_kernel` (36 each per verify graph; the last one also appears in the unfused commit graph);
* after `FUSED_GDN`: `leleka_verify_gdn_fused_step`, 36 per verify graph, the three above absent from the window graph;
launches per verify graph (V8) 2061 -> 1989 by count (-72);
* after `GDN_AB_UNROLL`: `leleka_gdn_ab_unrolled_t<T>` in place of the a/b kernel.
The section delta is K7 minus the commit part: sum of the three kernels per graph (conv, ab, step) against the fused
kernel. Risks to read off the window: the fused kernel runs 48 blocks only, so its prologue is serial per block (conv of
three chunks, then the gates, then the loop), the q/k conv is done three times, and with SIDE_MIXER the conv no longer
overlaps the gates. No gain is claimed.
## Identity risks left
* ptxas contraction decisions follow the PTX shape; the shapes were compared, but SASS was not (no `nvdisasm` in the server
toolkit). The probe is the proof.
* The barrier hazards of the double buffered `red_kv`, `l2` and the single `red_o` / `wsum` were argued on paper (each
buffer is re-written only after a barrier all readers have passed) and cannot be seen by a unit test.
* `log1pf` and the other libdevice expansions come from nvcc 13.2.86 here and 13.0.88 in `original_verify.ptx`; the
constants of `log1pf` are equal, the rest of the sequences are covered by the opcode-set test.
+32
View File
@@ -927,6 +927,38 @@
},
"group": "draft-round",
"optional": false
},
{
"cu": "crates/cuda-driver/src/sm120_gdn_fused.cu",
"ptx": "crates/cuda-driver/src/sm120_gdn_fused.ptx",
"flags": [
"-ptx",
"-O3",
"-arch=sm_120",
"-std=c++17",
"--fmad=true",
"--ftz=false"
],
"include_profile": "standard",
"policy": "precise (--fmad=true --ftz=false: the recipe of original_verify.cu; verify-gdn-fused-kernels: the GDN layer's conv, a/b gates and step in one launch, and upstream's unrolled a/b projection; plain C++ expressions on purpose, ptxas contracts plain mul + add/sub, so the PTX shapes are the Original's)",
"entries": [
"leleka_verify_gdn_fused_step",
"leleka_gdn_ab_unrolled_t1",
"leleka_gdn_ab_unrolled_t2",
"leleka_gdn_ab_unrolled_t3",
"leleka_gdn_ab_unrolled_t4",
"leleka_gdn_ab_unrolled_t5",
"leleka_gdn_ab_unrolled_t6",
"leleka_gdn_ab_unrolled_t8"
],
"encoding": "concat_include_str",
"rust_fields_to_fill": {
"original_verify_window_gdn_fused.rs": [
"GDN_FUSED.sha"
]
},
"group": "sm120-decode",
"optional": false
}
]
}
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# Build the GDN fused-kernel probe (never run on the server's GPU queue by its author) and collect the PTX it compares.
# tools/gdn-fused/build.sh [OUTDIR] default OUTDIR=$HOME/gdn-fused-bin ; then: OUTDIR/gdn_fused_probe OUTDIR/ptx
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
root="$(cd "$here/../.." && pwd)"
out="${1:-$HOME/gdn-fused-bin}"
nvcc="${NVCC:-$HOME/cuda-toolkits/13.2.2/bin/nvcc}"
mkdir -p "$out/ptx"
"$nvcc" -O2 -std=c++17 "$here/gdn_fused_probe.cpp" -lcuda -o "$out/gdn_fused_probe"
for f in original_verify sm120_gdn_fused chain_window; do
cp "$root/crates/cuda-driver/src/$f.ptx" "$out/ptx/$f.ptx"
done
sha256sum "$out"/gdn_fused_probe "$out"/ptx/* > "$out/SHA256SUMS"
ls -la "$out" "$out/ptx"
+208
View File
@@ -0,0 +1,208 @@
// verify-gdn-fused-kernels: model-free probe of crates/cuda-driver/src/sm120_gdn_fused.ptx. NOT RUN by the author (no GPU access in that task): the orchestrator runs it.
//
// The fused GDN layer launch (`leleka_verify_gdn_fused_step`) is run next to the three kernels it replaces (`verify_gdn_conv_l2_multi_kernel`, `verify_gdn_ab_multi_kernel`,
// `verify_gdn_step_norm_multi_kernel` of original_verify.ptx) on real-size random inputs, for every window width T = 1..8, every split of the window into two row groups (the second group
// replays the first group's tokens from h / gate / beta), with the gates computed inside the kernel and with the gates joined (SIDE_MIXER: computed by a separate launch first). EVERY
// byte of h, gate, beta and y is compared, and the canonical state and history must be untouched. The unrolled a/b kernels (`leleka_gdn_ab_unrolled_t*`) are compared with the
// Original's a/b kernel (and chain_window.ptx's `chain_gdn_ab_multi_kernel` when present). Prints "RESULT name key=value" lines; exits 1 if any comparison differs.
// gdn_fused_probe PTXDIR PTXDIR holds original_verify.ptx, sm120_gdn_fused.ptx (and optionally chain_window.ptx): copies of crates/cuda-driver/src/
#include <cuda.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#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 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 bool load_module(const std::string& p, CUmodule* m) {
std::string s = read_file(p);
if (s.empty()) return false;
s.push_back('\0');
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 true;
}
static CUfunction get_fn(CUmodule m, const char* name) {
CUfunction f; CUresult r = cuModuleGetFunction(&f, m, name);
if (r != CUDA_SUCCESS) { fprintf(stderr, "no entry %s\n", name); exit(2); }
return f;
}
struct Dev {
CUdeviceptr p = 0; size_t n = 0;
void alloc(size_t bytes) { n = bytes; CU(cuMemAlloc(&p, bytes ? bytes : 1)); CU(cuMemsetD8(p, 0, bytes ? bytes : 1)); }
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 bool same(const char* what, const std::vector<uint8_t>& a, const std::vector<uint8_t>& b) {
if (a.size() != b.size()) { printf("MISMATCH %s: size %zu vs %zu\n", what, a.size(), b.size()); g_fail++; return false; }
size_t bad = 0, first = (size_t)-1;
for (size_t i = 0; i < a.size(); ++i) if (a[i] != b[i]) { if (first == (size_t)-1) first = i; ++bad; }
if (bad) { printf("MISMATCH %s: %zu of %zu bytes differ (first at %zu)\n", what, bad, a.size(), first); g_fail++; return false; }
return true;
}
static CUstream g_s;
static void launch(CUfunction f, unsigned gx, unsigned gy, unsigned bx, unsigned by, void** args) {
CU(cuLaunchKernel(f, gx, gy, 1, bx, by, 1, 0, g_s, args, nullptr));
}
constexpr int C = 10240, H = 48, T = 8, N = 2560, ZS = 6144;
constexpr size_t STATE_WORDS = (size_t)128 * 48 * 128;
// the buffers of one GDN layer; two sets (original / fused) with the same contents
struct Layer {
Dev state, hist, qkv, w, h, gate, beta, z, gamma, y, x, wa, wb, dt, a;
};
static void alloc_layer(Layer& l) {
l.state.alloc(STATE_WORDS * 4); l.hist.alloc((size_t)C * 3 * 4); l.qkv.alloc((size_t)T * C * 4); l.w.alloc((size_t)C * 4 * 4);
l.h.alloc((size_t)T * C * 4); l.gate.alloc((size_t)T * H * 4); l.beta.alloc((size_t)T * H * 4); l.z.alloc((size_t)T * ZS * 4);
l.gamma.alloc(128 * 4); l.y.alloc((size_t)T * ZS * 4); l.x.alloc((size_t)T * N * 4); l.wa.alloc((size_t)H * N * 2);
l.wb.alloc((size_t)H * N * 2); l.dt.alloc(H * 4); l.a.alloc(H * 4);
}
struct Inputs { std::vector<float> state, hist, qkv, w, z, gamma, x, dt, a; std::vector<uint16_t> wa, wb; };
static Inputs make_inputs(int seed) {
Inputs in;
auto fill = [&](std::vector<float>& v, size_t n, float scale, float shift) { v.resize(n); for (auto& e : v) e = rndf() * scale + shift; };
fill(in.state, STATE_WORDS, seed ? 0.5f : 2.0f, 0.0f); fill(in.hist, (size_t)C * 3, 1.0f, 0.0f); fill(in.qkv, (size_t)T * C, 1.0f, 0.0f);
fill(in.w, (size_t)C * 4, 0.6f, 0.0f); fill(in.z, (size_t)T * ZS, 2.0f, 0.0f); fill(in.gamma, 128, 0.5f, 1.0f);
fill(in.x, (size_t)T * N, 1.5f, 0.0f); fill(in.dt, H, 1.0f, 0.0f); fill(in.a, H, 0.5f, -1.0f);
auto bf16 = [&](std::vector<uint16_t>& v) { v.resize((size_t)H * N); for (auto& e : v) { float f = rndf() * 0.1f; uint32_t u; memcpy(&u, &f, 4); e = (uint16_t)(u >> 16); } };
bf16(in.wa); bf16(in.wb);
return in;
}
static void upload(Layer& l, const Inputs& in) {
l.state.put(in.state.data(), in.state.size() * 4); l.hist.put(in.hist.data(), in.hist.size() * 4); l.qkv.put(in.qkv.data(), in.qkv.size() * 4);
l.w.put(in.w.data(), in.w.size() * 4); l.z.put(in.z.data(), in.z.size() * 4); l.gamma.put(in.gamma.data(), 512); l.x.put(in.x.data(), in.x.size() * 4);
l.wa.put(in.wa.data(), in.wa.size() * 2); l.wb.put(in.wb.data(), in.wb.size() * 2); l.dt.put(in.dt.data(), H * 4); l.a.put(in.a.data(), H * 4);
for (Dev* d : {&l.h, &l.gate, &l.beta, &l.y}) CU(cuMemsetD8(d->p, 0, d->n));
}
struct Fns { CUfunction conv, ab, step, chain_ab, fused, unrolled[7]; };
static const char* kUnrolled[7] = {"leleka_gdn_ab_unrolled_t1", "leleka_gdn_ab_unrolled_t2", "leleka_gdn_ab_unrolled_t3", "leleka_gdn_ab_unrolled_t4",
"leleka_gdn_ab_unrolled_t5", "leleka_gdn_ab_unrolled_t6", "leleka_gdn_ab_unrolled_t8"};
// the Original's three kernels for rows [begin, end) (capture_layer_stage)
static void ab_args_launch(CUfunction f, Layer& l, int begin, int end, unsigned gx, unsigned bx) {
CUdeviceptr x = l.x.p + (size_t)begin * N * 4, wa = l.wa.p, wb = l.wb.p, dt = l.dt.p, a = l.a.p, g = l.gate.p + (size_t)begin * H * 4, b = l.beta.p + (size_t)begin * H * 4;
int n = N, hv = H, t = end - begin;
void* args[] = {&x, &wa, &wb, &dt, &a, &g, &b, &n, &hv, &t};
launch(f, gx, 1, bx, 1, args);
}
static void original_rows(const Fns& f, Layer& l, int begin, int end, bool with_ab) {
CUdeviceptr hist = l.hist.p, qkv = l.qkv.p, w = l.w.p, h = l.h.p;
int c = C, qkh = 32, tb = begin; float eps = 1e-6f;
void* a1[] = {&hist, &qkv, &w, &h, &c, &qkh, &eps, &tb};
launch(f.conv, 80, end - begin, 128, 1, a1);
if (with_ab) ab_args_launch(f.ab, l, begin, end, 12, 256);
CUdeviceptr state = l.state.p, g = l.gate.p, b = l.beta.p, z = l.z.p, gm = l.gamma.p, y = l.y.p, nk = 0;
int hk = 16, hv = H, tt = end;
void* a2[] = {&state, &h, &c, &g, &b, &z, &gm, &eps, &y, &hk, &hv, &tt, &nk, &tb};
launch(f.step, 48, 1, 128, 4, a2);
}
// the fused launch for rows [begin, end); in_kernel = false: the gates were computed by a separate launch before (SIDE_MIXER)
static void fused_rows(const Fns& f, Layer& l, int begin, int end, bool in_kernel) {
float eps = 1e-6f; uint32_t eb; memcpy(&eb, &eps, 4);
uint64_t w[18] = {l.state.p, l.hist.p, l.qkv.p, l.w.p, l.h.p, l.gate.p, l.beta.p, l.z.p, l.gamma.p, l.y.p,
in_kernel ? l.x.p + (size_t)begin * N * 4 : 0, l.wa.p, l.wb.p, l.dt.p, l.a.p, (uint64_t)eb, (uint64_t)begin, (uint64_t)end};
void* af[] = {w};
launch(f.fused, 48, 1, 128, 4, af);
}
static void compare_layers(const char* what, Layer& a, Layer& b) {
CU(cuStreamSynchronize(g_s));
char name[160];
for (auto pr : {std::make_pair("h", std::make_pair(&a.h, &b.h)), std::make_pair("gate", std::make_pair(&a.gate, &b.gate)), std::make_pair("beta", std::make_pair(&a.beta, &b.beta)),
std::make_pair("y", std::make_pair(&a.y, &b.y)), std::make_pair("state", std::make_pair(&a.state, &b.state)), std::make_pair("hist", std::make_pair(&a.hist, &b.hist))}) {
snprintf(name, sizeof name, "%s %s", what, pr.first);
same(name, pr.second.first->get(), pr.second.second->get());
}
}
static void test_fused(const Fns& f) {
Layer a, b; alloc_layer(a); alloc_layer(b);
int cases = 0;
for (int seed = 0; seed < 3; ++seed) {
Inputs in = make_inputs(seed);
for (int end = 1; end <= T; ++end) {
for (int split = 0; split < end; ++split) { // split == 0: one group of `end` rows; split > 0: rows [0, split) first, then [split, end)
for (int mode = 0; mode < 2; ++mode) { // 0: gates inside the fused launch, 1: gates joined (computed by the separate a/b launch first)
upload(a, in); upload(b, in);
if (split) { original_rows(f, a, 0, split, true); original_rows(f, b, 0, split, true); }
original_rows(f, a, split, end, true);
if (mode == 1) ab_args_launch(f.ab, b, split, end, 12, 256);
fused_rows(f, b, split, end, mode == 0);
char what[96]; snprintf(what, sizeof what, "fused seed %d end %d split %d %s", seed, end, split, mode ? "joined" : "in-kernel");
compare_layers(what, a, b);
++cases;
}
}
}
}
printf("RESULT fused cases=%d\n", cases);
}
static void test_unrolled(const Fns& f) {
Layer a, b; alloc_layer(a); alloc_layer(b);
int cases = 0;
for (int seed = 0; seed < 3; ++seed) {
Inputs in = make_inputs(seed);
for (int rows = 1; rows <= T; ++rows) {
for (int begin = 0; begin + rows <= T; begin += (T - rows > 0 ? T - rows : 1)) {
upload(a, in); upload(b, in);
ab_args_launch(f.ab, a, begin, begin + rows, 12, 256);
char what[96]; snprintf(what, sizeof what, "unrolled-ab seed %d rows %d begin %d", seed, rows, begin);
const unsigned geometry[2][2] = {{96, 32}, {48, 64}}; // the shipped chain shape, upstream's shape
for (const auto& g : geometry) {
upload(b, in);
ab_args_launch(f.unrolled[rows <= 6 ? rows - 1 : 6], b, begin, begin + rows, g[0], g[1]);
CU(cuStreamSynchronize(g_s));
same(what, a.gate.get(), b.gate.get()); same(what, a.beta.get(), b.beta.get());
}
if (f.chain_ab) {
upload(b, in);
ab_args_launch(f.chain_ab, b, begin, begin + rows, 96, 32);
CU(cuStreamSynchronize(g_s));
same(what, a.gate.get(), b.gate.get()); same(what, a.beta.get(), b.beta.get());
}
++cases;
}
}
}
printf("RESULT unrolled_ab cases=%d chain=%d\n", cases, f.chain_ab ? 1 : 0);
}
int main(int argc, char** argv) {
if (argc < 2) { fprintf(stderr, "usage: %s PTXDIR\n", argv[0]); return 2; }
std::string dir = argv[1];
CU(cuInit(0)); CUdevice dev; CU(cuDeviceGet(&dev, 0)); CUcontext ctx; CU(cuDevicePrimaryCtxRetain(&ctx, dev)); CU(cuCtxSetCurrent(ctx)); CU(cuStreamCreate(&g_s, 0));
CUmodule mo, mf, mc;
if (!load_module(dir + "/original_verify.ptx", &mo) || !load_module(dir + "/sm120_gdn_fused.ptx", &mf)) { fprintf(stderr, "original_verify.ptx / sm120_gdn_fused.ptx missing in %s\n", dir.c_str()); return 2; }
Fns f = {};
f.conv = get_fn(mo, "verify_gdn_conv_l2_multi_kernel"); f.ab = get_fn(mo, "verify_gdn_ab_multi_kernel"); f.step = get_fn(mo, "verify_gdn_step_norm_multi_kernel");
f.fused = get_fn(mf, "leleka_verify_gdn_fused_step");
for (int i = 0; i < 7; ++i) f.unrolled[i] = get_fn(mf, kUnrolled[i]);
f.chain_ab = load_module(dir + "/chain_window.ptx", &mc) ? get_fn(mc, "chain_gdn_ab_multi_kernel") : nullptr;
test_unrolled(f);
test_fused(f);
printf(g_fail ? "FAIL %d comparisons differ\n" : "PASS every byte identical\n", g_fail);
return g_fail ? 1 : 0;
}