Modern Apps git

← Modern-Apps.git

library:ml: Supertonic's flow-matching sampler, with guidance on the host

Commit
fb379091a75c20a946bf308e9bfae33218e5546d
Author
vayun-mathur <[email protected]>
When
2026-08-28 15:54 UTC (3 months ago)
Parents
33e5835

Diff

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 f4cc8818fa..61873a94a4 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -37,6 +37,7 @@ pub mod ppocr_rec; pub mod scrfd; pub mod selfie; pub mod supertonic_duration;+pub mod supertonic_sampler; pub mod supertonic_text; pub mod supertonic_vocoder; pub mod u2netp;@@ -1247,6 +1248,20 @@ impl<'a> Builder<'a> {         out     } +    /// Declare that a tensor is read on the **host** rather than by the plan.+    ///+    /// [`Builder::finish`] refuses a file with an unread tensor, because that is what a forward+    /// pass which skipped a layer looks like from the outside. A few tensors legitimately never+    /// reach a shader: Supertonic's sampler conditions on a timestep embedding that is a function+    /// of two scalars, and on classifier-free-guidance tokens that differ per branch, so the host+    /// evaluates those and passes the results in as plan inputs. Naming them here keeps the+    /// invariant — nothing is *accidentally* unread — and puts the list in the net module beside+    /// the code that uses it.+    pub fn host_tensor(&mut self, weight_index: usize, dims: &[u32]) {+        // Through `weight` so the shape is checked against the file like any other tensor.+        self.weight(weight_index, dims);+    }+     /// `a + b` where `b` is `C x 1 x 1`, a per-channel shift. See [`Kind::AddBroadcast`].     pub fn add_channel(&mut self, a: Id, b: Id) -> Id {         let (sa, sb) = (self.shape_of(a), self.shape_of(b));
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 225862f82a..c9f364616e 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -1100,8 +1100,8 @@ fn uniform(state: &mut u32) -> f32 { #[cfg(test)] mod tests {     use super::super::{-        embed_lanes, mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration, supertonic_text,-        supertonic_vocoder, u2netp, vits_dec, vits_enc, vits_flow, Act, Builder, EMBED_LANE,+        embed_lanes, mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration, supertonic_sampler,+        supertonic_text, supertonic_vocoder, u2netp, vits_dec, vits_enc, vits_flow, Act, Builder, EMBED_LANE,     };     use super::*; @@ -2696,6 +2696,60 @@ mod tests {             println!("supertonic_voc at {width} frames: wrote {} values", samples.len());             return;         }+        if graph == "supertonic_ve" {+            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_VE)+                    .expect("the sampler asset parses");+            let chars: u32 = std::env::var("PARITY_CHARS")+                .expect("PARITY_CHARS")+                .parse()+                .expect("a character count");+            let plan = supertonic_sampler::build(&weights, width, chars).expect("the sampler builds");+            let read = |name: &str| -> Vec<f32> {+                let raw = std::fs::read(dir.join(name)).unwrap_or_else(|e| panic!("{name}: {e}"));+                raw.chunks_exact(4)+                    .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))+                    .collect()+            };+            let text = read("text.f32");+            let style = read("style.f32");+            use crate::post::supertonic as post;+            let (current, total) = (5u32, 16u32);+            let shifts = post::time_shifts(&weights, current, total).expect("the timestep shifts");+            let query_angles = post::rotary_angles(&weights, width).expect("the query angles");+            let key_angles = post::rotary_angles(&weights, chars).expect("the key angles");+            // The export tiles its batch to two: the real conditioning, and two learned+            // unconditional tokens. Two runs of one plan here, combined below.+            let conditional_keys = post::style_keys(&weights, true).expect("the conditional keys");+            let unconditional_keys =+                post::style_keys(&weights, false).expect("the unconditional keys");+            let unconditional_text =+                post::unconditional_text(&weights, chars).expect("the unconditional text");+            let unconditional_style =+                post::unconditional_style(&weights).expect("the unconditional style");+            let run_branch = |text: &[f32], keys: &[f32], style: &[f32]| -> Vec<f32> {+                let outputs = run_multi(+                    &plan,+                    weights.data(),+                    &[&input, text, keys, style, &shifts, &query_angles, &key_angles],+                )+                .expect("the sampler runs");+                outputs.into_iter().next().expect("the velocity")+            };+            let conditional = run_branch(&text, &conditional_keys, &style);+            let unconditional =+                run_branch(&unconditional_text, &unconditional_keys, &unconditional_style);+            let denoised = post::step(&input, &conditional, &unconditional, total)+                .expect("the Euler step");+            write(&dir.join("reference.f32"), &denoised);+            println!(+                "supertonic_ve at {width} frames, {chars} chars: wrote {} values",+                denoised.len()+            );+            return;+        }         if graph == "supertonic_ttl" {             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_sampler.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_sampler.rs b/library/ml/src/main/rust/src/nets/supertonic_sampler.rsnew file mode 100644index 0000000000..0bff6c66ad--- /dev/null+++ b/library/ml/src/main/rust/src/nets/supertonic_sampler.rs@@ -0,0 +1,597 @@+//! Supertonic 3's flow-matching sampler: the velocity field, run N times per utterance.+//!+//! # What it is+//!+//! The expensive one. 1004 ONNX nodes and 64,013,449 parameters, of which 92% are the 56+//! pointwise convolutions inside its 28 ConvNeXt blocks, and it runs 16 times per utterance —+//! twice per step, for the reason below. Everything else in Supertonic is a rounding error+//! against it.+//!+//! Its shape is four **main blocks**, each of them+//!+//! ```text+//! 4 ConvNeXt blocks at dilations 1, 2, 4, 8+//! + a per-channel shift from the timestep+//! 1 ConvNeXt block+//! + an 8-head cross-attention over the text, with rotary positions+//! 1 ConvNeXt block+//! + a 2-head cross-attention over the 50 style tokens+//! ```+//!+//! then four more ConvNeXt blocks at dilation 1, between a `[512, 144, 1]` projection in and a+//! `[144, 512, 1]` projection out. The export flattens the four into `main_blocks.0` through+//! `main_blocks.23`, six entries each.+//!+//! # It is classifier-free guidance, and that doubles the cost+//!+//! The export's first three nodes are `Tile(x, [2, 1, 1])`: it runs the **whole network twice**,+//! once on the real text and style and once on two learned unconditional tokens, and combines+//! them at the end. Read off the graph:+//!+//! ```text+//! v = 4 * conditional - 3 * unconditional+//! denoised = (noisy_latent + v / total_step) * latent_mask+//! ```+//!+//! So the ONNX is not a velocity field but a whole **Euler step**, guidance scale 4 baked in.+//! This runtime has no batch axis and cannot fake one — putting the two branches side by side+//! along the sequence would let the depthwise convolutions mix them — so the plan is one branch+//! and [`post::supertonic`] runs it twice. That is a real doubling of the sampler's cost against+//! any measurement taken of a single branch.+//!+//! Both branches are the same plan with different **inputs**: the unconditional one passes+//! `uncond_masker.text_special_token` broadcast over the text positions, and+//! `style_value_special_token` in place of the voice. Only the style *keys* differ structurally,+//! and those are folded constants (below), so they are an input too.+//!+//! # What the host computes, and why+//!+//! Four things never reach a shader, and [`Builder::host_tensor`] names each so+//! [`Builder::finish`] still refuses an *accidentally* unread tensor:+//!+//! * **The timestep conditioning.** A sinusoidal embedding of `current_step / total_step`, a+//!   two-layer MLP with a Mish in the middle, and then four `Linear`s to 512 numbers each — all+//!   a function of two scalars. That is `Sin`, `Cos`, `Softplus` and `Tanh` shaders for 2,048+//!   values, against a net that does 64M multiply-adds a position. The host evaluates it and+//!   passes `[2048, 1, 1]`, which [`Builder::slice_channels`] cuts into four per-channel shifts.+//! * **The rotary angles.** `(position / length) * theta`, so they depend on the two sequence+//!   lengths and on nothing learned. See [`super::Kind::Rotary`].+//! * **The style keys**, `tanh(W_key . style_key + b_key)`, entirely constant — and different per+//!   guidance branch *and* per main block, since the four style attentions share one `style_key`+//!   but each has its own `W_key`. Folding only the first was a real bug here: the net was exact+//!   through ten of its twenty-four sub-blocks and then correlated at 0.29.+//! * **The unconditional tokens**, which are the other branch's inputs.+//!+//! # Two scales that are not `1 / sqrt(head_dim)`+//!+//! Both attentions divide their scores by **16**. The text one has heads of 64 and the style one+//! heads of 128, so [`Builder::attn_scores`]'s own `1 / sqrt(head_dim)` is 2x and `sqrt(2)`x too+//! large respectively. The converter folds the difference into each `W_query`, which is exact —+//! and safe across the rotary, because a rotation commutes with a scalar.++//! # Measured parity+//!+//! Against onnxruntime on `denoised_latent` at 32 frames and 16 characters \u2014 the whole Euler step+//! over both guidance branches, so both plan runs and all the host arithmetic: correlation+//! 0.99999981, max 0.006019 on values reaching 5.13. Every one of the 25 stage boundaries inside+//! the net agrees to better than 0.99998.+//!+//! Getting there took one bisect. The first attempt folded a single style `W_key` and reused it+//! for all four style attentions; the net was then exact through `main_blocks.10` and correlated+//! at 0.29 from `main_blocks.11` on. A per-stage comparison found it in one run, which is much+//! faster than reasoning about a 1004-node graph.++use super::{Act, Builder, Id, Plan, Shape, WeightSource};++/// Latent channels in and out. `ldim * chunk_compress_factor`, and the vocoder's `PACKED`.+pub const LATENT: u32 = 144;++/// Channels the stack works in. `vector_field.proj_in.odim`.+pub const CHANNELS: u32 = 512;++/// The ConvNeXt widening. `intermediate_dim`.+pub const INNER: u32 = 2048;++/// The text conditioning's width, which is the text encoder's output. `text_dim`.+pub const TEXT: u32 = 256;++/// The style conditioning's width. `style_dim`.+pub const STYLE: u32 = 256;++/// Style tokens each style cross-attention attends over. `n_style`.+pub const STYLE_TOKENS: u32 = 50;++/// Heads in the text cross-attention, so `head_dim` is 64. `text_cond_layer.n_heads`.+pub const TEXT_HEADS: u32 = 8;++/// Heads in the style cross-attention, so `head_dim` is 128.+pub const STYLE_HEADS: u32 = 2;++/// The timestep embedding's width. `time_encoder.time_dim`.+pub const TIME: u32 = 64;++/// The timestep MLP's inner width. `time_encoder.hdim`.+pub const TIME_INNER: u32 = 256;++/// Main blocks, each one four ConvNeXt blocks, a timestep shift, two conditionings and two more+/// ConvNeXt blocks.+pub const MAIN_BLOCKS: usize = 4;++/// ConvNeXt blocks in each main block's leading stack, at dilations 1, 2, 4 and 8.+const LEADING: [u32; 4] = [1, 2, 4, 8];++/// ConvNeXt blocks after the last main block, all at dilation 1. `last_convnext.num_layers`.+pub const TRAILING: usize = 4;++/// ConvNeXt blocks in the whole net: `4 * (4 + 1 + 1) + 4`.+pub const BLOCKS: usize = MAIN_BLOCKS * 6 + TRAILING;++/// The depthwise kernel width, `ksz`.+const KERNEL: u32 = 5;++/// The epsilon in all 36 layer norms.+const EPSILON: f32 = 1e-5;++/// Rotary frequencies, which is `head_dim / 2` of the text attention.+pub const FREQUENCIES: u32 = 32;++/// The guidance scale the export bakes in: `v = 4 * conditional - 3 * unconditional`.+pub const GUIDANCE: f32 = 4.0;++/// Tensors the plan itself reads: `proj_in`, 28 ConvNeXt blocks of eight, four main blocks'+/// conditioning, and `proj_out`.+pub const PLAN_TENSORS: usize = 2 + BLOCKS * 8 + MAIN_BLOCKS * 18 + 2;++/// Tensors the `.maml` must hold: the plan's, then the host's eighteen.+pub const TENSORS: usize = PLAN_TENSORS + 18;++/// The rotary `theta`, `[32]`. `rotary_scale * rotary_base ^ (-j / 32)`.+pub const HOST_THETA: usize = PLAN_TENSORS;++/// The timestep embedding's sinusoidal frequencies, `[32]`.+pub const HOST_FREQUENCIES: usize = PLAN_TENSORS + 1;++/// The timestep MLP's first `Linear`, `[256, 64]` then `[256]`.+pub const HOST_MLP_IN: usize = PLAN_TENSORS + 2;++/// The timestep MLP's second `Linear`, `[64, 256]` then `[64]`.+pub const HOST_MLP_OUT: usize = PLAN_TENSORS + 4;++/// The four per-block timestep `Linear`s, `[512, 64]` and `[512]` each, in block order.+pub const HOST_TIME_LINEARS: usize = PLAN_TENSORS + 6;++/// `uncond_masker.text_special_token`, `[256]`, broadcast over every text position.+pub const HOST_TEXT_TOKEN: usize = PLAN_TENSORS + 14;++/// `uncond_masker.style_value_special_token`, `[256, 50]` and already transposed.+pub const HOST_STYLE_TOKEN: usize = PLAN_TENSORS + 15;++/// The folded conditional style keys, `[4 * 256, 50]` — one 256-channel block per main block.+pub const HOST_KEYS_CONDITIONAL: usize = PLAN_TENSORS + 16;++/// The folded unconditional style keys, `[4 * 256, 50]`.+pub const HOST_KEYS_UNCONDITIONAL: usize = PLAN_TENSORS + 17;++/// Hands out `.maml` tensor indices in the order the layers appear.+struct Layers {+    next: usize,+}++impl Layers {+    fn take(&mut self) -> usize {+        let index = self.next;+        self.next += 2;+        index+    }+}++/// A `1 x 1` convolution, which every projection here is.+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)+}++/// One ConvNeXt block: depthwise, layer norm, widening 1x1 with a GELU, narrowing 1x1, residual.+///+/// Symmetric edge padding of `2 * dilation` each side, as in the text encoder. The block's+/// `[1, 512, 1]` gamma is folded into `pwconv2` by the converter.+fn convnext(b: &mut Builder, l: &mut Layers, x: Id, dilation: u32) -> Id {+    let each = dilation * (KERNEL - 1) / 2;+    let along = b.conv(+        x,+        l.take(),+        CHANNELS,+        (1, KERNEL),+        (1, 1),+        (1, dilation),+        (0, each, 0, each),+        CHANNELS,+        Act::None,+    );+    let normed = b.layer_norm(along, l.take(), EPSILON);+    let widened = point(b, l, normed, INNER, Act::Gelu);+    let narrowed = point(b, l, widened, CHANNELS, Act::None);+    b.add(x, narrowed)+}++/// Build one guidance branch of the sampler.+///+/// Seven inputs, in this order:+///+/// 0. `noisy_latent`, `[144, 1, frames]`+/// 1. the text conditioning, `[256, 1, chars]` — the text encoder's output, or the unconditional+///    token broadcast+/// 2. the folded style keys, `[1024, 1, 50]` — four stacked 256-channel blocks, one per main+///    block+/// 3. the style values, `[256, 1, 50]` — the voice's `style_ttl` transposed, or the unconditional+///    token+/// 4. the four timestep shifts, `[2048, 1, 1]`+/// 5. the query rotary angles, `[64, 1, frames]`+/// 6. the key rotary angles, `[64, 1, chars]`+///+/// The output is this branch's velocity, `[144, 1, frames]`. Combining the two branches and+/// taking the Euler step is [`crate::post::supertonic::step`].+pub fn build(weights: &dyn WeightSource, frames: u32, chars: u32) -> Result<Plan, String> {+    if frames == 0 {+        return Err("a sampler pass over no frames".into());+    }+    if chars == 0 {+        return Err("a sampler pass over no characters".into());+    }++    let l = &mut Layers { next: 0 };+    let mut builder = Builder::new(weights);+    let b = &mut builder;+    // Every padded convolution here replicates its border; all 28 `Pad`s are `mode=edge`.+    b.edge_padding();++    let latent = b.input(Shape::new(LATENT, 1, frames));+    let text = b.input(Shape::new(TEXT, 1, chars));+    let style_keys = b.input(Shape::new(STYLE * MAIN_BLOCKS as u32, 1, STYLE_TOKENS));+    let style_values = b.input(Shape::new(STYLE, 1, STYLE_TOKENS));+    let shifts = b.input(Shape::new(CHANNELS * MAIN_BLOCKS as u32, 1, 1));+    let query_angles = b.input(Shape::new(TEXT_HEADS * 2 * FREQUENCIES / TEXT_HEADS, 1, frames));+    let key_angles = b.input(Shape::new(2 * FREQUENCIES, 1, chars));++    // `proj_in` has no bias in the export; the converter synthesises a zero one.+    let mut x = point(b, l, latent, CHANNELS, Act::None);++    for block in 0..MAIN_BLOCKS {+        for &dilation in &LEADING {+            x = convnext(b, l, x, dilation);+        }++        // The timestep shift, one 512-vector per main block out of the host's `[2048, 1, 1]`.+        let shift = b.slice_channels(shifts, CHANNELS * block as u32, CHANNELS);+        x = b.add_channel(x, shift);++        x = convnext(b, l, x, 1);++        // The text cross-attention. Rotary on both sides, and the angles are normalised by each+        // sequence's own length so a query at the middle of the latent meets a key at the middle+        // of the text.+        let query = point(b, l, x, CHANNELS, Act::None);+        let query = b.rotary(query, query_angles, TEXT_HEADS);+        let keys = point(b, l, text, CHANNELS, Act::None);+        let keys = b.rotary(keys, key_angles, TEXT_HEADS);+        let values = point(b, l, text, CHANNELS, Act::None);+        let scores = b.attn_scores(query, keys, TEXT_HEADS);+        let probs = b.softmax(scores);+        let mixed = b.attn_apply(probs, values, TEXT_HEADS);+        let projected = point(b, l, mixed, CHANNELS, Act::None);+        let residual = b.add(x, projected);+        x = b.layer_norm(residual, l.take(), EPSILON);++        x = convnext(b, l, x, 1);++        // The style cross-attention.++        // The style cross-attention. Its keys arrive already through `tanh`, folded, and each+        // main block has its own: they share one `style_key` but not one `W_key`.+        let keys = b.slice_channels(style_keys, STYLE * block as u32, STYLE);+        let query = point(b, l, x, STYLE, Act::None);+        let values = point(b, l, style_values, STYLE, Act::None);+        let scores = b.attn_scores(query, keys, STYLE_HEADS);+        let probs = b.softmax(scores);+        let mixed = b.attn_apply(probs, values, STYLE_HEADS);+        let projected = point(b, l, mixed, CHANNELS, Act::None);+        let residual = b.add(x, projected);+        x = b.layer_norm(residual, l.take(), EPSILON);+    }++    for _ in 0..TRAILING {+        x = convnext(b, l, x, 1);+    }++    // `proj_out` has no bias either.+    let velocity = point(b, l, x, LATENT, Act::None);++    if l.next != PLAN_TENSORS {+        return Err(format!("the forward pass claims {} tensors, not {PLAN_TENSORS}", l.next));+    }+    // Named rather than skipped: see `Builder::host_tensor`.+    b.host_tensor(HOST_THETA, &[FREQUENCIES]);+    b.host_tensor(HOST_FREQUENCIES, &[FREQUENCIES]);+    b.host_tensor(HOST_MLP_IN, &[TIME_INNER, TIME]);+    b.host_tensor(HOST_MLP_IN + 1, &[TIME_INNER]);+    b.host_tensor(HOST_MLP_OUT, &[TIME, TIME_INNER]);+    b.host_tensor(HOST_MLP_OUT + 1, &[TIME]);+    for block in 0..MAIN_BLOCKS {+        b.host_tensor(HOST_TIME_LINEARS + block * 2, &[CHANNELS, TIME]);+        b.host_tensor(HOST_TIME_LINEARS + block * 2 + 1, &[CHANNELS]);+    }+    b.host_tensor(HOST_TEXT_TOKEN, &[TEXT]);+    b.host_tensor(HOST_STYLE_TOKEN, &[STYLE, STYLE_TOKENS]);+    b.host_tensor(HOST_KEYS_CONDITIONAL, &[STYLE * MAIN_BLOCKS as u32, STYLE_TOKENS]);+    b.host_tensor(HOST_KEYS_UNCONDITIONAL, &[STYLE * MAIN_BLOCKS as u32, STYLE_TOKENS]);++    builder.finish(&[velocity])+}++#[cfg(test)]+mod tests {+    use super::super::tests::{assert_no_aliasing, Shapes};+    use super::super::{Kind, Op};+    use super::*;++    /// About four seconds of audio, and a sentence to match.+    const FRAMES: u32 = 54;+    const CHARS: u32 = 24;++    fn plan(frames: u32, chars: u32) -> (Shapes, Plan) {+        let source = Shapes::new(TENSORS);+        let plan = build(&source, frames, chars).expect("the sampler builds");+        (source, plan)+    }++    #[test]+    fn the_pass_reads_every_tensor_in_the_file_exactly_once() {+        let (source, _) = plan(FRAMES, 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() {+        // Checked as a sum of its own parts, because the export's float initializer total+        // (64,013,449) also holds a few dozen scalar literals — the guidance 4 and 3, the+        // score divisor 16, the GELU constants — which are initializers here rather than+        // `Constant` nodes, so an exact equation against it would be reconciling weights+        // against arithmetic. The material differences from that figure are:+        //+        //   - the 28 `[1, 512, 1]` layer scales fold into their `pwconv2`:      -14,336+        //   - the four style `W_key`s and their biases fold into the keys:     -263,168+        //   - the folded keys are four stacked `[256, 50]` per branch, where+        //     the export holds one `[1, 50, 256]` `style_key` per branch:      +76,800+        //   - `proj_in` and `proj_out` have no bias, so two are synthesised:      +656+        //   - the timestep embedding's frequency table is a `Constant` node+        //     in the export rather than an initializer, so it is new here:         +32+        //+        // `increments` is an int64 ramp and never counted; the two `[1, 50, 256]` style key+        // constants leave and eight folded `[256, 50]` tensors arrive.+        let (source, _) = plan(FRAMES, CHARS);+        let total: u64 = source+            .asked+            .borrow()+            .iter()+            .map(|(_, dims)| dims.iter().map(|&d| d as u64).product::<u64>())+            .sum();++        let projection = |a: u64, b: u64| a * b + a;+        let block = 2_560 + 512 + 512 + 512 + 1_048_576 + 2_048 + 1_048_576 + 512;+        let text_attention = projection(512, 512) * 2 + projection(512, 256) * 2 + 1_024;+        let style_attention =+            projection(256, 512) + projection(256, 256) + projection(512, 256) + 1_024;+        let host = 32 + 32+            + projection(256, 64)+            + projection(64, 256)+            + projection(512, 64) * MAIN_BLOCKS as u64+            + 256+            + 12_800+            + 12_800 * 2 * MAIN_BLOCKS as u64;+        assert_eq!(+            total,+            projection(512, 144)+                + block * BLOCKS as u64+                + (text_attention + style_attention) * MAIN_BLOCKS as u64+                + projection(144, 512)+                + host+        );+        // And spelled out, so a reordering that preserved the sum would still be caught.+        assert_eq!(total, 63_813_392);+    }++    #[test]+    fn the_inputs_are_the_latent_the_two_conditionings_and_the_two_angle_tables() {+        let (_, plan) = plan(FRAMES, CHARS);+        let inputs: Vec<Shape> = plan.inputs.iter().map(|b| b.shape).collect();+        assert_eq!(+            inputs,+            vec![+                Shape::new(LATENT, 1, FRAMES),+                Shape::new(TEXT, 1, CHARS),+                Shape::new(STYLE * MAIN_BLOCKS as u32, 1, STYLE_TOKENS),+                Shape::new(STYLE, 1, STYLE_TOKENS),+                Shape::new(CHANNELS * MAIN_BLOCKS as u32, 1, 1),+                Shape::new(2 * FREQUENCIES, 1, FRAMES),+                Shape::new(2 * FREQUENCIES, 1, CHARS),+            ]+        );+        // One branch's velocity, at the latent's own shape. Not the Euler step: that is+        // `post::supertonic::step`, which needs both branches.+        assert_eq!(+            plan.output().expect("one output").shape,+            Shape::new(LATENT, 1, FRAMES)+        );+    }++    #[test]+    fn the_text_attention_is_a_cross_attention_of_frames_against_characters() {+        // `[8, frames, chars]` — the shape that made the cross-attention change necessary. The+        // style one is `[2, frames, 50]`.+        let (_, plan) = plan(FRAMES, CHARS);+        let maps: Vec<(u32, u32, u32)> = plan+            .ops+            .iter()+            .filter_map(|op| match op {+                Op::Dispatch { kind: Kind::AttnScores, push, .. } => {+                    Some((push.out_c, push.out_h, push.out_w))+                }+                _ => None,+            })+            .collect();+        let mut want = Vec::new();+        for _ in 0..MAIN_BLOCKS {+            want.push((TEXT_HEADS, FRAMES, CHARS));+            want.push((STYLE_HEADS, FRAMES, STYLE_TOKENS));+        }+        assert_eq!(maps, want);+    }++    #[test]+    fn rotary_runs_on_both_sides_of_every_text_attention() {+        // Eight in all: the query over the latent's length and the key over the text's. A+        // rotary on only one side would leave the two sequences in different frames and the+        // alignment would drift with the length ratio.+        let (_, plan) = plan(FRAMES, CHARS);+        let widths: Vec<(u32, u32, u32)> = plan+            .ops+            .iter()+            .filter_map(|op| match op {+                Op::Dispatch { kind: Kind::Rotary, push, .. } => {+                    Some((push.group, push.in_c, push.out_w))+                }+                _ => None,+            })+            .collect();+        let mut want = Vec::new();+        for _ in 0..MAIN_BLOCKS {+            want.push((TEXT_HEADS, 2 * FREQUENCIES, FRAMES));+            want.push((TEXT_HEADS, 2 * FREQUENCIES, CHARS));+        }+        assert_eq!(widths, want);+    }++    #[test]+    fn the_depthwise_dilations_are_the_exports_own_sequence() {+        // Per main block 1, 2, 4, 8 then 1 then 1; then four more at 1. Sixteen at dilation 1,+        // four each at 2, 4 and 8 — which is exactly the export's `Conv` inventory.+        let (_, plan) = plan(FRAMES, CHARS);+        let found: Vec<(u32, u32)> = plan+            .ops+            .iter()+            .filter_map(|op| match op {+                Op::Dispatch { kind: Kind::Conv, push, .. } if push.group == CHANNELS => {+                    Some((push.dil_w, push.pad_l))+                }+                _ => None,+            })+            .collect();+        let mut want = Vec::new();+        for _ in 0..MAIN_BLOCKS {+            for &dilation in &LEADING {+                want.push((dilation, dilation * (KERNEL - 1) / 2));+            }+            want.push((1, 2));+            want.push((1, 2));+        }+        for _ in 0..TRAILING {+            want.push((1, 2));+        }+        assert_eq!(found, want);+        let ones = found.iter().filter(|&&(d, _)| d == 1).count();+        assert_eq!(ones, 16);+        assert_eq!(found.len(), BLOCKS);+    }++    #[test]+    fn each_main_block_takes_its_own_slice_of_the_timestep_shifts() {+        // Four shifts of 512 out of one `[2048, 1, 1]` input, in block order. Reading the same+        // slice four times would condition every block on the first one's timestep - which at+        // step 0 of 16 is not even wrong by much, and gets worse as the step index grows.+        let (_, plan) = plan(FRAMES, CHARS);+        let shifts: Vec<u32> = plan+            .ops+            .iter()+            .filter_map(|op| match op {+                Op::Dispatch { kind: Kind::AddBroadcast, push, .. } => Some(push.out_c),+                _ => None,+            })+            .collect();+        assert_eq!(shifts, vec![CHANNELS; MAIN_BLOCKS]);+        // Four timestep slices and four style-key slices, each lowering to one copy.+        let copies = plan.ops.iter().filter(|op| matches!(op, Op::Copy { .. })).count();+        assert_eq!(copies, MAIN_BLOCKS * 2);+    }++    #[test]+    fn the_op_inventory_is_twenty_eight_convnext_blocks_and_eight_attentions() {+        let (_, plan) = plan(FRAMES, 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;+            }+        }+        // Three per ConvNeXt block, four per text attention (query, key, value, output),+        // three per style attention, plus the two projections.+        let convolutions = BLOCKS * 3 + MAIN_BLOCKS * (4 + 3) + 2;+        assert_eq!(counts.get("Conv"), Some(&convolutions), "{counts:?}");+        assert_eq!(counts.get("Rotary"), Some(&(MAIN_BLOCKS * 2)), "{counts:?}");+        assert_eq!(counts.get("AttnScores"), Some(&(MAIN_BLOCKS * 2)), "{counts:?}");+        assert_eq!(counts.get("AttnApply"), Some(&(MAIN_BLOCKS * 2)), "{counts:?}");+        assert_eq!(counts.get("Softmax"), Some(&(MAIN_BLOCKS * 2)), "{counts:?}");+        assert_eq!(counts.get("AddBroadcast"), Some(&MAIN_BLOCKS), "{counts:?}");+        assert_eq!(counts.get("LayerNorm"), Some(&(BLOCKS + MAIN_BLOCKS * 2)), "{counts:?}");+        assert_eq!(counts.get("Add"), Some(&(BLOCKS + MAIN_BLOCKS * 2)), "{counts:?}");+        // No relative attention here: the positions are rotary.+        assert_eq!(counts.get("AttnScoresRelative"), None, "{counts:?}");+        assert_eq!(counts.get("Embed"), None, "{counts:?}");+        assert_eq!(counts.len(), 8, "{counts:?}");+    }++    #[test]+    fn nothing_changes_the_latent_length() {+        let (_, plan) = plan(FRAMES, CHARS);+        for (step, op) in plan.ops.iter().enumerate() {+            if let Op::Dispatch { kind: Kind::Conv, push, .. } = op {+                assert!(+                    push.out_w == FRAMES || push.out_w == CHARS || push.out_w == STYLE_TOKENS,+                    "step {step} produced {} positions",+                    push.out_w+                );+                assert_ne!(push.pad_edge, 0, "step {step} pads with zeros");+            }+        }+    }++    #[test]+    fn an_empty_latent_or_text_is_refused() {+        let source = Shapes::new(TENSORS);+        let error = build(&source, 0, CHARS).expect_err("no frames");+        assert!(error.contains("no frames"), "{error}");+        let source = Shapes::new(TENSORS);+        let error = build(&source, FRAMES, 0).expect_err("no characters");+        assert!(error.contains("no characters"), "{error}");+    }++    #[test]+    fn no_op_reads_a_region_of_the_arena_that_it_also_writes() {+        let (_, plan) = plan(FRAMES, CHARS);+        assert_no_aliasing(&plan);+    }++    #[test]+    fn the_arena_is_bounded_at_a_long_utterance() {+        // This is the net that decides how much device memory a voice needs: 2048 channels over+        // the latent, and an `[8, frames, chars]` score map four times.+        for (frames, chars) in [(FRAMES, CHARS), (216, 400)] {+            let (_, plan) = plan(frames, chars);+            let mib = plan.arena_elems as f32 * 2.0 / (1024.0 * 1024.0);+            println!("supertonic_sampler at {frames} frames, {chars} chars: {mib:.2} MiB");+            assert!(mib < 256.0, "{frames} frames wants {mib} MiB");+        }+    }+}
library/ml/src/main/rust/src/post/mod.rs
diff --git a/library/ml/src/main/rust/src/post/mod.rs b/library/ml/src/main/rust/src/post/mod.rsindex 65d65a701e..80aab3fb87 100644--- a/library/ml/src/main/rust/src/post/mod.rs+++ b/library/ml/src/main/rust/src/post/mod.rs@@ -19,4 +19,5 @@ pub mod nms; pub mod phonemes; pub mod speech; pub mod spline;+pub mod supertonic; pub mod ocr;
library/ml/src/main/rust/src/post/supertonic.rs
diff --git a/library/ml/src/main/rust/src/post/supertonic.rs b/library/ml/src/main/rust/src/post/supertonic.rsnew file mode 100644index 0000000000..c55b871892--- /dev/null+++ b/library/ml/src/main/rust/src/post/supertonic.rs@@ -0,0 +1,247 @@+//! The host half of Supertonic 3's sampler: the timestep embedding, the rotary angles, and the+//! guidance combination that turns two forward passes into one Euler step.+//!+//! # Why any of this is on the host+//!+//! [`crate::nets::supertonic_sampler`] is a plan of convolutions, attentions and layer norms.+//! Four things in the export are none of those, and all four are cheap:+//!+//! * The **timestep conditioning** is a sinusoidal embedding of `current_step / total_step`, a+//!   two-layer MLP with a Mish between, and four `Linear`s to 512 numbers. 2,048 values from two+//!   scalars, against a net that spends 64M multiply-adds per latent frame — so `Sin`, `Cos`,+//!   `Softplus` and `Tanh` shaders would exist for nothing.+//! * The **rotary angles** are `(position / length) * theta`. Nothing learned, and they change+//!   with the sequence lengths rather than with the weights.+//! * The **unconditional branch's inputs** are two learned tokens, one broadcast over the text+//!   and one standing in for the voice.+//! * The **guidance combination and the Euler step**, four multiply-adds per latent value.+//!+//! Each of those tensors is declared to [`crate::nets::Builder::host_tensor`] so a genuinely+//! unread weight is still an error.+//!+//! # The step is two passes+//!+//! The export tiles its batch to two and runs the whole network twice, once conditioned on the+//! real text and voice and once on the unconditional tokens, then takes+//! `4 * conditional - 3 * unconditional`. This runtime has no batch axis, so [`step`] takes the+//! two velocities the caller already ran. That is a genuine doubling of the sampler's cost.++use crate::nets::supertonic_sampler as net;+use crate::preprocess::f16_to_f32;+use crate::weights::Weights;++/// The frequency multiplier the export applies before the sinusoids: `t * 1000 * frequency`.+const TIME_SCALE: f32 = 1000.0;++/// One tensor of the `.maml` as `f32`, in the file's order.+fn tensor(weights: &Weights, index: usize, dims: &[u32]) -> Result<Vec<f32>, String> {+    let found = weights.shaped(index, dims)?;+    let bytes = weights.data();+    let start = found.offset as usize;+    let end = start + (found.len as usize) * 2;+    let raw = bytes+        .get(start..end)+        .ok_or_else(|| format!("tensor {index} runs past the file"))?;+    Ok(raw+        .chunks_exact(2)+        .map(|c| f16_to_f32(u16::from_le_bytes([c[0], c[1]])))+        .collect())+}++/// `out[o] = sum_i weight[o][i] * x[i] + bias[o]`, over a row-major `[out, in]` weight.+fn linear(weight: &[f32], bias: &[f32], x: &[f32]) -> Vec<f32> {+    let inputs = x.len();+    bias.iter()+        .enumerate()+        .map(|(o, &b)| {+            let row = &weight[o * inputs..(o + 1) * inputs];+            row.iter().zip(x).map(|(&w, &v)| w * v).sum::<f32>() + b+        })+        .collect()+}++/// `x * tanh(softplus(x))`, the export's `mlp.1`.+///+/// `softplus` is written as `ln(1 + e^x)` only for negative `x`: for large positive `x` the+/// exponential overflows while the function is within an fp32 epsilon of `x` itself.+fn mish(x: f32) -> f32 {+    let softplus = if x > 20.0 { x } else { x.exp().ln_1p() };+    x * softplus.tanh()+}++/// The four per-block timestep shifts, `[4 * 512]`, for step `current` of `total`.+///+/// The plan reads them as one `[2048, 1, 1]` input and [`crate::nets::Builder::slice_channels`]+/// hands each main block its own 512.+pub fn time_shifts(weights: &Weights, current: u32, total: u32) -> Result<Vec<f32>, String> {+    if total == 0 {+        return Err("a sampler step out of no steps".into());+    }+    let frequencies = tensor(weights, net::HOST_FREQUENCIES, &[net::FREQUENCIES])?;+    let progress = current as f32 / total as f32;++    // Sines then cosines, which is the order of the export's `Concat`.+    let angles: Vec<f32> = frequencies.iter().map(|&f| progress * TIME_SCALE * f).collect();+    let embedding: Vec<f32> = angles+        .iter()+        .map(|a| a.sin())+        .chain(angles.iter().map(|a| a.cos()))+        .collect();++    let in_weight = tensor(weights, net::HOST_MLP_IN, &[net::TIME_INNER, net::TIME])?;+    let in_bias = tensor(weights, net::HOST_MLP_IN + 1, &[net::TIME_INNER])?;+    let hidden: Vec<f32> = linear(&in_weight, &in_bias, &embedding).into_iter().map(mish).collect();++    let out_weight = tensor(weights, net::HOST_MLP_OUT, &[net::TIME, net::TIME_INNER])?;+    let out_bias = tensor(weights, net::HOST_MLP_OUT + 1, &[net::TIME])?;+    let time = linear(&out_weight, &out_bias, &hidden);++    let mut shifts = Vec::with_capacity(net::MAIN_BLOCKS * net::CHANNELS as usize);+    for block in 0..net::MAIN_BLOCKS {+        let index = net::HOST_TIME_LINEARS + block * 2;+        let weight = tensor(weights, index, &[net::CHANNELS, net::TIME])?;+        let bias = tensor(weights, index + 1, &[net::CHANNELS])?;+        shifts.extend(linear(&weight, &bias, &time));+    }+    Ok(shifts)+}++/// The rotary angle table for a sequence of `positions`, as the `[64, 1, positions]` the plan+/// wants: 32 channels of cosine then 32 of sine.+///+/// The angle is `(position / positions) * theta` — normalised by the sequence's **own** length,+/// which is what lets a latent frame and a text character at the same fraction of the way through+/// meet at the same angle. It also means the query table and the key table are different tensors+/// even though they share `theta`.+pub fn rotary_angles(weights: &Weights, positions: u32) -> Result<Vec<f32>, String> {+    if positions == 0 {+        return Err("a rotary table over no positions".into());+    }+    let theta = tensor(weights, net::HOST_THETA, &[net::FREQUENCIES])?;+    let width = positions as usize;+    let mut table = vec![0.0f32; 2 * net::FREQUENCIES as usize * width];+    for (frequency, &turn) in theta.iter().enumerate() {+        for position in 0..width {+            let angle = position as f32 / positions as f32 * turn;+            table[frequency * width + position] = angle.cos();+            table[(net::FREQUENCIES as usize + frequency) * width + position] = angle.sin();+        }+    }+    Ok(table)+}++/// The unconditional branch's text input: `text_special_token` at every one of `chars` positions.+pub fn unconditional_text(weights: &Weights, chars: u32) -> Result<Vec<f32>, String> {+    if chars == 0 {+        return Err("an unconditional text of no characters".into());+    }+    let token = tensor(weights, net::HOST_TEXT_TOKEN, &[net::TEXT])?;+    let mut out = Vec::with_capacity(token.len() * chars as usize);+    for value in token {+        out.extend(std::iter::repeat_n(value, chars as usize));+    }+    Ok(out)+}++/// The unconditional branch's style values, `[256, 1, 50]` and already transposed in the file.+pub fn unconditional_style(weights: &Weights) -> Result<Vec<f32>, String> {+    tensor(weights, net::HOST_STYLE_TOKEN, &[net::STYLE, net::STYLE_TOKENS])+}++/// The folded style keys for one guidance branch, `[4 * 256, 1, 50]`.+///+/// `tanh(W_key . style_key + b_key)`, all constant, so the converter evaluates it. The four style+/// attentions share one `style_key` but each has its own `W_key`, so this is four 256-channel+/// blocks stacked; the plan slices its own out. The two branches have different `style_key`s,+/// which is the only structural difference between them — everything else is an input, so one+/// plan serves both.+pub fn style_keys(weights: &Weights, conditional: bool) -> Result<Vec<f32>, String> {+    let index = if conditional {+        net::HOST_KEYS_CONDITIONAL+    } else {+        net::HOST_KEYS_UNCONDITIONAL+    };+    tensor(+        weights,+        index,+        &[net::STYLE * net::MAIN_BLOCKS as u32, net::STYLE_TOKENS],+    )+}++/// One Euler step: combine the two guidance branches and advance the latent.+///+/// `denoised = latent + (GUIDANCE * conditional - (GUIDANCE - 1) * unconditional) / total`, which+/// is what the export's last five nodes do once its batch is split back in two.+pub fn step(+    latent: &[f32],+    conditional: &[f32],+    unconditional: &[f32],+    total: u32,+) -> Result<Vec<f32>, String> {+    if total == 0 {+        return Err("a sampler step out of no steps".into());+    }+    if conditional.len() != latent.len() || unconditional.len() != latent.len() {+        return Err(format!(+            "a step over {} latent values against {} conditional and {} unconditional",+            latent.len(),+            conditional.len(),+            unconditional.len()+        ));+    }+    let scale = 1.0 / total as f32;+    Ok(latent+        .iter()+        .zip(conditional)+        .zip(unconditional)+        .map(|((&x, &c), &u)| {+            let velocity = net::GUIDANCE * c - (net::GUIDANCE - 1.0) * u;+            x + velocity * scale+        })+        .collect())+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn mish_matches_its_definition_and_survives_a_large_input() {+        // `x * tanh(softplus(x))`. At 0 it is 0, at 1 it is 0.86509836, and at 100 it is 100 —+        // the last only because `softplus` is not computed as `ln(1 + e^100)`, which is inf.+        assert!((mish(0.0)).abs() < 1e-6);+        assert!((mish(1.0) - 0.865_098_4).abs() < 1e-5);+        assert!((mish(100.0) - 100.0).abs() < 1e-3);+        assert!(mish(100.0).is_finite());+        // And it is not ReLU: a small negative input is negative, not zero.+        assert!(mish(-1.0) < -0.3 && mish(-1.0) > -0.31);+    }++    #[test]+    fn a_linear_reads_its_weight_row_major() {+        // `[2, 3]` over three inputs. A column-major read would give (14, 32) here, which is+        // the same magnitude and the wrong answer.+        let weight = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0];+        let got = linear(&weight, &[10.0, 20.0], &[1.0, 1.0, 1.0]);+        assert_eq!(got, vec![16.0, 35.0]);+    }++    #[test]+    fn the_euler_step_is_guidance_four_over_the_step_count() {+        // `x + (4c - 3u) / total`. With c = u the guidance cancels to plain c, which is the+        // check that the two coefficients differ by exactly one.+        let got = step(&[0.0, 1.0], &[2.0, 2.0], &[2.0, 2.0], 4).expect("steps");+        assert_eq!(got, vec![0.5, 1.5]);+        // And with them apart, the conditional is extrapolated away from the unconditional.+        let got = step(&[0.0], &[1.0], &[0.0], 1).expect("steps");+        assert_eq!(got, vec![4.0]);+    }++    #[test]+    fn the_euler_step_refuses_mismatched_branches() {+        let error = step(&[0.0, 0.0], &[0.0], &[0.0, 0.0], 1).expect_err("a short branch");+        assert!(error.contains("conditional"), "{error}");+        let error = step(&[0.0], &[0.0], &[0.0], 0).expect_err("no steps");+        assert!(error.contains("no steps"), "{error}");+    }+}
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 83399b3d98..80e56ed191 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -79,6 +79,8 @@ pub mod graph {     pub const SUPERTONIC_DP: u32 = 12;     /// Supertonic 3's text encoder. See [`crate::nets::supertonic_text`].     pub const SUPERTONIC_TTL: u32 = 13;+    /// Supertonic 3's flow-matching sampler. See [`crate::nets::supertonic_sampler`].+    pub const SUPERTONIC_VE: u32 = 14; }  /// 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 3e55490c19..c62c1d491e 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -114,6 +114,7 @@ GRAPHS = {     "supertonic_voc": 11,     "supertonic_dp": 12,     "supertonic_ttl": 13,+    "supertonic_ve": 14, }  # SHA-256 over the ordered layer table (see `layer_table_digest`). Regenerate with@@ -132,6 +133,7 @@ EXPECTED_DIGEST = {     "supertonic_voc": "64e3a3437fa8f889fb679a5e08553ba7392c05a32cd844a0d2340698372a0071",     "supertonic_dp": "a294dac3e0fa1acf03d5a483b96782190a626c6adbc517969592ec6a888e15cd",     "supertonic_ttl": "92d0fa8ae73d4a8a223c77fb4230e390df580744014a3fcf3211ab72a988c020",+    "supertonic_ve": "d76f1fb13eaa9f5a16fed1f97a491d25f75325a36f00535fa3a11a7b16527951", }  # 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 a4ff88552d..a9b71be593 100644--- a/scripts/ml/onnx_parity.py+++ b/scripts/ml/onnx_parity.py@@ -65,6 +65,9 @@ PROBE = {     "supertonic_dp": "/sentence_encoder/Add_output_0",     # The graph's own output, which is the whole conditioning sequence.     "supertonic_ttl": None,+    # `denoised_latent`, the graph's own output. That is a whole Euler step over both guidance+    # branches, so the runtime side runs the plan twice - which is the point worth checking.+    "supertonic_ve": None, }  # Graphs that are one module of a larger export, and have to be cut out of it before they can@@ -164,6 +167,10 @@ def main():     parser.add_argument("onnx")     parser.add_argument("--width", type=int, default=64)     parser.add_argument("--maml", help="the .maml, for a graph that is a runtime download")+    parser.add_argument(+        "--probe",+        help="compare this tensor instead of the graph's usual one, for isolating a layer",+    )     args = parser.parse_args()      onnxruntime.set_default_logger_severity(3)@@ -176,7 +183,7 @@ def main():     # larger one, so there is nothing to extract.     if cut is not None and cut.get("first"):         model = extract(args.onnx, model, cut, work)-    probe = PROBE[args.graph] or final_logits(model)+    probe = args.probe or PROBE[args.graph] or final_logits(model)     if probe not in {o.name for o in model.graph.output}:         model.graph.output.append(             onnx.helper.make_tensor_value_info(probe, onnx.TensorProto.FLOAT, None)@@ -233,6 +240,29 @@ def main():         feed["text_mask"] = np.ones((1, 1, args.width), dtype=np.float32)         x = ids.astype(np.float32)         style.tofile(os.path.join(work, "style.f32"))+    elif args.graph == "supertonic_ve":+        # A latent, a text conditioning and a voice. `--width` is the latent length; the text is+        # deliberately a different length, because the rotary angles normalise each sequence by+        # its own and a square case would hide a swap.+        rng = np.random.default_rng(20240827)+        chars = max(4, args.width // 2)+        latent = rng.standard_normal((1, 144, args.width)).astype(np.float32)+        text = rng.standard_normal((1, 256, chars)).astype(np.float32)+        style = rng.standard_normal((1, 50, 256)).astype(np.float32)+        feed = {+            "noisy_latent": latent,+            "text_emb": text,+            "style_ttl": style,+            "latent_mask": np.ones((1, 1, args.width), dtype=np.float32),+            "text_mask": np.ones((1, 1, chars), dtype=np.float32),+            "current_step": np.array([5.0], dtype=np.float32),+            "total_step": np.array([16.0], dtype=np.float32),+        }+        x = latent+        text.tofile(os.path.join(work, "text.f32"))+        # Channel-major, which is how the runtime holds a sequence.+        np.ascontiguousarray(style.reshape(50, 256).T).tofile(os.path.join(work, "style.f32"))+        os.environ["PARITY_CHARS"] = str(chars)     else:         height = 48 if args.graph == "ppocr_rec" else args.width         # Deterministic and free of transcendentals, so both sides read identical bytes.@@ -262,6 +292,12 @@ def main():      # The runtime writes `[c, h, w]`; reshape the ONNX tensor to match by element count.     want = np.ascontiguousarray(reference).flatten()+    # Supertonic's sampler runs both classifier-free-guidance branches in one batch of two, so+    # an *internal* probe of it has twice the runtime's element count. The conditional branch is+    # the first half. The graph's own output is already combined, so this does not fire there.+    if want.size == got.size * 2 and args.graph == "supertonic_ve":+        want = want[: got.size]+        quantised = np.ascontiguousarray(quantised).flatten()[: got.size]     if want.size != got.size:         raise SystemExit(f"{probe}: onnx has {want.size} values, the runtime {got.size}")     if args.graph == "ppocr_rec":
scripts/ml/supertonic_fold.py
diff --git a/scripts/ml/supertonic_fold.py b/scripts/ml/supertonic_fold.pyindex bea32f6168..a26d8f2026 100644--- a/scripts/ml/supertonic_fold.py+++ b/scripts/ml/supertonic_fold.py@@ -61,6 +61,7 @@ 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     ./scripts/ml/supertonic_fold.py text_encoder.onnx --graph supertonic_ttl -o text.maml+    ./scripts/ml/supertonic_fold.py vector_estimator.onnx --graph supertonic_ve -o sampler.maml """  import argparse@@ -98,6 +99,23 @@ TE_PREFIX = "tts.ttl.text_encoder" TE_STYLE_PREFIX = "tts.ttl.speech_prompted_text_encoder" TE_STYLE_KEY = "tts.ttl.style_encoder.style_token_layer.style_key" +# The sampler's. `VE_PREFIX` is where every one of its parameters lives.+VE_LATENT = 144+VE_CHANNELS = 512+VE_INNER = 2048+VE_TEXT = 256+VE_STYLE = 256+VE_STYLE_TOKENS = 50+VE_TEXT_HEADS = 8+VE_STYLE_HEADS = 2+VE_TIME = 64+VE_TIME_INNER = 256+VE_MAIN_BLOCKS = 4+VE_LEADING = [1, 2, 4, 8]+VE_TRAILING = 4+VE_PREFIX = "vector_estimator.tts.ttl.vector_field"+VE_UNCOND = "vector_estimator.tts.ttl.uncond_masker"+  def constants(graph):     """Every initializer and `Constant` node output, by name."""@@ -569,6 +587,194 @@ def collect_text(graph):     return table.layers, table.tensors  +def collect_sampler(graph):+    """The sampler's layers and tensors, folded, in the order the Rust reads them.++    Four main blocks of `convnext x4, timestep shift, convnext, text attention, convnext, style+    attention`, then four trailing ConvNeXt blocks, between two unbiased projections. The+    export flattens the four into `main_blocks.0` .. `main_blocks.23`, six entries each.+    """+    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"+        )+    table = Table(held)++    def matmul(prefix, name):+        return matmul_weights(graph, held, prefix)[name]++    def linear(at, prefix, name, out_channels):+        """One `MatMul` plus its bias, as a 1x1 convolution. The weight is `[in, out]`."""+        weight = matmul(prefix, name).T+        bias = table.at(f"{at}.{name}.linear.bias")+        if weight.shape[0] != out_channels:+            raise SystemExit(f"{at}.{name} is {list(weight.shape)}, not [{out_channels}, in]")+        table.add(+            "Conv",+            f"{at}.{name}",+            f"Conv w={[*weight.shape, 1, 1]} b={list(bias.shape)} k={[1, 1]}"+            f" p={[0, 0, 0, 0]} g=1 pad=edge transposed",+            weight.reshape(weight.shape[0], weight.shape[1], 1, 1),+            bias,+        )++    def scaled_query(at, prefix, out_channels, heads):+        """`W_query`, with the difference between the export's /16 and 1/sqrt(head_dim) folded in.++        Both attentions divide by 16. `Builder::attn_scores` divides by `sqrt(head_dim)`, so the+        query carries `sqrt(head_dim) / 16` - exact, and safe across the rotary because a+        rotation commutes with a scalar.+        """+        scale = np.sqrt(out_channels / heads) / 16.0+        weight = matmul(prefix, "W_query").T * scale+        bias = table.at(f"{at}.W_query.linear.bias") * scale+        table.add(+            "Conv",+            f"{at}.W_query",+            f"Conv w={[*weight.shape, 1, 1]} b={list(bias.shape)} k={[1, 1]}"+            f" p={[0, 0, 0, 0]} g=1 pad=edge transposed scaled={scale:.6f}",+            weight.reshape(weight.shape[0], weight.shape[1], 1, 1),+            bias,+        )++    table.conv(f"{VE_PREFIX}.proj_in.net", VE_CHANNELS, synthesise_bias=True)++    for block in range(VE_MAIN_BLOCKS):+        base = block * 6+        for layer, dilation in enumerate(VE_LEADING):+            table.convnext(+                f"{VE_PREFIX}.main_blocks.{base}.convnext.{layer}",+                VE_CHANNELS,+                VE_INNER,+                dilation,+            )+        # `main_blocks.{base + 1}` is the timestep `Linear`, evaluated on the host.+        table.convnext(+            f"{VE_PREFIX}.main_blocks.{base + 2}.convnext.0", VE_CHANNELS, VE_INNER, 1+        )++        at = f"{VE_PREFIX}.main_blocks.{base + 3}.attn"+        prefix = f"/vector_estimator/vector_field/main_blocks.{base + 3}/attn/"+        scaled_query(at, prefix, VE_CHANNELS, VE_TEXT_HEADS)+        linear(at, prefix, "W_key", VE_CHANNELS)+        linear(at, prefix, "W_value", VE_CHANNELS)+        linear(at, prefix, "out_fc", VE_CHANNELS)+        table.layer_norm(f"{VE_PREFIX}.main_blocks.{base + 3}.norm.norm")++        table.convnext(+            f"{VE_PREFIX}.main_blocks.{base + 4}.convnext.0", VE_CHANNELS, VE_INNER, 1+        )++        at = f"{VE_PREFIX}.main_blocks.{base + 5}.attention"+        prefix = f"/vector_estimator/vector_field/main_blocks.{base + 5}/attention/"+        scaled_query(at, prefix, VE_STYLE, VE_STYLE_HEADS)+        linear(at, prefix, "W_value", VE_STYLE)+        linear(at, prefix, "out_fc", VE_CHANNELS)+        table.layer_norm(f"{VE_PREFIX}.main_blocks.{base + 5}.norm.norm")++    for layer in range(VE_TRAILING):+        table.convnext(f"{VE_PREFIX}.last_convnext.convnext.{layer}", VE_CHANNELS, VE_INNER, 1)++    table.conv(f"{VE_PREFIX}.proj_out.net", VE_LATENT, synthesise_bias=True)++    # Everything from here is read on the host. `nets::Builder::host_tensor` names each, so an+    # accidentally unread weight is still an error.+    theta = table.at(f"{VE_PREFIX}.main_blocks.3.attn.theta").reshape(-1)+    table.add("Host", "rotary theta", f"Host t={list(theta.shape)} rotary=theta", theta)+    frequencies = table.at(+        "/vector_estimator/vector_field/time_encoder/sinusoidal/Constant_3_output_0"+    ).reshape(-1)+    table.add(+        "Host", "time frequencies", f"Host t={list(frequencies.shape)} time=frequencies", frequencies+    )++    for which, (rows, columns) in (("mlp.0", (VE_TIME_INNER, VE_TIME)), ("mlp.2", (VE_TIME, VE_TIME_INNER))):+        at = f"{VE_PREFIX}.time_encoder.mlp.{which.split('.')[1]}.linear"+        weight = table.at(f"{at}.weight")+        bias = table.at(f"{at}.bias")+        if list(weight.shape) != [rows, columns]:+            raise SystemExit(f"{at} is {list(weight.shape)}, not {[rows, columns]}")+        table.add(+            "Host",+            at,+            f"Host w={list(weight.shape)} b={list(bias.shape)} time={which}",+            weight,+            bias,+        )++    for block in range(VE_MAIN_BLOCKS):+        base = block * 6 + 1+        at = f"{VE_PREFIX}.main_blocks.{base}.linear.linear"+        prefix = f"/vector_estimator/vector_field/main_blocks.{base}/linear/linear/"+        node = next(n for n in graph.node if n.name == f"{prefix}MatMul")+        weight = np.asarray(held[next(i for i in node.input if i in held)], dtype=np.float64).T+        bias = table.at(f"{at}.bias")+        table.add(+            "Host",+            at,+            f"Host w={list(weight.shape)} b={list(bias.shape)} time=shift{block} transposed",+            weight,+            bias,+        )++    token = table.at(f"{VE_UNCOND}.text_special_token").reshape(-1)+    table.add("Host", "text_special_token", f"Host t={list(token.shape)} uncond=text", token)+    style = np.ascontiguousarray(+        table.at(f"{VE_UNCOND}.style_value_special_token").reshape(-1, VE_STYLE).T+    )+    table.add("Host", "style_value_special_token", f"Host t={list(style.shape)} uncond=style", style)++    # The two branches' style keys, `tanh(W_key . style_key + b_key)`, entirely constant. The+    # conditional key is a nameless initializer reached through the `Tile` that broadcasts it.+    for label, source in (("conditional", conditional_style_key(graph, held)), ("unconditional", f"{VE_UNCOND}.style_key_special_token")):+        # One `style_key` but four `W_key`s, so four folded tensors per branch, stacked along+        # channels for `Builder::slice_channels` to cut apart. Folding only the first left the+        # net exact through ten sub-blocks and then wrong, which is what the bisect found.+        stacked = []+        for block in range(VE_MAIN_BLOCKS):+            index = block * 6 + 5+            keys = matmul_weights(+                graph, held, f"/vector_estimator/vector_field/main_blocks.{index}/attention/"+            )["W_key"]+            bias = table.at(f"{VE_PREFIX}.main_blocks.{index}.attention.W_key.linear.bias")+            folded = np.tanh(table.at(source).reshape(-1, VE_STYLE) @ keys + bias)+            if folded.shape != (VE_STYLE_TOKENS, VE_STYLE):+                raise SystemExit(f"{label} keys for block {block} folded to {list(folded.shape)}")+            stacked.append(np.ascontiguousarray(folded.T))+        folded = np.concatenate(stacked, axis=0)+        table.add(+            "Host",+            f"style keys {label}",+            f"Host t={list(folded.shape)} folded=tanh(W_key.style_key+b) {label}",+            folded,+        )+    return table.layers, table.tensors+++def conditional_style_key(graph, held):+    """The name of the conditional `style_key`, which the export leaves nameless.++    It reaches `W_key` through a `Concat` of a `Tile` of itself and an `Expand` of the+    unconditional token, so it is found rather than spelled.+    """+    producer = {o: n for n in graph.node for o in n.output}+    node = next(+        n+        for n in graph.node+        if n.name == "/vector_estimator/vector_field/main_blocks.5/attention/W_key/linear/MatMul"+    )+    concat = producer[node.input[0]]+    for branch in concat.input:+        broadcast = producer[branch]+        for name in broadcast.input:+            if name in held and list(np.asarray(held[name]).shape) == [1, VE_STYLE_TOKENS, VE_STYLE]:+                if "uncond" not in name:+                    return name+    raise SystemExit("no conditional style_key found ahead of the style W_key")++ def main():     parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])     parser.add_argument("onnx")@@ -585,6 +791,8 @@ def main():         layers, tensors = collect_duration(model.graph)     elif args.graph == "supertonic_ttl":         layers, tensors = collect_text(model.graph)+    elif args.graph == "supertonic_ve":+        layers, tensors = collect_sampler(model.graph)     else:         layers, tensors = collect(model.graph)