ml: v2 multi-graph files, tinyclip plus supertonic kin
- Commit
683c7ab060782451f5f80259f88a44b832441b7e- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-14 09:41 UTC (2 months ago)
- Parents
32e4e23
Diff
library/ml/src/main/rust/examples/emit_net_maml2.rs
diff --git a/library/ml/src/main/rust/examples/emit_net_maml2.rs b/library/ml/src/main/rust/examples/emit_net_maml2.rsindex 4bb9c9e8cd..a1c98e0168 100644--- a/library/ml/src/main/rust/examples/emit_net_maml2.rs+++ b/library/ml/src/main/rust/examples/emit_net_maml2.rs@@ -41,8 +41,12 @@ struct NetSpec { } fn usage() -> ! {- eprintln!("usage: emit_net_maml2 <selfie|u2netp|scrfd|mobilefacenet|ppocr_det|ppocr_rec|maia> [dims...]");- eprintln!(" scrfd, ppocr_det take HEIGHT WIDTH; ppocr_rec takes WIDTH");+ eprintln!("usage: emit_net_maml2 <net> [dims...]");+ eprintln!(" single-graph: selfie u2netp scrfd mobilefacenet ppocr_det ppocr_rec maia");+ eprintln!(" vocoder duration text");+ eprintln!(" multi-graph: tinyclip");+ eprintln!(" scrfd, ppocr_det take HEIGHT WIDTH; ppocr_rec takes WIDTH;");+ eprintln!(" vocoder takes FRAMES; duration, text take CHARS; tinyclip takes LEN"); std::process::exit(1) } @@ -204,12 +208,126 @@ fn main() { sha, ) }+ "vocoder" => {+ let frames: u32 = dim1(49);+ let asset = "speech/src/main/assets/supertonic/supertonic_voc.maml";+ let (data, tensors, offsets, sha) =+ load_v1(&root, asset, weights::graph::SUPERTONIC_VOC);+ let recorded =+ modelrunner::nets::supertonic_vocoder::record(&offsets, frames).expect("record");+ (+ NetSpec {+ name: "vocoder",+ asset,+ graph: weights::graph::SUPERTONIC_VOC,+ roles: vec!["latent"],+ description: "supertonic-vocoder fp16/int8 nchw (v2)",+ },+ recorded,+ tensors,+ data,+ sha,+ )+ }+ "duration" => {+ let chars: u32 = dim1(55);+ let asset = "speech/src/main/assets/supertonic/supertonic_dp.maml";+ let (data, tensors, offsets, sha) =+ load_v1(&root, asset, weights::graph::SUPERTONIC_DP);+ let recorded =+ modelrunner::nets::supertonic_duration::record(&offsets, chars).expect("record");+ (+ NetSpec {+ name: "duration",+ asset,+ graph: weights::graph::SUPERTONIC_DP,+ roles: vec!["char_ids", "style"],+ description: "supertonic-duration fp16/int8 nchw (v2)",+ },+ recorded,+ tensors,+ data,+ sha,+ )+ }+ "text" => {+ let chars: u32 = dim1(55);+ let asset = "speech/src/main/assets/supertonic/supertonic_ttl.maml";+ let (data, tensors, offsets, sha) =+ load_v1(&root, asset, weights::graph::SUPERTONIC_TTL);+ let recorded =+ modelrunner::nets::supertonic_text::record(&offsets, chars).expect("record");+ (+ NetSpec {+ name: "text",+ asset,+ graph: weights::graph::SUPERTONIC_TTL,+ roles: vec!["char_ids", "style"],+ description: "supertonic-text-encoder fp16 nchw (v2)",+ },+ recorded,+ tensors,+ data,+ sha,+ )+ }+ "tinyclip" => {+ let len: u32 = dim1(16);+ let asset = "photos/src/main/assets/clip/tinyclip.maml";+ let (data, tensors, offsets, sha) = load_v1(&root, asset, weights::graph::TINYCLIP);+ let image = modelrunner::nets::tinyclip::record(+ &offsets,+ modelrunner::nets::tinyclip::Mode::Image,+ )+ .expect("record image");+ let text = modelrunner::nets::tinyclip::record(+ &offsets,+ modelrunner::nets::tinyclip::Mode::Text { len },+ )+ .expect("record text");+ let emitted = emit::emit_graphs(+ &tensors,+ &data,+ "tinyclip int8 nchw (v2)",+ "maml2 emit_net_maml2",+ sha,+ &[+ emit::GraphSpec {+ recorded: &image,+ graph_name: "image",+ entry_name: "image",+ roles: &["pixels"],+ },+ emit::GraphSpec {+ recorded: &text,+ graph_name: "text",+ entry_name: "text",+ roles: &["embedded"],+ },+ ],+ )+ .expect("emission succeeds");+ let out_path = root.join(asset.replace(".maml", ".maml2"));+ std::fs::write(&out_path, &emitted.bytes).expect("write the v2 file");+ println!("tinyclip v2: {} nodes over 2 graphs", emitted.op_inventory.iter().map(|(_, n)| n).sum::<usize>());+ println!("graph_digest: {}", hex(&emitted.graph_digest));+ println!("wrote {}", out_path.display());+ return;+ } _ => usage(), }; let _ = spec.graph; emit_and_check(&root, &spec, &recorded, &table, &data, source_sha256); } +/// One positional dim with a default, for the singly-shaped nets.+fn dim1(default: u32) -> u32 {+ std::env::args()+ .nth(2)+ .map(|s| s.parse().unwrap_or_else(|_| usage()))+ .unwrap_or(default)+}+ /// Two positional dims (HEIGHT WIDTH) with defaults, for the shaped nets. fn dims2(_net: &str, default_h: u32, default_w: u32) -> (u32, u32) { let h: u32 = std::env::args()
library/ml/src/main/rust/src/maml2/emit.rs
diff --git a/library/ml/src/main/rust/src/maml2/emit.rs b/library/ml/src/main/rust/src/maml2/emit.rsindex 9799b6e796..dd45be0562 100644--- a/library/ml/src/main/rust/src/maml2/emit.rs+++ b/library/ml/src/main/rust/src/maml2/emit.rs@@ -605,9 +605,12 @@ fn emit_nodes( )); } nodes.push(EmittedNode {- // v2 stores quantised convolutions as MatMul when 1x1- // (the loader lowers by shape); the kernel dims say so.- op: if kernel == (1, 1) { fb::Op::MatMul } else { fb::Op::Conv },+ // Quantised convolutions are always `MatMul` in file+ // vocabulary; the kernel/stride/pads/groups attrs carry+ // the geometry and the loader routes by shape (tiled,+ // GEMV, or untiled) exactly as the hand-written pass+ // does.+ op: fb::Op::MatMul, inputs: vec![a, w, s, b], outputs: vec![y], attrs,@@ -806,14 +809,62 @@ fn emit_nodes( ], }); }- Node::Softmax { input, out, mode, .. } => {+ Node::AttnScoresRelative { q, k, out, heads, scale, table, offsets } => {+ let x = computed(q.0, id_map, emit_tensors);+ let y_in = computed(k.0, id_map, emit_tensors);+ let y = computed(out.0, id_map, emit_tensors);+ let t = weights.fp16("relative table", table)?;+ nodes.push(EmittedNode {+ op: fb::Op::Attention,+ inputs: vec![x, y_in, t],+ outputs: vec![y],+ attrs: vec![+ ("heads".into(), AttrValue::Int(heads as i32)),+ ("scale".into(), AttrValue::Float(scale)),+ ("phase".into(), AttrValue::Int(2)),+ ("rel_offsets".into(), AttrValue::Int(offsets as i32)),+ ],+ });+ }+ Node::AttnApplyRelative { probs, v, out, heads, table, offsets } => {+ let p = computed(probs.0, id_map, emit_tensors);+ let vv = computed(v.0, id_map, emit_tensors);+ let y = computed(out.0, id_map, emit_tensors);+ let t = weights.fp16("relative table", table)?;+ nodes.push(EmittedNode {+ op: fb::Op::Attention,+ inputs: vec![p, vv, t],+ outputs: vec![y],+ attrs: vec![+ ("heads".into(), AttrValue::Int(heads as i32)),+ ("phase".into(), AttrValue::Int(3)),+ ("rel_offsets".into(), AttrValue::Int(offsets as i32)),+ ],+ });+ }+ Node::Embed { ids, out, table, rows } => {+ let ii = computed(ids.0, id_map, emit_tensors);+ let y = computed(out.0, id_map, emit_tensors);+ let t = weights.fp16("embed table", table)?;+ nodes.push(EmittedNode {+ op: fb::Op::Embedding,+ inputs: vec![ii, t],+ outputs: vec![y],+ attrs: vec![("rows".into(), AttrValue::Int(rows as i32))],+ });+ }+ Node::Softmax { input, out, mode, sliding, window } => { let x = computed(input.0, id_map, emit_tensors); let y = computed(out.0, id_map, emit_tensors); nodes.push(EmittedNode { op: fb::Op::Softmax, inputs: vec![x], outputs: vec![y],- attrs: vec![("mode".into(), AttrValue::Int(softmax_mode_code(mode)))],+ attrs: vec![+ ("mode".into(), AttrValue::Int(softmax_mode_code(mode))),+ ("sliding".into(), AttrValue::Bool(sliding)),+ ("window".into(), AttrValue::Int(window as i32)),+ ], }); } Node::Rotary { input, angles, out, heads, axes } => {@@ -898,38 +949,22 @@ pub struct Emitted { pub op_inventory: Vec<(fb::Op, usize)>, } -/// Emit a MAML v2 model from one recorded single-graph pass.+/// File tensors named by node offsets (kernels, biases, scales, gammas):+/// collect every resolved offset the nodes carry, inverted to file indices.+/// A tensor marked read but named by no node is host-side data (the v1+/// `host_tensor` contract: read on the CPU, never bound). A tensor neither+/// read nor named cannot reach here — `Builder::record` fails it first. ///-/// `recorded` is the [`Builder::record`] output at a fixed shape; `table` +-/// `data` are the v1 file's tensor table and data section, whose weight-/// bytes are stored verbatim into the v2 buffers. `description` names the-/// model for humans; `converter_version` and `source_sha256` trace-/// provenance. `graph_name` / `entry_name` / `roles` name the single graph,-/// its entry point, and the entry's input roles (positional over the graph-/// inputs; must cover them exactly).-///-/// The sampler's `emit_sampler` is this with its seven roles; every-/// single-graph net shares the core.-#[allow(clippy::too_many_arguments)]-pub fn emit_graph(- recorded: &Recorded,+/// Returns the quantised-kernel map (merged by the caller across graphs)+/// plus the full ref set. Scales ride beside their kernel: marked+/// referenced so the host check does not misclassify them (they are skipped+/// in emission order, not emitted as host rows).+fn collect_refs(+ nodes: &[Node], table: &[WeightTensor],- data: &[u8],- description: &str,- converter_version: &str,- source_sha256: [u8; 32],- graph_name: &str,- entry_name: &str,- roles: &[&str],-) -> Result<Emitted, String> {- // 1. Which file tensors are quantised kernels, and which are their scales.- let kernels = quant_kernels(&recorded.nodes, table, data)?;+) -> Result<(HashMap<usize, WeightQuant>, HashMap<usize, ()>), String> {+ let kernels = quant_kernels(nodes, table, &[])?; let scales = scale_indices(&kernels);- // File tensors named by node offsets (kernels, biases, scales, gammas):- // collect every resolved offset the nodes carry, inverted to file indices.- // A tensor marked read but named by no node is host-side data (the v1- // `host_tensor` contract: read on the CPU, never bound). A tensor neither- // read nor named cannot reach here — `Builder::record` fails it first. let mut node_refs: HashMap<usize, ()> = HashMap::new(); { let mut word_to_file: HashMap<u32, usize> = HashMap::new();@@ -955,7 +990,7 @@ pub fn emit_graph( elem_to_file.get(&offset).copied() } };- for node in &recorded.nodes {+ for node in nodes { match node { Node::Conv { weight, bias, act_weight, act, .. } => { // The fp16 kernel/bias resolve through elem offsets; find@@ -1027,6 +1062,107 @@ pub fn emit_graph( node_refs.insert(*scale, ()); } }+ Ok((kernels, node_refs))+}+/// One graph in a multi-graph emission: its recording plus its names.+pub struct GraphSpec<'a> {+ /// The recorded pass.+ pub recorded: &'a Recorded,+ /// Graph name in the file.+ pub graph_name: &'a str,+ /// Entry point name over this graph.+ pub entry_name: &'a str,+ /// Input roles, positional over the graph inputs.+ pub roles: &'a [&'a str],+}++/// Emit a MAML v2 model from one recorded single-graph pass.+///+/// `recorded` is the [`Builder::record`] output at a fixed shape; `table` ++/// `data` are the v1 file's tensor table and data section, whose weight+/// bytes are stored verbatim into the v2 buffers. `description` names the+/// model for humans; `converter_version` and `source_sha256` trace+/// provenance. `graph_name` / `entry_name` / `roles` name the single graph,+/// its entry point, and the entry's input roles (positional over the graph+/// inputs; must cover them exactly).+///+/// Thin wrapper over [`emit_graphs`]; every single-graph net shares it, and+/// the sampler's `emit_sampler` shares it with its seven roles.+#[allow(clippy::too_many_arguments)]+pub fn emit_graph(+ recorded: &Recorded,+ table: &[WeightTensor],+ data: &[u8],+ description: &str,+ converter_version: &str,+ source_sha256: [u8; 32],+ graph_name: &str,+ entry_name: &str,+ roles: &[&str],+) -> Result<Emitted, String> {+ emit_graphs(+ table,+ data,+ description,+ converter_version,+ source_sha256,+ &[GraphSpec { recorded, graph_name, entry_name, roles }],+ )+}++/// Emit a MAML v2 model from several recorded passes sharing one tensor table.+///+/// The multi-graph path (TinyCLIP's towers, whisper's encoder/decoder, an+/// LLM's prefill/decode): weights emit ONCE from the union of the graphs'+/// refs, then each graph's inputs/nodes/outputs emit into disjoint tensor+/// ranges, and the model digest folds every graph in order. A weight shared+/// by two graphs is one row; a tensor read by no graph is dead weight the+/// file refuses to carry; a tensor marked by one graph but referenced by+/// none is host data. Per-record `Builder::record` gates already proved each+/// pass self-consistent; the union checks here prove the file is.+pub fn emit_graphs(+ table: &[WeightTensor],+ data: &[u8],+ description: &str,+ converter_version: &str,+ source_sha256: [u8; 32],+ specs: &[GraphSpec<'_>],+) -> Result<Emitted, String> {+ if specs.is_empty() {+ return Err("a model with no graphs".into());+ }+ // 1. Union refs across graphs: quantised kernels (with cross-graph kind+ // agreement — one kernel, one quantisation), every node-named file+ // tensor, and the read flags.+ let mut kernels: HashMap<usize, WeightQuant> = HashMap::new();+ let mut node_refs: HashMap<usize, ()> = HashMap::new();+ let mut read_all = vec![false; table.len()];+ for spec in specs {+ let (kinds, refs) = collect_refs(&spec.recorded.nodes, table)?;+ for (index, kind) in kinds {+ match kernels.insert(index, kind) {+ Some(previous) if previous != kind => {+ return Err(format!("tensor {index} read with two quant kinds"));+ }+ _ => {}+ }+ }+ node_refs.extend(refs);+ for (index, mark) in spec.recorded.read.iter().enumerate() {+ if *mark && index < read_all.len() {+ read_all[index] = true;+ }+ }+ }+ if let Some(index) = read_all.iter().position(|&read| !read) {+ return Err(format!(+ "tensor {index} of {} is read by no graph; a v2 file carries no dead weights",+ read_all.len()+ ));+ }+ let scales = scale_indices(&kernels);++ // 2. Emit the weight tensors in file order (skipping scales: they ride // beside their kernel), assigning v2 tensor indices.@@ -1039,10 +1175,11 @@ pub fn emit_graph( continue; } // Host tensors are read on the CPU, never bound: they still occupy a- // v2 tensor row (placement HOST, no buffer) so the graph can name them.- // Named by no node but marked read = the v1 `host_tensor` contract.+ // v2 tensor row (placement HOST, no buffer) so the graphs can name+ // them. Named by no graph but marked by one = the v1 `host_tensor`+ // contract, unioned across graphs. let is_host = !node_refs.contains_key(&index)- && recorded.read.get(index).copied().unwrap_or(false);+ && read_all.get(index).copied().unwrap_or(false); if is_host { let tensor = table.get(index).copied().ok_or_else(|| { format!("tensor {index} of {}: out of range", table.len())@@ -1080,56 +1217,90 @@ pub fn emit_graph( let _ = weight_rows; let weights = WeightLookup::new(table, &id_map.weights)?; - // 3. Graph inputs: declaration order = binding order.- let mut input_ids = Vec::with_capacity(recorded.inputs.len());- for input in &recorded.inputs {- let v2 = id_map.alloc();- id_map.computed.insert(input.0, v2);- input_ids.push(v2);+ // 3-5. Per graph: inputs (declaration order = binding order), nodes ++ // computed tensors in first-use order, exact outputs. Each graph gets a+ // fresh tensor-id map (recordings number their ids from zero) over the+ // shared weight map and allocator, so ranges stay disjoint.+ struct PerGraph {+ nodes: Vec<EmittedNode>,+ input_ids: Vec<i32>,+ outputs: Vec<i32>,+ name: String, } let mut emit_tensors: Vec<EmittedTensor> = Vec::new();- for input in &recorded.inputs {- let shape = recorded.shapes.get(input.0).copied().unwrap_or(Shape::new(0, 0, 0));- emit_tensors.push(EmittedTensor {- name: format!("in{}", input.0),- dims: vec![shape.c as i32, shape.h as i32, shape.w as i32],- dtype: fb::DType::F16,- layout: fb::Layout::NCHW,- bytes: Vec::new(),- elems: shape.len() as u64,- quant: WeightQuant::None,- });- }- // 4. Nodes + computed tensors.- // `emit_nodes` allocates computed tensors in first-use order and records- // tensor-id → v2-index in `seen`.- let mut seen: HashMap<usize, i32> = HashMap::new();- let nodes = emit_nodes(recorded, &mut id_map, &weights, &mut emit_tensors, &mut seen)?;+ let mut graphs: Vec<PerGraph> = Vec::with_capacity(specs.len());+ for spec in specs {+ let recorded = spec.recorded;+ id_map.computed = HashMap::new();+ let mut input_ids = Vec::with_capacity(recorded.inputs.len());+ for input in &recorded.inputs {+ let v2 = id_map.alloc();+ id_map.computed.insert(input.0, v2);+ input_ids.push(v2);+ }+ for input in &recorded.inputs {+ let shape = recorded.shapes.get(input.0).copied().unwrap_or(Shape::new(0, 0, 0));+ emit_tensors.push(EmittedTensor {+ name: format!("in{}", input.0),+ dims: vec![shape.c as i32, shape.h as i32, shape.w as i32],+ dtype: fb::DType::F16,+ layout: fb::Layout::NCHW,+ bytes: Vec::new(),+ elems: shape.len() as u64,+ quant: WeightQuant::None,+ });+ }+ // `emit_nodes` allocates computed tensors in first-use order and+ // records tensor-id → v2-index in `seen`.+ let mut seen: HashMap<usize, i32> = HashMap::new();+ let nodes = emit_nodes(recorded, &mut id_map, &weights, &mut emit_tensors, &mut seen)?; - // 5. Outputs: the v2 index of each recorded output tensor id. Exact —- // no shape matching, no last-writer heuristics.- let plan_outputs: Vec<i32> = recorded- .outputs- .iter()- .map(|id| {- seen.get(&id.index()).copied().ok_or_else(|| {- format!("output tensor {} was never emitted", id.index())+ // Outputs: the v2 index of each recorded output tensor id. Exact —+ // no shape matching, no last-writer heuristics.+ let plan_outputs: Vec<i32> = recorded+ .outputs+ .iter()+ .map(|id| {+ seen.get(&id.index()).copied().ok_or_else(|| {+ format!("output tensor {} was never emitted", id.index())+ }) })- })- .collect::<Result<Vec<i32>, String>>()?;+ .collect::<Result<Vec<i32>, String>>()?;+ // Roles must cover the graph inputs exactly: a missing role is an+ // input the bridge cannot bind, an extra one a name with no tensor.+ if spec.roles.len() != input_ids.len() {+ return Err(format!(+ "entry point {} declares {} roles for {} graph inputs",+ spec.entry_name,+ spec.roles.len(),+ input_ids.len()+ ));+ }+ graphs.push(PerGraph {+ nodes,+ input_ids,+ outputs: plan_outputs,+ name: spec.graph_name.to_string(),+ });+ } // 6. Canonical digest over the graph-indexed op/edge/attr sequences // (spec section 9.2): the graph index first, then the nodes in the same- // order `infer` replays. Model-wide so a second graph (prefill +- // decode, twin towers) cannot smuggle an unaudited topology past the- // gate; single-graph files hash index 0, then fold once like every- // model with one graph.- let mut hasher = Sha256::new();- hasher.update(0u32.to_le_bytes());- digest_nodes(&mut hasher, &nodes);- let graph0: [u8; 32] = hasher.finalize().into();+ // order `infer` replays, folded across graphs in model order. A second+ // graph (prefill + decode, twin towers) cannot smuggle an unaudited+ // topology past the gate; single-graph files hash index 0, then fold+ // once like every model with one graph.+ let mut graph_digests: Vec<[u8; 32]> = Vec::with_capacity(graphs.len());+ for (index, graph) in graphs.iter().enumerate() {+ let mut hasher = Sha256::new();+ hasher.update((index as u32).to_le_bytes());+ digest_nodes(&mut hasher, &graph.nodes);+ graph_digests.push(hasher.finalize().into());+ } let mut model_hasher = Sha256::new();- model_hasher.update(graph0);+ for digest in &graph_digests {+ model_hasher.update(digest);+ } let graph_digest: [u8; 32] = model_hasher.finalize().into(); // 7. Assemble the FlatBuffers model.@@ -1138,40 +1309,37 @@ pub fn emit_graph( // reference no buffer. let buffer_offsets: Vec<flatbuffers::WIPOffset<fb::Buffer<'_>>> = Vec::new(); let _ = buffer_offsets;- // Roles must cover the graph inputs exactly: a missing role is an input- // the bridge cannot bind, an extra one a name with no tensor.- if roles.len() != input_ids.len() {- return Err(format!(- "entry point {entry_name} declares {} roles for {} graph inputs",- roles.len(),- input_ids.len()- ));- } // NOTE: assembly continues below; tensor/buffer vectors need the payloads // built first. The full builder sequence is in `assemble`.+ let assembled_graphs: Vec<AssembledGraph<'_>> = graphs+ .iter()+ .map(|graph| AssembledGraph {+ nodes: &graph.nodes,+ input_ids: &graph.input_ids,+ outputs: &graph.outputs,+ name: &graph.name,+ })+ .collect(); let assembled = assemble( &mut builder, &emitted, &emit_tensors,- &nodes,- &input_ids,- &plan_outputs,- recorded,+ &assembled_graphs,+ specs, description, converter_version, source_sha256, graph_digest,- graph_name,- entry_name,- roles, )?; let _ = assembled; let mut op_inventory: Vec<(fb::Op, usize)> = Vec::new();- for node in &nodes {- match op_inventory.iter_mut().find(|(op, _)| *op == node.op) {- Some((_, n)) => *n += 1,- None => op_inventory.push((node.op, 1)),+ for graph in &graphs {+ for node in &graph.nodes {+ match op_inventory.iter_mut().find(|(op, _)| *op == node.op) {+ Some((_, n)) => *n += 1,+ None => op_inventory.push((node.op, 1)),+ } } } op_inventory.sort_by_key(|(_, n)| std::cmp::Reverse(*n));@@ -1213,23 +1381,30 @@ pub fn emit_sampler( ) } +/// One emitted graph: its nodes plus the tensor refs the file needs.+struct AssembledGraph<'a> {+ /// Nodes in file (topological) order.+ nodes: &'a [EmittedNode],+ /// Graph inputs, declaration order = binding order.+ input_ids: &'a [i32],+ /// Graph outputs.+ outputs: &'a [i32],+ /// Graph name.+ name: &'a str,+}+ /// Build the FlatBuffers vectors and finish the model. #[allow(clippy::too_many_arguments)] fn assemble( builder: &mut flatbuffers::FlatBufferBuilder<'_>, emitted: &[EmittedTensor], computed: &[EmittedTensor],- nodes: &[EmittedNode],- input_ids: &[i32],- outputs: &[i32],- recorded: &Recorded,+ graphs: &[AssembledGraph<'_>],+ specs: &[GraphSpec<'_>], description: &str, converter_version: &str, source_sha256: [u8; 32], graph_digest: [u8; 32],- graph_name: &str,- entry_name: &str,- roles: &[&str], ) -> Result<(), String> { // Weight payloads become Buffers; each emitted weight tensor points at // its buffer. Computed tensors (buffer -1) and host tensors (no bytes)@@ -1251,7 +1426,6 @@ fn assemble( // Quantization structs are inline; build the per-tensor Tensor tables. // Scale refs: the kernel's `quant` names the v1 scale file index, which // the weight map already turned into a v2 tensor index.- let _ = recorded; let mut tensors: Vec<flatbuffers::WIPOffset<fb::Tensor<'_>>> = Vec::new(); // v2 tensor index → position in `tensors`, for scale refs. Weights were // allocated in emission order starting at 0; inputs and computed follow.@@ -1338,88 +1512,96 @@ fn assemble( } let tensors = builder.create_vector(&tensors); - // Nodes with typed attributes.- let mut node_offsets = Vec::with_capacity(nodes.len());- for node in nodes {- let inputs = builder.create_vector(&node.inputs);- let outputs = builder.create_vector(&node.outputs);- let mut attr_offsets = Vec::with_capacity(node.attrs.len());- for (name, attr) in &node.attrs {- let name = builder.create_string(name);- let (value_type, value) = match attr {- AttrValue::Int(v) => {- let t = fb::AttrInt::create(builder, &fb::AttrIntArgs { value: *v });- (fb::AttrValue::AttrInt, t.as_union_value())- }- AttrValue::Ints(vs) => {- let v = builder.create_vector(vs);- let t = fb::AttrInts::create(builder, &fb::AttrIntsArgs { value: Some(v) });- (fb::AttrValue::AttrInts, t.as_union_value())- }- AttrValue::Float(v) => {- let t = fb::AttrFloat::create(builder, &fb::AttrFloatArgs { value: *v });- (fb::AttrValue::AttrFloat, t.as_union_value())- }- AttrValue::Bool(v) => {- let t = fb::AttrBool::create(builder, &fb::AttrBoolArgs { value: *v });- (fb::AttrValue::AttrBool, t.as_union_value())- }- };- attr_offsets.push(fb::Attribute::create(+ // Nodes with typed attributes, per graph. Hoisted per graph (not one+ // shared loop) because the builder borrows mutably per create call.+ let mut graph_offsets = Vec::with_capacity(graphs.len());+ for graph in graphs {+ let mut node_offsets = Vec::with_capacity(graph.nodes.len());+ for node in graph.nodes {+ let inputs = builder.create_vector(&node.inputs);+ let outputs = builder.create_vector(&node.outputs);+ let mut attr_offsets = Vec::with_capacity(node.attrs.len());+ for (name, attr) in &node.attrs {+ let name = builder.create_string(name);+ let (value_type, value) = match attr {+ AttrValue::Int(v) => {+ let t = fb::AttrInt::create(builder, &fb::AttrIntArgs { value: *v });+ (fb::AttrValue::AttrInt, t.as_union_value())+ }+ AttrValue::Ints(vs) => {+ let v = builder.create_vector(vs);+ let t = fb::AttrInts::create(builder, &fb::AttrIntsArgs { value: Some(v) });+ (fb::AttrValue::AttrInts, t.as_union_value())+ }+ AttrValue::Float(v) => {+ let t = fb::AttrFloat::create(builder, &fb::AttrFloatArgs { value: *v });+ (fb::AttrValue::AttrFloat, t.as_union_value())+ }+ AttrValue::Bool(v) => {+ let t = fb::AttrBool::create(builder, &fb::AttrBoolArgs { value: *v });+ (fb::AttrValue::AttrBool, t.as_union_value())+ }+ };+ attr_offsets.push(fb::Attribute::create(+ builder,+ &fb::AttributeArgs { name: Some(name), value_type, value: Some(value) },+ ));+ }+ let attrs = builder.create_vector(&attr_offsets);+ node_offsets.push(fb::Node::create( builder,- &fb::AttributeArgs { name: Some(name), value_type, value: Some(value) },+ &fb::NodeArgs {+ op: node.op,+ inputs: Some(inputs),+ outputs: Some(outputs),+ attrs: Some(attrs),+ payload: None,+ }, )); }- let attrs = builder.create_vector(&attr_offsets);- node_offsets.push(fb::Node::create(+ let nodes = builder.create_vector(&node_offsets);+ // The graph's tensor scope is every v2 tensor.+ let tensor_count = emitted.len() + computed.len();+ let scope: Vec<i32> = (0..tensor_count as i32).collect();+ let scope = builder.create_vector(&scope);+ let graph_inputs = builder.create_vector(graph.input_ids);+ let graph_outputs = builder.create_vector(graph.outputs);+ let graph_name = builder.create_string(graph.name);+ graph_offsets.push(fb::Graph::create( builder,- &fb::NodeArgs {- op: node.op,- inputs: Some(inputs),- outputs: Some(outputs),- attrs: Some(attrs),- payload: None,+ &fb::GraphArgs {+ name: Some(graph_name),+ tensors: Some(scope),+ nodes: Some(nodes),+ inputs: Some(graph_inputs),+ outputs: Some(graph_outputs), }, )); }- let nodes = builder.create_vector(&node_offsets);- // The graph's tensor scope is every v2 tensor.- let tensor_count = emitted.len() + computed.len();- let scope: Vec<i32> = (0..tensor_count as i32).collect();- let scope = builder.create_vector(&scope);- let graph_inputs = builder.create_vector(input_ids);- let graph_outputs = builder.create_vector(outputs);- let graph_name = builder.create_string(graph_name);- let graph = fb::Graph::create(- builder,- &fb::GraphArgs {- name: Some(graph_name),- tensors: Some(scope),- nodes: Some(nodes),- inputs: Some(graph_inputs),- outputs: Some(graph_outputs),- },- );- let graphs = builder.create_vector(&[graph]);+ let graphs = builder.create_vector(&graph_offsets); - // Entry point over graph 0. Roles bind positionally to the graph inputs;- // the caller guarantees they cover the inputs exactly.- let entry_name = builder.create_string(entry_name);- let roles: Vec<flatbuffers::WIPOffset<&str>> = roles- .iter()- .map(|role| builder.create_string(role))- .collect();- let roles = builder.create_vector(&roles);- let entry_point = fb::EntryPoint::create(- builder,- &fb::EntryPointArgs {- name: Some(entry_name),- graph: 0,- inputs: Some(roles),- step_uniforms: None,- },- );- let entry_points = builder.create_vector(&[entry_point]);+ // One entry point per spec, over its graph by model order. Roles bind+ // positionally to the graph inputs; the driver checked coverage.+ let mut entry_offsets = Vec::with_capacity(specs.len());+ for (index, spec) in specs.iter().enumerate() {+ let entry_name = builder.create_string(spec.entry_name);+ let roles: Vec<flatbuffers::WIPOffset<&str>> = spec+ .roles+ .iter()+ .map(|role| builder.create_string(role))+ .collect();+ let roles = builder.create_vector(&roles);+ entry_offsets.push(fb::EntryPoint::create(+ builder,+ &fb::EntryPointArgs {+ name: Some(entry_name),+ graph: index as u32,+ inputs: Some(roles),+ step_uniforms: None,+ },+ ));+ }+ let entry_points = builder.create_vector(&entry_offsets); let description = builder.create_string(description); let converter_version = builder.create_string(converter_version);
library/ml/src/main/rust/src/maml2/infer.rs
diff --git a/library/ml/src/main/rust/src/maml2/infer.rs b/library/ml/src/main/rust/src/maml2/infer.rsindex 236550cebb..146a8c5fcb 100644--- a/library/ml/src/main/rust/src/maml2/infer.rs+++ b/library/ml/src/main/rust/src/maml2/infer.rs@@ -302,6 +302,11 @@ fn infer_node( Ok(vec![Inferred { dims: vec![m, out_h, out_w], layout: computed_layout }]) } fb::Op::MatMul => {+ // Quantised convolution in file vocabulary: 1x1 projections and+ // heads, but also strided/padded/grouped kernels (the patch+ // projection, maia's grouped expansion). Geometry rides the same+ // attrs as `Conv`; lowering routes by shape exactly as the+ // hand-written pass does. if inputs.len() != 4 && inputs.len() != 3 { return Err(err("MatMul wants [a, w, s, b] or [a, w, b]")); }@@ -310,8 +315,16 @@ fn infer_node( if a.len() != 3 || w.len() < 2 { return Err(err("MatMul shapes are not [c, h, w] / [m, ...]")); }- // Pointwise: `[m, 1, positions]`.- Ok(vec![Inferred { dims: vec![w[0], a[1], a[2]], layout: computed_layout }])+ let kernel = attrs.ints("kernel")?;+ let stride = attrs.ints("stride")?;+ let dilation = attrs.ints("dilation")?;+ let pads = attrs.ints("pads")?;+ if kernel.len() != 2 || stride.len() != 2 || dilation.len() != 2 || pads.len() != 4 {+ return Err(err("MatMul geometry attrs are not kernel/stride/dilation/pads"));+ }+ let out_h = conv_out(a[1], kernel[0], stride[0], dilation[0], pads[0] + pads[2]);+ let out_w = conv_out(a[2], kernel[1], stride[1], dilation[1], pads[1] + pads[3]);+ Ok(vec![Inferred { dims: vec![w[0], out_h, out_w], layout: computed_layout }]) } fb::Op::ConvTranspose => { // Learned upsample: weights `[in_c, m, kh, kw]`, output@@ -477,8 +490,10 @@ fn infer_node( Ok(vec![Inferred { dims: x, layout: computed_layout }]) } fb::Op::Attention => {- // Two phases share one op: phase 0 scores (q, k -> map), phase 1- // apply (probs, v -> mixed). The `phase` attr says which.+ // Four phases share one op: 0 scores (q, k -> map), 1 apply+ // (probs, v -> mixed), 2 relative scores, 3 relative apply. The+ // `phase` attr says which; relative phases carry the learned+ // offset table as a third input plus `rel_offsets`. let phase = attrs.opt_int("phase")?.unwrap_or(0); if phase == 0 { if inputs.len() != 2 {@@ -491,7 +506,7 @@ fn infer_node( return Err(err("Attention shapes are not sequences")); } Ok(vec![Inferred { dims: vec![heads, q[2], k[2]], layout: computed_layout }])- } else {+ } else if phase == 1 { if inputs.len() != 2 { return Err(err("Attention apply wants [probs, v]")); }@@ -506,7 +521,67 @@ fn infer_node( let kv_heads = attrs.opt_int("kv_heads")?.unwrap_or(heads); let head_dim = v[0] / kv_heads.max(1); Ok(vec![Inferred { dims: vec![heads * head_dim, 1, probs[1]], layout: computed_layout }])+ } else if phase == 2 {+ if inputs.len() != 3 {+ return Err(err("relative Attention scores wants [q, k, table]"));+ }+ let q = shape_of(inputs[0])?.dims.clone();+ let k = shape_of(inputs[1])?.dims.clone();+ let table = shape_of(inputs[2])?.dims.clone();+ let heads = attrs.int("heads")?;+ let offsets = attrs.int("rel_offsets")?;+ if q.len() != 3 || k.len() != 3 {+ return Err(err("Attention shapes are not sequences"));+ }+ if q[2] != k[2] {+ return Err(err("relative offsets need one sequence, not two lengths"));+ }+ // Table is `[offsets, head_dim]` shared across heads.+ if table.len() < 2 || table[0] != offsets {+ return Err(err(&format!(+ "relative table {table:?} does not hold {offsets} offsets"+ )));+ }+ Ok(vec![Inferred { dims: vec![heads, q[2], k[2]], layout: computed_layout }])+ } else if phase == 3 {+ if inputs.len() != 3 {+ return Err(err("relative Attention apply wants [probs, v, table]"));+ }+ let probs = shape_of(inputs[0])?.dims.clone();+ let v = shape_of(inputs[1])?.dims.clone();+ let table = shape_of(inputs[2])?.dims.clone();+ let heads = attrs.int("heads")?;+ let offsets = attrs.int("rel_offsets")?;+ if probs.len() != 3 || v.len() != 3 {+ return Err(err("Attention shapes are not sequences"));+ }+ if table.len() < 2 || table[0] != offsets {+ return Err(err(&format!(+ "relative table {table:?} does not hold {offsets} offsets"+ )));+ }+ Ok(vec![Inferred { dims: vec![v[0], 1, probs[1]], layout: computed_layout }])+ } else {+ Err(err(&format!("Attention phase {phase} is not 0, 1, 2, or 3")))+ }+ }+ fb::Op::Embedding => {+ if inputs.len() != 2 {+ return Err(err("Embedding wants [ids, table]"));+ }+ let ids = shape_of(inputs[0])?.dims.clone();+ let table = shape_of(inputs[1])?.dims.clone();+ let rows = attrs.int("rows")?;+ if table.len() < 2 || table[0] != rows {+ return Err(err(&format!("embedding table {table:?} has {rows} rows")));+ }+ // Ids split across two lanes past fp16-exact range (v1+ // `EMBED_LANE`): `[lanes, 1, T]` with lanes 1 or 2.+ let lanes = if rows > crate::nets::EMBED_LANE as i32 { 2 } else { 1 };+ if ids.len() != 3 || ids[0] != lanes || ids[1] != 1 {+ return Err(err(&format!("embedding ids {ids:?} are not [{lanes}, 1, T]"))); }+ Ok(vec![Inferred { dims: vec![table[1], 1, ids[2]], layout: computed_layout }]) } fb::Op::Softmax => { if inputs.len() != 1 {
library/ml/src/main/rust/src/maml2/lower.rs
diff --git a/library/ml/src/main/rust/src/maml2/lower.rs b/library/ml/src/main/rust/src/maml2/lower.rsindex 07a5f612ea..a9743fefb8 100644--- a/library/ml/src/main/rust/src/maml2/lower.rs+++ b/library/ml/src/main/rust/src/maml2/lower.rs@@ -329,6 +329,59 @@ pub fn lower_nchw( lower_with_options(verified, inferred, weights, entry_graph, true) } +/// Every tensor any graph names: node inputs plus attribute-carried weight+/// refs (PRelu's `slope`), plus host tensors (no buffer, read on the CPU).+///+/// File-wide union across all graphs: in a multi-graph file a weight the+/// lowered graph never names may belong to another graph. Tensors named by+/// nothing at all are dead weight the file refuses to carry — the same gate+/// the emitter enforces, re-checked here so a hand-built file gets no free+/// pass around emission.+fn file_refs(model: fb::Model<'_>) -> Result<Vec<bool>, String> {+ let tensors = model.tensors().ok_or("a model with no tensors")?;+ let graphs = model.graphs().ok_or("a model with no graphs")?;+ let mut read = vec![false; tensors.len()];+ for g in 0..graphs.len() {+ let nodes = graphs.get(g).nodes().ok_or_else(|| format!("graph {g} has no nodes"))?;+ for n in 0..nodes.len() {+ let node = nodes.get(n);+ if let Some(inputs) = node.inputs() {+ for i in 0..inputs.len() {+ let t = inputs.get(i) as usize;+ if t < read.len() {+ read[t] = true;+ }+ }+ }+ if let Some(attrs) = node.attrs() {+ for i in 0..attrs.len() {+ let attr = attrs.get(i);+ if attr.name() == Some("slope") {+ if let Some(v) = attr.value_as_attr_int() {+ let t = v.value() as usize;+ if t < read.len() {+ read[t] = true;+ }+ }+ }+ }+ }+ }+ }+ for t in 0..tensors.len() {+ if tensors.get(t).buffer() == -1 {+ read[t] = true;+ }+ }+ if let Some(index) = read.iter().position(|&read| !read) {+ return Err(format!(+ "tensor {index} of {} is named by no graph; a v2 file carries no dead weights",+ read.len()+ ));+ }+ Ok(read)+}+ /// [`lower`] with an explicit blocked-rewrite switch. fn lower_with_options( verified: &Verified<'_>,@@ -358,51 +411,17 @@ fn lower_with_options( // dropped — the file loads, the pass runs, and one layer reads whatever // its neighbour's payload happens to be. //+ // Coverage is file-wide, not per-graph: in a multi-graph file a weight+ // the lowered graph never names may belong to another graph, and that+ // is that graph's business. What this lowering must prove is that every+ // tensor IT names resolves — the resolvability check below — while the+ // union gate (every tensor named somewhere) already ran at emit time+ // and re-runs here cheaply.+ // // Marking happens up front (not after lowering) because `finish` // consumes the builder: the check must be armed before the nodes replay. {- let tensors = model.tensors().ok_or("a model with no tensors")?;- let nodes = graph.nodes().ok_or("a graph with no nodes")?;- let mut read: Vec<bool> = vec![false; tensors.len()];- for n in 0..nodes.len() {- let node = nodes.get(n);- if let Some(inputs) = node.inputs() {- for i in 0..inputs.len() {- let t = inputs.get(i) as usize;- if t < read.len() {- read[t] = true;- }- }- }- // Weight refs that ride attributes, not inputs: PRelu's `slope`.- // A slope names a buffered weight no input edge covers; without- // this the gate below mistakes it for a dropped layer.- if let Some(attrs) = node.attrs() {- for i in 0..attrs.len() {- let attr = attrs.get(i);- if attr.name() == Some("slope") {- if let Some(v) = attr.value_as_attr_int() {- let t = v.value() as usize;- if t < read.len() {- read[t] = true;- }- }- }- }- }- }- // Host tensors (placement HOST, no buffer) are read on the CPU.- for t in 0..tensors.len() {- if tensors.get(t).buffer() == -1 {- read[t] = true;- }- }- if let Some(index) = read.iter().position(|&read| !read) {- return Err(format!(- "the lowering never reads tensor {index} of {}. A v2 graph that names a weight no node reads is a dropped layer.",- read.len()- ));- }+ let read = file_refs(model)?; // Resolvability: every named weight must resolve through the bridge // in its dtype class (word vs element addressing). A mismatch fails // here rather than silently binding the wrong payload.@@ -464,60 +483,11 @@ fn lower_with_options( .ok_or_else(|| format!("output tensor {t} was never written")) }) .collect::<Result<Vec<Id>, String>>()?;- // Every-tensor rule (mirrors `Builder::record`): each buffered weight- // tensor must have been named by a node, and each host tensor must be- // declared. `Builder::record` enforces this from the `read` flags the- // indexed builders set; the `*_raw` door bypasses those flags (it takes- // resolved offsets), so the loader enforces the same rule here, from the- // node refs, before finishing. A skipped weight is a layer the lowering- // dropped — the file loads, the pass runs, and one layer reads whatever- // its neighbour's payload happens to be.+ // File-wide coverage re-check before finishing (see the pre-pass): the+ // `*_raw` door never sets the builder's read flags, so the union refs+ // arm `finish`'s gate the same way up front. {- let tensors = model.tensors().ok_or("a model with no tensors")?;- let nodes = graph.nodes().ok_or("a graph with no nodes")?;- let mut read = vec![false; tensors.len()];- for n in 0..nodes.len() {- let node = nodes.get(n);- if let Some(inputs) = node.inputs() {- for i in 0..inputs.len() {- let t = inputs.get(i) as usize;- if t < read.len() && tensors.get(t).buffer() != -1 {- read[t] = true;- }- }- }- // Weight refs that ride attributes, not inputs: PRelu's `slope`- // (see the pre-pass above).- if let Some(attrs) = node.attrs() {- for i in 0..attrs.len() {- let attr = attrs.get(i);- if attr.name() == Some("slope") {- if let Some(v) = attr.value_as_attr_int() {- let t = v.value() as usize;- if t < read.len() {- read[t] = true;- }- }- }- }- }- }- // Host tensors (placement HOST, no buffer) are read on the CPU: mark- // them named so the rule below exempts them the way- // `Builder::host_tensor` exempts the v1 path.- for t in 0..tensors.len() {- let tensor = tensors.get(t);- if tensor.buffer() == -1 {- read[t] = true;- }- }- if let Some(index) = read.iter().position(|&read| !read) {- return Err(format!(- "the lowering never reads tensor {index} of {}. A v2 graph that names a weight no node reads is a dropped layer.",- read.len()- ));- }- builder.mark_read(&read);+ builder.mark_read(&file_refs(model)?); } let mut plan = builder.finish(&outputs)?; if !nchw_only {@@ -546,7 +516,7 @@ fn rewrite_blocked_kinds( verified: &Verified<'_>, entry_graph: usize, ) -> Result<(), String> {- use crate::nets::{Kind, Op};+ use crate::nets::Op; let model = verified.model; let tensors = model.tensors().ok_or("a model with no tensors")?; let graphs = model.graphs().ok_or("a model with no graphs")?;@@ -767,16 +737,27 @@ fn lower_node( ) } fb::Op::MatMul => {- // Quantised 1x1: `[a, w, s, b]`. The loader routes by shape- // through `conv_int8_raw_fused`, which lowers to the- // tiled/GEMV/untiled kernels — including grouped 1x1s (maia's- // replicated smolgen expansion, group 8), which take the untiled- // path exactly as the hand-written pass does. Groups ride the- // node attrs; the kernel dims carry per-group taps.+ // Quantised convolution: `[a, w, s, b]`. 1x1 projections take+ // the tiled/GEMV kernels; strided, padded, or grouped kernels+ // take the untiled one — `conv_int8_raw_fused` routes by shape+ // exactly as the hand-written pass does, so the loader passes+ // the file geometry through rather than re-deciding it. if inputs.len() != 4 { return Err(err("MatMul wants [a, w, s, b]")); } let act = act_from_code(attrs.int("activation")?).map_err(|e| err(&e))?;+ let quant = match attrs.int("quant")? {+ 1 => crate::nets::Quant::I8,+ 2 => crate::nets::Quant::I4,+ q => return Err(err(&format!("MatMul quant {q} is not 1 (int8) or 2 (int4)"))),+ };+ let kernel = attrs.ints("kernel")?;+ let stride = attrs.ints("stride")?;+ let dilation = attrs.ints("dilation")?;+ let pads = attrs.ints("pads")?;+ if kernel.len() != 2 || stride.len() != 2 || dilation.len() != 2 || pads.len() != 4 {+ return Err(err("MatMul geometry attrs are not kernel/stride/dilation/pads"));+ } let groups = attrs.int("groups").unwrap_or(1) as u32; let m = tensors .get(inputs[1] as usize)@@ -788,7 +769,9 @@ fn lower_node( .dims() .map(|d| if d.len() > 1 { d.get(1) as u32 } else { 0 }) .unwrap_or(0);- let w = weight_word(inputs[1], &[m, in_c, 1, 1])?;+ let kh = kernel[0] as u32;+ let kw = kernel[1] as u32;+ let w = weight_word(inputs[1], &[m, in_c, kh, kw])?; let s = weight_elem(inputs[2])?; let b = weight_elem(inputs[3])?; let res = attrs.opt_int("res").map(id_of).transpose()?;@@ -800,12 +783,12 @@ fn lower_node( b, m, act,- (1, 1),- (1, 1),- (1, 1),- (0, 0, 0, 0),+ (kh, kw),+ (stride[0] as u32, stride[1] as u32),+ (dilation[0] as u32, dilation[1] as u32),+ (pads[0] as u32, pads[1] as u32, pads[2] as u32, pads[3] as u32), groups,- crate::nets::Quant::I8,+ quant, res, shift, )@@ -953,7 +936,8 @@ fn lower_node( builder.layer_norm_raw(id_of(inputs[0])?, g, be, epsilon) } fb::Op::Attention => {- // Phase 0 scores / phase 1 apply share one op; split by `phase`.+ // Phases 0/1 scores/apply share builders with the relative+ // phases 2/3; split by `phase`. let phase = attrs.opt_int("phase").unwrap_or(0); let heads = attrs.int("heads")? as u32; if phase == 0 {@@ -961,18 +945,78 @@ fn lower_node( return Err(err("Attention scores wants [q, k]")); } builder.attn_scores(id_of(inputs[0])?, id_of(inputs[1])?, heads)- } else {+ } else if phase == 1 { if inputs.len() != 2 { return Err(err("Attention apply wants [probs, v]")); } builder.attn_apply(id_of(inputs[0])?, id_of(inputs[1])?, heads)+ } else if phase == 2 {+ if inputs.len() != 3 {+ return Err(err("relative Attention scores wants [q, k, table]"));+ }+ let scale = attrs.float("scale")?;+ let offsets = attrs.int("rel_offsets")? as u32;+ let t = weight_elem(inputs[2])?;+ builder.attn_scores_relative_raw(+ id_of(inputs[0])?,+ id_of(inputs[1])?,+ heads,+ scale,+ t,+ offsets,+ )+ } else if phase == 3 {+ if inputs.len() != 3 {+ return Err(err("relative Attention apply wants [probs, v, table]"));+ }+ let offsets = attrs.int("rel_offsets")? as u32;+ let t = weight_elem(inputs[2])?;+ builder.attn_apply_relative_raw(+ id_of(inputs[0])?,+ id_of(inputs[1])?,+ heads,+ t,+ offsets,+ )+ } else {+ return Err(err(&format!("Attention phase {phase} is not 0, 1, 2, or 3"))); } }+ fb::Op::Embedding => {+ if inputs.len() != 2 {+ return Err(err("Embedding wants [ids, table]"));+ }+ let rows = attrs.int("rows")? as u32;+ // Rank 2 `[rows, channels]`, possibly padded to rank 3 by the+ // emitter's uniform rank-3 weight rows.+ let table_dims = tensors+ .get(inputs[1] as usize)+ .dims()+ .map(|d| (0..d.len()).map(|i| d.get(i) as u32).collect::<Vec<u32>>())+ .unwrap_or_default();+ if table_dims.len() < 2 || table_dims[0] != rows {+ return Err(err("embedding table is not [rows, channels]"));+ }+ let t = weight_elem(inputs[1])?;+ builder.embed_raw(id_of(inputs[0])?, t, rows, table_dims[1])+ } fb::Op::Softmax => { if inputs.len() != 1 { return Err(err("Softmax wants [x]")); }- builder.softmax(id_of(inputs[0])?)+ // Full, causal, and prefix share one file op; the mode, window,+ // and sliding attrs pick the pipeline. A sliding full softmax is+ // still full (sliding only narrows causal and prefix bounds).+ let mode = attrs.int("mode")?;+ let window = attrs.opt_int("window").unwrap_or(0);+ let sliding = attrs.opt_bool("sliding");+ match (mode, window, sliding) {+ (0, _, false) => builder.softmax(id_of(inputs[0])?),+ (1, 0, false) => builder.softmax_causal(id_of(inputs[0])?),+ (1, _, _) => builder.softmax_causal_windowed(id_of(inputs[0])?, window as u32),+ (2, _, _) => builder.softmax_prefix(id_of(inputs[0])?, sliding),+ _ => return Err(err(&format!("Softmax mode {mode} is not 0, 1, or 2"))),+ } } fb::Op::RotaryEmbedding => { if inputs.len() != 2 {
library/ml/src/main/rust/src/maml2/parity.rs
diff --git a/library/ml/src/main/rust/src/maml2/parity.rs b/library/ml/src/main/rust/src/maml2/parity.rsindex 5ba5e3f9c0..b55275c8e6 100644--- a/library/ml/src/main/rust/src/maml2/parity.rs+++ b/library/ml/src/main/rust/src/maml2/parity.rs@@ -145,13 +145,15 @@ fn lowered_plan_schedules_like_v1() { /// /// Builds the v1 plan against the real `Offsets` (never the `Shapes` stub, /// whose index-as-address reads wrong weights on a real blob), lowers the-/// v2 file, and requires bit-exact outputs through the same interpreter on-/// the same invented inputs. Skips quietly when either asset is absent.+/// v2 file's `entry` graph, and requires bit-exact outputs through the same+/// interpreter on the same invented inputs. Skips quietly when either asset+/// is absent. fn assert_bit_exact( what: &str, v1asset: &str, graph_id: u32, v2asset: &str,+ entry: usize, build_v1: impl FnOnce(&crate::weights::Offsets) -> Result<crate::nets::Plan, String>, inputs: Vec<Vec<f32>>, ) {@@ -179,7 +181,7 @@ fn assert_bit_exact( let verified = verify::verify(&bytes).expect("verify"); let inferred = infer::infer(&verified).expect("infer"); let bridge = lower::V2Weights::new(&verified).expect("bridge");- let plan = lower::lower(&verified, &inferred[0], &bridge, 0).expect("lower");+ let plan = lower::lower(&verified, &inferred[entry], &bridge, entry).expect("lower"); let refs: Vec<&[f32]> = inputs.iter().map(|v| v.as_slice()).collect(); assert_eq!( refs.len(),@@ -231,6 +233,7 @@ fn v2_plan_matches_v1_bit_exact() { "speech/src/main/assets/supertonic/supertonic_ve.maml", weights::graph::SUPERTONIC_VE, "speech/src/main/assets/supertonic/supertonic_ve.maml2",+ 0, |offsets| supertonic_sampler::build(offsets, 49, 55), spread_inputs( &[@@ -257,6 +260,7 @@ fn v2_selfie_matches_v1_bit_exact() { "camera/src/main/assets/selfie_segmentation.maml", weights::graph::SELFIE, "camera/src/main/assets/selfie_segmentation.maml2",+ 0, |offsets| selfie::build(offsets), spread_inputs(&[(3usize, 256usize, 256usize)], 0.0), );@@ -271,6 +275,7 @@ fn v2_u2netp_matches_v1_bit_exact() { "photos/src/main/assets/u2netp.maml", weights::graph::U2NETP, "photos/src/main/assets/u2netp.maml2",+ 0, |offsets| u2netp::build(offsets), spread_inputs(&[(3usize, 320usize, 320usize)], 1.0), );@@ -285,6 +290,7 @@ fn v2_scrfd_matches_v1_bit_exact() { "photos/src/main/assets/scrfd_500m.maml", weights::graph::SCRFD, "photos/src/main/assets/scrfd_500m.maml2",+ 0, |offsets| scrfd::build(offsets, 640, 640), spread_inputs(&[(3usize, 640usize, 640usize)], 2.0), );@@ -300,6 +306,7 @@ fn v2_mobilefacenet_matches_v1_bit_exact() { "photos/src/main/assets/w600k_mbf.maml", weights::graph::MOBILEFACENET, "photos/src/main/assets/w600k_mbf.maml2",+ 0, |offsets| mobilefacenet::build(offsets), spread_inputs(&[(3usize, 112usize, 112usize)], 3.0), );@@ -314,6 +321,7 @@ fn v2_ppocr_det_matches_v1_bit_exact() { "library/ocr/src/main/assets/ppocr_det.maml", weights::graph::PPOCR_DET, "library/ocr/src/main/assets/ppocr_det.maml2",+ 0, |offsets| ppocr_det::build(offsets, 960, 960), spread_inputs(&[(3usize, 960usize, 960usize)], 4.0), );@@ -328,6 +336,7 @@ fn v2_ppocr_rec_matches_v1_bit_exact() { "library/ocr/src/main/assets/ppocr_rec.maml", weights::graph::PPOCR_REC, "library/ocr/src/main/assets/ppocr_rec.maml2",+ 0, |offsets| ppocr_rec_extra::build(offsets, 320), spread_inputs(&[(3usize, 48usize, 320usize)], 5.0), );@@ -343,6 +352,7 @@ fn v2_maia_matches_v1_bit_exact() { "games/chess/src/main/assets/maia3-5m.maml", weights::graph::MAIA, "games/chess/src/main/assets/maia3-5m.maml2",+ 0, |offsets| maia::build(offsets), spread_inputs( &[(@@ -354,3 +364,81 @@ fn v2_maia_matches_v1_bit_exact() { ), ); }++/// True numeric parity for the supertonic vocoder at 49 frames.+#[test]+fn v2_vocoder_matches_v1_bit_exact() {+ use crate::nets::supertonic_vocoder;+ assert_bit_exact(+ "vocoder at 49 frames",+ "speech/src/main/assets/supertonic/supertonic_voc.maml",+ weights::graph::SUPERTONIC_VOC,+ "speech/src/main/assets/supertonic/supertonic_voc.maml2",+ 0,+ |offsets| supertonic_vocoder::build(offsets, 49),+ spread_inputs(&[(24usize, 1usize, 294usize)], 7.0),+ );+}++/// True numeric parity for the supertonic duration predictor at 55 chars+/// (two outputs: the encoder state and the log-seconds).+#[test]+fn v2_duration_matches_v1_bit_exact() {+ use crate::nets::supertonic_duration;+ assert_bit_exact(+ "duration at 55 chars",+ "speech/src/main/assets/supertonic/supertonic_dp.maml",+ weights::graph::SUPERTONIC_DP,+ "speech/src/main/assets/supertonic/supertonic_dp.maml2",+ 0,+ |offsets| supertonic_duration::build(offsets, 55),+ spread_inputs(&[(2usize, 1usize, 56usize), (128usize, 1usize, 1usize)], 8.0),+ );+}++/// True numeric parity for the supertonic text encoder at 55 chars+/// (exercises relative attention and embeddings through the file).+#[test]+fn v2_text_matches_v1_bit_exact() {+ use crate::nets::supertonic_text;+ assert_bit_exact(+ "text at 55 chars",+ "speech/src/main/assets/supertonic/supertonic_ttl.maml",+ weights::graph::SUPERTONIC_TTL,+ "speech/src/main/assets/supertonic/supertonic_ttl.maml2",+ 0,+ |offsets| supertonic_text::build(offsets, 55),+ spread_inputs(&[(2usize, 1usize, 55usize), (256usize, 1usize, 50usize)], 9.0),+ );+}++/// True numeric parity for TinyCLIP's vision tower: entry 0 of the first+/// multi-graph v2 file.+#[test]+fn v2_tinyclip_image_matches_v1_bit_exact() {+ use crate::nets::tinyclip;+ assert_bit_exact(+ "tinyclip image at 224x224",+ "photos/src/main/assets/clip/tinyclip.maml",+ weights::graph::TINYCLIP,+ "photos/src/main/assets/clip/tinyclip.maml2",+ 0,+ |offsets| tinyclip::build(offsets, tinyclip::Mode::Image),+ spread_inputs(&[(3usize, 224usize, 224usize)], 10.0),+ );+}++/// True numeric parity for TinyCLIP's text tower at 16 positions: entry 1.+#[test]+fn v2_tinyclip_text_matches_v1_bit_exact() {+ use crate::nets::tinyclip;+ assert_bit_exact(+ "tinyclip text at 16 positions",+ "photos/src/main/assets/clip/tinyclip.maml",+ weights::graph::TINYCLIP,+ "photos/src/main/assets/clip/tinyclip.maml2",+ 1,+ |offsets| tinyclip::build(offsets, tinyclip::Mode::Text { len: 16 }),+ spread_inputs(&[(256usize, 1usize, 16usize)], 11.0),+ );+}
library/ml/src/main/rust/src/nets/mod_part6.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part6.rs b/library/ml/src/main/rust/src/nets/mod_part6.rsindex 234473211f..8bd457dd5d 100644--- a/library/ml/src/main/rust/src/nets/mod_part6.rs+++ b/library/ml/src/main/rust/src/nets/mod_part6.rs@@ -465,4 +465,36 @@ impl<'a> Builder<'a> { self.nodes.push(Node::AttnScoresRelative { q, k, out, heads, scale, table, offsets }); out }++ /// [`Builder::attn_scores_relative`] with a resolved table offset rather+ /// than a table index.+ ///+ /// As [`Builder::conv_raw`]: the loader validated shapes at inference, so+ /// lowering only translates addressing.+ pub fn attn_scores_relative_raw(+ &mut self,+ q: Id,+ k: Id,+ heads: u32,+ scale: f32,+ table: u32,+ offsets: u32,+ ) -> Id {+ let (out, _) = self.score_map(q, k, heads, heads);+ self.nodes.push(Node::AttnScoresRelative { q, k, out, heads, scale, table, offsets });+ out+ }++ /// [`Builder::embed`] with a resolved table offset rather than a table+ /// index.+ ///+ /// As [`Builder::conv_raw`]: the loader validated shapes at inference, so+ /// lowering only translates addressing. `rows`/`channels` are the table's+ /// stored dims.+ pub fn embed_raw(&mut self, ids: Id, table: u32, rows: u32, channels: u32) -> Id {+ let shape = self.shape_of(ids);+ let out = self.tensor(Shape::new(channels, 1, shape.w));+ self.nodes.push(Node::Embed { ids, out, table, rows });+ out+ } }
library/ml/src/main/rust/src/nets/mod_part7.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part7.rs b/library/ml/src/main/rust/src/nets/mod_part7.rsindex de90e6b41f..c7e19c8b71 100644--- a/library/ml/src/main/rust/src/nets/mod_part7.rs+++ b/library/ml/src/main/rust/src/nets/mod_part7.rs@@ -24,6 +24,24 @@ impl<'a> Builder<'a> { out } + /// [`Builder::attn_apply_relative`] with a resolved table offset rather+ /// than a table index.+ ///+ /// As [`Builder::conv_raw`]: the loader validated shapes at inference, so+ /// lowering only translates addressing.+ pub fn attn_apply_relative_raw(+ &mut self,+ probs: Id,+ v: Id,+ heads: u32,+ table: u32,+ offsets: u32,+ ) -> Id {+ let out = self.mixed(probs, v, heads);+ self.nodes.push(Node::AttnApplyRelative { probs, v, out, heads, table, offsets });+ out+ }+ /// Attention scores over a backward sliding window of `band` keys, as a `[heads, T, band]` /// band, with the relative-position term and the `cap` logit softcap fused in. ///
library/ml/src/main/rust/src/nets/supertonic_duration.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_duration.rs b/library/ml/src/main/rust/src/nets/supertonic_duration.rsindex 5429cee3fb..a5246a600b 100644--- a/library/ml/src/main/rust/src/nets/supertonic_duration.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_duration.rs@@ -183,6 +183,15 @@ fn depthwise(b: &mut Builder, l: &mut Layers, x: Id) -> Id { /// `[64, 1, chars + 1]` state, which is the tensor worth checking for parity, and the one value /// [`seconds`] exponentiates. pub fn build(weights: &dyn WeightSource, chars: u32) -> Result<Plan, String> {+ Ok(record(weights, chars)?.plan)+}++/// Record the duration pass for an utterance of `chars` characters.+///+/// [`build`] is this plus `Op` emission; the MAML v2 emitter needs the graph+/// without the plan, after the same fusion fold and the same every-tensor+/// rule. Split out so both share the body verbatim. See [`Builder::record`].+pub fn record(weights: &dyn WeightSource, chars: u32) -> Result<crate::nets::Recorded, String> { if chars == 0 { return Err("a duration pass over no characters".into()); }@@ -255,7 +264,7 @@ pub fn build(weights: &dyn WeightSource, chars: u32) -> Result<Plan, String> { if l.next != TENSORS { return Err(format!("the forward pass claims {} tensors, not {TENSORS}", l.next)); }- builder.finish(&[encoded, log_seconds])+ builder.record(&[encoded, log_seconds], &crate::weights::Offsets::empty()) } #[cfg(test)]
library/ml/src/main/rust/src/nets/supertonic_text.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_text.rs b/library/ml/src/main/rust/src/nets/supertonic_text.rsindex 778b2d1346..84245c1ec2 100644--- a/library/ml/src/main/rust/src/nets/supertonic_text.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_text.rs@@ -189,6 +189,15 @@ fn depthwise(b: &mut Builder, l: &mut Layers, x: Id, dilation: u32) -> Id { /// and the voice's `style_ttl` **transposed** to `[256, 1, 50]`. The output is /// `[256, 1, chars]`, which the sampler conditions on. pub fn build(weights: &dyn WeightSource, chars: u32) -> Result<Plan, String> {+ Ok(record(weights, chars)?.plan)+}++/// Record the encoder for an utterance of `chars` characters.+///+/// [`build`] is this plus `Op` emission; the MAML v2 emitter needs the graph+/// without the plan, after the same fusion fold and the same every-tensor+/// rule. Split out so both share the body verbatim. See [`Builder::record`].+pub fn record(weights: &dyn WeightSource, chars: u32) -> Result<crate::nets::Recorded, String> { if chars == 0 { return Err("a text encoder pass over no characters".into()); }@@ -254,7 +263,7 @@ pub fn build(weights: &dyn WeightSource, chars: u32) -> Result<Plan, String> { if l.next != TENSORS { return Err(format!("the forward pass claims {} tensors, not {TENSORS}", l.next)); }- builder.finish(&[out])+ builder.record(&[out], &crate::weights::Offsets::empty()) } #[cfg(test)]
library/ml/src/main/rust/src/nets/supertonic_vocoder.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_vocoder.rs b/library/ml/src/main/rust/src/nets/supertonic_vocoder.rsindex da32491fc8..b41b429718 100644--- a/library/ml/src/main/rust/src/nets/supertonic_vocoder.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_vocoder.rs@@ -164,13 +164,22 @@ pub fn interleave(channelled: &[f32]) -> Vec<f32> { /// output is `[512, 1, 6 * frames]`, which the caller reads transposed as /// `frames * SAMPLES_PER_FRAME` samples. pub fn build(weights: &dyn WeightSource, frames: u32) -> Result<Plan, String> {+ Ok(record(weights, frames)?.plan)+}++/// Record the vocoder for a latent of `frames` frames.+///+/// [`build`] is this plus `Op` emission; the MAML v2 emitter needs the graph+/// without the plan, after the same fusion fold and the same every-tensor+/// rule. Split out so both share the body verbatim. See [`Builder::record`].+pub fn record(weights: &dyn WeightSource, frames: u32) -> Result<crate::nets::Recorded, String> { let l = &mut Layers { next: 0 }; let mut builder = Builder::new(weights); let samples = sequence(&mut builder, l, frames)?; if l.next != TENSORS { return Err(format!("the forward pass claims {} tensors, not {TENSORS}", l.next)); }- builder.finish(&[samples])+ builder.record(&[samples], &crate::weights::Offsets::empty()) } /// The vocoder's graph with its inputs declared, returning the sample tensor.
library/ml/src/main/rust/src/nets/tinyclip.rs
diff --git a/library/ml/src/main/rust/src/nets/tinyclip.rs b/library/ml/src/main/rust/src/nets/tinyclip.rsindex 732a4503c3..eb7f3cca28 100644--- a/library/ml/src/main/rust/src/nets/tinyclip.rs+++ b/library/ml/src/main/rust/src/nets/tinyclip.rs@@ -245,14 +245,30 @@ fn encoder_layer(b: &mut Builder, l: &mut Layers, x: Id, causal: bool) -> Id { /// Build one of TinyCLIP's two passes. See [`Mode`]. pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> {+ Ok(record(weights, mode)?.plan)+}++/// Record one of TinyCLIP's two passes: the resolved plan plus the graph.+///+/// [`build`] is this plus `Op` emission; the MAML v2 emitter needs the graph+/// without the plan, after the same fusion fold and the same every-tensor+/// rule. Split out so both share the bodies verbatim. See [`Builder::record`].+/// Each pass names the other's tensors host (the multi-pass file idiom);+/// the union check lives in the v2 emitter, which holds both recordings.+pub fn record(weights: &dyn WeightSource, mode: Mode) -> Result<crate::nets::Recorded, String> { match mode {- Mode::Image => image(weights),- Mode::Text { len } => text(weights, len),+ Mode::Image => image_record(weights),+ Mode::Text { len } => text_record(weights, len), } } /// The vision tower over one 224x224 image. fn image(weights: &dyn WeightSource) -> Result<Plan, String> {+ Ok(image_record(weights)?.plan)+}++/// The recording behind [`image`].+fn image_record(weights: &dyn WeightSource) -> Result<crate::nets::Recorded, String> { let mut builder = Builder::new(weights); let b = &mut builder; name_host_tensors(b, PATCH_CONV..TOKENS);@@ -288,11 +304,16 @@ fn image(weights: &dyn WeightSource) -> Result<Plan, String> { if head.next != TOKENS { return Err(format!("the visual projection ends at {}, not {TOKENS}", head.next)); }- builder.finish(&[projected])+ builder.record(&[projected], &crate::weights::Offsets::empty()) } /// The text tower over `len` already-embedded positions. fn text(weights: &dyn WeightSource, len: u32) -> Result<Plan, String> {+ Ok(text_record(weights, len)?.plan)+}++/// The recording behind [`text`].+fn text_record(weights: &dyn WeightSource, len: u32) -> Result<crate::nets::Recorded, String> { if len == 0 { return Err("a text pass over no tokens".into()); }@@ -318,7 +339,7 @@ fn text(weights: &dyn WeightSource, len: u32) -> Result<Plan, String> { if head.next != TENSORS { return Err(format!("the text projection ends at {}, not {TENSORS}", head.next)); }- builder.finish(&[projected])+ builder.record(&[projected], &crate::weights::Offsets::empty()) } /// Name every tensor **outside** `read` as one this pass does not touch.