library:ml: Supertonic's text encoder, with the style keys folded
- Commit
a66bb836495b93b2b0061de79a1d035b238f0c50- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 15:19 UTC (3 months ago)
- Parents
e9a3014
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 0bf0abc445..32d27dcb59 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_text; pub mod supertonic_vocoder; pub mod u2netp; pub mod vits_dec;
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 c6fc4f6c17..60e96f6eb7 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -1059,8 +1059,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_vocoder,- u2netp, vits_dec, vits_enc, vits_flow, Act, Builder, EMBED_LANE,+ 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, }; use super::*; @@ -2554,6 +2554,27 @@ mod tests { println!("supertonic_voc at {width} frames: wrote {} values", samples.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}"));+ let weights =+ crate::weights::Weights::parse(&bytes, crate::weights::graph::SUPERTONIC_TTL)+ .expect("the text encoder asset parses");+ let plan = supertonic_text::build(&weights, width).expect("the text encoder 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();+ let ids: Vec<u32> = input.iter().map(|&v| v as u32).collect();+ let lanes = super::super::embed_lanes(&ids);+ let outputs = run_multi(&plan, weights.data(), &[&lanes, &style])+ .expect("the text encoder runs");+ let emb = outputs.first().expect("the conditioning output");+ write(&dir.join("reference.f32"), emb);+ println!("supertonic_ttl at {width} chars: wrote {} values", emb.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}"));
library/ml/src/main/rust/src/nets/supertonic_text.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_text.rs b/library/ml/src/main/rust/src/nets/supertonic_text.rsnew file mode 100644index 0000000000..b9ec20937c--- /dev/null+++ b/library/ml/src/main/rust/src/nets/supertonic_text.rs@@ -0,0 +1,468 @@+//! Supertonic 3's text encoder: characters and a voice to a 256-channel conditioning sequence.+//!+//! # What it is+//!+//! The duration predictor's sentence encoder, four times wider, plus a style path it does not+//! have. 1934 ONNX nodes and 9,000,960 parameters: a character embedding, six ConvNeXt blocks at+//! 256/1024, four layers of relative-position attention, a skip around the whole attention+//! stack, and then two **cross**-attentions from the text over 50 style tokens.+//!+//! Same as `nets::supertonic_duration` and for the same reasons: symmetric edge padding, six+//! `[1, 256, 1]` layer scales folded into their `pwconv2`, post-norm attention layers whose+//! feed-forward convolutions are 1x1, and a padding mask that is the identity for one+//! utterance. Two differences: the depthwise dilations are **1, 1, 2, 2, 4, 4** rather than all+//! ones, and there is no sentence token — the output is the whole sequence.+//!+//! `proj_out` appears in `onnx/tts.json` but not in the export: its input and output widths are+//! both 256, so it is an identity and carries no weights.+//!+//! # The style path+//!+//! `/speech_prompted_text_encoder/`, two attentions over the voice's 50 style tokens:+//!+//! ```text+//! h1 = x + out_fc1(attend(Wq1 x, K1, Wv1 style))+//! h2 = x + out_fc2(attend(Wq2 h1, K2, Wv2 style))+//! out = layer_norm(h2)+//! ```+//!+//! The second attention's **query** comes from `h1` but its residual comes from `x` again, not+//! from `h1`. That is what the export does and it is easy to write the other way round.+//!+//! Three things that are not obvious:+//!+//! * **The keys are constant.** `K = tanh(W_key . style_key + b_key)`, and `style_key` is a+//! learned `[50, 256]` table, so the whole expression folds to one tensor per attention at+//! conversion time. It has to reach the arena to be an attention operand, which is what+//! [`super::Kind::Constant`] is for. This removes two convolutions, two biases and two+//! tanhs.+//! * **The scale is `/16`, not `1 / sqrt(head_dim)`.** Two heads of 128, so+//! [`Builder::attn_scores`]'s own scale is `sqrt(2)` too large. The converter folds+//! `sqrt(128) / 16` into `W_query`, which is exact and costs no op.+//! * **`style_ttl` is position-major in the export** (`[1, 50, 256]`) and this runtime is+//! channel-major, so the caller passes it transposed to `[256, 1, 50]`.+//!+//! # Weights that are `MatMul`s, not `Conv`s+//!+//! Every projection in the style path is a `MatMul` over `[T, 256]`, so its weight is+//! `[in, out]` — the **transpose** of the `[out, in, 1, 1]` a 1x1 convolution reads. All eight+//! are 256x256, where a missed transpose is invisible in the shape and produces a plausible+//! wrong answer. The converter transposes them; `scripts/ml/supertonic_fold.py` says so at the+//! one place it happens.+//!+//! # Measured parity, and why it is above the script's bar+//!+//! Against onnxruntime at 24 characters, on `text_emb`: correlation 0.99948766, max 0.077335 on+//! values reaching 1.46. `onnx_parity.py`'s "fp16 weights alone" bar is 0.023410, so the runtime+//! is over three times it — and that bar keeps activations in fp32, which this runtime does not.+//!+//! Walking the same run inwards shows diffuse fp16 accumulation rather than one wrong layer:+//!+//! | tensor | `|values|` | runtime max | in fp16 ULPs |+//! | --- | --- | --- | --- |+//! | after the six ConvNeXt blocks | 0.72 | 0.00267 | ~5 |+//! | after the four attention layers | 7.29 | 0.0724 | ~15 |+//! | after the final layer norm | 1.46 | 0.0773 | ~80 |+//!+//! Five ULPs after roughly twenty-four fp16 stores, fifteen after forty. The last row is the+//! layer norm dividing by a standard deviation smaller than the signal it normalises, which+//! amplifies whatever came in. Correlation stays above 0.9999 at every depth, and a structural+//! error in a net this size shows up an order of magnitude below that — the duration predictor's+//! two wrong hypotheses correlated at 0.02 and 0.009.++use super::{Act, Builder, Id, Plan, Shape, WeightSource};++/// Characters in the embedding table. No sentence token here, unlike the duration predictor.+pub const SYMBOLS: u32 = 8322;++/// Channels throughout. `char_emb_dim`, `hidden_channels` and `text_dim` are all 256.+pub const D_MODEL: u32 = 256;++/// The ConvNeXt widening and the attention feed-forward's width: `intermediate_dim` and+/// `filter_channels`, both 1024.+pub const INNER: u32 = 1024;++/// Heads in the relative-position attention, so `head_dim` is 64 — the relative table's width.+pub const HEADS: u32 = 4;++/// Entries in each relative position table: `2 * window + 1` at `window_size` 4.+pub const OFFSETS: u32 = 9;++/// ConvNeXt blocks.+pub const BLOCKS: usize = 6;++/// Relative-attention layers.+pub const ATTN_LAYERS: usize = 4;++/// Style tokens the two cross-attentions attend over. `n_style`.+pub const STYLE_TOKENS: u32 = 50;++/// Heads in each style cross-attention, so `head_dim` is 128. `n_heads` of+/// `speech_prompted_text_encoder`.+pub const STYLE_HEADS: u32 = 2;++/// Cross-attentions in the style path.+pub const STYLE_ATTENTIONS: usize = 2;++/// Each block's depthwise dilation, read from the export in order. `dilation_lst`, and not the+/// duration predictor's all-ones.+const DILATIONS: [u32; BLOCKS] = [1, 1, 2, 2, 4, 4];++/// The depthwise kernel width, `ksz`.+const KERNEL: u32 = 5;++/// The epsilon in all fifteen layer norms.+const EPSILON: f32 = 1e-5;++/// Tensors the `.maml` must hold.+///+/// The embedding table (1), six blocks of eight (48), four attention layers of eighteen (72),+/// two style attentions of seven (14) and the final layer norm (2). The seven are `W_query`,+/// the folded constant keys, `W_value` and `out_fc` — a pair each except the keys.+pub const TENSORS: usize = 137;++/// 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, the folded style keys.+ fn take_one(&mut self) -> usize {+ let index = self.next;+ self.next += 1;+ 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)+}++/// The depthwise convolution along the sequence, padded symmetrically so the length holds.+fn depthwise(b: &mut Builder, l: &mut Layers, x: Id, dilation: u32) -> Id {+ let each = dilation * (KERNEL - 1) / 2;+ b.conv(+ x,+ l.take(),+ D_MODEL,+ (1, KERNEL),+ (1, 1),+ (1, dilation),+ // (top, left, bottom, right). `2 * dilation` each side, verified against the export's+ // own `Pad` inputs at all six dilations.+ (0, each, 0, each),+ D_MODEL,+ Act::None,+ )+}++/// Build the encoder for an utterance of `chars` characters.+///+/// Two inputs, in this order: the character ids as the two lanes [`super::Kind::Embed`] wants,+/// and the voice's `style_ttl` **transposed** to `[256, 1, 50]`. The output is+/// `[256, 1, chars]`, which the sampler conditions on.+pub fn build(weights: &dyn WeightSource, chars: u32) -> Result<Plan, String> {+ if chars == 0 {+ return Err("a text encoder 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.+ b.edge_padding();++ let ids = b.input(Shape::new(2, 1, chars));+ let style = b.input(Shape::new(D_MODEL, 1, STYLE_TOKENS));+ let mut x = b.embed(ids, l.take_one(), SYMBOLS, D_MODEL);++ for &dilation in &DILATIONS {+ let along = depthwise(b, l, x, dilation);+ 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, as in the duration predictor.+ 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);+ let residual = b.add(x, attended);+ x = b.layer_norm(residual, l.take(), EPSILON);++ 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 text = b.add(convnext, x);++ // The style path. Both attentions read `text` as their residual; only the second's query+ // comes from the first's output.+ let mut query_source = text;+ let mut attended = text;+ for _ in 0..STYLE_ATTENTIONS {+ let q = point(b, l, query_source, D_MODEL, Act::None);+ // `tanh(W_key . style_key + b_key)`, folded to one tensor. It is an attention operand+ // rather than a kernel, so it is loaded into the arena.+ let keys = b.constant(l.take_one(), Shape::new(D_MODEL, 1, STYLE_TOKENS));+ let values = point(b, l, style, D_MODEL, Act::None);+ let scores = b.attn_scores(q, keys, STYLE_HEADS);+ let probs = b.softmax(scores);+ let mixed = b.attn_apply(probs, values, STYLE_HEADS);+ let projected = point(b, l, mixed, D_MODEL, Act::None);+ attended = b.add(text, projected);+ query_source = attended;+ }+ let out = b.layer_norm(attended, l.take(), EPSILON);++ if l.next != TENSORS {+ return Err(format!("the forward pass claims {} tensors, not {TENSORS}", l.next));+ }+ builder.finish(&[out])+}++#[cfg(test)]+mod tests {+ use super::super::tests::{assert_no_aliasing, Shapes};+ use super::super::{Kind, Op};+ use super::*;++ /// A short sentence.+ const CHARS: u32 = 24;++ fn plan(chars: u32) -> (Shapes, Plan) {+ let source = Shapes::new(TENSORS);+ let plan = build(&source, chars).expect("the text encoder 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 9,000,960 parameters. Three differences:+ //+ // - the six `[1, 256, 1]` layer scales fold into their `pwconv2`: -1,536+ // - `W_key` and its bias fold into the constant keys, twice: -131,584+ // - `style_key` (12,800) becomes one folded `[256, 50]` per+ // attention rather than one table shared by both: +12,800+ 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, 9_000_960 - 1_536 - 131_584 + 12_800);+ // And spelled out, so a reordering that preserved the sum would still be caught.+ assert_eq!(total, 8_880_640);+ }++ #[test]+ fn the_inputs_are_ids_and_a_transposed_style() {+ // `style_ttl` is `[1, 50, 256]` in the export and `[256, 1, 50]` here: 50 positions of+ // 256 channels, which is the layout every other sequence in this runtime uses. Feeding+ // it untransposed would be 256 positions of 50 channels — a shape the plan refuses+ // rather than a wrong answer, which is the point of checking it here.+ let (_, plan) = plan(CHARS);+ let inputs: Vec<Shape> = plan.inputs.iter().map(|b| b.shape).collect();+ assert_eq!(+ inputs,+ vec![Shape::new(2, 1, CHARS), Shape::new(D_MODEL, 1, STYLE_TOKENS)]+ );+ assert_eq!(+ plan.output().expect("one output").shape,+ Shape::new(D_MODEL, 1, CHARS)+ );+ }++ #[test]+ fn the_style_attention_is_a_cross_attention_over_fifty_tokens() {+ // The score maps are `[2, chars, 50]` — not square, which is the whole reason the+ // attention ops take two lengths. The relative ones are square, so this also pins that+ // the two kinds have not been swapped.+ let (_, plan) = plan(CHARS);+ let cross: 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();+ assert_eq!(cross, vec![(STYLE_HEADS, CHARS, STYLE_TOKENS); STYLE_ATTENTIONS]);+ let square: Vec<(u32, u32, u32)> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ Op::Dispatch { kind: Kind::AttnScoresRelative, push, .. } => {+ Some((push.out_c, push.out_h, push.out_w))+ }+ _ => None,+ })+ .collect();+ assert_eq!(square, vec![(HEADS, CHARS, CHARS); ATTN_LAYERS]);+ }++ #[test]+ fn the_style_mix_writes_one_vector_per_character() {+ // 50 keys in, `chars` out. An `attn_apply` that took its width from the values would+ // write a 50-position tensor and the residual after it would refuse the shape.+ let (_, plan) = plan(CHARS);+ let mixes: Vec<(u32, u32)> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ Op::Dispatch { kind: Kind::AttnApply, push, .. } => Some((push.in_w, push.out_w)),+ _ => None,+ })+ .collect();+ assert_eq!(mixes, vec![(STYLE_TOKENS, CHARS); STYLE_ATTENTIONS]);+ }++ #[test]+ fn the_style_keys_are_loaded_from_the_weights_file() {+ // Two of them, one per attention, each `[256, 1, 50]`. If these were still a+ // convolution over a `style_key` input the plan would have three inputs.+ let (_, plan) = plan(CHARS);+ let loaded: Vec<(u32, u32, u32)> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ Op::Dispatch { kind: Kind::Constant, push, .. } => {+ Some((push.out_c, push.out_h, push.out_w))+ }+ _ => None,+ })+ .collect();+ assert_eq!(loaded, vec![(D_MODEL, 1, STYLE_TOKENS); STYLE_ATTENTIONS]);+ assert_eq!(plan.inputs.len(), 2);+ }++ #[test]+ fn the_depthwise_dilations_are_the_exports_own_sequence() {+ // 1, 1, 2, 2, 4, 4 — pairs, unlike the vocoder's 1, 2, 4, 1, 2, 4 and unlike the+ // duration predictor's all-ones. The pad follows the dilation, so getting the table+ // wrong shifts the signal as well as widening the wrong receptive field.+ let (_, plan) = plan(CHARS);+ let found: Vec<(u32, u32)> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ Op::Dispatch { kind: Kind::Conv, push, .. } if push.group == D_MODEL => {+ Some((push.dil_w, push.pad_l))+ }+ _ => None,+ })+ .collect();+ let want: Vec<(u32, u32)> =+ DILATIONS.iter().map(|&d| (d, d * (KERNEL - 1) / 2)).collect();+ assert_eq!(found, want);+ }++ #[test]+ fn nothing_changes_the_sequence_length() {+ let (_, plan) = plan(CHARS);+ for (step, op) in plan.ops.iter().enumerate() {+ if let Op::Dispatch { kind: Kind::Conv, push, .. } = op {+ // The style path's `W_value` runs over the 50 tokens; everything else over+ // the characters.+ assert!(+ 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 the_op_inventory_is_six_blocks_four_layers_and_two_style_attentions() {+ 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;+ }+ }+ // Three per block, six per attention layer, three per style attention.+ let convolutions = BLOCKS * 3 + ATTN_LAYERS * 6 + STYLE_ATTENTIONS * 3;+ assert_eq!(counts.get("Conv"), Some(&convolutions), "{counts:?}");+ assert_eq!(counts.get("Embed"), Some(&1), "{counts:?}");+ assert_eq!(counts.get("Constant"), Some(&STYLE_ATTENTIONS), "{counts:?}");+ assert_eq!(counts.get("AttnScoresRelative"), Some(&ATTN_LAYERS), "{counts:?}");+ assert_eq!(counts.get("AttnApplyRelative"), Some(&ATTN_LAYERS), "{counts:?}");+ assert_eq!(counts.get("AttnScores"), Some(&STYLE_ATTENTIONS), "{counts:?}");+ assert_eq!(counts.get("AttnApply"), Some(&STYLE_ATTENTIONS), "{counts:?}");+ assert_eq!(+ counts.get("Softmax"),+ Some(&(ATTN_LAYERS + STYLE_ATTENTIONS)),+ "{counts:?}"+ );+ // Six block residuals, two per attention layer, the whole-stack skip, and one per+ // style attention.+ assert_eq!(+ counts.get("Add"),+ Some(&(BLOCKS + ATTN_LAYERS * 2 + 1 + STYLE_ATTENTIONS)),+ "{counts:?}"+ );+ assert_eq!(+ counts.get("LayerNorm"),+ Some(&(BLOCKS + ATTN_LAYERS * 2 + 1)),+ "{counts:?}"+ );+ assert_eq!(counts.len(), 10, "{counts:?}");+ }++ #[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 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() {+ for chars in [CHARS, 400] {+ let (_, plan) = plan(chars);+ let mib = plan.arena_elems as f32 * 2.0 / (1024.0 * 1024.0);+ println!("supertonic_text at {chars} chars: {mib:.2} MiB");+ assert!(mib < 128.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 168582f46f..83399b3d98 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -77,6 +77,8 @@ pub mod graph { pub const SUPERTONIC_VOC: u32 = 11; /// Supertonic 3's duration predictor. See [`crate::nets::supertonic_duration`]. pub const SUPERTONIC_DP: u32 = 12;+ /// Supertonic 3's text encoder. See [`crate::nets::supertonic_text`].+ pub const SUPERTONIC_TTL: u32 = 13; } /// 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 e64bfacd2b..3e55490c19 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -113,6 +113,7 @@ GRAPHS = { "vits_dp": 10, "supertonic_voc": 11, "supertonic_dp": 12,+ "supertonic_ttl": 13, } # SHA-256 over the ordered layer table (see `layer_table_digest`). Regenerate with@@ -130,6 +131,7 @@ EXPECTED_DIGEST = { "vits_dp": "d02a6e28700823af95cbeeeb2b40d77e531f90086599deb3f840ce9a2a57a494", "supertonic_voc": "64e3a3437fa8f889fb679a5e08553ba7392c05a32cd844a0d2340698372a0071", "supertonic_dp": "a294dac3e0fa1acf03d5a483b96782190a626c6adbc517969592ec6a888e15cd",+ "supertonic_ttl": "92d0fa8ae73d4a8a223c77fb4230e390df580744014a3fcf3211ab72a988c020", } # 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 13f47ba227..a4ff88552d 100644--- a/scripts/ml/onnx_parity.py+++ b/scripts/ml/onnx_parity.py@@ -63,6 +63,8 @@ PROBE = { # 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",+ # The graph's own output, which is the whole conditioning sequence.+ "supertonic_ttl": None, } # Graphs that are one module of a larger export, and have to be cut out of it before they can@@ -212,18 +214,23 @@ def main(): "scales": np.array([0.667, 1.0, 0.8], dtype=np.float32), } x = ids.astype(np.float32)- elif args.graph == "supertonic_dp":+ elif args.graph in ("supertonic_dp", "supertonic_ttl"): # 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.+ # `embed_lanes` exists. 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),- }+ if args.graph == "supertonic_dp":+ # `[1, 8, 16]`, which flattens row-major to 128.+ style = rng.standard_normal((1, 8, 16)).astype(np.float32)+ feed = {"text_ids": ids, "style_dp": style}+ else:+ # `[1, 50, 256]` position-major, which the runtime reads transposed. Writing the+ # transpose here is what the voice bundle will hold.+ style = rng.standard_normal((1, 50, 256)).astype(np.float32)+ feed = {"text_ids": ids, "style_ttl": style}+ style = np.ascontiguousarray(style.reshape(50, 256).T)+ 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")) else:
scripts/ml/supertonic_fold.py
diff --git a/scripts/ml/supertonic_fold.py b/scripts/ml/supertonic_fold.pyindex 171897fa55..bea32f6168 100644--- a/scripts/ml/supertonic_fold.py+++ b/scripts/ml/supertonic_fold.py@@ -45,9 +45,22 @@ Unlike the vocoder this graph is **not** entirely edge-padded — twelve of its the relative-attention skew and are `constant`. What matters is that every pad feeding a *convolution* replicates, which is checked separately. +# The text encoder++`--graph supertonic_ttl` is the same shape again, four times wider, with two additions:++ block gamma [1, 256, 1] -> folds into that block's `pwconv2`, as above+ tanh(W_key . style_key + b) -> folded to one `[256, 50]` tensor per style attention+ W_query -> scaled by sqrt(128)/16, since the export's own scale is+ sqrt(256) and `Builder::attn_scores` uses sqrt(head_dim)++Every projection in its style path is a `MatMul` whose weight is `[in, out]`, so all eight are+**transposed** here. They are all 256x256, where a missed transpose is invisible in the shape.+ 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 """ import argparse@@ -74,6 +87,17 @@ DP_ATTN_LAYERS = 2 DP_HIDDEN = 128 DP_PREFIX = "tts.dp.sentence_encoder" +# The text encoder's, likewise.+TE_CHANNELS = 256+TE_INNER = 1024+TE_BLOCKS = 6+TE_ATTN_LAYERS = 4+TE_STYLE_TOKENS = 50+TE_STYLE_HEADS = 2+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"+ def constants(graph): """Every initializer and `Constant` node output, by name."""@@ -288,44 +312,51 @@ 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.+class Table:+ """The `.maml` layer table under construction, for a graph collected by parameter name. - 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.+ The vocoder is a plain stack where walking the ONNX nodes lands each tensor in the right+ slot. The duration predictor and the text encoder are not: each attention layer interleaves+ two relative-position tables, several mask multiplies and a twenty-node skew, so naming each+ tensor is both shorter and checkable against the Rust 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)+ def __init__(self, held):+ self.held = held+ self.layers = []+ self.tensors = [] - layers, tensors = [], []+ def at(self, name):+ if name not in self.held:+ raise SystemExit(f"{name} is not in this export")+ return np.asarray(self.held[name], dtype=np.float64) - def add(op, name, key, *values):- first = len(tensors)+ def add(self, op, name, key, *values):+ first = len(self.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)))+ self.tensors.append(np.ascontiguousarray(value, dtype=np.float32))+ self.layers.append(+ maml_convert.Layer(len(self.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")+ def conv(self, name, out_channels, fold_scale=None, synthesise_bias=False,+ pads=(0, 0, 0, 0), kernel=(1, 1), group=1, transpose=False, scale=None):+ """One convolution's pair, lifted to the rank-4 `[out, in, 1, k]` the Rust indexes.++ `transpose` is for the style path's `MatMul`s, whose weight is `[in, out]` \u2014 all eight of+ them are 256x256, where a missed transpose is invisible in the shape.+ """+ weight = self.at(f"{name}.weight") if synthesise_bias: bias = np.zeros(out_channels, dtype=np.float64) else:- bias = held_at(f"{name}.bias")+ bias = self.at(f"{name}.bias")+ if transpose:+ weight = weight.T if fold_scale is not None: weight, bias = fold_output(weight, bias, fold_scale, 0.0)+ if scale is not None:+ weight, bias = weight * scale, bias * scale 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)@@ -333,7 +364,9 @@ def collect_duration(graph): 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(+ note += " transposed" if transpose else ""+ note += f" scaled={scale:.6f}" if scale is not None else ""+ self.add( "Conv", name, f"Conv w={list(weight.shape)} b={list(bias.shape)} k={list(kernel)}"@@ -342,10 +375,10 @@ def collect_duration(graph): bias, ) - def layer_norm(name):- gamma = held_at(f"{name}.weight")- beta = held_at(f"{name}.bias")- add(+ def layer_norm(self, name):+ gamma = self.at(f"{name}.weight")+ beta = self.at(f"{name}.bias")+ self.add( "LayerNorm", name, f"LayerNorm g={list(gamma.shape)} b={list(beta.shape)}",@@ -353,64 +386,187 @@ def collect_duration(graph): beta, ) + def convnext(self, at, channels, inner, dilation):+ """One ConvNeXt block: depthwise, norm, widening 1x1, narrowing 1x1 with the gamma.++ Symmetric padding, `2 * dilation` each side. The vocoder's is causal instead, and that+ difference cost real debugging time once already.+ """+ each = dilation * 4 // 2+ self.conv(+ f"{at}.dwconv",+ channels,+ pads=(0, each, 0, each),+ kernel=(1, 5),+ group=channels,+ )+ self.layer_norm(f"{at}.norm.norm")+ self.conv(f"{at}.pwconv1", inner)+ # The block's gamma rides on `pwconv2`, which is a 1x1 and so has no border.+ self.conv(f"{at}.pwconv2", channels, fold_scale=self.at(f"{at}.gamma").reshape(-1))++ def relative_attention(self, at, layer, channels, inner, head_dim):+ """One post-norm relative-attention layer, in the order the export declares it."""+ attn = f"{at}.attn_layers.{layer}"+ for projection in ("conv_q", "conv_k", "conv_v"):+ self.conv(f"{attn}.{projection}", channels)+ # `[1, 9, head_dim]` in the export; the Rust reads `[offsets, head_dim]`.+ for table_name in ("emb_rel_k", "emb_rel_v"):+ relative = self.at(f"{attn}.{table_name}").reshape(9, -1)+ if relative.shape[1] != head_dim:+ raise SystemExit(f"{attn}.{table_name} is {list(relative.shape)}, not [9, {head_dim}]")+ self.add("RelPos", f"{attn}.{table_name}", f"RelPos t={list(relative.shape)}", relative)+ self.conv(f"{attn}.conv_o", channels)+ self.layer_norm(f"{at}.norm_layers_1.{layer}.norm")+ self.conv(f"{at}.ffn_layers.{layer}.conv_1", inner)+ self.conv(f"{at}.ffn_layers.{layer}.conv_2", channels)+ self.layer_norm(f"{at}.norm_layers_2.{layer}.norm")+++def collect_duration(graph):+ """The duration predictor's layers and tensors, folded, in the order the Rust reads them."""+ 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)+ # 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)+ rows = table.at(f"{DP_PREFIX}.text_embedder.char_embedder.weight")+ token = table.at(f"{DP_PREFIX}.sentence_token").reshape(1, -1)+ if token.shape[1] != rows.shape[1]:+ raise SystemExit(f"a {list(token.shape)} sentence token for a {list(rows.shape)} table")+ rows = np.concatenate([rows, token], axis=0)+ table.add(+ "Embed", "char_embedder+sentence_token", f"Embed t={list(rows.shape)} token=last", rows+ ) 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))-+ table.convnext(f"{DP_PREFIX}.convnext.convnext.{block}", DP_CHANNELS, DP_INNER, 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")+ table.relative_attention(f"{DP_PREFIX}.attn_encoder", layer, DP_CHANNELS, DP_INNER, 32) # `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)+ table.conv(f"{DP_PREFIX}.proj_out.net", DP_CHANNELS, synthesise_bias=True)+ table.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(+ table.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+ table.conv("tts.dp.predictor.layers.1", 1)+ return table.layers, table.tensors+++def style_attention(table, graph, which):+ """One of the text encoder's two cross-attentions over the 50 style tokens.++ Four entries: `W_query` (scaled), the folded constant keys, `W_value` and `out_fc`.+ """+ at = f"{TE_STYLE_PREFIX}.attention{which}"+ linears = matmul_weights(+ graph, table.held, f"/speech_prompted_text_encoder/attention{which}/"+ )+ head_dim = TE_CHANNELS // TE_STYLE_HEADS+ # The export divides the scores by 16 = sqrt(256), not by sqrt(head_dim) = sqrt(128), so+ # `Builder::attn_scores`'s own scale is sqrt(2) too large. Folding the difference into the+ # query projection is exact and costs no op.+ scale = np.sqrt(head_dim) / 16.0+ square = [TE_CHANNELS, TE_CHANNELS, 1, 1]+ table.add(+ "Conv",+ f"{at}.W_query",+ f"Conv w={square} b={[TE_CHANNELS]} k={[1, 1]} p={[0, 0, 0, 0]} g=1 pad=edge"+ f" transposed scaled={scale:.6f}",+ (linears["W_query"].T * scale).reshape(*square),+ table.at(f"{at}.W_query.linear.bias") * scale,+ )++ # `tanh(W_key . style_key + b_key)` is entirely constant, so it folds to one tensor. Stored+ # channel-major as `[256, 1, 50]`, which is what `Kind::Constant` loads and+ # `Kind::AttnScores` contracts.+ style_key = table.at(TE_STYLE_KEY).reshape(-1, TE_CHANNELS)+ keys = np.tanh(style_key @ linears["W_key"] + table.at(f"{at}.W_key.linear.bias"))+ if keys.shape != (TE_STYLE_TOKENS, TE_CHANNELS):+ raise SystemExit(f"{at}: folded keys are {list(keys.shape)}")+ keys = np.ascontiguousarray(keys.T).reshape(TE_CHANNELS, 1, TE_STYLE_TOKENS)+ table.add(+ "Constant",+ f"{at}.keys",+ f"Constant t={list(keys.shape)} folded=tanh(W_key.style_key+b_key)",+ keys,+ )++ for name in ("W_value", "out_fc"):+ table.add(+ "Conv",+ f"{at}.{name}",+ f"Conv w={square} b={[TE_CHANNELS]} k={[1, 1]} p={[0, 0, 0, 0]} g=1 pad=edge"+ " transposed",+ linears[name].T.reshape(*square),+ table.at(f"{at}.{name}.linear.bias"),+ )+++def matmul_weights(graph, held, prefix):+ """The four `MatMul` weights under the node-name `prefix`, by the linear they belong to.++ They are `onnx::MatMul_3680` and friends rather than named parameters, so each is found+ through the node that consumes it.+ """+ wanted = ("W_query", "W_key", "W_value", "out_fc")+ found = {}+ for node in graph.node:+ if node.op_type != "MatMul" or not node.name.startswith(prefix):+ continue+ for name in wanted:+ if f"/{name}/" not in node.name:+ continue+ weights = [i for i in node.input if i in held]+ if len(weights) != 1:+ raise SystemExit(f"{node.name} has {len(weights)} held inputs, expected one")+ found[name] = np.asarray(held[weights[0]], dtype=np.float64)+ missing = set(wanted) - set(found)+ if missing:+ raise SystemExit(f"{prefix}: no MatMul found for {sorted(missing)}")+ return found+++def collect_text(graph):+ """The text encoder's layers and tensors, folded, in the order the Rust reads them."""+ 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)++ rows = table.at(f"{TE_PREFIX}.text_embedder.char_embedder.weight")+ table.add("Embed", "char_embedder", f"Embed t={list(rows.shape)}", rows)++ # 1, 1, 2, 2, 4, 4 - pairs, and the pad follows the dilation.+ for block, dilation in enumerate([1, 1, 2, 2, 4, 4]):+ table.convnext(f"{TE_PREFIX}.convnext.convnext.{block}", TE_CHANNELS, TE_INNER, dilation)+ for layer in range(TE_ATTN_LAYERS):+ table.relative_attention(f"{TE_PREFIX}.attn_encoder", layer, TE_CHANNELS, TE_INNER, 64)++ for which in (1, 2):+ style_attention(table, graph, which)+ table.layer_norm(f"{TE_STYLE_PREFIX}.norm.norm")+ return table.layers, table.tensors def main():@@ -427,6 +583,8 @@ def main(): model = onnx.load(args.onnx) if args.graph == "supertonic_dp": layers, tensors = collect_duration(model.graph)+ elif args.graph == "supertonic_ttl":+ layers, tensors = collect_text(model.graph) else: layers, tensors = collect(model.graph)