From d4787878637cb8d568ce8c0e6d30ef980f505aab Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Tue, 1 Dec 2026 04:35:46 +0100 Subject: [PATCH] [LD][ABI] Inkling plan foundations: physical schedule + scratch arenas + graph emitter (trunk) - ld::inkling_plan: physical_schedule() unrolls the looped core (verified against the reference logical->physical mapping; Inkling = 6 + 3x12 + 6 = 48 physical steps over 24 logical layers). scratch_layout()/scratch_plan() lay out the decode activation arenas (residual/q/k/v/attn_out/moe/logits), 4 KiB-aligned with checked offsets, validated by abi::arena. - ld::inkling_graph: GraphBuilder accumulates arena decls (scratch=0, weights=1, inputs=2) + a flat op sequence and validates the whole plan (no overlap, checked bounds, no use-before-write) via abi::arena. emit_trunk() emits the first complete sub-graph: embed(+embed_norm fused) -> final norm -> unembed, arena-validated. The per-layer k1->k4 body plugs into the same builder next. - abi::vplan: add GemmBf16 opcode (BF16 trunk/unembed GEMM). - docs/inkling-forward-design.md: forward blueprint grounded in the strata reference (k1->k4 stage order from kernel numbering, real scratch buffer set, loop structure, two forward paths main-LLM + MTP DSpark). Verified live: RUSTFLAGS="-D warnings" cargo test --workspace = 96/96 PASS; 4 ignored live tests pass; lean proofs (4 files, 42 theorems) green. --- crates/vetta-infer-abi/src/vplan.rs | 5 +- crates/vetta-infer-ld/src/inkling_graph.rs | 201 +++++++++++++++++++++ crates/vetta-infer-ld/src/inkling_plan.rs | 195 ++++++++++++++++++++ crates/vetta-infer-ld/src/lib.rs | 2 + docs/inkling-forward-design.md | 57 ++++++ 5 files changed, 459 insertions(+), 1 deletion(-) create mode 100644 crates/vetta-infer-ld/src/inkling_graph.rs create mode 100644 crates/vetta-infer-ld/src/inkling_plan.rs create mode 100644 docs/inkling-forward-design.md diff --git a/crates/vetta-infer-abi/src/vplan.rs b/crates/vetta-infer-abi/src/vplan.rs index 55e19cc..c88c96c 100644 --- a/crates/vetta-infer-abi/src/vplan.rs +++ b/crates/vetta-infer-abi/src/vplan.rs @@ -15,6 +15,7 @@ pub enum VplanOp { GemmQ8G64T16, GemmQ4G64T16, GemmNvfp4Mxfp8, + GemmBf16, RopeKvWrite, FlashGqaWmma, GdnChunkwiseWy, @@ -54,6 +55,7 @@ impl VplanOp { Self::GemmQ8G64T16 => "gemm_q8_g64_t16", Self::GemmQ4G64T16 => "gemm_q4_g64_t16", Self::GemmNvfp4Mxfp8 => "gemm_nvfp4_mxfp8", + Self::GemmBf16 => "gemm_bf16", Self::RopeKvWrite => "rope_kv_write", Self::FlashGqaWmma => "flash_gqa_wmma", Self::GdnChunkwiseWy => "gdn_chunkwise_wy", @@ -82,6 +84,7 @@ impl VplanOp { "gemm_q8_g64_t16" => Self::GemmQ8G64T16, "gemm_q4_g64_t16" => Self::GemmQ4G64T16, "gemm_nvfp4_mxfp8" => Self::GemmNvfp4Mxfp8, + "gemm_bf16" => Self::GemmBf16, "rope_kv_write" => Self::RopeKvWrite, "flash_gqa_wmma" => Self::FlashGqaWmma, "gdn_chunkwise_wy" => Self::GdnChunkwiseWy, @@ -119,7 +122,7 @@ mod tests { fn name_roundtrip_all_opcodes() { let all = [ VplanOp::EmbedBf16, VplanOp::RmsNorm, VplanOp::QuantizeXG64, - VplanOp::GemmQ8G64T16, VplanOp::GemmQ4G64T16, VplanOp::GemmNvfp4Mxfp8, + VplanOp::GemmQ8G64T16, VplanOp::GemmQ4G64T16, VplanOp::GemmNvfp4Mxfp8, VplanOp::GemmBf16, VplanOp::RopeKvWrite, VplanOp::FlashGqaWmma, VplanOp::GdnChunkwiseWy, VplanOp::GdnRecurrentStep, VplanOp::MoeRouteBucket, VplanOp::MoeW13Wmma, VplanOp::MoeW2Wmma, VplanOp::MoeReduce, VplanOp::VitFlashAttnWmma, diff --git a/crates/vetta-infer-ld/src/inkling_graph.rs b/crates/vetta-infer-ld/src/inkling_graph.rs new file mode 100644 index 0000000..2634109 --- /dev/null +++ b/crates/vetta-infer-ld/src/inkling_graph.rs @@ -0,0 +1,201 @@ +//! Inkling `graph.vplan` emitter (docs/inkling-forward-design.md). +//! +//! `GraphBuilder` accumulates arena declarations (scratch + weights + inputs) +//! and a flat op sequence, then validates the whole plan with `abi::arena` +//! (proof `arena_plan.lean`): no overlap, checked bounds, no use-before-write. +//! Weights live in arena 1 (mapped from `.vbundle/weights/*.vbin`), scratch in +//! arena 0, token inputs in arena 2. The first emitted sub-graph is the trunk +//! (embed → final norm → unembed); the per-layer k1→k4 body plugs into the same +//! builder following the verified stage order. + +use std::collections::HashMap; + +use crate::inkling_ir::{InklingIr, LlmComp}; +use vetta_infer_abi::arena::{self, Decl, Op, Plan}; +use vetta_infer_abi::bundle::GraphOp; +use vetta_infer_abi::vplan::VplanOp; +use vetta_infer_abi::vtc1::{align_up, CACHE_ALIGN}; + +const ARENA_SCRATCH: u32 = 0; +const ARENA_WEIGHT: u32 = 1; +const ARENA_INPUT: u32 = 2; + +#[derive(Default)] +pub struct GraphBuilder { + decls: Vec, + index: HashMap, + ops: Vec, + inputs: Vec, + cursor: [u64; 3], +} + +impl GraphBuilder { + pub fn new() -> Self { + Self::default() + } + + /// Declare a buffer (4 KiB-aligned, checked offset) and return its index. + pub fn add_buf(&mut self, arena: u32, name: &str, bytes: u64) -> Result { + if self.index.contains_key(name) { + return Err(format!("duplicate buffer '{name}'")); + } + let a = arena as usize; + let len = align_up(bytes.max(1), CACHE_ALIGN)?; + let off = self.cursor[a]; + self.cursor[a] = off.checked_add(len).ok_or_else(|| format!("arena {arena} offset overflow"))?; + let idx = self.decls.len(); + self.decls.push(Decl { arena, off, len }); + self.index.insert(name.to_string(), idx); + Ok(idx) + } + + pub fn buf(&self, name: &str) -> Option { + self.index.get(name).copied() + } + + /// Mark a declared buffer as pre-initialized (weight or token input). + pub fn mark_input(&mut self, idx: usize) { + if !self.inputs.contains(&idx) { + self.inputs.push(idx); + } + } + + pub fn emit(&mut self, op: VplanOp, reads: &[usize], writes: &[usize]) { + self.ops.push(GraphOp { op, reads: reads.to_vec(), writes: writes.to_vec() }); + } + + /// Validate (arena safety) and return the plan + typed graph. + pub fn finish(self) -> Result<(Plan, Vec), String> { + let plan = Plan { + decls: self.decls, + ops: self.ops.iter().map(|g| Op { reads: g.reads.clone(), writes: g.writes.clone() }).collect(), + inputs: self.inputs, + }; + arena::validate(&plan).map_err(|e| format!("graph arena invalid: {e:?}"))?; + Ok((plan, self.ops)) + } +} + +/// Emit the trunk sub-graph: embed(+embed_norm fused) → final norm → unembed. +/// Mathematically complete and arena-validated; the per-layer body is inserted +/// between embed and final norm by the full decode emitter (next brick). +pub fn emit_trunk(ir: &InklingIr, batch: usize) -> Result<(Plan, Vec), String> { + let mut g = GraphBuilder::new(); + let b = batch as u64; + let hidden = ir.config.text.hidden as u64; + let vocab = ir.config.text.vocab as u64; + + // Inputs: token ids + trunk weights (sizes from the IR). + let tok = g.add_buf(ARENA_INPUT, "token_ids", b * 4)?; + g.mark_input(tok); + let weight = |g: &mut GraphBuilder, comp: LlmComp, name: &str| -> Result { + let meta = ir.trunk.get(&comp).ok_or_else(|| format!("missing trunk {comp:?}"))?; + let idx = g.add_buf(ARENA_WEIGHT, name, meta.bytes)?; + g.mark_input(idx); + Ok(idx) + }; + let embed = weight(&mut g, LlmComp::Embed, "w_embed")?; + let embed_norm = weight(&mut g, LlmComp::EmbedNorm, "w_embed_norm")?; + let final_norm = weight(&mut g, LlmComp::FinalNorm, "w_final_norm")?; + let unembed = weight(&mut g, LlmComp::Unembed, "w_unembed")?; + + // 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 logits = g.add_buf(ARENA_SCRATCH, "logits", b * vocab * 4)?; + + // embed_lookup fuses gather + embed_norm (reference k_embed_lookup). + g.emit(VplanOp::EmbedBf16, &[tok, embed, embed_norm], &[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::*; + use crate::inkling_ir::assemble; + use crate::TensorInfo; + + const CFG: &str = r#"{ + "eos_token_id": 0, + "text_config": { + "hidden_size": 8, "num_hidden_layers": 2, "vocab_size": 16, + "unpadded_vocab_size": 16, "num_attention_heads": 2, "num_key_value_heads": 1, + "head_dim": 4, "d_rel": 2, "rel_extent": 4, "sliding_window_size": 4, + "sconv_kernel_size": 4, "rms_norm_eps": 1e-06, "n_routed_experts": 4, + "num_experts_per_tok": 2, "n_shared_experts": 0, "intermediate_size": 8, + "route_scale": 1.0, "final_logit_softcapping": 30.0, "local_layer_ids": [0], + "loop_config": {"core_start":0,"core_end":1,"num_passes":2,"gate_rank":2,"is_varloop":false} + }, + "quantization_config": {"quant_algo":"NVFP4"} + }"#; + + fn ir() -> InklingIr { + let cfg = crate::inkling::parse_config(CFG).unwrap(); + let mut ts: Vec<(String, TensorInfo)> = vec![ + ("model.llm.embed.weight".into(), ti(vec![16, 8])), + ("model.llm.embed_norm.weight".into(), ti(vec![8])), + ("model.llm.norm.weight".into(), ti(vec![8])), + ("model.llm.unembed.weight".into(), ti(vec![16, 8])), + ]; + for l in 0..2 { + for (s, sh) in [ + ("attn.wq_du.weight", vec![8, 8]), ("attn.wk_dv.weight", vec![4, 8]), + ("attn.wv_dv.weight", vec![4, 8]), ("attn.wo_ud.weight", vec![8, 8]), + ("attn_norm.weight", vec![8]), ("mlp_norm.weight", vec![8]), + ("q_input_norm.weight", vec![8]), ("k_input_norm.weight", vec![8]), + ("v_input_norm.weight", vec![8]), ("mlp.gate.weight", vec![4, 8]), + ("mlp.experts.w13_weight", vec![4, 8, 8]), ("mlp.experts.w2_weight", vec![4, 8, 8]), + ] { + ts.push((format!("model.llm.layers.{l}.{s}"), ti(sh))); + } + } + assemble(&cfg, ts.iter().map(|(n, t)| (n.as_str(), t))).unwrap() + } + + fn ti(shape: Vec) -> TensorInfo { + let bytes: u64 = shape.iter().product::() * 2; + TensorInfo { shard_idx: 0, dtype: "BF16".into(), shape, begin: 0, end: bytes } + } + + #[test] + fn trunk_graph_valid() { + let (plan, graph) = emit_trunk(&ir(), 1).unwrap(); + assert_eq!(graph.len(), 3); + assert_eq!(graph[0].op, VplanOp::EmbedBf16); + assert_eq!(graph[2].op, VplanOp::GemmBf16); + assert!(arena::validate(&plan).is_ok()); + // logits buffer sized from vocab (16 * 4 = 64 -> 4096 aligned) + let logits = plan.decls.iter().find(|d| d.arena == 0 && d.len >= 4096).unwrap(); + assert!(logits.len >= 64); + } + + #[test] + fn builder_rejects_use_before_write() { + let mut g = GraphBuilder::new(); + let a = g.add_buf(0, "a", 64).unwrap(); + let b = g.add_buf(0, "b", 64).unwrap(); + // read `a` before anything writes it (and it is not an input) + g.emit(VplanOp::RmsNorm, &[a], &[b]); + assert!(g.finish().is_err()); + } + + #[test] + fn builder_rejects_duplicate_buffer() { + let mut g = GraphBuilder::new(); + g.add_buf(0, "x", 64).unwrap(); + assert!(g.add_buf(0, "x", 64).is_err()); + } + + #[test] + fn inputs_satisfy_reads() { + let mut g = GraphBuilder::new(); + let w = g.add_buf(1, "w", 64).unwrap(); + g.mark_input(w); + let out = g.add_buf(0, "out", 64).unwrap(); + g.emit(VplanOp::GemmBf16, &[w], &[out]); + assert!(g.finish().is_ok()); + } +} \ No newline at end of file diff --git a/crates/vetta-infer-ld/src/inkling_plan.rs b/crates/vetta-infer-ld/src/inkling_plan.rs new file mode 100644 index 0000000..7e11cfa --- /dev/null +++ b/crates/vetta-infer-ld/src/inkling_plan.rs @@ -0,0 +1,195 @@ +//! Inkling execution-plan generation (docs/inkling-forward-design.md). +//! +//! First bricks of the `graph.vplan`/`memory.vplan` generator: +//! 1. the physical layer schedule (loop unrolling, verified against the +//! reference `ink_hip_backend.hip.cpp` logical→physical mapping); +//! 2. the decode scratch arena layout (4 KiB-aligned, checked offsets), +//! validated by `abi::arena` (proof `arena_plan.lean`) before any launch. +//! +//! The per-layer op wiring (k1→k2→k3→k4 stages) is emitted on top of this +//! once extracted from `forward_batch_chunk`; these are its foundations. + +use crate::inkling::TextConfig; +use vetta_infer_abi::arena::{self, Decl, Plan}; +use vetta_infer_abi::vtc1::{align_up, CACHE_ALIGN}; + +/// Physical execution schedule: logical layers unrolled over the loop passes. +/// Mirrors the reference mapping (pre-core, then `num_passes` × core body, +/// then post-core). For Inkling-2-Mini: 6 + 3×12 + 6 = 48 physical steps. +pub fn physical_schedule(cfg: &TextConfig) -> Vec { + let mut out = Vec::new(); + for l in 0..cfg.loop_cfg.core_start { + out.push(l); + } + for _ in 0..cfg.loop_cfg.num_passes { + for l in cfg.loop_cfg.core_start..cfg.loop_cfg.core_end { + out.push(l); + } + } + for l in cfg.loop_cfg.core_end..cfg.n_layers { + out.push(l); + } + out +} + +/// One named scratch buffer with its arena declaration. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScratchBuf { + pub name: &'static str, + pub decl: Decl, +} + +/// Decode scratch arenas (f32 activations), dimensions from the config. +/// Arena 0 = per-step activation scratch; each buffer 4 KiB-aligned, offsets +/// checked (`align_up`), no overlap (validated by `abi::arena`). +pub fn scratch_layout(cfg: &TextConfig, batch: usize) -> Result, String> { + let b = batch as u64; + let hidden = cfg.hidden as u64; + let q_dim = (cfg.n_head * cfg.head_dim) as u64; + let kv_dim = (cfg.n_kv * cfg.head_dim) as u64; + let inter = cfg.inter as u64; + let vocab = cfg.vocab as u64; + + // (name, element count) — f32 activations of the decode critical path. + let specs: &[(&'static str, u64)] = &[ + ("residual", b * hidden), + ("norm_out", b * hidden), + ("q", b * q_dim), + ("k", b * kv_dim), + ("v", b * kv_dim), + ("attn_out", b * q_dim), + ("proj_out", b * hidden), + ("moe_gate", b * inter), + ("moe_up", b * inter), + ("moe_down", b * hidden), + ("logits", b * vocab), + ]; + + let mut off: u64 = 0; + let mut bufs = Vec::with_capacity(specs.len()); + for (name, elems) in specs { + let bytes = elems.checked_mul(4).ok_or_else(|| format!("scratch '{name}' byte overflow"))?; + let len = align_up(bytes, CACHE_ALIGN)?; + bufs.push(ScratchBuf { name, decl: Decl { arena: 0, off, len } }); + off = off.checked_add(len).ok_or_else(|| format!("scratch '{name}' offset overflow"))?; + } + Ok(bufs) +} + +/// Lower the scratch layout into an arena `Plan` (decls only; the graph adds +/// the op sequence) and validate it: no overlap, checked bounds. +pub fn scratch_plan(cfg: &TextConfig, batch: usize) -> Result { + let bufs = scratch_layout(cfg, batch)?; + let plan = Plan { + decls: bufs.iter().map(|b| b.decl).collect(), + ops: Vec::new(), + inputs: Vec::new(), + }; + arena::validate(&plan).map_err(|e| format!("scratch arena invalid: {e:?}"))?; + Ok(plan) +} + +#[cfg(test)] +mod tests { + use super::*; + + const CFG: &str = r#"{ + "eos_token_id": 0, + "text_config": { + "hidden_size": 8, "num_hidden_layers": 4, "vocab_size": 16, + "unpadded_vocab_size": 16, "num_attention_heads": 2, "num_key_value_heads": 1, + "head_dim": 4, "d_rel": 2, "rel_extent": 4, "sliding_window_size": 4, + "sconv_kernel_size": 4, "rms_norm_eps": 1e-06, "n_routed_experts": 4, + "num_experts_per_tok": 2, "n_shared_experts": 0, "intermediate_size": 8, + "route_scale": 1.0, "final_logit_softcapping": 30.0, "local_layer_ids": [0,1,2], + "loop_config": {"core_start":1,"core_end":3,"num_passes":2,"gate_rank":2,"is_varloop":false} + }, + "quantization_config": {"quant_algo":"NVFP4"} + }"#; + + fn cfg() -> crate::inkling::InklingConfig { + crate::inkling::parse_config(CFG).unwrap() + } + + #[test] + fn schedule_unrolls_loop() { + let c = cfg(); + // pre [0], core 2×[1,2], post [3] + assert_eq!(physical_schedule(&c.text), vec![0, 1, 2, 1, 2, 3]); + } + + #[test] + fn schedule_inkling_shape() { + // 6 pre + 3×12 core + 6 post = 48 (Inkling-2-Mini shape). + let mut c = cfg(); + c.text.n_layers = 24; + c.text.loop_cfg.core_start = 6; + c.text.loop_cfg.core_end = 18; + c.text.loop_cfg.num_passes = 3; + let s = physical_schedule(&c.text); + assert_eq!(s.len(), 48); + assert_eq!(&s[..6], &[0, 1, 2, 3, 4, 5]); + assert_eq!(&s[6..18], &[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]); + assert_eq!(&s[18..30], &s[6..18]); // pass 2 + assert_eq!(&s[30..42], &s[6..18]); // pass 3 + assert_eq!(&s[42..], &[18, 19, 20, 21, 22, 23]); + } + + #[test] + fn scratch_aligned_and_disjoint() { + let c = cfg(); + let bufs = scratch_layout(&c.text, 1).unwrap(); + for b in &bufs { + assert_eq!(b.decl.off % CACHE_ALIGN, 0, "{} not aligned", b.name); + assert!(b.decl.len > 0); + } + // validated plan: no overlap, checked bounds + let plan = scratch_plan(&c.text, 1).unwrap(); + assert_eq!(plan.decls.len(), bufs.len()); + assert!(arena::validate(&plan).is_ok()); + } + + #[test] + fn scratch_dims_from_config() { + let c = cfg(); + let bufs = scratch_layout(&c.text, 1).unwrap(); + let q = bufs.iter().find(|b| b.name == "q").unwrap(); + // q_dim = n_head*head_dim = 2*4 = 8 elems * 4 bytes = 32 -> aligned 4096 + assert_eq!(q.decl.len, 4096); + let logits = bufs.iter().find(|b| b.name == "logits").unwrap(); + // vocab 16 * 4 = 64 -> aligned 4096 + assert_eq!(logits.decl.len, 4096); + } + + #[test] + fn scratch_batch_scaling() { + let mut c = cfg(); + // Realistic dims so batch scaling exceeds the 4 KiB alignment floor. + c.text.hidden = 2304; + c.text.vocab = 201024; + c.text.inter = 1152; + c.text.n_head = 24; + c.text.n_kv = 8; + c.text.head_dim = 128; + let b1 = scratch_layout(&c.text, 1).unwrap(); + let b8 = scratch_layout(&c.text, 8).unwrap(); + let last1 = b1.last().unwrap(); + let last8 = b8.last().unwrap(); + assert!(last8.decl.off + last8.decl.len > last1.decl.off + last1.decl.len); + assert!(arena::validate(&scratch_plan(&c.text, 8).unwrap()).is_ok()); + } + + /// Opt-in live plan against the real Inkling config. + /// `cargo test -p vetta-infer-ld -- --ignored inkling_plan_live`. + #[test] + #[ignore] + fn inkling_plan_live() { + let raw = std::fs::read_to_string("/mnt/models/Inkling/safetensors/config.json").unwrap(); + let c = crate::inkling::parse_config(&raw).unwrap(); + let sched = physical_schedule(&c.text); + assert_eq!(sched.len(), 48); + let plan = scratch_plan(&c.text, 1).unwrap(); + let total: u64 = plan.decls.iter().map(|d| d.len).sum(); + eprintln!("Inkling decode scratch: {} buffers, {} KiB, 48 physical steps", plan.decls.len(), total / 1024); + } +} \ No newline at end of file diff --git a/crates/vetta-infer-ld/src/lib.rs b/crates/vetta-infer-ld/src/lib.rs index 61a2a8f..5b06768 100644 --- a/crates/vetta-infer-ld/src/lib.rs +++ b/crates/vetta-infer-ld/src/lib.rs @@ -11,6 +11,8 @@ pub mod bundle; pub mod inkling; pub mod inkling_ir; +pub mod inkling_plan; +pub mod inkling_graph; use std::collections::{BTreeSet, HashMap}; use std::fs::{self, File, OpenOptions}; diff --git a/docs/inkling-forward-design.md b/docs/inkling-forward-design.md new file mode 100644 index 0000000..d5b9b9c --- /dev/null +++ b/docs/inkling-forward-design.md @@ -0,0 +1,57 @@ +# Inkling forward-pass design (grounded in the strata reference) + +Status: design foundation for the `graph.vplan` generator (M1). +Reference: `../strata-safetensors/engine/src/inkling2/hip/ink_hip_ops.hip.h` +(kernel families), `ink_hip_backend.hip.cpp` (`forward_batch_chunk` dispatch), +`ink_hip_tree.hip.h` (MTP beam-tree). Config: `ld::inkling::InklingConfig`. + +## Two forward paths + +1. **Main LLM** — 24 layers, looped MoE, hybrid SWA + relative attention. + This is the decode critical path and the first `graph.vplan` target. +2. **MTP / DSpark draft** — separate `mtp.safetensors` shard, 3 non-causal + block-8 layers (standard attention + SwiGLU) + Markov head (rank 256) + + beam-tree verification (`ink_hip_tree.hip.h`). Simpler; lands after the + main path. `target_layer_ids [5,23,41,48]` tap the main model. + +## Per-layer stage order (verified from kernel stage numbering) + +The reference kernels are numbered `k1_..k4_` — the numbering IS the +per-layer forward order: + +| Stage | Reference kernel(s) | Role | Our opcode | +| --- | --- | --- | --- | +| k1 | `k1_attn_res_mix_norm_fused` | attention-residual mix + norm | `rms_norm` (+residual) | +| k2 | `k2_shortconv4_*` | short conv (kernel 4) on q/k/v/attn/mlp | (new `shortconv4`) | +| k2 | `k2_qrkv_norm_clip_fused` | q/k/v proj + input-norm + L2 clip | `gemm_*` + `rms_norm` | +| k2 | `k2_qrkv_kvstore_relpos_fused` | KV store + relative position | `rope_kv_write` (+rel) | +| k3 | `k3_flash_swa_gqa` / `_splitkv` / `_prefill_wmma` | SWA flash attention (decode/prefill) | `flash_gqa_wmma` | +| k3 | `k_relpos_bias_proj` | relative-position bias (full-attn layers) | (rel attn variant) | +| k4 | `k4_moe_router_topk` | MoE routing top-8 of 128 | `moe_route_bucket` | +| k4 | expert GEMM + `k_scatter_add_expert` | NVFP4 experts w13/w2 + reduce | `moe_w13_wmma`/`moe_w2_wmma`/`moe_reduce` | +| — | `k_embed_lookup` / `k_unembed_softcap` | trunk embed / unembed (softcap 30) | `embed_bf16` / `gpu_penalties_topk` | + +Notes: +- SWA layers (20 of 24) use `attn_norm`; full-attention layers {5,11,17,23} + use `q/k/v_input_norm` + relative bias (verified on the live inventory). +- Controllers (`gain/forget/down` × attn/k/v/mlp) gate the looped passes. +- Trunk: `embed → embed_norm → [layers] → norm → unembed(softcap)`. + +## Loop structure (from config) + +`loop_config {core_start 6, core_end 18, num_passes 3, gate_rank 64}`: the +core layers [6,18) run 3 passes; `middle_cycle_cross_pass_queries` / +`..._kv_queries` carry state across passes; `attn_res.attn_queries[0..22]` / +`mlp_queries[0..23]` / `output_query` are the attention-residual block +queries (`n_layers_per_attn_res_block = 6`). The graph encodes this as +`loop_layer` over the core body ×3 with the cross-pass query buffers. + +## Next brick (executable graph) + +Extract the exact operand wiring (buffer offsets, fusion boundaries, the +controller gate application point) from `forward_batch_chunk` in +`ink_hip_backend.hip.cpp`, then emit `graph.vplan` + `memory.vplan` from +`InklingIr` following the k1→k2→k3→k4 stage order. The `memory.vplan` is +validated by `abi::arena` (proof `arena_plan.lean`) before any GPU launch. +Open detail to resolve from the reference: precise short-conv history +buffering (snapshot/rollback for speculative) and the relpos bias indexing. \ No newline at end of file