[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.
This commit is contained in:
1 parent
465315ae94
commit
d478787863
5 files changed
+459
-1
No files matched your search
@@ -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<Decl>,
|
||||
index: HashMap<String, usize>,
|
||||
ops: Vec<GraphOp>,
|
||||
inputs: Vec<usize>,
|
||||
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<usize, String> {
|
||||
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<usize> {
|
||||
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<GraphOp>), 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<GraphOp>), 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<usize, String> {
|
||||
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<u64>) -> TensorInfo {
|
||||
let bytes: u64 = shape.iter().product::<u64>() * 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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user