Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/56469317ce5dfc2e # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#874 (code only) closed derived `56469317ce5dfc2e` #874 Imported from GitHub aien-dev/aien-sovereign-core-mv#874 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `4c86d43a7142c8b2f55324140537213b2b64742a` · Head `e3ae7bce1ee3a3f2ce23bb0177adb7f7eb137fab` ### Apply it ``` git checkout -b patch-56469317ce5dfc2e 4c86d43a7142c8b2f55324140537213b2b64742a curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/56469317ce5dfc2e.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 874 e3ae7bce1ee3a3f2ce23bb0177adb7f7eb137fab ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":874,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/874","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:10Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/crates/aien-inference-abi/src/bin/q36_mtp_check.rs b/crates/aien-inference-abi/src/bin/q36_mtp_check.rs new file mode 100644 index 00000000..42cc20aa --- /dev/null +++ b/crates/aien-inference-abi/src/bin/q36_mtp_check.rs @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 Drake Stapleton (AIEN / aien-dev) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! `q36_mtp_check ...` (DRA-70, sc#866). Host only, no chip. +//! +//! Per golden (`prompt_ids` + `generated_ids` from `qwen38_check`): one teacher-forced target pass +//! over the whole sequence gives the target argmax G[i] and post-final-norm hidden H[i]; one +//! teacher-forced MTP pass over (H[i], S[i + 1]) gives the depth-1 draft D[i] for S[i + 2]. +//! Depth-1 acceptance over the generated region counts D[i] == G[i + 1]. Also checks that the +//! target argmax reproduces the golden (sanity) and times one single-row MTP draft step (the CPU +//! reference streams the routed experts from the shards, so this cost includes that read). + +use std::path::PathBuf; +use std::time::Instant; + +use aien_inference_abi::qwen38::mtp::MtpState; +use aien_inference_abi::qwen38::{argmax, Logits, Qwen38Reference}; + +fn ids(v: &serde_json::Value, key: &str) -> Result, String> { + v[key] + .as_array() + .ok_or(format!("no {key}"))? + .iter() + .map(|x| x.as_u64().map(|x| x as u32).ok_or(format!("bad {key}"))) + .collect() +} + +fn main() { + if let Err(e) = run() { + eprintln!("q36_mtp_check: {e}"); + std::process::exit(2); + } +} + +fn run() -> Result<(), String> { + let args: Vec = std::env::args().skip(1).collect(); + if args.len() < 3 { + return Err("usage: q36_mtp_check ...".into()); + } + let (ckpt, out) = (PathBuf::from(&args[0]), PathBuf::from(&args[1])); + let t0 = Instant::now(); + let mut r = Qwen38Reference::open(&ckpt)?; + let w = r.read_mtp()?; + let open_s = t0.elapsed().as_secs_f64(); + let (layers, h, vocab) = (r.config.layers, r.config.hidden, r.config.vocab); + let top_k = r.config.moe.as_ref().map_or(0, |m| m.top_k); + let mut items = Vec::new(); + let (mut acc_all, mut n_all) = (0usize, 0usize); + for g in &args[2..] { + let text = std::fs::read_to_string(g).map_err(|e| format!("{g}: {e}"))?; + let v: serde_json::Value = serde_json::from_str(&text).map_err(|e| format!("{g}: {e}"))?; + let (prompt, gen) = (ids(&v, "prompt_ids")?, ids(&v, "generated_ids")?); + let seq: Vec = prompt.iter().chain(&gen).copied().collect(); + let (pl, l) = (prompt.len(), seq.len()); + let t1 = Instant::now(); + let mut st = r.new_state(); + let mut taps = Vec::new(); + let logits = r.forward_tapped(&mut st, &seq, Logits::All, &[layers], &mut taps)?; + let target_s = t1.elapsed().as_secs_f64(); + let gt: Vec = logits.chunks_exact(vocab).map(|x| argmax(x) as u32).collect(); + // Sanity: the target argmax after S[..pl + j] is the golden's generated token j. + let golden_match = (0..gen.len()).filter(|&j| gt[pl - 1 + j] == gen[j]).count(); + let hid = r.final_hidden(&taps[0]); + // MTP rows i = 0..l-1 pair H[i] with S[i + 1]; the last row has no next token. + let t2 = Instant::now(); + let mut ms = MtpState::default(); + let rows = r.mtp_forward(&w, &mut ms, &hid[..(l - 1) * h], &seq[1..])?; + let mtp_s = t2.elapsed().as_secs_f64(); + let dl = r.lm_head().matmul(&rows, l - 1); + let d: Vec = dl.chunks_exact(vocab).map(|x| argmax(x) as u32).collect(); + // D[i] drafts S[i + 2]; the target's own token there is G[i + 1]. Generated region: + // draft positions where S[i + 2] is a generated token, i + 2 >= pl. + let (mut acc, mut n) = (0usize, 0usize); + for i in pl.saturating_sub(2)..l - 2 { + n += 1; + acc += usize::from(d[i] == gt[i + 1]); + } + // One single-row draft step after the cache holds l - 1 positions (rows the real + // decode would see): MTP layer + full bf16 head. + let mut one = ms.clone(); + one.truncate(l - 2, r.config.kv_dim()); + let t3 = Instant::now(); + let row = r.mtp_forward(&w, &mut one, &hid[(l - 2) * h..(l - 1) * h], &seq[l - 1..])?; + let step_layer_s = t3.elapsed().as_secs_f64(); + let t4 = Instant::now(); + let _ = r.lm_head().matmul(&row, 1); + let step_head_s = t4.elapsed().as_secs_f64(); + acc_all += acc; + n_all += n; + eprintln!( + "{g}: depth-1 {acc}/{n}, golden {golden_match}/{}, target {target_s:.1}s, mtp {mtp_s:.1}s, step {:.0}+{:.0} ms", + gen.len(), + step_layer_s * 1e3, + step_head_s * 1e3 + ); + items.push(serde_json::json!({ + "golden": g, "prompt_len": pl, "generated": gen.len(), + "golden_match": golden_match, "depth1_accepted": acc, "depth1_positions": n, + "target_seconds": target_s, "mtp_seconds": mtp_s, + "draft_step_layer_ms": step_layer_s * 1e3, "draft_step_head_ms": step_head_s * 1e3, + "drafts": d, "target_argmax": gt, + })); + } + let report = serde_json::json!({ + "tool": "q36_mtp_check", "checkpoint": ckpt.display().to_string(), + "open_seconds": open_s, + "mtp_draft_bytes_per_token": w.draft_bytes(top_k, 3_146_112), + "depth1_accepted": acc_all, "depth1_positions": n_all, + "depth1_rate": acc_all as f64 / n_all.max(1) as f64, + "items": items, + }); + std::fs::write(&out, serde_json::to_string_pretty(&report).unwrap()) + .map_err(|e| format!("{}: {e}", out.display()))?; + eprintln!( + "depth-1 acceptance {acc_all}/{n_all} = {:.3}", + acc_all as f64 / n_all.max(1) as f64 + ); + Ok(()) +} diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index 2ae86f7f..31132826 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -43,6 +43,7 @@ pub mod qwen3_moe_omega; pub mod qwen3_moe_omega_dattn; pub mod qwen3_moe_omega_prefill; pub mod resident; +pub mod spec; pub mod strict; pub mod tensor; pub mod tensor_abi; diff --git a/crates/aien-inference-abi/src/qwen38.rs b/crates/aien-inference-abi/src/qwen38.rs index 64a2de63..91967233 100644 --- a/crates/aien-inference-abi/src/qwen38.rs +++ b/crates/aien-inference-abi/src/qwen38.rs @@ -56,6 +56,8 @@ use rayon::prelude::*; use crate::qwen3_moe::{bf16_to_f32, fp8_table, FP8_BLOCK}; use crate::qwen3_moe_omega::{ShardSource, TensorSource}; +pub mod mtp; + /// The text model's shape, read from `config.json` (`text_config` of a `qwen3_5` checkpoint). #[derive(Debug, Clone, PartialEq)] pub struct Qwen38Config { @@ -793,11 +795,17 @@ impl Qwen38Reference { } fn read_layer(&mut self, l: usize) -> Result { - let c = self.config.clone(); let p = format!("{}layers.{l}", self.prefix); + let full = self.config.full_attention[l]; + self.read_layer_at(&p, full) + } + + /// One decoder layer under the tensor prefix `p` (`…layers.{l}` or the MTP's `mtp.layers.0`). + fn read_layer_at(&mut self, p: &str, full_attention: bool) -> Result { + let c = self.config.clone(); let src: &mut dyn TensorSource = &mut self.source; let h = c.hidden; - let mixer = if c.full_attention[l] { + let mixer = if full_attention { let a = format!("{p}.self_attn"); Mixer::Attention(AttentionWeights { q: read_matrix( @@ -857,7 +865,14 @@ impl Qwen38Reference { /// The sparse block over `t` rows of `xn` (post-attention normed): routes every row, reads /// each routed expert of layer `l` once and adds `weight * expert(x)` plus the gated shared /// expert. Records the routed ids in [`Self::routes`]. - fn moe(&mut self, l: usize, w: &MoeWeights, xn: &[f32], t: usize) -> Result, String> { + fn moe( + &mut self, + l: usize, + experts: &str, + w: &MoeWeights, + xn: &[f32], + t: usize, + ) -> Result, String> { let s = self.config.moe.clone().ok_or("moe: dense config")?; let h = self.config.hidden; let (jw, rel) = self.jitter; @@ -924,7 +939,7 @@ impl Qwen38Reference { gates.push(g); } self.shared_g[l] = gates; - let p = format!("{}layers.{l}.mlp.experts", self.prefix); + let p = experts; for (e, rows) in users.iter().enumerate() { if rows.is_empty() { continue; @@ -1017,7 +1032,10 @@ impl Qwen38Reference { rms_norm_zc(&mut xn, &w.post_norm, c.eps); let down = match &w.mlp { Mlp::Dense(f) => f.run(&xn, t), - Mlp::Moe(m) => self.moe(l, m, &xn, t)?, + Mlp::Moe(m) => { + let experts = format!("{}layers.{l}.mlp.experts", self.prefix); + self.moe(l, &experts, m, &xn, t)? + } }; x.iter_mut().zip(&down).for_each(|(a, b)| *a += b); } @@ -1232,7 +1250,7 @@ mod tests { use std::collections::HashMap; /// Deterministic pseudo-random values in [-1, 1). - fn prand(seed: u64, idx: usize) -> f32 { + pub(super) fn prand(seed: u64, idx: usize) -> f32 { let mut x = seed .wrapping_mul(0x9E37_79B9_7F4A_7C15) .wrapping_add(idx as u64 + 1); @@ -1243,9 +1261,9 @@ mod tests { } #[derive(Default)] - struct Mem { - tensors: HashMap, Vec)>, - seed: u64, + pub(super) struct Mem { + pub(super) tensors: HashMap, Vec)>, + pub(super) seed: u64, } impl TensorSource for Mem { @@ -1269,7 +1287,7 @@ mod tests { } impl Mem { - fn bf16(&mut self, name: &str, shape: &[usize], scale: f32, offset: f32) { + pub(super) fn bf16(&mut self, name: &str, shape: &[usize], scale: f32, offset: f32) { self.seed += 1; let n: usize = shape.iter().product(); let bytes = (0..n) @@ -1278,7 +1296,7 @@ mod tests { self.tensors .insert(name.into(), ("BF16".into(), shape.to_vec(), bytes)); } - fn fp8(&mut self, name: &str, n: usize, k: usize) { + pub(super) fn fp8(&mut self, name: &str, n: usize, k: usize) { self.seed += 1; let w = (0..n * k) .map(|i| f32_to_fp8_e4m3fn(prand(self.seed, i) * 8.0)) @@ -1296,7 +1314,7 @@ mod tests { } } - fn tiny() -> Qwen38Config { + pub(super) fn tiny() -> Qwen38Config { Qwen38Config { hidden: 256, layers: 4, @@ -1319,7 +1337,7 @@ mod tests { } } - fn tiny_moe() -> Qwen38Config { + pub(super) fn tiny_moe() -> Qwen38Config { Qwen38Config { intermediate: 0, moe: Some(MoeShape { @@ -1332,7 +1350,7 @@ mod tests { } } - fn tiny_source(c: &Qwen38Config) -> Mem { + pub(super) fn tiny_source(c: &Qwen38Config) -> Mem { let mut m = Mem::default(); let (h, p) = (c.hidden, "model.language_model."); m.bf16(&format!("{p}embed_tokens.weight"), &[c.vocab, h], 1.0, 0.0); @@ -1618,7 +1636,9 @@ mod tests { let xn: Vec = (0..t * h).map(|i| prand(77, i)).collect(); let w = r.read_layer(0).unwrap(); let Mlp::Moe(m) = &w.mlp else { panic!() }; - let got = r.moe(0, m, &xn, t).unwrap(); + let got = r + .moe(0, "model.language_model.layers.0.mlp.experts", m, &xn, t) + .unwrap(); let p = "model.language_model.layers.0.mlp"; let lut = fp8_table(); let wide = |src: &mut Mem, name: &str, n: usize, k: usize| -> Vec { diff --git a/crates/aien-inference-abi/src/qwen38/mtp.rs b/crates/aien-inference-abi/src/qwen38/mtp.rs new file mode 100644 index 00000000..61328e02 --- /dev/null +++ b/crates/aien-inference-abi/src/qwen38/mtp.rs @@ -0,0 +1,365 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 Drake Stapleton (AIEN / aien-dev) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The checkpoint's multi-token-prediction (MTP) layer on the host reference (DRA-70, sc#866). +//! +//! Qwen3.6-35B-A3B ships one MTP layer (`mtp_num_hidden_layers` 1) under `mtp.*` +//! (`mtp.safetensors`). Ground truth for the maths is vLLM `qwen3_next_mtp.py` +//! (`Qwen3NextMultiTokenPredictor.forward`): +//! +//! ```text +//! e = pre_fc_norm_embedding(embed_tokens(tok[i + 1])) zero-centred RMSNorm +//! g = pre_fc_norm_hidden(h[i]) h = the target's post-final-norm row +//! x = fc(cat[e, g]) bf16 [hidden][2 * hidden], no bias +//! x = decoder layer mtp.layers.0 (full attention + MoE, residual starts at x), position i +//! m = mtp.norm(x) the draft row; lm_head(m) drafts tok[i + 2] +//! ``` +//! +//! The layer has no own embedding or head (`embed_tokens` and `lm_head` are the target's). A chain +//! of k drafts feeds `m` back as the next `h` with the drafted token, one position further. The MTP +//! keeps its own attention cache ([`MtpState`]), filled teacher-forced over the prompt and the +//! accepted tokens. Its MoE routes are recorded at index `config.layers` (one past the target's). + +use super::*; + +/// Tensor prefix of the MTP decoder layer. +pub const MTP_LAYER: &str = "mtp.layers.0"; + +/// The MTP block as read: the fc projection, its two input norms, the output norm and one +/// full-attention MoE decoder layer. +pub struct MtpWeights { + fc: Matrix, + pre_embed: Vec, + pre_hidden: Vec, + norm: Vec, + layer: LayerWeights, +} + +impl MtpWeights { + /// Bytes the layer streams per drafted token when every routed expert is distinct: + /// fc + attention + router + shared expert + `top_k` experts (the head is counted apart). + pub fn draft_bytes(&self, top_k: usize, expert_bytes: usize) -> usize { + let m = |x: &Matrix| match x { + Matrix::Fp8 { w, scales, .. } => w.len() + 2 * scales.len(), + Matrix::Bf16 { w, .. } => 2 * w.len(), + }; + let mut b = m(&self.fc); + if let Mixer::Attention(a) = &self.layer.mixer { + b += m(&a.q) + m(&a.k) + m(&a.v) + m(&a.o); + } + if let Mlp::Moe(w) = &self.layer.mlp { + b += m(&w.router) + m(&w.shared.gate) + m(&w.shared.up) + m(&w.shared.down); + } + b + top_k * expert_bytes + } +} + +/// The MTP layer's attention cache between calls. +#[derive(Debug, Clone, Default)] +pub struct MtpState { + /// Next position (the MTP row for target position i sits at position i). + pub pos: usize, + k: Vec, + v: Vec, +} + +impl MtpState { + /// Drops every cached position at or past `pos` (rollback after a rejected draft). + pub fn truncate(&mut self, pos: usize, kv_dim: usize) { + if pos < self.pos { + self.k.truncate(pos * kv_dim); + self.v.truncate(pos * kv_dim); + self.pos = pos; + } + } +} + +impl Qwen38Reference { + /// Reads the MTP block (`mtp.*`). The 35B layer is a full-attention MoE layer. + pub fn read_mtp(&mut self) -> Result { + let h = self.config.hidden; + if self.config.moe.is_none() { + return Err("mtp: the config is dense (the 35B MTP layer is MoE)".into()); + } + let src: &mut dyn TensorSource = &mut self.source; + let fc = read_matrix(src, "mtp.fc.weight", h, 2 * h)?; + let pre_embed = read_vec(src, "mtp.pre_fc_norm_embedding.weight", h)?; + let pre_hidden = read_vec(src, "mtp.pre_fc_norm_hidden.weight", h)?; + let norm = read_vec(src, "mtp.norm.weight", h)?; + let layer = self.read_layer_at(MTP_LAYER, true)?; + Ok(MtpWeights { + fc, + pre_embed, + pre_hidden, + norm, + layer, + }) + } + + /// Embedding rows of `tokens`, `[t][hidden]`. + pub fn embed_rows(&self, tokens: &[u32]) -> Result, String> { + let (v, h) = (self.config.vocab, self.config.hidden); + let mut x = Vec::with_capacity(tokens.len() * h); + for &tok in tokens { + let tok = tok as usize; + if tok >= v { + return Err(format!("embed: token {tok} outside the vocab {v}")); + } + x.extend(self.embed[tok * h..(tok + 1) * h].iter().map(|&b| bf16_to_f32(b))); + } + Ok(x) + } + + /// The MTP block over `t` rows: row i pairs the target's post-final-norm `hidden[i]` with + /// `tokens[i]` (the token after it) at position `state.pos + i`. Returns the rows after + /// `mtp.norm`, `[t][hidden]` (multiply by the head for the draft logits). + pub fn mtp_forward( + &mut self, + w: &MtpWeights, + state: &mut MtpState, + hidden: &[f32], + tokens: &[u32], + ) -> Result, String> { + let c = self.config.clone(); + let (t, h) = (tokens.len(), c.hidden); + if t == 0 || hidden.len() != t * h { + return Err(format!( + "mtp: {t} tokens with {} hidden values (want {})", + hidden.len(), + t * h + )); + } + let mut e = self.embed_rows(tokens)?; + rms_norm_zc(&mut e, &w.pre_embed, c.eps); + let mut g = hidden.to_vec(); + rms_norm_zc(&mut g, &w.pre_hidden, c.eps); + let mut cat = Vec::with_capacity(2 * t * h); + for (er, gr) in e.chunks_exact(h).zip(g.chunks_exact(h)) { + cat.extend_from_slice(er); + cat.extend_from_slice(gr); + } + let mut x = w.fc.matmul(&cat, t); + let mut xn = x.clone(); + rms_norm_zc(&mut xn, &w.layer.input_norm, c.eps); + let Mixer::Attention(a) = &w.layer.mixer else { + return Err("mtp: the layer is not full attention".into()); + }; + let mixed = attention(&c, a, &xn, t, state.pos, &mut state.k, &mut state.v); + x.iter_mut().zip(&mixed).for_each(|(a, b)| *a += b); + let mut xn = x.clone(); + rms_norm_zc(&mut xn, &w.layer.post_norm, c.eps); + let Mlp::Moe(m) = &w.layer.mlp else { + return Err("mtp: the layer is not MoE".into()); + }; + let down = self.moe(c.layers, &format!("{MTP_LAYER}.mlp.experts"), m, &xn, t)?; + x.iter_mut().zip(&down).for_each(|(a, b)| *a += b); + state.pos += t; + rms_norm_zc(&mut x, &w.norm, c.eps); + Ok(x) + } + + /// The lm_head rows `ids` (ascending, unique) as their own bf16 matrix: the truncated draft + /// head. Logit j of it is the full head's logit `ids[j]`, bit for bit. + pub fn head_rows(&self, ids: &[u32]) -> Result { + let (v, h) = (self.config.vocab, self.config.hidden); + if ids.windows(2).any(|p| p[0] >= p[1]) || ids.last().is_some_and(|&l| l as usize >= v) { + return Err(format!("head_rows: ids not ascending within 0..{v}")); + } + let mut w = Vec::with_capacity(ids.len() * h); + for &id in ids { + let row = self + .lm_head + .bf16_row(id as usize) + .ok_or("head_rows: the lm_head is not bf16")?; + w.extend_from_slice(row); + } + Ok(Matrix::Bf16 { + n: ids.len(), + k: h, + w, + }) + } +} + +#[cfg(test)] +mod tests { + use super::super::tests::{tiny_moe, tiny_source, Mem}; + use super::*; + use crate::qwen3_moe::f32_to_bf16; + + /// A one-layer full-attention MoE target whose MTP layer is a copy of layer 0, `mtp.norm` a + /// copy of the final norm, and `fc` the given `[hidden][2 * hidden]` matrix. + fn mirrored(fc: impl Fn(usize, usize) -> f32) -> (Qwen38Config, Mem) { + let c = Qwen38Config { + layers: 1, + full_attention: vec![true], + ..tiny_moe() + }; + let mut m = tiny_source(&c); + let h = c.hidden; + let p = "model.language_model."; + // Unit-RMS embedding rows, so the MTP's pre-fc norm (w = 0) leaves them as the target + // embeds them (to bf16 rounding). + let (d, s, b) = m.tensors[&format!("{p}embed_tokens.weight")].clone(); + let mut rows: Vec = b + .chunks_exact(2) + .map(|x| bf16_to_f32(u16::from_le_bytes([x[0], x[1]]))) + .collect(); + for r in rows.chunks_exact_mut(h) { + let rms = (r.iter().map(|v| v * v).sum::() / h as f32).sqrt(); + r.iter_mut().for_each(|v| *v /= rms); + } + let bytes = rows + .iter() + .flat_map(|&v| f32_to_bf16(v).to_le_bytes()) + .collect(); + m.tensors + .insert(format!("{p}embed_tokens.weight"), (d, s, bytes)); + let names: Vec = m + .tensors + .keys() + .filter(|k| k.starts_with(&format!("{p}layers.0."))) + .cloned() + .collect(); + for k in names { + let t = m.tensors[&k].clone(); + m.tensors + .insert(k.replace(&format!("{p}layers.0"), MTP_LAYER), t); + } + let norm = m.tensors[&format!("{p}norm.weight")].clone(); + m.tensors.insert("mtp.norm.weight".into(), norm); + let zeros = |n: usize| ("BF16".to_string(), vec![n], vec![0u8; 2 * n]); + m.tensors + .insert("mtp.pre_fc_norm_embedding.weight".into(), zeros(h)); + m.tensors + .insert("mtp.pre_fc_norm_hidden.weight".into(), zeros(h)); + let fcw = (0..h * 2 * h) + .flat_map(|i| f32_to_bf16(fc(i / (2 * h), i % (2 * h))).to_le_bytes()) + .collect(); + m.tensors + .insert("mtp.fc.weight".into(), ("BF16".into(), vec![h, 2 * h], fcw)); + (c, m) + } + + fn max_rel(a: &[f32], b: &[f32]) -> f32 { + let scale = b.iter().fold(0f32, |m, v| m.max(v.abs())); + a.iter() + .zip(b) + .fold(0f32, |m, (x, y)| m.max((x - y).abs())) + / scale + } + + /// With fc = [I | 0] the MTP block is the one-layer target fed the (normed) embedding, so its + /// head logits match the target's: proves the concat order (embedding first), the layer + /// wiring, the positions and `mtp.norm`. + #[test] + fn identity_fc_reproduces_the_target() { + let (c, m) = mirrored(|r, col| if r == col { 1.0 } else { 0.0 }); + let h = c.hidden; + let mut r = Qwen38Reference::new(c.clone(), m).unwrap(); + let toks = [3u32, 17, 5, 60, 9]; + let mut st = r.new_state(); + let want = r.forward(&mut st, &toks, Logits::All).unwrap(); + let w = r.read_mtp().unwrap(); + let mut ms = MtpState::default(); + let junk: Vec = (0..toks.len() * h).map(|i| (i % 7) as f32 - 3.0).collect(); + let rows = r.mtp_forward(&w, &mut ms, &junk, &toks).unwrap(); + let got = r.lm_head().matmul(&rows, toks.len()); + let e = max_rel(&got, &want); + assert!(e < 2e-2, "mtp vs target logits: max rel {e}"); + for (g, t) in got.chunks_exact(c.vocab).zip(want.chunks_exact(c.vocab)) { + assert_eq!(argmax(g), argmax(t)); + } + assert_eq!(ms.pos, toks.len()); + assert_eq!(r.routes.len(), c.layers + 1, "MTP routes recorded past the target's"); + } + + /// Negative control: fc = [0 | I] reads the hidden half instead; the logits must move. + #[test] + fn swapped_concat_does_not_reproduce_the_target() { + let (c, m) = mirrored(|r, col| if col == r + 256 { 1.0 } else { 0.0 }); + let h = c.hidden; + let mut r = Qwen38Reference::new(c.clone(), m).unwrap(); + let toks = [3u32, 17, 5, 60, 9]; + let mut st = r.new_state(); + let want = r.forward(&mut st, &toks, Logits::All).unwrap(); + let w = r.read_mtp().unwrap(); + let junk: Vec = (0..toks.len() * h).map(|i| (i % 7) as f32 - 3.0).collect(); + let rows = r + .mtp_forward(&w, &mut MtpState::default(), &junk, &toks) + .unwrap(); + let got = r.lm_head().matmul(&rows, toks.len()); + assert!(max_rel(&got, &want) > 0.1); + } + + /// One call over t rows equals t calls of one row (the attention cache carries positions), + /// and truncate + replay restores the same rows (draft rollback). + #[test] + fn rows_one_call_equals_row_by_row_and_rollback_replays() { + let (c, m) = mirrored(|r, col| ((r * 31 + col * 7) % 13) as f32 / 64.0 - 0.09); + let h = c.hidden; + let mut r = Qwen38Reference::new(c.clone(), m).unwrap(); + let w = r.read_mtp().unwrap(); + let toks = [1u32, 2, 40, 33]; + let hid: Vec = (0..toks.len() * h) + .map(|i| ((i * 13) % 17) as f32 / 8.0 - 1.0) + .collect(); + let all = r + .mtp_forward(&w, &mut MtpState::default(), &hid, &toks) + .unwrap(); + let mut st = MtpState::default(); + let mut one = Vec::new(); + for i in 0..toks.len() { + one.extend( + r.mtp_forward(&w, &mut st, &hid[i * h..(i + 1) * h], &toks[i..i + 1]) + .unwrap(), + ); + } + assert!(max_rel(&one, &all) < 1e-5); + st.truncate(2, c.kv_dim()); + let again = r + .mtp_forward(&w, &mut st, &hid[2 * h..], &toks[2..]) + .unwrap(); + assert_eq!(&again[..], &one[2 * h..], "replay after rollback is bit-identical"); + } + + #[test] + fn head_rows_are_the_full_head_logits() { + let (c, m) = mirrored(|r, col| if r == col { 1.0 } else { 0.0 }); + let r = Qwen38Reference::new(c.clone(), m).unwrap(); + let ids = [0u32, 5, 9, 63]; + let sub = r.head_rows(&ids).unwrap(); + let x: Vec = (0..c.hidden).map(|i| (i % 5) as f32 - 2.0).collect(); + let full = r.lm_head().matmul(&x, 1); + let part = sub.matmul(&x, 1); + for (j, &id) in ids.iter().enumerate() { + assert_eq!(part[j].to_bits(), full[id as usize].to_bits()); + } + assert!(r.head_rows(&[5, 5]).is_err()); + assert!(r.head_rows(&[64]).is_err()); + } + + #[test] + fn refuses_a_misshapen_fc() { + let (c, mut m) = mirrored(|_, _| 0.0); + let h = c.hidden; + m.tensors.insert( + "mtp.fc.weight".into(), + ("BF16".into(), vec![h, h], vec![0u8; 2 * h * h]), + ); + let mut r = Qwen38Reference::new(c, m).unwrap(); + assert!(r.read_mtp().is_err()); + } +} diff --git a/crates/aien-inference-abi/src/spec.rs b/crates/aien-inference-abi/src/spec.rs new file mode 100644 index 00000000..6cafb03e --- /dev/null +++ b/crates/aien-inference-abi/src/spec.rs @@ -0,0 +1,306 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 Drake Stapleton (AIEN / aien-dev) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Speculative decoding bookkeeping shared by the MTP drafter (DRA-70, sc#866) and the CPU +//! suffix drafter (DRA-77, sc#867): the truncated draft vocabulary, the greedy and the sampled +//! acceptance rules, and the expected-length model. +//! +//! One verify step feeds the last accepted token plus k drafts (N = 1 + k rows) through the +//! target and gets k + 1 target tokens back. +//! +//! - Greedy: the longest prefix where `draft[j] == target[j]` is kept, then `target[a]` (the +//! target's own next token after the accepted prefix). Output is token-identical to plain greedy +//! decoding by construction: every emitted token is a target argmax. +//! - Sampled (Leviathan et al. 2023, Chen et al. 2023): draft x with draft probability q(x) is +//! kept with probability `min(1, p(x) / q(x))`; on rejection the token is drawn from +//! `max(0, p - q)` renormalised. The emitted token is distributed exactly as p. A truncated draft +//! head only makes q zero outside the draft vocabulary; the rule and its exactness are unchanged. + +use std::path::Path; + +use sha2::{Digest, Sha256}; + +/// The draft head's vocabulary: ascending unique target token ids. +#[derive(Debug, Clone, PartialEq)] +pub struct DraftVocab { + ids: Vec, + /// `slot[id]` = position of `id` in `ids`, or `u32::MAX` when absent. + slot: Vec, +} + +impl DraftVocab { + /// `ids` in any order, each below `vocab`, no repeats. + pub fn new(mut ids: Vec, vocab: usize) -> Result { + ids.sort_unstable(); + if ids.windows(2).any(|p| p[0] == p[1]) { + return Err("draft vocab: repeated id".into()); + } + if ids.last().is_some_and(|&l| l as usize >= vocab) { + return Err(format!("draft vocab: id outside the vocab {vocab}")); + } + let mut slot = vec![u32::MAX; vocab]; + for (j, &id) in ids.iter().enumerate() { + slot[id as usize] = j as u32; + } + Ok(Self { ids, slot }) + } + + /// Reads `{"vocab": V, "ids": [...]}` (the `q36_draft_vocab` output) and checks its + /// `ids_sha256` when present. + pub fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + let v: serde_json::Value = + serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; + let vocab = v["vocab"].as_u64().ok_or("draft vocab: no \"vocab\"")? as usize; + let ids = v["ids"] + .as_array() + .ok_or("draft vocab: no \"ids\"")? + .iter() + .map(|x| x.as_u64().map(|x| x as u32).ok_or("draft vocab: bad id")) + .collect::, _>>()?; + let dv = Self::new(ids, vocab)?; + if let Some(want) = v["ids_sha256"].as_str() { + if want != dv.sha256_hex() { + return Err(format!( + "draft vocab: ids_sha256 {want} but the ids hash to {}", + dv.sha256_hex() + )); + } + } + Ok(dv) + } + + pub fn ids(&self) -> &[u32] { + &self.ids + } + + pub fn len(&self) -> usize { + self.ids.len() + } + + pub fn is_empty(&self) -> bool { + self.ids.is_empty() + } + + pub fn contains(&self, id: u32) -> bool { + self.slot(id).is_some() + } + + /// Row of `id` in the truncated head. + pub fn slot(&self, id: u32) -> Option { + match self.slot.get(id as usize) { + Some(&s) if s != u32::MAX => Some(s as usize), + _ => None, + } + } + + /// sha256 of the ids as little-endian u32, ascending (the identity of the head's row set). + pub fn sha256_hex(&self) -> String { + let mut h = Sha256::new(); + for id in &self.ids { + h.update(id.to_le_bytes()); + } + h.finalize().iter().map(|b| format!("{b:02x}")).collect() + } + + /// Argmax over the truncated head's logits (`[len]`) as a target token id (first on ties). + pub fn argmax(&self, logits: &[f32]) -> u32 { + assert_eq!(logits.len(), self.ids.len()); + self.ids[crate::qwen38::argmax(logits)] + } +} + +/// Greedy verify: `drafts` (k) against `target` (k + 1 target argmaxes, row j being the target's +/// token after the accepted prefix plus `drafts[..j]`). Returns the accepted draft count a; the +/// step emits `drafts[..a]` and then `target[a]`. +pub fn greedy_accept(drafts: &[u32], target: &[u32]) -> usize { + assert_eq!(target.len(), drafts.len() + 1, "greedy_accept: want k + 1 target rows"); + drafts + .iter() + .zip(target) + .take_while(|(d, t)| d == t) + .count() +} + +/// The sampled rule for one draft token: `p` and `q` are the target and draft distributions over +/// the full vocabulary (q zero outside the draft vocab), `u` a uniform draw in [0, 1). `Ok(())` +/// keeps the draft; `Err(residual)` rejects it and gives `max(0, p - q)` renormalised to draw the +/// replacement from. +pub fn sampled_accept(p: &[f64], q: &[f64], draft: usize, u: f64) -> Result<(), Vec> { + assert_eq!(p.len(), q.len()); + let (pd, qd) = (p[draft], q[draft]); + if qd > 0.0 && u < (pd / qd).min(1.0) { + return Ok(()); + } + let mut r: Vec = p.iter().zip(q).map(|(a, b)| (a - b).max(0.0)).collect(); + let s: f64 = r.iter().sum(); + if s > 0.0 { + r.iter_mut().for_each(|x| *x /= s); + } else { + // p == q: the rejection branch has probability zero; fall back to p itself. + r.copy_from_slice(p); + } + Err(r) +} + +/// Probability that a draft drawn from q survives against p: `sum_x min(p(x), q(x))`. +pub fn acceptance_rate(p: &[f64], q: &[f64]) -> f64 { + p.iter().zip(q).map(|(a, b)| a.min(*b)).sum() +} + +/// Expected tokens emitted per verify step with conditional acceptance `alpha[j]` at depth j + 1 +/// (draft j + 1 kept given drafts 1..=j kept): `1 + a1 + a1 a2 + ... + a1..ak`. +pub fn expected_tokens(alpha: &[f64]) -> f64 { + let mut e = 1.0; + let mut run = 1.0; + for a in alpha { + run *= a; + e += run; + } + e +} + +/// Softmax of `logits` in f64. +pub fn softmax(logits: &[f32]) -> Vec { + let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max) as f64; + let mut p: Vec = logits.iter().map(|&v| (v as f64 - max).exp()).collect(); + let s: f64 = p.iter().sum(); + p.iter_mut().for_each(|x| *x /= s); + p +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn greedy_keeps_the_matching_prefix() { + assert_eq!(greedy_accept(&[5, 6, 7], &[5, 6, 7, 8]), 3); + assert_eq!(greedy_accept(&[5, 9, 7], &[5, 6, 7, 8]), 1); + assert_eq!(greedy_accept(&[1, 6, 7], &[5, 6, 7, 8]), 0); + assert_eq!(greedy_accept(&[], &[4]), 0); + } + + #[test] + fn expected_tokens_matches_the_series() { + assert_eq!(expected_tokens(&[]), 1.0); + // The DRA-70 issue's NVFP4 per-position rates 0.86 / 0.67 / 0.55 read as conditional. + let e = expected_tokens(&[0.86, 0.67, 0.55]); + assert!((e - (1.0 + 0.86 + 0.86 * 0.67 + 0.86 * 0.67 * 0.55)).abs() < 1e-12); + } + + /// Exactness of the sampled rule with a truncated draft (q zero off its vocab): the law of the + /// emitted token is p, computed in closed form from the rule's own branches. + #[test] + fn sampled_rule_emits_the_target_law_with_a_truncated_draft() { + let p = [0.30f64, 0.25, 0.20, 0.15, 0.10]; + // Draft vocab {0, 1, 3}: q is the draft's softmax renormalised over those ids. + let q = [0.50, 0.10, 0.0, 0.40, 0.0]; + let mut out = [0f64; 5]; + for (x, &qx) in q.iter().enumerate() { + if qx == 0.0 { + continue; + } + let keep = (p[x] / qx).min(1.0); + out[x] += qx * keep; + let r = sampled_accept(&p, &q, x, 1.0).unwrap_err(); + for (o, rv) in out.iter_mut().zip(&r) { + *o += qx * (1.0 - keep) * rv; + } + } + for (o, pv) in out.iter().zip(&p) { + assert!((o - pv).abs() < 1e-12, "{out:?} vs {p:?}"); + } + let a = acceptance_rate(&p, &q); + assert!((a - (0.30 + 0.10 + 0.15)).abs() < 1e-12); + } + + /// Same law by sampling (deterministic generator), so the branch logic is exercised and not + /// only the arithmetic. + #[test] + fn sampled_rule_by_draws() { + let p = [0.30f64, 0.25, 0.20, 0.15, 0.10]; + let q = [0.50, 0.10, 0.0, 0.40, 0.0]; + let mut s = 0x2545_F491_4F6C_DD1Du64; + let mut uni = || { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + (s >> 11) as f64 / (1u64 << 53) as f64 + }; + let draw = |d: &[f64], u: f64| { + let mut c = 0.0; + for (i, v) in d.iter().enumerate() { + c += v; + if u < c { + return i; + } + } + d.len() - 1 + }; + let n = 400_000; + let mut hist = [0usize; 5]; + for _ in 0..n { + let x = draw(&q, uni()); + let tok = match sampled_accept(&p, &q, x, uni()) { + Ok(()) => x, + Err(r) => draw(&r, uni()), + }; + hist[tok] += 1; + } + for (h, pv) in hist.iter().zip(&p) { + let f = *h as f64 / n as f64; + // 5 sigma of a binomial proportion at n = 400k is below 0.0037. + assert!((f - pv).abs() < 0.004, "{hist:?}"); + } + } + + /// Negative control: dropping the residual (re-drawing from p on rejection) is biased. + #[test] + fn redraw_from_p_on_rejection_is_biased() { + let p = [0.30f64, 0.25, 0.20, 0.15, 0.10]; + let q = [0.50, 0.10, 0.0, 0.40, 0.0]; + let mut out = [0f64; 5]; + for (x, &qx) in q.iter().enumerate() { + if qx == 0.0 { + continue; + } + let keep = (p[x] / qx).min(1.0); + out[x] += qx * keep; + for (o, pv) in out.iter_mut().zip(&p) { + *o += qx * (1.0 - keep) * pv; + } + } + assert!(out.iter().zip(&p).any(|(o, pv)| (o - pv).abs() > 0.01)); + } + + #[test] + fn draft_vocab_slots_and_hash() { + let v = DraftVocab::new(vec![9, 2, 5], 10).unwrap(); + assert_eq!(v.ids(), &[2, 5, 9]); + assert_eq!(v.slot(5), Some(1)); + assert_eq!(v.slot(3), None); + assert_eq!(v.slot(99), None); + assert_eq!(v.argmax(&[0.0, 3.0, 1.0]), 5); + assert!(DraftVocab::new(vec![1, 1], 10).is_err()); + assert!(DraftVocab::new(vec![10], 10).is_err()); + let w = DraftVocab::new(vec![2, 5, 9], 10).unwrap(); + assert_eq!(v.sha256_hex(), w.sha256_hex()); + assert_ne!( + v.sha256_hex(), + DraftVocab::new(vec![2, 5, 8], 10).unwrap().sha256_hex() + ); + } +} ```