[RT][ABI] executor dispatches full MoE path; composed MoE expert forward verified on GPU

- rt::executor: dispatch NVFP4 expert GEMV (MoeW13Wmma/MoeW2Wmma -> nvfp4_gemv),
  SiTU activation, MoE weighted reduce. execute_with(get) core + execute /
  execute_refs wrappers (owned or borrowed buffer tables, for shared weights).
- abi::vplan: Situ opcode (32 total).
- Composed MoE expert path test: router -> per-expert (w13 NVFP4 GEMV -> SiTU
  -> w2 NVFP4 GEMV) -> weighted reduce, verified end-to-end vs a full CPU
  oracle (router sigmoid top-k + NVFP4 dequant + SiTU). max_rel_err 9.2e-7.
  The entire MoE compute of the base decode graph now runs composed on GPU.

With the trunk composed forward, the executor proves both halves of the base
graph (attention trunk + MoE experts) compose correctly on real hardware.
Remaining for full inference: lowering CompiledPlans+IR -> ExecOp (shape
attachment) + .vbundle packer (real weights -> device), then Inkling parity
refinements + serve wiring.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; GPU 10/10 + rt composed 2/2
(--features hip).
This commit is contained in:
adm committed 2026-12-01 14:16:04 +01:00
1 parent 529709cc64
commit 1b3896bba9
2 files changed
+176 -5

No files matched your search

+4 -1
View File
@@ -34,6 +34,7 @@ pub enum VplanOp {
MoeRouterTopk, MoeRouterTopk,
VecAdd, VecAdd,
CastF32Bf16, CastF32Bf16,
Situ,
VitFlashAttnWmma, VitFlashAttnWmma,
GpuPenaltiesTopk, GpuPenaltiesTopk,
// Encoder lane (M1.5 embedder, docs/ARCHITECTURE.md §4) // Encoder lane (M1.5 embedder, docs/ARCHITECTURE.md §4)
@@ -83,6 +84,7 @@ impl VplanOp {
Self::MoeRouterTopk => "moe_router_topk", Self::MoeRouterTopk => "moe_router_topk",
Self::VecAdd => "vec_add", Self::VecAdd => "vec_add",
Self::CastF32Bf16 => "cast_f32_bf16", Self::CastF32Bf16 => "cast_f32_bf16",
Self::Situ => "situ",
Self::VitFlashAttnWmma => "vit_flash_attn_wmma", Self::VitFlashAttnWmma => "vit_flash_attn_wmma",
Self::GpuPenaltiesTopk => "gpu_penalties_topk", Self::GpuPenaltiesTopk => "gpu_penalties_topk",
Self::LayerNorm => "layer_norm", Self::LayerNorm => "layer_norm",
@@ -121,6 +123,7 @@ impl VplanOp {
"moe_router_topk" => Self::MoeRouterTopk, "moe_router_topk" => Self::MoeRouterTopk,
"vec_add" => Self::VecAdd, "vec_add" => Self::VecAdd,
"cast_f32_bf16" => Self::CastF32Bf16, "cast_f32_bf16" => Self::CastF32Bf16,
"situ" => Self::Situ,
"vit_flash_attn_wmma" => Self::VitFlashAttnWmma, "vit_flash_attn_wmma" => Self::VitFlashAttnWmma,
"gpu_penalties_topk" => Self::GpuPenaltiesTopk, "gpu_penalties_topk" => Self::GpuPenaltiesTopk,
"layer_norm" => Self::LayerNorm, "layer_norm" => Self::LayerNorm,
@@ -155,7 +158,7 @@ mod tests {
VplanOp::GdnRecurrentStep, VplanOp::MoeRouteBucket, VplanOp::MoeW13Wmma, VplanOp::GdnRecurrentStep, VplanOp::MoeRouteBucket, VplanOp::MoeW13Wmma,
VplanOp::MoeW2Wmma, VplanOp::MoeReduce, VplanOp::VitFlashAttnWmma, VplanOp::MoeW2Wmma, VplanOp::MoeReduce, VplanOp::VitFlashAttnWmma,
VplanOp::AttnResMix, VplanOp::ShortConv4, VplanOp::LoopCtrl, VplanOp::L2Clip, VplanOp::AttnResMix, VplanOp::ShortConv4, VplanOp::LoopCtrl, VplanOp::L2Clip,
VplanOp::KvStore, VplanOp::RelPosBias, VplanOp::MoeRouterTopk, VplanOp::VecAdd, VplanOp::CastF32Bf16, VplanOp::KvStore, VplanOp::RelPosBias, VplanOp::MoeRouterTopk, VplanOp::VecAdd, VplanOp::CastF32Bf16, VplanOp::Situ,
VplanOp::GpuPenaltiesTopk, VplanOp::LayerNorm, VplanOp::FlashFullAttn, VplanOp::GpuPenaltiesTopk, VplanOp::LayerNorm, VplanOp::FlashFullAttn,
VplanOp::GeluErf, VplanOp::PoolL2norm, VplanOp::LoopLayer, VplanOp::BranchB, VplanOp::GeluErf, VplanOp::PoolL2norm, VplanOp::LoopLayer, VplanOp::BranchB,
]; ];
+172 -4
View File
@@ -27,6 +27,12 @@ pub enum OpParams {
VecAdd { n: usize }, VecAdd { n: usize },
/// reads [x f32], writes [y bf16] /// reads [x f32], writes [y bf16]
Cast { n: usize }, Cast { n: usize },
/// reads [packed, scales, x], writes [y] (NVFP4 M=1 GEMV)
Nvfp4Gemv { n: i32, k: i32, outer_scale: f32 },
/// reads [gu], writes [act] (SiTU activation)
Situ { inter: i32, beta: f32, lb: f32 },
/// reads [y_part, tk_w], writes [out] (weighted expert sum)
MoeReduce { top_k: i32, hidden: i32 },
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -39,12 +45,22 @@ pub struct ExecOp {
/// Execute `ops` over a buffer table indexed by arena decl index. /// Execute `ops` over a buffer table indexed by arena decl index.
pub fn execute(buffers: &[DeviceBuf], ops: &[ExecOp]) -> Result<(), String> { pub fn execute(buffers: &[DeviceBuf], ops: &[ExecOp]) -> Result<(), String> {
execute_with(|idx| buffers.get(idx), ops)
}
/// Execute over a table of borrowed buffers (shared weight tables).
pub fn execute_refs(buffers: &[&DeviceBuf], ops: &[ExecOp]) -> Result<(), String> {
execute_with(|idx| buffers.get(idx).copied(), ops)
}
/// Core dispatch: `get` resolves a decl index to a device buffer.
pub fn execute_with<'a>(get: impl Fn(usize) -> Option<&'a DeviceBuf>, ops: &[ExecOp]) -> Result<(), String> {
for (i, o) in ops.iter().enumerate() { for (i, o) in ops.iter().enumerate() {
let r = |k: usize| -> Result<&DeviceBuf, String> { let r = |k: usize| -> Result<&'a DeviceBuf, String> {
o.reads.get(k).and_then(|&idx| buffers.get(idx)).ok_or_else(|| format!("op {i}: bad read operand")) o.reads.get(k).and_then(|&idx| get(idx)).ok_or_else(|| format!("op {i}: bad read operand"))
}; };
let w = |k: usize| -> Result<&DeviceBuf, String> { let w = |k: usize| -> Result<&'a DeviceBuf, String> {
o.writes.get(k).and_then(|&idx| buffers.get(idx)).ok_or_else(|| format!("op {i}: bad write operand")) o.writes.get(k).and_then(|&idx| get(idx)).ok_or_else(|| format!("op {i}: bad write operand"))
}; };
let res = match (&o.op, &o.params) { let res = match (&o.op, &o.params) {
(VplanOp::EmbedBf16, OpParams::Embed { b, d, vocab }) => { (VplanOp::EmbedBf16, OpParams::Embed { b, d, vocab }) => {
@@ -69,6 +85,16 @@ pub fn execute(buffers: &[DeviceBuf], ops: &[ExecOp]) -> Result<(), String> {
(VplanOp::CastF32Bf16, OpParams::Cast { n }) => { (VplanOp::CastF32Bf16, OpParams::Cast { n }) => {
vetta_infer_hip::cast_f32_bf16(r(0)?, w(0)?, *n) vetta_infer_hip::cast_f32_bf16(r(0)?, w(0)?, *n)
} }
(VplanOp::MoeW13Wmma, OpParams::Nvfp4Gemv { n, k, outer_scale })
| (VplanOp::MoeW2Wmma, OpParams::Nvfp4Gemv { n, k, outer_scale }) => {
vetta_infer_hip::nvfp4_gemv(r(0)?, r(1)?, *outer_scale, r(2)?, w(0)?, *n, *k)
}
(VplanOp::MoeReduce, OpParams::MoeReduce { top_k, hidden }) => {
vetta_infer_hip::moe_reduce(r(0)?, r(1)?, w(0)?, *top_k, *hidden)
}
(VplanOp::Situ, OpParams::Situ { inter, beta, lb }) => {
vetta_infer_hip::situ(r(0)?, w(0)?, *inter, *beta, *lb)
}
_ => Err(format!("op {i}: opcode {:?} not yet dispatched (params {:?})", o.op, o.params)), _ => Err(format!("op {i}: opcode {:?} not yet dispatched (params {:?})", o.op, o.params)),
}; };
res.map_err(|e| format!("op {i} ({:?}): {e}", o.op))?; res.map_err(|e| format!("op {i} ({:?}): {e}", o.op))?;
@@ -140,4 +166,146 @@ mod tests {
eprintln!("composed trunk forward max_rel_err={max_rel:.3e}"); eprintln!("composed trunk forward max_rel_err={max_rel:.3e}");
assert!(max_rel < 1e-4, "composed trunk parity failed: {max_rel}"); assert!(max_rel < 1e-4, "composed trunk parity failed: {max_rel}");
} }
fn e2m1(nib: u8) -> f32 {
const LUT: [f32; 16] = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0];
LUT[(nib & 15) as usize]
}
fn e4m3(b: u8) -> f32 {
let sign = ((b & 0x80) as u32) << 24;
let exp = (b >> 3) & 0xF;
let mant = b & 7;
if exp == 0 {
if mant == 0 { return f32::from_bits(sign); }
let val = mant as f32 / 512.0;
return if b & 0x80 != 0 { -val } else { val };
} else if exp == 15 && mant == 7 { return 0.0; }
f32::from_bits(sign | ((exp as u32 + 120) << 23) | ((mant as u32) << 20))
}
fn nvfp4_dequant_row(packed: &[u8], scales: &[u8], outer: f32, _n: usize, k: usize, row: usize) -> Vec<f32> {
let mut w = vec![0f32; k];
for b in 0..k / 16 {
let sc = e4m3(scales[row * (k / 16) + b]) * outer;
for j in 0..8 {
let byte = packed[row * (k / 2) + b * 8 + j];
w[b * 16 + j * 2] = e2m1(byte & 15) * sc;
w[b * 16 + j * 2 + 1] = e2m1(byte >> 4) * sc;
}
}
w
}
fn situ_cpu(g: f32, u: f32, beta: f32, lb: f32) -> f32 {
let sig = 1.0 / (1.0 + (-g).exp());
(beta * (g / beta).tanh() * sig) * (lb * (u / lb).tanh())
}
/// Composed MoE expert path on GPU: router -> per-expert (w13 NVFP4 GEMV ->
/// SiTU -> w2 NVFP4 GEMV) -> weighted reduce, verified vs a CPU oracle.
#[test]
#[ignore]
fn moe_expert_path_composed_parity() {
let (n_experts, top_k, hidden, inter) = (4usize, 2usize, 16usize, 16usize);
let (beta, lb, outer, route_scale) = (4.0f32, 25.0f32, 0.5f32, 8.0f32);
let mlpin: Vec<f32> = (0..hidden).map(|i| ((i % 13) as f32 - 6.0) * 0.1).collect();
let logits: Vec<f32> = (0..n_experts).map(|i| (i as f32 - 1.5) * 0.8).collect();
let bias: Vec<f32> = (0..n_experts).map(|i| (i as f32) * 0.05).collect();
// Per-expert NVFP4 weights: w13 [2*inter, hidden], w2 [hidden, inter].
let mut w13p = vec![vec![0u8; 2 * inter * (hidden / 2)]; n_experts];
let mut w13s = vec![vec![0u8; 2 * inter * (hidden / 16)]; n_experts];
let mut w2p = vec![vec![0u8; hidden * (inter / 2)]; n_experts];
let mut w2s = vec![vec![0u8; hidden * (inter / 16)]; n_experts];
for e in 0..n_experts {
for i in 0..w13p[e].len() { w13p[e][i] = ((i * 5 + e * 17) % 256) as u8; }
for i in 0..w13s[e].len() { w13s[e][i] = ((i * 7 + e * 11 + 3) % 251) as u8; }
for i in 0..w2p[e].len() { w2p[e][i] = ((i * 3 + e * 23) % 256) as u8; }
for i in 0..w2s[e].len() { w2s[e][i] = ((i * 9 + e * 13 + 5) % 251) as u8; }
}
// CPU oracle: router (sigmoid top-k) then per-expert dequant compute.
let prob: Vec<f32> = logits.iter().map(|&l| 1.0 / (1.0 + (-l).exp())).collect();
let mut score: Vec<f32> = (0..n_experts).map(|e| prob[e] + bias[e]).collect();
let mut chosen = vec![0usize; top_k];
let mut wsel = vec![0f32; top_k];
let mut wsum = 0f32;
for k in 0..top_k {
let mut bv = f32::NEG_INFINITY; let mut bi = 0;
for e in 0..n_experts { if score[e] > bv { bv = score[e]; bi = e; } }
chosen[k] = bi; wsel[k] = prob[bi]; wsum += prob[bi]; score[bi] = -1e30;
}
let inv = route_scale / (wsum + 1e-20);
for k in 0..top_k { wsel[k] *= inv; }
let mut want = vec![0f32; hidden];
for k in 0..top_k {
let e = chosen[k];
let mut gu = vec![0f32; 2 * inter];
for r in 0..2 * inter {
let w = nvfp4_dequant_row(&w13p[e], &w13s[e], outer, 2 * inter, hidden, r);
gu[r] = w.iter().zip(&mlpin).map(|(a, b)| a * b).sum();
}
let act: Vec<f32> = (0..inter).map(|j| situ_cpu(gu[j], gu[inter + j], beta, lb)).collect();
for d in 0..hidden {
let w = nvfp4_dequant_row(&w2p[e], &w2s[e], outer, hidden, inter, d);
let y: f32 = w.iter().zip(&act).map(|(a, b)| a * b).sum();
want[d] += wsel[k] * y;
}
}
// Device buffers.
let mk = |bytes: usize| DeviceBuf::alloc(bytes).unwrap();
let mlpin_b = mk(hidden * 4); mlpin_b.h2d(&mlpin).unwrap();
let logits_b = mk(n_experts * 4); logits_b.h2d(&logits).unwrap();
let bias_b = mk(n_experts * 4); bias_b.h2d(&bias).unwrap();
let tki_b = mk(top_k * 4);
let tkw_b = mk(top_k * 4);
let gu_b = mk(2 * inter * 4);
let act_b = mk(inter * 4);
let ypart_b = mk(top_k * hidden * 4);
let out_b = mk(hidden * 4);
let w13p_b: Vec<_> = (0..n_experts).map(|e| { let b = mk(w13p[e].len()); b.h2d_bytes(&w13p[e]).unwrap(); b }).collect();
let w13s_b: Vec<_> = (0..n_experts).map(|e| { let b = mk(w13s[e].len()); b.h2d_bytes(&w13s[e]).unwrap(); b }).collect();
let w2p_b: Vec<_> = (0..n_experts).map(|e| { let b = mk(w2p[e].len()); b.h2d_bytes(&w2p[e]).unwrap(); b }).collect();
let w2s_b: Vec<_> = (0..n_experts).map(|e| { let b = mk(w2s[e].len()); b.h2d_bytes(&w2s[e]).unwrap(); b }).collect();
// Router.
let rbuf = vec![&logits_b, &bias_b, &tki_b, &tkw_b];
let router_ops = vec![ExecOp { op: VplanOp::MoeRouterTopk, reads: vec![0, 1], writes: vec![2, 3], params: OpParams::Router { m: 1, n_experts: n_experts as i32, k_top: top_k as i32, route_scale } }];
execute_bufs(&rbuf, &router_ops).unwrap();
let mut tki = vec![0u8; top_k * 4]; tki_b.d2h_bytes(&mut tki).unwrap();
let chosen_dev: Vec<usize> = tki.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) as usize).collect();
assert_eq!(chosen_dev, chosen, "router selection must match oracle");
// Per-expert path into y_part slot k.
for k in 0..top_k {
let e = chosen_dev[k];
let ops = vec![
ExecOp { op: VplanOp::MoeW13Wmma, reads: vec![0, 1, 2], writes: vec![3], params: OpParams::Nvfp4Gemv { n: 2 * inter as i32, k: hidden as i32, outer_scale: outer } },
ExecOp { op: VplanOp::Situ, reads: vec![3], writes: vec![4], params: OpParams::Situ { inter: inter as i32, beta, lb } },
ExecOp { op: VplanOp::MoeW2Wmma, reads: vec![5, 6, 4], writes: vec![7], params: OpParams::Nvfp4Gemv { n: hidden as i32, k: inter as i32, outer_scale: outer } },
];
// w2 output into a single-slot buffer, then assemble y_part on host.
let slot_b = mk(hidden * 4);
let bufs2 = vec![&w13p_b[e], &w13s_b[e], &mlpin_b, &gu_b, &act_b, &w2p_b[e], &w2s_b[e], &slot_b];
execute_bufs(&bufs2, &ops).unwrap();
let mut slot = vec![0f32; hidden]; slot_b.d2h(&mut slot).unwrap();
// upload slot into y_part at offset k (re-upload full y_part).
let mut yp = vec![0f32; top_k * hidden];
if k > 0 { ypart_b.d2h(&mut yp).unwrap(); }
yp[k * hidden..(k + 1) * hidden].copy_from_slice(&slot);
ypart_b.h2d(&yp).unwrap();
}
// Reduce.
let red_bufs = vec![&ypart_b, &tkw_b, &out_b];
let red_ops = vec![ExecOp { op: VplanOp::MoeReduce, reads: vec![0, 1], writes: vec![2], params: OpParams::MoeReduce { top_k: top_k as i32, hidden: hidden as i32 } }];
execute_bufs(&red_bufs, &red_ops).unwrap();
let mut got = vec![0f32; hidden]; out_b.d2h(&mut got).unwrap();
let mut max_rel = 0f32;
for (g, w) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); }
eprintln!("composed MoE expert path max_rel_err={max_rel:.3e}");
assert!(max_rel < 1e-4, "composed MoE parity failed: {max_rel}");
}
/// execute() over borrowed buffers (test helper).
fn execute_bufs(bufs: &[&DeviceBuf], ops: &[ExecOp]) -> Result<(), String> {
execute_refs(bufs, ops)
}
} }