[ABI][LD][Proofs][Docs] M1 groundwork: arena-safety proof + .vbundle contract; embedder lane (M1.5) accepted

- proofs/arena_plan.lean: memory.vplan arena safety (8 theorems + 4
  computational examples, 0 sorryAx): no overlap, checked index bounds,
  no use-before-write, overlap-rejection completeness.
- abi::arena: validator mirroring the proof, checked offset arithmetic
  (invariant #2), explicit error per violation class; 8 tests.
- abi::bundle: .vbundle manifest (ABI_VERSION=1, source+packer fingerprints,
  backend target; incompatible ABI rejected explicitly), checked
  memory.vplan/graph.vplan parsing, arena-validated compile(); 7 tests.
- ld::bundle: read-only load_bundle_plans(dir) over manifest + plan/*.vplan;
  3 tests (good bundle, missing file, ABI mismatch).
- abi::vplan: encoder-lane opcodes (layer_norm, flash_full_attn, gelu_erf,
  mean_pool_l2norm) + wire name mapping for all 22 opcodes, roundtrip test.
- Docs: utility-encoder scope carve-out (dense decoder LMs out, small
  fully-resident encoders in), embedder-lane wire proposal + characteristic
  parity vs vetta-semantics (cosine vs oracle, internal bit-exact goldens),
  16-primitive kernel set, M1.5 milestone; README/AGENTS aligned
  (65 tests, 42 theorems across 4 proof files).
- review/: tandem exchange with the strata-ctl coder (their request +
  observations, our formal reply: embedder accepted, M0 dir cleanup done).

Verified live: RUSTFLAGS="-D warnings" cargo test --workspace = 65/65 PASS;
lean proofs/{slab_ring_dma,bus_lifecycle,serve_session,arena_plan}.lean green,
standard axioms only.
This commit is contained in:
adm committed 2026-11-30 15:22:00 +01:00
1 parent 7b50f1c07c
commit fb92662106
13 files changed
+1235 -16

No files matched your search

+185
View File
@@ -0,0 +1,185 @@
//! `memory.vplan` arena safety — implements `proofs/arena_plan.lean`.
//!
//! Static validation before the first GPU launch (docs/ARCHITECTURE.md §4/§8):
//! declared buffers in the same arena never overlap, every op index is within
//! the declaration table, and no read happens before a write (or an input).
//! All offset arithmetic is checked (hard invariant #2).
/// A declared buffer: arena id + byte interval `[off, off + len)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Decl {
pub arena: u32,
pub off: u64,
pub len: u64,
}
/// One micro-op: reads/writes are indices into the declaration table.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Op {
pub reads: Vec<usize>,
pub writes: Vec<usize>,
}
/// A memory plan: declarations, the op sequence, and pre-initialized inputs.
#[derive(Debug, Clone, Default)]
pub struct Plan {
pub decls: Vec<Decl>,
pub ops: Vec<Op>,
pub inputs: Vec<usize>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArenaError {
/// `off + len` overflowed (checked arithmetic, invariant #2).
OffsetOverflow { index: usize },
/// Two distinct declarations overlap in the same arena.
Overlap { a: usize, b: usize },
ReadOutOfBounds { op: usize, index: usize },
WriteOutOfBounds { op: usize, index: usize },
InputOutOfBounds { index: usize },
/// A read not covered by inputs or strictly earlier writes.
UseBeforeWrite { op: usize, buffer: usize },
}
/// Mirrors `Vetta.Proofs.Arena.validate`: disjointness, bounds, then the
/// sequential use-before-write check. First failure wins (explicit, never silent).
pub fn validate(p: &Plan) -> Result<(), ArenaError> {
let n = p.decls.len();
// Checked interval ends (before any comparison/allocation).
let mut ends = Vec::with_capacity(n);
for (i, d) in p.decls.iter().enumerate() {
let end = d.off.checked_add(d.len).ok_or(ArenaError::OffsetOverflow { index: i })?;
ends.push(end);
}
// Pairwise no-overlap within the same arena (touching boundaries allowed).
for i in 0..n {
for j in (i + 1)..n {
let a = &p.decls[i];
let b = &p.decls[j];
if a.arena == b.arena && !(ends[i] <= b.off || ends[j] <= a.off) {
return Err(ArenaError::Overlap { a: i, b: j });
}
}
}
// Index bounds for every op read/write and every input.
for (oi, op) in p.ops.iter().enumerate() {
for &r in &op.reads {
if r >= n {
return Err(ArenaError::ReadOutOfBounds { op: oi, index: r });
}
}
for &w in &op.writes {
if w >= n {
return Err(ArenaError::WriteOutOfBounds { op: oi, index: w });
}
}
}
for &i in &p.inputs {
if i >= n {
return Err(ArenaError::InputOutOfBounds { index: i });
}
}
// Sequential use-before-write: reads see inputs + strictly earlier writes.
let mut written = vec![false; n];
for &i in &p.inputs {
written[i] = true;
}
for (oi, op) in p.ops.iter().enumerate() {
for &r in &op.reads {
if !written[r] {
return Err(ArenaError::UseBeforeWrite { op: oi, buffer: r });
}
}
for &w in &op.writes {
written[w] = true;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn d(arena: u32, off: u64, len: u64) -> Decl {
Decl { arena, off, len }
}
#[test]
fn good_plan_accepted() {
// Mirrors the Lean acceptance example.
let p = Plan {
decls: vec![d(0, 0, 64), d(0, 64, 32), d(1, 0, 128)],
ops: vec![
Op { reads: vec![0], writes: vec![1] },
Op { reads: vec![1, 0], writes: vec![2] },
],
inputs: vec![0],
};
assert_eq!(validate(&p), Ok(()));
}
#[test]
fn overlap_rejected() {
let p = Plan { decls: vec![d(0, 0, 64), d(0, 32, 32)], ..Default::default() };
assert_eq!(validate(&p), Err(ArenaError::Overlap { a: 0, b: 1 }));
}
#[test]
fn touching_boundaries_and_different_arenas_ok() {
let p = Plan {
decls: vec![d(0, 0, 64), d(0, 64, 32), d(1, 0, 64)],
..Default::default()
};
assert_eq!(validate(&p), Ok(()));
}
#[test]
fn use_before_write_rejected() {
let p = Plan {
decls: vec![d(0, 0, 8), d(0, 8, 8)],
ops: vec![Op { reads: vec![0], writes: vec![1] }],
inputs: vec![],
};
assert_eq!(validate(&p), Err(ArenaError::UseBeforeWrite { op: 0, buffer: 0 }));
}
#[test]
fn read_of_own_write_same_op_rejected() {
// Writes land only AFTER the op's reads are checked (mirrors checkOps).
let p = Plan {
decls: vec![d(0, 0, 8)],
ops: vec![Op { reads: vec![0], writes: vec![0] }],
inputs: vec![],
};
assert_eq!(validate(&p), Err(ArenaError::UseBeforeWrite { op: 0, buffer: 0 }));
}
#[test]
fn out_of_bounds_rejected() {
let p = Plan {
decls: vec![d(0, 0, 8)],
ops: vec![Op { reads: vec![5], writes: vec![] }],
inputs: vec![],
};
assert_eq!(validate(&p), Err(ArenaError::ReadOutOfBounds { op: 0, index: 5 }));
let p2 = Plan { decls: vec![d(0, 0, 8)], inputs: vec![3], ..Default::default() };
assert_eq!(validate(&p2), Err(ArenaError::InputOutOfBounds { index: 3 }));
}
#[test]
fn offset_overflow_rejected() {
let p = Plan { decls: vec![d(0, u64::MAX, 2)], ..Default::default() };
assert_eq!(validate(&p), Err(ArenaError::OffsetOverflow { index: 0 }));
}
#[test]
fn empty_plan_ok() {
assert_eq!(validate(&Plan::default()), Ok(()));
}
}
+245
View File
@@ -0,0 +1,245 @@
//! `.vbundle` contracts: manifest + `.vplan` parsing + arena-validated compile
//! (docs/ARCHITECTURE.md §3/§4). Pure data and pure functions — the file IO
//! lives in `ld::bundle`. A bundle produced by an incompatible packer/ABI is
//! rejected explicitly, never misread (hard invariant #4 spirit).
use crate::arena::{self, ArenaError, Decl, Op, Plan};
use crate::json::{parse_json, JsonVal};
use crate::vplan::VplanOp;
/// Bumped on any breaking change to the bundle layout or plan semantics.
pub const ABI_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Manifest {
pub model_id: String,
pub source_fingerprint: u64,
pub packer_fingerprint: u64,
pub abi_version: u32,
pub backend_target: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BundleError {
Json(String),
MissingField(&'static str),
BadField(&'static str),
AbiMismatch { found: u32, expected: u32 },
UnknownOpcode(String),
Arena(ArenaError),
Io(String),
}
impl std::fmt::Display for BundleError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Json(e) => write!(f, "JSON: {e}"),
Self::MissingField(k) => write!(f, "missing field '{k}'"),
Self::BadField(k) => write!(f, "bad field '{k}'"),
Self::AbiMismatch { found, expected } => {
write!(f, "ABI mismatch: bundle {found}, engine {expected}")
}
Self::UnknownOpcode(s) => write!(f, "unknown opcode '{s}'"),
Self::Arena(e) => write!(f, "arena: {e:?}"),
Self::Io(e) => write!(f, "IO: {e}"),
}
}
}
fn obj<'a>(v: &'a JsonVal) -> Result<&'a std::collections::HashMap<String, JsonVal>, BundleError> {
v.as_obj().ok_or(BundleError::BadField("root"))
}
fn field<'a>(
m: &'a std::collections::HashMap<String, JsonVal>,
k: &'static str,
) -> Result<&'a JsonVal, BundleError> {
m.get(k).ok_or(BundleError::MissingField(k))
}
fn u64_field(
m: &std::collections::HashMap<String, JsonVal>,
k: &'static str,
) -> Result<u64, BundleError> {
field(m, k)?.as_u64().ok_or(BundleError::BadField(k))
}
fn str_field(
m: &std::collections::HashMap<String, JsonVal>,
k: &'static str,
) -> Result<String, BundleError> {
field(m, k)?.as_str().map(str::to_string).ok_or(BundleError::BadField(k))
}
fn idx(v: &JsonVal) -> Result<usize, BundleError> {
let n = v.as_u64().ok_or(BundleError::BadField("index"))?;
usize::try_from(n).map_err(|_| BundleError::BadField("index"))
}
fn idx_arr(v: &JsonVal) -> Result<Vec<usize>, BundleError> {
v.as_arr().ok_or(BundleError::BadField("indices"))?.iter().map(idx).collect()
}
/// Parse `manifest.json`; rejects incompatible ABI versions explicitly.
pub fn parse_manifest(text: &str) -> Result<Manifest, BundleError> {
let v = parse_json(text).map_err(BundleError::Json)?;
let m = obj(&v)?;
let abi = u64_field(m, "abi_version")?;
let abi_version = u32::try_from(abi).map_err(|_| BundleError::BadField("abi_version"))?;
if abi_version != ABI_VERSION {
return Err(BundleError::AbiMismatch { found: abi_version, expected: ABI_VERSION });
}
Ok(Manifest {
model_id: str_field(m, "model_id")?,
source_fingerprint: u64_field(m, "source_fingerprint")?,
packer_fingerprint: u64_field(m, "packer_fingerprint")?,
abi_version,
backend_target: str_field(m, "backend_target")?,
})
}
/// Parse `memory.vplan`: buffer declarations + pre-initialized inputs.
pub fn parse_memory(text: &str) -> Result<(Vec<Decl>, Vec<usize>), BundleError> {
let v = parse_json(text).map_err(BundleError::Json)?;
let m = obj(&v)?;
let decls_v = field(m, "decls")?.as_arr().ok_or(BundleError::BadField("decls"))?;
let mut decls = Vec::with_capacity(decls_v.len());
for d in decls_v {
let dm = obj(d)?;
let arena_id = u64_field(dm, "arena")?;
decls.push(Decl {
arena: u32::try_from(arena_id).map_err(|_| BundleError::BadField("arena"))?,
off: u64_field(dm, "off")?,
len: u64_field(dm, "len")?,
});
}
let inputs = idx_arr(field(m, "inputs")?)?;
Ok((decls, inputs))
}
/// One `graph.vplan` entry: opcode + operand indices into the memory decls.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GraphOp {
pub op: VplanOp,
pub reads: Vec<usize>,
pub writes: Vec<usize>,
}
/// Parse `graph.vplan`: a flat op sequence (unknown opcodes rejected).
pub fn parse_graph(text: &str) -> Result<Vec<GraphOp>, BundleError> {
let v = parse_json(text).map_err(BundleError::Json)?;
let m = obj(&v)?;
let ops_v = field(m, "ops")?.as_arr().ok_or(BundleError::BadField("ops"))?;
let mut ops = Vec::with_capacity(ops_v.len());
for o in ops_v {
let om = obj(o)?;
let name = str_field(om, "op")?;
let op = VplanOp::from_name(&name).ok_or(BundleError::UnknownOpcode(name))?;
ops.push(GraphOp {
op,
reads: idx_arr(field(om, "reads")?)?,
writes: idx_arr(field(om, "writes")?)?,
});
}
Ok(ops)
}
/// The boot-time compile product: manifest + arena-validated plan + typed graph.
/// `plan.ops` mirrors `graph` reads/writes — the artifact `abi::arena` verified.
#[derive(Debug, Clone)]
pub struct CompiledPlans {
pub manifest: Manifest,
pub plan: Plan,
pub graph: Vec<GraphOp>,
}
/// Lower manifest + memory.vplan + graph.vplan into a validated `CompiledPlans`.
/// Arena safety (no overlap / no use-before-write / checked bounds) is enforced
/// HERE, before any GPU launch — implements `proofs/arena_plan.lean`.
pub fn compile(
manifest_json: &str,
memory_json: &str,
graph_json: &str,
) -> Result<CompiledPlans, BundleError> {
let manifest = parse_manifest(manifest_json)?;
let (decls, inputs) = parse_memory(memory_json)?;
let graph = parse_graph(graph_json)?;
let plan = Plan {
decls,
ops: graph.iter().map(|g| Op { reads: g.reads.clone(), writes: g.writes.clone() }).collect(),
inputs,
};
arena::validate(&plan).map_err(BundleError::Arena)?;
Ok(CompiledPlans { manifest, plan, graph })
}
#[cfg(test)]
mod tests {
use super::*;
const MANIFEST: &str = r#"{"model_id":"inkling-2-mini","source_fingerprint":123,
"packer_fingerprint":456,"abi_version":1,"backend_target":"gfx1150"}"#;
const MEMORY: &str = r#"{"decls":[{"arena":0,"off":0,"len":64},
{"arena":0,"off":64,"len":32},{"arena":1,"off":0,"len":128}],"inputs":[0]}"#;
const GRAPH: &str = r#"{"ops":[{"op":"embed_bf16","reads":[0],"writes":[1]},
{"op":"rms_norm","reads":[1,0],"writes":[2]}]}"#;
#[test]
fn compile_good_bundle() {
let c = compile(MANIFEST, MEMORY, GRAPH).unwrap();
assert_eq!(c.manifest.model_id, "inkling-2-mini");
assert_eq!(c.manifest.backend_target, "gfx1150");
assert_eq!(c.graph.len(), 2);
assert_eq!(c.graph[0].op, VplanOp::EmbedBf16);
assert_eq!(c.plan.decls.len(), 3);
}
#[test]
fn abi_mismatch_rejected() {
let bad = MANIFEST.replace("\"abi_version\":1", "\"abi_version\":2");
assert_eq!(
parse_manifest(&bad),
Err(BundleError::AbiMismatch { found: 2, expected: ABI_VERSION })
);
}
#[test]
fn missing_and_bad_fields_rejected() {
assert_eq!(parse_manifest("{}"), Err(BundleError::MissingField("abi_version")));
let neg = MANIFEST.replace("\"source_fingerprint\":123", "\"source_fingerprint\":-1");
assert_eq!(parse_manifest(&neg), Err(BundleError::BadField("source_fingerprint")));
}
#[test]
fn unknown_opcode_rejected() {
let bad = GRAPH.replace("embed_bf16", "warp_drive");
let err = compile(MANIFEST, MEMORY, &bad).unwrap_err();
assert_eq!(err, BundleError::UnknownOpcode("warp_drive".into()));
}
#[test]
fn overlapping_memory_rejected_at_compile() {
let bad = MEMORY.replace("{\"arena\":0,\"off\":64,\"len\":32}", "{\"arena\":0,\"off\":32,\"len\":32}");
assert!(matches!(compile(MANIFEST, &bad, GRAPH), Err(BundleError::Arena(ArenaError::Overlap { .. }))));
}
#[test]
fn use_before_write_rejected_at_compile() {
// inputs empty: first op reads buffer 0 which nobody wrote yet.
let bad_mem = MEMORY.replace("\"inputs\":[0]", "\"inputs\":[]");
assert!(matches!(compile(MANIFEST, &bad_mem, GRAPH), Err(BundleError::Arena(ArenaError::UseBeforeWrite { .. }))));
}
#[test]
fn encoder_lane_opcodes_parse() {
let g = r#"{"ops":[{"op":"layer_norm","reads":[0],"writes":[1]},
{"op":"flash_full_attn","reads":[1],"writes":[2]},
{"op":"gelu_erf","reads":[2],"writes":[3]},
{"op":"mean_pool_l2norm","reads":[3],"writes":[4]}]}"#;
let m = r#"{"decls":[{"arena":0,"off":0,"len":8},{"arena":0,"off":8,"len":8},
{"arena":0,"off":16,"len":8},{"arena":0,"off":24,"len":8},
{"arena":0,"off":32,"len":8}],"inputs":[0]}"#;
let c = compile(MANIFEST, m, g).unwrap();
assert_eq!(c.graph[3].op, VplanOp::MeanPoolL2norm);
}
}
+2
View File
@@ -5,6 +5,8 @@
//! (docs/ARCHITECTURE.md §2, §4, §6, §9).
//! Zero external dependencies; pure data and pure functions only — no IO, no syscalls.
pub mod arena;
pub mod bundle;
pub mod bus;
pub mod json;
pub mod sampler;
+79
View File
@@ -25,6 +25,11 @@ pub enum VplanOp {
MoeReduce,
VitFlashAttnWmma,
GpuPenaltiesTopk,
// Encoder lane (M1.5 embedder, docs/ARCHITECTURE.md §4)
LayerNorm,
FlashFullAttn,
GeluErf,
MeanPoolL2norm,
// Restricted control flow
/// Repeat the enclosed layer body for each model layer.
LoopLayer,
@@ -37,6 +42,63 @@ impl VplanOp {
pub fn is_control(self) -> bool {
matches!(self, Self::LoopLayer | Self::BranchB)
}
/// Canonical wire name (as written in `graph.vplan`).
pub fn name(self) -> &'static str {
match self {
Self::EmbedBf16 => "embed_bf16",
Self::RmsNorm => "rms_norm",
Self::QuantizeXG64 => "quantize_x_g64",
Self::GemmQ8G64T16 => "gemm_q8_g64_t16",
Self::GemmQ4G64T16 => "gemm_q4_g64_t16",
Self::GemmNvfp4Mxfp8 => "gemm_nvfp4_mxfp8",
Self::RopeKvWrite => "rope_kv_write",
Self::FlashGqaWmma => "flash_gqa_wmma",
Self::GdnChunkwiseWy => "gdn_chunkwise_wy",
Self::GdnRecurrentStep => "gdn_recurrent_step",
Self::MoeRouteBucket => "moe_route_bucket",
Self::MoeW13Wmma => "moe_w13_wmma",
Self::MoeW2Wmma => "moe_w2_wmma",
Self::MoeReduce => "moe_reduce",
Self::VitFlashAttnWmma => "vit_flash_attn_wmma",
Self::GpuPenaltiesTopk => "gpu_penalties_topk",
Self::LayerNorm => "layer_norm",
Self::FlashFullAttn => "flash_full_attn",
Self::GeluErf => "gelu_erf",
Self::MeanPoolL2norm => "mean_pool_l2norm",
Self::LoopLayer => "loop_layer",
Self::BranchB => "branch_b",
}
}
/// Parse a wire name; unknown opcodes are rejected explicitly (never silent).
pub fn from_name(s: &str) -> Option<Self> {
Some(match s {
"embed_bf16" => Self::EmbedBf16,
"rms_norm" => Self::RmsNorm,
"quantize_x_g64" => Self::QuantizeXG64,
"gemm_q8_g64_t16" => Self::GemmQ8G64T16,
"gemm_q4_g64_t16" => Self::GemmQ4G64T16,
"gemm_nvfp4_mxfp8" => Self::GemmNvfp4Mxfp8,
"rope_kv_write" => Self::RopeKvWrite,
"flash_gqa_wmma" => Self::FlashGqaWmma,
"gdn_chunkwise_wy" => Self::GdnChunkwiseWy,
"gdn_recurrent_step" => Self::GdnRecurrentStep,
"moe_route_bucket" => Self::MoeRouteBucket,
"moe_w13_wmma" => Self::MoeW13Wmma,
"moe_w2_wmma" => Self::MoeW2Wmma,
"moe_reduce" => Self::MoeReduce,
"vit_flash_attn_wmma" => Self::VitFlashAttnWmma,
"gpu_penalties_topk" => Self::GpuPenaltiesTopk,
"layer_norm" => Self::LayerNorm,
"flash_full_attn" => Self::FlashFullAttn,
"gelu_erf" => Self::GeluErf,
"mean_pool_l2norm" => Self::MeanPoolL2norm,
"loop_layer" => Self::LoopLayer,
"branch_b" => Self::BranchB,
_ => return None,
})
}
}
#[cfg(test)]
@@ -50,4 +112,21 @@ mod tests {
assert!(!VplanOp::GemmQ8G64T16.is_control());
assert!(!VplanOp::GdnChunkwiseWy.is_control());
}
#[test]
fn name_roundtrip_all_opcodes() {
let all = [
VplanOp::EmbedBf16, VplanOp::RmsNorm, VplanOp::QuantizeXG64,
VplanOp::GemmQ8G64T16, VplanOp::GemmQ4G64T16, VplanOp::GemmNvfp4Mxfp8,
VplanOp::RopeKvWrite, VplanOp::FlashGqaWmma, VplanOp::GdnChunkwiseWy,
VplanOp::GdnRecurrentStep, VplanOp::MoeRouteBucket, VplanOp::MoeW13Wmma,
VplanOp::MoeW2Wmma, VplanOp::MoeReduce, VplanOp::VitFlashAttnWmma,
VplanOp::GpuPenaltiesTopk, VplanOp::LayerNorm, VplanOp::FlashFullAttn,
VplanOp::GeluErf, VplanOp::MeanPoolL2norm, VplanOp::LoopLayer, VplanOp::BranchB,
];
for op in all {
assert_eq!(VplanOp::from_name(op.name()), Some(op));
}
assert_eq!(VplanOp::from_name("bogus"), None);
}
}