Modern Apps git

← Modern-Apps.git

library:ml: Supertonic's duration predictor, and embedding ids past 2048

Commit
f6e0ce3e4700c20383f6b0ae05c3403614832323
Author
vayun-mathur <[email protected]>
When
2026-08-28 14:48 UTC (3 months ago)
Parents
15c9692

Diff

library/ml/src/main/rust/shaders/embed.comp
diff --git a/library/ml/src/main/rust/shaders/embed.comp b/library/ml/src/main/rust/shaders/embed.compindex 8d3b07fb5d..5d523d758f 100644--- a/library/ml/src/main/rust/shaders/embed.comp+++ b/library/ml/src/main/rust/shaders/embed.comp@@ -13,6 +13,10 @@ //! through the arena cannot move an id to its neighbour — 130 is nowhere near the 2048 where //! the gaps between representable integers open up. //!+//! Supertonic's 8,322 symbols and SMaLL-100's 128,112 are past that, so those pass ids as+//! **two lanes** — a `[2, 1, T]` tensor holding `id % 2048` then `id / 2048`, recombined+//! here. `p.in_c` is the lane count.+//! //! `p.in_w` is the table's row count. An id outside it clamps rather than reading past the //! table: a phonemiser that emitted an unknown symbol should mispronounce a word, not sample //! whatever weights follow the embedding.@@ -36,6 +40,10 @@ void main() {     // Round rather than truncate: an id that came back as 41.9997 is 42.     float raw = float(arena[p.in0 + position]);     uint id = uint(max(raw + 0.5, 0.0));+    if (p.in_c == 2u) {+        float high = float(arena[p.in0 + p.out_w + position]);+        id += 2048u * uint(max(high + 0.5, 0.0));+    }     uint rows = p.in_w;     if (id >= rows) {         id = rows - 1u;
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex 03af99d974..2d8fd3c1ed 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -36,6 +36,7 @@ pub mod ppocr_det; pub mod ppocr_rec; pub mod scrfd; pub mod selfie;+pub mod supertonic_duration; pub mod supertonic_vocoder; pub mod u2netp; pub mod vits_dec;@@ -282,6 +283,13 @@ pub enum Kind {     /// tensor, which is exact for the 130 phoneme symbols VITS uses — fp16 holds every     /// integer to 2048. Table at [`Push::weight`], its row count in [`Push::in_w`], and an     /// out-of-range id clamps rather than reading past the table.+    ///+    /// # Vocabularies past 2048+    ///+    /// Above [`EMBED_LANE`] the gaps between representable fp16 integers open up, so a single+    /// id lane would silently land on a neighbouring row — Supertonic has 8,322 symbols and+    /// SMaLL-100 has 128,112. Those arrive **split across two lanes**, `id = lo + 2048 * hi`,+    /// as a `[2, 1, T]` tensor; [`Push::in_c`] carries the lane count. See [`embed_lanes`].     Embed,     /// `x < 0 ? alpha * x : x`, as a standalone pass. 16 uses in Piper's HiFi-GAN vocoder.     ///@@ -651,6 +659,22 @@ pub struct Builder<'a> { /// boundary `.maml` aligns its tensors to. const ALIGN_ELEMS: u32 = 8; +/// The largest integer fp16 holds exactly, and so the width of one embedding id lane.+///+/// Every integer below this has an exact fp16 representation; at 2049 the gaps open to 2 and+/// keep doubling. A table with more rows than this takes its ids as two lanes — see+/// [`Kind::Embed`] and [`embed_lanes`].+pub const EMBED_LANE: u32 = 2048;++/// Ids for [`Builder::embed`] over a table of more than [`EMBED_LANE`] rows, laid out as the+/// `[2, 1, T]` tensor it wants: all the low lanes, then all the high ones.+pub fn embed_lanes(ids: &[u32]) -> Vec<f32> {+    let mut out = Vec::with_capacity(ids.len() * 2);+    out.extend(ids.iter().map(|&id| (id % EMBED_LANE) as f32));+    out.extend(ids.iter().map(|&id| (id / EMBED_LANE) as f32));+    out+}+ impl<'a> Builder<'a> {     /// Start recording a pass. Declare its inputs with [`Builder::input`].     pub fn new(weights: &'a dyn WeightSource) -> Builder<'a> {@@ -1187,16 +1211,28 @@ impl<'a> Builder<'a> {         out     } -    /// An embedding lookup: `out[c][t] = table[id(t)][c]`, over a `[1, 1, T]` id tensor.+    /// An embedding lookup: `out[c][t] = table[id(t)][c]`, over a `[1, 1, T]` id tensor, or a+    /// `[2, 1, T]` one when the table has more than [`EMBED_LANE`] rows.     ///     /// `table` indexes a `[rows, channels]` tensor. The `sqrt(d_model)` scale VITS applies     /// after the lookup belongs in the table, not here; see [`Kind::Embed`].     pub fn embed(&mut self, ids: Id, table: usize, rows: u32, channels: u32) -> Id {         let shape = self.shape_of(ids);-        if shape.c != 1 || shape.h != 1 {-            self.fail(format!(-                "embedding {shape:?}: ids are one per position, so a [1, 1, T] tensor"-            ));+        let lanes = if rows > EMBED_LANE { 2 } else { 1 };+        if shape.c != lanes || shape.h != 1 {+            if lanes == 2 {+                // Refused rather than rounded: a single lane holds ids to 2048 exactly and+                // then starts landing on a neighbouring row, which reads as a plausible+                // wrong word rather than as a failure.+                self.fail(format!(+                    "embedding {shape:?}: {rows} rows is past {EMBED_LANE}, so the ids split \+                     across two lanes as a [2, 1, T] tensor"+                ));+            } else {+                self.fail(format!(+                    "embedding {shape:?}: ids are one per position, so a [1, 1, T] tensor"+                ));+            }         }         if rows == 0 || channels == 0 {             self.fail(format!("an embedding table of {rows} x {channels}"));@@ -1823,6 +1859,8 @@ impl<'a> Builder<'a> {                         // clamps against it so an unknown symbol mispronounces a word                         // rather than reading whatever follows the embedding.                         in_w: *rows,+                        // Id lanes, 1 or 2. Not the output's channel count.+                        in_c: shape(*ids).c,                         out_c: so.c,                         out_h: so.h,                         out_w: so.w,@@ -2136,9 +2174,9 @@ pub(crate) mod tests {                         Kind::AttnApply | Kind::AttnApplyRelative => {                             vec![(push.in0, push.group * push.out_w * push.out_w), (push.in1, dense)]                         }-                        // One id per position, so the read is `out_w` and not `dense` —-                        // `dense` here would be the *table's* row count.-                        Kind::Embed => vec![(push.in0, push.out_w)],+                        // One id per position per lane, so the read is `in_c * out_w` and+                        // not `dense` - `in_w` here is the *table's* row count.+                        Kind::Embed => vec![(push.in0, push.in_c * push.out_w)],                         // As `Conv`: the whole input plane, whatever the kernel touches.                         Kind::ConvInt8 => vec![(push.in0, dense)],                         // count is tiles here, so the read span is the input plane.
library/ml/src/main/rust/src/nets/reference.rs
diff --git a/library/ml/src/main/rust/src/nets/reference.rs b/library/ml/src/main/rust/src/nets/reference.rsindex 5632b211b9..db96373b20 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -535,14 +535,18 @@ impl Reference {         Ok(())     } -    /// `out[c][t] = table[id(t)][c]`, with the id read out of the arena as fp16.+    /// `out[c][t] = table[id(t)][c]`, with the id read out of the arena as fp16, in one lane+    /// or in two (`lo + 2048 * hi`) for a table past `EMBED_LANE` rows.     fn embed(&mut self, p: &Push) -> Result<(), String> {         let rows = p.in_w;         if rows == 0 {             return Err("an embedding table with no rows".into());         }         for position in 0..p.out_w {-            let raw = self.load(p.in0, position)?;+            let mut raw = self.load(p.in0, position)?;+            if p.in_c == 2 {+                raw += 2048.0 * self.load(p.in0, p.out_w + position)?;+            }             // Round rather than truncate, and clamp: an unknown symbol should mispronounce             // a word rather than read past the table.             let id = ((raw + 0.5).max(0.0) as u32).min(rows - 1);@@ -1042,8 +1046,8 @@ fn uniform(state: &mut u32) -> f32 { #[cfg(test)] mod tests {     use super::super::{-        mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_vocoder, u2netp, vits_dec, vits_enc, vits_flow, Act,-        Builder,+        embed_lanes, mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration, supertonic_vocoder,+        u2netp, vits_dec, vits_enc, vits_flow, Act, Builder, EMBED_LANE,     };     use super::*; @@ -2039,6 +2043,46 @@ mod tests {         assert!(error.contains("one per position"), "{error}");     } +    #[test]+    fn a_two_lane_id_reaches_a_row_fp16_cannot_name() {+        // Supertonic has 8,322 symbols, so ids past 2048 arrive as `lo + 2048 * hi`. Each+        // row here carries its own index back as that same pair, both halves exact in fp16,+        // so a lane that was dropped, swapped or scaled shows up as the wrong row.+        let rows = 8322u32;+        let mut table = Vec::with_capacity(rows as usize * 2);+        for row in 0..rows {+            table.push((row / EMBED_LANE) as f32);+            table.push((row % EMBED_LANE) as f32);+        }+        let ids = [0u32, 1, 2047, 2048, 2049, 4096, 8321];+        let got = one(+            Shape::new(2, 1, ids.len() as u32),+            &embed_lanes(&ids),+            &[(vec![rows, 2], table)],+            |b, x| b.embed(x, 0, rows, 2),+        );+        let want: Vec<f32> = ids+            .iter()+            .map(|&id| (id / EMBED_LANE) as f32)+            .chain(ids.iter().map(|&id| (id % EMBED_LANE) as f32))+            .collect();+        close(&got, &want);+    }++    #[test]+    fn a_big_table_refuses_ids_in_one_lane() {+        // The failure this guards is silent otherwise: id 4000 in a single fp16 lane comes+        // back as 4000 exactly, but 4001 comes back as 4000, so the net reads a plausible+        // wrong row instead of failing.+        let rows = EMBED_LANE + 1;+        let source = Given::new(&[(vec![rows, 1], vec![0.0; rows as usize])]).expect("the fixture lays out");+        let mut b = Builder::new(&source);+        let ids = b.input(Shape::new(1, 1, 4));+        let out = b.embed(ids, 0, rows, 1);+        let error = b.finish(&[out]).expect_err("one lane for a big table");+        assert!(error.contains("two lanes"), "{error}");+    }+     #[test]     fn a_relative_score_map_adds_a_banded_term_from_its_table() {         // Q = K = 1 everywhere over four positions, two channels, one head. The content@@ -2416,6 +2460,36 @@ mod tests {             println!("supertonic_voc at {width} frames: wrote {} values", samples.len());             return;         }+        if graph == "supertonic_dp" {+            let path = std::env::var("PARITY_MAML").expect("PARITY_MAML");+            let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{path}: {e}"));+            let weights =+                crate::weights::Weights::parse(&bytes, crate::weights::graph::SUPERTONIC_DP)+                    .expect("the duration asset parses");+            let plan = supertonic_duration::build(&weights, width).expect("the predictor builds");+            let raw = std::fs::read(dir.join("style.f32")).expect("the style");+            let style: Vec<f32> = raw+                .chunks_exact(4)+                .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))+                .collect();+            // The sentence token leads the sequence, and the ids go past 2048 so they travel as+            // two lanes. Both are the caller's job in production too.+            let mut ids = vec![supertonic_duration::SENTENCE_TOKEN];+            ids.extend(input.iter().map(|&v| v as u32));+            let lanes = super::super::embed_lanes(&ids);+            let outputs =+                run_multi(&plan, weights.data(), &[&lanes, &style]).expect("the predictor runs");+            let encoded = outputs.first().expect("the encoder output");+            write(&dir.join("reference.f32"), encoded);+            let log_seconds = outputs[1][0];+            println!(+                "supertonic_dp at {width} chars: wrote {} values, {:.6} seconds ({} frames)",+                encoded.len(),+                supertonic_duration::seconds(log_seconds),+                supertonic_duration::latent_frames(supertonic_duration::seconds(log_seconds)),+            );+            return;+        }         if graph == "vits_dp" {             let path = std::env::var("PARITY_MAML").expect("PARITY_MAML");             let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{path}: {e}"));
library/ml/src/main/rust/src/nets/supertonic_duration.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_duration.rs b/library/ml/src/main/rust/src/nets/supertonic_duration.rsnew file mode 100644index 0000000000..a2b5a3b044--- /dev/null+++ b/library/ml/src/main/rust/src/nets/supertonic_duration.rs@@ -0,0 +1,478 @@+//! Supertonic 3's duration predictor: text to one number, the utterance's length in seconds.+//!+//! # What it is+//!+//! The smallest of the four nets — 1086 ONNX nodes and 864,706 parameters — and the first to+//! run, because everything after it is shaped by the answer. A character embedding, six+//! ConvNeXt blocks, two layers of relative-position attention, and a two-layer head that+//! reduces the whole sentence to a single scalar. [`latent_frames`] turns that into the length+//! the sampler and the vocoder are built for.+//!+//! # The sentence token, which is why the sequence is `T + 1`+//!+//! The export holds a learned `[1, 64, 1]` `sentence_token` and **prepends** it to the+//! embedded text, then reads position 0 back out at the end (`/sentence_encoder/Slice_1`) — a+//! CLS token, so the reduction is a slice rather than a pool. There is no op here for+//! concatenating along the sequence, and none is needed: the converter appends the token to the+//! embedding table as row [`SENTENCE_TOKEN`], and the caller prepends that id. The lookup then+//! produces `concat(token, embedded)` for free.+//!+//! The token row is the *last* row, so [`super::Kind::Embed`]'s out-of-range clamp lands on it+//! rather than on a character. That is only safe because the text front end drops unmapped+//! codepoints instead of emitting an out-of-range id.+//!+//! # Three things checked against the export rather than carried over from the vocoder+//!+//! **The padding is symmetric, not causal.** `nets::supertonic_vocoder` puts the whole+//! `dilation * (kernel - 1)` on the left, and assuming the same here would be wrong: the+//! `Pad` before each depthwise convolution is `[0, 0, 2, 0, 0, 2]`, two each side of a 5-tap at+//! dilation 1. Still `mode=edge`, so [`Builder::edge_padding`] is still right.+//!+//! **The layer scales are here too.** Each block ends in a `Mul` by a `[1, 64, 1]` gamma — 384+//! parameters of 864,706, invisible in any count check. The converter folds all six into their+//! block's `pwconv2`, which is a 1x1 and so has no border to get wrong.+//!+//! **The mask is not needed.** 58 `Mul` nodes multiply by the padding mask, which for one+//! utterance is all ones — including the leading one the token's position gets. The same+//! argument as [`super::vits_enc`], and it is why `text_mask` is not an input here.+//!+//! # The whole net is one plan+//!+//! Including the head. Its `Gemm [128, 192]` reads the sliced position and the style+//! concatenated, which is [`Builder::concat`] of a `[64, 1, 1]` and a `[128, 1, 1]`, and both+//! `Gemm`s are then 1x1 convolutions over a single position. The `Slice` is a 1x1 convolution+//! **strided by the sequence length**, which reads position 0 and nothing else. Only the final+//! `Exp` is left for the host, on one scalar: see [`seconds`].+//!+//! # Measured parity+//!+//! Against onnxruntime on `/sentence_encoder/Add_output_0` at 24 characters: correlation+//! 0.99999959, max 0.008547 on a tensor whose own values reach 3.21. That is about four fp16+//! ULPs at that magnitude and *above* the 0.001743 the script's fp16-weights bar reports,+//! because the bar rounds weights only and this runtime holds activations in fp16 as well —+//! through six residual blocks and ten layer norms. The predicted duration itself agrees to+//! 0.12%: 1.556031 seconds against 1.557878, which is the same [`latent_frames`] either way.++use super::{Act, Builder, Id, Plan, Shape, WeightSource};++/// Characters in the embedding table, from `onnx/unicode_indexer.json`'s 8,321 mapped+/// codepoints plus the unused row 0.+pub const SYMBOLS: u32 = 8322;++/// The id of the appended `sentence_token` row. See the module docs.+pub const SENTENCE_TOKEN: u32 = SYMBOLS;++/// Rows the `.maml`'s embedding table holds: the characters and the sentence token.+pub const TABLE_ROWS: u32 = SYMBOLS + 1;++/// Channels throughout the sentence encoder. `char_emb_dim` and `hidden_channels`.+pub const D_MODEL: u32 = 64;++/// The ConvNeXt widening, and the attention feed-forward's width. `intermediate_dim` and+/// `filter_channels`, which are the same 256 here.+pub const INNER: u32 = 256;++/// Attention heads, so `D_MODEL / HEADS` is 32 — which is also the relative table's width.+pub const HEADS: u32 = 2;++/// Entries in each attention layer's relative position table: `2 * window + 1` at+/// `window_size` 4, as in [`super::vits_enc`].+pub const OFFSETS: u32 = 9;++/// ConvNeXt blocks.+pub const BLOCKS: usize = 6;++/// Relative-attention layers.+pub const ATTN_LAYERS: usize = 2;++/// The style vector's width: `n_style * style_dim`, 8 by 16, flattened.+pub const STYLE: u32 = 128;++/// The predictor head's inner width. `hdim`.+pub const HIDDEN: u32 = 128;++/// The depthwise kernel width, `ksz`. Dilation is 1 in all six blocks.+const KERNEL: u32 = 5;++/// The epsilon in all ten layer norms.+const EPSILON: f32 = 1e-5;++/// Tensors the `.maml` must hold.+///+/// The embedding table (1), six blocks of eight (48), two attention layers of eighteen (36),+/// `proj_out` (2, the second a synthesised zero bias), the head's first `Gemm` (2), its PReLU+/// slope (1) and its second `Gemm` (2).+pub const TENSORS: usize = 92;++/// Latent frames for an utterance of `seconds`, which is what the sampler and the vocoder are+/// built for.+///+/// One frame is [`super::supertonic_vocoder::SAMPLES_PER_FRAME`] samples at+/// [`super::supertonic_vocoder::SAMPLE_RATE`]. Verified against onnxruntime at 54, 55 and 108.+pub fn latent_frames(seconds: f32) -> u32 {+    let per_frame = super::supertonic_vocoder::SAMPLES_PER_FRAME as f32;+    let frames = seconds * super::supertonic_vocoder::SAMPLE_RATE as f32 / per_frame;+    frames.round().max(1.0) as u32+}++/// The export's trailing `Exp`, on the plan's one output value.+///+/// A single transcendental on a single scalar, which is not worth a shader or a `Kind`.+pub fn seconds(log_seconds: f32) -> f32 {+    log_seconds.exp()+}++/// Hands out `.maml` tensor indices in the order the layers appear.+struct Layers {+    next: usize,+}++impl Layers {+    /// A weight and the bias after it.+    fn take(&mut self) -> usize {+        let index = self.next;+        self.next += 2;+        index+    }++    /// A lone tensor: the embedding table, a relative position table, a PReLU slope.+    fn take_one(&mut self) -> usize {+        let index = self.next;+        self.next += 1;+        index+    }+}++/// A `1 x 1` convolution, which every projection and both head `Gemm`s are.+fn point(b: &mut Builder, l: &mut Layers, x: Id, out: u32, act: Act) -> Id {+    b.conv(x, l.take(), out, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, act)+}++/// The depthwise convolution along the sequence, padded symmetrically so the length holds.+fn depthwise(b: &mut Builder, l: &mut Layers, x: Id) -> Id {+    let each = (KERNEL - 1) / 2;+    b.conv(+        x,+        l.take(),+        D_MODEL,+        (1, KERNEL),+        (1, 1),+        (1, 1),+        // (top, left, bottom, right). Two each side, not four on the left: this net's `Pad`+        // nodes are symmetric where the vocoder's are causal.+        (0, each, 0, each),+        D_MODEL,+        Act::None,+    )+}++/// Build the predictor for an utterance of `chars` characters.+///+/// Two inputs, in this order: the character ids as the two lanes+/// [`super::Kind::Embed`] wants over `chars + 1` positions — [`SENTENCE_TOKEN`] first — and the+/// voice's `style_dp` flattened to `[128, 1, 1]`. Two outputs: the sentence encoder's+/// `[64, 1, chars + 1]` state, which is the tensor worth checking for parity, and the one value+/// [`seconds`] exponentiates.+pub fn build(weights: &dyn WeightSource, chars: u32) -> Result<Plan, String> {+    if chars == 0 {+        return Err("a duration pass over no characters".into());+    }+    // The sentence token leads the sequence. See the module docs.+    let positions = chars.checked_add(1).ok_or("an utterance longer than an index can hold")?;++    let l = &mut Layers { next: 0 };+    let mut builder = Builder::new(weights);+    let b = &mut builder;+    // Every padded convolution here replicates its border.+    b.edge_padding();++    let ids = b.input(Shape::new(2, 1, positions));+    let style = b.input(Shape::new(STYLE, 1, 1));+    let mut x = b.embed(ids, l.take_one(), TABLE_ROWS, D_MODEL);++    for _ in 0..BLOCKS {+        let along = depthwise(b, l, x);+        let normed = b.layer_norm(along, l.take(), EPSILON);+        let widened = point(b, l, normed, INNER, Act::Gelu);+        // `pwconv2` carries the block's layer scale, folded in by the converter.+        let narrowed = point(b, l, widened, D_MODEL, Act::None);+        x = b.add(x, narrowed);+    }+    // The attention encoder is skipped around as a whole, not just per layer.+    let convnext = x;++    for _ in 0..ATTN_LAYERS {+        let q = point(b, l, x, D_MODEL, Act::None);+        let k = point(b, l, x, D_MODEL, Act::None);+        let v = point(b, l, x, D_MODEL, Act::None);+        let scores = b.attn_scores_relative(q, k, HEADS, l.take_one(), OFFSETS);+        let probs = b.softmax(scores);+        let mixed = b.attn_apply_relative(probs, v, HEADS, l.take_one(), OFFSETS);+        let attended = point(b, l, mixed, D_MODEL, Act::None);+        // Post-norm, as in `vits_enc`: the residual is added first and normalised after.+        let residual = b.add(x, attended);+        x = b.layer_norm(residual, l.take(), EPSILON);++        // Both feed-forward convolutions are 1x1 here, unlike VITS's three-wide pair.+        let inner = point(b, l, x, INNER, Act::Relu);+        let projected = point(b, l, inner, D_MODEL, Act::None);+        let residual = b.add(x, projected);+        x = b.layer_norm(residual, l.take(), EPSILON);+    }+    let encoded = b.add(convnext, x);++    // `Slice_1` and `proj_out` at once: a 1x1 convolution strided by the whole sequence reads+    // position 0 and produces one position, which is what the CLS reduction is.+    let leading = b.conv(+        encoded,+        l.take(),+        D_MODEL,+        (1, 1),+        (1, positions),+        (1, 1),+        (0, 0, 0, 0),+        1,+        Act::None,+    );++    let joined = b.concat(&[leading, style]);+    // The head's PReLU has one shared slope in the export, which the converter widens to a+    // value per channel.+    let slope = l.next + 2;+    let hidden = point(b, l, joined, HIDDEN, Act::PRelu(slope));+    l.take_one();+    let log_seconds = point(b, l, hidden, 1, Act::None);++    if l.next != TENSORS {+        return Err(format!("the forward pass claims {} tensors, not {TENSORS}", l.next));+    }+    builder.finish(&[encoded, log_seconds])+}++#[cfg(test)]+mod tests {+    use super::super::tests::{assert_no_aliasing, Shapes};+    use super::super::{Kind, Op};+    use super::*;++    /// A short sentence. Long enough that the relative band is interior somewhere.+    const CHARS: u32 = 24;++    fn plan(chars: u32) -> (Shapes, Plan) {+        let source = Shapes::new(TENSORS);+        let plan = build(&source, chars).expect("the predictor builds");+        (source, plan)+    }++    #[test]+    fn the_pass_reads_every_tensor_in_the_file_exactly_once() {+        let (source, _) = plan(CHARS);+        let asked = source.asked.borrow();+        assert_eq!(asked.len(), TENSORS);+        let mut indices: Vec<usize> = asked.iter().map(|(i, _)| *i).collect();+        indices.sort_unstable();+        assert_eq!(indices, (0..TENSORS).collect::<Vec<usize>>());+    }++    #[test]+    fn the_tensor_table_matches_the_export() {+        // The export's initializers total 864,706 parameters. Three differences, each derived+        // rather than guessed:+        //+        //   - the six `[1, 64, 1]` layer scales fold into their `pwconv2`:        -384+        //   - `proj_out` has no bias in the export, so a zero one is synthesised:  +64+        //   - the head PReLU's single shared slope is widened to one per channel: +127+        //+        // `sentence_token` is not a difference: its 64 values move from a standalone tensor+        // into the embedding table's last row, so the total is unchanged either way.+        let (source, _) = plan(CHARS);+        let total: u64 = source+            .asked+            .borrow()+            .iter()+            .map(|(_, dims)| dims.iter().map(|&d| d as u64).product::<u64>())+            .sum();+        assert_eq!(total, 864_706 - 384 + 64 + 127);+        // And spelled out, so a reordering that preserved the sum would still be caught.+        assert_eq!(total, 864_513);+    }++    #[test]+    fn the_sequence_is_one_longer_than_the_text() {+        // The sentence token leads it. A net built for `chars` positions instead would run,+        // produce a number of the right magnitude, and read the wrong position at the end.+        let (_, plan) = plan(CHARS);+        let shapes: Vec<Shape> = plan.inputs.iter().map(|b| b.shape).collect();+        assert_eq!(shapes, vec![Shape::new(2, 1, CHARS + 1), Shape::new(STYLE, 1, 1)]);+        let outputs: Vec<Shape> = plan.outputs.iter().map(|b| b.shape).collect();+        assert_eq!(+            outputs,+            vec![Shape::new(D_MODEL, 1, CHARS + 1), Shape::new(1, 1, 1)]+        );+    }++    #[test]+    fn the_ids_arrive_in_two_lanes_because_the_table_is_past_2048() {+        // 8,323 rows against fp16's 2,048 exact integers. A single-lane id tensor would make+        // every character past 2048 read a neighbouring row — plausible text, wrong duration.+        let (_, plan) = plan(CHARS);+        const _: () = assert!(TABLE_ROWS > super::super::EMBED_LANE);+        assert_eq!(plan.inputs[0].shape.c, 2);+        let lanes = plan+            .ops+            .iter()+            .filter_map(|op| match op {+                Op::Dispatch { kind: Kind::Embed, push, .. } => Some((push.in_c, push.in_w)),+                _ => None,+            })+            .collect::<Vec<_>>();+        assert_eq!(lanes, vec![(2, TABLE_ROWS)]);+    }++    #[test]+    fn the_depthwise_convolutions_pad_symmetrically_and_replicate() {+        // Two each side of a 5-tap, not four on the left. The vocoder is the other way round,+        // and copying it here correlated at 0.02 there — the same mistake in reverse.+        let (_, plan) = plan(CHARS);+        let mut seen = 0;+        for (step, op) in plan.ops.iter().enumerate() {+            if let Op::Dispatch { kind: Kind::Conv, push, .. } = op {+                if push.group == D_MODEL {+                    assert_eq!(push.kw, KERNEL, "step {step}");+                    assert_eq!(push.pad_l, (KERNEL - 1) / 2, "step {step}");+                    assert_eq!(push.dil_w, 1, "step {step}");+                    seen += 1;+                }+                assert_ne!(push.pad_edge, 0, "step {step} pads with zeros");+            }+        }+        assert_eq!(seen, BLOCKS);+    }++    #[test]+    fn the_reduction_reads_position_zero_and_no_other() {+        // `proj_out` is strided by the whole sequence, so it produces one position from+        // position 0. A stride of one would produce `T + 1` of them and the concat that+        // follows would refuse the shape — which is the point of doing it this way.+        let (_, plan) = plan(CHARS);+        let strided: Vec<&super::super::Push> = plan+            .ops+            .iter()+            .filter_map(|op| match op {+                Op::Dispatch { kind: Kind::Conv, push, .. } if push.stride_w > 1 => Some(push),+                _ => None,+            })+            .collect();+        assert_eq!(strided.len(), 1);+        assert_eq!(strided[0].stride_w, CHARS + 1);+        assert_eq!(strided[0].out_w, 1);+        assert_eq!(strided[0].out_c, D_MODEL);+    }++    #[test]+    fn the_head_joins_the_sentence_with_the_style() {+        // 64 from position 0 and 128 from `style_dp`, in that order: the export's+        // `/predictor/Concat_2` puts the text first, and swapping them would read the style+        // through the text's weights at exactly the right total width.+        let (_, plan) = plan(CHARS);+        let concats = plan+            .ops+            .iter()+            .filter(|op| matches!(op, Op::Copy { .. }))+            .count();+        // A concat lowers to one copy per part.+        assert!(concats >= 2, "{concats} copies for a two-part concat");+        let widths: Vec<u32> = plan+            .ops+            .iter()+            .filter_map(|op| match op {+                Op::Dispatch { kind: Kind::Conv | Kind::ConvPoint, push, .. }+                    if push.out_w == 1 =>+                {+                    Some(push.in_c)+                }+                _ => None,+            })+            .collect();+        assert_eq!(widths, vec![D_MODEL, D_MODEL + STYLE, HIDDEN]);+    }++    #[test]+    fn the_op_inventory_is_six_convnext_blocks_and_two_attention_layers() {+        let (_, plan) = plan(CHARS);+        let mut counts = std::collections::BTreeMap::new();+        for op in &plan.ops {+            if let Op::Dispatch { kind, .. } = op {+                *counts.entry(super::super::tests::name_of(*kind)).or_insert(0) += 1;+            }+        }+        // Per block a depthwise and two 1x1s; per attention layer q/k/v/o and two+        // feed-forward 1x1s; then `proj_out` and the head's two `Gemm`s.+        let convolutions = BLOCKS * 3 + ATTN_LAYERS * 6 + 3;+        assert_eq!(counts.get("Conv"), Some(&convolutions), "{counts:?}");+        assert_eq!(counts.get("Embed"), Some(&1), "{counts:?}");+        assert_eq!(counts.get("AttnScoresRelative"), Some(&ATTN_LAYERS), "{counts:?}");+        assert_eq!(counts.get("AttnApplyRelative"), Some(&ATTN_LAYERS), "{counts:?}");+        assert_eq!(counts.get("Softmax"), Some(&ATTN_LAYERS), "{counts:?}");+        // Six block residuals, two per attention layer, and the skip around the whole+        // attention encoder.+        assert_eq!(counts.get("Add"), Some(&(BLOCKS + ATTN_LAYERS * 2 + 1)), "{counts:?}");+        assert_eq!(counts.get("LayerNorm"), Some(&(BLOCKS + ATTN_LAYERS * 2)), "{counts:?}");+        // No pool: the reduction is the strided convolution, not an average over the+        // sentence. A `GlobalAvgPool` here would be the wrong model producing a plausible+        // number.+        assert_eq!(counts.get("GlobalAvgPool"), None, "{counts:?}");+        assert_eq!(counts.len(), 7, "{counts:?}");+    }++    #[test]+    fn a_one_character_utterance_still_builds() {+        // Two positions then, the token and the character. The relative band is entirely+        // outside the sequence, which the taps skip.+        let (_, plan) = plan(1);+        assert_eq!(plan.outputs[1].shape, Shape::new(1, 1, 1));+    }++    #[test]+    fn an_empty_utterance_is_refused() {+        let source = Shapes::new(TENSORS);+        let error = build(&source, 0).expect_err("no characters");+        assert!(error.contains("no characters"), "{error}");+    }++    #[test]+    fn a_duration_becomes_the_latent_length_the_vocoder_was_measured_at() {+        // 3072 samples a frame at 44.1 kHz, so a frame is 69.66 ms. The three lengths in+        // `supertonic_vocoder`'s docs were measured against onnxruntime.+        assert_eq!(latent_frames(54.0 * 3072.0 / 44_100.0), 54);+        assert_eq!(latent_frames(55.0 * 3072.0 / 44_100.0), 55);+        assert_eq!(latent_frames(108.0 * 3072.0 / 44_100.0), 108);+        // And a duration too short to fill a frame still gets one, rather than a plan over+        // nothing that `supertonic_vocoder::build` would refuse.+        assert_eq!(latent_frames(0.001), 1);+    }++    #[test]+    fn the_tail_exponentiates() {+        // The export's `Exp`, kept on the host. `log(2)` seconds out is two seconds.+        assert!((seconds(std::f32::consts::LN_2) - 2.0).abs() < 1e-6);+    }++    #[test]+    fn no_op_reads_a_region_of_the_arena_that_it_also_writes() {+        let (_, plan) = plan(CHARS);+        assert_no_aliasing(&plan);+    }++    #[test]+    fn the_arena_is_bounded_at_a_long_sentence() {+        // Attention is quadratic in the character count, and unlike phonemes these are+        // characters: 24 is a phrase and 400 is a long sentence.+        for chars in [CHARS, 400] {+            let (_, plan) = plan(chars);+            let mib = plan.arena_elems as f32 * 2.0 / (1024.0 * 1024.0);+            println!("supertonic_duration at {chars} chars: {mib:.2} MiB");+            assert!(mib < 64.0, "{chars} chars wants {mib} MiB");+        }+    }+}
library/ml/src/main/rust/src/weights.rs
diff --git a/library/ml/src/main/rust/src/weights.rs b/library/ml/src/main/rust/src/weights.rsindex 723b4c68a8..168582f46f 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -75,6 +75,8 @@ pub mod graph {     pub const VITS_DP: u32 = 10;     /// Supertonic 3's ConvNeXt vocoder. See [`crate::nets::supertonic_vocoder`].     pub const SUPERTONIC_VOC: u32 = 11;+    /// Supertonic 3's duration predictor. See [`crate::nets::supertonic_duration`].+    pub const SUPERTONIC_DP: u32 = 12; }  /// One tensor's entry in the table: where it is and what shape it is.
scripts/ml/maml_convert.py
diff --git a/scripts/ml/maml_convert.py b/scripts/ml/maml_convert.pyindex 1d193a690a..e64bfacd2b 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -112,6 +112,7 @@ GRAPHS = {     "vits_flow": 9,     "vits_dp": 10,     "supertonic_voc": 11,+    "supertonic_dp": 12, }  # SHA-256 over the ordered layer table (see `layer_table_digest`). Regenerate with@@ -128,6 +129,7 @@ EXPECTED_DIGEST = {     "vits_flow": "38cecda81bcfd4eb98782395905ddbe4637aa7f55fecb2de996d09fc530e2e6d",     "vits_dp": "d02a6e28700823af95cbeeeb2b40d77e531f90086599deb3f840ce9a2a57a494",     "supertonic_voc": "64e3a3437fa8f889fb679a5e08553ba7392c05a32cd844a0d2340698372a0071",+    "supertonic_dp": "a294dac3e0fa1acf03d5a483b96782190a626c6adbc517969592ec6a888e15cd", }  # Graphs that are one **module** of a larger export, keyed by the node-name prefix that
scripts/ml/onnx_parity.py
diff --git a/scripts/ml/onnx_parity.py b/scripts/ml/onnx_parity.pyindex 97d4ca57b7..13f47ba227 100644--- a/scripts/ml/onnx_parity.py+++ b/scripts/ml/onnx_parity.py@@ -59,6 +59,10 @@ PROBE = {     "vits_flow": None,     "vits_dp": None,     "supertonic_voc": None,+    # The sentence encoder's output, before the CLS slice. The graph's own output is a single+    # scalar, and a correlation over one value is not a number - this is where all but 25k of+    # the parameters are, and it is `[64, T + 1]` so a structural error has nowhere to hide.+    "supertonic_dp": "/sentence_encoder/Add_output_0", }  # Graphs that are one module of a larger export, and have to be cut out of it before they can@@ -88,6 +92,8 @@ SUBGRAPH = {     # runs would not agree with each other, let alone with the runtime.     # A whole file, not a module: no `first`, so nothing is extracted. 144 latent channels.     "supertonic_voc": {"channels": 144},+    # Also a whole file, but its input is character ids rather than a latent, so it is fed like+    # `vits_enc` below rather than through `cut`.     "vits_dp": {         "first": "/dp/pre/Conv",         "channels": 192,@@ -206,6 +212,20 @@ def main():             "scales": np.array([0.667, 1.0, 0.8], dtype=np.float32),         }         x = ids.astype(np.float32)+    elif args.graph == "supertonic_dp":+        # Character ids and a voice's style. The ids go past 2048, where fp16 stops holding+        # every integer, so the runtime reads them as two lanes - which is the whole reason+        # `embed_lanes` exists. The `[1, 8, 16]` style flattens row-major to 128.+        rng = np.random.default_rng(20240827)+        ids = rng.integers(0, 8322, size=(1, args.width), dtype=np.int64)+        style = rng.standard_normal((1, 8, 16)).astype(np.float32)+        feed = {+            "text_ids": ids,+            "style_dp": style,+            "text_mask": np.ones((1, 1, args.width), dtype=np.float32),+        }+        x = ids.astype(np.float32)+        style.tofile(os.path.join(work, "style.f32"))     else:         height = 48 if args.graph == "ppocr_rec" else args.width         # Deterministic and free of transcendentals, so both sides read identical bytes.@@ -251,7 +271,13 @@ def main():     bound = np.ascontiguousarray(         quantised.T if args.graph == "ppocr_rec" else quantised     ).flatten()-    print(f"{args.graph} at {args.width} wide, tensor {probe}:")+    # The tensor's own scale, because "max 0.008" means nothing on its own: the bar measures+    # fp16 *weights* against fp32 activations, and this runtime holds activations in fp16 too,+    # so a difference of order `eps * |tensor|` is the format rather than a bug.+    print(+        f"{args.graph} at {args.width} wide, tensor {probe}: "+        f"|values| max {np.abs(want).max():.4f}"+    )     report("fp16 weights alone (the bar)", want, bound)     report("the runtime", want, got) 
scripts/ml/supertonic_fold.py
diff --git a/scripts/ml/supertonic_fold.py b/scripts/ml/supertonic_fold.pyindex 74b55d2459..171897fa55 100644--- a/scripts/ml/supertonic_fold.py+++ b/scripts/ml/supertonic_fold.py@@ -1,5 +1,5 @@ #!/usr/bin/env python3-"""Supertonic 3's vocoder ONNX to `.maml`, folding its three per-channel affines away.+"""Supertonic 3's ONNX nets to `.maml`, folding their per-channel affines away.  `nets::supertonic_vocoder` is a hardcoded forward pass of convolutions, layer norms, GELUs and residual adds — and nothing else. The export has three per-channel affines that are not any of@@ -28,8 +28,26 @@ border supplies `a x_border + b`, which is what the fold assumes, so it holds ev * `head/layer2` has no bias in the export. A zero one is synthesised, as `maml_convert` already   does for `vits_dec`. +# The duration predictor++`--graph supertonic_dp` collects `duration_predictor.onnx` instead, which needs three fixes of+its own rather than the vocoder's three:++    sentence_token [1, 64, 1]  -> appended to the embedding table as its last row+    block gamma [1, 64, 1]     -> folds into that block's `pwconv2`+    proj_out                   -> a zero bias is synthesised++Prepending a learned token to the sequence is a `Concat` this runtime has no op for along the+sequence axis, and needs none: the token becomes row 8322 of the table and the caller prepends+that id. See `nets::supertonic_duration`.++Unlike the vocoder this graph is **not** entirely edge-padded — twelve of its eighteen `Pad`s are+the relative-attention skew and are `constant`. What matters is that every pad feeding a+*convolution* replicates, which is checked separately.+ Usage:     ./scripts/ml/supertonic_fold.py vocoder.onnx --graph supertonic_voc -o vocoder.maml+    ./scripts/ml/supertonic_fold.py duration_predictor.onnx --graph supertonic_dp -o dp.maml """  import argparse@@ -48,6 +66,14 @@ import maml_convert  # noqa: E402  (needs the path above) CHANNELS = 512 INNER = CHANNELS * 4 +# The duration predictor's, and the counts `nets::supertonic_duration` hardcodes.+DP_CHANNELS = 64+DP_INNER = 256+DP_BLOCKS = 6+DP_ATTN_LAYERS = 2+DP_HIDDEN = 128+DP_PREFIX = "tts.dp.sentence_encoder"+  def constants(graph):     """Every initializer and `Constant` node output, by name."""@@ -78,6 +104,31 @@ def edge_padded(graph):     return modes == {"edge"}  +def convolutions_edge_padded(graph):+    """Whether every `Pad` that feeds a convolution replicates its border.++    Laxer than [`edge_padded`], and it has to be: the duration predictor's relative-attention+    skew spends twelve `constant` pads on `Slice`s and `Reshape`s, which are not convolutions and+    are not transcribed. The six that matter are the depthwise ones.+    """+    consumers = {}+    for node in graph.node:+        for name in node.input:+            consumers.setdefault(name, []).append(node)+    for node in graph.node:+        if node.op_type != "Pad":+            continue+        if not any(c.op_type == "Conv" for c in consumers.get(node.output[0], [])):+            continue+        mode = "constant"+        for attribute in node.attribute:+            if attribute.name == "mode":+                mode = attribute.s.decode()+        if mode != "edge":+            return False+    return True++ def fold_into(weight, bias, scale, shift):     """`conv(scale * x + shift)` as a convolution on `x`. @@ -237,6 +288,131 @@ def collect(graph):     return layers, tensors  +def collect_duration(graph):+    """The duration predictor's layers and tensors, folded, in the order the Rust reads them.++    Driven by the export's parameter *names* rather than by graph order. The vocoder is a plain+    stack where walking the nodes lands each tensor in the right slot; this graph interleaves two+    relative-position tables, four masks and a skew per attention layer, and naming each tensor is+    both shorter and checkable against `nets::supertonic_duration` line by line.+    """+    held = constants(graph)+    if not convolutions_edge_padded(graph):+        raise SystemExit(+            "this export does not pad every convolution with mode=edge, so the layer-scale "+            "fold below is not valid; see the module docstring"+        )++    def held_at(name):+        if name not in held:+            raise SystemExit(f"{name} is not in this export")+        return np.asarray(held[name], dtype=np.float64)++    layers, tensors = [], []++    def add(op, name, key, *values):+        first = len(tensors)+        for value in values:+            tensors.append(np.ascontiguousarray(value, dtype=np.float32))+        layers.append(maml_convert.Layer(len(layers), op, name, key, first, len(values)))++    def conv(name, out_channels, fold_scale=None, synthesise_bias=False, pads=(0, 0, 0, 0),+             kernel=(1, 1), group=1):+        """One convolution's pair, lifted to the rank-4 `[out, in, 1, k]` the Rust indexes."""+        weight = held_at(f"{name}.weight")+        if synthesise_bias:+            bias = np.zeros(out_channels, dtype=np.float64)+        else:+            bias = held_at(f"{name}.bias")+        if fold_scale is not None:+            weight, bias = fold_output(weight, bias, fold_scale, 0.0)+        if weight.ndim == 2:+            # A `Gemm`'s `[out, in]`, at `transB=1`, is already the convolution's layout.+            weight = weight.reshape(weight.shape[0], weight.shape[1], 1, 1)+        elif weight.ndim == 3:+            weight = weight.reshape(weight.shape[0], weight.shape[1], 1, weight.shape[2])+        note = " b0=synthesised" if synthesise_bias else ""+        note += " folded=layer_scale" if fold_scale is not None else ""+        add(+            "Conv",+            name,+            f"Conv w={list(weight.shape)} b={list(bias.shape)} k={list(kernel)}"+            f" p={list(pads)} g={group} pad=edge{note}",+            weight,+            bias,+        )++    def layer_norm(name):+        gamma = held_at(f"{name}.weight")+        beta = held_at(f"{name}.bias")+        add(+            "LayerNorm",+            name,+            f"LayerNorm g={list(gamma.shape)} b={list(beta.shape)}",+            gamma,+            beta,+        )++    # The embedding table, with `sentence_token` as its last row. The token is prepended to the+    # sequence in the export and read back out of position 0 at the end; making it a row of the+    # table is how a plan with no sequence-axis concat expresses that.+    table = held_at(f"{DP_PREFIX}.text_embedder.char_embedder.weight")+    token = held_at(f"{DP_PREFIX}.sentence_token").reshape(1, -1)+    if token.shape[1] != table.shape[1]:+        raise SystemExit(f"a {list(token.shape)} sentence token for a {list(table.shape)} table")+    table = np.concatenate([table, token], axis=0)+    add("Embed", "char_embedder+sentence_token", f"Embed t={list(table.shape)} token=last", table)++    for block in range(DP_BLOCKS):+        at = f"{DP_PREFIX}.convnext.convnext.{block}"+        # Symmetric, not causal: `[0, 0, 2, 0, 0, 2]` around a 5-tap at dilation 1. The vocoder+        # is the other way round, which is the one thing here worth stating twice.+        conv(f"{at}.dwconv", DP_CHANNELS, pads=(0, 2, 0, 2), kernel=(1, 5), group=DP_CHANNELS)+        layer_norm(f"{at}.norm.norm")+        conv(f"{at}.pwconv1", DP_INNER)+        # The block's `[1, 64, 1]` gamma rides on `pwconv2`, which is a 1x1 and so has no border.+        conv(f"{at}.pwconv2", DP_CHANNELS, fold_scale=held_at(f"{at}.gamma").reshape(-1))++    for layer in range(DP_ATTN_LAYERS):+        at = f"{DP_PREFIX}.attn_encoder"+        attn = f"{at}.attn_layers.{layer}"+        for projection in ("conv_q", "conv_k", "conv_v"):+            conv(f"{attn}.{projection}", DP_CHANNELS)+        # `[1, 9, 32]` in the export; the Rust reads `[offsets, head_dim]`.+        for table_name in ("emb_rel_k", "emb_rel_v"):+            relative = held_at(f"{attn}.{table_name}").reshape(9, -1)+            add(+                "RelPos",+                f"{attn}.{table_name}",+                f"RelPos t={list(relative.shape)}",+                relative,+            )+        conv(f"{attn}.conv_o", DP_CHANNELS)+        layer_norm(f"{at}.norm_layers_1.{layer}.norm")+        conv(f"{at}.ffn_layers.{layer}.conv_1", DP_INNER)+        conv(f"{at}.ffn_layers.{layer}.conv_2", DP_CHANNELS)+        layer_norm(f"{at}.norm_layers_2.{layer}.norm")++    # `proj_out` has no bias in the export; the Rust reads a pair for every convolution.+    conv(f"{DP_PREFIX}.proj_out.net", DP_CHANNELS, synthesise_bias=True)+    conv("tts.dp.predictor.layers.0", DP_HIDDEN)++    prelu = next(n for n in graph.node if n.op_type == "PRelu")+    slope = np.asarray(held[prelu.input[1]], dtype=np.float64).reshape(-1)+    if slope.size != 1:+        raise SystemExit(f"{prelu.name}: a {slope.size}-element slope, expected one")+    widened = np.full((DP_HIDDEN, 1, 1), float(slope[0]), dtype=np.float32)+    add(+        "PRelu",+        prelu.name,+        f"PRelu s={list(widened.shape)} shared={float(slope[0]):.6f}",+        widened,+    )++    conv("tts.dp.predictor.layers.1", 1)+    return layers, tensors++ def main():     parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])     parser.add_argument("onnx")@@ -249,7 +425,10 @@ def main():     raw = open(args.onnx, "rb").read()     onnx_sha256 = hashlib.sha256(raw).digest()     model = onnx.load(args.onnx)-    layers, tensors = collect(model.graph)+    if args.graph == "supertonic_dp":+        layers, tensors = collect_duration(model.graph)+    else:+        layers, tensors = collect(model.graph)      if args.print_layers:         for layer in layers: