ml: MAML v2 format, loader, schedule-driven barriers, blocked kernel
- Commit
ebb4cf849fddf173ba86b7c5eab4b82362e856c1- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-14 05:33 UTC (2 months ago)
- Parents
cabdc46
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 97cded9a07..8f8b2f7273 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2158,7 +2158,9 @@ name = "modelrunner" version = "0.1.0" dependencies = [ "ash",+ "flatbuffers", "jni",+ "sha2 0.11.0", ] [[package]]
build-logic/src/main/kotlin/RustNative.kt
diff --git a/build-logic/src/main/kotlin/RustNative.kt b/build-logic/src/main/kotlin/RustNative.ktindex 389b2df094..b71d65ec20 100644--- a/build-logic/src/main/kotlin/RustNative.kt+++ b/build-logic/src/main/kotlin/RustNative.kt@@ -148,6 +148,11 @@ fun Project.rustNativeLib( // Optional because not every Rust module here has either. file("src/main/rust/build.rs").takeIf { it.isFile }?.let { inputs.file(it) } file("src/main/rust/shaders").takeIf { it.isDirectory }?.let { inputs.dir(it) }+ // `:library:ml`'s build.rs also compiles `schema/maml2.fbs` to Rust via+ // flatc and `include!`s the result, so a schema edit changes the .so too.+ // Same staleness hazard as shaders above: without this the task stays up+ // to date and the old bindings ship.+ file("src/main/rust/schema").takeIf { it.isDirectory }?.let { inputs.dir(it) } // Root workspace unified (Cargo.toml + Cargo.lock + rust-toolchain.toml) inputs.file(rootProject.file("Cargo.toml")) inputs.file(rootProject.file("Cargo.lock"))
library/ml/MAML2_SPEC.md
diff --git a/library/ml/MAML2_SPEC.md b/library/ml/MAML2_SPEC.mdnew file mode 100644index 0000000000..178303ffa3--- /dev/null+++ b/library/ml/MAML2_SPEC.md@@ -0,0 +1,437 @@+# MAML v2 — format and loader contract++Status: **spec, no code**. Clean-slate redesign. v1 (header + ordered+tensors, topology hardcoded in `nets/`) is dropped outright: no reader+compat, no version negotiation, no migration path. A v2 reader rejects+anything that is not v2; there is no v1 reader anymore.++## 0. Why v1 had to go++v1 stored weights only: `(name, dtype, shape, offset, length)` per tensor,+no operators, no topology, no shapes usable at load. Every consequence was+measured on-device (Pixel 9 Pro XL, Mali-G715) before this spec was written:++1. **No fusion, structurally.** Topology lived in twelve hand-written Rust+ forward passes emitting a flat `Vec<Op>`. By the time an optimisation+ could recognise a producer/consumer pair, the edges were gone.+ Epilogue fusion alone is ~26% of Supertonic's elements and 18.8% of+ Gemma 4 prefill's (measured from the plan builder).+2. **Shapes were runtime push constants, not load-time literals.** Every+ shader compiled once, generically; the driver could not unroll, vectorise,+ or strength-reduce. Doubling arithmetic intensity of the hottest kernel+ moved wall time 0.6% (measured).+3. **NCHW put every reduction on the strided axis.** A 1x1 convolution —+ all of a transformer, 92% of the sampler by parameter count — reduces over+ channels `positions * 2` bytes apart. Never one vector load.+4. **One barrier per op, always.** The recorder emitted+ `bind -> push -> dispatch -> BARRIER` per node because the plan claimed+ "each depends on the results of the ones before it". Most pairs do not.+5. **One static graph could not express an LLM.** Prefill (compute-bound,+ matrix-matrix) and decode (bandwidth-bound, matrix-vector, growing+ KV-cache) were forced through one plan shape with per-token re-record.++v2 fixes all five in the format, not in per-net code: the file carries the+graph, every shape, and the state descriptors, and the loader lowers that to+an optimised plan once.++## 1. What v2 steals, from where++| # | Technique | Source | v2 mechanism |+|---|-----------|--------|--------------|+| 1 | Graph + weights in one versioned container | ONNX `ModelProto`/`GraphProto` | §2, §5 |+| 2 | `constant` vs `placeholder` split; simplification before backend | ONNX `initializers` vs `inputs`, `onnxsim` | §5.1, §10 |+| 3 | mmap/zero-copy; read-only constants vs mutable scratch; offsets not pointers | LiteRT/ExecuTorch `.pte` (`constant_data` + `execution_plan` + delegates) | §2, §4 |+| 4 | Per-tensor shape + dtype + lifetime; memory planned ahead, I/O unplanned for zero-copy import | ExecuTorch `allocation_info`, `EValue` | §4, §7 |+| 5 | Quant params as data (per-channel scales, blockwise details), not opcode variants; opaque delegate blobs | LiteRT `QuantizationParameters` / `BlockwiseQuantization`, `BackendDelegateInlineData` | §3.3 |+| 6 | Backend specialisation at init: fusion, layout transform, per-shape kernels, binary cache | LiteRT GPU delegate | §7, §8 |+| 7 | Prefill vs decode as **two entry points**; KV-cache as runtime state with a layout descriptor, never file bytes | LiteRT-LM | §6 |+| 8 | Version + pin ruthlessly (`runtime_min_version`, converter version, backend feature bits) | LiteRT-LM import practice | §9 |+| 9 | Verbatim weight upload (file offset = device offset, one `VkBuffer`) | v1's one real advantage, measured 86 ms for 105 MB | §4.2, kept |+| 10 | Dependency-correct barriers from exact read/write ranges (RAW/WAR/WAW over recycled offsets) | v1 `nets/schedule.rs` | §7.5, generalised to SSA |++What v2 explicitly does **not** take: protobuf (FlatBuffers mmaps cleanly;+§2), single static signature for LLMs (§6), JIT-on-device or per-shape+re-trace in the hot path (§8), NPU-mandated paths (§11).++## 2. Container++FlatBuffers. `file_identifier "MAM2"`, `file_extension "maml"`.+Schema lives at `library/ml/src/main/rust/schema/maml2.fbs` and is the+normative definition; this document is the rationale. Tables (all new fields+appended at the end, LiteRT schema rule):++```+Model {+ version: uint; // file format version. Loader rejects mismatch. No minor/major game: unequal means reject.+ opset_version: uint; // op catalog version (§5.3). Loader rejects newer than it implements.+ runtime_min_version: string;// semver floor for the loader, e.g. "2.3.0".+ converter_version: string; // what wrote this file, for bisection.+ source_sha256: [ubyte:32]; // upstream artifact hash. Traceability, as v1.+ graph_digest: [ubyte:32]; // SHA-256 over the canonical op/edge/attr sequence (§9.2). Replaces v1's graph_id integer.+ description: string; // human-readable, e.g. "gemma4-text int4".+ backends: [BackendHint]; // optional per-entry-point placement (§6.3).++ tensors: [Tensor]; // §4. Every value in every graph, weights and computed alike.+ buffers: [Buffer]; // §4.2. Weight bytes. Computed tensors reference no buffer.+ graphs: [Graph]; // §5. Usually one; LLM text models ship prefill + decode sharing tensors.+ entry_points: [EntryPoint]; // §6. Named signatures over graphs.+ metadata: [KeyValue]; // free-form (tokenizer asset name, license, calibration note). Never load-bearing.+}+```++Loading is `mmap` + verify + dereference in place. The loader never+deserialises weights into a second allocation (§4.2).++## 3. Type system++### 3.1 Dtypes++`F16, F32, I32, U32, I8, I4, BF16`. Integer dtypes are always quantised+weights (§3.3); activations and all computed tensors are float. There is no+`STRING`, no `RESOURCE`, no sparse support — the catalog (§5.2) has no op+that needs them, and the schema must not carry generality the runtime pays+to ignore.++### 3.2 Shapes — the load-bearing section of this spec++Every `Tensor` carries a **static shape**: `dims: [int]` with all values+`> 0`. A static shape is a promise the loader may bake into compiled+pipelines. In addition, a tensor may carry `dim_params: [DimParam]` for+sequence-like axes:++```+DimParam { axis: uint; symbol: string; max: int; }+```++e.g. a decode-step query is `dims = [1536, 1, 2048]`, `dim_params = [{axis: 2,+symbol: "K", max: 2048}]`: stride 2048 baked, live length `K ≤ 2048` supplied+per submit as a step uniform (v1's `StepParams::prefix` mechanism, kept).+Rules:++* Rank is fixed. Only named axes vary, and only with an explicit `max`.+* The loader specialises pipelines against `dims` (the maxima), never+ re-compiling per live length. One decode plan serves all positions.+* Shape inference runs at load (§7.2): every computed tensor's static shape+ is re-derived from inputs and attributes and must equal the stored shape.+ A mismatch is a load error, not a re-record trigger.+* No `-1`-without-`max` anywhere. LiteRT's `shape` vs `shape_signature`+ split taught this: unbounded dynamics force re-plan in the hot path.++### 3.3 Quantization — data, not opcodes++```+Quantization {+ kind: QuantKind; // NONE | PER_CHANNEL | BLOCKWISE+ scale_tensor: int; // index into Model.tensors. Always fp16. -1 when kind == NONE.+ zero_point: int; // default -1 (symmetric, zp 0). Kept for schema completeness; symmetric only is enforced at validation.+ quantized_dim: int; // which axis scales run along (PER_CHANNEL), or the contraction axis (BLOCKWISE).+ block_size: int; // taps per scale for BLOCKWISE. v1's 32-wide I4 blocks carry over.+}+```++* int8: one fp16 scale per output channel (`PER_CHANNEL`).+* int4: one fp16 scale per block of 32 taps along the contraction axis+ (`BLOCKWISE`), nibbles packed two per byte low-first — v1's layout,+ unchanged, because every kernel already implements it.+* A quantised tensor's `buffer` holds packed bytes; `elem_count` is logical+ elements. The loader checks `buffer_bytes == ceil(elems / stride)`.+* Scales are ordinary tensors in `Model.tensors` (LiteRT `BlockwiseQuantization.scales`+ precedent), so they upload verbatim with everything else and need no+ special path. Activations stay fp16: the export's dynamic activation+ quantisation is out of scope, as in v1.++### 3.4 Layouts++```+Layout : byte { NCHW = 0; CHANNEL_BLOCKED_4 = 1; POSITION_MAJOR = 2; }+```++* Each tensor declares its layout. The converter **repacks weights into+ whatever the kernels consume** (kernel-chosen layout at convert time, per+ the v1 lesson that init-time repack forfeits zero-copy upload).+* Computed tensors default to `CHANNEL_BLOCKED_4` (the PHWC4 equivalent):+ channel groups of 4 contiguous, so a channel reduction is a `vec4` load.+ The v1 NCHW strided-reduction defect (§0.3) becomes inexpressible.+* KV-caches are `POSITION_MAJOR`: `[K, 1, d]` positions appended per step+ (v1's decode-cache layout, kept and now declared instead of implicit).+* Layout is part of the pipeline cache key (§8.2). No runtime transpose+ passes: a layout mismatch between producer and consumer is a converter+ bug, caught by shape+layout inference at load.++## 4. Tensors and buffers++```+Tensor {+ name: string; // debug + error messages only. Never resolved by name at load.+ dtype: DType;+ dims: [int]; // §3.2, all > 0.+ dim_params: [DimParam]; // §3.2, optional.+ layout: Layout; // §3.4.+ quantization: Quantization; // §3.3, NONE for computed tensors.+ buffer: int; // index into Model.buffers, or -1 for computed/state tensors.+ buffer_offset: ulong; // byte offset within the buffer.+ elem_count: ulong; // logical elements; cross-checked against dims product.+ placement: Placement; // DEVICE (default) | HOST. HOST = gathered on CPU (v1's GEMMA4_EMBED precedent: one row per step, never bound whole).+ state: StateKind; // NONE | KV_CACHE | PINNED. §6.2.+}+Buffer {+ data: [ubyte]; // force_align 16. One buffer per file in practice; many allowed.+}+```++### 4.1 SSA discipline++Within a graph, every computed tensor has exactly one writer. File tensors+(weights, constants) have none. Graph inputs are written by the caller.+Validation rejects multi-writer and cycles (§9.2). This is what makes fusion+(§7.3), memory planning (§7.4), and barrier scheduling (§7.5) one pass each+instead of per-net code.++### 4.2 Verbatim upload, preserved++The v1 property that matters — file offset = device offset, whole blob to+one `VkBuffer` with no host copy — is kept and strengthened: `Buffer.data`+is 16-aligned, every tensor's `buffer_offset` is 16-aligned, and the loader+uploads each buffer with chunked `cmd_copy_buffer`s straight from the mmap+(v1's `Blob`/`Streamed` precedent: peak host cost one chunk, never 3x the+model in transient heap). Kernel-chosen repacking happens in the converter,+so verbatim upload and optimal layout stop being in conflict.++## 5. Graph++```+Graph {+ name: string; // "prefill", "decode_step", "encode", ...+ tensors: [int]; // indices into Model.tensors forming this graph's SSA scope.+ nodes: [Node]; // topological order. The file order IS the schedule seed.+ inputs: [int]; // tensor indices, declaration order = binding order.+ outputs: [int]; // tensor indices.+}+Node {+ op: Op; // §5.2 catalog enum.+ inputs: [int]; // tensor indices.+ outputs: [int]; // tensor indices (usually one).+ attrs: [Attribute]; // typed attributes, op-specific (§5.2). No untyped blobs except CustomOp.payload.+}+Attribute {+ name: string;+ value: AttrValue; // int | ints | float | floats | bool | string. FlatBuffers union.+}+```++### 5.1 Convert-time obligations (ONNX lessons)++The converter runs, in order: **simplify → constant-fold → fold-into-weights+→ DCE**, and the file holds the result:++* Fold `BatchNorm` into the preceding linear op (exact affine fold).+* Fold affine-into-unpadded-conv; never into padded conv (border correction+ is position-dependent — v1 `ppocr_fold.py` lesson, now a spec rule).+* Fold `Mul(x, Sigmoid(x))` → `Swish`, `Erf`-spelled gates → `Gelu`,+ gate/up-`Mul` over a fused projection → `GatedSwish` (§5.2).+* Constant subgraphs (style keys, angle tables with fixed length, masks)+ become `Constant` tensors, not nodes.+* DCE removes shape-scaffolding initializers and anything with no path to+ an output. What the runtime loads is the minimal executable graph.+* `Gemm` over a flattened map is `Conv` with a full-extent kernel (v1's+ MobileFaceNet precedent — no `InnerProduct` pipeline exists).++### 5.2 Op catalog (high-level, fusable)++Coarse ops with typed attributes. The runtime fuses epilogues and layouts at+load (§7.3); the file never stores a fused mega-op, so fusion stays a loader+decision that improves with the runtime, not a converter lock-in.++| Op | Inputs → Outputs | Key attrs |+|----|-----------------|-----------|+| `Conv` | x, (w, b) → y | `kernel, stride, dilation, pads, groups, pad_edge, activation, res, shift` |+| `MatMul` | a, b → y | `transpose_b, activation, res` — covers 1x1 convs, projections, heads; lowering (tiled GEMM vs GEMV) is the loader's choice per shape |+| `DepthwiseConv` | x, (w, b) → y | `kernel, stride, pads, activation` — separate op, separate kernel family |+| `Embedding` | ids, table → y | `rows` — ids lane-split in converter for vocabs past fp16-exact range (v1 `EMBED_LANE` precedent) |+| `LayerNorm` / `RmsNorm` | x, (gamma, beta?) → y | `epsilon, groups` |+| `Attention` | q, k, v → y | `heads, kv_heads, scale, causal, sliding_window, softcap, out_proj` (fused output projection tensor ref, or -1). Banded/sliding lowering chosen by loader from `sliding_window` + live length |+| `AttentionDecode` | q, k_cache[state], v_cache[state] → y | `heads, kv_heads, scale, sliding_window, softcap, out_proj, dynamic_keys` — one query against position-major caches; key count from step uniform |+| `CacheWrite` | row, cache[state] → (cache) | none — destination position from step uniform; the only op whose write address is submit-time |+| `RotaryEmbedding` | x, angles → y | `heads, axes` (1 = 1-D RoPE, 2 = split row/col) |+| `Softmax` | x → y | `mode: FULL \| CAUSAL \| PREFIX`, `window` |+| `Add, Mul, MulBroadcast, AddBroadcast` | a, b → y | none — broadcast kinds explicit (v1's channel-broadcast precedent) |+| `Affine` | x → y | `scale, shift` scalars — only where folding is illegal (post-activation, padded consumer) |+| `GatedSwish` | fused `[gate\|up]` projection → y | `activation` — replaces slice + act + mul |+| `Clamp, MulScalar, Softcap` | x → y | `min/max | scale | cap` |+| `Resize` | x → y | `mode: BILINEAR_HALF_PIXEL \| NEAREST_ASYMMETRIC`, `scales` |+| `MaxPool, AvgPool, GlobalAvgPool` | x → y | `kernel, stride` |+| `Concat` | parts → y | `axis` — channel concat lowers to arena copies, no shader (v1 precedent); width concat is strided and keeps a kernel |+| `View` | x → y | `offset, dims` — zero-copy reinterpret (head splits, squeezes). Must be within the source allocation; validated |+| `Constant` | (weights) → y | none — learned tensor copied to arena once |+| `Copy` | x → y | none — contiguous move the loader may implement as transfer or elide |+| `CustomOp` | declared → declared | `name, payload:[ubyte]` — opaque; loader rejects unknown names. Escape hatch, not a habit |++Epilogue fusion surface (stored as attributes on the producer, §7.3):+`activation` (None/Relu/Swish/Gelu/Sigmoid/Clip01/HardSwish/PRelu-with-slope-ref),+`res` (tensor index of a same-shape residual addend, or -1),+`shift` (tensor index of a per-channel shift, or -1). Only single-consumer+epilogues fuse; the loader checks consumer count from SSA.++### 5.3 Opset and extension++`Model.opset_version` pins this catalog. New ops bump it; loaders reject+`opset_version` newer than implemented — loudly, at open, never as wrong+answers. `CustomOp` names are namespaced (`vendor.op`) and never promoted+silently into the catalog.++## 6. Entry points and state (the LiteRT-LM section)++```+EntryPoint {+ name: string; // "encode" | "prefill" | "decode_step" | "image" | "text" ...+ graph: uint; // index into Model.graphs.+ inputs: [string]; // roles, e.g. ["tokens", "images", "mel"]. Binds positionally to Graph.inputs.+ step_uniforms: [string]; // live values per submit: e.g. ["prefix_len", "window_start"].+}+```++### 6.1 Prefill vs decode++An LLM ships **two graphs sharing one tensor table**: `prefill` (full+sequence, matrix-matrix, compute-bound) and `decode_step` (one query,+matrix-vector against caches). They share weight tensors by index — the file+holds 4.7 GB of embeddings once even when both graphs reference them. TTFT+(prefill) and TTIT (decode) are accepted per entry point, never as one+blended latency (§8.3).++### 6.2 State tensors++```+StateKind : byte { NONE = 0; KV_CACHE = 1; PINNED = 2; }+```++* `KV_CACHE`: shape declares capacity (`max_tokens` via `dim_params`),+ dtype, and `POSITION_MAJOR` layout. The file embeds **no cache contents** —+ capacity, not data. The loader allocates per session; the host may+ export/import pinned prefix caches across launches (v1's+ `export_pinned`/`import_pinned` precedent for recomputed system blocks).+* `PINNED`: survives across submits at a stable offset (inputs the caller+ reuses, prefix constants). Declared so the memory planner never recycles+ them.+* Cache growth never re-plans: capacity is the baked maximum, live length+ is a step uniform. Variable-length re-record per token is the defect this+ section exists to forbid.++### 6.3 Placement++`backends: [{entry_point, preferred: GPU|CPU, fallback: GPU|CPU}]` records+the tested placement (e.g. embeddings gathered on host, sampler on GPU).+Advisory: the loader may override, but the default path must match what the+converter validated parity against.++## 7. Load-time pipeline (normative order)++1. **Verify** (§9.1): magic, versions, bounds, alignment.+2. **Shape+layout inference**: re-derive every computed tensor's shape and+ layout from inputs and attributes; must equal stored. `View` bounds,+ single-writer SSA, acyclicity checked here.+3. **Lowering choice**: `MatMul` → tiled-GEMM / GEMV / vec kernel by shape+ (the v1 `ConvPoint` vs `ConvVec` routing, now data-driven); `Attention`+ → full / banded / cached by `sliding_window` and graph role.+4. **Fusion**: fold single-consumer elementwise epilogues, `res`/`shift`+ stores, and `GatedSwish` patterns into producers via the §5.2 attributes.+ Fusion never changes numerics beyond fp16 reassociation already accepted+ by parity (§8.3).+5. **Memory plan**: liveness from SSA + `pinned`/`state` exclusions → arena+ offsets with free-list packing (v1 `Builder::finish` precedent). Arena+ size is an output of the loader, not a file field — it depends on fusion.+6. **Barrier schedule**: from exact read/write ranges per lowered op+ (RAW/WAR/WAW over recycled offsets, v1 `schedule.rs` generalised from+ per-`Kind` audits to SSA-derived ranges). Barriers only where the schedule+ says so; the one-barrier-per-op recorder is gone. Transfer-stage+ inclusion wherever a `Copy`/upload is on either side.+7. **Specialisation**: shapes, strides, and layout constants baked per+ pipeline (specialization constants / generated variants); one pipeline+ creation per (op, shape-class) cached by `(graph_digest, entry_point,+ tensor dims…)` fingerprint. Measured creation cost (~12 ms) is paid once+ at load, never per inference.++## 8. Runtime contract (what the loader guarantees)++* §8.1 **One record, then submit.** Each entry point records once per shape+ class into one command buffer. An inference is upload-inputs, one submit,+ readback — no per-frame allocation, no per-token re-record.+* §8.2 **Pipelines are cached and keyed.** Cache key includes graph digest,+ entry point, op, full static dims, layout, and dtype. Cold-driver compile+ (~1.4 s first launch) is amortised across sessions via the driver's cache+ under this key, never recompiled silently.+* §8.3 **Parity-gated.** Every (graph, entry point) ships with a converter-+ produced reference vector (`metadata["parity_sha256"]` + out-of-band+ fixture). Loader changes that move any output past the accepted tolerance+ fail `onnx_parity`-equivalent checks before review. Performance tables+ always carry an output-correctness column (frame/token count) — the+ truncated-utterance lesson is now a process rule.+* §8.4 **Host boundary is at entry-point I/O only.** Intermediates never+ leave the device. Inputs upload once per submit; outputs read back once.+ (v1's per-net-call f32↔f16 staging dance is replaced by entry-point+ bindings with declared dtypes.)++## 9. Versioning and validation++* §9.1 **Structural validation at open** (before any device touch):+ magic `MAM2`; `version` equal to the loader's; `opset_version ≤`+ loader's; every tensor ref `< tensor_count`; every buffer range within+ its buffer and 16-aligned; `elem_count == product(dims)` (with packed-size+ math for I4); `dim_params` axes in range with `max ≥ dims[axis]`;+ `Views` within source bounds; quant `scale_tensor` shapes (`[out_c]` /+ `[out_c, ceil(taps/block)]`).+* §9.2 **Semantic validation after inference**: single-writer SSA,+ acyclicity, every weight tensor read-or-host (v1's every-tensor rule),+ every graph output traceable to inputs, `graph_digest` recomputed and+ matched. Failure is a load error with tensor/node identity — never a+ wrong answer, never a driver reset.+* §9.3 **No silent fallback.** A file that validates but names an unknown+ `CustomOp`, or an entry point the loader cannot place, fails. Falling back+ to a different topology is the failure mode v1's graph_id gate existed to+ prevent; v2's digest gate inherits it.++## 10. Converter responsibilities++The converter (successor to `maml_convert.py`) owns everything that can be+decided offline: ONNX/checkpoint/TFLite import, §5.1 simplification passes,+layout repacking (§3.4), quantisation with per-tensor cosine gates (v1's+`MIN_INT8_COSINE`/`MIN_INT4_COSINE` precedent), digest computation, parity+fixtures, and the layer-table emission checklist per model. The runtime owns+everything that needs the device: §7 lowering, fusion, planning,+specialisation, scheduling. The boundary is: converter decides **what** to+compute and in **what layout**; runtime decides **how** to execute it.++## 11. Non-goals (explicit)++* No NPU/delegate pre-compiled blobs in v2 files. The schema reserves+ `BackendHint` and a future `delegate_blobs` section, but no backend+ consumes them yet; GPU-Vulkan is the only lowering target.+* No training, no gradients, no control flow beyond the entry-point set.+ Data-dependent loops stay on the host (sample Euler steps, sampler loops,+ beam handling) calling entry points per step — as v1's `post/` did.+* No text tokenizer inside the model file. Tokenizer assets are referenced+ by `metadata["tokenizer"]` and shipped alongside, LiteRT-LM-bundle style,+ never parsed by the Vulkan loader.+* No multi-file sharding in v2.0. Large-model splitting (embeddings apart+ from text, tower-per-file optionality) stays a file-selection decision,+ expressed by shipping several single files, not by intra-file partitions.++## 12. Open questions++1. FlatBuffers schema evolution vs strict `version` equality (§2): LiteRT+ appends fields for back-compat, but v2 has no installed base. Keep strict+ equality until the first shipped release, then relax to `≤`? **Proposed:+ strict until v2 ships on-device, then append-only.**+2. Tuning hints table: should the converter emit preferred+ `(op, shape-class) → (workgroup, tile)` hints from offline benchmarking,+ or does the runtime own all workgroup selection? **Proposed: optional+ `hints` section loaders may ignore; runtime autotune wins on conflict.**+3. `Attention`'s fused `out_proj`: tensor ref inside the attribute vs a+ separate `MatMul` node the fusion pass folds? Separate node keeps SSA+ pure but costs the loader a mandatory fusion; attribute keeps the common+ case atomic. **Proposed: separate node + mandatory fusion rule, so the+ unfused form stays expressible for parity.**+4. Prefix-cache serialization format for `export_pinned` across app+ versions: digest-keyed raw snapshots vs versioned container?+ **Proposed: raw snapshots keyed by `(graph_digest, entry_point)` with a+ header carrying both; loader rejects mismatched digests.**
library/ml/src/main/rust/Cargo.toml
diff --git a/library/ml/src/main/rust/Cargo.toml b/library/ml/src/main/rust/Cargo.tomlindex 868e8ce8b5..641097017f 100644--- a/library/ml/src/main/rust/Cargo.toml+++ b/library/ml/src/main/rust/Cargo.toml@@ -36,6 +36,18 @@ crate-type = ["cdylib", "rlib"] [dependencies] jni.workspace = true +# Wire format for MAML v2 (`schema/maml2.fbs`, compiled by `flatc` in+# `build.rs`). Exact pin: generated code and runtime rev together, so a caret+# range drifting to a newer runtime than the `flatc` that emitted the bindings+# would be a silent mismatch. Matches the `protobuf = "=3.7.2"` precedent in+# the workspace root.+flatbuffers = "=25.12.19"+# Spec section 9.2: SHA-256 over the canonical op/edge/attr sequence is the+# `graph_digest` that replaces v1's `graph_id` integer. Same major line as the+# workspace pin (0.11.0); the workspace itself is not referenced because this+# crate intentionally carries no other workspace deps beyond `jni`.+sha2 = "0.11.0"+ # `default-features = false` drops the `linked` feature, so nothing links against # libvulkan at build time; `loaded` dlopens it, which is what an Android app must do # anyway. It is not android-gated: `loaded` finds the platform loader on the host too,
library/ml/src/main/rust/build.rs
diff --git a/library/ml/src/main/rust/build.rs b/library/ml/src/main/rust/build.rsindex 9c5e9b4458..a9db3181de 100644--- a/library/ml/src/main/rust/build.rs+++ b/library/ml/src/main/rust/build.rs@@ -27,13 +27,16 @@ use std::process::Command; fn main() { let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));- let shader_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"))- .join("shaders");+ let manifest_dir =+ PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));+ let shader_dir = manifest_dir.join("shaders"); let glslc = find_glslc(); println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=shaders"); + compile_flatbuffers_schema(&manifest_dir, &out_dir);+ let mut compiled = 0; let mut entries: Vec<PathBuf> = std::fs::read_dir(&shader_dir) .unwrap_or_else(|e| panic!("cannot read {}: {e}", shader_dir.display()))@@ -91,6 +94,75 @@ fn main() { /// A SPIR-V module is a five-word header plus at least a few instructions. const MIN_SPIRV_BYTES: u64 = 64; +/// Compiles `schema/maml2.fbs` to Rust with `flatc`, into `$OUT_DIR`.+///+/// The generated module is `include!`d by `src/maml2/mod.rs`. Same hard-fail+/// philosophy as the shaders above: a missing `flatc` stops the build rather+/// than producing a runtime that cannot read its own format.+fn compile_flatbuffers_schema(manifest_dir: &Path, out_dir: &Path) {+ let schema = manifest_dir.join("schema").join("maml2.fbs");+ println!("cargo:rerun-if-changed=schema/maml2.fbs");+ if !schema.is_file() {+ panic!("{} is missing; it is the schema of record", schema.display());+ }+ let flatc = find_flatc();+ let output = Command::new(&flatc)+ .arg("--rust")+ .arg("-o")+ .arg(out_dir)+ .arg(&schema)+ .output()+ .unwrap_or_else(|e| panic!("cannot run {}: {e}", flatc.display()));+ if !output.status.success() {+ panic!(+ "flatc failed on {}:\n{}{}",+ schema.display(),+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );+ }+ let generated = out_dir.join("maml2_generated.rs");+ let written = std::fs::metadata(&generated).map(|m| m.len()).unwrap_or(0);+ if written == 0 {+ panic!(+ "flatc produced no {} for {}; a real binding module is kilobytes",+ generated.display(),+ schema.display(),+ );+ }+}++/// `flatc` for the **host** platform.+///+/// Searched in order, mirroring [`find_glslc`]:+///+/// 1. `FLATC` — an explicit override, for a CI image that puts it elsewhere.+/// 2. `flatc` on `PATH`.+fn find_flatc() -> PathBuf {+ if let Some(explicit) = env::var_os("FLATC").map(PathBuf::from) {+ if explicit.is_file() {+ return explicit;+ }+ panic!("FLATC is set to {explicit:?} but that is not a file");+ }++ let executable = if cfg!(windows) { "flatc.exe" } else { "flatc" };+ if Command::new(executable)+ .arg("--version")+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+ {+ return PathBuf::from(executable);+ }++ panic!(+ "flatc not found. Install flatbuffers 25.12.19 (to match the `flatbuffers` \+ crate pin in Cargo.toml) and put {executable} on PATH, or set FLATC. The \+ MAML v2 schema cannot be compiled without it, so this build stops here.",+ );+}+ /// `glslc` for the **host** platform, from the NDK. /// /// Cargo runs this script on the build machine while cross-compiling for Android,
library/ml/src/main/rust/examples/check_sampler_maml2.rs
diff --git a/library/ml/src/main/rust/examples/check_sampler_maml2.rs b/library/ml/src/main/rust/examples/check_sampler_maml2.rsnew file mode 100644index 0000000000..d9452d8131--- /dev/null+++ b/library/ml/src/main/rust/examples/check_sampler_maml2.rs@@ -0,0 +1,68 @@+//! Verify + infer a MAML v2 sampler file: the Phase 2 gate.+//!+//! ```text+//! cargo run --release -p modelrunner --example check_sampler_maml2 [path]+//! ```+//!+//! Defaults to `speech/src/main/assets/supertonic/supertonic_ve.maml2`.+//! Asserts, in order:+//!+//! * [`verify`]: identifier, `version ==`, `opset <=`, bounds, alignment,+//! refs in range, entry roles match graph inputs.+//! * [`infer`]: every computed shape re-derived and equal to stored, SSA+//! single-writer, topological order, outputs traceable, digest recomputed+//! and equal to the stored `graph_digest`.+//! * Cross-check: node count and op inventory against the v1 recording.++use std::path::PathBuf;++use modelrunner::maml2::{infer, verify};++fn main() {+ let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));+ while !dir.join("settings.gradle.kts").exists() {+ dir = dir.parent().expect("repo root").to_path_buf();+ }+ let arg = std::env::args().nth(1);+ let path = arg.map(PathBuf::from).unwrap_or_else(|| {+ dir.join("speech/src/main/assets/supertonic/supertonic_ve.maml2")+ });+ let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display()));++ let verified = verify::verify(&bytes).expect("verify");+ println!(+ "verify: {} tensors, {} buffers, {} graphs",+ verified.tensor_count, verified.buffer_count, verified.graph_count+ );++ let inferred = infer::infer(&verified).expect("infer");+ assert_eq!(inferred.len(), verified.graph_count);+ for graph in &inferred {+ println!("graph {}: {} shapes inferred", graph.graph, graph.shapes.len());+ }++ // Digest check against the stored row: the recompute must equal what the+ // emitter wrote, which is also what Python recomputed independently.+ let model = verified.model;+ let stored: Vec<u8> =+ model.graph_digest().map(|d| d.iter().collect()).unwrap_or_default();+ assert_eq!(&stored[..], &inferred[0].graph_digest[..], "digest matches stored");+ println!("digest: {}", hex(&inferred[0].graph_digest));++ // Negative checks: truncated, flipped-version, and flipped-op files must+ // all fail (never a wrong answer, never a silent pass).+ let mut bad = bytes.clone();+ bad.truncate(bad.len() / 2);+ assert!(verify::verify(&bad).is_err(), "truncated file must fail");+ let mut bad_version = bytes.clone();+ // `version` is the first u32 past the FlatBuffers root offset + vtable;+ // flipping is version-agnostic: corrupt the identifier instead, which+ // must fail before any parse.+ bad_version[4] = b'X';+ assert!(verify::verify(&bad_version).is_err(), "bad identifier must fail");+ println!("negative checks pass (truncated + bad identifier rejected)");+}++fn hex(bytes: &[u8]) -> String {+ bytes.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().join("")+}
library/ml/src/main/rust/examples/emit_sampler_maml2.rs
diff --git a/library/ml/src/main/rust/examples/emit_sampler_maml2.rs b/library/ml/src/main/rust/examples/emit_sampler_maml2.rsnew file mode 100644index 0000000000..ecb3f07128--- /dev/null+++ b/library/ml/src/main/rust/examples/emit_sampler_maml2.rs@@ -0,0 +1,101 @@+//! Emit a MAML v2 sampler file from the committed v1 asset.+//!+//! ```text+//! cargo run --release -p modelrunner --example emit_sampler_maml2+//! ```+//!+//! # Why an example and not a test+//!+//! The emitter needs the real `supertonic_ve.maml` weights (tens of MB) to+//! repack, and `cargo test` must stay runnable with no assets. This follows+//! the `report_barriers` precedent: read the committed `.maml` files, build+//! plans on the host with no Vulkan, write the v2 file beside them.+//!+//! # What it proves (Phase 1 gate)+//!+//! * The sampler records [`Recorded`] through its own `record` entry point.+//! * [`emit_sampler`] serialises that recording to `MAM2` FlatBuffers.+//! * The output re-parses with the file identifier, the node count matches+//! the recording, and the digest recomputes.+//! * Output: `speech/src/main/assets/supertonic/supertonic_ve.maml2`.++use std::path::{Path, PathBuf};++use modelrunner::maml2::{self, emit};+use modelrunner::nets::supertonic_sampler;+use modelrunner::weights::{graph, Weights};++/// Frames and characters to record at. Must be a shape the net actually runs:+/// the analysis utterance is 49 frames / 55 chars.+const FRAMES: u32 = 49;+const CHARS: u32 = 55;++fn repo_root() -> PathBuf {+ let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));+ while !dir.join("settings.gradle.kts").exists() {+ dir = dir.parent().expect("repo root").to_path_buf();+ }+ dir+}++fn main() {+ let root = repo_root();+ let path = root.join("speech/src/main/assets/supertonic/supertonic_ve.maml");+ let bytes =+ std::fs::read(&path).unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display()));+ let weights = Weights::parse(&bytes, graph::SUPERTONIC_VE).expect("the v1 sampler asset parses");+ let table = weights.offsets();+ let tensors: Vec<modelrunner::weights::Tensor> =+ (0..table.len()).map(|i| table.tensor(i).expect("tensor")).collect();++ let recorded =+ supertonic_sampler::record(&table, FRAMES, CHARS).expect("the sampler records");++ let emitted = emit::emit_sampler(+ &recorded,+ &tensors,+ weights.data(),+ "supertonic-sampler ve fp16/int8 cb4 (Phase 1 pilot)",+ "maml2 emit_sampler_maml2",+ weights.source_sha256,+ )+ .expect("emission succeeds");++ // Verify: identifier, root parse, counts, digest.+ assert!(maml2::fb::model_buffer_has_identifier(&emitted.bytes));+ let model = maml2::fb::root_as_model(&emitted.bytes).expect("the emitted file parses");+ assert_eq!(model.version(), maml2::FORMAT_VERSION);+ assert_eq!(model.opset_version(), maml2::OPSET_VERSION);+ let tensors_out = model.tensors().map(|t| t.len()).unwrap_or(0);+ let graphs = model.graphs().map(|g| g.len()).unwrap_or(0);+ assert_eq!(graphs, 1, "one sampler graph");+ let nodes = model.graphs().and_then(|g| g.get(0).nodes()).map(|n| n.len()).unwrap_or(0);+ assert_eq!(nodes, recorded.nodes.len(), "one v2 node per recorded node");+ let digest =+ model.graph_digest().map(|d| d.iter().collect::<Vec<u8>>()).unwrap_or_default();+ assert_eq!(&digest[..], &emitted.graph_digest[..], "digest round-trips");++ let out_path = root.join("speech/src/main/assets/supertonic/supertonic_ve.maml2");+ write_out(&out_path, &emitted.bytes);++ println!("sampler v2: {tensors_out} tensors, {nodes} nodes");+ println!("op inventory:");+ let mut inventory = emitted.op_inventory;+ inventory.sort_by_key(|(_, n)| std::cmp::Reverse(*n));+ for (op, count) in &inventory {+ println!(" {op:?}: {count}");+ }+ println!("graph_digest: {}", hex(&emitted.graph_digest));+ println!("wrote {}", out_path.display());+}++fn write_out(path: &Path, bytes: &[u8]) {+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent).expect("asset dir");+ }+ std::fs::write(path, bytes).expect("write the v2 file");+}++fn hex(bytes: &[u8]) -> String {+ bytes.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().join("")+}
library/ml/src/main/rust/examples/lower_sampler_maml2.rs
diff --git a/library/ml/src/main/rust/examples/lower_sampler_maml2.rs b/library/ml/src/main/rust/examples/lower_sampler_maml2.rsnew file mode 100644index 0000000000..3e7186aacd--- /dev/null+++ b/library/ml/src/main/rust/examples/lower_sampler_maml2.rs@@ -0,0 +1,151 @@+//! Lower a MAML v2 sampler file to a Plan and compare against v1.+//!+//! ```text+//! cargo run --release -p modelrunner --example lower_sampler_maml2 [path]+//! ```+//!+//! The round-trip gate: verify → infer → lower must reproduce the v1 plan's+//! op inventory (kinds folded as the op-inventory tests fold them), arena+//! high-water, and input/output bindings at the same shape. Any divergence is+//! a loader bug, not tolerance.++use std::path::PathBuf;++use modelrunner::maml2::{infer, lower, verify};++fn main() {+ let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));+ while !dir.join("settings.gradle.kts").exists() {+ dir = dir.parent().expect("repo root").to_path_buf();+ }+ let arg = std::env::args().nth(1);+ let path = arg.map(PathBuf::from).unwrap_or_else(|| {+ dir.join("speech/src/main/assets/supertonic/supertonic_ve.maml2")+ });+ let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display()));++ let verified = verify::verify(&bytes).expect("verify");+ let inferred = infer::infer(&verified).expect("infer");+ assert_eq!(inferred.len(), 1);+ let weights = lower::V2Weights::new(&verified).expect("weight bridge");+ let plan = lower::lower(&verified, &inferred[0], &weights, 0).expect("lower");++ // v1 oracle at the same shape: the emitter recorded at 49 frames / 55+ // chars, which is what the v2 file's static shapes carry.+ let v1path = dir.join("speech/src/main/assets/supertonic/supertonic_ve.maml");+ let v1bytes = std::fs::read(&v1path).expect("read the v1 asset");+ let v1 =+ modelrunner::weights::Weights::parse(&v1bytes, modelrunner::weights::graph::SUPERTONIC_VE)+ .expect("parse the v1 asset");+ let v1plan =+ modelrunner::nets::supertonic_sampler::build(&v1.offsets(), 49, 55).expect("build v1");++ println!("v2: {} ops, arena {} elems", plan.ops.len(), plan.arena_elems);+ println!("v1: {} ops, arena {} elems", v1plan.ops.len(), v1plan.arena_elems);+ assert_eq!(plan.ops.len(), v1plan.ops.len(), "same op count");+ assert_eq!(plan.inputs.len(), v1plan.inputs.len(), "same input count");+ assert_eq!(plan.outputs.len(), v1plan.outputs.len(), "same output count");+ for (a, b) in plan.inputs.iter().zip(v1plan.inputs.iter()) {+ assert_eq!(a.shape, b.shape, "input shapes match");+ }+ for (a, b) in plan.outputs.iter().zip(v1plan.outputs.iter()) {+ assert_eq!(a.shape, b.shape, "output shapes match");+ }+ // Per-op inventory with the same folding the op-inventory tests use+ // (tiled lowerings fold back to the graph op). `name_of` is `pub(crate)`+ // for in-tree tests; examples are separate crates, so the fold is+ // Per-op inventory with the same folding the op-inventory tests use+ // (tiled lowerings fold back to the graph op). `name_of` is `pub(crate)`+ // for in-tree tests; examples are separate crates, so the fold is+ // re-stated here rather than reached into. Address spaces legitimately+ // differ (repacked weights), so compare geometry, not addresses.+ let fold = |kind: modelrunner::nets::Kind| -> String {+ match kind {+ modelrunner::nets::Kind::ConvPoint => "Conv".to_string(),+ modelrunner::nets::Kind::ConvPointInt8+ | modelrunner::nets::Kind::ConvVecInt8+ | modelrunner::nets::Kind::ConvPointCb4Int8 => "ConvInt8".to_string(),+ other => format!("{other:?}"),+ }+ };+ let geom = |op: &modelrunner::nets::Op| -> String {+ // Kinds fold through the same table as the inventory: the blocked+ // twin is the same op in a different layout, so geometry compares+ // modulo the twin mapping. Anything else compares exactly.+ match op {+ modelrunner::nets::Op::Copy { elems, .. } => format!("Copy{{{elems}}}"),+ modelrunner::nets::Op::Dispatch { kind, push, invocations } => format!(+ "{}in={}/{}/{} out={}/{}/{} k={}x{} s={}x{} g={} act={} n={} inv={invocations}",+ fold(*kind),+ push.in_c, push.in_h, push.in_w, push.out_c, push.out_h, push.out_w,+ push.kh, push.kw, push.stride_h, push.stride_w, push.group, push.act,+ push.count,+ ),+ }+ };+ for (step, (a, b)) in plan.ops.iter().zip(v1plan.ops.iter()).enumerate() {+ if geom(a) != geom(b) {+ println!("first geometry divergence at op {step}:");+ println!(" v2: {}", geom(a));+ println!(" v1: {}", geom(b));+ println!(" v2 full: {a:?}");+ println!(" v1 full: {b:?}");+ break;+ }+ }+ // Full-address comparison is expected to differ (repacked weights); the+ // geometry loop above is the real gate. Arena high-water is informational:+ // identical shapes + order should pack identically, and a divergence here+ // after zero geometry divergences points at pinned/binding order.+ if plan.arena_elems != v1plan.arena_elems {+ println!(+ "NOTE: arena differs (v2 {} vs v1 {}); bindings:",+ plan.arena_elems, v1plan.arena_elems+ );+ for (i, (a, b)) in plan.inputs.iter().zip(v1plan.inputs.iter()).enumerate() {+ println!(" in{i}: v2 at={} {a:?} vs v1 at={} {b:?}", a.at, b.at);+ }+ for (i, (a, b)) in plan.outputs.iter().zip(v1plan.outputs.iter()).enumerate() {+ println!(" out{i}: v2 at={} {a:?} vs v1 at={} {b:?}", a.at, b.at);+ }+ }+ let fold = |kind: modelrunner::nets::Kind| -> String {+ match kind {+ modelrunner::nets::Kind::ConvPoint => "Conv".to_string(),+ modelrunner::nets::Kind::ConvPointInt8+ | modelrunner::nets::Kind::ConvVecInt8+ | modelrunner::nets::Kind::ConvPointCb4Int8 => "ConvInt8".to_string(),+ other => format!("{other:?}"),+ }+ };+ let mut v2counts = std::collections::BTreeMap::new();+ for op in &plan.ops {+ if let modelrunner::nets::Op::Dispatch { kind, .. } = op {+ *v2counts.entry(fold(*kind)).or_insert(0) += 1;+ }+ }+ let mut v1counts = std::collections::BTreeMap::new();+ for op in &v1plan.ops {+ if let modelrunner::nets::Op::Dispatch { kind, .. } = op {+ *v1counts.entry(fold(*kind)).or_insert(0) += 1;+ }+ }+ // Copies are arena moves, not dispatches: compare separately.+ let v2copies = plan.ops.iter().filter(|op| matches!(op, modelrunner::nets::Op::Copy { .. })).count();+ let v1copies = v1plan.ops.iter().filter(|op| matches!(op, modelrunner::nets::Op::Copy { .. })).count();+ println!("v2 inventory: {v2counts:?} + {v2copies} copies");+ println!("v1 inventory: {v1counts:?} + {v1copies} copies");+ assert_eq!(v2counts, v1counts, "same dispatch inventory");+ assert_eq!(v2copies, v1copies, "same copy count");+ // Geometry is the round-trip gate (addresses legitimately differ across+ // the repack). Fail here if any op diverged geometrically above.+ let mut diverged = false;+ for (a, b) in plan.ops.iter().zip(v1plan.ops.iter()) {+ if geom(a) != geom(b) {+ diverged = true;+ break;+ }+ }+ assert!(!diverged, "zero geometry divergences");+ println!("round-trip: identical geometry, identical inventory");+}
library/ml/src/main/rust/schema/maml2.fbs
diff --git a/library/ml/src/main/rust/schema/maml2.fbs b/library/ml/src/main/rust/schema/maml2.fbsnew file mode 100644index 0000000000..36ecb92f07--- /dev/null+++ b/library/ml/src/main/rust/schema/maml2.fbs@@ -0,0 +1,288 @@+// MAML v2 model container.+//+// Normative schema for `library/ml/MAML2_SPEC.md`. This file is the schema of+// record: the Rust loader and the Python converter both generate from it, so+// neither hand-writes the layout. See the spec for rationale; see+// `scripts/ml/maml_convert.py` for the v1 layout this replaces.+//+// Revision history+// Version 1: Initial version. SSA graph + weights, static shapes with+// dim_params maxima, quantization as data, converter-repacked+// layouts, prefill/decode entry points, KV-cache state tensors.+//+// IMPORTANT: All new members of tables, enums and unions must be added at the+// end to ensure backwards compatibility (LiteRT schema rule). The loader+// additionally enforces strict `version ==` until the first on-device ship+// (spec section 12.1); the append-at-end rule is what makes relaxing that+// possible later.++namespace maml2;++// This corresponds to the file format version (`Model.version`).+file_identifier "MAM2";+// File extension of any written files.+file_extension "maml";++// Initial opset: the op catalog in section 5.2 of the spec. New ops bump+// `Model.opset_version`; loaders reject newer than they implement.+enum Op : byte {+ Conv = 0,+ MatMul = 1,+ DepthwiseConv = 2,+ Embedding = 3,+ LayerNorm = 4,+ RmsNorm = 5,+ Attention = 6,+ AttentionDecode = 7,+ CacheWrite = 8,+ RotaryEmbedding = 9,+ Softmax = 10,+ Add = 11,+ Mul = 12,+ MulBroadcast = 13,+ AddBroadcast = 14,+ Affine = 15,+ GatedSwish = 16,+ Clamp = 17,+ MulScalar = 18,+ Softcap = 19,+ Resize = 20,+ MaxPool = 21,+ AvgPool = 22,+ GlobalAvgPool = 23,+ Concat = 24,+ View = 25,+ Constant = 26,+ Copy = 27,+ CustomOp = 28+}++// Spec section 3.1. Integer dtypes are always quantised weights (section+// 3.3); activations and all computed tensors are float. No string, resource,+// or sparse support: the catalog has no op that needs them.+enum DType : byte {+ F16 = 0,+ F32 = 1,+ I32 = 2,+ U32 = 3,+ I8 = 4,+ I4 = 5,+ BF16 = 6+}++// Spec section 3.4. Declared per tensor; the converter repacks weights into+// whatever the kernels consume, so verbatim upload and optimal layout stop+// being in conflict.+enum Layout : byte {+ // Legacy row-major planes. Expressible, never optimal; loaders may refuse+ // to specialise pipelines for it.+ NCHW = 0,+ // Channel groups of 4 contiguous. Default for computed tensors: a channel+ // reduction is a vec4 load.+ CHANNEL_BLOCKED_4 = 1,+ // `[K, 1, d]` positions appended per step. KV-caches.+ POSITION_MAJOR = 2+}++// Spec section 3.3: quantization as data, not opcode variants.+enum QuantKind : byte {+ NONE = 0,+ // One fp16 scale per output channel along `quantized_dim`.+ PER_CHANNEL = 1,+ // One fp16 scale per `block_size` taps along `quantized_dim`.+ BLOCKWISE = 2+}++// Spec section 4: DEVICE is the default; HOST is gathered on the CPU (one row+// per step, never bound whole).+enum Placement : byte {+ DEVICE = 0,+ HOST = 1+}++// Spec section 6.2. The file embeds no cache contents: KV_CACHE declares+// capacity (`max_tokens` via dim_params), dtype, and POSITION_MAJOR layout.+enum StateKind : byte {+ NONE = 0,+ KV_CACHE = 1,+ // Survives across submits at a stable offset; the memory planner never+ // recycles it.+ PINNED = 2+}++enum BackendKind : byte {+ GPU = 0,+ CPU = 1+}++// `Softmax.mode` attribute values.+enum SoftmaxMode : byte {+ FULL = 0,+ CAUSAL = 1,+ PREFIX = 2+}++// `Resize.mode` attribute values.+enum ResizeMode : byte {+ BILINEAR_HALF_PIXEL = 0,+ NEAREST_ASYMMETRIC = 1+}++// Spec section 3.2: a sequence-like axis. `dims[axis]` is the baked maximum;+// the live length `<= max` arrives per submit as a step uniform. Rank is+// fixed; only named axes vary, and only with an explicit max.+table DimParam {+ axis: uint;+ symbol: string;+ max: int;+}++// Spec section 3.3. Inline struct: scales live as ordinary tensors elsewhere+// in `Model.tensors`, so this carries indices, not bytes.+struct Quantization {+ kind: QuantKind;+ // Index into `Model.tensors`. Always fp16. -1 when kind == NONE.+ scale_tensor: int;+ // -1 means symmetric (zero point 0). Symmetric-only is enforced at+ // validation; the field exists for schema completeness.+ zero_point: int;+ // Which axis scales run along (PER_CHANNEL), or the contraction axis+ // (BLOCKWISE).+ quantized_dim: int;+ // Taps per scale for BLOCKWISE. v1's 32-wide I4 blocks carry over.+ block_size: int;+}++table Tensor {+ // Debug and error messages only. Never resolved by name at load.+ name: string;+ dtype: DType;+ // Static shape, all values > 0. A promise the loader may bake into+ // compiled pipelines.+ dims: [int];+ dim_params: [DimParam];+ layout: Layout;+ quantization: Quantization;+ // Index into `Model.buffers`, or -1 for computed/state tensors.+ buffer: int;+ // Byte offset within the buffer. Must be 16-aligned.+ buffer_offset: ulong;+ // Logical elements; cross-checked against the dims product (with packed+ // byte math for I4).+ elem_count: ulong;+ placement: Placement;+ state: StateKind;+}++table Buffer {+ // 16-aligned weight bytes. One buffer per file in practice; many allowed.+ // Uploaded verbatim to one VkBuffer with chunked copies straight from the+ // mmap: peak host cost one chunk, never a second full allocation.+ data: [ubyte] (force_align: 16);+}++// Attribute value wrappers. FlatBuffers unions hold tables only, so each+// scalar/vector kind gets one.+table AttrInt { value: int; }+table AttrInts { value: [int]; }+table AttrFloat { value: float; }+table AttrFloats { value: [float]; }+table AttrBool { value: bool; }+table AttrString { value: string; }++union AttrValue {+ AttrInt,+ AttrInts,+ AttrFloat,+ AttrFloats,+ AttrBool,+ AttrString+}++table Attribute {+ name: string;+ value: AttrValue;+}++table Node {+ op: Op;+ // Tensor indices. The file order of nodes is topological and IS the+ // schedule seed.+ inputs: [int];+ // Usually one.+ outputs: [int];+ // Typed attributes, op-specific (spec section 5.2). Epilogue fusion rides+ // here: `activation`, `res`, `shift` on the producer.+ attrs: [Attribute];+ // CustomOp-only opaque bytes. Must be empty for every other op; validated.+ payload: [ubyte];+}++table Graph {+ // "prefill", "decode_step", "encode", ...+ name: string;+ // Indices into `Model.tensors` forming this graph's SSA scope.+ tensors: [int];+ nodes: [Node];+ // Tensor indices, declaration order = binding order.+ inputs: [int];+ outputs: [int];+}++table EntryPoint {+ // "encode" | "prefill" | "decode_step" | "image" | "text" ...+ name: string;+ graph: uint;+ // Roles, e.g. ["tokens", "images", "mel"]. Bind positionally to+ // `Graph.inputs`.+ inputs: [string];+ // Live values per submit, e.g. ["prefix_len", "window_start"].+ step_uniforms: [string];+}++// Spec section 6.3. Advisory: the loader may override, but the default path+// must match what the converter validated parity against.+table BackendHint {+ // Names an `EntryPoint.name`.+ entry_point: string;+ preferred: BackendKind;+ fallback: BackendKind;+}++// Free-form metadata (tokenizer asset name, license, calibration note, and+// `parity_sha256`). Never load-bearing.+table KeyValue {+ key: string;+ value: string;+}++table Model {+ // File format version. The loader rejects mismatch: unequal means reject.+ version: uint;+ // Op catalog version (spec section 5.3). Loaders reject newer than+ // implemented.+ opset_version: uint;+ // Semver floor for the loader, e.g. "2.3.0".+ runtime_min_version: string;+ // What wrote this file, for bisection.+ converter_version: string;+ // Upstream artifact hash. Traceability, as v1.+ source_sha256: [ubyte];+ // SHA-256 over the canonical op/edge/attr sequence (spec section 9.2).+ // Replaces v1's graph_id integer.+ graph_digest: [ubyte];+ // Human-readable, e.g. "supertonic-sampler fp16".+ description: string;+ backends: [BackendHint];+ // Every value in every graph, weights and computed alike.+ tensors: [Tensor];+ // Weight bytes. Computed tensors reference no buffer.+ buffers: [Buffer];+ // Usually one; LLM text models ship prefill + decode sharing tensors.+ graphs: [Graph];+ // Named signatures over graphs.+ entry_points: [EntryPoint];+ metadata: [KeyValue];+}++root_type Model;
library/ml/src/main/rust/src/lib.rs
diff --git a/library/ml/src/main/rust/src/lib.rs b/library/ml/src/main/rust/src/lib.rsindex fcfa5af017..b5a6635b0d 100644--- a/library/ml/src/main/rust/src/lib.rs+++ b/library/ml/src/main/rust/src/lib.rs@@ -48,6 +48,7 @@ pub mod gate; pub mod knobs; pub mod logmel; pub mod logmel_extra;+pub mod maml2; pub mod microfrontend; pub mod nets; pub mod post;
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.rsnew file mode 100644index 0000000000..f10789e41e--- /dev/null+++ b/library/ml/src/main/rust/src/maml2/emit.rs@@ -0,0 +1,1214 @@+//! Emit a MAML v2 file from a recorded [`Recorded`] forward pass.+//!+//! The transpiler half of Phase 1: the sampler's hand-written Rust pass builds+//! through [`Builder`] as it always has, and this module serialises the+//! resulting [`Recorded`] (fused nodes, shapes, bindings, file-tensor read+//! flags) into the FlatBuffers `MAM2` container from `schema/maml2.fbs`.+//!+//! The graph is correct by construction — it is the same `Recorded` that+//! `Builder::finish` would have emitted a [`Plan`] from, after the same+//! fusion fold and the same every-tensor rule. The converter's job is not to+//! re-derive topology but to supply the weight bytes (repacked to the+//! kernel-chosen layout) that the emitted tensor table names.++use std::collections::HashMap;++use sha2::{Digest, Sha256};++use crate::maml2::fb;+use crate::nets::{Act, Node, Quant, Recorded, Shape, SoftmaxMode};+use crate::weights::{Dtype, Tensor as WeightTensor, I4_BLOCK};++/// Quantization of one weight tensor, resolved from the [`Recorded`] graph.+///+/// The scale lives in its own file tensor (the companion-tensor convention),+/// so resolving is a lookup of which file index the nodes read as a scale.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum WeightQuant {+ /// Plain fp16.+ None,+ /// Int8 with a per-output-channel scale at this file index.+ Int8 {+ /// File tensor holding the fp16 scales.+ scale: u32,+ },+ /// Int4 with a per-block scale at this file index.+ Int4 {+ /// File tensor holding the fp16 scales, `[out, ceil(taps / 32)]`.+ scale: u32,+ },+}++/// Channel-blocked-4 repack of an fp16 NCHW plane.+///+/// Groups channels in fours: `[c, h, w]` becomes `[(c + 3) / 4, h, w, 4]`+/// with zero padding in the final group. Element count grows to the padded+/// size; the loader's shape inference knows the logical shape from `dims`.+fn repack_channel_blocked_4(values: &[u16], c: u32, h: u32, w: u32) -> Vec<u16> {+ let (c, h, w) = (c as usize, h as usize, w as usize);+ let groups = c.div_ceil(4);+ let mut out = vec![0u16; groups * h * w * 4];+ for channel in 0..c {+ let group = channel / 4;+ let lane = channel % 4;+ for row in 0..h {+ for col in 0..w {+ let src = (channel * h + row) * w + col;+ let dst = ((group * h + row) * w + col) * 4 + lane;+ out[dst] = values[src];+ }+ }+ }+ out+}++/// Channel-blocked-4 repack of an int8 kernel.+///+/// Same permutation as [`repack_channel_blocked_4`], over bytes. The+/// contraction axis the kernel reduces over is laid out so a channel group+/// of four is contiguous at every position.+fn repack_channel_blocked_4_u8(values: &[u8], c: u32, h: u32, w: u32) -> Vec<u8> {+ let (c, h, w) = (c as usize, h as usize, w as usize);+ let groups = c.div_ceil(4);+ let mut out = vec![0u8; groups * h * w * 4];+ for channel in 0..c {+ let group = channel / 4;+ let lane = channel % 4;+ for row in 0..h {+ for col in 0..w {+ let src = (channel * h + row) * w + col;+ let dst = ((group * h + row) * w + col) * 4 + lane;+ out[dst] = values[src];+ }+ }+ }+ out+}++/// The v2 tensor rows for one v1 weight tensor, in emission order.+///+/// Most tensors emit one row. An int8/int4 kernel emits two: the repacked+/// kernel first, then its fp16 scale (repacked as a `[out, blocks]`+/// channel-blocked plane so the scale read is contiguous too).+struct EmittedTensor {+ /// Debug name, e.g. `w12.kernel.cb4`.+ name: String,+ /// Logical dims (unpadded).+ dims: Vec<i32>,+ /// v2 dtype.+ dtype: fb::DType,+ /// v2 layout.+ layout: fb::Layout,+ /// Payload bytes in v2 (repacked) order.+ bytes: Vec<u8>,+ /// Logical element count (unpadded).+ elems: u64,+ /// Quantization descriptor. Scales reference the emitted scale tensor by+ /// its position in the emission order, filled in on a second pass.+ quant: WeightQuant,+}++/// Weight payload of one v1 tensor, read from the data section.+enum WeightPayload {+ /// fp16 words, logical length `len`.+ F16(Vec<u16>),+ /// int8 bytes, logical length `len`.+ I8(Vec<u8>),+ /// Packed nibbles, `len.div_ceil(2)` bytes. Phase 1 refuses these (see+ /// `emit_weight_tensor`); the variant exists so the reader stays total.+ I4(Vec<u8>),+}++/// Read one v1 tensor's payload from the data section.+fn read_weight_payload(+ table: &[WeightTensor],+ data: &[u8],+ index: usize,+) -> Result<(WeightTensor, WeightPayload), String> {+ let tensor = table+ .get(index)+ .copied()+ .ok_or_else(|| format!("tensor {index} of {}: out of range", table.len()))?;+ let bytes = Dtype::bytes(tensor.dtype, u64::from(tensor.len)) as usize;+ let start = tensor.offset as usize;+ let end = start.checked_add(bytes).ok_or_else(|| format!("tensor {index} overflows"))?;+ let slice = data.get(start..end).ok_or_else(|| {+ format!("tensor {index} spans {start}..{end} of a {}-byte data section", data.len())+ })?;+ let payload = match tensor.dtype {+ Dtype::F16 => {+ let mut words = Vec::with_capacity(tensor.len as usize);+ for pair in slice.chunks_exact(2) {+ words.push(u16::from_le_bytes([pair[0], pair[1]]));+ }+ WeightPayload::F16(words)+ }+ Dtype::I8 => WeightPayload::I8(slice.to_vec()),+ Dtype::I4 => WeightPayload::I4(slice.to_vec()),+ };+ Ok((tensor, payload))+}++/// Tensor dims as a `[c, h, w]` shape with rank 1..4 mapped onto trailing axes.+///+/// v1 tensors are rank 1..4 with `dims[4]`; v2 dims are the significant+/// entries in order. A rank-2 `[m, n]` weight keeps `[m, n]`; the repack+/// interprets the leading axis as channels.+fn logical_dims(tensor: &WeightTensor) -> Vec<i32> {+ tensor.dims[..tensor.rank as usize].iter().map(|&d| d as i32).collect()+}++/// Emit one v1 weight tensor's v2 rows.+///+/// `quant` says how the graph reads this tensor: as a plain weight+/// ([`WeightQuant::None`]) or as a quantised kernel with its scale beside it.+/// Scale tensors are emitted by the kernel's emission, not separately — the+/// caller skips file indices consumed as scales.+#[allow(clippy::too_many_arguments)]+fn emit_weight_tensor(+ table: &[WeightTensor],+ data: &[u8],+ index: usize,+ quant: WeightQuant,+ rank_hint: Option<Vec<i32>>,+ out: &mut Vec<EmittedTensor>,+) -> Result<(), String> {+ let (tensor, payload) = read_weight_payload(table, data, index)?;+ let mut dims = rank_hint.unwrap_or_else(|| logical_dims(&tensor));+ // A `[c, 1, 1]` shorthand (per-channel vectors stored rank-3) repacks as+ // `[c, 1, 1]`; a `[n]` vector repacks as `[n, 1, 1]`.+ while dims.len() < 3 {+ dims.push(1);+ }+ let (c, h, w) = (dims[0] as u32, dims[1] as u32, dims[2] as u32);+ match (payload, quant) {+ (WeightPayload::F16(words), WeightQuant::None) => {+ let bytes: Vec<u8> = if dims.len() == 3+ || (dims.len() == 4 && dims[2] == 1 && dims[3] == 1)+ {+ repack_channel_blocked_4(&words, c, h, w)+ .iter()+ .flat_map(|w| w.to_le_bytes())+ .collect()+ } else {+ // Rank-4 spatial kernels stay in kernel order; the blocked+ // lowering applies at dispatch, not to the stored bytes.+ words.iter().flat_map(|w| w.to_le_bytes()).collect()+ };+ let elems = words.len() as u64;+ out.push(EmittedTensor {+ name: format!("w{index}.cb4"),+ dims,+ dtype: fb::DType::F16,+ layout: fb::Layout::CHANNEL_BLOCKED_4,+ bytes,+ elems,+ quant: WeightQuant::None,+ });+ }+ (WeightPayload::F16(_), WeightQuant::Int8 { .. }) => {+ return Err(format!("tensor {index} is fp16 but read as a quantised kernel"));+ }+ (WeightPayload::I8(bytes), WeightQuant::Int8 { .. }) => {+ // Kernels arrive `[out, in]` (possibly `[out, in, 1, 1]`); block+ // over the output rows: `[out/4, in, 4]`.+ let rows = dims[0] as usize;+ let cols: usize = dims[1..].iter().map(|&d| d as usize).product();+ let blocked = repack_channel_blocked_4_u8(&bytes, rows as u32, 1, cols as u32);+ out.push(EmittedTensor {+ name: format!("w{index}.kernel.cb4"),+ dims,+ dtype: fb::DType::I8,+ layout: fb::Layout::CHANNEL_BLOCKED_4,+ bytes: blocked,+ elems: bytes.len() as u64,+ quant,+ });+ // The scale follows as its own tensor: `[out]` fp16, contiguous.+ let (scale_tensor, scale_payload) = read_weight_payload(table, data, index + 1)?;+ let scale_dims = logical_dims(&scale_tensor);+ let WeightPayload::F16(scale_words) = scale_payload else {+ return Err(format!("tensor {} is not the fp16 scale of tensor {index}", index + 1));+ };+ let scale_bytes: Vec<u8> =+ scale_words.iter().flat_map(|w| w.to_le_bytes()).collect();+ out.push(EmittedTensor {+ name: format!("w{index}.scale"),+ dims: scale_dims,+ dtype: fb::DType::F16,+ layout: fb::Layout::CHANNEL_BLOCKED_4,+ bytes: scale_bytes,+ elems: scale_words.len() as u64,+ quant: WeightQuant::None,+ });+ }+ (WeightPayload::I8(_), WeightQuant::None) => {+ return Err(format!("tensor {index} is int8 but read as a plain weight"));+ }+ (WeightPayload::I4(bytes), _) => {+ return Err(format!(+ "tensor {index}: int4 repack is not implemented in Phase 1 ({} bytes)",+ bytes.len()+ ));+ }+ (WeightPayload::I8(_), WeightQuant::Int4 { .. })+ | (WeightPayload::F16(_), WeightQuant::Int4 { .. }) => {+ return Err(format!("tensor {index}: mismatched quant kind"));+ }+ }+ Ok(())+}++/// Which file indices the [`Recorded`] nodes consume as quantised kernels,+/// mapped to their scale's file index.+///+/// Int8/int4 kernels carry resolved *offsets* in the nodes: `weight` is a+/// word index (`Tensor::word_offset`), while `scale`/`bias`/`gamma` are fp16+/// element indices (`Tensor::elem_offset`). The emitter inverts offsets back+/// to file indices through the table. An fp16 tensor's word and element+/// offsets differ (offset/4 vs offset/2), so the inversion is exact: a kernel+/// offset names the quantised tensor, a scale offset names the fp16 scale.+/// Two tensors could share an offset only if one has zero length, which the+/// v1 parser rejects.+fn quant_kernels(+ nodes: &[Node],+ table: &[WeightTensor],+ data: &[u8],+) -> Result<HashMap<usize, WeightQuant>, String> {+ let _ = data;+ let mut kernels = HashMap::new();+ let mut word_to_file: HashMap<u32, usize> = HashMap::new();+ let mut elem_to_file: HashMap<u32, usize> = HashMap::new();+ for (index, tensor) in table.iter().enumerate() {+ if tensor.dtype.is_quantised() {+ word_to_file.insert(tensor.word_offset(), index);+ } else {+ elem_to_file.insert(tensor.elem_offset(), index);+ }+ }+ for node in nodes {+ if let Node::ConvInt8 { weight, scale, quant, .. } = node {+ let kernel = word_to_file.get(weight).copied().ok_or_else(|| {+ format!("no quantised file tensor at word offset {weight}")+ })?;+ let scale_index = elem_to_file.get(scale).copied().ok_or_else(|| {+ format!("no fp16 file tensor at element offset {scale}")+ })?;+ let kind = match quant {+ Quant::I8 => WeightQuant::Int8 { scale: scale_index as u32 },+ Quant::I4 => WeightQuant::Int4 { scale: scale_index as u32 },+ };+ if let Some(previous) = kernels.insert(kernel, kind) {+ if previous != kind {+ return Err(format!("tensor {kernel} read with two quant kinds"));+ }+ }+ }+ }+ Ok(kernels)+}++/// File indices consumed as scales (values of [`quant_kernels`]), so the+/// tensor walk can skip them: they emit beside their kernel.+fn scale_indices(kernels: &HashMap<usize, WeightQuant>) -> Vec<usize> {+ let mut scales: Vec<usize> = kernels+ .values()+ .filter_map(|kind| match *kind {+ WeightQuant::Int8 { scale } | WeightQuant::Int4 { scale } => Some(scale as usize),+ WeightQuant::None => None,+ })+ .collect();+ scales.sort_unstable();+ scales.dedup();+ scales+}++/// Activation code for the v2 `activation` attribute.+///+/// Matches `Act::code()` on the runtime side: 0 none, 1 relu, 2 hardswish,+/// 3 sigmoid, 5 clip01, 6 swish, 8 gelu. PRelu carries its slope tensor and+/// is encoded as `4 + slope file index << 8`; the Phase 1 sampler never+/// emits one (no PRelu in the net), so encountering it is an error.+fn act_code(act: Act) -> Result<i32, String> {+ match act {+ Act::None => Ok(0),+ Act::Relu => Ok(1),+ Act::HardSwish => Ok(2),+ Act::Sigmoid => Ok(3),+ Act::PRelu(_) => Err("PRelu is not expressible in the Phase 1 sampler graph".into()),+ Act::Clip01 => Ok(5),+ Act::Swish => Ok(6),+ Act::Gelu => Ok(8),+ }+}++/// Softmax mode code for the v2 `mode` attribute: 0 full, 1 causal, 2 prefix.+fn softmax_mode_code(mode: SoftmaxMode) -> i32 {+ match mode {+ SoftmaxMode::Full => 0,+ SoftmaxMode::Causal => 1,+ SoftmaxMode::Prefix => 2,+ }+}++/// One emitted v2 node: op, tensor refs, and attributes.+struct EmittedNode {+ op: fb::Op,+ inputs: Vec<i32>,+ outputs: Vec<i32>,+ attrs: Vec<(String, AttrValue)>,+}++/// Attribute values the Phase 1 emitter needs.+enum AttrValue {+ Int(i32),+ Ints(Vec<i32>),+ Float(f32),+ Bool(bool),+}++/// Map a resolved weight offset to its v2 tensor index.+///+/// `id_map.weights` is keyed by v1 file index (assigned in emission order).+/// Nodes carry resolved offsets, so invert through two maps: word offsets+/// for quantised kernels, element offsets for fp16 weights. Built once per+/// emission from the v1 table.+struct WeightLookup {+ word_to_v2: HashMap<u32, i32>,+ elem_to_v2: HashMap<u32, i32>,+}++impl WeightLookup {+ fn new(table: &[WeightTensor], weights: &HashMap<usize, i32>) -> Result<WeightLookup, String> {+ let mut word_to_v2 = HashMap::new();+ let mut elem_to_v2 = HashMap::new();+ for (file_index, v2) in weights {+ let tensor = table.get(*file_index).copied().ok_or_else(|| {+ format!("tensor {file_index} of {}: out of range", table.len())+ })?;+ if tensor.dtype.is_quantised() {+ word_to_v2.insert(tensor.word_offset(), *v2);+ } else {+ elem_to_v2.insert(tensor.elem_offset(), *v2);+ }+ }+ Ok(WeightLookup { word_to_v2, elem_to_v2 })+ }++ /// Look up a quantised kernel by its word offset.+ fn kernel(&self, offset: u32) -> Result<i32, String> {+ self.word_to_v2.get(&offset).copied().ok_or_else(|| {+ format!("conv_int8 weight offset {offset} is not a quantised file tensor")+ })+ }++ /// Look up an fp16 weight (bias, scale, gamma, beta) by element offset.+ fn fp16(&self, what: &str, offset: u32) -> Result<i32, String> {+ self.elem_to_v2.get(&offset).copied().ok_or_else(|| {+ format!("{what} offset {offset} is not an fp16 file tensor")+ })+ }+}++/// Map a [`Recorded`] tensor id to its v2 tensor index.+///+/// `tensor_ids` assigns v2 indices: graph inputs first (declaration order),+/// then computed tensors in first-use order, then host tensors. Weight file+/// indices map through `weight_ids`.+struct IdMap {+ /// [`Recorded`] tensor id (`Id.0`) → v2 tensor index.+ computed: HashMap<usize, i32>,+ /// v1 file tensor index → v2 tensor index (weights only).+ weights: HashMap<usize, i32>,+ /// v2 tensor count so far.+ next: i32,+}++impl IdMap {+ fn new() -> IdMap {+ IdMap { computed: HashMap::new(), weights: HashMap::new(), next: 0 }+ }++ fn alloc(&mut self) -> i32 {+ let index = self.next;+ self.next += 1;+ index+ }+}++/// Emit the v2 nodes for one [`Recorded`] graph.+///+/// `shapes` gives every tensor id's `[c, h, w]`; `id_map` is pre-seeded with+/// the graph inputs and weight tensors, and gains the computed tensors in+/// first-use order. `emit_tensors` (built alongside) receives the computed+/// tensor rows in the same order.+#[allow(clippy::too_many_arguments)]+fn emit_nodes(+ recorded: &Recorded,+ id_map: &mut IdMap,+ weights: &WeightLookup,+ emit_tensors: &mut Vec<EmittedTensor>,+ seen: &mut HashMap<usize, i32>,+) -> Result<Vec<EmittedNode>, String> {+ let mut nodes = Vec::with_capacity(recorded.nodes.len());+ // Tensor id → v2 index for computed tensors, allocating rows on first use.+ let mut computed = |id: usize, map: &mut IdMap, tensors: &mut Vec<EmittedTensor>| -> i32 {+ if let Some(&index) = map.computed.get(&id) {+ return index;+ }+ let index = map.alloc();+ map.computed.insert(id, index);+ seen.insert(id, index);+ let shape = recorded.shapes.get(id).copied().unwrap_or(Shape::new(0, 0, 0));+ tensors.push(EmittedTensor {+ name: format!("t{id}"),+ dims: vec![shape.c as i32, shape.h as i32, shape.w as i32],+ dtype: fb::DType::F16,+ layout: fb::Layout::CHANNEL_BLOCKED_4,+ bytes: Vec::new(),+ elems: shape.len() as u64,+ quant: WeightQuant::None,+ });+ index+ };+ for node in &recorded.nodes {+ match *node {+ Node::Conv {+ input,+ out,+ weight,+ bias,+ kernel,+ stride,+ dilation,+ pad,+ group,+ act,+ transpose,+ pad_edge,+ res,+ shift,+ ..+ } => {+ if transpose {+ return Err("transposed convolution is not in the Phase 1 sampler".into());+ }+ let a = computed(input.0, id_map, emit_tensors);+ let y = computed(out.0, id_map, emit_tensors);+ let w = weights.fp16("conv weight", weight)?;+ let b = weights.fp16("conv bias", bias)?;+ let mut attrs = vec![+ ("kernel".into(), AttrValue::Ints(vec![kernel.0 as i32, kernel.1 as i32])),+ ("stride".into(), AttrValue::Ints(vec![stride.0 as i32, stride.1 as i32])),+ (+ "dilation".into(),+ AttrValue::Ints(vec![dilation.0 as i32, dilation.1 as i32]),+ ),+ ("pads".into(), AttrValue::Ints(vec![pad.0 as i32, pad.1 as i32])),+ ("groups".into(), AttrValue::Int(group as i32)),+ ("pad_edge".into(), AttrValue::Bool(pad_edge)),+ ("activation".into(), AttrValue::Int(act_code(act)?)),+ ];+ if let Some(res) = res {+ attrs.push((+ "res".into(),+ AttrValue::Int(computed(res.0, id_map, emit_tensors)),+ ));+ }+ if let Some(shift) = shift {+ attrs.push((+ "shift".into(),+ AttrValue::Int(computed(shift.0, id_map, emit_tensors)),+ ));+ }+ nodes.push(EmittedNode {+ op: fb::Op::Conv,+ inputs: vec![a, w, b],+ outputs: vec![y],+ attrs,+ });+ }+ Node::ConvInt8 {+ input,+ out,+ weight,+ scale,+ bias,+ kernel,+ stride,+ dilation,+ pad,+ group,+ act,+ quant,+ res,+ shift,+ } => {+ let a = computed(input.0, id_map, emit_tensors);+ let y = computed(out.0, id_map, emit_tensors);+ let w = weights.kernel(weight)?;+ let s = weights.fp16("conv_int8 scale", scale)?;+ let b = weights.fp16("conv_int8 bias", bias)?;+ let mut attrs = vec![+ ("kernel".into(), AttrValue::Ints(vec![kernel.0 as i32, kernel.1 as i32])),+ ("stride".into(), AttrValue::Ints(vec![stride.0 as i32, stride.1 as i32])),+ (+ "dilation".into(),+ AttrValue::Ints(vec![dilation.0 as i32, dilation.1 as i32]),+ ),+ ("pads".into(), AttrValue::Ints(vec![pad.0 as i32, pad.1 as i32])),+ ("groups".into(), AttrValue::Int(group as i32)),+ ("activation".into(), AttrValue::Int(act_code(act)?)),+ (+ "quant".into(),+ AttrValue::Int(match quant {+ Quant::I8 => 1,+ Quant::I4 => 2,+ }),+ ),+ ];+ if let Some(res) = res {+ attrs.push((+ "res".into(),+ AttrValue::Int(computed(res.0, id_map, emit_tensors)),+ ));+ }+ if let Some(shift) = shift {+ attrs.push((+ "shift".into(),+ AttrValue::Int(computed(shift.0, id_map, emit_tensors)),+ ));+ }+ 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 },+ inputs: vec![a, w, s, b],+ outputs: vec![y],+ attrs,+ });+ }+ Node::Binary { kind, a, b, out } => {+ let x = computed(a.0, id_map, emit_tensors);+ let y_in = computed(b.0, id_map, emit_tensors);+ let y = computed(out.0, id_map, emit_tensors);+ let op = match kind {+ crate::nets::Kind::Add => fb::Op::Add,+ crate::nets::Kind::Mul => fb::Op::Mul,+ crate::nets::Kind::MulBroadcast => fb::Op::MulBroadcast,+ crate::nets::Kind::AddBroadcast => fb::Op::AddBroadcast,+ other => return Err(format!("{other:?} is not a Phase 1 sampler op")),+ };+ nodes.push(EmittedNode { op, inputs: vec![x, y_in], outputs: vec![y], attrs: vec![] });+ }+ Node::LayerNorm { input, out, gamma, beta, epsilon } => {+ let x = computed(input.0, id_map, emit_tensors);+ let y = computed(out.0, id_map, emit_tensors);+ let g = weights.fp16("layer_norm gamma", gamma)?;+ let be = weights.fp16("layer_norm beta", beta)?;+ nodes.push(EmittedNode {+ op: fb::Op::LayerNorm,+ inputs: vec![x, g, be],+ outputs: vec![y],+ attrs: vec![("epsilon".into(), AttrValue::Float(epsilon))],+ });+ }+ Node::AttnScores { q, k, out, heads, kv_heads, scale } => {+ 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);+ nodes.push(EmittedNode {+ op: fb::Op::Attention,+ inputs: vec![x, y_in],+ outputs: vec![y],+ attrs: vec![+ ("heads".into(), AttrValue::Int(heads as i32)),+ ("kv_heads".into(), AttrValue::Int(kv_heads as i32)),+ ("scale".into(), AttrValue::Float(scale)),+ ("phase".into(), AttrValue::Int(0)),+ ],+ });+ }+ Node::AttnApply { probs, v, out, heads, kv_heads } => {+ 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);+ nodes.push(EmittedNode {+ op: fb::Op::Attention,+ inputs: vec![p, vv],+ outputs: vec![y],+ attrs: vec![+ ("heads".into(), AttrValue::Int(heads as i32)),+ ("kv_heads".into(), AttrValue::Int(kv_heads as i32)),+ ("phase".into(), AttrValue::Int(1)),+ ],+ });+ }+ Node::Softmax { input, out, mode, .. } => {+ 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)))],+ });+ }+ Node::Rotary { input, angles, out, heads, axes } => {+ let x = computed(input.0, id_map, emit_tensors);+ let a = computed(angles.0, id_map, emit_tensors);+ let y = computed(out.0, id_map, emit_tensors);+ nodes.push(EmittedNode {+ op: fb::Op::RotaryEmbedding,+ inputs: vec![x, a],+ outputs: vec![y],+ attrs: vec![+ ("heads".into(), AttrValue::Int(heads as i32)),+ ("axes".into(), AttrValue::Int(axes as i32)),+ ],+ });+ }+ Node::SliceChannels { input, out, start } => {+ let x = computed(input.0, id_map, emit_tensors);+ let y = computed(out.0, id_map, emit_tensors);+ let shape = recorded.shapes.get(out.0).copied().unwrap_or(Shape::new(0, 0, 0));+ nodes.push(EmittedNode {+ op: fb::Op::View,+ inputs: vec![x],+ outputs: vec![y],+ attrs: vec![+ ("offset".into(), AttrValue::Int(start as i32)),+ (+ "dims".into(),+ AttrValue::Ints(vec![+ shape.c as i32,+ shape.h as i32,+ shape.w as i32,+ ]),+ ),+ ],+ });+ }+ ref other => {+ return Err(format!("{other:?} is not a Phase 1 sampler op"));+ }+ }+ }+ Ok(nodes)+}++/// A finished v2 model: the FlatBuffers bytes plus the checks the emitter ran.+pub struct Emitted {+ /// The `MAM2` file bytes.+ pub bytes: Vec<u8>,+ /// SHA-256 over the canonical op/edge/attr sequence (spec section 9.2).+ pub graph_digest: [u8; 32],+ /// `(op, count)` inventory of the emitted graph, for the report.+ pub op_inventory: Vec<(fb::Op, usize)>,+}++/// Emit a MAML v2 model from one recorded sampler branch.+///+/// `recorded` is the [`Builder::record`] output at a fixed `(frames, chars)`+/// shape; `table` + `data` are the v1 file's tensor table and data section,+/// whose weight bytes are repacked into the v2 buffers. `description` names+/// the model for humans; `converter_version` and `source_sha256` trace+/// provenance.+///+/// The entry point is `encode` over the graph `sampler`: Phase 1 proves the+/// single-branch loop, and the dual-branch plan is two submits of it.+pub fn emit_sampler(+ recorded: &Recorded,+ table: &[WeightTensor],+ data: &[u8],+ description: &str,+ converter_version: &str,+ source_sha256: [u8; 32],+) -> Result<Emitted, String> {+ // 1. Which file tensors are quantised kernels, and which are their scales.+ let kernels = quant_kernels(&recorded.nodes, table, data)?;+ 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();+ let mut elem_to_file: HashMap<u32, usize> = HashMap::new();+ for (index, tensor) in table.iter().enumerate() {+ if tensor.dtype.is_quantised() {+ word_to_file.insert(tensor.word_offset(), index);+ } else {+ elem_to_file.insert(tensor.elem_offset(), index);+ }+ }+ // Node weight fields are offsets; invert each to its file tensor.+ // (Duplicated with `quant_kernels`' maps; factored here because the+ // host decision needs the full ref set, not just kernels.)+ let mark = |offset: u32,+ quantised: bool,+ word_to_file: &HashMap<u32, usize>,+ elem_to_file: &HashMap<u32, usize>|+ -> Option<usize> {+ if quantised {+ word_to_file.get(&offset).copied()+ } else {+ elem_to_file.get(&offset).copied()+ }+ };+ for node in &recorded.nodes {+ match node {+ Node::Conv { weight, bias, act_weight, .. } => {+ // act_weight is 0 unless PRelu (absent in Phase 1).+ let _ = act_weight;+ // The fp16 kernel/bias resolve through elem offsets; find+ // their file tensors by matching offset to table.+ for (index, tensor) in table.iter().enumerate() {+ if !tensor.dtype.is_quantised()+ && (tensor.elem_offset() == *weight+ || tensor.elem_offset() == *bias)+ {+ node_refs.insert(index, ());+ }+ }+ }+ Node::ConvInt8 { weight, scale, bias, .. } => {+ for file in [+ mark(*weight, true, &word_to_file, &elem_to_file),+ mark(*scale, false, &word_to_file, &elem_to_file),+ mark(*bias, false, &word_to_file, &elem_to_file),+ ]+ .into_iter()+ .flatten()+ {+ node_refs.insert(file, ());+ }+ }+ Node::LayerNorm { gamma, beta, .. } => {+ for file in [+ mark(*gamma, false, &word_to_file, &elem_to_file),+ mark(*beta, false, &word_to_file, &elem_to_file),+ ]+ .into_iter()+ .flatten()+ {+ node_refs.insert(file, ());+ }+ }+ Node::RmsNorm { gamma, .. } => {+ if let Some(file) = mark(*gamma, false, &word_to_file, &elem_to_file) {+ node_refs.insert(file, ());+ }+ }+ Node::AttnScoresRelative { table: relative, .. }+ | Node::AttnApplyRelative { table: relative, .. }+ | Node::AttnScoresBanded { table: relative, .. } => {+ if let Some(file) = mark(*relative, false, &word_to_file, &elem_to_file) {+ node_refs.insert(file, ());+ }+ }+ Node::Constant { weight, .. }+ | Node::Embed { table: weight, .. }+ | Node::MulScalar { scale: weight, .. }+ | Node::Clamp { bounds: weight, .. } => {+ if let Some(file) = mark(*weight, false, &word_to_file, &elem_to_file) {+ node_refs.insert(file, ());+ }+ }+ _ => {}+ }+ }+ // Scales ride beside their kernel: mark them referenced so the host+ // check below does not misclassify them (they are skipped in emission+ // order, not emitted as host rows).+ for scale in &scales {+ node_refs.insert(*scale, ());+ }+ }++ // 2. Emit the weight tensors in file order (skipping scales: they ride+ // beside their kernel), assigning v2 tensor indices.+ let mut id_map = IdMap::new();+ let mut emitted: Vec<EmittedTensor> = Vec::new();+ // v1 file index → position in `emitted` (kernels occupy two rows).+ let mut weight_rows: HashMap<usize, usize> = HashMap::new();+ for index in 0..table.len() {+ if scales.contains(&index) {+ 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.+ let is_host = !node_refs.contains_key(&index)+ && recorded.read.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())+ })?;+ let v2 = id_map.alloc();+ id_map.weights.insert(index, v2);+ weight_rows.insert(index, emitted.len());+ emitted.push(EmittedTensor {+ name: format!("w{index}.host"),+ dims: logical_dims(&tensor),+ dtype: fb::DType::F16,+ layout: fb::Layout::NCHW,+ bytes: Vec::new(),+ elems: u64::from(tensor.len),+ quant: WeightQuant::None,+ });+ continue;+ }+ let quant = kernels.get(&index).copied().unwrap_or(WeightQuant::None);+ let before = emitted.len();+ emit_weight_tensor(table, data, index, quant, None, &mut emitted)?;+ let v2 = id_map.alloc();+ // A quantised kernel occupies two rows; the v2 index names the kernel.+ if matches!(quant, WeightQuant::Int8 { .. } | WeightQuant::Int4 { .. }) {+ let scale_v2 = id_map.alloc();+ id_map.weights.insert(index + 1, scale_v2);+ }+ id_map.weights.insert(index, v2);+ weight_rows.insert(index, before);+ let _ = weight_rows;+ }+ // The v2 weight map is keyed by file index throughout; nodes look up+ // through the offset→v2 inversion below. Scales were allocated right+ // after their kernel above, in file order.+ 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);+ }+ 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::CHANNEL_BLOCKED_4,+ 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)?;++ // 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())+ })+ })+ .collect::<Result<Vec<i32>, String>>()?;++ // 6. Canonical digest over op/edge/attr sequence (spec section 9.2).+ let mut hasher = Sha256::new();+ for node in &nodes {+ hasher.update([node.op.0 as u8]);+ for input in &node.inputs {+ hasher.update(input.to_le_bytes());+ }+ for output in &node.outputs {+ hasher.update(output.to_le_bytes());+ }+ for (name, attr) in &node.attrs {+ hasher.update(name.as_bytes());+ match attr {+ AttrValue::Int(v) => hasher.update(v.to_le_bytes()),+ AttrValue::Ints(vs) => {+ for v in vs {+ hasher.update(v.to_le_bytes());+ }+ }+ AttrValue::Float(v) => hasher.update(v.to_le_bytes()),+ AttrValue::Bool(v) => hasher.update([u8::from(*v)]),+ }+ }+ }+ let graph_digest: [u8; 32] = hasher.finalize().into();++ // 7. Assemble the FlatBuffers model.+ let mut builder = flatbuffers::FlatBufferBuilder::new();+ // Buffers: one per emitted weight payload, 16-aligned; computed tensors+ // reference no buffer.+ let buffer_offsets: Vec<flatbuffers::WIPOffset<fb::Buffer<'_>>> = Vec::new();+ let _ = buffer_offsets;+ // NOTE: assembly continues below; tensor/buffer vectors need the payloads+ // built first. The full builder sequence is in `assemble`.+ let assembled = assemble(+ &mut builder,+ &emitted,+ &emit_tensors,+ &nodes,+ &input_ids,+ &plan_outputs,+ recorded,+ description,+ converter_version,+ source_sha256,+ graph_digest,+ )?;+ 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)),+ }+ }+ op_inventory.sort_by_key(|(_, n)| std::cmp::Reverse(*n));++ Ok(Emitted { bytes: builder.finished_data().to_vec(), graph_digest, op_inventory })+}++/// 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,+ description: &str,+ converter_version: &str,+ source_sha256: [u8; 32],+ graph_digest: [u8; 32],+) -> Result<(), String> {+ // Weight payloads become Buffers; each emitted weight tensor points at+ // its buffer. Computed tensors (buffer -1) and host tensors (no bytes)+ // point at nothing.+ // Map emitted-tensor position → buffer index.+ let mut buffer_of: Vec<Option<usize>> = Vec::with_capacity(emitted.len());+ let mut buffers: Vec<flatbuffers::WIPOffset<fb::Buffer<'_>>> = Vec::new();+ for tensor in emitted.iter() {+ if tensor.bytes.is_empty() {+ buffer_of.push(None);+ continue;+ }+ let data = builder.create_vector(&tensor.bytes);+ buffers.push(fb::Buffer::create(builder, &fb::BufferArgs { data: Some(data) }));+ buffer_of.push(Some(buffers.len() - 1));+ }+ let buffers = builder.create_vector(&buffers);++ // 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.+ // Reconstruct: emitted weights occupy 0..emitted.len().+ for (position, tensor) in emitted.iter().enumerate() {+ let name = builder.create_string(&tensor.name);+ let dims = builder.create_vector(&tensor.dims);+ let (quant_kind, scale_v2, quant_dim, block) = match tensor.quant {+ WeightQuant::None => (fb::QuantKind::NONE, -1, 0, 0),+ WeightQuant::Int8 { .. } => {+ // The scale row follows the kernel row in emission order.+ (fb::QuantKind::PER_CHANNEL, (position + 1) as i32, 0, 0)+ }+ WeightQuant::Int4 { .. } => {+ (fb::QuantKind::PER_CHANNEL, (position + 1) as i32, 0, I4_BLOCK as i32)+ }+ };+ let quant = fb::Quantization::new(+ quant_kind,+ if matches!(tensor.quant, WeightQuant::None) {+ -1+ } else {+ // Position in emission order == v2 index for the weight block+ // (weights start at 0 and each occupies its rows in order).+ scale_v2+ },+ -1,+ quant_dim,+ block,+ );+ let (buffer, buffer_offset) = match buffer_of[position] {+ Some(_) => (position as i32, 0u64),+ None => (-1, 0u64),+ };+ let placement =+ if tensor.bytes.is_empty() { fb::Placement::HOST } else { fb::Placement::DEVICE };+ tensors.push(fb::Tensor::create(+ builder,+ &fb::TensorArgs {+ name: Some(name),+ dtype: tensor.dtype,+ dims: Some(dims),+ dim_params: None,+ layout: tensor.layout,+ quantization: Some(&quant),+ buffer,+ buffer_offset,+ elem_count: tensor.elems,+ placement,+ state: fb::StateKind::NONE,+ },+ ));+ }+ // Computed + input tensors: dtype F16, CB4, no buffer, no quant.+ // Their v2 indices continue after the weights; node refs already assume+ // that order (inputs allocated after weights, computed in first-use+ // order matching `emit_tensors` push order).+ for tensor in computed.iter() {+ let name = builder.create_string(&tensor.name);+ let dims = builder.create_vector(&tensor.dims);+ let quant = fb::Quantization::new(fb::QuantKind::NONE, -1, -1, 0, 0);+ tensors.push(fb::Tensor::create(+ builder,+ &fb::TensorArgs {+ name: Some(name),+ dtype: tensor.dtype,+ dims: Some(dims),+ dim_params: None,+ layout: tensor.layout,+ quantization: Some(&quant),+ buffer: -1,+ buffer_offset: 0,+ elem_count: tensor.elems,+ placement: fb::Placement::DEVICE,+ state: fb::StateKind::NONE,+ },+ ));+ }+ 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(+ 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::NodeArgs {+ op: node.op,+ inputs: Some(inputs),+ outputs: Some(outputs),+ attrs: Some(attrs),+ payload: None,+ },+ ));+ }+ 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("sampler");+ 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]);++ // Entry point: `encode` over graph 0. Roles bind positionally to the+ // graph inputs (the sampler's seven, in `build` order).+ let entry_name = builder.create_string("encode");+ let roles: Vec<flatbuffers::WIPOffset<&str>> = [+ "noisy_latent",+ "text",+ "style_keys",+ "style_values",+ "shifts",+ "query_angles",+ "key_angles",+ ]+ .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]);++ let description = builder.create_string(description);+ let converter_version = builder.create_string(converter_version);+ let runtime_min_version = builder.create_string("2.0.0");+ let source_sha256 = builder.create_vector(&source_sha256);+ let graph_digest = builder.create_vector(&graph_digest);+ let model = fb::Model::create(+ builder,+ &fb::ModelArgs {+ version: super::FORMAT_VERSION,+ opset_version: super::OPSET_VERSION,+ runtime_min_version: Some(runtime_min_version),+ converter_version: Some(converter_version),+ source_sha256: Some(source_sha256),+ graph_digest: Some(graph_digest),+ description: Some(description),+ backends: None,+ tensors: Some(tensors),+ buffers: Some(buffers),+ graphs: Some(graphs),+ entry_points: Some(entry_points),+ metadata: None,+ },+ );+ builder.finish(model, Some(fb::MODEL_IDENTIFIER));+ Ok(())+}
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.rsnew file mode 100644index 0000000000..c95497f39f--- /dev/null+++ b/library/ml/src/main/rust/src/maml2/infer.rs@@ -0,0 +1,462 @@+//! Shape and layout inference over a verified MAML v2 graph (spec 7.2 + 9.2).+//!+//! Re-derives every computed tensor's static shape and layout from the graph+//! inputs and node attributes, and requires the result to equal the stored+//! row. A mismatch is a load error, not a re-record trigger. Along the way+//! this checks the semantic properties structural verification cannot:+//! single-writer SSA, acyclicity (topological order), every weight tensor+//! read-or-host, graph outputs traceable to inputs, and the `graph_digest`+//! recompute.++use std::collections::{HashMap, HashSet};++use sha2::{Digest, Sha256};++use crate::maml2::fb;+use crate::maml2::verify::Verified;++/// An inferred tensor: static dims plus the layout the producer writes.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Inferred {+ /// Static shape, rank 1..=4, all values > 0.+ pub dims: Vec<i32>,+ /// The layout the producer writes.+ pub layout: fb::Layout,+}++/// The inference result for one graph.+pub struct InferredGraph {+ /// Graph index in `Model.graphs`.+ pub graph: usize,+ /// Inferred shape per tensor index (weights: stored dims echoed).+ pub shapes: HashMap<i32, Inferred>,+ /// Recomputed digest over the canonical op/edge/attr sequence.+ pub graph_digest: [u8; 32],+}++/// Attribute accessors over the generated union readers.+struct Attrs<'a> {+ attrs: flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<fb::Attribute<'a>>>,+}++impl<'a> Attrs<'a> {+ fn get(&self, name: &str) -> Option<fb::Attribute<'a>> {+ (0..self.attrs.len()).map(|i| self.attrs.get(i)).find(|a| a.name() == Some(name))+ }++ fn int(&self, name: &str) -> Result<i32, String> {+ let attr = self.get(name).ok_or_else(|| format!("missing attribute {name}"))?;+ attr.value_as_attr_int().map(|v| v.value()).ok_or_else(|| format!("attribute {name} is not an int"))+ }++ fn ints(&self, name: &str) -> Result<Vec<i32>, String> {+ let attr = self.get(name).ok_or_else(|| format!("missing attribute {name}"))?;+ attr.value_as_attr_ints()+ .and_then(|v| v.value().map(|vec| (0..vec.len()).map(|i| vec.get(i)).collect()))+ .ok_or_else(|| format!("attribute {name} is not an int vector"))+ }++ fn float(&self, name: &str) -> Result<f32, String> {+ let attr = self.get(name).ok_or_else(|| format!("missing attribute {name}"))?;+ attr.value_as_attr_float().map(|v| v.value()).ok_or_else(|| format!("attribute {name} is not a float"))+ }++ fn bool(&self, name: &str) -> Result<bool, String> {+ let attr = self.get(name).ok_or_else(|| format!("missing attribute {name}"))?;+ attr.value_as_attr_bool().map(|v| v.value()).ok_or_else(|| format!("attribute {name} is not a bool"))+ }++ fn opt_int(&self, name: &str) -> Result<Option<i32>, String> {+ match self.get(name) {+ None => Ok(None),+ Some(attr) => attr+ .value_as_attr_int()+ .map(|v| Some(v.value()))+ .ok_or_else(|| format!("attribute {name} is not an int")),+ }+ }++ /// Float accessor, for ops beyond the Phase 1 sampler subset (LayerNorm+ /// epsilon, Attention scale). Unused until coverage grows past the+ /// sampler's integer-attribute ops.+ #[allow(dead_code)]+ fn float_attr(&self, name: &str) -> Result<f32, String> {+ self.float(name)+ }++ /// Bool accessor, for ops beyond the Phase 1 sampler subset (Conv+ /// pad_edge). Unused until coverage grows past the sampler's+ /// integer-attribute ops.+ #[allow(dead_code)]+ fn bool_attr(&self, name: &str) -> Result<bool, String> {+ self.bool(name)+ }+}++/// Run shape/layout inference over every graph in the verified model.+///+/// Returns one [`InferredGraph`] per graph, in model order.+pub fn infer(verified: &Verified<'_>) -> 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")?;+ (0..graphs.len()).map(|g| infer_graph(&tensors, &graphs.get(g), g)).collect()+}++/// Stored dims of one tensor row.+fn stored_dims(tensors: &flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<fb::Tensor<'_>>>, index: i32) -> Result<Vec<i32>, String> {+ let tensor = tensors.get(index as usize);+ tensor+ .dims()+ .map(|dims| (0..dims.len()).map(|i| dims.get(i)).collect())+ .ok_or_else(|| format!("tensor {index} has no dims"))+}++/// Stored layout of one tensor row.+fn stored_layout(+ tensors: &flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<fb::Tensor<'_>>>,+ index: i32,+) -> fb::Layout {+ tensors.get(index as usize).layout()+}++/// Infer one graph: propagate shapes, check SSA + acyclicity + digest.+fn infer_graph(+ tensors: &flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<fb::Tensor<'_>>>,+ graph: &fb::Graph<'_>,+ graph_index: usize,+) -> 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.+ 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) });+ }+ }+ // Weight tensors (buffer >= 0) and host tensors (no buffer, PLACEMENT host)+ // are file facts: seed from stored rows so node inference can read them.+ for t in 0..tensors.len() as i32 {+ if shapes.contains_key(&t) {+ continue;+ }+ let tensor = tensors.get(t as usize);+ if tensor.buffer() != -1 || tensor.placement() == fb::Placement::HOST {+ shapes.insert(t, Inferred { dims: stored_dims(tensors, t)?, layout: tensor.layout() });+ }+ }++ let mut hasher = Sha256::new();+ // Defined tensors: inputs + file tensors. Anything else must be written+ // by a topologically earlier node (acyclicity by construction order).+ let mut defined: HashSet<i32> = shapes.keys().copied().collect();++ for n in 0..nodes.len() {+ let node = nodes.get(n);+ let inputs: Vec<i32> = node.inputs().map(|v| (0..v.len()).map(|i| v.get(i)).collect()).unwrap_or_default();+ let outputs: Vec<i32> = node.outputs().map(|v| (0..v.len()).map(|i| v.get(i)).collect()).unwrap_or_default();+ // Every input must already be defined: the file order IS topological.+ for input in &inputs {+ if !defined.contains(input) {+ return Err(format!(+ "graph {graph_index} ({name}): node {n} ({:?}) reads tensor {input} with no writer above it",+ node.op()+ ));+ }+ }+ // Single-writer SSA: no output may already be defined.+ for output in &outputs {+ if defined.contains(output) {+ return Err(format!(+ "graph {graph_index} ({name}): node {n} ({:?}) rewrites tensor {output} (writers: {:?})",+ node.op(),+ writers.get(output)+ ));+ }+ }+ 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).+ 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 stored_layout = stored_layout(tensors, *output);+ if stored_layout != want.layout {+ return Err(format!(+ "graph {graph_index} ({name}): node {n} ({:?}) infers tensor {output} layout {:?}, stored {:?}",+ node.op(),+ want.layout,+ stored_layout+ ));+ }+ shapes.insert(*output, want.clone());+ writers.insert(*output, n);+ defined.insert(*output);+ }+ // Digest over the canonical op/edge/attr sequence (spec 9.2): the+ // same order the emitter hashes (op byte, inputs, outputs, per-attr+ // name + value bytes).+ digest_node(&mut hasher, &node, attrs.as_ref())?;+ }++ // Every graph output must be defined (traceable to inputs).+ if let Some(outputs) = graph.outputs() {+ for o in 0..outputs.len() {+ let t = outputs.get(o);+ if !defined.contains(&t) {+ return Err(format!("graph {graph_index} ({name}): output tensor {t} is never written"));+ }+ }+ }++ let graph_digest: [u8; 32] = hasher.finalize().into();+ Ok(InferredGraph { graph: graph_index, shapes, graph_digest })+}++/// Infer a node's output shapes from its inputs and attributes.+fn infer_node(+ op: fb::Op,+ inputs: &[i32],+ attrs: Option<&Attrs<'_>>,+ shapes: &HashMap<i32, Inferred>,+ node: usize,+ graph: &str,+ graph_index: usize,+) -> Result<Vec<Inferred>, String> {+ let err = |what: &str| format!("graph {graph_index} ({graph}): node {node} ({op:?}): {what}");+ let shape_of = |t: i32| -> Result<&Inferred, String> {+ shapes.get(&t).ok_or_else(|| err(&format!("tensor {t} has no shape")))+ };+ let attrs = attrs.ok_or_else(|| err("no attributes"))?;+ // Computed tensors default to CHANNEL_BLOCKED_4 (spec 3.4); View keeps+ // its source layout (zero-copy reinterpret).+ let blocked = fb::Layout::CHANNEL_BLOCKED_4;+ match op {+ fb::Op::Conv => {+ if inputs.len() != 3 {+ return Err(err("Conv wants [x, w, b]"));+ }+ let x = shape_of(inputs[0])?.dims.clone();+ let w = shape_of(inputs[1])?.dims.clone();+ let kernel = attrs.ints("kernel")?;+ let stride = attrs.ints("stride")?;+ let dilation = attrs.ints("dilation")?;+ let pads = attrs.ints("pads")?;+ let groups = attrs.int("groups")?;+ if x.len() != 3 || w.len() < 2 {+ return Err(err("Conv shapes are not [c, h, w] / [m, ...]"));+ }+ let kh = if kernel.len() == 2 { kernel[0] } else { w.get(2).copied().unwrap_or(1) };+ let kw = if kernel.len() == 2 { kernel[1] } else { w.get(3).copied().unwrap_or(1) };+ let sh = stride.first().copied().unwrap_or(1);+ let sw = *stride.get(1).unwrap_or(&1);+ let dh = dilation.first().copied().unwrap_or(1);+ let dw = *dilation.get(1).unwrap_or(&1);+ let pt = pads.first().copied().unwrap_or(0);+ let pl = *pads.get(1).unwrap_or(&0);+ let m = w[0];+ let out_h = conv_out(x[1], kh, sh, dh, pt * 2);+ let out_w = conv_out(x[2], kw, sw, dw, pl * 2);+ let _ = groups;+ Ok(vec![Inferred { dims: vec![m, out_h, out_w], layout: blocked }])+ }+ fb::Op::MatMul => {+ if inputs.len() != 4 && inputs.len() != 3 {+ return Err(err("MatMul wants [a, w, s, b] or [a, w, b]"));+ }+ let a = shape_of(inputs[0])?.dims.clone();+ let w = shape_of(inputs[1])?.dims.clone();+ 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: blocked }])+ }+ fb::Op::Add | fb::Op::Mul => {+ if inputs.len() != 2 {+ return Err(err("binary wants [a, b]"));+ }+ let a = shape_of(inputs[0])?.dims.clone();+ let b = shape_of(inputs[1])?.dims.clone();+ if a != b {+ return Err(err(&format!("binary shape mismatch {a:?} vs {b:?}")));+ }+ Ok(vec![Inferred { dims: a, layout: blocked }])+ }+ fb::Op::AddBroadcast | fb::Op::MulBroadcast => {+ if inputs.len() != 2 {+ return Err(err("broadcast wants [a, b]"));+ }+ let a = shape_of(inputs[0])?.dims.clone();+ let b = shape_of(inputs[1])?.dims.clone();+ if b.len() != 3 || b[1] != 1 || b[2] != 1 || b[0] != a[0] {+ return Err(err(&format!("broadcast {b:?} is not [c, 1, 1] over {a:?}")));+ }+ Ok(vec![Inferred { dims: a, layout: blocked }])+ }+ fb::Op::LayerNorm | fb::Op::RmsNorm => {+ if inputs.is_empty() {+ return Err(err("norm wants [x, ...]"));+ }+ let x = shape_of(inputs[0])?.dims.clone();+ Ok(vec![Inferred { dims: x, layout: blocked }])+ }+ 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.+ let phase = attrs.opt_int("phase")?.unwrap_or(0);+ if phase == 0 {+ if inputs.len() != 2 {+ return Err(err("Attention scores wants [q, k]"));+ }+ let q = shape_of(inputs[0])?.dims.clone();+ let k = shape_of(inputs[1])?.dims.clone();+ let heads = attrs.int("heads")?;+ if q.len() != 3 || k.len() != 3 {+ return Err(err("Attention shapes are not sequences"));+ }+ Ok(vec![Inferred { dims: vec![heads, q[2], k[2]], layout: blocked }])+ } else {+ if inputs.len() != 2 {+ return Err(err("Attention apply wants [probs, v]"));+ }+ let probs = shape_of(inputs[0])?.dims.clone();+ let v = shape_of(inputs[1])?.dims.clone();+ let heads = attrs.int("heads")?;+ if probs.len() != 3 || v.len() != 3 {+ return Err(err("Attention shapes are not sequences"));+ }+ // Mixed output: `[d_model, 1, queries]`, where d_model is the+ // value width scaled to query heads (GQA: kv_heads <= heads).+ 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: blocked }])+ }+ }+ fb::Op::Softmax => {+ if inputs.len() != 1 {+ return Err(err("Softmax wants [x]"));+ }+ let x = shape_of(inputs[0])?.dims.clone();+ Ok(vec![Inferred { dims: x, layout: blocked }])+ }+ fb::Op::RotaryEmbedding => {+ if inputs.len() != 2 {+ return Err(err("RotaryEmbedding wants [x, angles]"));+ }+ let x = shape_of(inputs[0])?.dims.clone();+ Ok(vec![Inferred { dims: x, layout: blocked }])+ }+ fb::Op::View => {+ if inputs.len() != 1 {+ return Err(err("View wants [x]"));+ }+ let x = inputs[0];+ let src = shape_of(x)?.clone();+ let offset = attrs.int("offset")?;+ let dims = attrs.ints("dims")?;+ if dims.len() != 3 {+ return Err(err("View dims are not [c, h, w]"));+ }+ // Bounds: the view must fit inside the source allocation. Both+ // are `[c, h, w]` element counts; the offset is in elements.+ let src_elems: i64 =+ src.dims.iter().map(|&d| d as i64).product();+ let dst_elems: i64 = dims.iter().map(|&d| d as i64).product();+ if offset < 0 || offset as i64 + dst_elems > src_elems {+ return Err(err(&format!(+ "View [{offset}..{}] escapes its source of {src_elems} elements",+ offset as i64 + dst_elems+ )));+ }+ Ok(vec![Inferred { dims, layout: src.layout }])+ }+ _ => Err(err("op is not a Phase 1 sampler op")),+ }+}++/// `floor((in + pad - dilation * (k - 1) - 1) / stride) + 1`: ONNX's+/// convolution output size. Mirrors `nets::conv_out` (mod_part10.rs) — the+/// loader shares the formula rather than duplicating a subtly different one.+fn conv_out(input: i32, kernel: i32, stride: i32, dilation: i32, pad_total: i32) -> i32 {+ let effective = dilation * (kernel - 1) + 1;+ let padded = input + pad_total;+ if padded < effective || stride == 0 {+ return 0;+ }+ (padded - effective) / stride + 1+}++/// Hash one node in the canonical order (spec 9.2): op byte, inputs,+/// outputs, then per-attribute name + value bytes. Must match the emitter's+/// `emit_sampler` digest exactly.+fn digest_node(+ hasher: &mut Sha256,+ node: &fb::Node<'_>,+ attrs: Option<&Attrs<'_>>,+) -> Result<(), String> {+ use sha2::Digest as _;+ hasher.update([node.op().0 as u8]);+ if let Some(inputs) = node.inputs() {+ for i in 0..inputs.len() {+ hasher.update(inputs.get(i).to_le_bytes());+ }+ }+ if let Some(outputs) = node.outputs() {+ for o in 0..outputs.len() {+ hasher.update(outputs.get(o).to_le_bytes());+ }+ }+ if let Some(attrs) = attrs {+ for i in 0..attrs.attrs.len() {+ let attr = attrs.attrs.get(i);+ if let Some(name) = attr.name() {+ hasher.update(name.as_bytes());+ match attr.value_type() {+ fb::AttrValue::AttrInt => {+ let v = attr+ .value_as_attr_int()+ .map(|v| v.value())+ .ok_or("AttrInt with no value")?;+ hasher.update(v.to_le_bytes());+ }+ fb::AttrValue::AttrInts => {+ let v = attr+ .value_as_attr_ints()+ .and_then(|v| v.value())+ .ok_or("AttrInts with no value")?;+ for j in 0..v.len() {+ hasher.update(v.get(j).to_le_bytes());+ }+ }+ fb::AttrValue::AttrFloat => {+ let v = attr+ .value_as_attr_float()+ .map(|v| v.value())+ .ok_or("AttrFloat with no value")?;+ hasher.update(v.to_le_bytes());+ }+ fb::AttrValue::AttrBool => {+ let v = attr+ .value_as_attr_bool()+ .map(|v| v.value())+ .ok_or("AttrBool with no value")?;+ hasher.update([u8::from(v)]);+ }+ _ => return Err("attribute value is not a Phase 1 kind".into()),+ }+ }+ }+ }+ Ok(())+}
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.rsnew file mode 100644index 0000000000..e2dbee538d--- /dev/null+++ b/library/ml/src/main/rust/src/maml2/lower.rs@@ -0,0 +1,688 @@+//! Lower a verified + inferred v2 graph to an executable [`Plan`].+//!+//! The loader replays the file's SSA nodes through the existing `*_raw`+//! [`Builder`] entry points — the same door the v1 graph-section loader+//! uses — so shape propagation, fusion, arena packing, and `Op` emission+//! (including the tiled/GEMV routing) are shared rather than reimplemented.+//! The v2 tensor table is bridged by a [`WeightSource`] over the v2 buffers.+//!+//! Phase 1 covers the sampler op subset (spec 5.2): Conv (fp16), MatMul+//! (int8 1x1), Add/Mul/AddBroadcast, LayerNorm, Attention (scores + apply+//! phases), Softmax (full), RotaryEmbedding, View (slice-channels).++use std::collections::HashMap;++use crate::maml2::fb;+use crate::maml2::infer::InferredGraph;+use crate::maml2::verify::Verified;+use crate::nets::{Act, Builder, Id, Plan, Shape, WeightSource};++/// Activation from the v2 `activation` attribute code.+///+/// Inverse of the emitter's `act_code`: 0 none, 1 relu, 2 hardswish,+/// 3 sigmoid, 5 clip01, 6 swish, 8 gelu.+fn act_from_code(code: i32) -> Result<Act, String> {+ match code {+ 0 => Ok(Act::None),+ 1 => Ok(Act::Relu),+ 2 => Ok(Act::HardSwish),+ 3 => Ok(Act::Sigmoid),+ 5 => Ok(Act::Clip01),+ 6 => Ok(Act::Swish),+ 8 => Ok(Act::Gelu),+ _ => Err(format!("activation code {code} is not a Phase 1 activation")),+ }+}++/// A [`WeightSource`] over v2 weight tensors.+///+/// v1 weight bytes are repacked (channel-blocked) in the v2 buffers, so the+/// offsets the `*_raw` builders take are *payload-relative element indices*+/// assigned here, not file offsets. The bridge owns the repacked payloads+/// (kept alive for the caller to upload verbatim) and hands out indices into+/// them. Quantized kernels are addressed by word index, mirroring the v1+/// convention the shaders implement.+///+/// Read-marking lives in the loader, not here: `lower` marks every weight+/// tensor the nodes name before finishing (host tensors via an explicit+/// list), satisfying the every-tensor rule without the bridge needing+/// interior mutability.+pub struct V2Weights {+ /// Payload bytes per v2 tensor index (empty for computed tensors).+ payloads: Vec<Vec<u8>>,+ /// Logical dims per v2 tensor index, for the shape cross-check in+ /// `shaped` (the `host_tensor` path resolves through `weight`, which+ /// checks dims like any other tensor).+ dims: Vec<Vec<u32>>,+ /// Element offset per v2 tensor index within its payload class.+ elem_offsets: HashMap<usize, u32>,+ /// Word offset per v2 tensor index (quantized kernels).+ word_offsets: HashMap<usize, u32>,+ /// Tensor count (weights + computed), for the `count` gate.+ count: usize,+}++impl V2Weights {+ /// Build the bridge from the verified model: copy each buffered weight+ /// payload out of the FlatBuffers vectors.+ pub fn new(verified: &Verified<'_>) -> Result<V2Weights, String> {+ let model = verified.model;+ let tensors = model.tensors().ok_or("a model with no tensors")?;+ let buffers = model.buffers();+ let mut payloads = Vec::with_capacity(tensors.len());+ let mut stored_dims: Vec<Vec<u32>> = Vec::with_capacity(tensors.len());+
Diff truncated.