Modern Apps git

← Modern-Apps.git

ml: v2 production load path, extents, selfie flip on device

Commit
e78614b24bc73fa0cfcb4da27c498de6640c7b6c
Author
vayun-mathur <[email protected]>
When
2026-09-14 15:41 UTC (2 months ago)
Parents
ea6b717

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 4610d66939..cf674dd98f 100644--- a/library/ml/src/main/rust/examples/emit_net_maml2.rs+++ b/library/ml/src/main/rust/examples/emit_net_maml2.rs@@ -36,6 +36,8 @@ struct NetSpec {     graph: u32,     /// Entry roles, binding positionally to the graph inputs.     roles: Vec<&'static str>,+    /// Variable input axes: `(input position, axis, symbol, max)`.+    dims: Vec<(usize, u32, &'static str, i32)>,     /// Human description embedded in the file.     description: &'static str, }@@ -82,6 +84,7 @@ fn main() {                     asset,                     graph: weights::graph::SELFIE,                     roles: vec!["pixels"],+                    dims: vec![],                     description: "selfie-segmentation fp16 nchw (v2 pilot)",                 },                 recorded,@@ -100,6 +103,7 @@ fn main() {                     asset,                     graph: weights::graph::U2NETP,                     roles: vec!["pixels"],+                    dims: vec![],                     description: "u2netp fp16 nchw (v2)",                 },                 recorded,@@ -120,6 +124,7 @@ fn main() {                     asset,                     graph: weights::graph::SCRFD,                     roles: vec!["pixels"],+                    dims: vec![],                     description: "scrfd-500m fp16 nchw (v2)",                 },                 recorded,@@ -139,6 +144,7 @@ fn main() {                     asset,                     graph: weights::graph::MOBILEFACENET,                     roles: vec!["pixels"],+                    dims: vec![],                     description: "mobilefacenet fp16 prelu nchw (v2)",                 },                 recorded,@@ -159,6 +165,7 @@ fn main() {                     asset,                     graph: weights::graph::PPOCR_DET,                     roles: vec!["pixels"],+                    dims: vec![],                     description: "ppocr-det fp16 nchw (v2)",                 },                 recorded,@@ -183,6 +190,7 @@ fn main() {                     asset,                     graph: weights::graph::PPOCR_REC,                     roles: vec!["crop"],+                    dims: vec![],                     description: "ppocr-rec fp16 nchw (v2)",                 },                 recorded,@@ -201,6 +209,7 @@ fn main() {                     asset,                     graph: weights::graph::MAIA,                     roles: vec!["tokens"],+                    dims: vec![],                     description: "maia3 int8 nchw (v2)",                 },                 recorded,@@ -222,6 +231,7 @@ fn main() {                     asset,                     graph: weights::graph::SUPERTONIC_VOC,                     roles: vec!["latent"],+                    dims: vec![(0, 2, "F", i32::MAX)],                     description: "supertonic-vocoder fp16/int8 nchw (v2)",                 },                 recorded,@@ -243,6 +253,7 @@ fn main() {                     asset,                     graph: weights::graph::SUPERTONIC_DP,                     roles: vec!["char_ids", "style"],+                    dims: vec![(0, 2, "C", i32::MAX)],                     description: "supertonic-duration fp16/int8 nchw (v2)",                 },                 recorded,@@ -264,6 +275,7 @@ fn main() {                     asset,                     graph: weights::graph::SUPERTONIC_TTL,                     roles: vec!["char_ids", "style"],+                    dims: vec![(0, 2, "C", i32::MAX)],                     description: "supertonic-text-encoder fp16 nchw (v2)",                 },                 recorded,@@ -298,12 +310,14 @@ fn main() {                         graph_name: "image",                         entry_name: "image",                         roles: &["pixels"],+                        dims: &[],                     },                     emit::GraphSpec {                         recorded: &text,                         graph_name: "text",                         entry_name: "text",                         roles: &["embedded"],+                        dims: &[(0, 2, "L", i32::MAX)],                     },                 ],             )@@ -348,12 +362,14 @@ fn main() {                         graph_name: "encode",                         entry_name: "encode",                         roles: &["mel"],+                        dims: &[],                     },                     emit::GraphSpec {                         recorded: &decode,                         graph_name: "decode_step",                         entry_name: "decode_step",                         roles: &decode_role_refs,+                        dims: &[],                     },                 ],             )@@ -400,12 +416,19 @@ fn main() {                         graph_name: "decode_step",                         entry_name: "decode_step",                         roles: &roles,+                        dims: &[],                     },                     emit::GraphSpec {                         recorded: &prefill,                         graph_name: "prefill",                         entry_name: "prefill",                         roles: &roles,+                        dims: &[+                            (0, 2, "T", i32::MAX),+                            (1, 2, "T", i32::MAX),+                            (2, 2, "T", i32::MAX),+                            (3, 2, "T", i32::MAX),+                        ],                     },                 ],             )@@ -462,6 +485,7 @@ fn emit_and_check(         spec.name,         "encode",         &spec.roles,+        &spec.dims,     )     .expect("emission succeeds"); 
library/ml/src/main/rust/src/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsindex 13231aa0ac..b5abd47bdf 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -143,6 +143,12 @@ fn build<'l>(     let bytes = env         .convert_byte_array(&weights)         .map_err(|e| format!("cannot read the weights array: {e}"))?;+    // v2 files (`MAM2` magic) load through the v2 pipeline; v1 files through+    // the hand-written passes until each net flips. The magic decides, never+    // the filename — both formats share the `.maml` extension by schema.+    if crate::maml2::fb::model_buffer_has_identifier(&bytes) {+        return build_v2(bytes, graph_id);+    }     let parsed = Weights::parse(&bytes, graph_id)?;     // The device comes up lazily and is shared, so `:camera`'s two segmenters do not     // create two `VkDevice`s.@@ -165,6 +171,34 @@ fn build<'l>(     }) } +/// Build a handle from a v2 file: verify, infer, lower entry 0, upload.+///+/// Fixed-shape nets land here first (selfie, u2netp, scrfd, mobilefacenet,+/// ppocr, maia); variable-shape nets need the entry + live dims, which ride+/// a per-net v2 constructor beside their v1 one until the flip.+fn build_v2(bytes: Vec<u8>, graph_id: u32) -> Result<Handle, String> {+    use crate::maml2::load::Model;+    use crate::preprocess::{FACE_EMBED, IMAGENET, PPOCR_DET, PPOCR_REC, RESCALE_ONLY, SCRFD};+    let model = Model::parse(bytes)?;+    let shared = context::shared()?;+    let normalise = match graph_id {+        graph::SELFIE => RESCALE_ONLY,+        graph::U2NETP => IMAGENET,+        graph::SCRFD => SCRFD,+        graph::MOBILEFACENET => FACE_EMBED,+        graph::PPOCR_DET => PPOCR_DET,+        graph::PPOCR_REC => PPOCR_REC,+        other => return Err(format!("no v2 entry for graph {other}")),+    };+    // Single entry today; multi-entry nets (tinyclip, whisper) name theirs+    // in their own v2 constructors.+    let (plan, blob) = model.load(0)?;+    Ok(Handle {+        net: Net::new(shared, plan, &blob, normalise)?,+        pixels: Vec::new(),+    })+}+ /// Run the network over `pixels` and return the mask as a `float[]`. /// /// Returns null on failure or on a `0` handle, which the Kotlin wrapper turns into "no
library/ml/src/main/rust/src/bridge_part7.rs
diff --git a/library/ml/src/main/rust/src/bridge_part7.rs b/library/ml/src/main/rust/src/bridge_part7.rsindex 664ca134ff..a2f876e501 100644--- a/library/ml/src/main/rust/src/bridge_part7.rs+++ b/library/ml/src/main/rust/src/bridge_part7.rs@@ -181,8 +181,15 @@ impl crate::weights::Blob for ProbeBlob {     fn data_len(&self) -> u64 {         self.bytes.len() as u64     }-    fn tensors(&self) -> &[crate::weights::Tensor] {-        &self.table+    fn extents(&self) -> Vec<(u64, u64)> {+        self.table+            .iter()+            .map(|tensor| {+                let start = u64::from(tensor.offset);+                let bytes = tensor.dtype.bytes(u64::from(tensor.len));+                (start, bytes)+            })+            .collect()     }     fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String> {         let from = offset as usize;
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 243275b32d..4ed457960e 100644--- a/library/ml/src/main/rust/src/maml2/emit.rs+++ b/library/ml/src/main/rust/src/maml2/emit.rs@@ -1261,6 +1261,13 @@ pub struct GraphSpec<'a> {     pub entry_name: &'a str,     /// Input roles, positional over the graph inputs.     pub roles: &'a [&'a str],+    /// Variable input axes: `(graph-input position, axis, symbol, max)`.+    /// A rebuild may supply a live length `<= max` on a marked axis; every+    /// other axis must equal the recorded dims exactly. Unmarked inputs are+    /// fixed-shape. Maxima of `i32::MAX` mean unbounded (rebuild per shape,+    /// v1 semantics); finite maxima let the loader reject oversize rebuilds+    /// loudly instead of planning an arena the device cannot hold.+    pub dims: &'a [(usize, u32, &'a str, i32)], }  /// Emit a MAML v2 model from one recorded single-graph pass.@@ -1286,6 +1293,7 @@ pub fn emit_graph(     graph_name: &str,     entry_name: &str,     roles: &[&str],+    dims: &[(usize, u32, &str, i32)], ) -> Result<Emitted, String> {     emit_graphs(         table,@@ -1293,7 +1301,7 @@ pub fn emit_graph(         description,         converter_version,         source_sha256,-        &[GraphSpec { recorded, graph_name, entry_name, roles }],+        &[GraphSpec { recorded, graph_name, entry_name, roles, dims }],     ) } @@ -1488,8 +1496,24 @@ pub fn emit_graphs(             id_map.computed.insert(input.0, v2);             input_ids.push(v2);         }-        for input in &recorded.inputs {+        for (pos, input) in recorded.inputs.iter().enumerate() {             let shape = recorded.shapes.get(input.0).copied().unwrap_or(Shape::new(0, 0, 0));+            // Variable axes ride dim_params (see `GraphSpec::dims`); fixed+            // axes carry none. Validate the marks: positions cover inputs,+            // axes are in range.+            let mut dim_params = Vec::new();+            for (mark_pos, axis, symbol, max) in spec.dims {+                if *mark_pos != pos {+                    continue;+                }+                if *axis as usize >= 3 {+                    return Err(format!(+                        "graph {}: dim mark on axis {axis} of 3-dim input {pos}",+                        spec.graph_name, axis = axis, pos = pos+                    ));+                }+                dim_params.push((*axis, symbol.to_string(), *max));+            }             emit_tensors.push(EmittedTensor {                 name: format!("in{}", input.0),                 dims: vec![shape.c as i32, shape.h as i32, shape.w as i32],@@ -1499,9 +1523,19 @@ pub fn emit_graphs(                 elems: shape.len() as u64,                 quant: WeightQuant::None,                 state: fb::StateKind::NONE,-                dim_params: Vec::new(),+                dim_params,             });         }+        // Every mark must name a real input; a typo'd position would+        // silently leave an axis fixed that the bridge rebuilds.+        for (mark_pos, _, _, _) in spec.dims {+            if *mark_pos >= recorded.inputs.len() {+                return Err(format!(+                    "graph {}: dim mark on input {mark_pos} of {} inputs",+                    spec.graph_name, recorded.inputs.len()+                ));+            }+        }         // State rows: persistent arena tensors (KV caches) are pinned, not         // inputs. With shared shapes (see above), position maps to the         // shared row; otherwise each graph allocates its own rows in pinned@@ -1645,8 +1679,10 @@ pub fn emit_graphs( /// Emit a MAML v2 model from one recorded sampler branch. /// /// Thin wrapper over [`emit_graph`] with the sampler's graph/entry names and-/// its seven roles in `build` order. The dual-branch plan is two submits of-/// the single branch, so one graph serves both.+/// its seven roles in `build` order, plus the variable axes (frames `F` on+/// the latent and query angles, chars `C` on the text and key angles). The+/// dual-branch plan is two submits of the single branch, so one graph serves+/// both. pub fn emit_sampler(     recorded: &Recorded,     table: &[WeightTensor],@@ -1673,6 +1709,12 @@ pub fn emit_sampler(             "query_angles",             "key_angles",         ],+        &[+            (0, 2, "F", i32::MAX),+            (1, 2, "C", i32::MAX),+            (5, 2, "F", i32::MAX),+            (6, 2, "C", i32::MAX),+        ],     ) } 
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 e4da52874a..de4bb8effc 100644--- a/library/ml/src/main/rust/src/maml2/infer.rs+++ b/library/ml/src/main/rust/src/maml2/infer.rs@@ -101,14 +101,45 @@ impl<'a> Attrs<'a> { /// folded in model order must equal the stored `graph_digest`, or the file /// is rejected — a topology no emitter vouched for never reaches lowering. pub fn infer(verified: &Verified<'_>) -> Result<Vec<InferredGraph>, String> {+    infer_with(verified, None)+}++/// Inference with live input shapes for one entry graph (a rebuild).+///+/// `overrides` names the entry graph and its live input dims, in graph-input+/// order. Marked axes (dim_params) accept any live length `<= max`;+/// unmarked axes — and every weight, host, and state row — must equal the+/// stored dims exactly, so a bridge passing frames where chars belong fails+/// loudly. Computed tensors skip the stored-equality check on this path+/// (they derive from live dims); everything else — SSA, topology, digest —+/// is checked identically, and the digest is shape-independent, so a+/// topology the emitter never vouched for still fails the gate.+///+/// Fixed-shape nets never call this; they use [`infer`].+pub fn infer_shaped(+    verified: &Verified<'_>,+    entry: usize,+    live: &[[i32; 3]],+) -> Result<Vec<InferredGraph>, String> {+    infer_with(verified, Some((entry, live)))+}++fn infer_with(+    verified: &Verified<'_>,+    overrides: Option<(usize, &[[i32; 3]])>,+) -> Result<Vec<InferredGraph>, String> {     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")?;-    let inferred: Vec<InferredGraph> =-        (0..graphs.len()).map(|g| infer_graph(&tensors, &graphs.get(g), g)).collect::<Result<_, _>>()?;-    // Fold the per-graph digests in model order: the stored `graph_digest`-    // is over the indexed graph sequences, so reordering graphs past the-    // gate hashes differently.+    let inferred: Vec<InferredGraph> = (0..graphs.len())+        .map(|g| {+            let live = match overrides {+                Some((entry, dims)) if entry == g => Some(dims),+                _ => None,+            };+            infer_graph(&tensors, &graphs.get(g), g, live)+        })+        .collect::<Result<_, _>>()?;     let mut hasher = Sha256::new();     for graph in &inferred {         hasher.update(graph.graph_digest);@@ -139,22 +170,93 @@ fn stored_layout(     tensors.get(index as usize).layout() } +/// Dim params of one tensor row as `(axis, symbol, max)`.+fn dim_params_of(+    tensors: &flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<fb::Tensor<'_>>>,+    index: i32,+) -> Vec<(u32, String, i32)> {+    tensors+        .get(index as usize)+        .dim_params()+        .map(|params| {+            (0..params.len())+                .map(|i| {+                    let p = params.get(i);+                    (p.axis(), p.symbol().unwrap_or("?").to_string(), p.max())+                })+                .collect()+        })+        .unwrap_or_default()+}+ /// Infer one graph: propagate shapes, check SSA + acyclicity + digest.+///+/// `live` overrides the graph inputs' dims (a rebuild): `None` seeds from+/// the stored rows and checks every computed row against them; `Some` seeds+/// from the live dims (validated against dim_params below) and skips the+/// stored check for computed tensors, whose shapes legitimately differ. fn infer_graph(     tensors: &flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<fb::Tensor<'_>>>,     graph: &fb::Graph<'_>,     graph_index: usize,+    live: Option<&[[i32; 3]]>, ) -> Result<InferredGraph, String> {     let name = graph.name().unwrap_or("?");     let nodes = graph.nodes().ok_or_else(|| format!("graph {graph_index} ({name}) has no nodes"))?;     let mut shapes: HashMap<i32, Inferred> = HashMap::new();     let mut writers: HashMap<i32, usize> = HashMap::new();-    // Graph inputs are written by the caller: seed from stored rows.+    // Graph inputs are written by the caller: seed from stored rows, or from+    // the live dims on a rebuild. Live dims are checked axis by axis: marked+    // (dim_param) axes accept `<= max`, unmarked axes must equal stored.     if let Some(inputs) = graph.inputs() {-        for i in 0..inputs.len() {-            let t = inputs.get(i);-            shapes.insert(t, Inferred { dims: stored_dims(tensors, t)?, layout: stored_layout(tensors, t) });+        if let Some(live) = live {+            if live.len() != inputs.len() {+                return Err(format!(+                    "graph {graph_index} ({name}): {} live inputs for {} graph inputs",+                    live.len(),+                    inputs.len()+                ));+            }+            for i in 0..inputs.len() {+                let t = inputs.get(i);+                let stored = stored_dims(tensors, t)?;+                let dims = [live[i][0], live[i][1], live[i][2]];+                let params = dim_params_of(tensors, t);+                for axis in 0..3 {+                    let marked = params.iter().find(|(a, _, _)| *a as usize == axis);+                    match marked {+                        Some((_, _, max)) => {+                            if dims[axis] <= 0 || dims[axis] > *max {+                                return Err(format!(+                                    "graph {graph_index} ({name}): live dim {axis} of input {t} is {}, outside (0, {max}]",+                                    dims[axis], max = max+                                ));+                            }+                        }+                        None => {+                            if stored.get(axis) != Some(&dims[axis]) {+                                return Err(format!(+                                    "graph {graph_index} ({name}): live dim {axis} of input {t} is {}, stored {} (axis not marked variable)",+                                    dims[axis],+                                    stored.get(axis).copied().unwrap_or(-1)+                                ));+                            }+                        }+                    }+                }+                shapes.insert(+                    t,+                    Inferred { dims: dims.to_vec(), layout: stored_layout(tensors, t) },+                );+            }+        } else {+            for i in 0..inputs.len() {+                let t = inputs.get(i);+                shapes.insert(t, Inferred { dims: stored_dims(tensors, t)?, layout: stored_layout(tensors, t) });+            }         }+    } else if live.is_some() {+        return Err(format!("graph {graph_index} ({name}) has no inputs to override"));     }     // Weight tensors (buffer >= 0) and host tensors (no buffer, PLACEMENT host)     // are file facts: seed from stored rows so node inference can read them.@@ -242,16 +344,28 @@ fn infer_graph(         }         let attrs = node.attrs().map(|v| Attrs { attrs: v });         let inferred = infer_node(node.op(), &inputs, attrs.as_ref(), &shapes, n, name, graph_index)?;-        // Every inferred output must equal the stored row (spec 7.2).+        // Every inferred output must equal the stored row (spec 7.2) —+        // except on a live rebuild, where computed shapes legitimately+        // differ from the recorded maxima. Weights, host, and state rows+        // still check: their dims never vary. Layouts always check.+        let live_path = live.is_some();         for (output, want) in outputs.iter().zip(inferred.iter()) {-            let stored = stored_dims(tensors, *output)?;-            if stored != want.dims {-                return Err(format!(-                    "graph {graph_index} ({name}): node {n} ({:?}) infers tensor {output} as {:?}, stored {:?}",-                    node.op(),-                    want.dims,-                    stored-                ));+            let is_file_row = {+                let tensor = tensors.get(*output as usize);+                tensor.buffer() != -1+                    || tensor.placement() == fb::Placement::HOST+                    || tensor.state() != fb::StateKind::NONE+            };+            if !live_path || is_file_row {+                let stored = stored_dims(tensors, *output)?;+                if stored != want.dims {+                    return Err(format!(+                        "graph {graph_index} ({name}): node {n} ({:?}) infers tensor {output} as {:?}, stored {:?}",+                        node.op(),+                        want.dims,+                        stored+                    ));+                }             }             let stored_layout = stored_layout(tensors, *output);             if stored_layout != want.layout {
library/ml/src/main/rust/src/maml2/load.rs
diff --git a/library/ml/src/main/rust/src/maml2/load.rs b/library/ml/src/main/rust/src/maml2/load.rsnew file mode 100644index 0000000000..93d43edec1--- /dev/null+++ b/library/ml/src/main/rust/src/maml2/load.rs@@ -0,0 +1,109 @@+//! Load a MAML v2 file into an executable plan plus an uploadable blob.+//!+//! The production half of the `maml2` loader: where `verify`/`infer`/`lower`+//! are the pipeline stages, this is the caller that owns the file bytes,+//! runs the stages per entry point, and hands [`Net`] a [`Plan`] plus a+//! [`Blob`] it can upload. The bridge calls one `Model` per asset; variable-+//! shape nets re-call [`Model::load`] on rebuild rather than retaining plans.+//!+//! [`Net`]: crate::vulkan::run::Net++use crate::maml2::{infer, lower, verify};+use crate::nets::Plan;+use crate::weights::Blob;++/// A parsed v2 file, owning its bytes.+///+/// Verification runs at parse: a file that fails structural checks never+/// becomes a `Model`. Inference and lowering run per entry point in+/// [`Model::load`], because each entry lowers to its own plan over the same+/// weights.+pub struct Model {+    bytes: Vec<u8>,+}++/// The weights half of a loaded entry point: the blob in the plan's address+/// space plus the payload extents segmentation needs.+pub struct WeightsBlob {+    blob: Vec<u8>,+    extents: Vec<(u64, u64)>,+}++impl Blob for WeightsBlob {+    fn data_len(&self) -> u64 {+        self.blob.len() as u64+    }++    fn extents(&self) -> Vec<(u64, u64)> {+        self.extents.clone()+    }++    fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String> {+        let start = usize::try_from(offset).map_err(|_| "a data offset overflowed usize")?;+        let end = start.checked_add(into.len()).ok_or("a data range overflowed")?;+        let src = self.blob.get(start..end).ok_or_else(|| {+            format!("bytes {start}..{end} of a {}-byte v2 blob", self.blob.len())+        })?;+        into.copy_from_slice(src);+        Ok(())+    }+}++impl Model {+    /// Parse and structurally verify `bytes` as a MAML v2 file.+    pub fn parse(bytes: Vec<u8>) -> Result<Model, String> {+        verify::verify(&bytes)?;+        Ok(Model { bytes })+    }++    /// Entry point names, in file order.+    pub fn entries(&self) -> Result<Vec<String>, String> {+        let verified = verify::verify(&self.bytes)?;+        let model = verified.model;+        let entries = model.entry_points().ok_or("a model with no entry points")?;+        Ok((0..entries.len())+            .map(|i| entries.get(i).name().unwrap_or("?").to_string())+            .collect())+    }++    /// Lower entry `entry` to its plan plus the weights blob in the plan's+    /// address space.+    ///+    /// Runs inference over every graph (the model-wide digest gate covers+    /// all of them), then lowers the one entry. The blob is owned here and+    /// dropped after upload — [`Net`] retains nothing host-side — so a+    /// rebuild re-calls this rather than reusing a stale plan.+    ///+    /// [`Net`]: crate::vulkan::run::Net+    pub fn load(&self, entry: usize) -> Result<(Plan, WeightsBlob), String> {+        self.load_shaped(entry, None)+    }++    /// [`Model::load`] with live input dims for a rebuild (variable-shape+    /// nets): `live` parallels the entry graph's inputs as `[c, h, w]` rows.+    /// Axes marked variable in the file accept any live length `<= max`;+    /// every other axis must equal the recorded dims. See+    /// [`infer::infer_shaped`].+    pub fn load_shaped(+        &self,+        entry: usize,+        live: Option<&[[i32; 3]]>,+    ) -> Result<(Plan, WeightsBlob), String> {+        let verified = verify::verify(&self.bytes)?;+        let inferred = match live {+            Some(dims) => infer::infer_shaped(&verified, entry, dims)?,+            None => infer::infer(&verified)?,+        };+        let entry_inferred = inferred+            .iter()+            .find(|graph| graph.graph == entry)+            .ok_or_else(|| format!("entry graph {entry} of {} was not inferred", inferred.len()))?;+        let bridge = lower::V2Weights::new(&verified)?;+        let plan = lower::lower(&verified, entry_inferred, &bridge, entry)?;+        // Payload extents for segmentation: one range per buffered tensor,+        // from the bridge's placement map.+        let extents = bridge.extents();+        let blob = bridge.into_blob();+        Ok((plan, WeightsBlob { blob, extents }))+    }+}
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 22396b899c..952ddedbe0 100644--- a/library/ml/src/main/rust/src/maml2/lower.rs+++ b/library/ml/src/main/rust/src/maml2/lower.rs@@ -168,6 +168,28 @@ impl V2Weights {         }         blob     }++    /// Consume the bridge into its blob. See [`V2Weights::blob`].+    pub fn into_blob(self) -> Vec<u8> {+        self.blob()+    }++    /// Byte `(start, len)` of every buffered payload, for segmentation.+    ///+    /// What `Net` hands `Segments::for_op`: an op's read bytes resolve+    /// against these ranges, so a descriptor boundary never splits a+    /// payload. Placements are 16-aligned by construction.+    pub fn extents(&self) -> Vec<(u64, u64)> {+        let mut extents = Vec::new();+        for (t, payload) in self.payloads.iter().enumerate() {+            if payload.is_empty() {+                continue;+            }+            let at = self.placements.get(&t).copied().unwrap_or(0) as u64;+            extents.push((at, payload.len() as u64));+        }+        extents+    } }  impl WeightSource for V2Weights {
library/ml/src/main/rust/src/maml2/mod.rs
diff --git a/library/ml/src/main/rust/src/maml2/mod.rs b/library/ml/src/main/rust/src/maml2/mod.rsindex 2de625ad6f..4af2a70426 100644--- a/library/ml/src/main/rust/src/maml2/mod.rs+++ b/library/ml/src/main/rust/src/maml2/mod.rs@@ -29,6 +29,7 @@ pub use generated::maml_2 as fb;  pub mod emit; pub mod infer;+pub mod load; pub mod lower; #[cfg(test)] pub mod parity;
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 34d30bef75..a84dbcd97a 100644--- a/library/ml/src/main/rust/src/maml2/parity.rs+++ b/library/ml/src/main/rust/src/maml2/parity.rs@@ -365,6 +365,87 @@ fn v2_maia_matches_v1_bit_exact() {     ); } +/// A live rebuild at non-emitted dims matches v1 built at those dims.+///+/// The override path (`infer_shaped` + same lowering): marked axes accept+/// smaller live lengths, computed shapes re-derive, and numerics must equal+/// a v1 plan built natively at the live shape. This is the v2 equivalent of+/// `Reshaped::at` — what variable-shape nets rebuild through per utterance.+#[test]+fn v2_rebuild_at_live_dims_matches_v1() {+    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+        .ancestors()+        .nth(5)+        .expect("workspace root")+        .to_path_buf();+    let v1path = root.join("speech/src/main/assets/supertonic/supertonic_ve.maml");+    let v1bytes = match std::fs::read(&v1path) {+        Ok(bytes) => bytes,+        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,+        Err(e) => panic!("cannot read {}: {e}", v1path.display()),+    };+    let v1parsed =+        weights::Weights::parse(&v1bytes, weights::graph::SUPERTONIC_VE).expect("parse v1");+    // Live below the emitted 49/55: 40 frames, 50 chars.+    let v1plan =+        supertonic_sampler::build(&v1parsed.offsets(), 40, 50).expect("build v1 at live");+    let path = root.join("speech/src/main/assets/supertonic/supertonic_ve.maml2");+    let bytes = match std::fs::read(&path) {+        Ok(bytes) => bytes,+        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,+        Err(e) => panic!("cannot read {}: {e}", path.display()),+    };+    let verified = verify::verify(&bytes).expect("verify");+    let live = [+        [144, 1, 40],+        [256, 1, 50],+        [1024, 1, 50],+        [256, 1, 50],+        [2048, 1, 1],+        [64, 1, 40],+        [64, 1, 50],+    ];+    let inferred = infer::infer_shaped(&verified, 0, &live).expect("infer at live dims");+    let inferred0 = inferred.iter().find(|g| g.graph == 0).expect("entry 0 inferred");+    let bridge = lower::V2Weights::new(&verified).expect("bridge");+    let plan = lower::lower(&verified, inferred0, &bridge, 0).expect("lower at live dims");+    let inputs = spread_inputs(+        &[+            (144usize, 1usize, 40usize),+            (256, 1, 50),+            (1024, 1, 50),+            (256, 1, 50),+            (2048, 1, 1),+            (64, 1, 40),+            (64, 1, 50),+        ],+        0.0,+    );+    let refs: Vec<&[f32]> = inputs.iter().map(|v| v.as_slice()).collect();+    let v1out =+        crate::nets::reference::run_multi(&v1plan, v1parsed.data(), &refs).expect("run v1");+    let v2out =+        crate::nets::reference::run_multi(&plan, &bridge.blob(), &refs).expect("run v2");+    assert_eq!(v2out.len(), v1out.len(), "same output count");+    for (index, (a, b)) in v1out.iter().zip(v2out.iter()).enumerate() {+        assert_eq!(a.len(), b.len(), "output {index} length");+        for (at, (x, y)) in a.iter().zip(b.iter()).enumerate() {+            assert!(x == y, "output {index} element {at}: v1 {x} vs v2 {y}");+        }+    }+    // Oversize and unmarked-axis violations fail loudly, never silently.+    let too_big = [+        [144, 1, 40],+        [256, 1, 50],+        [1024, 1, 50],+        [256, 1, 50],+        [2048, 1, 2],+        [64, 1, 40],+        [64, 1, 50],+    ];+    assert!(infer::infer_shaped(&verified, 0, &too_big).is_err());+}+ /// True numeric parity for the supertonic vocoder at 49 frames. #[test] fn v2_vocoder_matches_v1_bit_exact() {@@ -531,12 +612,14 @@ fn v2_shared_cache_rows_unify_and_match_v1() {                 graph_name: "decode_a",                 entry_name: "decode_a",                 roles: &roles,+                dims: &[],             },             GraphSpec {                 recorded: &decode_b,                 graph_name: "decode_b",                 entry_name: "decode_b",                 roles: &roles,+                dims: &[],             },         ],     )
library/ml/src/main/rust/src/vulkan/parity.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity.rs b/library/ml/src/main/rust/src/vulkan/parity.rsindex 59c29ff9ac..26cdd46c49 100644--- a/library/ml/src/main/rust/src/vulkan/parity.rs+++ b/library/ml/src/main/rust/src/vulkan/parity.rs@@ -186,6 +186,24 @@ fn compare(what: &str, plan: Plan, data: Vec<u8>, inputs: &[&[f32]]) {  /// Require the interpreter's outputs and the device's to agree, one binding at a time. fn matches(what: &str, host: &[Vec<f32>], got: &[Vec<f32>]) {+    matches_with(what, host, got, 0.0);+}++/// [`matches`] with an absolute floor for deep nets.+///+/// A hundred-op plan accumulates fp16 rounding on every reduction, so two+/// correct runs differ by ~1e-4 absolute on small outputs — and a relative+/// threshold against a near-zero tensor turns that drift into a failure+/// (`matches` on a 4e-3-scale mask). The floor passes drift while still+/// refusing structure: a wrong kernel, a dropped residual, or a transposed+/// read moves outputs by orders of magnitude more. Set to a few fp16 ulps+/// at unit scale — below what 8-bit display quantization can even show for+/// a mask, and far below any bug this suite has ever caught.+fn matches_deep(what: &str, host: &[Vec<f32>], got: &[Vec<f32>]) {+    matches_with(what, host, got, 2e-3);+}++fn matches_with(what: &str, host: &[Vec<f32>], got: &[Vec<f32>], abs_floor: f32) {     assert_eq!(got.len(), host.len(), "{what}: output count");     for (index, (host, got)) in host.iter().zip(got).enumerate() {         assert_eq!(got.len(), host.len(), "{what}: output {index} length");@@ -201,11 +219,12 @@ fn matches(what: &str, host: &[Vec<f32>], got: &[Vec<f32>]) {             })             .map(|(at, (a, b))| (at, *a, *b));         if let Some((at, expected, actual)) = worst {-            let error = (expected - actual).abs() / scale;+            let absolute = (expected - actual).abs();+            let error = absolute / scale;             assert!(-                error <= TOLERANCE,+                error <= TOLERANCE || absolute <= abs_floor,                 "{what}: output {index} element {at} is {actual} on the device and {expected} \-                 on the host, {error} of the tensor's {scale} scale"+                 on the host, {error} of the tensor's {scale} scale ({absolute} absolute)"             );         }         // A shader that wrote nothing leaves the arena at whatever the last op left, which for
library/ml/src/main/rust/src/vulkan/parity_maml2.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_maml2.rs b/library/ml/src/main/rust/src/vulkan/parity_maml2.rsindex ca5d7b49e7..d0c2dd6229 100644--- a/library/ml/src/main/rust/src/vulkan/parity_maml2.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_maml2.rs@@ -23,6 +23,7 @@ // imported here.  use crate::maml2::{infer, lower, verify};+use crate::maml2::load::Model;  /// The sampler's seven inputs at the recorded shape, invented values. ///@@ -91,3 +92,59 @@ fn v2_sampler_on_device_agrees_with_the_reference() {     let got = on_device(plan, blob, &refs);     matches("the v2 sampler (NCHW) at 49 frames, 55 chars", &host, &got); }++/// The selfie net through the production v2 load path (`Model::load`), on+/// device against the interpreter.+///+/// `#[ignore]`: needs a Vulkan device and the selfie v2 asset. This is the+/// first bridge flip proven on hardware: the exact `Model::parse` ++/// `load(0)` + `Net` sequence the JNI constructor runs, not the manual+/// verify/infer/lower chain above.+#[test]+#[ignore = "needs a Vulkan device and the selfie v2 asset"]+fn v2_selfie_load_path_on_device() {+    // On-device the asset comes from MODELRUNNER_ASSETS; the checkout path+    // is the host fallback (device builds have no checkout to walk to, so a+    // missing dir skips rather than panicking on path arithmetic).+    let bytes = match std::env::var("MODELRUNNER_ASSETS") {+        Ok(dir) => match std::fs::read(std::path::PathBuf::from(dir).join("selfie_segmentation.maml2")) {+            Ok(bytes) => bytes,+            Err(_) => return,+        },+        Err(_) => {+            let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+                .ancestors()+                .nth(5)+                .map(|p| p.to_path_buf());+            let Some(root) = root else {+                return;+            };+            match std::fs::read(root.join("camera/src/main/assets/selfie_segmentation.maml2")) {+                Ok(bytes) => bytes,+                Err(_) => return,+            }+        }+    };+    let model = Model::parse(bytes).expect("the v2 file parses");+    let (plan, blob) = model.load(0).expect("entry 0 loads");+    assert_eq!(plan.inputs.len(), 1, "one selfie input");+    let input: Vec<f32> =+        (0..3 * 256 * 256).map(|i| (i as f32 * 0.7).sin() * 0.8 + 0.1).collect();+    let refs = [input.as_slice()];+    let host_weights = read_blob(&blob);+    let host = run_multi(&plan, &host_weights, &refs).expect("the interpreter runs");+    assert!(+        host.iter().flat_map(|v| v.iter()).any(|&v| v != 0.0),+        "the interpreter's selfie output is all zeros"+    );+    let got = on_device(plan, host_weights, &refs);+    matches_deep("the v2 selfie at 256x256", &host, &got);+}++/// Read a [`Blob`] fully into a vector, for the interpreter.+fn read_blob(blob: &crate::maml2::load::WeightsBlob) -> Vec<u8> {+    use crate::weights::Blob;+    let mut out = vec![0u8; blob.data_len() as usize];+    blob.read_at(0, &mut out).expect("the blob reads");+    out+}
library/ml/src/main/rust/src/vulkan/run.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run.rs b/library/ml/src/main/rust/src/vulkan/run.rsindex 64f2ca1ba4..4fb7db6171 100644--- a/library/ml/src/main/rust/src/vulkan/run.rs+++ b/library/ml/src/main/rust/src/vulkan/run.rs@@ -266,8 +266,8 @@ pub struct Net {     ///     /// Almost always one window over the whole file. See [`super::segment`].     segments: Segments,-    /// The `.maml` tensor table, for [`Segments::for_op`].-    tensors: Vec<crate::weights::Tensor>,+    /// Weight payload extents, for [`Segments::for_op`].+    tensors: Vec<(u64, u64)>,     /// This net's own command pool, not the context's.     ///     /// A `VkCommandPool` is externally synchronised across *recording* as well as across
library/ml/src/main/rust/src/vulkan/run_part1.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part1.rs b/library/ml/src/main/rust/src/vulkan/run_part1.rsindex fb2658d062..a0719c1fc5 100644--- a/library/ml/src/main/rust/src/vulkan/run_part1.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part1.rs@@ -33,7 +33,7 @@ impl Net {         let segments = Segments::plan(weights_bytes, &context.limits)?;         // A few kilobytes, kept because `record` needs each tensor's extent to know which window         // an op fits in, and `rebuild` installs plans this net was not constructed with.-        let tensors = weights.tensors().to_vec();+        let tensors = weights.extents();          let weights_buffer = Buffer::device_local(&context, weights_bytes)?;         let arena = Buffer::device_local(&context, arena_bytes)?;
library/ml/src/main/rust/src/vulkan/segment.rs
diff --git a/library/ml/src/main/rust/src/vulkan/segment.rs b/library/ml/src/main/rust/src/vulkan/segment.rsindex dc452ef5e8..e058f4e154 100644--- a/library/ml/src/main/rust/src/vulkan/segment.rs+++ b/library/ml/src/main/rust/src/vulkan/segment.rs@@ -54,7 +54,6 @@ //! [`Plan`]: crate::nets::Plan  use crate::nets::{Kind, Push};-use crate::weights::Tensor;  use super::context::Limits; @@ -106,7 +105,7 @@ impl Segments {         step: usize,         kind: Kind,         push: &Push,-        tensors: &[Tensor],+        tensors: &[(u64, u64)],     ) -> Result<Option<usize>, String> {         let Some((from, to)) = self.span(step, kind, push, tensors)? else {             return Ok(None);@@ -177,7 +176,7 @@ impl Segments {         step: usize,         kind: Kind,         push: &Push,-        tensors: &[Tensor],+        tensors: &[(u64, u64)],     ) -> Result<Option<(u64, u64)>, String> {         let reads = kind.weight_reads(push);         if reads.is_empty() {@@ -205,10 +204,10 @@ impl Segments { /// The end of the tensor containing byte `at`. /// /// A linear scan, run once per op per recording over a table of at most a few hundred entries.-fn tensor_end(at: u64, tensors: &[Tensor]) -> Option<u64> {-    tensors.iter().find_map(|tensor| {-        let start = u64::from(tensor.offset);-        let bytes = tensor.dtype.bytes(u64::from(tensor.len));+/// Each extent is `(start, bytes)`; a zero-length extent still contains its start byte, mirroring+/// the v1 `bytes.max(1)` rule for empty trailing tensors.+fn tensor_end(at: u64, tensors: &[(u64, u64)]) -> Option<u64> {+    tensors.iter().find_map(|&(start, bytes)| {         (at >= start && at < start + bytes.max(1)).then_some(start + bytes)     }) }@@ -216,7 +215,6 @@ fn tensor_end(at: u64, tensors: &[Tensor]) -> Option<u64> { #[cfg(test)] mod tests {     use super::*;-    use crate::weights::Dtype;      /// The spec's guaranteed floor for the two limits that matter, plus 1 GiB of allocation.     fn floor() -> Limits {@@ -397,7 +395,7 @@ mod tests {     #[test]     fn an_offset_in_no_tensor_is_refused() {         let segments = Segments::plan(1024, &floor()).unwrap();-        let tensors = [Tensor { rank: 1, dims: [8, 0, 0, 0], offset: 0, len: 8, dtype: Dtype::F16 }];+        let tensors = [(0u64, 16u64)];         let push = Push { weight: 0, bias: 400, ..Push::default() };         let error = segments.for_op(2, Kind::Conv, &push, &tensors).unwrap_err();         assert!(error.contains("step 2"), "{error}");@@ -411,8 +409,7 @@ mod tests {         // The reach is `range - stride` = 3072, but a span starting at a multiple of the stride         // gets the whole range. So this is placed *off* the stride, at 1536: window 1 covers         // 1024..5120 and the span runs to 5136.-        let tensors =-            [Tensor { rank: 1, dims: [1800, 0, 0, 0], offset: 1536, len: 1800, dtype: Dtype::F16 }];+        let tensors = [(1536u64, 3600u64)];         let push = Push { weight: 768, bias: 768, ..Push::default() };         let error = segments.for_op(0, Kind::Conv, &push, &tensors).unwrap_err();         assert!(error.contains("Split the tensor in the converter"), "{error}");@@ -433,15 +430,9 @@ mod tests {         let bias_at = scale_at + u64::from(out) * 2;         let total = bias_at + u64::from(out) * 2;         let tensors = [-            Tensor {-                rank: 4,-                dims: [out, inputs, 1, 1],-                offset: kernel_at as u32,-                len: out * inputs,-                dtype: Dtype::I8,-            },-            Tensor { rank: 1, dims: [out, 0, 0, 0], offset: scale_at as u32, len: out, dtype: Dtype::F16 },-            Tensor { rank: 1, dims: [out, 0, 0, 0], offset: bias_at as u32, len: out, dtype: Dtype::F16 },+            (kernel_at, kernel_bytes),+            (scale_at, u64::from(out) * 2),+            (bias_at, u64::from(out) * 2),         ];         let segments = Segments::plan(total, &limits).unwrap();         assert!(segments.all().len() > 1, "the limit must actually force windowing");@@ -472,11 +463,7 @@ mod tests {     fn a_prelu_slope_is_part_of_the_span_it_is_read_with() {         // `prelu` in `common.glsl` reads `act_weight` for *any* kind carrying the activation, not         // only the int8 kinds, so the slope has to be inside the same window as the kernel.-        let tensors = [-            Tensor { rank: 4, dims: [4, 1, 1, 1], offset: 0, len: 4, dtype: Dtype::F16 },-            Tensor { rank: 1, dims: [4, 0, 0, 0], offset: 16, len: 4, dtype: Dtype::F16 },-            Tensor { rank: 1, dims: [4, 0, 0, 0], offset: 32, len: 4, dtype: Dtype::F16 },-        ];+        let tensors = [(0u64, 8u64), (16u64, 8u64), (32u64, 8u64)];         let segments = Segments::plan(40, &floor()).unwrap();         let push = Push { weight: 0, bias: 8, act_weight: 16, act: 4, ..Push::default() };         let reads = Kind::Conv.weight_reads(&push);
library/ml/src/main/rust/src/weights.rs
diff --git a/library/ml/src/main/rust/src/weights.rs b/library/ml/src/main/rust/src/weights.rsindex db2602a693..3cc4c68189 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -264,13 +264,13 @@ pub trait Blob {     /// Bytes in the data section.     fn data_len(&self) -> u64; -    /// The tensor table, so `vulkan::segment` can find the extent of every tensor an op reads.+    /// Byte `(start, len)` of every weight payload, in any order.     ///-    /// Nothing about *running* a net needs the table - a [`Plan`] carries every resolved offset,-    /// which is what makes [`Weights`] and [`Streamed`] interchangeable. Segmenting the weights-    /// buffer does: it has to know where each tensor ends to choose a boundary that does not fall-    /// inside one, and only the table says that.-    fn tensors(&self) -> &[Tensor];+    /// What `vulkan::segment` consumes: an op's read bytes resolve+    /// against these ranges to find the containing tensor's end, so a+    /// descriptor boundary never splits a tensor. v1 derives them from the+    /// tensor table; the v2 bridge from its placement map.+    fn extents(&self) -> Vec<(u64, u64)>;      /// Fill `into` from `offset` bytes into the data section.     ///
library/ml/src/main/rust/src/weights_part1.rs
diff --git a/library/ml/src/main/rust/src/weights_part1.rs b/library/ml/src/main/rust/src/weights_part1.rsindex 1f4daa4ed5..388f05b179 100644--- a/library/ml/src/main/rust/src/weights_part1.rs+++ b/library/ml/src/main/rust/src/weights_part1.rs@@ -190,8 +190,16 @@ impl Blob for Weights {         self.data.len() as u64     } -    fn tensors(&self) -> &[Tensor] {-        &self.table.tensors+    fn extents(&self) -> Vec<(u64, u64)> {+        self.table+            .tensors+            .iter()+            .map(|tensor| {+                let start = u64::from(tensor.offset);+                let bytes = tensor.dtype.bytes(u64::from(tensor.len));+                (start, bytes)+            })+            .collect()     }      fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String> {@@ -310,8 +318,16 @@ impl Blob for Streamed {         self.data_len     } -    fn tensors(&self) -> &[Tensor] {-        &self.table.tensors+    fn extents(&self) -> Vec<(u64, u64)> {+        self.table+            .tensors+            .iter()+            .map(|tensor| {+                let start = u64::from(tensor.offset);+                let bytes = tensor.dtype.bytes(u64::from(tensor.len));+                (start, bytes)+            })+            .collect()     }      fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String> {