ml: delete MAML runtime, assets, converters; keep NNFP stubs
- Commit
cf25f360411a61341e0be241782148e83960eec5- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-14 22:59 UTC (2 months ago)
- Parents
c129349
Diff
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex 7af0724a7e..0d12779d47 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -15,7 +15,6 @@ members = [ "library/e2ee-p2p/src/main/rust", "library/jni-http/src/main/rust", "library/map/src/main/rust",- "library/ml/src/main/rust", "library/vision/src/main/rust", "measure/src/main/rust", "communicate/src/main/rust",
camera/build.gradle.kts
diff --git a/camera/build.gradle.kts b/camera/build.gradle.ktsindex a69c953393..7bc0d9f4eb 100644--- a/camera/build.gradle.kts+++ b/camera/build.gradle.kts@@ -15,10 +15,10 @@ android { applicationId = "com.vayunmathur.camera" } androidResources {- // selfie_segmentation.maml is read straight out of the APK by SelfieSegmenter, so- // leave it uncompressed: fp16 weights barely deflate, and a compressed asset would- // have to be inflated into a heap buffer before it could be uploaded.- noCompress += "maml"+ // selfie_segmentation.onnx is read straight out of the APK by SelfieSegmenter, so+ // leave it uncompressed: quantised weights barely deflate, and a compressed asset+ // would have to be inflated into a heap buffer before ORT could open it.+ noCompress += "onnx" } }
camera/src/main/assets/selfie_segmentation.maml
diff --git a/camera/src/main/assets/selfie_segmentation.maml b/camera/src/main/assets/selfie_segmentation.mamldeleted file mode 100644index 924e5c5210..0000000000Binary files a/camera/src/main/assets/selfie_segmentation.maml and /dev/null differ
games/chess/build.gradle.kts
diff --git a/games/chess/build.gradle.kts b/games/chess/build.gradle.ktsindex 7963be58e7..69e7e55766 100644--- a/games/chess/build.gradle.kts+++ b/games/chess/build.gradle.kts@@ -14,10 +14,10 @@ android { applicationId = "com.vayunmathur.games.chess" } androidResources {- // Maia3's weights are read in place through an `AssetFileDescriptor`, and- // `AssetManager.openFd` throws for a deflated entry. Costs nothing on download size:- // fp16 weights barely compress.- noCompress += "maml"+ // Maia3's weights are read straight out of the APK, and a compressed asset would have+ // to be inflated into a heap buffer before ORT could open it. Costs nothing on download+ // size: quantised weights barely compress.+ noCompress += "onnx" } }
games/chess/src/main/assets/maia3-5m.maml
diff --git a/games/chess/src/main/assets/maia3-5m.maml b/games/chess/src/main/assets/maia3-5m.mamldeleted file mode 100644index 604f2827f4..0000000000Binary files a/games/chess/src/main/assets/maia3-5m.maml and /dev/null differ
library/ml/MAML2_SPEC.md
diff --git a/library/ml/MAML2_SPEC.md b/library/ml/MAML2_SPEC.mddeleted file mode 100644index facee7f7bf..0000000000--- a/library/ml/MAML2_SPEC.md+++ /dev/null@@ -1,447 +0,0 @@-# 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. Kernels are **always NCHW** in the file:- every kernel — NCHW or blocked twin — reads kernel bytes NCHW, so one- stored layout serves every execution layout and the host interpreter- (NCHW-only) stays a valid oracle for all of them. Only activations block.- (The pilot stored blocked kernels; that forked the interpreter from the- device with both sides self-consistent, and was reverted.)-* Computed tensors are `CHANNEL_BLOCKED_4` where the dispatched kernels- consume blocked activations (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 wherever twins run.-* Mixed plans carry explicit transpose ops at NCHW↔blocked boundaries; a- producer/consumer pair with different layouts and no transpose between- them is a loader bug, caught by shape+layout inference at load.-* During the migration most files are all-NCHW (few dispatched kernels have- blocked twins yet): they declare NCHW throughout, honestly. A file is- re-emitted blocked when its net's transpose boundaries + twins land —- files are generated artifacts, and the layout declaration always matches- the execution the file was emitted for.-* 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).--## 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/build.gradle.kts
diff --git a/library/ml/build.gradle.kts b/library/ml/build.gradle.ktsindex f7bd832020..65d351e9a7 100644--- a/library/ml/build.gradle.kts+++ b/library/ml/build.gradle.kts@@ -2,37 +2,9 @@ plugins { id("common-conventions-library") } -androidComponents {- onVariants { variant ->- variant.sources.jniLibs?.addStaticSourceDirectory(- layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath- )- }-}--// The Vulkan compute ML runtime: `library/ml/src/main/rust`, on ash.-//-// No `externalNativeBuild` and no `ndkVersion`: there is no C++ or CMake in this repo-// (CMake was deliberately removed — see maps/build.gradle.kts:29-31), so cargo does the-// cross-compile and the NDK is only reached for its clang wrappers and glslc.-//-// Shaders are GLSL compute compiled to SPIR-V by the crate's own build.rs, which resolves-// glslc from the NDK and fails the build if it cannot.-// `-PemulatorAbi=x86_64` additionally cross-compiles for the emulator's ABI so the gate can be-// exercised on an x86_64 host. Off unless asked for, so no default or release build is affected.-rustNativeLib(- "modelrunner",- "ml",- extraAbis = if (providers.gradleProperty("emulatorAbi").orNull == ABI_X86_64) {- listOf(ABI_X86_64)- } else {- emptyList()- },-)- dependencies {- // On-device inference executor going forward: reduced-operator ONNX Runtime rebuild- // (arm64-only, 10 MB native). Coexists with the modelrunner JNI below during migration;- // MAML deletion removes the rustNativeLib wiring above.+ // On-device inference executor: reduced-operator ONNX Runtime rebuild (arm64-only,+ // 10 MB native). All models run as `.onnx` through the handles in this module; the old+ // Vulkan `modelrunner` crate is deleted. implementation(libs.onnxruntime.reduced.android) }
library/ml/src/main/rust/Cargo.toml
diff --git a/library/ml/src/main/rust/Cargo.toml b/library/ml/src/main/rust/Cargo.tomldeleted file mode 100644index 641097017f..0000000000--- a/library/ml/src/main/rust/Cargo.toml+++ /dev/null@@ -1,55 +0,0 @@-# The Vulkan compute ML runtime for `:library:ml`.-#-# Replaces `com.github.vayun-mathur:ncnn-android` for the two pure-CNN vision models-# the repo ships: MediaPipe Selfie Segmentation (`:camera` portrait bokeh) and U^2-Net-# portable (`:photos` auto-select-subject). ncnn stays for the two face models in-# `:photos` and for `:library:ocr`, `:pdf`, `:translate` and `:speech`.-#-# Why this exists: the ncnn fork is built CPU-only (`NCNN_VULKAN=OFF`) and compiles-# ncnn's entire layer registry into one `libncnn_android.so` for models that use a-# small fraction of it. This runs on Vulkan compute with our own weights encoding and-# only the ~11 shaders these two nets need.-#-# Why `ash` and not `androidx.webgpu`: the same reasoning as `library/map` — read the-# header comment there. `features = ["loaded"]` dlopens the platform's Vulkan loader and-# links nothing, so the only native code shipped is our own — and so the same code runs-# on a development host, which is where the shaders get exercised before a phone sees-# them.-#-# There is no graph interpreter: each net's forward pass is hardcoded Rust in `nets/`,-# so a `.maml` file carries ordered tensors and no topology. See `src/weights.rs`.--[package]-name = "modelrunner"-version = "0.1.0"-edition = "2021"-publish = false-license = "GPL-2.0-only"-description = "Vulkan compute ML runtime: .maml weights in, segmentation mask out"--[lib]-name = "modelrunner"-# cdylib for the JNI surface; rlib so the host test binary can link it and exercise-# the `.maml` reader and the CPU preprocessing without a device.-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,-# which is the only way the shaders ever get executed before they reach a phone.-ash = { version = "0.38", default-features = false, features = ["loaded"] }
library/ml/src/main/rust/build.rs
diff --git a/library/ml/src/main/rust/build.rs b/library/ml/src/main/rust/build.rsdeleted file mode 100644index a9db3181de..0000000000--- a/library/ml/src/main/rust/build.rs+++ /dev/null@@ -1,269 +0,0 @@-//! Compiles the GLSL in `shaders/` to SPIR-V with the NDK's `glslc`.-//!-//! Copied from `library/map/src/main/rust/build.rs`, which already globbed `.comp`-//! alongside `.vert`/`.frag` and already targeted `vulkan1.1`. Only the doc comments-//! and the final panic message differ.-//!-//! # This deliberately does not do what `games/voxels/build.rs` does-//!-//! That build script (`build.rs:94-106`) resolves `glslc` from two hardcoded-//! absolute paths under one developer's home directory, and when it finds neither-//! it calls `minimal_vert_spv()` / `minimal_frag_spv()` — writing a **28-byte stub**-//! consisting of a SPIR-V header and a single `OpCapability`. A build that takes-//! that path succeeds, installs, runs, and draws nothing at all, with no warning-//! anywhere. The failure surfaces as "the screen is black" long after the build.-//!-//! So this script resolves the compiler from the environment for the *host*-//! platform it is running on, and [`panic!`]s if it cannot find it or if a shader-//! fails to compile. A missing shader compiler must stop the build.-//!-//! SPIR-V is `include_bytes!`d rather than shipped as an asset: the shaders are-//! part of the runtime, and an asset can be missing at run time while a linked-//! `&[u8]` cannot.--use std::env;-use std::path::{Path, PathBuf};-use std::process::Command;--fn main() {- let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));- 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()))- .filter_map(|e| e.ok().map(|e| e.path()))- .filter(|p| {- matches!(- p.extension().and_then(|e| e.to_str()),- Some("vert") | Some("frag") | Some("comp")- )- })- .collect();- // Sorted so the build is reproducible and a diff of the log is stable.- entries.sort();-- for shader in &entries {- let name = shader.file_name().expect("shader file name");- println!("cargo:rerun-if-changed={}", shader.display());- let target = out_dir.join(format!("{}.spv", name.to_string_lossy()));-- let output = Command::new(&glslc)- .arg("--target-env=vulkan1.1")- .arg("-O")- .arg("-o")- .arg(&target)- .arg(shader)- .output()- .unwrap_or_else(|e| panic!("cannot run {}: {e}", glslc.display()));-- if !output.status.success() {- panic!(- "glslc failed on {}:\n{}{}",- shader.display(),- String::from_utf8_lossy(&output.stdout),- String::from_utf8_lossy(&output.stderr),- );- }- // A zero-exit that wrote nothing usable is the silent-stub case, caught here- // rather than at run time on a black screen.- let written = std::fs::metadata(&target).map(|m| m.len()).unwrap_or(0);- if written < MIN_SPIRV_BYTES {- panic!(- "glslc produced {written} bytes for {}; a real SPIR-V module is at least \- {MIN_SPIRV_BYTES} bytes",- shader.display(),- );- }- compiled += 1;- }-- if compiled == 0 {- panic!("no shaders found in {}", shader_dir.display());- }-}--/// 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,-/// so the host triple is what matters, not the target. Searched in order:-///-/// 1. `GLSLC` — an explicit override, for a CI image that puts it elsewhere.-/// 2. `ANDROID_NDK_HOME` / `ANDROID_NDK_ROOT` — set directly by some CI setups.-/// 3. `ANDROID_HOME` / `ANDROID_SDK_ROOT`, then the highest installed `ndk/*`.-/// 4. `sdk.dir` from the repo's `local.properties`, which is what a dev box has.-/// 5. `glslc` on `PATH`.-fn find_glslc() -> PathBuf {- if let Some(explicit) = env::var_os("GLSLC").map(PathBuf::from) {- if explicit.is_file() {- return explicit;- }- panic!("GLSLC is set to {explicit:?} but that is not a file");- }-- let host = host_dir();- let executable = if cfg!(windows) { "glslc.exe" } else { "glslc" };-- let mut ndks: Vec<PathBuf> = Vec::new();- for key in ["ANDROID_NDK_HOME", "ANDROID_NDK_ROOT"] {- if let Some(dir) = env::var_os(key) {- ndks.push(PathBuf::from(dir));- }- }- let mut sdks: Vec<PathBuf> = Vec::new();- for key in ["ANDROID_HOME", "ANDROID_SDK_ROOT"] {- if let Some(dir) = env::var_os(key) {- sdks.push(PathBuf::from(dir));- }- }- if let Some(dir) = sdk_dir_from_local_properties() {- sdks.push(dir);- }- for sdk in &sdks {- // Highest version first, so a box with several NDKs uses the newest.- let mut installed: Vec<PathBuf> = std::fs::read_dir(sdk.join("ndk"))- .into_iter()- .flatten()- .filter_map(|e| e.ok().map(|e| e.path()))- .filter(|p| p.is_dir())- .collect();- installed.sort();- installed.reverse();- ndks.extend(installed);- }-- for ndk in &ndks {- let candidate = ndk.join("shader-tools").join(&host).join(executable);- if candidate.is_file() {- return candidate;- }- }-- if Command::new(executable).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {- return PathBuf::from(executable);- }-- panic!(- "glslc not found. Looked for ndk/*/shader-tools/{host}/{executable} under \- {sdks:?} and {ndks:?}, then on PATH. Install the NDK, or set GLSLC. Every \- layer of both networks is a compute shader, so this build stops here rather \- than producing a runtime that reports itself unavailable on every device.",- );-}--/// The NDK's prebuilt-tool directory name for the host we are running on.-fn host_dir() -> String {- let os = if cfg!(target_os = "windows") {- "windows"- } else if cfg!(target_os = "macos") {- "darwin"- } else {- "linux"- };- // The NDK ships x86_64 host tools even on arm64 macOS, where they run under- // Rosetta, so the host CPU is deliberately not consulted.- format!("{os}-x86_64")-}--/// `sdk.dir` out of the repo root's `local.properties`.-///-/// Walks up from the crate rather than assuming a depth, so moving the crate does-/// not silently break shader compilation.-fn sdk_dir_from_local_properties() -> Option<PathBuf> {- let mut dir: &Path = &PathBuf::from(env::var("CARGO_MANIFEST_DIR").ok()?);- loop {- let candidate = dir.join("local.properties");- if candidate.is_file() {- let text = std::fs::read_to_string(&candidate).ok()?;- for line in text.lines() {- let line = line.trim();- if let Some(value) = line.strip_prefix("sdk.dir=") {- // Gradle properties escape the Windows separator.- return Some(PathBuf::from(value.replace("\\\\", "\\").replace("\\:", ":")));- }- }- return None;- }- dir = dir.parent()?;- }-}
library/ml/src/main/rust/examples/bake_gemma4_prefix.rs
diff --git a/library/ml/src/main/rust/examples/bake_gemma4_prefix.rs b/library/ml/src/main/rust/examples/bake_gemma4_prefix.rsdeleted file mode 100644index 72d6c80b41..0000000000--- a/library/ml/src/main/rust/examples/bake_gemma4_prefix.rs+++ /dev/null@@ -1,341 +0,0 @@-//! Precomputes the KV cache for Gemma 4's fixed prompt prefix and writes it to a file.-//!-//! ```text-//! cargo run --offline --release -p modelrunner --example bake_gemma4_prefix -- \-//! gemma4_text.maml gemma4_embed.maml gemma4_tokenizer.spm1 prefix.txt gemma4_prefix.kv-//! ```-//!-//! # Why this exists-//!-//! The system block and the tool declarations are ~1,100 positions and they never change. On a-//! Tensor G4 prefilling them costs about **14 seconds**, and every device pays it on every cold-//! start, forever, to compute numbers that are identical everywhere.-//!-//! They are identical because the inputs are: the same tokens against the same weights. So they-//! can be computed once, here, and shipped.-//!-//! # Not bit-identical, and that is fine-//!-//! A desktop GPU and a phone will not produce the same bits - different reduction orders, fp16-//! rounding. The difference is far inside the noise the int4 weights already carry, and the cache-//! is not compared against anything, only attended over. What must match exactly is the **token-//! sequence**, which is why the digest below covers it.-//!-//! # The format-//!-//! ```text-//! magic "GKV1" 4 bytes-//! positions u32-//! tensors u32 (30: fifteen layers, keys and values)-//! digest 32 bytes, SHA-256 of the prefix tokens-//! payload per tensor, in plan order: positions * width fp16 values-//! ```-//!-//! Per tensor rather than one flat arena image, so the file does not depend on arena offsets and-//! survives being loaded into a different cache tier than it was baked at.-use std::path::PathBuf;-use std::sync::Arc;--use modelrunner::nets::gemma4;-use modelrunner::post::sentencepiece::{Table, GEMMA};-use modelrunner::vulkan::context;-use modelrunner::vulkan::reshape::Reshaped;-use modelrunner::vulkan::run::StepParams;-use modelrunner::weights::{graph, Weights};--/// Positions one prefill submit covers. As the bridge's, for the same fence reasons.-const CHUNK: usize = 4096;--/// The markers a rendered prompt may contain. Mirrors `Gemma4Handle.MARKERS`.-const MARKERS: [&str; 11] = [- "<bos>", "<eos>", "<|turn>", "<turn|>", "<|tool>", "<tool|>", "<|tool_call>", "<tool_call|>",- "<|tool_response>", "<tool_response|>", "<|\"|>",-];--fn main() {- let mut args = std::env::args().skip(1);- let (Some(text), Some(embed), Some(tokenizer), Some(prefix), Some(out)) =- (args.next(), args.next(), args.next(), args.next(), args.next())- else {- println!(- "usage: bake_gemma4_prefix <text.maml> <embed.maml> <table.spm1> <prefix.txt> <out.kv>"- );- return;- };- let read = |p: &str| std::fs::read(PathBuf::from(p));- let (Ok(text_bytes), Ok(embed_bytes), Ok(table_bytes)) =- (read(&text), read(&embed), read(&tokenizer))- else {- return println!("cannot read the model files");- };- let Ok(rendered) = std::fs::read_to_string(&prefix) else {- return println!("cannot read {prefix}");- };- let (Ok(weights), Ok(embed_weights)) = (- Weights::parse(&text_bytes, graph::GEMMA4_TEXT),- Weights::parse(&embed_bytes, graph::GEMMA4_EMBED),- ) else {- return println!("the weights do not parse");- };- let table = match Table::parse_with(&table_bytes, GEMMA) {- Ok(table) => table,- Err(why) => return println!("the tokenizer does not parse: {why}"),- };-- let tokens = table.encode_with_specials(rendered.trim_end_matches('\n'), &MARKERS);- println!("prefix {} chars -> {} positions", rendered.len(), tokens.len());- if tokens.is_empty() {- return println!("an empty prefix");- }-- let context = match context::shared() {- Ok(context) => context,- Err(why) => return println!("no Vulkan device: {why}"),- };- // Baked at the top tier so the file covers any device; a smaller tier reads the prefix it- // has room for and refuses the rest, which `import_pinned` checks.- let tier = gemma4::MAX_CONTEXT;- let mut net = match Reshaped::new(Arc::clone(&context), &weights, gemma4::Mode::DecodeStep.at(tier), |o, m| {- gemma4::build(o, m)- }) {- Ok(net) => net,- Err(why) => return println!("the model did not open: {why}"),- };- let reader = embed_weights.reader();- let rotary = weights.reader();- let (Ok(local), Ok(global)) = (- rotary.fp16(gemma4::ROTARY_LOCAL, &[gemma4::MAX_CONTEXT, gemma4::HEAD_DIM]),- rotary.fp16(gemma4::ROTARY_GLOBAL, &[gemma4::MAX_CONTEXT, gemma4::GLOBAL_HEAD_DIM]),- ) else {- return println!("the rotary tables did not load");- };-- // Every position, including the last: this is a prefix, not a prompt, so nothing here is a- // prediction and the whole thing belongs in the cache.- let mut fed = 0usize;- for chunk in tokens.chunks(CHUNK) {- let width = chunk.len() as u32;- let base = fed as u32;- let mut hidden = vec![0f32; (gemma4::D_MODEL * width) as usize];- let mut per_layer =- vec![0f32; (gemma4::PER_LAYER * gemma4::LAYERS as u32 * width) as usize];- let mut al = vec![0f32; (gemma4::HEAD_DIM * width) as usize];- let mut ag = vec![0f32; (gemma4::GLOBAL_HEAD_DIM * width) as usize];- for (offset, &token) in chunk.iter().enumerate() {- let column = offset as u32;- let position = base + column;- let Ok((h, p)) = gemma4::gather(&reader, token) else {- return println!("token {token} is not in the embedding");- };- place(&mut hidden, &h, column, width);- place(&mut per_layer, &p, column, width);- let from = (position * gemma4::HEAD_DIM) as usize;- place(&mut al, &local[from..from + gemma4::HEAD_DIM as usize], column, width);- let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;- place(&mut ag, &global[from..from + gemma4::GLOBAL_HEAD_DIM as usize], column, width);- }- let Ok(at) = net.at(gemma4::Mode::Prefill { tokens: width }.at(tier)) else {- return println!("the prefill plan did not build");- };- let _ = at.set_params(StepParams {- prefix: base,- window_start: base.saturating_sub(gemma4::WINDOW - 1),- });- if at.infer_raw_many(&[&hidden, &per_layer, &al, &ag]).is_err() {- return println!("the prefill failed at {base}");- }- fed += chunk.len();- print!("\r {fed} / {} positions", tokens.len());- }- println!();-- let positions = fed as u32;- let payload = match net.at(gemma4::Mode::DecodeStep.at(tier)) {- Ok(net) => match net.export_pinned(gemma4::CACHE_TENSORS, positions) {- Ok(bytes) => bytes,- Err(why) => return println!("the cache did not export: {why}"),- },- Err(why) => return println!("{why}"),- };-- let mut file = Vec::with_capacity(payload.len() + 64);- file.extend_from_slice(b"GKV1");- file.extend_from_slice(&positions.to_le_bytes());- file.extend_from_slice(&(payload.len() as u32 / positions.max(1)).to_le_bytes());- file.extend_from_slice(&digest(&tokens));- file.extend_from_slice(&payload);- // Round-trip it before claiming success. Importing into a *fresh* net and continuing from- // the same position must give the same next token as the net that just prefilled it - which- // is the only property the app relies on, and the only one worth checking.- let expected = argmax_next(&mut net, &reader, &local, &global, tokens[tokens.len() - 1], positions);- let mut fresh = match Reshaped::new(Arc::clone(&context), &weights, gemma4::Mode::DecodeStep.at(tier), |o, m| {- gemma4::build(o, m)- }) {- Ok(net) => net,- Err(why) => return println!("the check net did not open: {why}"),- };- match fresh.at(gemma4::Mode::DecodeStep.at(tier)) {- Ok(net) => {- if let Err(why) = net.import_pinned(gemma4::CACHE_TENSORS, positions, &payload) {- return println!("the cache did not import: {why}");- }- }- Err(why) => return println!("{why}"),- }- // Continue for a while, not one token. One token agreeing only says export and import are- // each other's inverse; it says nothing about whether the numbers mean anything to a model- // that keeps reading them. A cache that is subtly wrong still produces *a* plausible first- // token and then falls apart, which is exactly what shipping this did.- let ask = table.encode_with_specials("<turn|>\n<|turn>user\nWhat is 2+2?<turn|>\n<|turn>model\n", &MARKERS);- let live = continue_with(&mut net, &reader, &local, &global, &ask, positions, 12);- let baked = continue_with(&mut fresh, &reader, &local, &global, &ask, positions, 12);- println!(" prefilled continues: {:?}", table.decode(&live));- println!(" imported continues: {:?}", table.decode(&baked));- if live != baked {- println!("MISMATCH: the imported cache does not behave like the prefilled one");- }- let got = argmax_next(&mut fresh, &reader, &local, &global, tokens[tokens.len() - 1], positions);- match (expected, got) {- (Some(a), Some(b)) if a == b => println!("round trip ok: both continue with token {a}"),- (a, b) => {- return println!("ROUND TRIP FAILED: prefilled gives {a:?}, imported gives {b:?}");- }- }-- match std::fs::write(&out, &file) {- Ok(()) => {- println!("wrote {out} {:.1} MB", file.len() as f64 / 1e6);- println!(" {positions} positions, {} bytes each", payload.len() / positions as usize);- }- Err(why) => println!("cannot write {out}: {why}"),- }-}--/// Write one position's `values` into column `column` of a `[C, 1, width]` block.-fn place(into: &mut [f32], values: &[f32], column: u32, width: u32) {- for (channel, &value) in values.iter().enumerate() {- if let Some(slot) = into.get_mut(channel * width as usize + column as usize) {- *slot = value;- }- }-}--/// A digest of the token sequence, so a cache cannot be used against a prompt it was not baked-/// for.-///-/// Not cryptographic - FNV-1a widened to 32 bytes. The threat is a stale asset after someone-/// edits the system prompt, not an adversary: the file ships beside the weights over the same-/// channel, and anyone who could substitute it could substitute those.-fn digest(tokens: &[u32]) -> [u8; 32] {- let mut out = [0u8; 32];- for lane in 0..4usize {- let mut hash: u64 = 0xcbf2_9ce4_8422_2325 ^ (lane as u64).wrapping_mul(0x9e37_79b9);- for &token in tokens {- for byte in token.to_le_bytes() {- hash ^= u64::from(byte);- hash = hash.wrapping_mul(0x100_0000_01b3);- }- }- out[lane * 8..lane * 8 + 8].copy_from_slice(&hash.to_le_bytes());- }- out-}--/// The token this net would produce next, given `token` at `position`.-fn argmax_next(- net: &mut Reshaped<gemma4::Pass>,- reader: &modelrunner::weights::Reader<'_>,- local: &[f32],- global: &[f32],- token: u32,- position: u32,-) -> Option<u32> {- let (hidden, per_layer) = gemma4::gather(reader, token).ok()?;- let from = (position * gemma4::HEAD_DIM) as usize;- let al = local[from..from + gemma4::HEAD_DIM as usize].to_vec();- let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;- let ag = global[from..from + gemma4::GLOBAL_HEAD_DIM as usize].to_vec();- let at = net.at(gemma4::Mode::DecodeStep.at(gemma4::MAX_CONTEXT)).ok()?;- at.set_params(StepParams {- prefix: position,- window_start: position.saturating_sub(gemma4::WINDOW - 1),- })- .ok()?;- let out = at.infer_raw_many(&[&hidden, &per_layer, &al, &ag]).ok()?;- let mut best = (f32::NEG_INFINITY, 0u32);- let mut base = 0u32;- for split in out.iter().take(gemma4::HEAD_SPLITS) {- for (offset, &value) in split.iter().enumerate() {- if value > best.0 {- best = (value, base + offset as u32);- }- }- base += split.len() as u32;- }- Some(best.1)-}--/// Feed `ask` at `from`, then generate `limit` tokens greedily.-fn continue_with(- net: &mut Reshaped<gemma4::Pass>,- reader: &modelrunner::weights::Reader<'_>,- local: &[f32],- global: &[f32],- ask: &[u32],- from: u32,- limit: usize,-) -> Vec<u32> {- let mut out = Vec::new();- let mut at = from;- for &token in ask {- if argmax_at(net, reader, local, global, token, at).is_none() {- return out;- }- at += 1;- }- let mut next = *ask.last().unwrap_or(&2);- for _ in 0..limit {- let Some(token) = argmax_at(net, reader, local, global, next, at) else { break };- at += 1;- if token == 1 || token == 106 {- break;- }- out.push(token);- next = token;- }- out-}--/// One decode step, returning the argmax.-fn argmax_at(- net: &mut Reshaped<gemma4::Pass>,- reader: &modelrunner::weights::Reader<'_>,- local: &[f32],- global: &[f32],- token: u32,- position: u32,-) -> Option<u32> {- let (hidden, per_layer) = gemma4::gather(reader, token).ok()?;- let from = (position * gemma4::HEAD_DIM) as usize;- let al = local[from..from + gemma4::HEAD_DIM as usize].to_vec();- let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;- let ag = global[from..from + gemma4::GLOBAL_HEAD_DIM as usize].to_vec();- let at = net.at(gemma4::Mode::DecodeStep.at(gemma4::MAX_CONTEXT)).ok()?;- at.set_params(StepParams {- prefix: position,- window_start: position.saturating_sub(gemma4::WINDOW - 1),- })- .ok()?;- let out = at.infer_raw_many(&[&hidden, &per_layer, &al, &ag]).ok()?;- let mut best = (f32::NEG_INFINITY, 0u32);- let mut base = 0u32;- for split in out.iter().take(gemma4::HEAD_SPLITS) {- for (offset, &value) in split.iter().enumerate() {- if value > best.0 {- best = (value, base + offset as u32);- }- }- base += split.len() as u32;- }- Some(best.1)-}
library/ml/src/main/rust/examples/check_gate_audio.rs
diff --git a/library/ml/src/main/rust/examples/check_gate_audio.rs b/library/ml/src/main/rust/examples/check_gate_audio.rsdeleted file mode 100644index a1de10974c..0000000000--- a/library/ml/src/main/rust/examples/check_gate_audio.rs+++ /dev/null@@ -1,756 +0,0 @@-//! Measures what the music gate scores on music, speech, noise and silence — offline, no device.-//!-//! ```text-//! cargo run --offline --release -p modelrunner --example check_gate_audio-//! cargo run --offline --release -p modelrunner --example check_gate_audio -- song.wav ...-//! ```-//!-//! # What this answers-//!-//! Every other check on `gate.rs` is a *layout* check: 8,200 weights in the order the graph-//! declares them, a forward pass bit-exact against `scripts/ml/gate_reference.py`, a front end-//! bit-exact against numpy. All of that can pass while the detector is useless, because a-//! network that has been transcribed correctly and *scaled* wrongly still produces a number-//! between zero and one for every frame. The unanswered question is empirical: does the score-//! rise on music and stay down on everything else?-//!-//! # Why speech is the control that matters-//!-//! Noise and silence are trivial negatives — anything that responds to spectral structure at all-//! will reject them. Speech is harmonic, band-limited to roughly the same 60–3800 Hz the front-//! end keeps, and temporally structured, so it is the input that separates a music detector from-//! an "is there sound" detector. If speech scores where music scores, the reported separation is-//! not evidence of a working port.-//!-//! # Why every signal is RMS-matched-//!-//! The front end is a log-mel bank with no per-utterance normalisation, so level walks straight-//! into the features. Comparing loud synthetic music against quiet synthetic speech would-//! measure the level difference and report it as discrimination. Everything here is normalised-//! to the same RMS, and `music_chords` is additionally swept across three levels so the level-//! sensitivity is visible rather than hidden.-//!-//! Synthetic audio is a real limitation and is not the same as recordings; pass WAV paths on the-//! command line to add real material. 16-bit PCM only, any rate, mono or stereo.-//!-//! # What it measured, 2026-09-05-//!-//! Run over 12 real recordings (Windows Media ringtones, alarms and chimes), real speech from two-//! Windows SAPI voices, the ASI APK's audio assets, and a synthetic set, all resampled to 16 kHz-//! mono and RMS-matched.-//!-//! **The gate fires on music and rejects speech, decisively.** Median raw score: real ringtones-//! 0.69–0.96, real speech 0.0033–0.0048. Under a debounced latch at threshold 0.90 the real music-//! clips hold the positive state 67–99% of the time and the speech clips hold it 0%. Speech is the-//! hard negative and the separation there is about as clean as it could be.-//!-//! **It does not reject broadband noise.** Pink noise holds 87% duty at threshold 0.58 and still-//! 80% at 0.98, and 47 s of real keyboard clicks holds 89%. Dropping the noise to −50 dBFS barely-//! moves it, so this is not an artefact of testing noise at music's level. No threshold separates-//! music from noise, because the noise score distribution has a long tail into 1.0 rather than a-//! shifted mean.-//!-//! **The shipped latch parameters are unusable as-is**, independent of the threshold.-//! [`Hysteresis::negative_frames_before_event`] is 1, so at 100 Hz the state drops on a single-//! dipping frame and immediately re-arms: every input, including silence-adjacent ones, produces-//! 100–200 positive events per minute. That is why `sweep` reports duty cycle and not event rate.-//!-//! # Two earlier conclusions that were wrong, recorded so they are not re-derived-//!-//! Against synthetic music alone this harness said the gate ranked pink noise *above* music and-//! that the port therefore had a weight-layout or scale bug. Both were artefacts of the-//! synthesiser: `music_chords` scores 0.44 where real ringtones score 0.75–0.96, and-//! `music_harmonics` — a sustained, perfectly stationary chord — scores 0.04, lower than anything-//! but silence. Real music is none of those things. Synthetic positives are not a substitute here-//! and a negative result from them alone should not be trusted.-//!-//! The front end is not implicated either way: `features()` shows a flat bank for noise, a-//! structured one for chords, nothing pinned at the ceiling. And `scripts/ml/gate_reference.py`-//! cannot arbitrate any of this — the forward pass is already bit-exact against it, so both sides-//! would reproduce a shared misreading of the flatbuffer identically.--use modelrunner::gate::{probability, Gate, Hysteresis, Latch, CHANNELS, HOP_SAMPLES};-use modelrunner::microfrontend::{Frontend, NOW_PLAYING};--const RATE: usize = 16_000;-const SECONDS: usize = 12;-const SAMPLES: usize = RATE * SECONDS;--/// Full-scale fraction every generated signal is normalised to before quantisation.-const TARGET_RMS: f32 = 0.1;--fn main() {- let mut signals: Vec<(String, Vec<i16>)> = Vec::new();-- for (name, samples) in [- ("silence", silence()),- ("white_noise", white_noise()),- ("pink_noise", pink_noise()),- ("noise_low_band", band_noise(60.0, 500.0)),- ("noise_high_band", band_noise(2000.0, 3800.0)),- ("tone_440", tone()),- ("music_harmonics", harmonic_stack()),- ("music_chords", chords()),- ("music_melody", melody()),- ("music_full_mix", full_mix()),- ("speech_male", speech(112.0, true)),- ("speech_female", speech(196.0, true)),- ("speech_continuous", speech(120.0, false)),- ("babble_two_voices", babble()),- ("am_noise", am_noise()),- ] {- signals.push((name.to_string(), quantize(&samples, TARGET_RMS)));- }-- // The same music at three levels, to show whether the score is tracking loudness.- for level in [0.02f32, 0.05, 0.30] {- signals.push((format!("music_chords@rms{level:.2}"), quantize(&chords(), level)));- }-- // Pink noise at four levels. Everything above is matched at -20 dBFS, which is loud for room- // noise and quiet for music, so a noise false-accept measured there may not be one in a real- // room. This is the control that says whether the noise problem survives realistic levels.- for level in [0.003f32, 0.01, 0.03, 0.10] {- signals.push((format!("noise_pink@rms{level:.3}"), quantize(&pink_noise(), level)));- }-- for path in std::env::args().skip(1) {- // The label drives the grouping in `summarise`, so real files are named with the same- // `music_` / `speech_` / `noise_` prefixes the synthetic ones use.- let label = std::path::Path::new(&path)- .file_stem()- .map(|stem| stem.to_string_lossy().into_owned())- .unwrap_or_else(|| path.clone());- match read_wav(&path) {- Ok(samples) => signals.push((label, samples)),- Err(error) => println!("skipping {path}: {error}"),- }- }-- println!(- "{:<26} {:>6} {:>7} {:>7} {:>7} {:>7} {:>7} {:>7} {:>7} {:>6} {:>7}",- "input", "hops", "min", "mean", "p50", "p90", "max", "sd", "d/hop", "rail%", "events"- );- println!("{}", "-".repeat(110));-- let mut rows = Vec::new();- for (name, pcm) in &signals {- let Some(row) = run(pcm) else {- println!("{name:<26} too short to warm the gate up");- continue;- };- println!(- "{:<26} {:>6} {:>7.4} {:>7.4} {:>7.4} {:>7.4} {:>7.4} {:>7.4} {:>7.4} {:>5.1}% {:>7}",- name,- row.hops,- row.min,- row.mean,- row.p50,- row.p90,- row.max,- row.sd,- row.step,- row.rail * 100.0,- row.events- );- rows.push((name.clone(), row));- }-- println!();- summarise(&rows);- println!();- sweep(&rows);- println!();- features(&signals);- println!();- trajectory(&signals);-}--/// Fraction of time the latch holds the positive state, at a range of positive thresholds.-///-/// This is the decision-relevant view, and it is deliberately *not* an event count. The shipped-/// [`Hysteresis::negative_frames_before_event`] is 1, so at 100 Hz the state drops on a single-/// dipping frame and re-arms immediately; event rates then land at 100–200 per minute for almost-/// every input and measure the latch's chatter rather than the threshold. Duty cycle — how much-/// of the clip the app would believe music is playing — is monotone in the threshold and is what-/// a caller actually consumes.-///-/// `DEBOUNCED` is the same sweep with a hold time, to separate "the threshold is wrong" from-/// "the latch parameters are wrong".-fn sweep(rows: &[(String, Row)]) {- for (label, hold, band) in [("SHIPPED latch", 1u32, 0.01f32), ("DEBOUNCED latch", 50, 0.05)] {- println!("active duty cycle %, {label} (hold {hold} frames, band {band:.2})");- let thresholds = [0.50f32, 0.58, 0.70, 0.80, 0.90, 0.95, 0.98];- print!("{:<26}", "");- for threshold in thresholds {- print!("{threshold:>8.2}");- }- println!();- println!("{}", "-".repeat(26 + 8 * thresholds.len()));-- let mut totals = vec![(0.0f32, 0.0f32); thresholds.len()];- for (name, row) in rows {- print!("{name:<26}");- for (column, threshold) in thresholds.iter().enumerate() {- let duty = replay(&row.scores, *threshold, hold, band);- print!("{:>8.1}", duty * 100.0);- // Everything not named `music_` counts against the false-accept budget.- let slot = &mut totals[column];- if name.starts_with("music_") {- slot.0 += duty;- } else {- slot.1 += duty;- }- }- println!();- }-- let music = rows.iter().filter(|(n, _)| n.starts_with("music_")).count() as f32;- let other = rows.len() as f32 - music;- for (heading, pick) in [- ("MEAN music (want high)", 0usize),- ("MEAN non-music (want low)", 1),- ] {- print!("{heading:<26}");- for total in &totals {- let (sum, count) = if pick == 0 { (total.0, music) } else { (total.1, other) };- print!("{:>8.1}", 100.0 * sum / count);- }- println!();- }- println!();- }-}--/// Re-run the latch over an already-computed score stream, returning the active duty cycle.-fn replay(scores: &[i16], positive_threshold: f32, hold: u32, band: f32) -> f32 {- let mut latch = Latch::new(Hysteresis {- positive_threshold,- negative_threshold: positive_threshold - band,- negative_frames_before_event: hold,- ..Hysteresis::SHIPPED- });- let active = scores.iter().filter(|&&score| latch.push(score).active).count();- active as f32 / scores.len() as f32-}--/// The first 40 reported hops of a few inputs, because a distribution hides whether the score is-/// tracking anything or just rattling. At 100 Hz these forty numbers are 400 ms.-fn trajectory(signals: &[(String, Vec<i16>)]) {- println!("first 40 reported hops (400 ms)");- for (name, pcm) in signals {- if !matches!(name.as_str(), "white_noise" | "music_chords" | "music_harmonics") {- continue;- }- let mut frontend = Frontend::new(NOW_PLAYING).expect("the front end builds");- let mut gate = Gate::new();- let mut frames = Vec::new();- frontend.process(pcm, &mut frames);- let scores: Vec<String> = (0..frames.len() / CHANNELS)- .filter_map(|frame| gate.push(&frames[frame * CHANNELS..(frame + 1) * CHANNELS]))- .take(40)- .map(|score| format!("{:.2}", probability(score)))- .collect();- println!(" {name:<18} {}", scores.join(" "));- }-}--/// Mean log-mel per channel, so a nonsense score can be attributed to the trunk rather than to-/// the front end feeding it. A bank pinned at the ceiling or flat across every channel would mean-/// the harness is wrong, not the gate.-fn features(signals: &[(String, Vec<i16>)]) {- println!("mean log-mel by channel (front-end sanity; ceiling is 15.0)");- for (name, pcm) in signals {- if !matches!(name.as_str(), "white_noise" | "music_chords" | "music_harmonics" | "speech_male")- {- continue;- }- let mut frontend = Frontend::new(NOW_PLAYING).expect("the front end builds");- let mut frames = Vec::new();- frontend.process(pcm, &mut frames);- let count = frames.len() / CHANNELS;- let mut mean = vec![0.0f32; CHANNELS];- for frame in 0..count {- for (channel, slot) in mean.iter_mut().enumerate() {- *slot += frames[frame * CHANNELS + channel];- }- }- let line: Vec<String> = mean- .iter()- .step_by(4)- .map(|total| format!("{:>5.1}", total / count as f32))- .collect();- println!(" {name:<18} {}", line.join(" "));- }-}--struct Row {- hops: usize,- min: f32,- mean: f32,- p50: f32,- p90: f32,- max: f32,- /// Fraction of hops whose raw probability is at or above the shipped positive threshold.- above: f32,- /// Standard deviation of the raw probability.- sd: f32,- /// Mean absolute change in probability between consecutive 10 ms hops.- step: f32,- /// Fraction of hops where the int8 logit hit a rail, i.e. the classifier saturated.- rail: f32,- /// Positive events the shipped `SmoothedLatchingClassifier` fired.- events: usize,- /// Every reported int16 score, kept so `sweep` can re-latch without re-running the gate.- scores: Vec<i16>,-}--/// PCM in, one raw probability per hop out, plus what the shipped latch did with the scores.-///-/// `None` when the clip is shorter than the gate's 230 ms receptive field, which real recordings-/// of UI blips easily are.-fn run(pcm: &[i16]) -> Option<Row> {- let mut frontend = Frontend::new(NOW_PLAYING).expect("the front end builds");- let mut gate = Gate::new();- let mut latch = Latch::new(Hysteresis::SHIPPED);-- let mut probabilities = Vec::new();- let mut scores = Vec::new();- let mut events = 0usize;- let mut frames = Vec::new();-- for chunk in pcm.chunks(HOP_SAMPLES) {- frames.clear();- let produced = frontend.process(chunk, &mut frames);- for frame in 0..produced {- let logmel = &frames[frame * CHANNELS..(frame + 1) * CHANNELS];- if let Some(score) = gate.push(logmel) {- probabilities.push(probability(score));- scores.push(score);- if latch.push(score).positive_event {- events += 1;- }- }- }- }-- let mut sorted = probabilities.clone();- sorted.sort_by(|a, b| a.partial_cmp(b).expect("scores are finite"));- let hops = sorted.len();- if hops < 2 {- return None;- }- let threshold = Hysteresis::SHIPPED.positive_threshold;- let mean = probabilities.iter().sum::<f32>() / hops as f32;- let variance = probabilities.iter().map(|p| (p - mean) * (p - mean)).sum::<f32>() / hops as f32;- let step = probabilities.windows(2).map(|w| (w[1] - w[0]).abs()).sum::<f32>()- / (hops - 1).max(1) as f32;- // The int8 logit spans +-10 through a scale of 0.0784, so a probability outside this band can- // only come from the quantized logit clamping at 127 or -128.- let rail = probabilities.iter().filter(|&&p| !(0.001..=0.999).contains(&p)).count() as f32- / hops as f32;- Some(Row {- hops,- min: sorted[0],- mean,- p50: sorted[hops / 2],- p90: sorted[hops * 9 / 10],- max: sorted[hops - 1],- above: probabilities.iter().filter(|&&p| p >= threshold).count() as f32 / hops as f32,- sd: variance.sqrt(),- step,- rail,- events,- scores,- })-}--/// The separation statement, stated in terms of the measured distributions rather than a verdict.-fn summarise(rows: &[(String, Row)]) {- let pick = |prefix: &str| -> Vec<&(String, Row)> {- rows.iter().filter(|(name, _)| name.starts_with(prefix)).collect()- };- let music = pick("music_");- let speech: Vec<_> = pick("speech_").into_iter().chain(pick("babble_")).collect();- let noise: Vec<_> = pick("white_")- .into_iter()- .chain(pick("pink_"))- .chain(pick("noise_"))- .chain(pick("silence"))- .collect();-- let span = |group: &[&(String, Row)]| -> (f32, f32) {- let low = group.iter().map(|(_, r)| r.p50).fold(f32::MAX, f32::min);- let high = group.iter().map(|(_, r)| r.p50).fold(f32::MIN, f32::max);- (low, high)- };-- let (music_low, music_high) = span(&music);- let (speech_low, speech_high) = span(&speech);- let (noise_low, noise_high) = span(&noise);-- println!("median raw score by group");- println!(" music {music_low:.4} .. {music_high:.4}");- println!(" speech {speech_low:.4} .. {speech_high:.4}");- println!(" noise {noise_low:.4} .. {noise_high:.4}");- println!();- println!(- "music vs speech gap: {:+.4} music vs noise gap: {:+.4}",- music_low - speech_high,- music_low - noise_high- );- println!(- "shipped positive threshold {:.2}; total positive events across all inputs: {}",- Hysteresis::SHIPPED.positive_threshold,- rows.iter().map(|(_, r)| r.events).sum::<usize>()- );- println!(- "fraction of hops at or above threshold: music {:.1}%, speech {:.1}%, noise {:.1}%",- 100.0 * music.iter().map(|(_, r)| r.above).sum::<f32>() / music.len() as f32,- 100.0 * speech.iter().map(|(_, r)| r.above).sum::<f32>() / speech.len() as f32,- 100.0 * noise.iter().map(|(_, r)| r.above).sum::<f32>() / noise.len() as f32,- );-}--// --- signal generation --------------------------------------------------------------------//-// Deterministic, so a run is reproducible and a regression is attributable.--struct Random(u32);--impl Random {- fn new() -> Random {- Random(0x2545_F491)- }-- /// Uniform in `[-1, 1)`.- fn signed(&mut self) -> f32 {- self.0 = self.0.wrapping_mul(1103515245).wrapping_add(12345) & 0x7FFF_FFFF;- (self.0 >> 11) as f32 / (1u32 << 19) as f32 - 1.0- }-}--/// Scale to `rms` of full scale and round to i16. Silence is passed through untouched.-fn quantize(samples: &[f32], rms: f32) -> Vec<i16> {- let energy = samples.iter().map(|s| s * s).sum::<f32>() / samples.len() as f32;- if energy <= 0.0 {- return vec![0i16; samples.len()];- }- let gain = rms / energy.sqrt();- samples- .iter()- .map(|s| (s * gain * 32767.0).clamp(-32768.0, 32767.0) as i16)- .collect()-}--fn silence() -> Vec<f32> {- vec![0.0; SAMPLES]-}--fn white_noise() -> Vec<f32> {- let mut random = Random::new();- (0..SAMPLES).map(|_| random.signed()).collect()-}--/// Voss-McCartney: octave-spaced random holds summed, giving a 1/f slope.-fn pink_noise() -> Vec<f32> {- let mut random = Random::new();- let mut rows = [0.0f32; 12];- (0..SAMPLES)- .map(|n| {- for (octave, row) in rows.iter_mut().enumerate() {- if n % (1 << octave) == 0 {- *row = random.signed();- }- }- rows.iter().sum::<f32>() / rows.len() as f32- })- .collect()-}--/// White noise through a band-pass, to see which part of the 60–3800 Hz band drives the score.-fn band_noise(low: f32, high: f32) -> Vec<f32> {- let mut out = white_noise();- let centre = (low * high).sqrt();- resonate(&mut out, centre, high - low);- out-}--fn tone() -> Vec<f32> {- (0..SAMPLES)- .map(|n| (2.0 * std::f32::consts::PI * 440.0 * n as f32 / RATE as f32).sin())- .collect()-}--/// One sustained chord: three notes, eight harmonics each, slight detune, slow tremolo.-fn harmonic_stack() -> Vec<f32> {- let roots = [220.0f32, 277.18, 329.63];- (0..SAMPLES)- .map(|n| {- let t = n as f32 / RATE as f32;- let mut sum = 0.0;- for (voice, root) in roots.iter().enumerate() {- let detune = 1.0 + 0.0015 * voice as f32;- for harmonic in 1..=8 {- let f = root * detune * harmonic as f32;- if f < 7800.0 {- sum += (2.0 * std::f32::consts::PI * f * t).sin() / harmonic as f32;- }- }- }- sum * (1.0 + 0.08 * (2.0 * std::f32::consts::PI * 4.5 * t).sin())- })- .collect()-}--/// A note with a plucked envelope and a 1/k harmonic series.-fn note(out: &mut [f32], start: usize, length: usize, hz: f32, gain: f32) {- for n in 0..length.min(out.len().saturating_sub(start)) {- let t = n as f32 / RATE as f32;- let envelope = (1.0 - (-t * 60.0).exp()) * (-t * 1.6).exp();- let mut sum = 0.0;- for harmonic in 1..=10 {- let f = hz * harmonic as f32;- if f < 7800.0 {- sum += (2.0 * std::f32::consts::PI * f * t).sin() / harmonic as f32;- }- }- out[start + n] += sum * envelope * gain;- }-}--/// I–V–vi–IV in C, three times, each chord struck twice.-fn chords() -> Vec<f32> {- let progression: [[f32; 3]; 4] = [- [261.63, 329.63, 392.00],- [392.00, 493.88, 587.33],- [220.00, 261.63, 329.63],- [174.61, 220.00, 261.63],- ];- let mut out = vec![0.0f32; SAMPLES];- let beat = RATE / 2;- for bar in 0..(SAMPLES / (beat * 2)) {- let chord = progression[bar % progression.len()];- for pitch in chord {- note(&mut out, bar * beat * 2, beat * 2, pitch, 1.0);- note(&mut out, bar * beat * 2 + beat, beat, pitch, 0.6);- }- note(&mut out, bar * beat * 2, beat * 2, chord[0] / 2.0, 1.2);- }- out-}--/// A monophonic line with vibrato over a held bass note.-fn melody() -> Vec<f32> {- let scale = [261.63f32, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25];- let order = [0usize, 2, 4, 7, 5, 4, 2, 0, 3, 5, 7, 5, 4, 2, 1, 0];- let mut out = vec![0.0f32; SAMPLES];- let step = RATE / 4;- for index in 0..(SAMPLES / step) {- let hz = scale[order[index % order.len()]];- let start = index * step;- for n in 0..step.min(SAMPLES - start) {- let t = n as f32 / RATE as f32;- let vibrato = 1.0 + 0.006 * (2.0 * std::f32::consts::PI * 5.5 * t).sin();- let envelope = (1.0 - (-t * 40.0).exp()) * (-t * 1.2).exp();- let mut sum = 0.0;- for harmonic in 1..=9 {- let f = hz * vibrato * harmonic as f32;- if f < 7800.0 {- sum += (2.0 * std::f32::consts::PI * f * t).sin() / harmonic as f32;- }- }- out[start + n] += sum * envelope;- }- note(&mut out, start, step, scale[0] / 2.0, 0.8);- }- out-}--/// Chords plus a kick on every beat and a hat on every off-beat: the closest thing here to a mix.-fn full_mix() -> Vec<f32> {- let mut out = chords();- let mut random = Random::new();- let beat = RATE / 2;- for hit in 0..(SAMPLES / beat) {- let start = hit * beat;- for n in 0..(RATE / 8).min(SAMPLES - start) {- let t = n as f32 / RATE as f32;- let sweep = 120.0 * (-t * 30.0).exp() + 45.0;- out[start + n] += (2.0 * std::f32::consts::PI * sweep * t).sin() * (-t * 22.0).exp() * 2.0;- }- let hat = start + beat / 2;- for n in 0..(RATE / 40).min(SAMPLES.saturating_sub(hat)) {- let t = n as f32 / RATE as f32;- out[hat + n] += random.signed() * (-t * 180.0).exp() * 0.5;- }- }- out-}--/// A two-pole resonator, applied in place. `bandwidth` is in Hz.-fn resonate(buffer: &mut [f32], hz: f32, bandwidth: f32) {- let r = (-std::f32::consts::PI * bandwidth / RATE as f32).exp();- let theta = 2.0 * std::f32::consts::PI * hz / RATE as f32;- let (a1, a2) = (2.0 * r * theta.cos(), -r * r);- let (mut y1, mut y2) = (0.0f32, 0.0f32);- for sample in buffer.iter_mut() {- let y = *sample * (1.0 - r) + a1 * y1 + a2 * y2;- y2 = y1;- y1 = y;- *sample = y;- }-}--/// Source-filter speech: a jittered glottal pulse train through three moving formants, with-/// syllable-rate amplitude modulation, fricative bursts and, when `pauses`, inter-phrase silence.-///-/// Not a recording, and does not claim to be one. What it does carry is the properties that make-/// speech the hard negative: a harmonic source, formant structure inside the gate's band, and a-/// 4–5 Hz envelope — everything music has except a stable pitch and a metrical grid.-///-/// `pauses` exists because RMS is measured over the whole signal, so a speech clip full of gaps is-/// louder than music during its voiced parts and quieter on average. The pause-free variant-/// removes that confound.-fn speech(f0: f32, pauses: bool) -> Vec<f32> {- // Five vowels, as (F1, F2, F3) in Hz.- let vowels = [- (700.0f32, 1220.0f32, 2600.0f32),- (400.0, 2000.0, 2550.0),- (300.0, 2300.0, 3000.0),- (600.0, 900.0, 2400.0),- (500.0, 1500.0, 2500.0),- ];- let mut random = Random::new();- let mut out = vec![0.0f32; SAMPLES];- let phoneme = RATE * 13 / 100;- let mut index = 0usize;- let mut position = 0usize;- let mut phase = 0.0f32;-- while position < SAMPLES {- let length = phoneme.min(SAMPLES - position);- // Every seventh segment is a pause; every third is a fricative rather than a vowel.- let kind = index % 7;- let mut segment = vec![0.0f32; length];- if kind == 6 && pauses {- // Silence between phrases.- } else if kind == 2 || kind == 5 {- for sample in segment.iter_mut() {- *sample = random.signed() * 0.35;- }- resonate(&mut segment, 4200.0, 1400.0);- } else {- // Declining pitch contour across the phrase, plus per-period jitter.- let base = f0 * (1.0 + 0.18 * (index as f32 * 0.9).sin() - 0.02 * (index % 7) as f32);- for sample in segment.iter_mut() {- phase += base * (1.0 + 0.01 * random.signed()) / RATE as f32;- // A glottal pulse: one impulse per period, not a sine.- *sample = if phase >= 1.0 {- phase -= 1.0;- 1.0- } else {- 0.0- };- }- let (f1, f2, f3) = vowels[index % vowels.len()];- resonate(&mut segment, f1, 80.0);- resonate(&mut segment, f2, 110.0);- resonate(&mut segment, f3, 170.0);- }- // Syllable-rate envelope with onset and offset ramps.- for (n, sample) in segment.iter_mut().enumerate() {- let t = n as f32 / length as f32;- *sample *= (std::f32::consts::PI * t).sin().powf(0.6);- }- out[position..position + length].copy_from_slice(&segment);- position += length;- index += 1;- }- out-}--/// Two speakers at once — no pauses, denser harmonic content, closer to a room with people in it.-fn babble() -> Vec<f32> {- let a = speech(104.0, true);- let b = speech(188.0, true);- let offset = RATE * 3 / 10;- (0..SAMPLES)- .map(|n| a[n] + b[(n + offset) % SAMPLES] * 0.8)- .collect()-}--/// White noise wearing speech's envelope: structureless, but modulated. Separates a detector that-/// keys on spectral structure from one that keys on the shape of the level over time.-fn am_noise() -> Vec<f32> {- let envelope = speech(112.0, true);- let mut random = Random::new();- let window = 160usize;- let mut out = vec![0.0f32; SAMPLES];- for start in (0..SAMPLES).step_by(window) {- let end = (start + window).min(SAMPLES);- let level = envelope[start..end].iter().map(|s| s.abs()).sum::<f32>() / (end - start) as f32;- for sample in out[start..end].iter_mut() {- *sample = random.signed() * level;- }- }- out-}--// --- WAV -----------------------------------------------------------------------------------/// Minimal 16-bit PCM WAV reader: downmixes to mono and resamples to 16 kHz linearly.-fn read_wav(path: &str) -> Result<Vec<i16>, String> {- let bytes = std::fs::read(path).map_err(|e| e.to_string())?;- if bytes.len() < 44 || &bytes[0..4] != b"RIFF" || &bytes[8..12] != b"WAVE" {- return Err("not a RIFF/WAVE file".into());- }- let word = |at: usize| u16::from_le_bytes([bytes[at], bytes[at + 1]]) as usize;- let long =- |at: usize| u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) as usize;-- let (mut channels, mut rate, mut bits) = (0usize, 0usize, 0usize);- let mut data: Option<(usize, usize)> = None;- let mut at = 12usize;- while at + 8 <= bytes.len() {- let id = &bytes[at..at + 4];- let size = long(at + 4);- let body = at + 8;- if id == b"fmt " && body + 16 <= bytes.len() {- channels = word(body + 2);- rate = long(body + 4);- bits = word(body + 14);- } else if id == b"data" {- data = Some((body, size.min(bytes.len() - body)));- }- at = body + size + (size & 1);- }-- let (body, size) = data.ok_or("no data chunk")?;- if bits != 16 || channels == 0 || rate == 0 {- return Err(format!("need 16-bit PCM; got {bits}-bit, {channels}ch, {rate}Hz"));- }-- let mono: Vec<f32> = bytes[body..body + size]- .chunks_exact(2)- .map(|c| i16::from_le_bytes([c[0], c[1]]) as f32)- .collect::<Vec<_>>()- .chunks(channels)- .map(|frame| frame.iter().sum::<f32>() / channels as f32)- .collect();-- let length = mono.len() * RATE / rate;- let resampled: Vec<f32> = (0..length)- .map(|n| {- let source = n as f32 * rate as f32 / RATE as f32;- let index = source as usize;- let frac = source - index as f32;- let a = mono[index.min(mono.len() - 1)];- let b = mono[(index + 1).min(mono.len() - 1)];- a + (b - a) * frac- })- .collect();-- // Same RMS normalisation as the synthetic signals, so the table stays comparable.- Ok(quantize(&resampled, TARGET_RMS))-}
library/ml/src/main/rust/examples/check_gemma4_audio_parity.rs
diff --git a/library/ml/src/main/rust/examples/check_gemma4_audio_parity.rs b/library/ml/src/main/rust/examples/check_gemma4_audio_parity.rsdeleted file mode 100644index 6b76d3c121..0000000000--- a/library/ml/src/main/rust/examples/check_gemma4_audio_parity.rs+++ /dev/null@@ -1,445 +0,0 @@-//! Runs Gemma 4's audio tower on the GPU and compares it with onnxruntime's.-//!-//! ```text-//! python scripts/ml/gemma4_audio_encoder_parity.py audio_encoder_fp16.onnx -o audio_golden.json-//! cargo run --offline --release -p modelrunner --example check_gemma4_audio_parity -- \-//! gemma4_audio.maml audio_golden.json-//! ```-//!-//! # What only this catches-//!-//! Until this existed the audio tower had never executed on a GPU in any form. `nets::gemma4_audio`-//! has twenty unit tests and `vulkan::parity` has ten for the banded ops, and all of them pass —-//! but the unit tests check that 747 tensors are declared in the order the converter writes them,-//! and the parity tests check one op against its own oracle. Both are satisfied by a tower whose-//! twelve layers are composed wrongly.-//!-//! # The int4 control is the bar, and it is not optional-//!-//! The device runs int4 weights and the export runs fp16 ones, so the two cannot agree closely.-//! Measured by the generator, four bits alone cost this much cosine at the output:-//!-//! ```text-//! T = 1 0.009 T = 25 0.017 T = 48 0.041-//! T = 4 0.002 T = 56 0.037-//! ```-//!-//! So against the exact reference a *correct* tower reads anywhere from 0.998 to 0.958 depending-//! only on how long the clip is, and no fixed floor exists that anyone could set. The control's-//! value is not that it widens the gap — it is that it makes the correct answer a CONSTANT. Every-//! comparison below is against `_int4` when the golden carries it.-//!-//! # The per-probe bar, which I expected not to exist-//!-//! The plan was to print the profile unthresholded, on the reasoning that fp16 Vulkan against-//! fp32 onnxruntime must drift with depth and no floor could be both tight enough to localise and-//! loose enough to pass. The first device run disproved that: the drift across twelve layers is-//! two parts in a million, against negative controls three orders of magnitude further out. So-//! [`PROBE_FLOOR`] is real and measured, not assumed.-use std::path::PathBuf;-use std::sync::Arc;--use modelrunner::logmel::{self, LogMel};-use modelrunner::nets::gemma4_audio as audio;-use modelrunner::vulkan::context;-use modelrunner::vulkan::reshape::Reshaped;-use modelrunner::weights::{graph, Weights};--/// The bar every probe must clear against the int4 control.-///-/// I expected this to be impossible to set. The reasoning was that Vulkan fp16 against fp32-/// onnxruntime must drift with depth, so any threshold tight enough to localise a fault would-/// fire on a correct run. The first device run disproved it. Measured on `multi`, T = 56:-///-/// ```text-/// layer0_in_projected 1.000000 layer_in_4..9 0.999999 tower_out 0.999998-/// layer_in_0..3 1.000000 layer_in_10,11 0.999998 encoder_out 0.999998-/// ```-///-/// Two parts in one millionth across twelve layers. The drift is real and monotonic and it is-/// four orders of magnitude smaller than I assumed. Against that, the generator's three negative-/// controls read 0.9677, 0.9874 and 0.9111 on the same clip, so this floor sits with roughly-/// three orders of margin on both sides.-///-/// Tighten it if the drift ever comes in lower; do NOT loosen it to accommodate a failure.-const PROBE_FLOOR: f64 = 0.9995;--/// The bar the output must clear against the int4 control.-///-/// Measured rather than chosen. The generator's three negative controls — all twelve relative-/// tables reversed, layer 6's alone, and q/k swapped — read 0.9677, 0.9874 and 0.9111 against the-/// same control. A correct device should reach the control almost exactly, so 0.99 sits between-/// the two populations. Note how little room that leaves: the single-layer fault is at 0.9874, so-/// a subtler one will sit above this floor and only the profile will show it.-const OUTPUT_FLOOR: f64 = 0.99;--/// A reproducible sample, bit-identical to `synthetic_pcm` in the generator.-///-/// Integer hash to i16 then a divide by 32768, which is exact in binary, so both sides agree to-/// the bit and the golden carries no waveform.-fn synthetic_pcm(count: usize) -> Vec<f32> {- (0..count)- .map(|i| {- let mut h = (i as u32).wrapping_mul(73_856_093);- h ^= h >> 13;- h = h.wrapping_mul(1_274_126_177);- h ^= h >> 16;- ((h & 0xFFFF) as i32 - 32768) as f32 / 32768.0- })- .collect()-}--/// The mel frames for a clip, through this crate's own front end.-///-/// Deliberately `logmel` rather than a dump from the golden: it makes the harness end to end, and-/// `logmel` is already pinned against the same reference extractor to 2.24e-7 of the frame peak,-/// so it cannot be the source of a disagreement seen here.-fn mel_for(real: usize) -> Result<(Vec<f32>, u32), String> {- let waveform = synthetic_pcm(real);- let mut frames = Vec::new();- let count = LogMel::new().spectrogram(&waveform, &mut frames);- if count != logmel::frame_count(real) {- return Err(format!("{count} frames, not {}", logmel::frame_count(real)));- }- Ok((frames, count as u32))-}--/// One plan, run once. `outputs` is however many the mode produces.-fn run(- context: &Arc<context::Context>,- weights: &Weights,- mode: audio::Mode,- input: &[f32],-) -> Result<Vec<Vec<f32>>, String> {- let mut net = Reshaped::new(Arc::clone(context), weights, mode, |offsets, mode| {- audio::build(offsets, mode)- })?;- net.at(mode)?.infer_raw_many(&[input])-}--/// Rows `probes` of a `[channels, 1, positions]` tensor, laid out row-major as the golden is.-fn gather_rows(values: &[f32], positions: usize, channels: usize, probes: &[usize]) -> Vec<f32> {- let mut out = Vec::with_capacity(probes.len() * channels);- for &position in probes {- for channel in 0..channels {- out.push(values.get(channel * positions + position).copied().unwrap_or(f32::NAN));- }- }- out-}--/// Cosine between a device tensor and the reference's.-fn cosine(got: &[f32], want: &[f32]) -> f64 {- if got.len() != want.len() || got.is_empty() {- return f64::NAN;- }- let dot: f64 = got.iter().zip(want).map(|(a, b)| f64::from(*a) * f64::from(*b)).sum();- let na: f64 = got.iter().map(|a| f64::from(*a) * f64::from(*a)).sum::<f64>().sqrt();- let nb: f64 = want.iter().map(|b| f64::from(*b) * f64::from(*b)).sum::<f64>().sqrt();- dot / (na * nb).max(1e-30)-}--/// The worst single probe token, and which one.-///-/// A pooled cosine over six probe rows hides a fault confined to one of them, and the ramp is-/// exactly such a fault: an unguarded band read corrupts only tokens 0..10, which is 44 % of a-/// T = 25 clip but 1.5 % of a T = 750 one. The clips that would make it unmissable - T = 1 and-/// T = 4 - cannot execute, because `MIN_TOKENS` is 12 and the band is the model's rather than-/// the clip's. So the ramp has to be caught per token instead of per clip, and `probe_tokens`-/// carries 0, 1, 11 and 12 for that reason.-fn worst_token(got: &[f32], want: &[f32], probes: &[usize], width: usize) -> (usize, f64) {- let mut lowest = (usize::MAX, 1.0_f64);- for (row, token) in probes.iter().enumerate() {- let (from, to) = (row * width, (row + 1) * width);- let (Some(a), Some(b)) = (got.get(from..to), want.get(from..to)) else { continue };- let each = cosine(a, b);- if each < lowest.1 {- lowest = (*token, each);- }- }- lowest-}--/// Compare one probe point against the control when there is one, else the exact reference.-///-/// Returns `(line, cosine, measured_against_control)`. The third matters: a cosine against the-/// exact reference is not comparable to [`OUTPUT_FLOOR`], because four bits alone move it by up-/// to 0.04 and the amount depends on the clip's length.-fn against(got: &[f32], clip: &str, label: &str, golden: &str) -> (String, f64, bool) {- let Some(exact) = field(golden, clip, label) else {- return (format!("{label}: absent from the golden"), f64::NAN, false);- };- let exact_cosine = cosine(got, &exact);- match field(golden, clip, &format!("{label}_int4")) {- Some(control) => {- let c = cosine(got, &control);- (format!("int4 {c:.6} (exact {exact_cosine:.6})"), c, true)- }- None => (format!("exact {exact_cosine:.6} NO CONTROL"), exact_cosine, false),- }-}--fn main() {- let mut args = std::env::args().skip(1);- let (Some(model), Some(path)) = (args.next().map(PathBuf::from), args.next()) else {- println!("usage: check_gemma4_audio_parity <gemma4_audio.maml> <audio_golden.json>");- return;- };- let bytes = match std::fs::read(&model) {- Ok(bytes) => bytes,- Err(why) => return println!("cannot read {}: {why}", model.display()),- };- let weights = match Weights::parse(&bytes, graph::GEMMA4_AUDIO) {- Ok(w) => w,- Err(why) => return println!("the audio model does not parse: {why}"),- };- if weights.len() != audio::TENSORS {- return println!("{} tensors, not {}", weights.len(), audio::TENSORS);- }- let golden = match std::fs::read_to_string(&path) {- Ok(text) => text,- Err(why) => return println!("cannot read the golden: {why}"),- };- let context = match context::shared() {- Ok(context) => context,- Err(why) => return println!("no Vulkan device: {why}"),- };-- let mut worst = (1.0_f64, String::new());- let mut any_control = false;- for clip in clips(&golden) {- let (Some(real), Some(want_frames), Some(want_tokens)) = (- scalar(&golden, &clip, "real"),- scalar(&golden, &clip, "frames"),- scalar(&golden, &clip, "tokens"),- ) else {- println!("{clip}: incomplete entry, skipped");- continue;- };- let probes = field_usize(&golden, &clip, "probe_tokens").unwrap_or_default();- println!();- println!("=== {clip}: {real} samples, {want_frames} frames, T {want_tokens}");-- let (mel, frames) = match mel_for(real) {- Ok(pair) => pair,- Err(why) => {- println!(" the front end failed: {why}");- continue;- }- };- if frames != want_frames as u32 {- println!(" FRAME COUNT DISAGREES: {frames} here, {want_frames} in the golden");- continue;- }- let input = match audio::prepare(&mel, frames) {- Ok(input) => input,- Err(why) => {- println!(" prepare failed: {why}");- continue;- }- };- let tokens = audio::tokens(frames) as usize;- if tokens != want_tokens {- println!(" TOKEN COUNT DISAGREES: {tokens} here, {want_tokens} in the golden");- continue;- }- // The module refuses a clip shorter than the attention band, and it is right to: the band- // is a property of the model, not of the clip. So the two short cases in the golden - the- // T = 1 and T = 4 clips chosen to sit entirely inside the start-of-sequence ramp - cannot- // execute here at all, and this says so once instead of failing fifteen times.- //- // The ramp is still covered. Queries 0..10 of EVERY clip are on it, and `probe_tokens`- // includes 0, 1, 11 and 12 precisely to straddle its boundary.- if tokens < audio::MIN_TOKENS as usize {- println!(- " skipped: T {tokens} is under MIN_TOKENS {}, which the 12-wide band requires.",- audio::MIN_TOKENS- );- println!(" the ramp it was chosen for is still probed at tokens 0, 1, 11, 12 elsewhere");- continue;- }-- // The front end. Only `projected` is compared: the device's `sscp_out` is in a PERMUTED- // channel order relative to the export's, because the converter permutes the input- // projection's rows (`input_rows` in `collect_gemma4_audio`) and the projection undoes it.- // Measured: sscp_out reads 0.29 against the golden while projected reads 1.000000 on the- // same run, which is the permutation and not a fault. Comparing it would need the golden- // to carry the permutation, which it does not.- match run(&context, &weights, audio::Mode::Sscp { frames }, &input) {- Ok(out) => {- let Some(values) = out.get(1) else {- println!(" Sscp produced no projected output");- continue;- };- let got = gather_rows(values, tokens, audio::D_MODEL as usize, &probes);- let (line, c, controlled) = against(&got, &clip, "layer0_in_projected", &golden);- any_control |= controlled;- println!(" {:<22} {line}", "layer0_in_projected");- println!(" {:<22} not compared: permuted channel order, see the source", "sscp_out");- if c < worst.0 {- worst = (c, format!("{clip}/layer0_in_projected"));- }- }- Err(why) => println!(" Sscp failed: {why}"),- }-- // The layer sweep, on the two extremes only. Every stop point re-records the plan, so- // thirteen of them per clip is the expensive part of this harness; `tiny` is the- // start-of-sequence ramp where every query is on the edge, and `multi` is the longest and- // the one where int4 costs the most, which is where a fault hides best.- if clip == "multi" || clip == "tiny" {- for layer in 0..=audio::LAYERS {- let mode = audio::Mode::Trace { frames, layers: layer };- let label = if layer == audio::LAYERS {- "tower_out".to_string()- } else {- format!("layer_in_{layer}")- };- match run(&context, &weights, mode, &input) {- Ok(out) => {- let Some(hidden) = out.first() else { continue };- let got = gather_rows(hidden, tokens, audio::D_MODEL as usize, &probes);- let (line, c, controlled) = against(&got, &clip, &label, &golden);- any_control |= controlled;- println!(" {label:<22} {line}");- if c < worst.0 {- worst = (c, format!("{clip}/{label}"));- }- if layer == audio::LAYERS {- if let Some(tail) = out.get(1) {- let got =- gather_rows(tail, tokens, audio::OUT_DIM as usize, &probes);- let (line, c, _) = against(&got, &clip, "encoder_out", &golden);- println!(" {:<22} {line}", "encoder_out");- if c < worst.0 {- worst = (c, format!("{clip}/encoder_out"));- }- }- }- }- Err(why) => println!(" {label:<22} failed: {why}"),- }- }- }-- // The output, which is the only figure with a floor under it.- match run(&context, &weights, audio::Mode::Clip { frames }, &input) {- Ok(out) => {- let Some(features) = out.first() else {- println!(" the clip pass produced no output");- continue;- };- let all: Vec<usize> = (0..tokens).collect();- let whole = gather_rows(features, tokens, audio::OUT_DIM as usize, &all);- let got = gather_rows(features, tokens, audio::OUT_DIM as usize, &probes);- let (line, c, controlled) = against(&got, &clip, "audio_features", &golden);- any_control |= controlled;- let verdict = if !controlled {- "NO CONTROL, unreadable"- } else if c > OUTPUT_FLOOR {- "ok"- } else {- "WRONG"- };- println!(" {:<22} {line} {verdict}", "audio_features");- // Per token, because the ramp is a fault in tokens 0..10 only and the pooled- // figure above averages it away. This is the check that stands in for the T = 1- // clip the module will not run.- let bar = field(&golden, &clip, "audio_features_int4")- .or_else(|| field(&golden, &clip, "audio_features"));- if let Some(bar) = bar {- let (token, each) =- worst_token(&got, &bar, &probes, audio::OUT_DIM as usize);- let ramp = if token < audio::ATTEND_SPAN as usize { " ON THE RAMP" } else { "" };- let mark = if each > OUTPUT_FLOOR { "ok" } else { "WRONG" };- println!(- " {:<22} token {token} at {each:.6} {mark}{ramp}",- "worst probe token"- );- if each < worst.0 {- worst = (each, format!("{clip}/token {token}"));- }- }- let _ = whole;- }- Err(why) => println!(" the clip pass failed: {why}"),- }- }-- println!();- if !any_control {- println!("NOTE: the golden carries no int4 control, so nothing above can tell a bug from");- println!(" four bits. Regenerate the golden without --no-control.");- return;- }- let verdict = if worst.0 > PROBE_FLOOR { "PASS" } else { "FAIL" };- println!("worst probe {:.6} at {} floor {PROBE_FLOOR} {verdict}", worst.0, worst.1);- println!();- if worst.0 > PROBE_FLOOR {- println!("The tower is as close to the reference as four bits allow, at every probe.");- println!("For scale: the generator's negative controls read 0.9677 (all twelve relative");- println!("tables reversed), 0.9874 (layer 6's alone) and 0.9111 (q/k swapped) against the");- println!("same control. A composition error is three orders of magnitude away from here.");- } else {- println!("This is a composition error, not quantisation. Read the profile above: the");- println!("first probe to fall names the layer AFTER the fault. Smooth and monotonic is");- println!("quantisation; a step at one layer is not.");- }-}--/// The clip names in the golden, in order.-fn clips(text: &str) -> Vec<String> {- let mut out = Vec::new();- let mut at = 0usize;- while let Some(found) = text[at..].find("\"name\":") {- let start = at + found + "\"name\":".len();- let rest = text[start..].trim_start();- if let Some(stripped) = rest.strip_prefix('"') {- if let Some(end) = stripped.find('"') {- out.push(stripped[..end].to_string());- }- }- at = start;- }- out-}--/// The slice of the golden belonging to `clip`, so a key lookup cannot cross into another one.-fn slice<'a>(text: &'a str, clip: &str) -> Option<&'a str> {- let start = text.find(&format!("\"name\": \"{clip}\""))?;- let rest = &text[start + 1..];- let end = rest.find("\"name\":").map_or(text.len(), |n| start + 1 + n);- Some(&text[start..end])-}--/// One `"key": number` from a clip's slice.-fn scalar(text: &str, clip: &str, key: &str) -> Option<usize> {- let body = slice(text, clip)?;- let at = body.find(&format!("\"{key}\""))?;- let rest = &body[at..];- let colon = rest.find(':')?;- rest[colon + 1..]- .trim_start()- .split(|c: char| !c.is_ascii_digit())- .next()- .and_then(|n| n.parse().ok())-}--/// One named array of floats from a clip's slice.-fn field(text: &str, clip: &str, key: &str) -> Option<Vec<f32>> {- Some(array(slice(text, clip)?, key)?.split(',').filter_map(|p| p.trim().parse().ok()).collect())-}--/// One named array of indices from a clip's slice.-fn field_usize(text: &str, clip: &str, key: &str) -> Option<Vec<usize>> {- Some(array(slice(text, clip)?, key)?.split(',').filter_map(|p| p.trim().parse().ok()).collect())-}--/// The text between the brackets of `"key": [...]`, matching the key exactly.-fn array<'a>(text: &'a str, key: &str) -> Option<&'a str> {- let at = text.find(&format!("\"{key}\": ["))?;- let rest = &text[at..];- let open = rest.find('[')?;- let close = rest[open..].find(']')?;- Some(&rest[open + 1..open + close])-}
library/ml/src/main/rust/examples/check_gemma4_parity.rs
diff --git a/library/ml/src/main/rust/examples/check_gemma4_parity.rs b/library/ml/src/main/rust/examples/check_gemma4_parity.rsdeleted file mode 100644index 74a9a18f7d..0000000000--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ /dev/null@@ -1,270 +0,0 @@-//! Runs Gemma 4's decode step on the GPU and compares its logits with onnxruntime's.-//!-//! ```text-//! cargo run --offline --release -p modelrunner --example check_gemma4_parity -- \-//! gemma4_text.maml gemma4_embed.maml logits_golden.json-//! ```-//!-//! # This is the check nothing else substitutes for-//!-//! Every other test in this port checks *layout* - that 999 tensors are declared in the order the-//! converter writes them, that a scale has the rank its precision implies, that one op agrees-//! with a CPU oracle. All of that can pass while the model is wrong, because a transposed read-//! agrees with itself and a doubled scale is still a number.-//!-//! Thirty-five layers in sequence against real weights is the only thing that catches an error of-//! *composition*: a residual added before its norm instead of after, a rotary applied to the key-//! but not the query, a cache written at the wrong position. Those produce plausible logits.-//!-//! # What agreement to expect-//!-//! The reference is fp16 weights in fp32 arithmetic; this is int4 weights with a per-block scale.-//! The logits will not match to the bit and should not be expected to. What must match is the-//! **argmax** and the broad ordering of the top few - a model that is right differs from the-//! reference by quantisation noise, and a model that is wrong differs by rearranging the ranking.-use std::path::PathBuf;-use std::sync::Arc;--use modelrunner::nets::gemma4;-use modelrunner::vulkan::context;-use modelrunner::vulkan::reshape::Reshaped;-use modelrunner::vulkan::run::StepParams;-use modelrunner::weights::{graph, Weights};--/// The cache these examples record against: the top tier, so a long prompt fits.-const TIER: u32 = gemma4::MAX_CONTEXT;--fn main() {- let mut args = std::env::args().skip(1);- let (Some(text), Some(embed), Some(golden)) =- (args.next().map(PathBuf::from), args.next().map(PathBuf::from), args.next())- else {- println!("usage: check_gemma4_parity <text.maml> <embed.maml> <golden.json>");- return;- };- let (text_bytes, embed_bytes) = match (std::fs::read(&text), std::fs::read(&embed)) {- (Ok(a), Ok(b)) => (a, b),- (a, b) => {- println!("cannot read the weights: {:?} {:?}", a.err(), b.err());- return;- }- };- let weights = match Weights::parse(&text_bytes, graph::GEMMA4_TEXT) {- Ok(w) => w,- Err(why) => return println!("the text model does not parse: {why}"),- };- let embed_weights = match Weights::parse(&embed_bytes, graph::GEMMA4_EMBED) {- Ok(w) => w,- Err(why) => return println!("the embedding does not parse: {why}"),- };- let golden = match std::fs::read_to_string(&golden) {- Ok(text) => text,- Err(why) => return println!("cannot read the golden: {why}"),- };- let (tokens, want_ids, want_logits) = parse_golden(&golden);- if tokens.is_empty() {- return println!("the golden holds no tokens");- }- println!("tokens {tokens:?}");-- let context = match context::shared() {- Ok(context) => context,- Err(why) => return println!("no Vulkan device: {why}"),- };- match run(&context, &weights, &embed_weights, &tokens) {- Ok(logits) => report(&logits, &want_ids, &want_logits),- Err(why) => println!("the decode failed: {why}"),- }-- // Bisect: where do the two first disagree? Only useful when the logits already failed, but- // cheap enough to always print.- let trace_path = std::env::args().nth(4);- let Some(trace_path) = trace_path else { return };- let Ok(trace) = std::fs::read_to_string(&trace_path) else {- return println!("cannot read {trace_path}");- };- println!();- println!("bisect against the reference's intermediates");- for (label, layers) in [("ple_combined", 0usize), ("l0_out", 1), ("l1_out", 2)] {- let Some(want) = field(&trace, label) else {- println!(" {label:<14} not in the trace file");- continue;- };- match trace_run(&context, &weights, &embed_weights, &tokens, layers) {- Ok((hidden, per_layer)) => {- let got: &[f32] = if label == "ple_combined" { &per_layer } else { &hidden };- println!(" {label:<14} {}", compare(got, &want));- }- Err(why) => println!(" {label:<14} failed: {why}"),- }- }-}--/// Cosine and relative RMS between a device tensor and the reference's.-fn compare(got: &[f32], want: &[f32]) -> String {- if got.len() != want.len() {- return format!("length {} against {}", got.len(), want.len());- }- let dot: f64 = got.iter().zip(want).map(|(a, b)| f64::from(*a) * f64::from(*b)).sum();- let na: f64 = got.iter().map(|a| f64::from(*a) * f64::from(*a)).sum::<f64>().sqrt();- let nb: f64 = want.iter().map(|b| f64::from(*b) * f64::from(*b)).sum::<f64>().sqrt();- let cosine = dot / (na * nb).max(1e-30);- let verdict = if cosine > 0.99 { "ok" } else { "WRONG" };- format!("cosine {cosine:.6} rms {:.4} against {:.4} {verdict}", na / got.len() as f64, nb / want.len() as f64)-}--/// One named array from the trace file.-fn field(text: &str, key: &str) -> Option<Vec<f32>> {- let at = text.find(&format!("\"{key}\""))?;- let rest = &text[at..];- let open = rest.find('[')?;- let close = rest[open..].find(']')?;- Some(rest[open + 1..open + close].split(',').filter_map(|p| p.trim().parse().ok()).collect())-}--/// [`run`] stopping after `layers` layers, returning `(hidden, per_layer)`.-fn trace_run(- context: &Arc<context::Context>,- weights: &Weights,- embed: &Weights,- tokens: &[u32],- layers: usize,-) -> Result<(Vec<f32>, Vec<f32>), String> {- let mode = gemma4::Mode::Trace { layers }.at(TIER);- let mut net =- Reshaped::new(Arc::clone(context), weights, mode, |offsets, mode| gemma4::build(offsets, mode))?;- let reader = embed.reader();- let rotary = weights.reader();- let mut last = (Vec::new(), Vec::new());- for (step, &token) in tokens.iter().enumerate() {- let position = u32::try_from(step).map_err(|_| "a step past u32")?;- let (hidden, per_layer) = gemma4::gather(&reader, token)?;- let angles_local = rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?;- let angles_global =- rotary_row(&rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?;- let at = net.at(mode)?;- at.set_params(StepParams {- prefix: position,- window_start: position.saturating_sub(gemma4::WINDOW - 1),- })?;- let out = at.infer_raw_many(&[&hidden, &per_layer, &angles_local, &angles_global])?;- let mut it = out.into_iter();- last = (it.next().unwrap_or_default(), it.next().unwrap_or_default());- }- Ok(last)-}--/// Feed every token in order and return the last step's logits.-fn run(- context: &Arc<context::Context>,- weights: &Weights,- embed: &Weights,- tokens: &[u32],-) -> Result<Vec<f32>, String> {- let mut net = Reshaped::new(- Arc::clone(context),- weights,- gemma4::Mode::DecodeStep.at(TIER),- |offsets, mode| gemma4::build(offsets, mode),- )?;- let reader = embed.reader();- let rotary = weights.reader();- let mut logits = Vec::new();- for (step, &token) in tokens.iter().enumerate() {- let position = u32::try_from(step).map_err(|_| "a step past u32")?;- if position >= gemma4::MAX_CONTEXT {- return Err(format!("position {position} is past MAX_CONTEXT"));- }- let (hidden, per_layer) = gemma4::gather(&reader, token)?;- let angles_local = rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?;- let angles_global =- rotary_row(&rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?;-- let at = net.at(gemma4::Mode::DecodeStep.at(TIER))?;- // The sliding layers attend `[position - WINDOW + 1, position]`; the full ones want the- // whole prefix. One `window_start` serves both only while the prefix is inside the- // window, which it is for a golden this short - a longer one needs the per-layer window- // this runtime does not carry yet.- at.set_params(StepParams {- prefix: position,- window_start: position.saturating_sub(gemma4::WINDOW - 1),- })?;- let out = at.infer_raw_many(&[&hidden, &per_layer, &angles_local, &angles_global])?;- logits.clear();- for split in out.iter().take(gemma4::HEAD_SPLITS) {- logits.extend_from_slice(split);- }- }- if logits.len() != gemma4::VOCAB as usize {- return Err(format!("{} logits, not {}", logits.len(), gemma4::VOCAB));- }- Ok(logits)-}--/// One position's angles from a rotary table, which is plain fp16.-fn rotary_row(- reader: &modelrunner::weights::Reader<'_>,- index: usize,- width: u32,- position: u32,-) -> Result<Vec<f32>, String> {- let all = reader.fp16(index, &[gemma4::MAX_CONTEXT, width])?;- let from = (position * width) as usize;- all.get(from..from + width as usize)- .map(<[f32]>::to_vec)- .ok_or_else(|| format!("position {position} is past the rotary table"))-}--/// Print the comparison, and say plainly whether it passed.-fn report(got: &[f32], want_ids: &[u32], want_logits: &[f32]) {- let mut order: Vec<u32> = (0..got.len() as u32).collect();- order.sort_by(|&a, &b| got[b as usize].total_cmp(&got[a as usize]));- let top: Vec<u32> = order.iter().copied().take(10).collect();-- println!();- println!(" reference top10 {want_ids:?}");- println!(" device top10 {top:?}");- println!();- println!(" {:>8} {:>12} {:>12}", "id", "reference", "device");- for (rank, &id) in want_ids.iter().enumerate().take(10) {- println!(- " {id:>8} {:>12.4} {:>12.4}",- want_logits.get(rank).copied().unwrap_or(f32::NAN),- got.get(id as usize).copied().unwrap_or(f32::NAN),- );- }- println!();- let argmax_ok = top.first() == want_ids.first();- let overlap = top.iter().filter(|id| want_ids.contains(id)).count();- println!(" argmax {}", if argmax_ok { "MATCHES" } else { "DIFFERS" });- println!(" {overlap} of the reference's top 10 are in the device's top 10");- if argmax_ok && overlap >= 8 {- println!();- println!("PASS: the forward pass agrees with onnxruntime within quantisation noise");- } else {- println!();- println!("FAIL: this is a composition error, not quantisation - the ranking moved");- }-}--/// `{"tokens": [...], "top_ids": [...], "top_logits": [...]}`.-fn parse_golden(text: &str) -> (Vec<u32>, Vec<u32>, Vec<f32>) {- let numbers = |key: &str| -> String {- let Some(at) = text.find(key) else { return String::new() };- let rest = &text[at + key.len()..];- let Some(open) = rest.find('[') else { return String::new() };- let Some(close) = rest[open..].find(']') else { return String::new() };- rest[open + 1..open + close].to_string()- };- let ints = |s: String| -> Vec<u32> {- s.split(',').filter_map(|p| p.trim().parse().ok()).collect()- };- let floats = |s: String| -> Vec<f32> {- s.split(',').filter_map(|p| p.trim().parse().ok()).collect()- };- (- ints(numbers("\"tokens\"")),- ints(numbers("\"top_ids\"")),- floats(numbers("\"top_logits\"")),- )-}
library/ml/src/main/rust/examples/check_gemma4_tokenizer.rs
diff --git a/library/ml/src/main/rust/examples/check_gemma4_tokenizer.rs b/library/ml/src/main/rust/examples/check_gemma4_tokenizer.rsdeleted file mode 100644index 4778477165..0000000000--- a/library/ml/src/main/rust/examples/check_gemma4_tokenizer.rs+++ /dev/null@@ -1,154 +0,0 @@-//! Checks `post::sentencepiece` against real HuggingFace `tokenizers` output for Gemma 4.-//!-//! ```text-//! cargo run --offline --release -p modelrunner --example check_gemma4_tokenizer -- \-//! gemma4_tokenizer.spm1 tok_golden.json-//! ```-//!-//! # Why a golden and not a unit test-//!-//! The merge loop is already unit-tested on a handful of hand-built pieces, and that catches an-//! algorithm that merges in the wrong order. It cannot catch the things that actually differ-//! between two tokenizers of the *same* algorithm: whether whitespace is collapsed, whether a-//! dummy prefix is added, how an unrepresentable byte is spelled, and whether the merge ranks-//! were inverted correctly on the way into the file. Those only show up against the real thing.-//!-//! The samples deliberately include runs of spaces and a code block, because Gemma's normaliser-//! is a bare `Replace(" ", metaspace)` with no trimming - the opposite of what fairseq's models-//! were trained with, and what `Flavour::tidy_whitespace` exists to distinguish.-use std::path::PathBuf;--use modelrunner::post::sentencepiece::{Table, GEMMA};--/// One `{ "text": ..., "ids": [...] }` from the golden file.-struct Case {- text: String,- ids: Vec<u32>,-}--fn main() {- let mut args = std::env::args().skip(1);- let (Some(table_path), Some(golden_path)) =- (args.next().map(PathBuf::from), args.next().map(PathBuf::from))- else {- println!("usage: check_gemma4_tokenizer <table.spm1> <golden.json>");- return;- };- let blob = match std::fs::read(&table_path) {- Ok(bytes) => bytes,- Err(why) => return println!("cannot read {}: {why}", table_path.display()),- };- let table = match Table::parse_with(&blob, GEMMA) {- Ok(table) => table,- Err(why) => return println!("the table does not parse: {why}"),- };- println!("{} pieces, byte fallback {}", table.len(), table.has_byte_fallback());- if !table.has_byte_fallback() {- println!("FAIL: Gemma's vocabulary holds all 256 byte pieces and this one does not");- return;- }-- let golden = match std::fs::read_to_string(&golden_path) {- Ok(text) => text,- Err(why) => return println!("cannot read {}: {why}", golden_path.display()),- };- let cases = parse_golden(&golden);- println!("{} cases", cases.len());- println!();-- // The markers a chat template inserts. `<bos>` is the one the golden exercises; the rest are- // listed because the same call site will need them and an unknown entry is skipped.- let specials = [- "<bos>",- "<eos>",- "<pad>",- "<unk>",- "<|tool>",- "<tool|>",- "<|tool_call>",- "<tool_call|>",- "<|tool_response>",- "<tool_response|>",- ];-- let mut passed = 0;- for case in &cases {- let got = table.encode_with_specials(&case.text, &specials);- if got == case.ids {- passed += 1;- continue;- }- println!("MISMATCH for {:?}", case.text);- println!(" want {:?}", case.ids);- println!(" got {got:?}");- let first = got.iter().zip(&case.ids).position(|(a, b)| a != b).unwrap_or(0);- println!(" first differs at {first}");- }- println!();- println!("{passed} of {} match HuggingFace", cases.len());-- // Round-tripping matters as much as encoding: byte fallback is only useful if `decode` fuses- // the byte pieces back into characters rather than emitting one replacement each.- let mut round_tripped = 0;- for case in &cases {- let text = table.decode(&case.ids);- let want = case.text.trim();- if text == want {- round_tripped += 1;- } else {- println!("ROUND TRIP {:?} -> {:?}", case.text, text);- }- }- println!("{round_tripped} of {} round-trip through decode", cases.len());-}--/// The golden file, parsed without pulling in a JSON crate for one shape.-fn parse_golden(text: &str) -> Vec<Case> {- let mut cases = Vec::new();- let mut rest = text;- while let Some(at) = rest.find("\"text\":") {- rest = &rest[at + 7..];- let Some(text_value) = read_string(&mut rest) else { break };- let Some(at) = rest.find("\"ids\":") else { break };- rest = &rest[at + 6..];- let Some(open) = rest.find('[') else { break };- let Some(close) = rest[open..].find(']') else { break };- let ids = rest[open + 1..open + close]- .split(',')- .filter_map(|piece| piece.trim().parse::<u32>().ok())- .collect();- rest = &rest[open + close..];- cases.push(Case { text: text_value, ids });- }- cases-}--/// The next JSON string in `rest`, advancing past it. Handles the escapes the writer emits.-fn read_string(rest: &mut &str) -> Option<String> {- let open = rest.find('"')?;- let mut out = String::new();- let mut chars = rest[open + 1..].char_indices();- while let Some((at, c)) = chars.next() {- match c {- '"' => {- *rest = &rest[open + 1 + at + 1..];- return Some(out);- }- '\\' => {- let (_, escaped) = chars.next()?;- out.push(match escaped {- 'n' => '\n',- 't' => '\t',- 'r' => '\r',- 'u' => {- let hex: String = (0..4).filter_map(|_| chars.next().map(|(_, c)| c)).collect();- char::from_u32(u32::from_str_radix(&hex, 16).ok()?)?- }- other => other,- });- }- other => out.push(other),- }- }- None-}
library/ml/src/main/rust/examples/check_gemma4_vision_parity.rs
diff --git a/library/ml/src/main/rust/examples/check_gemma4_vision_parity.rs b/library/ml/src/main/rust/examples/check_gemma4_vision_parity.rsdeleted file mode 100644index 9cb476f219..0000000000--- a/library/ml/src/main/rust/examples/check_gemma4_vision_parity.rs+++ /dev/null@@ -1,371 +0,0 @@-//! Runs Gemma 4's vision tower on the GPU and compares it with onnxruntime's.-//!-//! ```text-//! python scripts/ml/gemma4_vision_parity.py vision_encoder_fp16.onnx -o vision_golden.json-//! cargo run --offline --release -p modelrunner --example check_gemma4_vision_parity -- \-//! gemma4_vision.maml vision_golden.json-//! ```-//!-//! # What only this catches-//!-//! `nets::gemma4_vision`'s unit tests check that 637 tensors are declared in the order the-//! converter writes them,
Diff truncated.