[LD][ABI][Docs] Inkling base decode graph emitter (675 ops, arena-validated) + full forward blueprint

- ld::inkling_graph: emit_decode_base() generates the complete base decode
  forward from the IR over the unrolled physical schedule: embed ->
  [per-layer: norm -> QKV -> flash -> O-proj -> residual-add -> MLP norm ->
  router -> experts w13/w2 -> reduce -> residual-add] -> final norm ->
  unembed. Live-verified on Inkling: 675 ops, 236 arena decls, validated by
  abi::arena (no overlap / checked bounds / no use-before-write). This is
  the structurally-complete base; Inkling parity refinements (learned
  AttnRes block-mix, loop controllers, ShortConv4, relpos, SWA window,
  paged KV) layer on top next.
- abi::vplan: add the Inkling stage opcodes AttnResMix, ShortConv4, LoopCtrl,
  L2Clip, KvStore, RelPosBias, MoeRouterTopk, VecAdd (30 total, roundtrip).
- ld::inkling_ir: LlmComp derives Copy (used by value in the emitter).
- docs/inkling-forward-design.md: full per-layer sequence extracted from
  forward_batch_chunk (k1 AttnRes block-mix + controllers, k2 projections +
  shortconv + relpos + KV store, k3 flash, O-proj block-boundary rule, k4
  sigmoid router + SiTU experts), real scratch buffer set, deep-residual
  block mechanism (block_size=6 snapshots + learned queries).

Verified live: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
5 ignored live tests pass (base graph 675 ops); lean proofs (4 files, 42
theorems) green.
This commit is contained in:
adm committed 2026-12-01 04:39:08 +01:00
1 parent d478787863
commit f57060caa7
4 files changed
+200 -2

No files matched your search

+27
View File
@@ -24,6 +24,15 @@ pub enum VplanOp {
MoeW13Wmma,
MoeW2Wmma,
MoeReduce,
// Inkling-specific stages (docs/inkling-forward-design.md).
AttnResMix,
ShortConv4,
LoopCtrl,
L2Clip,
KvStore,
RelPosBias,
MoeRouterTopk,
VecAdd,
VitFlashAttnWmma,
GpuPenaltiesTopk,
// Encoder lane (M1.5 embedder, docs/ARCHITECTURE.md §4)
@@ -64,6 +73,14 @@ impl VplanOp {
Self::MoeW13Wmma => "moe_w13_wmma",
Self::MoeW2Wmma => "moe_w2_wmma",
Self::MoeReduce => "moe_reduce",
Self::AttnResMix => "attn_res_mix",
Self::ShortConv4 => "shortconv4",
Self::LoopCtrl => "loop_ctrl",
Self::L2Clip => "l2_clip",
Self::KvStore => "kv_store",
Self::RelPosBias => "relpos_bias",
Self::MoeRouterTopk => "moe_router_topk",
Self::VecAdd => "vec_add",
Self::VitFlashAttnWmma => "vit_flash_attn_wmma",
Self::GpuPenaltiesTopk => "gpu_penalties_topk",
Self::LayerNorm => "layer_norm",
@@ -93,6 +110,14 @@ impl VplanOp {
"moe_w13_wmma" => Self::MoeW13Wmma,
"moe_w2_wmma" => Self::MoeW2Wmma,
"moe_reduce" => Self::MoeReduce,
"attn_res_mix" => Self::AttnResMix,
"shortconv4" => Self::ShortConv4,
"loop_ctrl" => Self::LoopCtrl,
"l2_clip" => Self::L2Clip,
"kv_store" => Self::KvStore,
"relpos_bias" => Self::RelPosBias,
"moe_router_topk" => Self::MoeRouterTopk,
"vec_add" => Self::VecAdd,
"vit_flash_attn_wmma" => Self::VitFlashAttnWmma,
"gpu_penalties_topk" => Self::GpuPenaltiesTopk,
"layer_norm" => Self::LayerNorm,
@@ -126,6 +151,8 @@ mod tests {
VplanOp::RopeKvWrite, VplanOp::FlashGqaWmma, VplanOp::GdnChunkwiseWy,
VplanOp::GdnRecurrentStep, VplanOp::MoeRouteBucket, VplanOp::MoeW13Wmma,
VplanOp::MoeW2Wmma, VplanOp::MoeReduce, VplanOp::VitFlashAttnWmma,
VplanOp::AttnResMix, VplanOp::ShortConv4, VplanOp::LoopCtrl, VplanOp::L2Clip,
VplanOp::KvStore, VplanOp::RelPosBias, VplanOp::MoeRouterTopk, VplanOp::VecAdd,
VplanOp::GpuPenaltiesTopk, VplanOp::LayerNorm, VplanOp::FlashFullAttn,
VplanOp::GeluErf, VplanOp::PoolL2norm, VplanOp::LoopLayer, VplanOp::BranchB,
];
+128
View File
@@ -112,6 +112,109 @@ pub fn emit_trunk(ir: &InklingIr, batch: usize) -> Result<(Plan, Vec<GraphOp>),
g.finish()
}
/// Emit the base decode forward skeleton: embed → [per-layer: norm → QKV →
/// flash → O-proj → residual-add → MLP norm → router → experts → reduce →
/// residual-add] → final norm → unembed, over the unrolled physical schedule.
///
/// This is the structurally-complete, arena-validated base graph. The
/// Inkling-specific parity refinements (docs/inkling-forward-design.md) layer
/// on top: the learned AttnRes block-mix replaces the plain residual add,
/// loop controllers gate the core passes, ShortConv4 + relpos + SWA window +
/// paged KV replace the simplified attention. Those are emitted next; this
/// base establishes the buffer/op wiring the arena validator checks.
pub fn emit_decode_base(ir: &InklingIr, batch: usize) -> Result<(Plan, Vec<GraphOp>), String> {
use crate::inkling_ir::{AttnPart, ExpertMat, ExpertPart, RouterPart};
let mut g = GraphBuilder::new();
let b = batch as u64;
let t = &ir.config.text;
let hidden = t.hidden as u64;
let q_dim = (t.n_head * t.head_dim) as u64;
let kv_dim = (t.n_kv * t.head_dim) as u64;
let inter = t.inter as u64;
let vocab = t.vocab as u64;
let n_experts = t.n_experts as u64;
let tok = g.add_buf(ARENA_INPUT, "token_ids", b * 4)?;
g.mark_input(tok);
// Trunk weights.
let trunk_w = |g: &mut GraphBuilder, comp: LlmComp, name: &str| -> Result<usize, String> {
let m = ir.trunk.get(&comp).ok_or_else(|| format!("missing trunk {comp:?}"))?;
let i = g.add_buf(ARENA_WEIGHT, name, m.bytes)?;
g.mark_input(i);
Ok(i)
};
let embed = trunk_w(&mut g, LlmComp::Embed, "w_embed")?;
let embed_norm = trunk_w(&mut g, LlmComp::EmbedNorm, "w_embed_norm")?;
let final_norm = trunk_w(&mut g, LlmComp::FinalNorm, "w_final_norm")?;
let unembed = trunk_w(&mut g, LlmComp::Unembed, "w_unembed")?;
// Per-logical-layer weights (reused across physical loop passes).
struct LW { an: usize, mn: usize, wq: usize, wk: usize, wv: usize, wo: usize, gate: usize, w13: usize, w2: usize }
let mut lw: Vec<LW> = Vec::new();
for l in 0..t.n_layers {
let layer = ir.layer(l).ok_or_else(|| format!("missing layer {l}"))?;
let w = |g: &mut GraphBuilder, comp: LlmComp, name: String| -> Result<usize, String> {
let m = layer.get(comp).ok_or_else(|| format!("layer {l} missing {comp:?}"))?;
let i = g.add_buf(ARENA_WEIGHT, &name, m.bytes)?;
g.mark_input(i);
Ok(i)
};
let an_comp = if layer.is_full_attn { LlmComp::QInputNorm } else { LlmComp::AttnNorm };
lw.push(LW {
an: w(&mut g, an_comp, format!("w{l}_an"))?,
mn: w(&mut g, LlmComp::MlpNorm, format!("w{l}_mn"))?,
wq: w(&mut g, LlmComp::Attn(AttnPart::WqDu), format!("w{l}_wq"))?,
wk: w(&mut g, LlmComp::Attn(AttnPart::WkDv), format!("w{l}_wk"))?,
wv: w(&mut g, LlmComp::Attn(AttnPart::WvDv), format!("w{l}_wv"))?,
wo: w(&mut g, LlmComp::Attn(AttnPart::WoUd), format!("w{l}_wo"))?,
gate: w(&mut g, LlmComp::Router(RouterPart::Weight), format!("w{l}_gate"))?,
w13: w(&mut g, LlmComp::Expert(ExpertMat::W13, ExpertPart::Weight), format!("w{l}_w13"))?,
w2: w(&mut g, LlmComp::Expert(ExpertMat::W2, ExpertPart::Weight), format!("w{l}_w2"))?,
});
}
// Scratch activations.
let residual = g.add_buf(ARENA_SCRATCH, "residual", b * hidden * 4)?;
let norm_out = g.add_buf(ARENA_SCRATCH, "norm_out", b * hidden * 4)?;
let q = g.add_buf(ARENA_SCRATCH, "q", b * q_dim * 4)?;
let k = g.add_buf(ARENA_SCRATCH, "k", b * kv_dim * 4)?;
let v = g.add_buf(ARENA_SCRATCH, "v", b * kv_dim * 4)?;
let aout = g.add_buf(ARENA_SCRATCH, "aout", b * q_dim * 4)?;
let oproj = g.add_buf(ARENA_SCRATCH, "oproj", b * hidden * 4)?;
let mlpin = g.add_buf(ARENA_SCRATCH, "mlpin", b * hidden * 4)?;
let rlog = g.add_buf(ARENA_SCRATCH, "rlog", b * n_experts * 4)?;
let tk_i = g.add_buf(ARENA_SCRATCH, "tk_i", b * t.top_k as u64 * 4)?;
let tk_w = g.add_buf(ARENA_SCRATCH, "tk_w", b * t.top_k as u64 * 4)?;
let act = g.add_buf(ARENA_SCRATCH, "act", b * t.top_k as u64 * inter * 4)?;
let y_part = g.add_buf(ARENA_SCRATCH, "y_part", b * t.top_k as u64 * hidden * 4)?;
let moeout = g.add_buf(ARENA_SCRATCH, "moeout", b * hidden * 4)?;
let logits = g.add_buf(ARENA_SCRATCH, "logits", b * vocab * 4)?;
g.emit(VplanOp::EmbedBf16, &[tok, embed, embed_norm], &[residual]);
for &ip in &crate::inkling_plan::physical_schedule(t) {
let w = &lw[ip];
g.emit(VplanOp::RmsNorm, &[residual, w.an], &[norm_out]);
g.emit(VplanOp::GemmBf16, &[norm_out, w.wq], &[q]);
g.emit(VplanOp::GemmBf16, &[norm_out, w.wk], &[k]);
g.emit(VplanOp::GemmBf16, &[norm_out, w.wv], &[v]);
g.emit(VplanOp::FlashGqaWmma, &[q, k, v], &[aout]);
g.emit(VplanOp::GemmBf16, &[aout, w.wo], &[oproj]);
g.emit(VplanOp::VecAdd, &[residual, oproj], &[residual]);
g.emit(VplanOp::RmsNorm, &[residual, w.mn], &[mlpin]);
g.emit(VplanOp::GemmBf16, &[mlpin, w.gate], &[rlog]);
g.emit(VplanOp::MoeRouterTopk, &[rlog], &[tk_i, tk_w]);
g.emit(VplanOp::MoeW13Wmma, &[mlpin, tk_i, w.w13], &[act]);
g.emit(VplanOp::MoeW2Wmma, &[act, tk_i, w.w2], &[y_part]);
g.emit(VplanOp::MoeReduce, &[y_part, tk_w], &[moeout]);
g.emit(VplanOp::VecAdd, &[residual, moeout], &[residual]);
}
g.emit(VplanOp::RmsNorm, &[residual, final_norm], &[norm_out]);
g.emit(VplanOp::GemmBf16, &[norm_out, unembed], &[logits]);
g.finish()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -198,4 +301,29 @@ mod tests {
g.emit(VplanOp::GemmBf16, &[w], &[out]);
assert!(g.finish().is_ok());
}
#[test]
fn decode_base_valid() {
let (plan, graph) = emit_decode_base(&ir(), 1).unwrap();
// schedule [0,0,1] = 3 physical steps; 1 embed + 14/step + 2 final
assert_eq!(graph.len(), 1 + 14 * 3 + 2);
assert_eq!(graph[0].op, VplanOp::EmbedBf16);
assert_eq!(graph.last().unwrap().op, VplanOp::GemmBf16);
assert!(arena::validate(&plan).is_ok());
}
/// Opt-in live base graph for the real Inkling.
/// `cargo test -p vetta-infer-ld -- --ignored decode_base_live`.
#[test]
#[ignore]
fn decode_base_live() {
let ar = crate::SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
let raw = std::fs::read_to_string("/mnt/models/Inkling/safetensors/config.json").unwrap();
let cfg = crate::inkling::parse_config(&raw).unwrap();
let ir = crate::inkling_ir::assemble_archive(&cfg, &ar).unwrap();
let (plan, graph) = emit_decode_base(&ir, 1).unwrap();
// 48 physical steps -> 1 + 14*48 + 2 = 675 ops
assert_eq!(graph.len(), 675);
eprintln!("Inkling base decode graph: {} ops, {} arena decls", graph.len(), plan.decls.len());
}
}
+1 -1
View File
@@ -82,7 +82,7 @@ pub enum ExpertPart {
OuterScale,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LlmComp {
Embed,
EmbedNorm,