From 00271e44600fd37ecfceba1e4d1f1ec55391b73d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 14 Oct 2026 15:58:20 +0200 Subject: [PATCH] feat(verify): GR / head-mix / PLE layer-1 window launch plans over the sealed fused-GR, native post and PLE assets hc_read (fused_gr_read_multi variants + down_chunk), final_write, per-token lm_head_mix and the layer-1 PLE block, with the exact-size weight binding. Co-Authored-By: Claude Sonnet 5.5 --- .../src/original_verify_window_gr.rs | 1367 ++++++++++++++++- 1 file changed, 1366 insertions(+), 1 deletion(-) diff --git a/crates/cuda-driver/src/original_verify_window_gr.rs b/crates/cuda-driver/src/original_verify_window_gr.rs index 36113f1d..2c5b5c53 100644 --- a/crates/cuda-driver/src/original_verify_window_gr.rs +++ b/crates/cuda-driver/src/original_verify_window_gr.rs @@ -1 +1,1366 @@ -//! (stub: filled by the window-producer family work; see `original_verify_window_proj.rs` for the pattern) +//! Hyper-connection family of the Verifier window (child of `original_verify`): the fused +//! GR read (`fused_gr_read_multi`), the final residual write, the head mix +//! (`lm_head_mix`) and the layer-1 PLE block of `Verifier::record_window`. +//! +//! Everything here is a pure planner (addresses in, `Launch`es out) over sealed assets: +//! +//! * `mtp_original_full_fused_gr.ptx` holds the literal Original `fused_gr.cu` kernels as the +//! six `mtp_scalar_gr_*` wrappers, each taking the Original `GrMulti` by value +//! (114 u64 words: eight 14-word `FusedGrArgs`, then `xn` at word 112 and `T` at word 113): +//! `norm` (plain norm, one block per token), `split` (norm per token and stream), +//! `staged` (cp.async down projection), `up`, `down1280` / `down2560` +//! (`gr_down_multi_kernel`). +//! * `mtp_original_full_gr_norm.ptx` / `mtp_original_full_gr_post.ptx` hold the native +//! (`gr_set_native_mmvf(true)`, the mode17 setting) `gr_read` / `gr_write` pieces: +//! `native_gr_rms_norm_weighted`, `native_gr_down_silu`, `native_gr_pre_gated`, +//! `native_gr_post`. +//! * `ple_native_batch.ptx` holds the Original `native_ple_postops_batch` kernels; with `T = 1` +//! their launch geometry and per-element arithmetic are the single-token `native_ple_postops` +//! kernels `ple_block` runs in the decode path (see `plan_ple_row`). +//! * the projections are the shared `proj` primitives (`bf16_gemv_fp32_mmvf`, q8_1 + MMVQ). +//! +//! The Original selects the hc read variant per card (`fused_gr_check`, `STRATA_HC_SPLIT`) and +//! the down kernel's tile and token chunking from the device attributes (`down_chunk`); +//! `GrConfig` carries exactly those decisions and `GrConfig::from_device` replicates `down_chunk`. +use super::kernels::{A, ArenaMap, AssetSpec, Launch}; +use super::layout::OriginalVerifyGeometry; +use super::proj::{self, NativeWeight, plan_bf16_gemv, plan_mmvq, plan_quantize_q8_1, q8_1_row_bytes}; +use super::window_record::{HcHalf, Rows}; +use super::{OriginalVerifyGdnJournal, admit, handle}; +use crate::native_head::native_head_row_bytes; +use crate::{Context, DeviceBuffer, Error, NativeHeadDispatch, Result}; + +// ------------------------------------------------------------------------------------------------ +// Geometry of the artifact (`fused_gr.cu` is compiled for exactly these) +// ------------------------------------------------------------------------------------------------ +const N: usize = 2560; +const HC: usize = 4; +const LR: usize = 320; +const D: usize = N * HC; +const MAX_T: usize = 8; +const LAYERS: usize = 48; +const DOWN_BLOCKS: u32 = (LR / 8) as u32 + 1; +const UP_BLOCKS: u32 = (N / 16) as u32; +const THREADS: u32 = 256; +const EPS: f32 = 1e-6; +/// `1.0f / float(hc)`: the scale of `native_gr_down_silu`, `native_gr_pre_gated`, `native_gr_post`. +const QUARTER: f32 = 0.25; +const STAGED_TILE: u32 = 1280; + +/// Words of `FusedGrArgs` (112 bytes) and of `GrMulti` (912 bytes). +const ARGS_WORDS: usize = 14; +const MULTI_WORDS: usize = ARGS_WORDS * MAX_T + 2; +const XN_WORD: usize = ARGS_WORDS * MAX_T; +const T_WORD: usize = XN_WORD + 1; + +/// Bytes of the hc weights of one half (`hc_attn_*` / `hc_ffn_*`) and of the final mixer. +pub const HC_NORM_BYTES: usize = D * 4; +pub const HC_DOWN_BYTES: usize = LR * D * 2; +pub const HC_UP_BYTES: usize = D * LR * 2; +pub const HC_INJECT_BYTES: usize = HC * D * 2; + +// ------------------------------------------------------------------------------------------------ +// Sealed assets +// ------------------------------------------------------------------------------------------------ +const E_NORM: &str = "mtp_scalar_gr_norm"; +const E_SPLIT: &str = "mtp_scalar_gr_split"; +const E_STAGED: &str = "mtp_scalar_gr_staged"; +const E_UP: &str = "mtp_scalar_gr_up"; +const E_DOWN1280: &str = "mtp_scalar_gr_down1280"; +const E_DOWN2560: &str = "mtp_scalar_gr_down2560"; + +pub(crate) static GR_FUSED: AssetSpec = AssetSpec { + name: "mtp_original_full_fused_gr.ptx", + ptx: include_bytes!("mtp_original_full_fused_gr.ptx"), + sha: [ + 172, 84, 0, 167, 151, 43, 63, 36, 38, 72, 194, 222, 113, 239, 79, 23, 132, 102, 211, 139, 19, 146, 168, 58, 149, + 145, 179, 178, 78, 146, 197, 155, + ], + entries: &[E_NORM, E_SPLIT, E_STAGED, E_UP, E_DOWN1280, E_DOWN2560], + unsealed: "Original verifier asset unsealed: mtp_original_full_fused_gr.ptx (fused hc read)", +}; +pub(crate) static GR_NORM: AssetSpec = AssetSpec { + name: "mtp_original_full_gr_norm.ptx", + ptx: include_bytes!("mtp_original_full_gr_norm.ptx"), + sha: [ + 186, 149, 215, 197, 178, 124, 201, 212, 193, 207, 188, 107, 59, 205, 0, 14, 91, 162, 155, 18, 76, 102, 28, 9, 5, + 21, 200, 109, 130, 55, 224, 92, + ], + entries: &["mtp_full_gr_norm"], + unsealed: "Original verifier asset unsealed: mtp_original_full_gr_norm.ptx (native weighted RMS norm)", +}; +pub(crate) static GR_POST: AssetSpec = AssetSpec { + name: "mtp_original_full_gr_post.ptx", + ptx: include_bytes!("mtp_original_full_gr_post.ptx"), + sha: [ + 232, 132, 196, 163, 162, 6, 149, 199, 152, 212, 139, 21, 102, 87, 255, 36, 185, 50, 44, 21, 104, 67, 15, 81, 68, + 207, 218, 238, 209, 78, 242, 90, + ], + entries: &["mtp_full_down_silu", "mtp_full_pre_final", "mtp_full_native_write"], + unsealed: "Original verifier asset unsealed: mtp_original_full_gr_post.ptx (native hc silu / gate / write)", +}; +pub(crate) static PLE_BATCH: AssetSpec = AssetSpec { + name: "ple_native_batch.ptx", + ptx: concat!(include_str!("ple_native_batch.ptx"), "\0").as_bytes(), + sha: [ + 26, 56, 44, 190, 134, 123, 193, 147, 198, 175, 82, 146, 194, 203, 207, 189, 142, 47, 87, 205, 25, 80, 201, 13, 228, + 243, 0, 0, 54, 116, 16, 179, + ], + entries: &["ple_gate", "ple_rms", "ple_broadcast", "ple_conv", "ple_history"], + unsealed: "Original verifier asset unsealed: ple_native_batch.ptx (native PLE post-ops)", +}; + +/// Every module this family may launch from (the lead preloads them BEFORE capture). +pub(crate) fn assets() -> Vec<&'static AssetSpec> { + vec![ + &GR_FUSED, + &GR_NORM, + &GR_POST, + &PLE_BATCH, + &proj::BF16, + &proj::HEAD_NATIVE, + &proj::HEAD_IQ, + ] +} + +// ------------------------------------------------------------------------------------------------ +// Process-wide / per-card decisions of the Original +// ------------------------------------------------------------------------------------------------ + +/// `fused_gr_variant()`: which bitwise-equal arrangement of the multi read runs on the card. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum GrVariant { + /// `kHcPlain`: norm one block per token, plain down projection. + Plain, + /// `kHcSplit`: norm one block per token and stream, plain down projection. + Split, + /// `kHcStaged`: split norm, cp.async staged down projection. + Staged, +} +impl GrVariant { + /// `env_variant()`: `STRATA_HC_SPLIT` unset / empty / other = staged, `0` plain, `1` split. + /// `fused_gr_check` may still lower the choice for a card where the check disagrees; the + /// runtime passes the variant that check settled on. + pub(crate) fn from_env_value(value: Option<&str>) -> Self { + match value.and_then(|v| v.bytes().next()) { + None => GrVariant::Staged, + Some(b'0') => GrVariant::Plain, + Some(b'1') => GrVariant::Split, + Some(_) => GrVariant::Staged, + } + } +} + +/// `cuDeviceGetAttribute` ids `down_chunk` reads. +pub(crate) const ATTR_MAX_SHARED_PER_BLOCK: i32 = 8; +pub(crate) const ATTR_COMPUTE_CAPABILITY_MAJOR: i32 = 75; +pub(crate) const ATTR_COMPUTE_CAPABILITY_MINOR: i32 = 76; +pub(crate) const ATTR_MAX_SHARED_PER_BLOCK_OPTIN: i32 = 97; + +/// The hc-read decisions: `fused_gr_variant()` plus the result of `down_chunk` on this card. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct GrConfig { + pub variant: GrVariant, + /// `gr_set_native_mmvf` (`--native`, the mode17 setting). The final write and the head mix + /// follow it; a non-native Original is refused (fail closed). + pub native_mmvf: bool, + /// The plain down kernel's TILEV: 1280 on sm_75, 2560 elsewhere. + pub tile: u32, + /// Tokens one plain down launch may carry (`down_chunk(false)`). + pub chunk_plain: usize, + /// Tokens one staged down launch may carry (`down_chunk(true)`). + pub chunk_staged: usize, + /// The shared memory a launch can actually have (`usable` of `down_chunk`). + pub usable_shared: u32, + /// `cudaFuncSetAttribute(gr_down_multi_kernel, MaxDynamicSharedMemorySize, bytes)`. + pub attr_down: Option, + /// The same for `gr_down_staged_kernel`. + pub attr_staged: Option, +} +impl GrConfig { + /// Replicates the one-time per-device block of `down_chunk` from the four device attributes + /// (`ATTR_*`). An attribute call is only emitted when the card reports an opt-in (Original + /// issues it unconditionally but ignores its failure and drops the error). + pub(crate) fn from_device( + variant: GrVariant, + native_mmvf: bool, + cc_major: i32, + cc_minor: i32, + optin: i32, + per_block: i32, + ) -> Self { + let optin = optin.max(0) as u32; + let per_block = per_block.max(0) as u32; + let small_tile = cc_major * 10 + cc_minor == 75; + let tile: u32 = if small_tile { 1280 } else { 2560 }; + let mut want = MAX_T as u32 * tile * 4; + if optin > 0 && want > optin { + want = optin; + } + let mut want_staged = 2 * MAX_T as u32 * STAGED_TILE * 4; + if optin > 0 && want_staged > optin { + want_staged = optin; + } + // Below sm_70 the opt-in is a promise the card does not keep: the per-block limit counts. + let usable = if cc_major >= 7 && optin > 0 { optin } else { per_block }; + let clamp = |capacity: u32| (capacity.max(1) as usize).min(MAX_T); + Self { + variant, + native_mmvf, + tile, + chunk_plain: clamp(usable / (tile * 4)), + chunk_staged: clamp(usable / (2 * STAGED_TILE * 4)), + usable_shared: usable, + attr_down: (optin > 0).then_some(want), + attr_staged: (optin > 0).then_some(want_staged), + } + } + + /// `from_device` with the attributes read from the verifier's device. + pub(crate) fn query( + journal: &OriginalVerifyGdnJournal<'_, '_>, + variant: GrVariant, + native_mmvf: bool, + ) -> Result { + Ok(Self::from_device( + variant, + native_mmvf, + journal.window_device_attribute(ATTR_COMPUTE_CAPABILITY_MAJOR)?, + journal.window_device_attribute(ATTR_COMPUTE_CAPABILITY_MINOR)?, + journal.window_device_attribute(ATTR_MAX_SHARED_PER_BLOCK_OPTIN)?, + journal.window_device_attribute(ATTR_MAX_SHARED_PER_BLOCK)?, + )) + } + + fn down_entry(&self) -> &'static str { + if self.variant == GrVariant::Staged { + E_STAGED + } else if self.tile == 1280 { + E_DOWN1280 + } else { + E_DOWN2560 + } + } +} + +/// The `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE)` calls `down_chunk` makes once per device +/// (`gr_down_multi_kernel` and `gr_down_staged_kernel`), to apply before capture. +pub(crate) fn shared_attributes(cfg: &GrConfig) -> Vec<(&'static AssetSpec, &'static str, usize)> { + let mut out = Vec::new(); + if let Some(bytes) = cfg.attr_down { + let entry = if cfg.tile == 1280 { E_DOWN1280 } else { E_DOWN2560 }; + out.push((&GR_FUSED, entry, bytes as usize)); + } + if let Some(bytes) = cfg.attr_staged { + out.push((&GR_FUSED, E_STAGED, bytes as usize)); + } + out +} + +/// PLE settings of the Original (`--native`: `ple_set_native_bf16` + `ple_set_native_postops`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PleConfig { + /// `ple_set_native_bf16`: the value projection is the pinned BF16 MMVF. + pub native_value_bf16: bool, + /// `ple_set_native_postops`: pinned norms, gate, conv and residual. + pub native_postops: bool, + /// The dispatch of the native key MMVQ (`PleKey::Native`). + pub dispatch: NativeHeadDispatch, +} +impl PleConfig { + pub(crate) fn mode17() -> Self { + Self { native_value_bf16: true, native_postops: true, dispatch: NativeHeadDispatch::default() } + } +} + +// ------------------------------------------------------------------------------------------------ +// Weight addresses +// ------------------------------------------------------------------------------------------------ + +/// The four weights of one hc half (`hc_attn_*` / `hc_ffn_*` of one layer). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct HcAddrs { + pub norm: u64, + pub down: u64, + pub up: u64, + pub inject: u64, +} +/// `output_hc_{norm,down,up}` (the final mixer has no injection). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct HeadAddrs { + pub norm: u64, + pub down: u64, + pub up: u64, +} +/// The PLE key projection of the Original's `PleWeights`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PleKey { + /// `key_bf16`: `[n_embd, hc_dim]` BF16 (IQ model files). + Bf16(u64), + /// `key_native_data` of ggml type `ty` (42, 18, 23 or 8) with the q8_1 scratch in the arena. + Native { ty: u32, data: u64 }, +} +/// The `PleWeights` / `ss.ple` state of the layer-1 PLE block. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PleAddrs { + pub key: PleKey, + pub value: u64, + pub norm_key: u64, + pub norm_query: u64, + pub norm_conv: u64, + pub conv1d: u64, + /// `ss.ple.scratch`: the `ple_block` workspace (first `PLE_SCRATCH_BYTES` are used). + pub scratch: u64, + /// `ss.ple.hist`: 9 rows x 10240 floats, row-fastest. + pub history: u64, +} + +/// `5 * hc_dim + n_embd + hc` floats of `ple_block`'s workspace; the Q8 / bf16 images behind it +/// are not used by the native path. +pub const PLE_SCRATCH_BYTES: usize = (5 * D + N + HC) * 4; +pub const PLE_HISTORY_BYTES: usize = 9 * D * 4; +pub const PLE_VALUE_BYTES: usize = N * N * 2; +pub const PLE_KEY_BF16_BYTES: usize = D * N * 2; +pub const PLE_NORM_BYTES: usize = D * 4; +pub const PLE_CONV_BYTES: usize = 4 * D * 2; +const SCRATCH_KEY: u64 = 0; +const SCRATCH_QUERY: u64 = (D * 4) as u64; +const SCRATCH_NORM: u64 = 2 * (D * 4) as u64; +const SCRATCH_GATED: u64 = 3 * (D * 4) as u64; +const SCRATCH_CONV: u64 = 4 * (D * 4) as u64; +const SCRATCH_VALUE: u64 = 5 * (D * 4) as u64; +const SCRATCH_GATE: u64 = SCRATCH_VALUE + (N * 4) as u64; + +// ------------------------------------------------------------------------------------------------ +// Shared helpers +// ------------------------------------------------------------------------------------------------ +fn check_geometry(geo: &OriginalVerifyGeometry) -> Result<()> { + if geo.n != N || geo.hc != HC || geo.lr != LR || !(1..=MAX_T).contains(&geo.max_t) { + return Err(Error::InvalidQwenShape); + } + Ok(()) +} +fn check_rows(geo: &OriginalVerifyGeometry, rows: Rows) -> Result<()> { + check_geometry(geo)?; + if rows.begin >= rows.end || rows.end > geo.max_t || rows.len() > MAX_T { + return Err(Error::InvalidQwenShape); + } + Ok(()) +} +fn row_span(arena: &dyn ArenaMap, name: &str, row: usize, row_bytes: usize) -> Result { + arena.span(name, row * row_bytes, row_bytes) +} +fn refuse(producer: &'static str) -> Error { + // The precise reasons are in the module docs; the error text is a `&'static str`. + match producer { + "head" => Error::InvalidDriverValue( + "Original verifier producer unavailable: head: only the native (gr_set_native_mmvf) head mix is sealed", + ), + "final_write" => Error::InvalidDriverValue( + "Original verifier producer unavailable: final_write: only the native gr_write (native_gr_post) is sealed", + ), + "ple_layer1" => Error::InvalidDriverValue( + "Original verifier producer unavailable: ple_layer1: only native PLE (native bf16 value + native post-ops) is sealed", + ), + _ => Error::UnsupportedQwenOperation, + } +} + +// ------------------------------------------------------------------------------------------------ +// hc_read: fused_gr_read_multi +// ------------------------------------------------------------------------------------------------ + +/// One window row's `FusedGrArgs` addresses. +#[derive(Clone, Copy)] +struct RowArgs { + r: u64, + bo_prev: u64, + inj_prev: u64, + lo: u64, + rs: u64, + inject_out: u64, + mixed: u64, +} + +/// `GrMulti` as the 114 words the wrapper kernels take by value. +fn multi_words(rows: &[RowArgs], w: &HcAddrs, apply: bool, xn: u64) -> Vec { + let mut words = vec![0u64; MULTI_WORDS]; + for (k, row) in rows.iter().enumerate() { + let a = &mut words[k * ARGS_WORDS..(k + 1) * ARGS_WORDS]; + a[0] = row.r; // R + a[1] = row.r; // R_out (in place) + a[2] = u64::from(apply); // bool apply (+ padding) + a[3] = row.bo_prev; + a[4] = row.inj_prev; + a[5] = w.norm; + a[6] = w.down; + a[7] = w.up; + a[8] = w.inject; + a[9] = u64::from(EPS.to_bits()); // float eps (+ padding) + a[10] = row.lo; + a[11] = row.rs; + a[12] = row.inject_out; + a[13] = row.mixed; + } + words[XN_WORD] = xn; + words[T_WORD] = rows.len() as u64; + words +} + +/// The down projection's launch for tokens `[c0, c0 + ct)` of the call: the whole `GrMulti` when it +/// is one chunk, else `GrMulti c{}` with `xn + c0 * D`, `T = ct` and `a[k] = m.a[c0 + k]`. +fn chunk_words(full: &[u64], n: usize, c0: usize, ct: usize) -> Vec { + if ct == n { + return full.to_vec(); + } + let mut words = vec![0u64; MULTI_WORDS]; + words[..ct * ARGS_WORDS].copy_from_slice(&full[c0 * ARGS_WORDS..(c0 + ct) * ARGS_WORDS]); + words[XN_WORD] = full[XN_WORD] + (c0 * D * 4) as u64; + words[T_WORD] = ct as u64; + words +} + +/// The kernels of one `fused_gr_read_multi` call in their order (`launch_multi`). The profile stamps +/// the Original puts after the norm and after the down launches (group 0 only, profile mode) are +/// the caller's: `norm`, then `down`, then `up`. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct HcReadPlan { + pub norm: Launch, + pub down: Vec, + pub up: Launch, +} +impl HcReadPlan { + pub(crate) fn launches(self) -> Vec { + let mut out = Vec::with_capacity(self.down.len() + 2); + out.push(self.norm); + out.extend(self.down); + out.push(self.up); + out + } +} + +/// `gr_read_group(half, apply, inj_prev, inj_out)` of `pre(l, group)` for the window rows +/// `[tb, te)`: `fused_gr_read_multi(fa, n, xn_ + tb * HC * N, ...)`. +/// +/// Per row `t`: `R = R_out = R_ + t*HC*N` (in place), `bo_prev = bo_ + t*N`, `lo = lo_ + t*hc_lr`, +/// `rs = rs_ + t*HC`, `mixed = mixed_ + t*N`; the attention half reads `inj2_` and writes `inj_`, the +/// FFN half the reverse. +pub(crate) fn plan_hc_read( + arena: &dyn ArenaMap, + geo: &OriginalVerifyGeometry, + w: &HcAddrs, + cfg: &GrConfig, + half: HcHalf, + apply: bool, + rows: Rows, +) -> Result { + check_rows(geo, rows)?; + let (inj_prev_name, inj_out_name) = match half { + HcHalf::Attention => ("inj2", "inj"), + HcHalf::Ffn => ("inj", "inj2"), + }; + let n = rows.len(); + let mut per_row = Vec::with_capacity(n); + for t in rows.begin..rows.end { + per_row.push(RowArgs { + r: row_span(arena, "R", t, D * 4)?, + bo_prev: row_span(arena, "bo", t, N * 4)?, + inj_prev: row_span(arena, inj_prev_name, t, HC * 4)?, + lo: row_span(arena, "lo", t, LR * 4)?, + rs: row_span(arena, "rs", t, HC * 4)?, + inject_out: row_span(arena, inj_out_name, t, HC * 4)?, + mixed: row_span(arena, "mixed", t, N * 4)?, + }); + } + let xn = arena.span("xn", rows.begin * D * 4, n * D * 4)?; + let full = multi_words(&per_row, w, apply, xn); + + // norm: variant >= split is [n, 4] blocks, the plain read [n] blocks + let norm = if cfg.variant == GrVariant::Plain { + Launch::new(&GR_FUSED, E_NORM, [n as u32, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full.clone())])? + } else { + Launch::new(&GR_FUSED, E_SPLIT, [n as u32, HC as u32, 1], [THREADS, 1, 1], 0, vec![A::Words(full.clone())])? + }; + + // down: launches of as many tokens as the shared memory allows + let staged = cfg.variant == GrVariant::Staged; + let per_token = if staged { 2 * STAGED_TILE * 4 } else { cfg.tile * 4 }; + let chunk_tok = if staged { cfg.chunk_staged } else { cfg.chunk_plain }; + if chunk_tok == 0 { + return Err(Error::InvalidQwenShape); + } + let mut down = Vec::new(); + let mut c0 = 0; + while c0 < n { + let ct = (n - c0).min(chunk_tok); + let shared = ct as u32 * per_token; + if shared > cfg.usable_shared { + // the card cannot launch it (Original would fail the launch) + return Err(Error::InvalidProjectionShape); + } + down.push(Launch::new( + &GR_FUSED, + cfg.down_entry(), + [DOWN_BLOCKS, 1, 1], + [THREADS, 1, 1], + shared, + vec![A::Words(chunk_words(&full, n, c0, ct))], + )?); + c0 += ct; + } + + let up = Launch::new(&GR_FUSED, E_UP, [UP_BLOCKS, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full)])?; + Ok(HcReadPlan { norm, down, up }) +} + +// ------------------------------------------------------------------------------------------------ +// gr_write: the last layer's final residual write, and the PLE pending write +// ------------------------------------------------------------------------------------------------ + +/// `gr_write(Rt(t), bo_ + t*N, inj2_ + t*HC, gs, Rt(t), cs)` for one window row: `native_gr_post`. +fn write_row(arena: &dyn ArenaMap, cfg: &GrConfig, row: usize, producer: &'static str) -> Result { + if !cfg.native_mmvf { + return Err(refuse(producer)); + } + let r = row_span(arena, "R", row, D * 4)?; + let bo = row_span(arena, "bo", row, N * 4)?; + let inject = row_span(arena, "inj2", row, HC * 4)?; + Launch::new( + &GR_POST, + "mtp_full_native_write", + [(D as u32).div_ceil(THREADS), 1, 1], + [THREADS, 1, 1], + 0, + vec![A::P(r), A::P(bo), A::P(inject), A::P(r), A::I32(N as i32), A::I32(HC as i32), A::F32(QUARTER)], + ) +} + +/// `for t in [tb, te): gr_write(Rt(t), bo_+t*N, inj2_+t*HC, gs, Rt(t), cs)` of the last layer. +pub(crate) fn plan_final_write( + arena: &dyn ArenaMap, + geo: &OriginalVerifyGeometry, + cfg: &GrConfig, + rows: Rows, +) -> Result> { + check_rows(geo, rows)?; + (rows.begin..rows.end).map(|t| write_row(arena, cfg, t, "final_write")).collect() +} + +// ------------------------------------------------------------------------------------------------ +// head: lm_head_mix per token +// ------------------------------------------------------------------------------------------------ + +/// The per-token `lm_head_mix(wt, g, bb, cs, err)` of the head section: the native +/// `gr_read(R, output_hc_norm, output_hc_down, output_hc_up, nullptr, ...)` writing the mixed row +/// `t` at `mixed_out_base + t*N*4` (the head rows' `mixed`, which the `head_->loaded()` path +/// quantizes and projects next). +/// +/// Per row, in order: `native_gr_rms_norm_weighted(R_t -> xn)`, `bf16_gemv_fp32_mmvf(xn, down -> lo)`, +/// `native_gr_down_silu(lo)`, `bf16_gemv_fp32_mmvf(lo, up -> gated)`, `native_gr_pre_gated(xn, +/// gated -> mixed)` (no injection: the final mixer). The Original's per-session `bb.gr` workspace +/// (xn, gated, lo) is carved from arena spans that are dead after the layers: `xn` slot `t`, `lo` +/// slot `t` and the first `HC*N` floats of `parts` slot `t`. +pub(crate) fn plan_head_mix( + arena: &dyn ArenaMap, + geo: &OriginalVerifyGeometry, + w: &HeadAddrs, + cfg: &GrConfig, + mixed_out_base: u64, + rows: usize, +) -> Result> { + check_geometry(geo)?; + if !(1..=geo.max_t).contains(&rows) { + return Err(Error::InvalidQwenShape); + } + if !cfg.native_mmvf { + return Err(refuse("head")); + } + let mut out = Vec::with_capacity(rows * 5); + for t in 0..rows { + let r = row_span(arena, "R", t, D * 4)?; + let xn = row_span(arena, "xn", t, D * 4)?; + let lo = row_span(arena, "lo", t, LR * 4)?; + let gated = arena.span("parts", t * geo.k * N * 4, D * 4)?; + let mixed = mixed_out_base + (t * N * 4) as u64; + // native_gr_rms_norm_weighted(R, w_norm, xn, n_embd, hc, eps): n_cols >= 1024 -> <1024>, hc blocks + out.push(Launch::new( + &GR_NORM, + "mtp_full_gr_norm", + [HC as u32, 1, 1], + [1024, 1, 1], + 0, + vec![A::P(r), A::P(w.norm), A::P(xn), A::I32(N as i32), A::F32(EPS)], + )?); + out.push(plan_bf16_gemv(xn, D, w.down, lo, LR, D, LR, 1)?); + out.push(Launch::new( + &GR_POST, + "mtp_full_down_silu", + [(LR as u32).div_ceil(THREADS), 1, 1], + [THREADS, 1, 1], + 0, + vec![A::P(lo), A::I32(LR as i32), A::F32(QUARTER)], + )?); + out.push(plan_bf16_gemv(lo, LR, w.up, gated, D, LR, D, 1)?); + out.push(Launch::new( + &GR_POST, + "mtp_full_pre_final", + [(N as u32).div_ceil(THREADS), 1, 1], + [THREADS, 1, 1], + 0, + vec![A::P(xn), A::P(gated), A::P(mixed), A::I32(N as i32), A::I32(HC as i32), A::F32(QUARTER)], + )?); + } + Ok(out) +} + +// ------------------------------------------------------------------------------------------------ +// ple_layer1 +// ------------------------------------------------------------------------------------------------ + +/// One window row of the layer-1 PLE block (`for t in [tb, te)` of `pre(1, group)`), WITHOUT the +/// trailing `copy_from_mapped(hist_snap_ + t*HS, ss.ple.hist, HS)`: the caller records that with +/// `OriginalVerifyGdnJournal::capture_ple_snapshot(t)` after submitting this row, so each row's +/// snapshot sees that row's history. +/// +/// Order: `gr_write(Rt, bo, inj2 -> Rt)` (the pending layer-0 write), then `ple_block(ple_+t*N, Rt, +/// hist, w, po{normalized, result=Rt})`: key projection (BF16 MMVF, or q8_1 + MMVQ for a native +/// Q2_0 / IQ3_XXS / IQ4_XS / Q8_0 key), value projection (BF16 MMVF), `native_ple_postops` +/// (rms of the key, rms of the hidden, gate, broadcast, rms of the gated, conv + residual into +/// `Rt`), then `ple_history_advance(hist, normalized)`. +/// +/// The Original copies `normalized` out of the workspace (a device-to-device memcpy node) and then +/// shifts the history with `history_advance_kernel`; here `ple_history(T = 1)` reads `normalized` +/// from the workspace and performs the identical shift-and-append (pure data movement, same +/// 40x256 launch), so the memcpy node is not recorded. `native_ple_postops_batch`'s kernels at +/// `T = 1` have the single-token kernels' launch geometry and per-element arithmetic. +pub(crate) fn plan_ple_row( + arena: &dyn ArenaMap, + geo: &OriginalVerifyGeometry, + cfg: &GrConfig, + ple: &PleConfig, + a: &PleAddrs, + row: usize, +) -> Result> { + check_geometry(geo)?; + if row >= geo.max_t { + return Err(Error::InvalidQwenShape); + } + if !(ple.native_value_bf16 && ple.native_postops) { + return Err(refuse("ple_layer1")); + } + let mut out = Vec::with_capacity(14); + out.push(write_row(arena, cfg, row, "ple_layer1")?); + + let r = row_span(arena, "R", row, D * 4)?; + let emb = row_span(arena, "ple", row, N * 4)?; + let key = a.scratch + SCRATCH_KEY; + let query = a.scratch + SCRATCH_QUERY; + let norm = a.scratch + SCRATCH_NORM; + let gated = a.scratch + SCRATCH_GATED; + let conv = a.scratch + SCRATCH_CONV; + let value = a.scratch + SCRATCH_VALUE; + let gate = a.scratch + SCRATCH_GATE; + + // key = ple_key @ emb + match a.key { + PleKey::Bf16(w) => out.push(plan_bf16_gemv(emb, N, w, key, D, N, D, 1)?), + PleKey::Native { ty, data } => { + if !matches!(ty, 42 | 18 | 23 | 8) { + return Err(Error::UnsupportedQwenOperation); + } + let q8 = arena.span("xq", 0, q8_1_row_bytes(N))?; + out.push(plan_quantize_q8_1(emb, q8, N, 1)?); + out.push(plan_mmvq(&NativeWeight { ty, data }, q8, key, N, D, 1, ple.dispatch)?); + } + } + // value = ple_value @ emb + out.push(plan_bf16_gemv(emb, N, a.value, value, N, N, N, 1)?); + + // native_ple_postops(d_key, hidden, d_value, hist, w, {key=d_query, query=d_norm, gate=d_gate, + // gated=d_gated, normalized=d_norm, conv=d_conv, result=hidden}) + let rms = |input: u64, gamma: u64, output: u64| { + Launch::new(&PLE_BATCH, "ple_rms", [HC as u32, 1, 1], [1024, 1, 1], 0, vec![A::P(input), A::P(gamma), A::P(output)]) + }; + out.push(rms(key, a.norm_key, query)?); + out.push(rms(r, a.norm_query, norm)?); + out.push(Launch::new( + &PLE_BATCH, + "ple_gate", + [HC as u32, 1, 1], + [512, 1, 1], + 0, + vec![A::P(query), A::P(norm), A::P(gate), A::F32(1.0f32 / (N as f32).sqrt())], + )?); + let blocks = (D as u32) / THREADS; + out.push(Launch::new( + &PLE_BATCH, + "ple_broadcast", + [blocks, 1, 1], + [THREADS, 1, 1], + 0, + vec![A::P(value), A::P(gate), A::P(gated), A::I32(1)], + )?); + out.push(rms(gated, a.norm_conv, norm)?); + out.push(Launch::new( + &PLE_BATCH, + "ple_conv", + [blocks, 1, 1], + [THREADS, 1, 1], + 0, + vec![A::P(a.history), A::P(norm), A::P(a.conv1d), A::P(r), A::P(gated), A::P(conv), A::I32(1)], + )?); + // ple_history_advance(hist, normalized) + out.push(Launch::new( + &PLE_BATCH, + "ple_history", + [blocks, 1, 1], + [THREADS, 1, 1], + 0, + vec![A::P(a.history), A::P(norm), A::I32(1)], + )?); + Ok(out) +} + +/// `pre(1, group)`'s PLE loop for the rows `[tb, te)`: one `(row, launches)` entry per row, to be +/// submitted in order, each followed by `capture_ple_snapshot(row)`. +pub(crate) fn plan_ple_layer1( + arena: &dyn ArenaMap, + geo: &OriginalVerifyGeometry, + cfg: &GrConfig, + ple: &PleConfig, + a: &PleAddrs, + rows: Rows, +) -> Result)>> { + check_rows(geo, rows)?; + (rows.begin..rows.end).map(|t| Ok((t, plan_ple_row(arena, geo, cfg, ple, a, t)?))).collect() +} + +// ------------------------------------------------------------------------------------------------ +// Binding: the weights the runtime hands over +// ------------------------------------------------------------------------------------------------ + +/// The four buffers of one hc half: `norm` F32 `[hc*N]`, `down` BF16 `[hc_lr][hc*N]`, `up` BF16 +/// `[hc*N][hc_lr]`, `inject` BF16 `[hc][hc*N]`. +pub struct HcHalfBuffers<'a, 'ctx> { + pub norm: &'a DeviceBuffer<'ctx>, + pub down: &'a DeviceBuffer<'ctx>, + pub up: &'a DeviceBuffer<'ctx>, + pub inject: &'a DeviceBuffer<'ctx>, +} +pub struct HcLayerBuffers<'a, 'ctx> { + pub attention: HcHalfBuffers<'a, 'ctx>, + pub ffn: HcHalfBuffers<'a, 'ctx>, +} +/// `output_hc_norm.weight` / `output_hc_down.weight` / `output_hc_up.weight` (no injection). +pub struct HcOutputBuffers<'a, 'ctx> { + pub norm: &'a DeviceBuffer<'ctx>, + pub down: &'a DeviceBuffer<'ctx>, + pub up: &'a DeviceBuffer<'ctx>, +} +pub enum PleKeyBuffer<'a, 'ctx> { + /// BF16 `[hc_dim][n_embd]` (`PLE_KEY_BF16_BYTES`). + Bf16(&'a DeviceBuffer<'ctx>), + /// A native GGUF key of ggml type `ty` (42, 18, 23, 8): `hc_dim` rows of `n_embd`. + Native { ty: u32, data: &'a DeviceBuffer<'ctx> }, +} +/// The PLE weights and state of the layer-1 block. `history` must be the SAME buffer the verify +/// journal snapshots (`ss.ple.hist`). +pub struct PleBuffers<'a, 'ctx> { + pub key: PleKeyBuffer<'a, 'ctx>, + pub value: &'a DeviceBuffer<'ctx>, + pub norm_key: &'a DeviceBuffer<'ctx>, + pub norm_query: &'a DeviceBuffer<'ctx>, + pub norm_conv: &'a DeviceBuffer<'ctx>, + pub conv1d: &'a DeviceBuffer<'ctx>, + /// At least `PLE_SCRATCH_BYTES` (`ss.ple.scratch`). + pub scratch: &'a DeviceBuffer<'ctx>, + pub history: &'a DeviceBuffer<'ctx>, +} + +/// The weights of the GR family for the 48 layers, the final mixer and (optionally) the PLE block, +/// validated for context and exact byte sizes. +pub struct OriginalVerifyGrBinding<'a, 'ctx> { + context: &'ctx Context<'ctx>, + layers: Vec>, + output: HcOutputBuffers<'a, 'ctx>, + ple: Option>, +} +impl<'a, 'ctx> OriginalVerifyGrBinding<'a, 'ctx> { + pub fn new( + context: &'ctx Context<'ctx>, + layers: Vec>, + output: HcOutputBuffers<'a, 'ctx>, + ple: Option>, + ) -> Result { + if layers.len() != LAYERS { + return Err(Error::InvalidQwenShape); + } + let binding = Self { context, layers, output, ple }; + // fail early: every address is validated once here and again when it is used + for layer in 0..LAYERS { + binding.half_addrs(layer, HcHalf::Attention)?; + binding.half_addrs(layer, HcHalf::Ffn)?; + } + binding.head_addrs()?; + if binding.ple.is_some() { + binding.ple_addrs()?; + } + Ok(binding) + } + fn half(&self, layer: usize, half: HcHalf) -> Result<&HcHalfBuffers<'a, 'ctx>> { + let l = self.layers.get(layer).ok_or(Error::InvalidQwenShape)?; + Ok(match half { + HcHalf::Attention => &l.attention, + HcHalf::Ffn => &l.ffn, + }) + } + /// `hc_attn_*` / `hc_ffn_*` of `layer`. + pub(crate) fn half_addrs(&self, layer: usize, half: HcHalf) -> Result { + let h = self.half(layer, half)?; + let c = self.context; + Ok(HcAddrs { + norm: admit(c, h.norm, HC_NORM_BYTES)?, + down: admit(c, h.down, HC_DOWN_BYTES)?, + up: admit(c, h.up, HC_UP_BYTES)?, + inject: admit(c, h.inject, HC_INJECT_BYTES)?, + }) + } + pub(crate) fn head_addrs(&self) -> Result { + let c = self.context; + Ok(HeadAddrs { + norm: admit(c, self.output.norm, HC_NORM_BYTES)?, + down: admit(c, self.output.down, HC_DOWN_BYTES)?, + up: admit(c, self.output.up, HC_UP_BYTES)?, + }) + } + pub fn has_ple(&self) -> bool { + self.ple.is_some() + } + pub(crate) fn ple_addrs(&self) -> Result { + let p = self.ple.as_ref().ok_or(Error::InvalidQwenShape)?; + let c = self.context; + let key = match &p.key { + PleKeyBuffer::Bf16(b) => PleKey::Bf16(admit(c, b, PLE_KEY_BF16_BYTES)?), + PleKeyBuffer::Native { ty, data } => { + if !matches!(ty, 42 | 18 | 23 | 8) { + return Err(Error::UnsupportedQwenOperation); + } + let bytes = native_head_row_bytes(*ty, N)?.checked_mul(D).ok_or(Error::InvalidSize)?; + PleKey::Native { ty: *ty, data: admit(c, data, bytes)? } + } + }; + let scratch = p.scratch; + if !std::ptr::eq(c, scratch.context) { + return Err(Error::ContextMismatch); + } + if scratch.len() < PLE_SCRATCH_BYTES { + return Err(Error::ShapeMismatch { expected: PLE_SCRATCH_BYTES, actual: scratch.len() }); + } + let scratch_handle = handle(scratch)?; + scratch_handle.validate_projection_extent(PLE_SCRATCH_BYTES, 4)?; + Ok(PleAddrs { + key, + value: admit(c, p.value, PLE_VALUE_BYTES)?, + norm_key: admit(c, p.norm_key, PLE_NORM_BYTES)?, + norm_query: admit(c, p.norm_query, PLE_NORM_BYTES)?, + norm_conv: admit(c, p.norm_conv, PLE_NORM_BYTES)?, + conv1d: admit(c, p.conv1d, PLE_CONV_BYTES)?, + scratch: scratch_handle.qwen_address(), + history: admit(c, p.history, PLE_HISTORY_BYTES)?, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use super::super::kernels::{LayoutMap, test_geometry}; + + const BASE: u64 = 0x7000_0000_0000; + + fn arena() -> LayoutMap { + LayoutMap::new(BASE, test_geometry()) + } + fn at(m: &LayoutMap, name: &str, offset: usize) -> u64 { + BASE + (m.layout.span(name).unwrap().offset + offset) as u64 + } + fn weights() -> HcAddrs { + HcAddrs { norm: 0x1000_0000, down: 0x2000_0000, up: 0x3000_0000, inject: 0x4000_0000 } + } + fn words(l: &Launch) -> &[u64] { + match &l.args[..] { + [A::Words(w)] => w, + other => panic!("expected one by-value struct, got {other:?}"), + } + } + fn rows(begin: usize, end: usize, group: usize) -> Rows { + Rows { begin, end, group } + } + /// RTX-class sm_120: 99 KiB opt-in, 48 KiB default per block. + fn sm120(variant: GrVariant) -> GrConfig { + GrConfig::from_device(variant, true, 12, 0, 101_376, 49_152) + } + fn entry_declared(ptx: &str, e: &str) -> bool { + ptx.contains(&format!(".entry {e}(")) || ptx.contains(&format!(".visible .entry {e}(")) + } + + // ---------------------------------------------------------------------------------- assets + #[test] + fn assets_are_pinned_and_export_every_named_entry() { + for spec in assets() { + spec.sealed().unwrap_or_else(|e| panic!("{}: {e:?}", spec.name)); + let text = String::from_utf8_lossy(spec.ptx); + for e in spec.entries { + assert!(entry_declared(&text, e), "{} lacks {e}", spec.name); + } + } + // the six fused-gr wrappers take ONE 912-byte by-value struct (the Original GrMulti) + let text = String::from_utf8_lossy(GR_FUSED.ptx); + for e in GR_FUSED.entries { + assert!(text.contains(&format!("{e}_param_0[912]")), "{e} is not a GrMulti-by-value entry"); + } + } + + #[test] + fn struct_layout_constants_match_fused_gr_args() { + // FusedGrArgs: R,R_out,bool(+pad),bo,inj,wn,wd,wu,wi,float(+pad),lo,rs,inject,mixed = 112 bytes + assert_eq!(ARGS_WORDS * 8, 112); + // GrMulti: 8 * 112 + xn pointer + int T (+pad) = 912 bytes + assert_eq!(MULTI_WORDS * 8, 912); + assert_eq!((XN_WORD, T_WORD), (112, 113)); + assert_eq!(1e-6f32.to_bits(), 0x358637BD); + } + + // ----------------------------------------------------------------- down_chunk replication + #[test] + fn down_chunk_on_big_cards_runs_the_2560_tile_with_all_eight_tokens() { + let c = sm120(GrVariant::Staged); + assert_eq!(c.tile, 2560); + // 8 * 2560 * 4 = 81920 <= 101376 -> attribute is the full want + assert_eq!(c.attr_down, Some(81_920)); + // staged: 2 * 8 * 1280 * 4 = 81920 + assert_eq!(c.attr_staged, Some(81_920)); + // capacity 101376 / 10240 = 9 -> clamped to 8, both kinds + assert_eq!((c.chunk_plain, c.chunk_staged), (8, 8)); + assert_eq!(c.usable_shared, 101_376); + } + + #[test] + fn down_chunk_on_turing_slices_staged_tokens_and_uses_the_1280_tile() { + // sm_75: 64 KiB opt-in + let c = GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152); + assert_eq!(c.tile, 1280); + assert_eq!(c.attr_down, Some(8 * 1280 * 4)); // 40960 fits + assert_eq!(c.attr_staged, Some(65_536)); // 81920 > opt-in -> opt-in + assert_eq!(c.chunk_plain, 8); // 65536 / 5120 = 12 -> 8 + assert_eq!(c.chunk_staged, 6); // 65536 / 10240 = 6 ("sm_75 carries 6 tokens") + } + + #[test] + fn down_chunk_below_volta_uses_the_per_block_limit_and_never_less_than_one_token() { + // sm_61 reports no usable opt-in: per-block limit 48 KiB + let c = GrConfig::from_device(GrVariant::Plain, true, 6, 1, 0, 49_152); + assert_eq!(c.tile, 2560); + assert_eq!((c.chunk_plain, c.chunk_staged), (4, 4)); // 49152 / 10240 + assert_eq!((c.attr_down, c.attr_staged), (None, None)); + // sm_60 answers a 64 KiB opt-in it does not keep: the limit is still per block + let c60 = GrConfig::from_device(GrVariant::Plain, true, 6, 0, 65_536, 49_152); + assert_eq!(c60.usable_shared, 49_152); + assert_eq!(c60.chunk_plain, 4); + // a card that cannot hold one token still reports a chunk of 1 (the launch is then refused) + let tiny = GrConfig::from_device(GrVariant::Plain, true, 6, 1, 0, 4096); + assert_eq!((tiny.chunk_plain, tiny.chunk_staged), (1, 1)); + let m = arena(); + assert_eq!( + plan_hc_read(&m, &test_geometry(), &weights(), &tiny, HcHalf::Attention, false, rows(0, 2, 0)).unwrap_err(), + Error::InvalidProjectionShape + ); + } + + #[test] + fn shared_attributes_name_the_tile_kernel_of_the_card_and_the_staged_kernel() { + let big = shared_attributes(&sm120(GrVariant::Staged)); + assert_eq!(big.len(), 2); + assert_eq!((big[0].1, big[0].2), (E_DOWN2560, 81_920)); + assert_eq!((big[1].1, big[1].2), (E_STAGED, 81_920)); + assert!(big.iter().all(|a| std::ptr::eq(a.0, &GR_FUSED))); + let turing = shared_attributes(&GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152)); + assert_eq!((turing[0].1, turing[0].2), (E_DOWN1280, 40_960)); + assert_eq!((turing[1].1, turing[1].2), (E_STAGED, 65_536)); + } + + #[test] + fn variant_follows_strata_hc_split() { + assert_eq!(GrVariant::from_env_value(None), GrVariant::Staged); + assert_eq!(GrVariant::from_env_value(Some("")), GrVariant::Staged); + assert_eq!(GrVariant::from_env_value(Some("0")), GrVariant::Plain); + assert_eq!(GrVariant::from_env_value(Some("1")), GrVariant::Split); + assert_eq!(GrVariant::from_env_value(Some("2")), GrVariant::Staged); + } + + // ------------------------------------------------------------------------------- hc_read + #[test] + fn staged_read_of_eight_rows_is_three_launch_kinds_with_the_multi_struct() { + let m = arena(); + let g = test_geometry(); + let w = weights(); + let plan = plan_hc_read(&m, &g, &w, &sm120(GrVariant::Staged), HcHalf::Attention, true, rows(0, 8, 0)).unwrap(); + // norm: split, one block per token and stream + assert_eq!((plan.norm.entry, plan.norm.grid, plan.norm.block, plan.norm.shared), (E_SPLIT, [8, 4, 1], [256, 1, 1], 0)); + // down: ONE launch, 41 blocks, dynamic shared = 8 tokens * 2 * 1280 * 4 + assert_eq!(plan.down.len(), 1); + let d = &plan.down[0]; + assert_eq!((d.entry, d.grid, d.block, d.shared), (E_STAGED, [41, 1, 1], [256, 1, 1], 81_920)); + // up: 160 blocks of 16 columns + assert_eq!((plan.up.entry, plan.up.grid, plan.up.block, plan.up.shared), (E_UP, [160, 1, 1], [256, 1, 1], 0)); + let full = words(&plan.norm).to_vec(); + assert_eq!(words(&plan.up), &full[..]); + assert_eq!(words(d), &full[..]); + assert_eq!(full.len(), 114); + // trailer: xn = xn_ + tb*HC*N*4, T = 8 + assert_eq!(full[112], at(&m, "xn", 0)); + assert_eq!(full[113], 8); + // token 3, attention half, apply + let a = &full[3 * 14..4 * 14]; + assert_eq!(a[0], at(&m, "R", 3 * 40_960)); + assert_eq!(a[1], a[0]); + assert_eq!(a[2], 1); + assert_eq!(a[3], at(&m, "bo", 3 * 10_240)); + assert_eq!(a[4], at(&m, "inj2", 3 * 16)); + assert_eq!(&a[5..9], &[w.norm, w.down, w.up, w.inject]); + assert_eq!(a[9], 0x358637BD); + assert_eq!(a[10], at(&m, "lo", 3 * 1280)); + assert_eq!(a[11], at(&m, "rs", 3 * 16)); + assert_eq!(a[12], at(&m, "inj", 3 * 16)); + assert_eq!(a[13], at(&m, "mixed", 3 * 10_240)); + // every distinct row has its own addresses + assert_ne!(full[0], full[14]); + } + + #[test] + fn ffn_half_swaps_the_injection_buffers_and_apply_is_carried() { + let m = arena(); + let g = test_geometry(); + let plan = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Staged), HcHalf::Ffn, false, rows(0, 1, 0)).unwrap(); + let a = &words(&plan.norm)[..14]; + assert_eq!(a[2], 0); + assert_eq!(a[4], at(&m, "inj", 0)); + assert_eq!(a[12], at(&m, "inj2", 0)); + // a single row: norm grid [1, 4] + assert_eq!(plan.norm.grid, [1, 4, 1]); + assert_eq!(words(&plan.norm)[113], 1); + assert_eq!(plan.down[0].shared, 10_240); + } + + #[test] + fn split_windows_read_their_own_rows_and_offset_the_scratch() { + let m = arena(); + let g = test_geometry(); + // T = 7 -> groups [0,4) and [4,7): (T+1)/2 = 4 + let g1 = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Staged), HcHalf::Ffn, true, rows(4, 7, 1)).unwrap(); + let w1 = words(&g1.norm); + assert_eq!(w1[112], at(&m, "xn", 4 * 40_960)); + assert_eq!(w1[113], 3); + assert_eq!(w1[0], at(&m, "R", 4 * 40_960)); + assert_eq!(w1[14 + 10], at(&m, "lo", 5 * 1280)); + assert_eq!(g1.norm.grid, [3, 4, 1]); + assert_eq!(g1.down[0].shared, 3 * 10_240); + // unused slots stay zero + assert!(w1[3 * 14..112].iter().all(|&x| x == 0)); + } + + #[test] + fn plain_and_split_variants_pick_the_norm_and_the_tile_kernel() { + let m = arena(); + let g = test_geometry(); + let plain = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Plain), HcHalf::Attention, false, rows(0, 5, 0)).unwrap(); + assert_eq!((plain.norm.entry, plain.norm.grid), (E_NORM, [5, 1, 1])); + assert_eq!((plain.down[0].entry, plain.down[0].shared), (E_DOWN2560, 5 * 2560 * 4)); + let split = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Split), HcHalf::Attention, false, rows(0, 5, 0)).unwrap(); + assert_eq!((split.norm.entry, split.norm.grid), (E_SPLIT, [5, 4, 1])); + assert_eq!(split.down[0].entry, E_DOWN2560); + let turing = GrConfig::from_device(GrVariant::Plain, true, 7, 5, 65_536, 49_152); + let t = plan_hc_read(&m, &g, &weights(), &turing, HcHalf::Attention, false, rows(0, 8, 0)).unwrap(); + assert_eq!((t.down[0].entry, t.down[0].shared), (E_DOWN1280, 8 * 1280 * 4)); + } + + #[test] + fn down_projection_is_chunked_by_the_card_capacity() { + let m = arena(); + let g = test_geometry(); + let turing = GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152); + let plan = plan_hc_read(&m, &g, &weights(), &turing, HcHalf::Attention, true, rows(0, 8, 0)).unwrap(); + // 8 tokens, 6 per launch -> 6 + 2 + assert_eq!(plan.down.len(), 2); + assert_eq!((plan.down[0].shared, plan.down[1].shared), (61_440, 20_480)); + let full = words(&plan.norm).to_vec(); + let first = words(&plan.down[0]); + let second = words(&plan.down[1]); + // the first chunk is a FRESH struct: tokens 0..6, T = 6, same xn + assert_eq!(first[113], 6); + assert_eq!(first[112], full[112]); + assert_eq!(&first[..6 * 14], &full[..6 * 14]); + assert!(first[6 * 14..112].iter().all(|&x| x == 0)); + // the second: tokens 6..8 moved to slots 0..2, xn advanced by 6 * D floats, T = 2 + assert_eq!(second[113], 2); + assert_eq!(second[112], full[112] + 6 * 40_960); + assert_eq!(&second[..2 * 14], &full[6 * 14..8 * 14]); + assert!(second[2 * 14..112].iter().all(|&x| x == 0)); + // norm and up still see all eight tokens + assert_eq!(words(&plan.up), &full[..]); + assert_eq!(plan.norm.grid, [8, 4, 1]); + assert_eq!(plan.clone().launches().len(), 4); + // launches() keeps the Original order: norm, down..., up + let order: Vec<&str> = plan.launches().iter().map(|l| l.entry).collect(); + assert_eq!(order, [E_SPLIT, E_STAGED, E_STAGED, E_UP]); + } + + #[test] + fn hc_read_validates_rows_and_geometry() { + let m = arena(); + let g = test_geometry(); + let c = sm120(GrVariant::Staged); + let w = weights(); + assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(3, 3, 0)).is_err()); + assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(0, 9, 0)).is_err()); + assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(7, 9, 1)).is_err()); + let mut odd = g; + odd.hc = 8; + assert_eq!( + plan_hc_read(&m, &odd, &w, &c, HcHalf::Attention, false, rows(0, 1, 0)).unwrap_err(), + Error::InvalidQwenShape + ); + // every T = 1..=8 and both groups of the split window plan + for t in 1..=8usize { + let first = (t + 1) / 2; + let groups = if t >= 2 { vec![(0, first), (first, t)] } else { vec![(0, t)] }; + for (gi, (b, e)) in groups.into_iter().enumerate() { + let plan = plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, true, rows(b, e, gi)).unwrap(); + assert_eq!(words(&plan.up)[113], (e - b) as u64); + assert_eq!(plan.norm.grid[0], (e - b) as u32); + } + } + } + + // ----------------------------------------------------------------------------- final write + #[test] + fn final_write_is_native_post_in_place_per_row() { + let m = arena(); + let g = test_geometry(); + let l = plan_final_write(&m, &g, &sm120(GrVariant::Staged), rows(2, 5, 0)).unwrap(); + assert_eq!(l.len(), 3); + for (i, launch) in l.iter().enumerate() { + let t = 2 + i; + assert!(std::ptr::eq(launch.asset, &GR_POST)); + assert_eq!((launch.entry, launch.grid, launch.block, launch.shared), ("mtp_full_native_write", [40, 1, 1], [256, 1, 1], 0)); + assert_eq!( + launch.args, + vec![ + A::P(at(&m, "R", t * 40_960)), + A::P(at(&m, "bo", t * 10_240)), + A::P(at(&m, "inj2", t * 16)), + A::P(at(&m, "R", t * 40_960)), + A::I32(2560), + A::I32(4), + A::F32(0.25), + ] + ); + } + let mut non_native = sm120(GrVariant::Staged); + non_native.native_mmvf = false; + assert!(matches!( + plan_final_write(&m, &g, &non_native, rows(0, 1, 0)), + Err(Error::InvalidDriverValue(s)) if s.contains("final_write") + )); + } + + // ------------------------------------------------------------------------------------ head + #[test] + fn head_mix_is_the_native_unfused_gr_read_per_token() { + let m = arena(); + let g = test_geometry(); + let w = HeadAddrs { norm: 0xA000, down: 0xB000, up: 0xC000 }; + let mixed_base = 0x9999_0000u64; + let l = plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 3).unwrap(); + assert_eq!(l.len(), 15); + for t in 0..3usize { + let k = &l[t * 5..t * 5 + 5]; + let r = at(&m, "R", t * 40_960); + let xn = at(&m, "xn", t * 40_960); + let lo = at(&m, "lo", t * 1280); + let gated = at(&m, "parts", t * 10 * 2560 * 4); + let mixed = mixed_base + (t * 10_240) as u64; + // 1. native_gr_rms_norm_weighted: hc blocks of 1024 threads + assert_eq!((k[0].entry, k[0].grid, k[0].block), ("mtp_full_gr_norm", [4, 1, 1], [1024, 1, 1])); + assert_eq!(k[0].args, vec![A::P(r), A::P(0xA000), A::P(xn), A::I32(2560), A::F32(1e-6)]); + // 2. bf16_gemv_fp32_mmvf(xn, down -> lo, 10240 -> 320): mmvf block 256 + assert_eq!((k[1].entry, k[1].grid, k[1].block), ("mtp_full_mmvf256", [320, 1, 1], [256, 1, 1])); + assert_eq!(k[1].args, vec![A::P(xn), A::P(0xB000), A::P(lo), A::I32(10_240)]); + // 3. native_gr_down_silu(lo, 320, 1/4): ceil(320/256) = 2 blocks + assert_eq!((k[2].entry, k[2].grid, k[2].block), ("mtp_full_down_silu", [2, 1, 1], [256, 1, 1])); + assert_eq!(k[2].args, vec![A::P(lo), A::I32(320), A::F32(0.25)]); + // 4. bf16_gemv_fp32_mmvf(lo, up -> gated, 320 -> 10240): mmvf block 96 + assert_eq!((k[3].entry, k[3].grid, k[3].block), ("mtp_full_mmvf96", [10_240, 1, 1], [96, 1, 1])); + assert_eq!(k[3].args, vec![A::P(lo), A::P(0xC000), A::P(gated), A::I32(320)]); + // 5. native_gr_pre_gated(xn, gated, mixed, n, hc, 1/4): 10 blocks + assert_eq!((k[4].entry, k[4].grid, k[4].block), ("mtp_full_pre_final", [10, 1, 1], [256, 1, 1])); + assert_eq!(k[4].args, vec![A::P(xn), A::P(gated), A::P(mixed), A::I32(2560), A::I32(4), A::F32(0.25)]); + } + // the whole window: 1..=8 rows; none beyond max_t + assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 8).is_ok()); + assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 9).is_err()); + assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 0).is_err()); + let mut non_native = sm120(GrVariant::Staged); + non_native.native_mmvf = false; + assert!(matches!( + plan_head_mix(&m, &g, &w, &non_native, mixed_base, 1), + Err(Error::InvalidDriverValue(s)) if s.contains("head") + )); + } + + // ------------------------------------------------------------------------------------ PLE + fn ple_addrs(key: PleKey) -> PleAddrs { + PleAddrs { + key, + value: 0x5000_0000, + norm_key: 0x5100_0000, + norm_query: 0x5200_0000, + norm_conv: 0x5300_0000, + conv1d: 0x5400_0000, + scratch: 0x6000_0000, + history: 0x6100_0000, + } + } + + #[test] + fn ple_scratch_matches_ple_block_workspace_carving() { + // 5 * hc_dim + n_embd + hc floats: key, query, norm, gated, conv, value, gate + assert_eq!(PLE_SCRATCH_BYTES, 215_056); + assert_eq!(SCRATCH_QUERY, 40_960); + assert_eq!(SCRATCH_NORM, 81_920); + assert_eq!(SCRATCH_GATED, 122_880); + assert_eq!(SCRATCH_CONV, 163_840); + assert_eq!(SCRATCH_VALUE, 204_800); + assert_eq!(SCRATCH_GATE, 215_040); + assert_eq!(SCRATCH_GATE + 16, PLE_SCRATCH_BYTES as u64); + } + + #[test] + fn ple_row_with_a_bf16_key_follows_ple_block_native_order() { + let m = arena(); + let g = test_geometry(); + let a = ple_addrs(PleKey::Bf16(0x7000_0000)); + let l = plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &a, 2).unwrap(); + let names: Vec<&str> = l.iter().map(|x| x.entry).collect(); + assert_eq!( + names, + [ + "mtp_full_native_write", // the pending layer-0 gr_write + "mtp_full_mmvf256", // key = ple_key @ emb (10240 x 2560) + "mtp_full_mmvf256", // value = ple_value @ emb (2560 x 2560) + "ple_rms", // key norm -> d_query + "ple_rms", // hidden norm -> d_norm + "ple_gate", + "ple_broadcast", + "ple_rms", // gated norm -> d_norm + "ple_conv", + "ple_history", + ] + ); + let r = at(&m, "R", 2 * 40_960); + let emb = at(&m, "ple", 2 * 10_240); + let s = 0x6000_0000u64; + assert_eq!(l[0].args[0], A::P(r)); + assert_eq!(l[0].args[3], A::P(r)); + // key: x = emb, y = scratch key (ldy = 10240), 2560 -> 10240 + assert_eq!(l[1].grid, [10_240, 1, 1]); + assert_eq!(l[1].args, vec![A::P(emb), A::P(0x7000_0000), A::P(s), A::I32(2560)]); + // value: y = scratch value, 2560 -> 2560 + assert_eq!(l[2].grid, [2560, 1, 1]); + assert_eq!(l[2].args, vec![A::P(emb), A::P(0x5000_0000), A::P(s + 204_800), A::I32(2560)]); + // postops: rms(key -> query), rms(hidden -> norm), gate(query, norm -> gate), ... + assert_eq!(l[3].args, vec![A::P(s), A::P(0x5100_0000), A::P(s + 40_960)]); + assert_eq!(l[4].args, vec![A::P(r), A::P(0x5200_0000), A::P(s + 81_920)]); + assert_eq!((l[3].grid, l[3].block), ([4, 1, 1], [1024, 1, 1])); + assert_eq!((l[5].grid, l[5].block), ([4, 1, 1], [512, 1, 1])); + assert_eq!(l[5].args, vec![A::P(s + 40_960), A::P(s + 81_920), A::P(s + 215_040), A::F32(1.0 / 2560f32.sqrt())]); + assert_eq!((l[6].grid, l[6].block), ([40, 1, 1], [256, 1, 1])); + assert_eq!(l[6].args, vec![A::P(s + 204_800), A::P(s + 215_040), A::P(s + 122_880), A::I32(1)]); + assert_eq!(l[7].args, vec![A::P(s + 122_880), A::P(0x5300_0000), A::P(s + 81_920)]); + // conv + residual: hidden = Rt in place + assert_eq!( + l[8].args, + vec![A::P(0x6100_0000), A::P(s + 81_920), A::P(0x5400_0000), A::P(r), A::P(s + 122_880), A::P(s + 163_840), A::I32(1)] + ); + assert_eq!((l[8].grid, l[8].block), ([40, 1, 1], [256, 1, 1])); + // history advance reads the normalized row from the workspace + assert_eq!(l[9].args, vec![A::P(0x6100_0000), A::P(s + 81_920), A::I32(1)]); + assert_eq!((l[9].grid, l[9].block), ([40, 1, 1], [256, 1, 1])); + for launch in &l[3..] { + assert!(std::ptr::eq(launch.asset, &PLE_BATCH)); + } + } + + #[test] + fn ple_row_with_a_native_key_quantizes_into_the_arena_and_runs_mmvq() { + let m = arena(); + let g = test_geometry(); + let a = ple_addrs(PleKey::Native { ty: 42, data: 0x7100_0000 }); + let l = plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &a, 0).unwrap(); + let names: Vec<&str> = l.iter().map(|x| x.entry).collect(); + assert_eq!(&names[..4], &["mtp_full_native_write", "head_quant", "head_n42_s1", "mtp_full_mmvf256"]); + assert_eq!(l.len(), 11); + let q8 = at(&m, "xq", 0); + let emb = at(&m, "ple", 0); + assert_eq!(l[1].args, vec![A::P(emb), A::P(q8), A::I32(2560)]); + // 2560 / 64 = 40 blocks < 64 per iteration: the "small" layout, 4 rows per block + assert_eq!((l[2].grid, l[2].block), ([2560, 1, 1], [32, 4, 1])); + assert_eq!( + l[2].args, + vec![A::P(0x7100_0000), A::P(q8), A::P(0x6000_0000), A::I32(2560), A::I32(10_240)] + ); + // an unsupported native key type fails closed + let bad = ple_addrs(PleKey::Native { ty: 14, data: 1 }); + assert_eq!( + plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &bad, 0).unwrap_err(), + Error::UnsupportedQwenOperation + ); + } + + #[test] + fn ple_layer1_walks_the_group_rows_in_order_and_fails_closed_on_policy() { + let m = arena(); + let g = test_geometry(); + let a = ple_addrs(PleKey::Bf16(0x7000_0000)); + let c = sm120(GrVariant::Staged); + let out = plan_ple_layer1(&m, &g, &c, &PleConfig::mode17(), &a, rows(4, 7, 1)).unwrap(); + assert_eq!(out.iter().map(|(t, _)| *t).collect::>(), [4, 5, 6]); + assert!(out.iter().all(|(_, l)| l.len() == 10)); + let mut legacy = PleConfig::mode17(); + legacy.native_postops = false; + assert!(matches!( + plan_ple_layer1(&m, &g, &c, &legacy, &a, rows(0, 1, 0)), + Err(Error::InvalidDriverValue(s)) if s.contains("ple_layer1") + )); + legacy = PleConfig::mode17(); + legacy.native_value_bf16 = false; + assert!(plan_ple_row(&m, &g, &c, &legacy, &a, 0).is_err()); + assert!(plan_ple_row(&m, &g, &c, &PleConfig::mode17(), &a, 8).is_err()); + } + + // ---------------------------------------------------------------------------- byte sizes + #[test] + fn weight_byte_sizes_follow_the_hc_geometry() { + // hc=4, N=2560, hc_lr=320 + assert_eq!(HC_NORM_BYTES, 4 * 2560 * 4); + assert_eq!(HC_DOWN_BYTES, 320 * 4 * 2560 * 2); + assert_eq!(HC_UP_BYTES, 4 * 2560 * 320 * 2); + assert_eq!(HC_INJECT_BYTES, 4 * 4 * 2560 * 2); + assert_eq!(PLE_HISTORY_BYTES, 9 * 4 * 2560 * 4); + assert_eq!(PLE_VALUE_BYTES, 2560 * 2560 * 2); + assert_eq!(PLE_KEY_BF16_BYTES, 10_240 * 2560 * 2); + assert_eq!(PLE_CONV_BYTES, 4 * 10_240 * 2); + // a Q2_0 key: 64-element blocks of 18 bytes -> 40 blocks per row + assert_eq!(native_head_row_bytes(42, 2560).unwrap(), 40 * 18); + } +}