From 7e1d183313172eb037488a5efffc8d9798efdead Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 14 Oct 2026 16:05:50 +0200 Subject: [PATCH] test(verify): whole-window planner harness (every T, both splits, PLE) and mmvf block-size corrections PlanOps drives the literal recorder through the pure planners with synthetic weights and pins the launch order of GDN/QSA layers, post phase, split groups, head and PLE; fixes two hand-derived expectations (mmvf block for 320 inputs is 160). Co-Authored-By: Claude Sonnet 5.5 --- .../src/original_verify_window_gr.rs | 4 +- .../src/original_verify_window_planner.rs | 372 ++++++++++++++++++ .../src/original_verify_window_proj.rs | 4 +- 3 files changed, 377 insertions(+), 3 deletions(-) diff --git a/crates/cuda-driver/src/original_verify_window_gr.rs b/crates/cuda-driver/src/original_verify_window_gr.rs index 2c5b5c53..94404386 100644 --- a/crates/cuda-driver/src/original_verify_window_gr.rs +++ b/crates/cuda-driver/src/original_verify_window_gr.rs @@ -1199,8 +1199,8 @@ mod tests { // 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])); + // 4. bf16_gemv_fp32_mmvf(lo, up -> gated, 320 -> 10240): mmvf block 160 (ceil(320/320) = 1 iteration) + assert_eq!((k[3].entry, k[3].grid, k[3].block), ("mtp_full_mmvf160", [10_240, 1, 1], [160, 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])); diff --git a/crates/cuda-driver/src/original_verify_window_planner.rs b/crates/cuda-driver/src/original_verify_window_planner.rs index e616a522..c3aa8218 100644 --- a/crates/cuda-driver/src/original_verify_window_planner.rs +++ b/crates/cuda-driver/src/original_verify_window_planner.rs @@ -161,3 +161,375 @@ impl<'p> Planner<'p> { moe::plan_combine(self.arena, &self.geo, &self.moe_knobs(), rows, batched) } } + +#[cfg(test)] +mod tests { + use super::super::kernels::{LayoutMap, test_geometry}; + use super::super::moe::MoeLayerAddrs; + use super::super::proj::NativeWeight; + use super::super::qsa::{OriginalVerifyQsaKvBinding, QsaWeightAddrs}; + use super::super::window_plan::WINDOW_LAYERS; + use super::super::window_record::{WindowOps, record_window}; + use super::*; + + const BASE: u64 = 0x7000_0000_0000; + + /// Synthetic weights: every layer's operands get distinct, 256-aligned addresses. + struct Fake { + formats: OriginalVerifyExpertFormats, + ple: bool, + } + fn w(a: u64) -> NativeWeight { + NativeWeight { ty: 14, data: a } + } + impl WindowWeights for Fake { + fn gdn_projections(&self, g: usize) -> Result { + let b = 0x10_0000_0000u64 + g as u64 * 0x1000_0000; + Ok(GdnProjectionAddrs { qkv: w(b), gate: NativeWeight { ty: 8, data: b + 0x100_0000 }, out: NativeWeight { ty: 12, data: b + 0x200_0000 } }) + } + fn qsa_projections(&self, q: usize) -> Result { + let b = 0x20_0000_0000u64 + q as u64 * 0x1000_0000; + Ok(QsaProjectionAddrs { + k: NativeWeight { ty: 12, data: b }, + v: NativeWeight { ty: 12, data: b + 0x100_0000 }, + q: w(b + 0x200_0000), + out: w(b + 0x300_0000), + }) + } + fn hc(&self, layer: usize, half: HcHalf) -> Result { + let b = 0x30_0000_0000u64 + layer as u64 * 0x1_0000_0000 + if half == HcHalf::Ffn { 0x8000_0000 } else { 0 }; + Ok(HcAddrs { norm: b, down: b + 0x100_0000, up: b + 0x200_0000, inject: b + 0x300_0000 }) + } + fn head(&self) -> Result { + Ok(HeadAddrs { norm: 0x3f_0000_0000, down: 0x3f_0100_0000, up: 0x3f_0200_0000 }) + } + fn ple(&self) -> Result> { + Ok(self.ple.then_some(PleAddrs { + key: gr::PleKey::Bf16(0x40_0000_0000), + value: 0x40_1000_0000, + norm_key: 0x40_2000_0000, + norm_query: 0x40_2100_0000, + norm_conv: 0x40_2200_0000, + conv1d: 0x40_2300_0000, + scratch: 0x40_3000_0000, + history: 0x40_4000_0000, + })) + } + fn qsa(&self, q: usize) -> Result { + let b = 0x50_0000_0000u64 + q as u64 * 0x1_0000_0000; + Ok(QsaLayerAddrs { + weights: QsaWeightAddrs { q_norm: b, k_norm: b + 0x1_0000, index_q_norm: b + 0x2_0000, index_k_proj: b + 0x100_0000, index_q_proj: b + 0x200_0000 }, + kv: OriginalVerifyQsaKvBinding { + resident: [b + 0x1000_0000, b + 0x1100_0000, b + 0x1200_0000, b + 0x1210_0000], + table: b + 0x1300_0000, + host: [b + 0x2000_0000, b + 0x2100_0000, b + 0x2200_0000, b + 0x2210_0000], + resolver: [b + 0x1300_0000, b + 0x1310_0000, b + 0x1320_0000, b + 0x1330_0000, b + 0x1340_0000, b + 0x1350_0000, b + 0x1360_0000], + pooled: b + 0x1400_0000, + pooled_bytes: 1026 * 512, + dead: b + 0x1410_0000, + dead_bytes: 512, + }, + }) + } + fn rope(&self) -> Result { + QsaRope::new(0.7498942, 1.0, 0.0, 0.0, 0.0, 1.0) + } + fn moe(&self, layer: usize) -> Result { + let b = 0x60_0000_0000u64 + layer as u64 * 0x1_0000_0000; + Ok(MoeLayerAddrs { + router: b, + gate_inp_shexp: b + 0x100_0000, + gate_shexp: NativeWeight { ty: 8, data: b + 0x200_0000 }, + up_shexp: NativeWeight { ty: 8, data: b + 0x300_0000 }, + down_shexp: NativeWeight { ty: 8, data: b + 0x400_0000 }, + }) + } + fn expert_formats(&self) -> Result<&OriginalVerifyExpertFormats> { + Ok(&self.formats) + } + } + + /// Readable name of a launched kernel: the entry, or for a mangled Original kernel its base name. + fn kernel(l: &Launch) -> String { + const BASES: [&str; 14] = [ + "mmvf_multi_kernel", "mmvf_kernel", "to_bf16_kernel", "native_swiglu_kernel", "scalar_gate_kernel", + "native_scalar_sigmoid_multi_kernel", "native_scalar_sigmoid_kernel", "scale_rows_kernel", "moe_combine_kernel", + "swiglu_entries_kernel", "quantize_q8_1_kernel", "add_hits_kernel", "router_top10_kernel", "block_scores_kernel", + ]; + if !l.entry.starts_with("_ZN") { + return l.entry.to_string(); + } + BASES.iter().find(|b| l.entry.contains(*b)).map(|b| b.to_string()).unwrap_or_else(|| l.entry.to_string()) + } + + /// The recorder driven through the planners with no driver: every producer logs the kernels it would + /// launch (journal-owned producers log a marker). `fail` makes the named producer error. + struct PlanOps<'p> { + planner: Planner<'p>, + log: Vec, + t: usize, + } + impl PlanOps<'_> { + fn plan(&mut self, name: &str, r: Result>) -> Result<()> { + let launches = r?; + self.log.push(format!("<{name}")); + for l in &launches { + self.log.push(kernel(l)); + } + self.log.push(format!("{name}>")); + Ok(()) + } + fn mark(&mut self, s: String) -> Result<()> { + self.log.push(s); + Ok(()) + } + } + impl WindowOps for PlanOps<'_> { + fn embed(&mut self) -> Result<()> { self.mark("embed".into()) } + fn stamp(&mut self, l: usize, s: usize) -> Result<()> { self.mark(format!("stamp {l}.{s}")) } + fn ple_layer1(&mut self, rows: Rows) -> Result<()> { + let per = self.planner.ple_layer1(rows)?; + for (row, launches) in per { + self.log.push(format!(" Result<()> { + let x = self.planner.hc_read(l, h, a, r); + self.plan(&format!("hc {h:?} apply={a}"), x) + } + fn quantize_q8_1(&mut self, _: usize, s: QuantSource, r: Rows) -> Result<()> { + let x = self.planner.quantize_q8_1(s, r); + self.plan(&format!("quant {s:?}"), x) + } + fn mmvq(&mut self, l: usize, p: Projection, r: Rows) -> Result<()> { + let x = self.planner.mmvq(l, p, r); + self.plan(&format!("mmvq {p:?}"), x) + } + fn gdn_conv(&mut self, g: usize, r: Rows) -> Result<()> { self.mark(format!("gdn_conv g{g} {}..{}", r.begin, r.end)) } + fn gdn_alpha_beta(&mut self, g: usize, _: Rows) -> Result<()> { self.mark(format!("gdn_ab g{g}")) } + fn gdn_recurrence(&mut self, g: usize, _: Rows) -> Result<()> { self.mark(format!("gdn_rec g{g}")) } + fn qsa_index_k(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_index_k(q, r, b); + self.plan("index_k", x) + } + fn qsa_k_norm_rope(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_k_norm_rope(q, r, b); + self.plan("k_norm_rope", x) + } + fn qsa_tail_snapshot(&mut self, q: usize) -> Result<()> { self.mark(format!("tail q{q}")) } + fn qsa_kv_append(&mut self, q: usize, r: Rows) -> Result<()> { + let x = self.planner.qsa_kv_append(q, r); + self.plan("kv_append", x) + } + fn qsa_indexer_append(&mut self, q: usize, _: Rows) -> Result<()> { self.mark(format!("indexer_append q{q}")) } + fn qsa_q_path(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_q_path(q, r, b); + self.plan("q_path", x) + } + fn qsa_index_q_path(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_index_q_path(q, r, b); + self.plan("index_q_path", x) + } + fn qsa_block_scores_topk(&mut self, q: usize, r: Rows) -> Result<()> { + let x = self.planner.qsa_block_scores_topk(q, r); + self.plan("scores_topk", x) + } + fn qsa_kv_resolve(&mut self, q: usize, r: Rows) -> Result<()> { + let x = self.planner.qsa_kv_resolve(q, r); + self.plan("kv_resolve", x) + } + fn qsa_decode_attention(&mut self, q: usize, r: Rows) -> Result<()> { + let x = self.planner.qsa_decode_attention(q, r); + self.plan("attention", x) + } + fn qsa_gate(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_gate(q, r, b); + self.plan("gate", x) + } + fn router(&mut self, l: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.router(l, r, b); + self.plan("router", x) + } + fn doorbell(&mut self, _: Rows) -> Result<()> { self.mark("doorbell".into()) } + fn shared_expert(&mut self, l: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.shared_expert(l, r, b); + self.plan("shared", x) + } + fn quantize_expert_input(&mut self, _: usize, r: Rows) -> Result<()> { + let x = self.planner.quantize_expert_input(r); + self.plan("xq", x) + } + fn wait_plan(&mut self, ring: u32, _: Rows) -> Result<()> { self.mark(format!("waitA {ring}")) } + fn expert_groups(&mut self, l: usize, r: Rows, t: ExpertTier) -> Result<()> { + let x = self.planner.expert_groups(l, r, t); + self.plan(&format!("experts {t:?}"), x) + } + fn wait_copies(&mut self, ring: u32) -> Result<()> { self.mark(format!("waitB {ring}")) } + fn pcie_stage(&mut self, _: usize, _: Rows) -> Result<()> { self.mark("pcie_stage".into()) } + fn wait_cpu(&mut self, ring: u32) -> Result<()> { self.mark(format!("waitM {ring}")) } + fn copy_cpu_rows(&mut self, _: Rows, _: bool) -> Result<()> { self.mark("cpu_rows".into()) } + fn hit_add(&mut self, r: Rows) -> Result<()> { + let x = self.planner.hit_add(r); + self.plan("hit_add", x) + } + fn combine(&mut self, _: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.combine(r, b); + self.plan("combine", x) + } + fn final_write(&mut self, r: Rows) -> Result<()> { + let x = self.planner.final_write(r); + self.plan("final_write", x) + } + fn head(&mut self, rows: usize) -> Result<()> { + assert_eq!(rows, self.t); + let x = self.planner.head_mix(0x7f_0000_0000, rows); + self.plan("head_mix", x)?; + self.mark("head_tail".into()) + } + } + + fn geometry_and_fake(ple: bool) -> (LayoutMap, Fake) { + let m = LayoutMap::new(BASE, test_geometry()); + let formats = OriginalVerifyExpertFormats::new([(16, 20); WINDOW_LAYERS], 2560, 640).unwrap(); + (m, Fake { formats, ple }) + } + fn sm120() -> GrConfig { + GrConfig::from_device(gr::GrVariant::Staged, true, 12, 0, 99 * 1024, 48 * 1024) + } + fn record(t: usize, groups: usize, ple: bool) -> Vec { + let (m, fake) = geometry_and_fake(ple); + let planner = Planner::new(&m, test_geometry(), WindowPolicy::mode17(), sm120(), &fake); + let mut ops = PlanOps { planner, log: Vec::new(), t }; + record_window(&mut ops, &WindowPolicy::mode17(), t, groups, ple).unwrap(); + ops.log + } + fn section<'a>(log: &'a [String], from: &str, to: &str) -> &'a [String] { + let a = log.iter().position(|s| s == from).unwrap_or_else(|| panic!("{from} missing")); + let b = a + log[a..].iter().position(|s| s == to).unwrap_or_else(|| panic!("{to} missing")); + &log[a..=b] + } + fn names(log: &[String]) -> Vec<&str> { + log.iter().map(String::as_str).collect() + } + + #[test] + fn every_window_size_and_group_split_plans_without_error() { + for groups in [1usize, 2] { + for t in 1..=8usize { + if groups == 2 && t < 2 { + continue; + } + for ple in [false, true] { + // the 8-row xq/qfull/kcur ... spans and every arena bound hold for the whole 48-layer window + let log = record(t, groups, ple); + assert_eq!(log.iter().filter(|s| *s == "doorbell").count(), 48 * groups); + assert_eq!(log.iter().filter(|s| s.as_str() == "head_tail").count(), 1); + assert_eq!(log.iter().filter(|s| s.starts_with("") < pos(""); + assert_eq!(names(router).iter().filter(|s| s.contains("mmvf_multi_kernel") || **s == "mtp_full_route").count(), 2); + // the projections are the native MMVQ of the bound weight types at three rows + assert!(k.contains(&"head_n14_t3_large") && k.contains(&"head_n8_t3_large") && k.contains(&"head_n12_t3_large")); + // layer 1's attention read folds the pending write (apply=true), layer 0's did not + assert!(log.iter().any(|s| s == " = order.iter().map(|n| pos(n)).collect(); + assert!(at.windows(2).all(|w| w[0] < w[1]), "{order:?} -> {at:?}"); + // four rows are batched: one index-k multi gemv, one mmvq per projection at four columns + assert!(k.iter().any(|s| s.contains("mmvf_multi_kernel"))); + assert!(k.contains(&"head_n12_t4_large") && k.contains(&"head_n14_t4_large")); + assert!(k.contains(&"verify_window_qsa_gate")); + assert!(k.contains(&"leleka_qsa_decode_chunk") && k.contains(&"leleka_qsa_decode_merge")); + // the single-row window keeps the per-token (unbatched) kernels + let one = record(1, 1, false); + let one_k = names(section(&one, "stamp 3.0", "stamp 3.16")); + assert!(one_k.iter().any(|s| s.contains("mtp_full_mmvf"))); + assert!(!one_k.iter().any(|s| s.contains("mmvf_multi_kernel"))); + } + + #[test] + fn post_records_vram_then_pcie_experts_hit_add_and_combine() { + let log = record(2, 1, false); + let post = section(&log, "waitA 1", "stamp 0.24"); + let k = names(post); + let order = ["waitA 1", " = order.iter().map(|n| k.iter().position(|s| s == n).unwrap_or_else(|| panic!("{n} missing"))).collect(); + assert!(at.windows(2).all(|w| w[0] < w[1]), "{at:?}"); + // each tier is gate/up, swiglu, quantize, down + let vram = names(section(&log, "")); + assert_eq!(&vram[1..vram.len() - 1], ["window_moe_gu_16", "swiglu_entries_kernel", "quantize_q8_1_kernel", "window_moe_down_20"]); + // the last layer writes the residual once per row + let last = section(&log, "stamp 47.24", "stamp 48.0"); + assert_eq!(names(last).iter().filter(|s| **s == "mtp_full_native_write").count(), 2); + } + + #[test] + fn split_windows_interleave_groups_but_keep_each_group_in_order() { + let log = record(5, 2, false); + // pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) ...: group B's first read follows A's FFN prep, then A's experts + let hcs: Vec = log.iter().enumerate().filter(|(_, s)| s.starts_with(" 160 (later candidates cannot beat one iteration) + assert_eq!(mmvf_block_size(320), 160); + assert_eq!(mmvf_block_size(192), 96); assert_eq!(mmvf_block_size(10240), 256); assert_eq!(mmvf_block_size(64), 32); assert_eq!(mmvf_block_size(128), 64);