sm120 decode switch GU_SWIGLU: fused expert gate/up + SwiGLU + q8_1 (upstream native_gu_swiglu_kernel) in the verify window (default on for cc 12.0)
Replaces window_moe_gu_<T> + swiglu_entries_kernel + quantize_q8_1_kernel of every routed-expert group launch (VRAM and PCIe tier) by one launch of upstream's native_gu_swiglu_kernel (16-lane sub-warp rows, gate and up row at once) for the gate/up types 16 17 18 21 22 23 at n_embd 2560, n_ff % 32 == 0; every other format keeps the three-kernel plan. New sealed asset sm120_gu_swiglu.cu (group sm120-decode) textually includes sm120_iq_prefix.cuh, the pinned iq_kernels.cu up to the dequant banner (generated and checked by scripts/decode-sm120/make_iq_prefix.py; the whole file would instantiate 24 MB of PTX). Kernel parameter: upstream's 88-byte NativeExpertLayout (the window's 64 bytes + tail_off, had_block, d_signs = 0). Switch: policy.gu_swiglu, resolved at window recording from the card (cc 12.0), LELEKA_SM120_PERF=0 and LELEKA_SM120_GU_SWIGLU=0|1. Model-free probe (tools/decode-sm120/sm120_probe.cpp gu, RTX 5090): the q8_1 blocks the down kernel reads are byte-identical to the old three-kernel path in 30 cases (types 16 17 18 21 22 23, 1-8 rows, 1-40 groups, 1-7 entries a group, random blobs with valid block scales); per layer at 4 rows 20.9 -> 14.2 us (16), 29.8 -> 20.7 us (18), 24.9 -> 19.6 us (21), warm L2. Types 29 and 42 are not probed and not routed to the new kernel. Not yet measured end to end. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
0ca709cad1
commit
0765a20958
@@ -280,6 +280,8 @@ pub(crate) struct MoeKnobs {
|
||||
pub native_bf16_extra: bool,
|
||||
/// `native_mmvq` dispatch of the shared expert's projections.
|
||||
pub dispatch: NativeHeadDispatch,
|
||||
/// sm_120 `GU_SWIGLU` (`original_verify_window_sm120.rs`): the fused gate/up + SwiGLU + q8_1 kernel for the formats that have one.
|
||||
pub gu_swiglu: bool,
|
||||
}
|
||||
impl MoeKnobs {
|
||||
pub(crate) fn mode17() -> Self {
|
||||
@@ -290,6 +292,7 @@ impl MoeKnobs {
|
||||
native_bf16: true,
|
||||
native_bf16_extra: true,
|
||||
dispatch: NativeHeadDispatch::default(),
|
||||
gu_swiglu: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -819,6 +822,21 @@ pub(crate) fn plan_expert_groups(
|
||||
])
|
||||
};
|
||||
let mut launches = Vec::with_capacity(4);
|
||||
// sm_120 GU_SWIGLU: one launch for gate/up + SwiGLU + q8_1 where the layer's format has the fused kernel (80 dots a row at n_embd 2560, n_ff a multiple of 32)
|
||||
let fused = if knobs.gu_swiglu && blob.n_embd == 2560 && blob.n_ff % 32 == 0 { super::sm120::gu_swiglu_entry(blob.gu_type) } else { None };
|
||||
if let Some(entry) = fused {
|
||||
// upstream's 88-byte NativeExpertLayout: the 64 bytes above, then tail_off, had_block (+ padding) and d_signs, all zero
|
||||
let mut fused_words = words.clone();
|
||||
fused_words.extend([0u64; 3]);
|
||||
launches.push(Launch::new(
|
||||
&super::sm120::GU_SWIGLU,
|
||||
entry,
|
||||
[(n_ff / 32) as u32, cap as u32, 1],
|
||||
[512, 1, 1],
|
||||
0,
|
||||
vec![A::P(grp_ptr), A::P(grp_start), A::P(n_groups), A::P(ent_tok), A::P(x_q8_1), A::Words(fused_words), A::P(hq)],
|
||||
)?);
|
||||
} else {
|
||||
launches.push(Launch::new(
|
||||
&EXPERTS,
|
||||
gu_entry,
|
||||
@@ -837,6 +855,7 @@ pub(crate) fn plan_expert_groups(
|
||||
],
|
||||
)?);
|
||||
launches.extend(swiglu_quant(tiny)?);
|
||||
}
|
||||
launches.push(Launch::new(
|
||||
&EXPERTS,
|
||||
down_entry,
|
||||
@@ -1478,6 +1497,42 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gu_swiglu_replaces_gate_up_swiglu_and_quantize_by_one_launch_and_keeps_the_down_kernel() {
|
||||
let m = map();
|
||||
let g = test_geometry();
|
||||
let mut fmts = [(16, 20); WINDOW_LAYERS];
|
||||
fmts[7] = (12, 8);
|
||||
fmts[8] = (22, 20);
|
||||
let f = OriginalVerifyExpertFormats::new(fmts, 2560, 640).unwrap();
|
||||
let mut on = MoeKnobs::mode17();
|
||||
on.gu_swiglu = true;
|
||||
let off = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, 0, rows(0, 3, 0), ExpertTier::Vram).unwrap();
|
||||
let fused = plan_expert_groups(&m, &g, &on, &f, 0, rows(0, 3, 0), ExpertTier::Vram).unwrap();
|
||||
assert_eq!(entries(&fused), ["sm120_moe_gu_swiglu_16", "window_moe_down_20"]);
|
||||
assert_eq!((fused[0].grid, fused[0].block, fused[0].shared), ([20, 30, 1], [512, 1, 1], 0));
|
||||
// the arguments: the same group tables, activations and q8_1 output as the three kernels, upstream's 88-byte layout
|
||||
let gu = &off[0].args;
|
||||
let scratch_hq = match &off[2].args[1] { A::P(p) => *p, _ => unreachable!() };
|
||||
assert_eq!(fused[0].args[..5], gu[..5]);
|
||||
assert_eq!(fused[0].args[6], A::P(scratch_hq));
|
||||
match (&fused[0].args[5], &gu[5]) {
|
||||
(A::Words(n), A::Words(o)) => {
|
||||
assert_eq!((n.len(), o.len()), (11, 8));
|
||||
assert_eq!(n[..8], o[..]);
|
||||
assert_eq!(n[8..], [0, 0, 0]);
|
||||
}
|
||||
_ => panic!("layout words"),
|
||||
}
|
||||
// the down kernel is untouched (same arguments, reading the same hq)
|
||||
assert_eq!(fused[1].args, off[3].args);
|
||||
assert_eq!(fused[1].entry, off[3].entry);
|
||||
// layers whose gate/up format has no fused kernel keep the three-kernel plan; so does a knobs set without the switch
|
||||
assert_eq!(entries(&plan_expert_groups(&m, &g, &on, &f, 7, rows(0, 3, 0), ExpertTier::Vram).unwrap())[0], "window_moe_gu_12");
|
||||
assert_eq!(entries(&plan_expert_groups(&m, &g, &on, &f, 8, rows(0, 3, 0), ExpertTier::Pcie).unwrap())[0], "sm120_moe_gu_swiglu_22");
|
||||
assert_eq!(entries(&off).len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expert_groups_refuse_s2_and_a_mismatched_geometry() {
|
||||
let m = map();
|
||||
|
||||
@@ -214,6 +214,9 @@ impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> {
|
||||
}
|
||||
if self.moe.is_some() {
|
||||
assets.extend(moe::assets());
|
||||
if policy.gu_swiglu {
|
||||
assets.push(&sm120::GU_SWIGLU);
|
||||
}
|
||||
}
|
||||
assets.extend(chain::assets());
|
||||
assets
|
||||
@@ -634,13 +637,14 @@ impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> {
|
||||
SAID.call_once(|| eprintln!("leleka-serve qsa decode top-k: {} (compute capability {cc})", if policy.qsa.cluster_topk { "thread-block cluster" } else { "qsa_topk_ref (cluster refused)" }));
|
||||
}
|
||||
// the sm_120 decode switches (original_verify_window_sm120.rs): resolved from the card and the environment, once per recording
|
||||
if policy.qsa.attn_daily || sm120::DEFAULT_ON_ATTN_DAILY || std::env::var_os("LELEKA_SM120_ATTN_DAILY").is_some() {
|
||||
if sm120::DEFAULT_ON_ATTN_DAILY || sm120::DEFAULT_ON_GU_SWIGLU || std::env::vars_os().any(|(k, _)| k.to_string_lossy().starts_with("LELEKA_SM120_")) {
|
||||
let major = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?;
|
||||
let minor = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MINOR)?;
|
||||
let want = policy.qsa.attn_daily || sm120::Sm120Switches::from_env(major, minor).attn_daily;
|
||||
policy.qsa.attn_daily = want && sm120::ATTN_DAILY.sealed().is_ok();
|
||||
let want = sm120::Sm120Switches::from_env(major, minor);
|
||||
policy.qsa.attn_daily = (policy.qsa.attn_daily || want.attn_daily) && sm120::ATTN_DAILY.sealed().is_ok();
|
||||
policy.gu_swiglu = (policy.gu_swiglu || want.gu_swiglu) && sm120::GU_SWIGLU.sealed().is_ok();
|
||||
static SAID: std::sync::Once = std::sync::Once::new();
|
||||
SAID.call_once(|| eprintln!("leleka-serve sm120 attn_daily: {} (compute capability {major}.{minor}, requested {want})", policy.qsa.attn_daily));
|
||||
SAID.call_once(|| eprintln!("leleka-serve sm120 switches: attn_daily={} gu_swiglu={} (compute capability {major}.{minor}, requested {want:?})", policy.qsa.attn_daily, policy.gu_swiglu));
|
||||
}
|
||||
let ple = resources.verifier_journal().has_ple();
|
||||
let roles = if policy.pcie_mode == 2 {
|
||||
|
||||
@@ -59,6 +59,7 @@ impl<'p> Planner<'p> {
|
||||
native_bf16: policy.native_bf16,
|
||||
native_bf16_extra: policy.native_bf16_extra,
|
||||
dispatch: policy.dispatch,
|
||||
gu_swiglu: policy.gu_swiglu,
|
||||
}
|
||||
}
|
||||
fn moe_knobs(&self) -> MoeKnobs {
|
||||
|
||||
@@ -96,6 +96,9 @@ pub struct WindowPolicy {
|
||||
pub gr_variant: super::gr::GrVariant,
|
||||
/// Process-wide QSA branch configuration (native QSA / RoPE, INT8 streamed KV, multi-query scores).
|
||||
pub qsa: super::qsa::OriginalVerifyQsaPolicy,
|
||||
/// sm_120 `GU_SWIGLU` (`sm120_gu_swiglu.cu`): gate/up, SwiGLU and q8_1 of the routed experts in one launch where the layer's gate/up format has the
|
||||
/// fused kernel. Off in `mode17()`; `record_literal_window` resolves it from the card and `LELEKA_SM120_GU_SWIGLU`.
|
||||
pub gu_swiglu: bool,
|
||||
}
|
||||
impl WindowPolicy {
|
||||
pub const fn mode17() -> Self {
|
||||
@@ -116,6 +119,7 @@ impl WindowPolicy {
|
||||
native_ple: true,
|
||||
gr_variant: super::gr::GrVariant::Staged,
|
||||
qsa: super::qsa::OriginalVerifyQsaPolicy::mode17(),
|
||||
gu_swiglu: false,
|
||||
}
|
||||
}
|
||||
pub fn validate_selected(&self) -> Result<()> {
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
//! * `ATTN_DAILY` (`sm120_attn_daily.cu`): the decode attention chunk of upstream's `attn_chunk_kernel_pre75` (16 shuffles per cell pair instead of
|
||||
//! 60, cell-major probabilities, four V loads in flight) and `attn_merge_v2_kernel` (bounded by the width, loads of 16 chunks in flight).
|
||||
//!
|
||||
//! * `GU_SWIGLU` (`sm120_gu_swiglu.cu`): the routed experts' gate/up, SwiGLU and q8_1 quantization in one launch of upstream's `native_gu_swiglu_kernel`
|
||||
//! (16-lane rows, a gate row and its up row at once) instead of `window_moe_gu_<T>` + `swiglu_entries_kernel` + `quantize_q8_1_kernel`.
|
||||
//!
|
||||
//! Resolution, per window recording (`resolve`): a switch is on when its own variable says so (`LELEKA_SM120_<NAME>=1` on, `=0` off, on any card), and
|
||||
//! otherwise when the card is a 12.0 one, `LELEKA_SM120_PERF` is not `0`, and the switch is in the set that passed its gates (`DEFAULT_ON`).
|
||||
use super::kernels::AssetSpec;
|
||||
@@ -23,12 +26,39 @@ pub(crate) static ATTN_DAILY: AssetSpec = AssetSpec {
|
||||
unsealed: "Original verifier asset unsealed: sm120_attn_daily.ptx (ATTN_DAILY decode attention chunk and merge)",
|
||||
};
|
||||
|
||||
pub(crate) const E_GU_SWIGLU: [&str; 6] = [
|
||||
"sm120_moe_gu_swiglu_16",
|
||||
"sm120_moe_gu_swiglu_17",
|
||||
"sm120_moe_gu_swiglu_18",
|
||||
"sm120_moe_gu_swiglu_21",
|
||||
"sm120_moe_gu_swiglu_22",
|
||||
"sm120_moe_gu_swiglu_23",
|
||||
];
|
||||
/// The ggml gate/up types `E_GU_SWIGLU` covers, in the same order.
|
||||
pub(crate) const GU_SWIGLU_TYPES: [u32; 6] = [16, 17, 18, 21, 22, 23];
|
||||
|
||||
/// `sm120_gu_swiglu.cu`, sealed by `scripts/gpu-bringup/seal_pins.py` (extra-seal-plan.json, group sm120-decode).
|
||||
pub(crate) static GU_SWIGLU: AssetSpec = AssetSpec {
|
||||
name: "sm120_gu_swiglu.ptx",
|
||||
ptx: concat!(include_str!("sm120_gu_swiglu.ptx"), "\0").as_bytes(),
|
||||
sha: [107, 0, 213, 80, 35, 131, 13, 91, 78, 112, 245, 194, 119, 44, 69, 22, 61, 118, 18, 91, 59, 9, 185, 31, 8, 119, 145, 191, 64, 140, 101, 123],
|
||||
entries: &E_GU_SWIGLU,
|
||||
unsealed: "Original verifier asset unsealed: sm120_gu_swiglu.ptx (GU_SWIGLU fused expert gate/up + SwiGLU + q8_1)",
|
||||
};
|
||||
|
||||
/// The entry of the fused kernel for gate/up type `ty`, when there is one.
|
||||
pub(crate) fn gu_swiglu_entry(ty: u32) -> Option<&'static str> {
|
||||
GU_SWIGLU_TYPES.iter().position(|t| *t == ty).map(|i| E_GU_SWIGLU[i])
|
||||
}
|
||||
|
||||
/// The switches that are on by default on a 12.0 card.
|
||||
pub(crate) const DEFAULT_ON_ATTN_DAILY: bool = true;
|
||||
pub(crate) const DEFAULT_ON_GU_SWIGLU: bool = true;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Sm120Switches {
|
||||
pub attn_daily: bool,
|
||||
pub gu_swiglu: bool,
|
||||
}
|
||||
|
||||
fn one(get: &impl Fn(&str) -> Option<String>, var: &str, default: bool) -> bool {
|
||||
@@ -43,7 +73,10 @@ impl Sm120Switches {
|
||||
/// The switches for a card of compute capability `major.minor`, from an environment lookup.
|
||||
pub fn resolve(major: i32, minor: i32, get: impl Fn(&str) -> Option<String>) -> Self {
|
||||
let sm120 = major == 12 && minor == 0 && get("LELEKA_SM120_PERF").as_deref().map(str::trim) != Some("0");
|
||||
Self { attn_daily: one(&get, "LELEKA_SM120_ATTN_DAILY", sm120 && DEFAULT_ON_ATTN_DAILY) }
|
||||
Self {
|
||||
attn_daily: one(&get, "LELEKA_SM120_ATTN_DAILY", sm120 && DEFAULT_ON_ATTN_DAILY),
|
||||
gu_swiglu: one(&get, "LELEKA_SM120_GU_SWIGLU", sm120 && DEFAULT_ON_GU_SWIGLU),
|
||||
}
|
||||
}
|
||||
pub fn from_env(major: i32, minor: i32) -> Self {
|
||||
Self::resolve(major, minor, |k| std::env::var(k).ok())
|
||||
@@ -56,6 +89,9 @@ pub(crate) fn assets(s: &Sm120Switches) -> Vec<&'static AssetSpec> {
|
||||
if s.attn_daily {
|
||||
out.push(&ATTN_DAILY);
|
||||
}
|
||||
if s.gu_swiglu {
|
||||
out.push(&GU_SWIGLU);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -82,6 +118,23 @@ mod tests {
|
||||
assert!(!on(12, 0, env(&[("LELEKA_SM120_PERF", "0")])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gu_swiglu_follows_its_own_variable_and_the_master_switch() {
|
||||
assert!(Sm120Switches::resolve(12, 0, env(&[("LELEKA_SM120_GU_SWIGLU", "1")])).gu_swiglu);
|
||||
assert!(Sm120Switches::resolve(8, 9, env(&[("LELEKA_SM120_GU_SWIGLU", "1")])).gu_swiglu);
|
||||
assert!(!Sm120Switches::resolve(12, 0, env(&[("LELEKA_SM120_GU_SWIGLU", "0")])).gu_swiglu);
|
||||
assert_eq!(Sm120Switches::resolve(12, 0, env(&[])).gu_swiglu, DEFAULT_ON_GU_SWIGLU);
|
||||
assert!(!Sm120Switches::resolve(12, 0, env(&[("LELEKA_SM120_PERF", "0")])).gu_swiglu);
|
||||
assert_eq!(gu_swiglu_entry(22), Some("sm120_moe_gu_swiglu_22"));
|
||||
assert_eq!(gu_swiglu_entry(12), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gu_swiglu_asset_is_sealed_and_exports_every_entry() {
|
||||
GU_SWIGLU.assert_sealed_and_fail_closed();
|
||||
assert_eq!(GU_SWIGLU.entries.len(), GU_SWIGLU_TYPES.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_attn_daily_asset_is_sealed_and_exports_both_entries() {
|
||||
ATTN_DAILY.assert_sealed_and_fail_closed();
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// claude/decode-sm120-switches, switch GU_SWIGLU (upstream STRATA_GU_SWIGLU=1, one of the five bitwise switches that Strata 0.2.6 turns on by default on a
|
||||
// compute capability 12.0 card, engine/strata/include/strata/core/sm120_series.hpp; upstream commit 147-verify).
|
||||
//
|
||||
// The window's grouped routed-expert gate/up kernel (`window_moe_gu_<T>`, the old pin's native_gu_multi_kernel: one 32-lane warp per row), the entry-wise
|
||||
// SwiGLU (`swiglu_entries_kernel`) and the q8_1 quantizer (`quantize_q8_1_kernel`) are replaced by ONE launch of upstream's `native_gu_swiglu_kernel<TG, STAGE>`:
|
||||
// 16-lane sub-warp rows (`row_dot2_80_sub16`: a gate row and its up row at once, 100 % active lanes where the warp-per-row kernel idles half of them on its third
|
||||
// pass), the SwiGLU product formed in the block and quantized there (`q8_1_store`), so the gate / up floats never round-trip through memory.
|
||||
//
|
||||
// Source: engine/strata/src/kernels/cuda/iq_kernels.cu at the pinned upstream (docs/upstream.md), textually included (sm120_iq_prefix.cuh: the file up to the dequant
|
||||
// banner, generated by scripts/decode-sm120/make_iq_prefix.py; the whole file's host launchers would instantiate ~60 MB of PTX) so every trait, row dot, q8_1_store and the
|
||||
// grid staging are upstream's. A `__global__` template cannot be called from another kernel, so the body of native_gu_swiglu_kernel is repeated below as a
|
||||
// `__device__` template, line for line, and one extern "C" kernel per gate/up format wraps it. The staging default is upstream's on a 12.0 card
|
||||
// (`launch_gu_swiglu`: stage the codebook for 16 / 17 / 22 / 29, not for IQ3_XXS / IQ3_S (STRATA_IQ_STAGE_TABLES off), none for 23 / 42).
|
||||
//
|
||||
// Outputs are bit for bit the three kernels they replace: tools/decode-sm120/sm120_probe.cpp `gu` compares hq byte for byte against window_moe_gu_<T> +
|
||||
// swiglu_entries_kernel + quantize_q8_1_kernel. Entries: sm120_moe_gu_swiglu_<T> for T in 16 17 18 21 22 23 (the split IQ formats with 80 dots a row at
|
||||
// n_embd 2560 that the probe verified; 29 (IQ1_M) and 42 (Q2_0) would compile but are not probed, so they keep the three-kernel path, like every other gate/up format).
|
||||
//
|
||||
// Compile flags (the recipe of original_verify_window_moe_experts.cu): -ptx -O3 -arch=sm_120 -std=c++17 --fmad=true --ftz=false
|
||||
#include "sm120_iq_prefix.cuh" // opens namespace strata::kernels { namespace {
|
||||
|
||||
|
||||
template <int TG, bool STAGE_GRID>
|
||||
__device__ __forceinline__ void gu_swiglu_body(const unsigned long long* __restrict__ grp_ptr, const int32_t* __restrict__ grp_start,
|
||||
const int32_t* __restrict__ n_groups, const int32_t* __restrict__ ent_tok,
|
||||
const block_q8_1* __restrict__ xq, const NativeExpertLayout& L, block_q8_1* __restrict__ hq) {
|
||||
static_assert(kSplit<TG>, "native_gu_swiglu_kernel is for the split formats");
|
||||
static_assert((2560 / Fmt<TG>::qk) * Fmt<TG>::ipb == 80, "the 16-lane rows assume 80 dots a row at n_embd 2560");
|
||||
const int ng = *n_groups;
|
||||
if ((int) blockIdx.y >= ng) return;
|
||||
STRATA_SHARED_ALIGN16_U32(s_grid_buf, IqGridWords<TG, STAGE_GRID>::value);
|
||||
const uint32_t* s_grid = stage_iq_grid<TG, STAGE_GRID>(s_grid_buf, threadIdx.x, 512);
|
||||
__shared__ float sh[GRP_NC][32];
|
||||
const int sw = threadIdx.x >> 4, t = threadIdx.x & 15, warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
|
||||
const int r = blockIdx.x * 32 + sw; // the hidden column (gate row r, up row r)
|
||||
const size_t g_off = (size_t) r * L.gu_row, u_off = L.up_off + (size_t) r * L.gu_row;
|
||||
for (int g = blockIdx.y; g < ng; g += gridDim.y) {
|
||||
const uint8_t* blob = (const uint8_t*) grp_ptr[g];
|
||||
const float sg = L.tail_off ? ((const float*) (blob + L.tail_off))[0] : 1.0f; // NVFP4: s_gate / s_up
|
||||
const float su = L.tail_off ? ((const float*) (blob + L.tail_off))[1] : 1.0f;
|
||||
const int e0 = grp_start[g], e1 = grp_start[g + 1];
|
||||
for (int e = e0; e < e1; e += GRP_NC) {
|
||||
const int n = min(GRP_NC, e1 - e);
|
||||
float gv[GRP_NC], uv[GRP_NC];
|
||||
if (n == 1) {
|
||||
const int off1[1] = { ent_tok[e] * 80 };
|
||||
float a1[1], b1[1];
|
||||
row_dot2_80_sub16<TG, 1, true, STAGE_GRID>(blob + g_off, blob + u_off, xq, off1, 1, t, a1, b1, s_grid);
|
||||
gv[0] = a1[0]; uv[0] = b1[0];
|
||||
} else if (n == 2) {
|
||||
const int off2[2] = { ent_tok[e] * 80, ent_tok[e + 1] * 80 };
|
||||
float a2[2], b2[2];
|
||||
row_dot2_80_sub16<TG, 2, true, STAGE_GRID>(blob + g_off, blob + u_off, xq, off2, 2, t, a2, b2, s_grid);
|
||||
#pragma unroll
|
||||
for (int c = 0; c < 2; ++c) { gv[c] = a2[c]; uv[c] = b2[c]; }
|
||||
} else if (n == 3) {
|
||||
const int off3[3] = { ent_tok[e] * 80, ent_tok[e + 1] * 80, ent_tok[e + 2] * 80 };
|
||||
float a3[3], b3[3];
|
||||
row_dot2_80_sub16<TG, 3, true, STAGE_GRID>(blob + g_off, blob + u_off, xq, off3, 3, t, a3, b3, s_grid);
|
||||
#pragma unroll
|
||||
for (int c = 0; c < 3; ++c) { gv[c] = a3[c]; uv[c] = b3[c]; }
|
||||
} else {
|
||||
const int off4[4] = { ent_tok[e] * 80, ent_tok[e + 1] * 80, ent_tok[e + 2] * 80, ent_tok[e + 3] * 80 };
|
||||
float a4[4], b4[4];
|
||||
row_dot2_80_sub16<TG, 4, true, STAGE_GRID>(blob + g_off, blob + u_off, xq, off4, 4, t, a4, b4, s_grid);
|
||||
#pragma unroll
|
||||
for (int c = 0; c < 4; ++c) { gv[c] = a4[c]; uv[c] = b4[c]; }
|
||||
}
|
||||
// sub-lane c holds entry c's sums (as the separate kernel's store): h of column r, entry c
|
||||
#pragma unroll
|
||||
for (int c = 0; c < GRP_NC; ++c) {
|
||||
if (c < n && t == c) {
|
||||
const float gg = gv[c] * sg, uu = uv[c] * su;
|
||||
sh[c][sw] = __fmul_rn(gg / (1.0f + __expf(-gg)), uu);
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (warp < n) q8_1_store(sh[warp][lane], hq, (long long) (e + warp) * L.n_ff + (long long) blockIdx.x * 32 + lane);
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace (the anonymous one the prefix opened)
|
||||
|
||||
// Kernel parameters, in upstream's order: (grp_ptr, grp_start, n_groups, ent_tok, xq, L, hq); `L` is the 64-byte NativeExpertLayout by value.
|
||||
// STAGE: upstream's default on a 12.0 card (see the header).
|
||||
#define STRATA_SM120_GU_SWIGLU(T, STAGE) \
|
||||
extern "C" __global__ void __launch_bounds__(512) sm120_moe_gu_swiglu_##T( \
|
||||
const unsigned long long* __restrict__ grp_ptr, const int32_t* __restrict__ grp_start, \
|
||||
const int32_t* __restrict__ n_groups, const int32_t* __restrict__ ent_tok, const block_q8_1* __restrict__ xq, \
|
||||
NativeExpertLayout L, block_q8_1* __restrict__ hq) { \
|
||||
gu_swiglu_body<T, STAGE>(grp_ptr, grp_start, n_groups, ent_tok, xq, L, hq); \
|
||||
}
|
||||
STRATA_SM120_GU_SWIGLU(16, true)
|
||||
STRATA_SM120_GU_SWIGLU(17, true)
|
||||
STRATA_SM120_GU_SWIGLU(18, false)
|
||||
STRATA_SM120_GU_SWIGLU(21, false)
|
||||
STRATA_SM120_GU_SWIGLU(22, true)
|
||||
STRATA_SM120_GU_SWIGLU(23, false)
|
||||
#undef STRATA_SM120_GU_SWIGLU
|
||||
|
||||
} // namespace strata::kernels
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate (or --check) crates/cuda-driver/src/sm120_iq_prefix.cuh: lines 1..END of engine/strata/src/kernels/cuda/iq_kernels.cu.
|
||||
|
||||
END is the line before the `dequant (dequantize.cuh)` banner, i.e. everything up to and including native_gu_swiglu_kernel. The whole file instantiates ~60 MB of PTX
|
||||
through its host launchers (past the 16 MiB asset limit); the prefix holds every trait, row dot and q8_1_store the fused expert kernel needs and no launcher.
|
||||
The prefix is byte for byte the upstream text (plus a two-line header), so it is checked against the engine tree: --check fails when the pinned file changed.
|
||||
"""
|
||||
import sys
|
||||
|
||||
SRC = "engine/strata/src/kernels/cuda/iq_kernels.cu"
|
||||
DST = "crates/cuda-driver/src/sm120_iq_prefix.cuh"
|
||||
BANNER = "// ---------------------------------------------------------------- dequant (dequantize.cuh)"
|
||||
HEADER = ("// GENERATED by scripts/decode-sm120/make_iq_prefix.py from " + SRC + " (the pinned upstream, docs/upstream.md): the file up to the dequant banner,\n"
|
||||
"// unchanged. Do not edit; `make_iq_prefix.py --check` compares it with the engine tree. Opens `namespace strata::kernels { namespace {` and leaves both open.\n")
|
||||
|
||||
lines = open(SRC, newline="").read().split("\n")
|
||||
end = next(i for i, l in enumerate(lines) if l.rstrip("\r") == BANNER)
|
||||
want = HEADER + "\n".join(lines[:end]) + "\n"
|
||||
if "--check" in sys.argv:
|
||||
have = open(DST, newline="").read()
|
||||
sys.exit(0 if have == want else "sm120_iq_prefix.cuh is stale against " + SRC)
|
||||
open(DST, "w", newline="").write(want)
|
||||
print("wrote", DST, end, "upstream lines")
|
||||
@@ -843,6 +843,37 @@
|
||||
},
|
||||
"group": "sm120-decode",
|
||||
"optional": false
|
||||
},
|
||||
{
|
||||
"cu": "crates/cuda-driver/src/sm120_gu_swiglu.cu",
|
||||
"ptx": "crates/cuda-driver/src/sm120_gu_swiglu.ptx",
|
||||
"flags": [
|
||||
"-ptx",
|
||||
"-O3",
|
||||
"-arch=sm_120",
|
||||
"-std=c++17",
|
||||
"--fmad=true",
|
||||
"--ftz=false",
|
||||
"-Iengine/strata/src/kernels/cuda"
|
||||
],
|
||||
"include_profile": "standard",
|
||||
"policy": "precise (--fmad=true --ftz=false: the recipe of original_verify_window_moe_experts.cu; upstream STRATA_GU_SWIGLU, bitwise the three kernels it replaces)",
|
||||
"entries": [
|
||||
"sm120_moe_gu_swiglu_16",
|
||||
"sm120_moe_gu_swiglu_17",
|
||||
"sm120_moe_gu_swiglu_18",
|
||||
"sm120_moe_gu_swiglu_21",
|
||||
"sm120_moe_gu_swiglu_22",
|
||||
"sm120_moe_gu_swiglu_23"
|
||||
],
|
||||
"encoding": "concat_include_str",
|
||||
"rust_fields_to_fill": {
|
||||
"original_verify_window_sm120.rs": [
|
||||
"GU_SWIGLU.sha"
|
||||
]
|
||||
},
|
||||
"group": "sm120-decode",
|
||||
"optional": false
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ out="${1:-$HOME/sm120-bin}"
|
||||
nvcc="${NVCC:-$HOME/cuda-toolkits/13.2.2/bin/nvcc}"
|
||||
mkdir -p "$out/ptx"
|
||||
"$nvcc" -O2 -std=c++17 "$here/sm120_probe.cpp" -lcuda -o "$out/sm120_probe"
|
||||
for f in mtp_original_full_attention sm120_attn_daily; do
|
||||
for f in mtp_original_full_attention original_verify_window_moe_experts mtp_original_full_head_iq sm120_attn_daily sm120_gu_swiglu; do
|
||||
cp "$root/crates/cuda-driver/src/$f.ptx" "$out/ptx/$f.ptx"
|
||||
done
|
||||
sha256sum "$out"/sm120_probe "$out"/ptx/* > "$out/SHA256SUMS"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// claude/decode-sm120-switches: model-free probe of the sm_120 decode switches. Each switch's PTX (crates/cuda-driver/src/sm120_*.ptx) is run next to the
|
||||
// kernel of the current window that it replaces, on real-size random inputs, and EVERY output byte is compared; the kernels are also timed inside a CUDA graph
|
||||
// with cold data. Prints "RESULT name key=value" lines; exits 1 if any comparison differs. Never touches the model.
|
||||
// sm120_probe PTXDIR [test ...] tests: attn (default: all that exist)
|
||||
// sm120_probe PTXDIR [test ...] tests: attn gu (default: all); PTXDIR holds the sealed Original PTX (mtp_original_full_attention, original_verify_window_moe_experts, mtp_original_full_head_iq) and the sm120_*.ptx
|
||||
// PTXDIR holds mtp_original_full_attention.ptx (the sealed Original chunk / merge) and sm120_attn_daily.ptx.
|
||||
#include <cuda.h>
|
||||
#include <vector_types.h>
|
||||
@@ -161,12 +161,116 @@ static void test_attn() {
|
||||
printf("RESULT attn_summary cases=%d byte_mismatches=%d\n", cases, g_fail - bad_before);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
// GU_SWIGLU: window_moe_gu_<T> + swiglu_entries_kernel + quantize_q8_1_kernel (sealed Original) against sm120_moe_gu_swiglu_<T>; compares hq (the q8_1 blocks
|
||||
// the down kernel reads) byte for byte, on random expert blobs (valid fp16 block scales) and random q8_1 activations.
|
||||
static uint16_t half_of(float f) { // IEEE half, round to nearest even, normal range only
|
||||
uint32_t u; memcpy(&u, &f, 4); uint32_t sign = (u >> 16) & 0x8000; int e = ((u >> 23) & 0xff) - 127 + 15; uint32_t m = (u >> 13) & 0x3ff;
|
||||
return (uint16_t)(sign | (e << 10) | m);
|
||||
}
|
||||
struct Layout88 { int32_t gu_type, d_type; int64_t n_embd, n_ff; uint64_t gu_row, d_row, up_off, down_off, bytes, tail_off; int32_t had_block, pad; uint64_t d_signs; };
|
||||
static_assert(sizeof(Layout88) == 88, "upstream NativeExpertLayout");
|
||||
struct Layout64 { int32_t gu_type, d_type; int64_t n_embd, n_ff; uint64_t gu_row, d_row, up_off, down_off, bytes; };
|
||||
static_assert(sizeof(Layout64) == 64, "Original NativeExpertLayout");
|
||||
|
||||
static void test_gu() {
|
||||
CUmodule mOld = load_module(g_dir + "/original_verify_window_moe_experts.ptx");
|
||||
CUmodule mIq = load_module(g_dir + "/mtp_original_full_head_iq.ptx");
|
||||
CUmodule mNew = load_module(g_dir + "/sm120_gu_swiglu.ptx");
|
||||
CUfunction fSwi = get_fn(mIq, "_ZN6strata7kernels65_GLOBAL__N__a184a76c_28_mtp_original_full_head_iq_cu_934c6f21_28421swiglu_entries_kernelEPKfS3_Pfx");
|
||||
CUfunction fQ = get_fn(mIq, "_ZN6strata7kernels65_GLOBAL__N__a184a76c_28_mtp_original_full_head_iq_cu_934c6f21_28420quantize_q8_1_kernelEPKfP10block_q8_1x");
|
||||
struct T { int ty; int blk; }; // 256-value block bytes (d is the first fp16 of the block)
|
||||
const T types[] = {{16, 66}, {17, 74}, {18, 98}, {21, 110}, {22, 82}, {23, 136}};
|
||||
const int n_embd = 2560, n_ff = 640, K = 10;
|
||||
int cases = 0, bad_before = g_fail;
|
||||
for (auto tt : types) {
|
||||
const size_t gu_row = (size_t)(n_embd / 256) * tt.blk, up_off = (size_t)n_ff * gu_row, down_off = up_off * 2;
|
||||
const size_t d_row = (size_t)(n_ff / 32) * 18; // a down row (unused by the gate/up kernels)
|
||||
const size_t blob_bytes = down_off + (size_t)n_embd * d_row;
|
||||
for (int T_rows : {1, 3, 4, 6, 8}) {
|
||||
const int cap = T_rows * K;
|
||||
// groups: a random subset of 'experts' with random entry counts; entries are (token) rows
|
||||
int ng = 1 + (int)(rnd() % (unsigned)std::min(cap, 40));
|
||||
if (cases % 5 == 0) ng = std::min(cap, 40);
|
||||
std::vector<int32_t> start(ng + 1), tok;
|
||||
start[0] = 0;
|
||||
for (int g = 0; g < ng; ++g) {
|
||||
int c = 1 + (int)(rnd() % 7);
|
||||
if (g == ng - 1 && cases % 3 == 0) c = 1;
|
||||
c = std::min(c, cap - (int)tok.size() - (ng - 1 - g));
|
||||
if (c < 1) c = 1;
|
||||
for (int i = 0; i < c; ++i) tok.push_back((int32_t)(rnd() % T_rows));
|
||||
start[g + 1] = (int32_t)tok.size();
|
||||
}
|
||||
const int E = (int)tok.size();
|
||||
if (E > cap) continue;
|
||||
std::vector<std::vector<uint8_t>> blobs(ng);
|
||||
std::vector<Dev> dblob(ng);
|
||||
std::vector<uint64_t> ptrs(ng);
|
||||
for (int g = 0; g < ng; ++g) {
|
||||
blobs[g].resize(blob_bytes);
|
||||
for (auto& b : blobs[g]) b = (uint8_t)rnd();
|
||||
for (size_t off = 0; off + tt.blk <= down_off; off += tt.blk) { uint16_t h = half_of(0.002f + 0.01f * fabsf(rndf())); memcpy(&blobs[g][off], &h, 2); }
|
||||
dblob[g].alloc(blob_bytes); dblob[g].put(blobs[g].data(), blob_bytes); ptrs[g] = dblob[g].p;
|
||||
}
|
||||
const size_t xrow = 80 * 36;
|
||||
std::vector<uint8_t> xq((size_t)T_rows * xrow);
|
||||
for (int r = 0; r < T_rows; ++r) for (int b = 0; b < 80; ++b) {
|
||||
uint8_t* blk = &xq[(size_t)r * xrow + (size_t)b * 36];
|
||||
uint16_t d = half_of(0.01f + 0.02f * fabsf(rndf())), s = half_of(rndf());
|
||||
memcpy(blk, &d, 2); memcpy(blk + 2, &s, 2);
|
||||
for (int j = 0; j < 32; ++j) blk[4 + j] = (uint8_t)rnd();
|
||||
}
|
||||
Dev dptr, dstart, dng, dtok, dx, gate, up, h, hq0, hq1;
|
||||
const size_t nh = (size_t)cap * n_ff, hqb = (size_t)cap * (n_ff / 32) * 36;
|
||||
dptr.alloc(ng * 8); dptr.put(ptrs.data(), ng * 8); dstart.alloc((ng + 1) * 4); dstart.put(start.data(), (ng + 1) * 4);
|
||||
int32_t ngi = ng; dng.alloc(4); dng.put(&ngi, 4);
|
||||
std::vector<int32_t> tokp(tok); tokp.resize(cap + 8, 0); dtok.alloc(tokp.size() * 4); dtok.put(tokp.data(), tokp.size() * 4);
|
||||
dx.alloc(xq.size()); dx.put(xq.data(), xq.size());
|
||||
gate.alloc(nh * 4); up.alloc(nh * 4); h.alloc(nh * 4); hq0.alloc(hqb); hq1.alloc(hqb);
|
||||
Layout64 l64{tt.ty, 20, n_embd, n_ff, gu_row, d_row, up_off, down_off, blob_bytes};
|
||||
Layout88 l88{};
|
||||
l88.gu_type = tt.ty; l88.d_type = 20; l88.n_embd = n_embd; l88.n_ff = n_ff; l88.gu_row = gu_row; l88.d_row = d_row;
|
||||
l88.up_off = up_off; l88.down_off = down_off; l88.bytes = blob_bytes;
|
||||
char nm[64];
|
||||
snprintf(nm, sizeof nm, "window_moe_gu_%d", tt.ty); CUfunction fo = get_fn(mOld, nm);
|
||||
snprintf(nm, sizeof nm, "sm120_moe_gu_swiglu_%d", tt.ty); CUfunction fn = get_fn(mNew, nm);
|
||||
long long nhl = (long long)nh;
|
||||
void* a0[] = {&dptr.p, &dstart.p, &dng.p, &dtok.p, &dx.p, &l64, &gate.p, &up.p};
|
||||
void* sw[] = {&gate.p, &up.p, &h.p, &nhl};
|
||||
void* qa[] = {&h.p, &hq0.p, &nhl};
|
||||
void* a1[] = {&dptr.p, &dstart.p, &dng.p, &dtok.p, &dx.p, &l88, &hq1.p};
|
||||
auto old_path = [&]() {
|
||||
CU(cuLaunchKernel(fo, (2 * n_ff + 7) / 8, cap, 1, 256, 1, 1, 0, g_s, a0, nullptr));
|
||||
CU(cuLaunchKernel(fSwi, (unsigned)((nh + 255) / 256), 1, 1, 256, 1, 1, 0, g_s, sw, nullptr));
|
||||
CU(cuLaunchKernel(fQ, (unsigned)((nh + 255) / 256), 1, 1, 256, 1, 1, 0, g_s, qa, nullptr));
|
||||
};
|
||||
auto new_path = [&]() { CU(cuLaunchKernel(fn, n_ff / 32, cap, 1, 512, 1, 1, 0, g_s, a1, nullptr)); };
|
||||
old_path(); new_path(); CU(cuStreamSynchronize(g_s));
|
||||
// compare the blocks of the E real entries only (rows >= E are never written by either path)
|
||||
auto v0 = hq0.get(), v1 = hq1.get();
|
||||
v0.resize((size_t)E * (n_ff / 32) * 36); v1.resize(v0.size());
|
||||
char tag[96]; snprintf(tag, sizeof tag, "gu type=%d rows=%d groups=%d entries=%d", tt.ty, T_rows, ng, E);
|
||||
bool ok = same(tag, v0, v1);
|
||||
++cases;
|
||||
if (T_rows == 4 && ng >= 20) {
|
||||
double to = time_graph([&](int) { old_path(); }, 30), tn = time_graph([&](int) { new_path(); }, 30);
|
||||
printf("RESULT gu type=%d rows=%d groups=%d entries=%d ok=%d old3_us=%.3f new_us=%.3f\n", tt.ty, T_rows, ng, E, ok, to, tn);
|
||||
}
|
||||
for (auto& d : dblob) cuMemFree(d.p);
|
||||
cuMemFree(dptr.p); cuMemFree(dstart.p); cuMemFree(dng.p); cuMemFree(dtok.p); cuMemFree(dx.p);
|
||||
cuMemFree(gate.p); cuMemFree(up.p); cuMemFree(h.p); cuMemFree(hq0.p); cuMemFree(hq1.p);
|
||||
}
|
||||
}
|
||||
printf("RESULT gu_summary cases=%d byte_mismatches=%d\n", cases, g_fail - bad_before);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 2) { fprintf(stderr, "usage: sm120_probe PTXDIR [tests...]\n"); return 2; }
|
||||
g_dir = argv[1];
|
||||
std::vector<std::string> tests;
|
||||
for (int i = 2; i < argc; ++i) tests.push_back(argv[i]);
|
||||
if (tests.empty()) tests = {"attn"};
|
||||
if (tests.empty()) tests = {"attn", "gu"};
|
||||
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);
|
||||
@@ -174,6 +278,7 @@ int main(int argc, char** argv) {
|
||||
CU(cuStreamCreate(&g_s, CU_STREAM_NON_BLOCKING));
|
||||
for (auto& t : tests) {
|
||||
if (t == "attn") test_attn();
|
||||
else if (t == "gu") test_gu();
|
||||
else fprintf(stderr, "unknown test %s\n", t.c_str());
|
||||
}
|
||||
printf("RESULT summary failures=%d\n", g_fail);
|
||||
|
||||
Reference in New Issue
Block a user