library:ml: Piper's VITS text encoder, verified against onnxruntime
- Commit
5a083ea6b2388ce6a154f4f6fa16826b8fd91058- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 00:04 UTC (3 months ago)
- Parents
346f4a6
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 b1fdf39f9d..bc7c7bddce 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -38,6 +38,7 @@ pub mod scrfd; pub mod selfie; pub mod u2netp; pub mod vits_dec;+pub mod vits_enc; /// A `1 x c x h x w` fp16 tensor. Batch is always 1; neither net is ever batched. #[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -992,7 +993,7 @@ impl<'a> Builder<'a> { let (out, scale) = self.score_map(q, k, heads); let shape = self.shape_of(q); let head_dim = shape.c.checked_div(heads.max(1)).unwrap_or(0);- self.check_offsets(offsets, shape.w);+ self.check_offsets(offsets); let table = self.weight(table, &[offsets, head_dim]); self.nodes.push(Node::AttnScoresRelative { q, k, out, heads, scale, table, offsets }); out@@ -1010,26 +1011,24 @@ impl<'a> Builder<'a> { let out = self.mixed(probs, v, heads); let shape = self.shape_of(v); let head_dim = shape.c.checked_div(heads.max(1)).unwrap_or(0);- self.check_offsets(offsets, shape.w);+ self.check_offsets(offsets); let table = self.weight(table, &[offsets, head_dim]); self.nodes.push(Node::AttnApplyRelative { probs, v, out, heads, table, offsets }); out } /// A relative table is `2 * window + 1` entries centred on zero displacement.- fn check_offsets(&mut self, offsets: u32, sequence: u32) {+ ///+ /// Only the parity is checked. The table's size is deliberately *not* related to the+ /// sequence length: for a one-phoneme utterance only the centre entry is ever reachable+ /// and the other eight go unused, which is correct rather than an error — "a" is a word.+ fn check_offsets(&mut self, offsets: u32) { if offsets == 0 || offsets.is_multiple_of(2) { self.fail(format!( "{offsets} relative offsets: the table is 2 * window + 1 entries centred on \ zero displacement, so an even count has no centre" )); }- if offsets > sequence * 2 {- self.fail(format!(- "{offsets} relative offsets over a sequence of {sequence}: the band is wider \- than any pair of positions can be apart"- ));- } } /// Apply `probs`, a `[heads, T, T]` score map, to `v`, a `[d_model, 1, T]` sequence.@@ -1733,12 +1732,19 @@ pub(crate) mod tests { Kind::MulBroadcast => { vec![(push.in0, written), (push.in1, push.in_c)] }- // Q and K are both whole sequences.- Kind::AttnScores => vec![(push.in0, dense), (push.in1, dense)],+ // Q and K are both whole sequences. The relative variants read a+ // table out of the weights buffer as well, which cannot alias the+ // arena at all.+ Kind::AttnScores | Kind::AttnScoresRelative => {+ vec![(push.in0, dense), (push.in1, dense)]+ } // The score map is `[heads, T, T]`; V is a sequence.- Kind::AttnApply => {+ Kind::AttnApply | Kind::AttnApplyRelative => { vec![(push.in0, push.group * push.out_w * push.out_w), (push.in1, dense)] }+ // One id per position, so the read is `out_w` and not `dense` —+ // `dense` here would be the *table's* row count.+ Kind::Embed => vec![(push.in0, push.out_w)], _ => vec![(push.in0, dense)], }; ((push.out, written), reads)
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 44ecb50005..67f6629983 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -939,7 +939,8 @@ fn uniform(state: &mut u32) -> f32 { #[cfg(test)] mod tests { use super::super::{- mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, u2netp, vits_dec, Act, Builder,+ mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, u2netp, vits_dec, vits_enc, Act,+ Builder, }; use super::*; @@ -2106,6 +2107,17 @@ mod tests { // A voice is a runtime download rather than a bundled asset, so the vocoder's // `.maml` is given by path instead of being looked up in the tree.+ if graph == "vits_enc" {+ 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::VITS_ENC)+ .expect("the encoder asset parses");+ let plan = vits_enc::build(&weights, width).expect("vits_enc builds");+ let stats = run(&plan, weights.data(), &input).expect("the encoder runs");+ write(&dir.join("reference.f32"), &stats);+ println!("vits_enc at {width} phonemes: wrote {} values", stats.len());+ return;+ } if graph == "vits_dec" { 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/vits_enc.rs
diff --git a/library/ml/src/main/rust/src/nets/vits_enc.rs b/library/ml/src/main/rust/src/nets/vits_enc.rsnew file mode 100644index 0000000000..f0f4f1603a--- /dev/null+++ b/library/ml/src/main/rust/src/nets/vits_enc.rs@@ -0,0 +1,290 @@+//! Piper's VITS text encoder: the `enc_p` module, phonemes to a latent distribution.+//!+//! # What it is+//!+//! An embedding lookup over 130 phoneme symbols, six post-norm transformer layers with+//! **relative** position attention, and a 1x1 projection to twice the channel count — the+//! mean and log-variance of the prior the flow and the vocoder sample from.+//!+//! 865 ONNX nodes and 111 tensors. Most of those nodes are not arithmetic: the export spends+//! 48 `Pad`s, 96 `Reshape`s and 42 `Slice`s building the `[heads, T, 2T-1]` relative form of+//! its attention and skewing it back, and none of that survives here. See+//! [`super::Kind::AttnScoresRelative`] for why nine taps is the same function.+//!+//! # Two things checked against the export rather than assumed+//!+//! **The mask is not needed.** Six `Where` nodes write `-10000` into the scores wherever the+//! padding mask is zero. At `input_lengths == T` they are bit-identically the identity, so an+//! utterance processed on its own does not need them — and this runtime speaks one utterance+//! at a time. Batching would need the mask back.+//!+//! **The scale is in the table.** VITS multiplies the embedding by `sqrt(d_model)`. The+//! converter folds that into the table, which is one op fewer and one rounding fewer:+//! `round(table * sqrt(d))` is closer than `round(table) * sqrt(d)`.+//!+//! # Where it sits+//!+//! `enc_p` is one of four modules the VITS export splits into, and one of the three that are+//! static enough to be a plan. The fourth, `dp`, samples noise and builds a monotonic+//! alignment out of `NonZero` and `ScatterND`; it belongs on the CPU. See+//! [`super::vits_dec`] for the whole picture.++use super::{Act, Builder, Id, Plan, Shape, WeightSource};++/// Phoneme symbols in the table, from the voice's `.onnx.json` `num_symbols`.+pub const SYMBOLS: u32 = 130;++/// Channels throughout the encoder, VITS's `hidden_channels`.+pub const D_MODEL: u32 = 192;++/// Attention heads. `D_MODEL / HEADS` is 96, which is also the relative table's width.+pub const HEADS: u32 = 2;++/// The feed-forward layer's inner width.+pub const FFN: u32 = 768;++/// Transformer layers.+pub const LAYERS: usize = 6;++/// Entries in each attention layer's relative position table: `2 * window + 1` at+/// `window_size` 4.+pub const OFFSETS: u32 = 9;++/// Output channels: the mean and the log-variance of the prior, concatenated.+pub const STATS: u32 = D_MODEL * 2;++/// The epsilon in every one of the twelve layer norms.+const EPSILON: f32 = 1e-5;++/// Tensors the `.maml` must hold.+///+/// The embedding table, then eighteen per layer, then the projection's pair:+/// `1 + 6 * 18 + 2`. The eighteen are three attention projections (six), the two relative+/// tables (two — one tensor each, not a pair), the output projection (two), a layer norm+/// (two), the two feed-forward convolutions (four) and the second layer norm (two).+pub const TENSORS: usize = 111;++/// Hands out `.maml` tensor indices in the order the layers appear.+///+/// Unlike the other net modules this one deals in both pairs and singles, because a relative+/// position table is one tensor with no bias beside it.+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.+ fn take_one(&mut self) -> usize {+ let index = self.next;+ self.next += 1;+ index+ }+}++/// A 1x1 convolution along the sequence, which is what 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)+}++/// A `1 x 3` convolution padded to hold the length, which is what the feed-forward uses.+fn along(b: &mut Builder, l: &mut Layers, x: Id, out: u32, act: Act) -> Id {+ b.conv(x, l.take(), out, (1, 3), (1, 1), (1, 1), (0, 1, 0, 1), 1, act)+}++/// Build the encoder for an utterance of `phonemes` symbols.+///+/// The input is `[1, 1, phonemes]` of symbol ids, held as fp16 — exact, because fp16 carries+/// every integer to 2048 and there are 130 symbols. The output is `[384, 1, phonemes]`: the+/// prior's mean in the first 192 channels and its log-variance in the rest.+pub fn build(weights: &dyn WeightSource, phonemes: u32) -> Result<Plan, String> {+ if phonemes == 0 {+ return Err("an encoder pass over no phonemes".into());+ }++ let l = &mut Layers { next: 0 };+ let mut builder = Builder::new(weights);+ let b = &mut builder;+ let ids = b.input(Shape::new(1, 1, phonemes));+ let mut x = b.embed(ids, l.take_one(), SYMBOLS, D_MODEL);++ for _ in 0..LAYERS {+ // Attention. The three projections read the same tensor, and the relative tables+ // sit between the value projection and the output one, which is the order the+ // export's nodes appear in.+ let q = point(b, l, x, D_MODEL, Act::None);+ let k = point(b, l, x, D_MODEL, Act::None);+ let v = point(b, l, x, D_MODEL, Act::None);+ let scores = b.attn_scores_relative(q, k, HEADS, l.take_one(), OFFSETS);+ let probs = b.softmax(scores);+ let mixed = b.attn_apply_relative(probs, v, HEADS, l.take_one(), OFFSETS);+ let attended = point(b, l, mixed, D_MODEL, Act::None);+ // Post-norm: the residual is added first and normalised after, which is what the+ // export does and the opposite of the recogniser's transformer.+ let residual = b.add(x, attended);+ x = b.layer_norm(residual, l.take(), EPSILON);++ // Feed-forward, both convolutions three wide.+ let inner = along(b, l, x, FFN, Act::Relu);+ let projected = along(b, l, inner, D_MODEL, Act::None);+ let residual = b.add(x, projected);+ x = b.layer_norm(residual, l.take(), EPSILON);+ }++ let stats = point(b, l, x, STATS, Act::None);+ if l.next != TENSORS {+ return Err(format!("the forward pass claims {} tensors, not {TENSORS}", l.next));+ }+ builder.finish(&[stats])+}++#[cfg(test)]+mod tests {+ use super::super::tests::{assert_no_aliasing, Shapes};+ use super::super::{Kind, Op};+ use super::*;++ /// A short sentence. Long enough that the relative band is interior somewhere, which at+ /// four or fewer phonemes it would not be.+ const PHONEMES: u32 = 24;++ fn plan(phonemes: u32) -> (Shapes, Plan) {+ let source = Shapes::new(TENSORS);+ let plan = build(&source, phonemes).expect("the encoder builds");+ (source, plan)+ }++ #[test]+ fn the_pass_reads_every_tensor_in_the_file_exactly_once() {+ let (source, _) = plan(PHONEMES);+ 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() {+ // Every parameter `enc_p` holds in en_GB-alan-low, summed. Each of the 111 names was+ // looked up in the export, so this pins the channel counts, the kernel widths and+ // the relative tables' shape at once — a structural test would pass without them.+ let (source, _) = plan(PHONEMES);+ let total: u64 = source+ .asked+ .borrow()+ .iter()+ .map(|(_, dims)| dims.iter().map(|&d| d as u64).product::<u64>())+ .sum();+ assert_eq!(total, 6_317_568);+ }++ #[test]+ fn the_output_is_a_mean_and_a_log_variance_per_phoneme() {+ let (_, plan) = plan(PHONEMES);+ assert_eq!(+ plan.output().expect("one output").shape,+ Shape::new(STATS, 1, PHONEMES)+ );+ // Ids, one per phoneme, not one per channel.+ assert_eq!(plan.input().expect("one input").shape, Shape::new(1, 1, PHONEMES));+ }++ #[test]+ fn every_layer_keeps_the_sequence_length() {+ // The feed-forward convolutions are three wide and padded by one, so nothing here+ // changes `T`. A missing pad would shorten the sequence at every layer and the+ // durations the predictor produced would no longer line up with it.+ let (_, plan) = plan(PHONEMES);+ for (step, op) in plan.ops.iter().enumerate() {+ if let Op::Dispatch { kind: Kind::Conv, push, .. } = op {+ assert_eq!(push.out_w, PHONEMES, "step {step} changed the length");+ assert_eq!(push.out_h, 1, "step {step} is not a sequence");+ }+ }+ }++ #[test]+ fn the_op_inventory_is_six_layers_of_relative_attention() {+ let (_, plan) = plan(PHONEMES);+ let mut counts = std::collections::BTreeMap::new();+ for op in &plan.ops {+ if let Op::Dispatch { kind, .. } = op {+ *counts.entry(format!("{kind:?}")).or_insert(0) += 1;+ }+ }+ // Four projections and two feed-forward convolutions per layer, plus the output+ // projection: `6 * 6 + 1`.+ assert_eq!(counts.get("Conv"), Some(&37), "{counts:?}");+ assert_eq!(counts.get("Embed"), Some(&1), "{counts:?}");+ assert_eq!(counts.get("AttnScoresRelative"), Some(&LAYERS), "{counts:?}");+ assert_eq!(counts.get("AttnApplyRelative"), Some(&LAYERS), "{counts:?}");+ assert_eq!(counts.get("Softmax"), Some(&LAYERS), "{counts:?}");+ // Two residuals and two norms per layer.+ assert_eq!(counts.get("Add"), Some(&(LAYERS * 2)), "{counts:?}");+ assert_eq!(counts.get("LayerNorm"), Some(&(LAYERS * 2)), "{counts:?}");+ // In particular no plain AttnScores or AttnApply: every layer here is relative, and+ // a mix would mean one layer had lost its position information.+ assert_eq!(counts.get("AttnScores"), None, "{counts:?}");+ assert_eq!(counts.get("AttnApply"), None, "{counts:?}");+ assert_eq!(counts.len(), 7, "{counts:?}");+ }++ #[test]+ fn every_attention_splits_d_model_into_two_heads_over_nine_offsets() {+ let (_, plan) = plan(PHONEMES);+ let mut seen = 0;+ for op in &plan.ops {+ match op {+ Op::Dispatch { kind: Kind::AttnScoresRelative, push, .. }+ | Op::Dispatch { kind: Kind::AttnApplyRelative, push, .. } => {+ assert_eq!(push.group, HEADS, "{push:?}");+ assert_eq!(push.kw, OFFSETS, "{push:?}");+ seen += 1;+ }+ _ => {}+ }+ }+ assert_eq!(seen, LAYERS * 2);+ }++ #[test]+ fn a_sequence_shorter_than_the_relative_band_still_builds() {+ // A one-phoneme utterance is legal — "a" is a word. The band is then entirely+ // outside the sequence, which the taps skip rather than clamping.+ let (_, plan) = plan(1);+ assert_eq!(plan.output().expect("one output").shape.w, 1);+ }++ #[test]+ fn an_empty_utterance_is_refused() {+ let source = Shapes::new(TENSORS);+ let error = build(&source, 0).expect_err("no phonemes");+ assert!(error.contains("no phonemes"), "{error}");+ }++ #[test]+ fn no_op_reads_a_region_of_the_arena_that_it_also_writes() {+ let (_, plan) = plan(PHONEMES);+ assert_no_aliasing(&plan);+ }++ #[test]+ fn the_arena_is_bounded_at_a_long_sentence() {+ // Attention is quadratic in the phoneme count, and this is the only net here where+ // that matters: 24 phonemes is a short phrase and 400 is about as long as a+ // sentence Piper is asked to say in one go.+ for phonemes in [PHONEMES, 400] {+ let (_, plan) = plan(phonemes);+ let mib = plan.arena_elems as f32 * 2.0 / (1024.0 * 1024.0);+ println!("vits_enc at {phonemes} phonemes: {} elements, {mib:.2} MiB", plan.arena_elems);+ assert!(mib < 64.0, "{phonemes} phonemes 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 3c47af4d9b..35ed55883a 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -45,6 +45,10 @@ pub mod graph { /// graphs, because VITS's duration predictor samples noise and builds its alignment out /// of ops no plan can express. See [`crate::nets::vits_dec`]. pub const VITS_DEC: u32 = 7;+ /// Piper's VITS text encoder — the `enc_p` module, 130 phoneme symbols to a prior.+ ///+ /// See [`crate::nets::vits_enc`]. Its input is symbol ids rather than pixels or latents.+ pub const VITS_ENC: u32 = 8; } /// 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 c9b01ca6ec..17e5aeb247 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -46,6 +46,7 @@ with the shaders about a transpose. import argparse import hashlib+import math import struct import sys @@ -98,6 +99,7 @@ GRAPHS = { "ppocr_det": 5, "ppocr_rec": 6, "vits_dec": 7,+ "vits_enc": 8, } # SHA-256 over the ordered layer table (see `layer_table_digest`). Regenerate with@@ -110,6 +112,7 @@ EXPECTED_DIGEST = { "ppocr_det": "51b0c9ed871526fa270b4bfa53b393c056db21c58193849fb83d44768f69ef9b", "ppocr_rec": "8c16a8702aa7a1e7b4d94787d089616ca4bc3d8aaeebb0b0159eabc56af3ba08", "vits_dec": "ac3fa714b9c0074e7fb7fa1d5f5b65e30bf558df0817b014897cd56b6e850020",+ "vits_enc": "93ee24f70b490334d11b383f043e81284a3e781bc263597830c50f8df14db2c1", } # Graphs that are one **module** of a larger export, keyed by the node-name prefix that@@ -128,6 +131,7 @@ EXPECTED_DIGEST = { # route. MODULES = { "vits_dec": "/dec/",+ "vits_enc": "/enc_p/", } # `outputs` are the graph outputs the Rust forward pass corresponds to; the export may@@ -189,6 +193,17 @@ EXPECTED_OPS = { "vits_dec": { "Conv": 20, "ConvTranspose": 3, "LeakyRelu": 16, "Add": 24, "Div": 3, "Tanh": 1, },+ # Counted within `/enc_p/` only. Most of these are not arithmetic: 48 Pad, 96 Reshape,+ # 42 Slice and 130 Unsqueeze are the export building a [heads, T, 2T-1] relative score+ # map and skewing it back, which `nets::vits_enc` does as nine taps instead. The six+ # `Where` are the padding mask, which is bit-identically the identity for one unpadded+ # utterance and so is not transcribed either.+ "vits_enc": {+ "Add": 60, "Cast": 1, "Concat": 66, "Conv": 37, "Div": 18, "Equal": 1,+ "Gather": 61, "Less": 1, "MatMul": 24, "Mul": 72, "Pad": 48, "Pow": 12, "Range": 1,+ "ReduceMean": 24, "Relu": 6, "Reshape": 96, "Shape": 25, "Slice": 42, "Softmax": 6,+ "Split": 1, "Sqrt": 12, "Sub": 42, "Transpose": 73, "Unsqueeze": 130, "Where": 6,+ }, } @@ -355,6 +370,10 @@ def collect_layers(model, prefix=None): # Which node's output each BatchNormalization consumes, so the layer producing it # can absorb it. batch_norms = {n.input[0]: n for n in graph.node if n.op_type == "BatchNormalization"}+ consumers = {}+ for node in graph.node:+ for name in node.input:+ consumers.setdefault(name, []).append(node) folded = set() layers = []@@ -424,6 +443,37 @@ def collect_layers(model, prefix=None): ) tensors.append(weight) tensors.append(bias)+ elif node.op_type == "Gather" and held(node.input[0]) and array(node.input[0]).ndim == 2:+ # An embedding table. VITS multiplies the looked-up row by `sqrt(d_model)`, and+ # that scale belongs here rather than in a shader: it is one op fewer and one+ # rounding fewer, since `round(table * sqrt(d))` is closer than+ # `round(table) * sqrt(d)`.+ table = array(node.input[0]).astype(np.float64)+ table = table * math.sqrt(table.shape[1])+ key = f"Embed t={list(table.shape)} scaled=sqrt({table.shape[1]})"+ tensors.append(table)+ elif node.op_type == "Pad" and held(node.input[0]):+ # A relative position table, which the export pads out to `2T-1` entries and+ # then skews. `nets::vits_enc` reads the nine unpadded entries directly, so the+ # leading batch axis is dropped and the padding never happens.+ table = np.squeeze(array(node.input[0]))+ if table.ndim != 2 or table.shape[0] % 2 == 0:+ raise SystemExit(+ f"{node.output[0]}: a padded constant of {list(np.shape(table))}; a "+ "relative table is [2 * window + 1, head_dim]"+ )+ key = f"Relative t={list(table.shape)}"+ tensors.append(table)+ elif node.op_type == "Mul" and layer_norm_scale(node, consumers, held, array):+ # A layer norm's gamma and the beta on the `Add` after it. The export decomposes+ # the rest of the norm into ReduceMean/Sub/Pow/Sqrt/Div, none of which carries a+ # weight, so this pair is all there is to collect.+ gamma = next(array(n) for n in node.input if held(n))+ follow = consumers[node.output[0]][0]+ beta = next(array(n) for n in follow.input if held(n))+ key = f"LayerNorm g={list(gamma.shape)} b={list(beta.shape)}"+ tensors.append(gamma)+ tensors.append(beta) elif node.op_type == "BatchNormalization": # Folded above, when the layer it follows was emitted. One that was not is a # batch norm somewhere in the middle of the graph, which nothing here can@@ -449,6 +499,28 @@ def collect_layers(model, prefix=None): return layers, tensors +def layer_norm_scale(node, consumers, held, array):+ """Whether `node` is the `Mul(x, gamma)` of a decomposed layer norm.++ Recognised by structure rather than by name: a `Mul` against a rank-1 constant whose one+ consumer is an `Add` against a rank-1 constant of the same length. In Piper's encoder that+ matches exactly the twelve norms and nothing else — the mask multiplies and the embedding+ scale are against scalars or computed tensors.+ """+ scales = [n for n in node.input if held(n) and array(n).ndim == 1]+ if len(scales) != 1:+ return False+ follow = consumers.get(node.output[0], [])+ if len(follow) != 1 or follow[0].op_type != "Add":+ return False+ shifts = [+ n+ for n in follow[0].input+ if held(n) and array(n).ndim == 1 and array(n).size == array(scales[0]).size+ ]+ return len(shifts) == 1++ def layer_table_digest(layers): h = hashlib.sha256() for layer in layers:
scripts/ml/onnx_parity.py
diff --git a/scripts/ml/onnx_parity.py b/scripts/ml/onnx_parity.pyindex b0f06f66ca..4e586b72f6 100644--- a/scripts/ml/onnx_parity.py+++ b/scripts/ml/onnx_parity.py@@ -53,6 +53,9 @@ PROBE = { "ppocr_rec": None, "ppocr_det": "p2o.pd_op.hardswish.23.0", "vits_dec": None,+ # The prior's mean and log-variance. `enc_p` is reachable from the graph's own inputs, so+ # unlike the vocoder it needs no extraction — the duration predictor runs after it.+ "vits_enc": "/enc_p/proj/Conv_output_0", } # Graphs that are one module of a larger export, and have to be cut out of it before they can@@ -108,12 +111,13 @@ def final_logits(model): return next(iter(outputs)) -def run(model, probe, x):+def run(model, probe, x, feed=None): session = onnxruntime.InferenceSession( model.SerializeToString(), providers=["CPUExecutionProvider"] ) names = [o.name for o in session.get_outputs()]- outputs = session.run(None, {session.get_inputs()[0].name: x})+ inputs = feed if feed is not None else {session.get_inputs()[0].name: x}+ outputs = session.run(None, inputs) return np.squeeze(np.asarray(outputs[names.index(probe)])) @@ -138,11 +142,23 @@ def main(): onnx.helper.make_tensor_value_info(probe, onnx.TensorProto.FLOAT, None) ) + feed = None if cut is not None: # Random latents, deterministic. The vocoder is not a classifier, so there is no # "sensible" input; what matters is that both sides see the same one. rng = np.random.default_rng(20240827) x = rng.standard_normal((1, cut["channels"], args.width)).astype(np.float32)+ elif args.graph == "vits_enc":+ # Phoneme ids. int64 for onnxruntime, the same values as fp32 for the runtime, which+ # carries them in the arena — exact, since fp16 holds every integer to 2048.+ rng = np.random.default_rng(20240827)+ ids = rng.integers(0, 130, size=(1, args.width), dtype=np.int64)+ feed = {+ "input": ids,+ "input_lengths": np.array([args.width], dtype=np.int64),+ "scales": np.array([0.667, 1.0, 0.8], dtype=np.float32),+ }+ x = ids.astype(np.float32) else: height = 48 if args.graph == "ppocr_rec" else args.width # Deterministic and free of transcendentals, so both sides read identical bytes.@@ -153,8 +169,8 @@ def main(): x = ramp.reshape(1, 3, height, args.width) x.tofile(os.path.join(work, "input.f32")) - reference = run(model, probe, x)- quantised = run(rounded_to_fp16(model), probe, x)+ reference = run(model, probe, x, feed)+ quantised = run(rounded_to_fp16(model), probe, x, feed) environment = dict(os.environ, PARITY_DIR=work, PARITY_GRAPH=args.graph) environment["PARITY_WIDTH"] = str(args.width)