library:ml: Piper's normalising flow, and its three no-op leftovers
- Commit
596974002149966a4948e6790c7fa397510d445e- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 00:19 UTC (3 months ago)
- Parents
5a083ea
Diff
library/ml/src/main/rust/shaders/flip_channels.comp
diff --git a/library/ml/src/main/rust/shaders/flip_channels.comp b/library/ml/src/main/rust/shaders/flip_channels.compnew file mode 100644index 0000000000..687a78d508--- /dev/null+++ b/library/ml/src/main/rust/shaders/flip_channels.comp@@ -0,0 +1,33 @@+#version 450+//! Reverse the channel order: `out[c] = in[C - 1 - c]`.+//!+//! VITS interleaves its four coupling layers with four `Flip`s, each of which is+//! `torch.flip(x, [1])` and exports as a single `Slice` with a negative step. Four uses in+//! Piper's flow.+//!+//! # Why a pass and not a fold+//!+//! A fixed channel permutation can in principle be folded into the convolutions either side+//! of it — permuting a weight's input channels before, or its output channels after. That+//! would make this free. It is a pass instead because the fold has to thread through a split+//! and a concatenation to reach those convolutions, and the arithmetic saved is one read and+//! one write of `[192, 1, T]`: at 400 phonemes that is 76,800 elements, against the tens of+//! millions the coupling layer around it costs. The fold would trade a real risk of getting+//! a permutation backwards for nothing measurable.+//!+//! Without the flips a coupling layer would only ever transform the same half of the+//! channels, and the other half would pass through all four unchanged.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ uint channel, row, column;+ unpack(index, channel, row, column);+ uint mirrored = p.out_c - 1u - channel;+ uint plane = p.out_h * p.out_w;+ arena[p.out_at + index] = arena[p.in0 + mirrored * plane + row * p.out_w + column];+}
library/ml/src/main/rust/shaders/gated_tanh.comp
diff --git a/library/ml/src/main/rust/shaders/gated_tanh.comp b/library/ml/src/main/rust/shaders/gated_tanh.compnew file mode 100644index 0000000000..b1d4de4f7e--- /dev/null+++ b/library/ml/src/main/rust/shaders/gated_tanh.comp@@ -0,0 +1,32 @@+#version 450+//! WaveNet's gated activation: `out[c] = tanh(in[c]) * sigmoid(in[c + C])`.+//!+//! The input carries twice the output's channels — a "filter" half and a "gate" half, which+//! a single convolution produces together and this splits. 16 uses in Piper's flow, four in+//! each of its four coupling layers.+//!+//! # Why it is one op and not three+//!+//! `tanh` and `sigmoid` both exist as fusable activations, so this could be a convolution+//! with a `Tanh`, another with a `Sigmoid` and an elementwise multiply. It is one op because+//! the two halves come from the *same* convolution: splitting them would mean either running+//! that convolution twice or materialising a `[2C, 1, T]` tensor and reading it twice. One+//! pass that reads both halves and writes one is strictly less work and less arena.+//!+//! The export spells it as a `Slice`, a `Slice`, a `Tanh`, a `Sigmoid` and a `Mul`, and+//! leaves the two `Slice`s' outputs as separate tensors. Nothing is lost by fusing: the+//! halves are never read again.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ // `p.out_c` channels out, so the gate half starts this many elements on.+ uint gate_at = p.out_c * p.out_h * p.out_w;+ float filtered = float(arena[p.in0 + index]);+ float gate = float(arena[p.in0 + gate_at + index]);+ arena[p.out_at + index] = float16_t(tanh(filtered) / (1.0 + exp(-gate)));+}
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 bc7c7bddce..e3d08c0a85 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -39,6 +39,7 @@ pub mod selfie; pub mod u2netp; pub mod vits_dec; pub mod vits_enc;+pub mod vits_flow; /// 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)]@@ -235,6 +236,13 @@ pub enum Kind { /// [`Kind::AttnApply`] plus the value-side relative term. See /// [`Kind::AttnScoresRelative`]. AttnApplyRelative,+ /// WaveNet's gated activation, `tanh(in[c]) * sigmoid(in[c + C])`.+ ///+ /// The input has twice the output''s channels, because one convolution produces the+ /// filter and the gate together. 16 uses in Piper''s flow.+ GatedTanh,+ /// `out[c] = in[C - 1 - c]`, a channel reversal. VITS''s `Flip` between coupling layers.+ FlipChannels, /// `out[c][t] = table[id(t)][c]`, an embedding lookup. /// /// The only op here whose addresses depend on the data. Ids arrive as an ordinary fp16@@ -515,6 +523,19 @@ enum Node { table: u32, rows: u32, },+ GatedTanh {+ input: Id,+ out: Id,+ },+ FlipChannels {+ input: Id,+ out: Id,+ },+ SliceChannels {+ input: Id,+ out: Id,+ start: u32,+ }, AttnApply { probs: Id, v: Id,@@ -949,6 +970,48 @@ impl<'a> Builder<'a> { out } + /// WaveNet's gated activation: `tanh(x[c]) * sigmoid(x[c + C])` over an input of `2C`+ /// channels, writing `C`.+ pub fn gated_tanh(&mut self, input: Id) -> Id {+ let shape = self.shape_of(input);+ if shape.c == 0 || !shape.c.is_multiple_of(2) {+ self.fail(format!(+ "a gated activation over {shape:?}: the filter and the gate are halves of \+ the same tensor, so the channel count must be even"+ ));+ }+ let out = self.tensor(Shape::new(shape.c / 2, shape.h, shape.w));+ self.nodes.push(Node::GatedTanh { input, out });+ out+ }++ /// `out[c] = in[C - 1 - c]`, VITS's `Flip` between coupling layers.+ pub fn flip_channels(&mut self, input: Id) -> Id {+ let shape = self.shape_of(input);+ let out = self.tensor(shape);+ self.nodes.push(Node::FlipChannels { input, out });+ out+ }++ /// Channels `start .. start + count` of `input`, as a tensor of its own.+ ///+ /// One copy and no shader: a channel range of a `[C, H, W]` tensor is contiguous, so this+ /// is a element-range move like the one [`Builder::concat`] already uses. It is a copy+ /// rather than a view because a view would have to survive the arena's last-use+ /// bookkeeping, and the ranges here are a few hundred kilobytes.+ pub fn slice_channels(&mut self, input: Id, start: u32, count: u32) -> Id {+ let shape = self.shape_of(input);+ if count == 0 || start.saturating_add(count) > shape.c {+ self.fail(format!(+ "channels {start}..{} of {shape:?}",+ start.saturating_add(count)+ ));+ }+ let out = self.tensor(Shape::new(count, shape.h, shape.w));+ self.nodes.push(Node::SliceChannels { input, out, start });+ out+ }+ /// An embedding lookup: `out[c][t] = table[id(t)][c]`, over a `[1, 1, T]` id tensor. /// /// `table` indexes a `[rows, channels]` tensor. The `sqrt(d_model)` scale VITS applies@@ -1444,6 +1507,47 @@ impl<'a> Builder<'a> { invocations: so.len(), }); }+ Node::GatedTanh { input, out } => {+ let so = shape(*out);+ ops.push(Op::Dispatch {+ kind: Kind::GatedTanh,+ push: Push {+ in0: at(*input)?,+ out: at(*out)?,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ count: so.len(),+ ..Push::default()+ },+ invocations: so.len(),+ });+ }+ Node::FlipChannels { input, out } => {+ let so = shape(*out);+ ops.push(Op::Dispatch {+ kind: Kind::FlipChannels,+ push: Push {+ in0: at(*input)?,+ out: at(*out)?,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ count: so.len(),+ ..Push::default()+ },+ invocations: so.len(),+ });+ }+ Node::SliceChannels { input, out, start } => {+ let so = shape(*out);+ // A channel range is contiguous, so this is one element-range move.+ ops.push(Op::Copy {+ src: at(*input)? + start * so.h * so.w,+ dst: at(*out)?,+ elems: so.len(),+ });+ } Node::Embed { ids, out, table, rows } => { let so = shape(*out); ops.push(Op::Dispatch {@@ -1550,6 +1654,9 @@ impl Node { | Node::Softmax { out, .. } | Node::LeakyRelu { out, .. } | Node::Embed { out, .. }+ | Node::GatedTanh { out, .. }+ | Node::FlipChannels { out, .. }+ | Node::SliceChannels { out, .. } | Node::AttnApply { out, .. } | Node::Concat { out, .. } => *out, }@@ -1566,6 +1673,9 @@ impl Node { | Node::Softmax { input, .. } | Node::LeakyRelu { input, .. } | Node::Embed { ids: input, .. }+ | Node::GatedTanh { input, .. }+ | Node::FlipChannels { input, .. }+ | Node::SliceChannels { input, .. } | Node::GlobalAvgPool { input, .. } => vec![*input], Node::Binary { a, b, .. } => vec![*a, *b], Node::AttnScores { q: a, k: b, .. }@@ -1745,6 +1855,8 @@ pub(crate) mod tests { // 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)],+ // Twice what it writes: the filter half and the gate half.+ Kind::GatedTanh => vec![(push.in0, written * 2)], _ => 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 67f6629983..c1105e6652 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -190,6 +190,8 @@ impl Reference { Kind::AttnScoresRelative => self.attn_scores_relative(push), Kind::AttnApplyRelative => self.attn_apply_relative(push), Kind::Embed => self.embed(push),+ Kind::GatedTanh => self.gated_tanh(push),+ Kind::FlipChannels => self.flip_channels(push), }, }; result.map_err(|e| format!("step {step} ({op:?}): {e}"))?;@@ -465,6 +467,30 @@ impl Reference { Ok(()) } + /// `out[c] = tanh(in[c]) * sigmoid(in[c + C])`, WaveNet''s gated activation.+ fn gated_tanh(&mut self, p: &Push) -> Result<(), String> {+ let gate_at = p.out_c * p.out_h * p.out_w;+ for i in 0..p.count {+ let filtered = self.load(p.in0, i)?;+ let gate = self.load(p.in0, gate_at + i)?;+ self.store(p.out, i, filtered.tanh() / (1.0 + (-gate).exp()))?;+ }+ Ok(())+ }++ /// `out[c] = in[C - 1 - c]`, a channel reversal.+ fn flip_channels(&mut self, p: &Push) -> Result<(), String> {+ let plane = p.out_h * p.out_w;+ for channel in 0..p.out_c {+ let mirrored = p.out_c - 1 - channel;+ for i in 0..plane {+ let value = self.load(p.in0, mirrored * plane + i)?;+ self.store(p.out, channel * plane + i, value)?;+ }+ }+ Ok(())+ }+ /// `out[c][t] = table[id(t)][c]`, with the id read out of the arena as fp16. fn embed(&mut self, p: &Push) -> Result<(), String> { let rows = p.in_w;@@ -939,7 +965,7 @@ fn uniform(state: &mut u32) -> f32 { #[cfg(test)] mod tests { use super::super::{- mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, u2netp, vits_dec, vits_enc, Act,+ mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, u2netp, vits_dec, vits_enc, vits_flow, Act, Builder, }; use super::*;@@ -1681,6 +1707,90 @@ mod tests { assert!(error.contains("height above"), "{error}"); } + #[test]+ fn a_gated_activation_multiplies_a_tanh_by_a_sigmoid_of_the_other_half() {+ // Four channels in, two out: channels 0 and 1 are the filter and 2 and 3 the gate.+ // Distinct values in each half, so swapping filter for gate would be visible —+ // tanh and sigmoid disagree about the sign of a negative input.+ let got = one(+ Shape::new(4, 1, 2),+ &[0.0, 1.0, -1.0, 2.0, 0.0, 2.0, 3.0, -2.0],+ &[],+ |b, x| b.gated_tanh(x),+ );+ let gate = |x: f32| 1.0 / (1.0 + (-x).exp());+ close(+ &got,+ &[+ 0.0f32.tanh() * gate(0.0),+ 1.0f32.tanh() * gate(2.0),+ (-1.0f32).tanh() * gate(3.0),+ 2.0f32.tanh() * gate(-2.0),+ ],+ );+ }++ #[test]+ fn a_gated_activation_over_an_odd_channel_count_is_refused() {+ // The filter and the gate are halves of one tensor, so an odd count has no split.+ let given = Given::new(&[]).expect("no tensors");+ let mut b = Builder::new(&given);+ let x = b.input(Shape::new(3, 1, 2));+ let out = b.gated_tanh(x);+ let error = b.finish(&[out]).expect_err("three channels");+ assert!(error.contains("must be even"), "{error}");+ }++ #[test]+ fn flipping_channels_reverses_them_and_leaves_each_plane_alone() {+ // Three channels of two positions. The reversal is over channels only: getting the+ // plane indexing wrong would also reverse each channel's own values, which at one+ // row would look almost right.+ let got = one(+ Shape::new(3, 1, 2),+ &[1.0, 2.0, 10.0, 20.0, 100.0, 200.0],+ &[],+ |b, x| b.flip_channels(x),+ );+ close(&got, &[100.0, 200.0, 10.0, 20.0, 1.0, 2.0]);+ }++ #[test]+ fn flipping_twice_is_the_identity() {+ let values: Vec<f32> = (0..12).map(|i| i as f32).collect();+ let got = one(Shape::new(4, 1, 3), &values, &[], |b, x| {+ let once = b.flip_channels(x);+ b.flip_channels(once)+ });+ close(&got, &values);+ }++ #[test]+ fn slicing_channels_takes_a_contiguous_range_and_nothing_else() {+ // Channels 1 and 2 of four. A slice that got the element stride wrong would return+ // the right *count* of values from the wrong place.+ let values: Vec<f32> = vec![+ 1.0, 2.0, 3.0, //+ 10.0, 20.0, 30.0, //+ 100.0, 200.0, 300.0, //+ 1000.0, 2000.0, 3000.0,+ ];+ let got = one(Shape::new(4, 1, 3), &values, &[], |b, x| {+ b.slice_channels(x, 1, 2)+ });+ close(&got, &[10.0, 20.0, 30.0, 100.0, 200.0, 300.0]);+ }++ #[test]+ fn slicing_past_the_end_is_refused() {+ let given = Given::new(&[]).expect("no tensors");+ let mut b = Builder::new(&given);+ let x = b.input(Shape::new(4, 1, 3));+ let out = b.slice_channels(x, 3, 2);+ let error = b.finish(&[out]).expect_err("past the end");+ assert!(error.contains("channels 3..5"), "{error}");+ }+ #[test] fn an_embedding_gathers_the_row_each_id_names() { // Four symbols of three channels, looked up in an order that is neither ascending@@ -2107,6 +2217,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_flow" {+ 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_FLOW)+ .expect("the flow asset parses");+ let plan = vits_flow::build(&weights, width).expect("vits_flow builds");+ let latent = run(&plan, weights.data(), &input).expect("the flow runs");+ write(&dir.join("reference.f32"), &latent);+ println!("vits_flow at {width} frames: wrote {} values", latent.len());+ return;+ } 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}"));
library/ml/src/main/rust/src/nets/vits_flow.rs
diff --git a/library/ml/src/main/rust/src/nets/vits_flow.rs b/library/ml/src/main/rust/src/nets/vits_flow.rsnew file mode 100644index 0000000000..a34d5390f9--- /dev/null+++ b/library/ml/src/main/rust/src/nets/vits_flow.rs@@ -0,0 +1,275 @@+//! Piper's VITS normalising flow: the `flow` module, run in reverse.+//!+//! # What it is+//!+//! Four residual coupling layers with a channel reversal between each, applied in reverse+//! order. Each coupling splits its 192 channels in half, runs a four-layer WaveNet over the+//! first half to predict a shift for the second, and subtracts it. 196 ONNX nodes and 80+//! tensors.+//!+//! In VITS the flow maps the prior the encoder produced into the latent the vocoder decodes.+//! At inference it runs backwards, which for a mean-only coupling is a subtraction rather+//! than the division the forward direction needs.+//!+//! # Three things the export leaves in that are not there+//!+//! Each read from the graph rather than assumed:+//!+//! * **The log-scale is zero.** The coupling is mean-only, so its `post` convolution emits+//! 96 channels — a shift and no scale. The export still builds the scale: a+//! `ConstantOfShape` of zeros, a `Neg` and an `Exp`, which is `exp(-0) = 1`, and a `Mul`+//! by it. Four of each, all identity.+//! * **The mask is all ones.** 32 `Mul`s by the padding mask, which for one unpadded+//! utterance is the identity — the same argument as [`super::vits_enc`].+//! * **The flips are one `Slice` each.** `torch.flip(x, [1])` exports as a slice with a+//! negative step, not as a permutation table.+//!+//! # Why the flips are not folded away+//!+//! A fixed channel permutation could be pushed into the convolutions either side of it. It is+//! [`super::Kind::FlipChannels`] instead because the fold has to thread through a split and a+//! concatenation, and what it saves is one pass over `[192, 1, T]`. Without the flips a+//! coupling would only ever transform the same half of the channels.++use super::{Act, Builder, Id, Plan, Shape, WeightSource};++/// Channels in and out, VITS's `inter_channels`.+pub const CHANNELS: u32 = 192;++/// Channels each coupling layer transforms, which is half of them.+pub const HALF: u32 = CHANNELS / 2;++/// The WaveNet's width inside a coupling layer.+pub const HIDDEN: u32 = 192;++/// Coupling layers, each preceded by a channel reversal.+pub const COUPLINGS: usize = 4;++/// Convolutions in each coupling's WaveNet.+const WAVENET_LAYERS: usize = 4;++/// Tensors the `.maml` must hold: ten convolutions per coupling, each a weight and a bias.+///+/// `pre`, four `in_layers`, four `res_skip_layers` and `post` — `4 * 10 * 2`.+pub const TENSORS: usize = 80;++/// 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+ }+}++/// One residual coupling layer, in the reverse direction.+///+/// `x0` conditions a WaveNet whose output shifts `x1`; `x0` itself passes through. Returns+/// the concatenation, which is what the next flip reverses.+fn coupling(b: &mut Builder, l: &mut Layers, x: Id) -> Id {+ let x0 = b.slice_channels(x, 0, HALF);+ let x1 = b.slice_channels(x, HALF, HALF);++ // The WaveNet. `skip` accumulates every layer's contribution; the first layer starts it+ // rather than adding to a zero tensor, which would be a pass over 192 x T of nothing.+ let mut h = b.conv(x0, l.take(), HIDDEN, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::None);+ let mut skip: Option<Id> = None;+ for layer in 0..WAVENET_LAYERS {+ let last = layer == WAVENET_LAYERS - 1;+ // Kernel five, padded by two, so the length is unchanged. Every dilation in this+ // voice is one, which is not WaveNet's usual 1/3/9/27 — read from the export.+ let gated = b.conv(+ h,+ l.take(),+ HIDDEN * 2,+ (1, 5),+ (1, 1),+ (1, 1),+ (0, 2, 0, 2),+ 1,+ Act::None,+ );+ let acts = b.gated_tanh(gated);+ // The last layer's projection emits only a skip; the others emit a residual too.+ let width = if last { HIDDEN } else { HIDDEN * 2 };+ let projected =+ b.conv(acts, l.take(), width, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::None);+ let contribution = if last {+ projected+ } else {+ let residual = b.slice_channels(projected, 0, HIDDEN);+ h = b.add(h, residual);+ b.slice_channels(projected, HIDDEN, HIDDEN)+ };+ skip = Some(match skip {+ Some(total) => b.add(total, contribution),+ None => contribution,+ });+ }+ let skip = skip.expect("a WaveNet with no layers");++ let shift = b.conv(skip, l.take(), HALF, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::None);+ // Reverse of `x1 * exp(logs) + m` at `logs == 0`, which is a subtraction. There is no+ // subtract op, and negating the shift is one pass over 96 x T.+ let negated = b.affine(shift, -1.0, 0.0);+ let shifted = b.add(x1, negated);+ b.concat(&[x0, shifted])+}++/// Build the flow for an utterance of `frames` latent frames.+///+/// Input and output are both `[192, 1, frames]`: the prior sampled at frame rate in, the+/// latent the vocoder decodes out.+pub fn build(weights: &dyn WeightSource, frames: u32) -> Result<Plan, String> {+ if frames == 0 {+ return Err("a flow pass over no frames".into());+ }++ let l = &mut Layers { next: 0 };+ let mut builder = Builder::new(weights);+ let b = &mut builder;+ let input = b.input(Shape::new(CHANNELS, 1, frames));++ // Reverse order, so a flip comes first: the export's node order is flows.7, flows.6,+ // flows.5, ... and the odd-numbered flows are the flips.+ let mut x = input;+ for _ in 0..COUPLINGS {+ x = b.flip_channels(x);+ x = coupling(b, l, x);+ }++ if l.next != TENSORS {+ return Err(format!("the forward pass claims {} tensors, not {TENSORS}", l.next));+ }+ builder.finish(&[x])+}++#[cfg(test)]+mod tests {+ use super::super::tests::{assert_no_aliasing, Shapes};+ use super::super::{Kind, Op};+ use super::*;++ /// About a second of audio at 16 kHz and 256 samples a frame.+ const FRAMES: u32 = 64;++ fn plan(frames: u32) -> (Shapes, Plan) {+ let source = Shapes::new(TENSORS);+ let plan = build(&source, frames).expect("the flow builds");+ (source, plan)+ }++ #[test]+ fn the_pass_reads_every_tensor_in_the_file_exactly_once() {+ let (source, _) = plan(FRAMES);+ 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 the `flow` module of en_GB-alan-low holds. This pins the WaveNet's+ // widths, including that the *last* projection emits 192 channels and the other three+ // emit 384 — a detail no structural test would notice.+ let (source, _) = plan(FRAMES);+ let total: u64 = source+ .asked+ .borrow()+ .iter()+ .map(|(_, dims)| dims.iter().map(|&d| d as u64).product::<u64>())+ .sum();+ assert_eq!(total, 7_090_560);+ }++ #[test]+ fn the_flow_preserves_its_shape() {+ // A normalising flow is a bijection, so in and out are the same shape. A coupling+ // that concatenated its halves the wrong way round would still be 192 channels, but+ // the tensor count check above would not catch it — the ordering test below does.+ let (_, plan) = plan(FRAMES);+ let shape = Shape::new(CHANNELS, 1, FRAMES);+ assert_eq!(plan.input().expect("one input").shape, shape);+ assert_eq!(plan.output().expect("one output").shape, shape);+ }++ #[test]+ fn every_convolution_holds_the_frame_count() {+ let (_, plan) = plan(FRAMES);+ for (step, op) in plan.ops.iter().enumerate() {+ if let Op::Dispatch { kind: Kind::Conv, push, .. } = op {+ assert_eq!(push.out_w, FRAMES, "step {step} changed the length");+ }+ }+ }++ #[test]+ fn the_op_inventory_is_four_couplings_each_with_a_flip() {+ let (_, plan) = plan(FRAMES);+ 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;+ }+ }+ assert_eq!(counts.get("Conv"), Some(&40), "{counts:?}");+ assert_eq!(counts.get("FlipChannels"), Some(&COUPLINGS), "{counts:?}");+ assert_eq!(counts.get("GatedTanh"), Some(&(COUPLINGS * WAVENET_LAYERS)), "{counts:?}");+ // One negation of the shift per coupling.+ assert_eq!(counts.get("Affine"), Some(&COUPLINGS), "{counts:?}");+ // Three residual adds, three skip accumulations and the shift, per coupling.+ assert_eq!(counts.get("Add"), Some(&(COUPLINGS * 7)), "{counts:?}");+ assert_eq!(counts.len(), 5, "{counts:?}");+ // Two splits of the input, six inside the WaveNet, and two copies for the+ // concatenation — all `Op::Copy`, no shader.+ let copies = plan.ops.iter().filter(|o| matches!(o, Op::Copy { .. })).count();+ assert_eq!(copies, COUPLINGS * 10, "{copies}");+ }++ #[test]+ fn the_wavenet_widens_to_384_and_narrows_back() {+ // `in_layers` emits twice the hidden width because the gated activation consumes a+ // filter and a gate together; the gate halves it again.+ let (_, plan) = plan(FRAMES);+ let gates: Vec<(u32, u32)> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ Op::Dispatch { kind: Kind::GatedTanh, push, .. } => Some((push.out_c, push.count)),+ _ => None,+ })+ .collect();+ assert_eq!(gates.len(), COUPLINGS * WAVENET_LAYERS);+ for (channels, count) in gates {+ assert_eq!(channels, HIDDEN);+ assert_eq!(count, HIDDEN * FRAMES);+ }+ }++ #[test]+ fn a_zero_length_utterance_is_refused() {+ let source = Shapes::new(TENSORS);+ let error = build(&source, 0).expect_err("no frames");+ assert!(error.contains("no frames"), "{error}");+ }++ #[test]+ fn no_op_reads_a_region_of_the_arena_that_it_also_writes() {+ let (_, plan) = plan(FRAMES);+ assert_no_aliasing(&plan);+ }++ #[test]+ fn the_arena_is_bounded_at_a_realistic_utterance() {+ let (_, plan) = plan(FRAMES);+ let mib = plan.arena_elems as f32 * 2.0 / (1024.0 * 1024.0);+ println!("vits_flow at {FRAMES} frames: {} elements, {mib:.2} MiB", plan.arena_elems);+ assert!(mib < 64.0, "{mib} MiB");+ }+}
library/ml/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline.rs b/library/ml/src/main/rust/src/vulkan/pipeline.rsindex a437ef3dc2..822286f876 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -46,9 +46,12 @@ const ATTN_SCORES_RELATIVE: &[u8] = const ATTN_APPLY_RELATIVE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/attn_apply_relative.comp.spv")); const EMBED: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/embed.comp.spv"));+const GATED_TANH: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gated_tanh.comp.spv"));+const FLIP_CHANNELS: &[u8] =+ include_bytes!(concat!(env!("OUT_DIR"), "/flip_channels.comp.spv")); /// Every shader, in the order [`Pipelines::create`] destructures them.-const SPIRV: [&[u8]; 18] = [+const SPIRV: [&[u8]; 20] = [ CONV, CONV_TRANSPOSE, MAXPOOL,@@ -67,6 +70,8 @@ const SPIRV: [&[u8]; 18] = [ ATTN_SCORES_RELATIVE, ATTN_APPLY_RELATIVE, EMBED,+ GATED_TANH,+ FLIP_CHANNELS, ]; /// `local_size_x` in `shaders/common.glsl`. A dispatch covers `ceil(invocations / this)`@@ -108,6 +113,8 @@ pub struct Pipelines { attn_scores_relative: vk::Pipeline, attn_apply_relative: vk::Pipeline, embed: vk::Pipeline,+ gated_tanh: vk::Pipeline,+ flip_channels: vk::Pipeline, } impl Pipelines {@@ -248,6 +255,8 @@ impl Pipelines { attn_scores_relative, attn_apply_relative, embed,+ gated_tanh,+ flip_channels, ] = match <[vk::Pipeline; SPIRV.len()]>::try_from(built) { Ok(all) => all, Err(built) => {@@ -282,6 +291,8 @@ impl Pipelines { attn_scores_relative, attn_apply_relative, embed,+ gated_tanh,+ flip_channels, }) } @@ -306,6 +317,8 @@ impl Pipelines { Kind::AttnScoresRelative => self.attn_scores_relative, Kind::AttnApplyRelative => self.attn_apply_relative, Kind::Embed => self.embed,+ Kind::GatedTanh => self.gated_tanh,+ Kind::FlipChannels => self.flip_channels, } } @@ -332,6 +345,8 @@ impl Pipelines { self.attn_scores_relative, self.attn_apply_relative, self.embed,+ self.gated_tanh,+ self.flip_channels, ] { device.destroy_pipeline(pipeline, None); }
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 35ed55883a..b1d806541f 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -49,6 +49,10 @@ pub mod graph { /// /// See [`crate::nets::vits_enc`]. Its input is symbol ids rather than pixels or latents. pub const VITS_ENC: u32 = 8;+ /// Piper's VITS normalising flow \u2014 the `flow` module, run in reverse.+ ///+ /// See [`crate::nets::vits_flow`].+ pub const VITS_FLOW: u32 = 9; } /// 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 17e5aeb247..df3eccac9a 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -100,6 +100,7 @@ GRAPHS = { "ppocr_rec": 6, "vits_dec": 7, "vits_enc": 8,+ "vits_flow": 9, } # SHA-256 over the ordered layer table (see `layer_table_digest`). Regenerate with@@ -113,6 +114,7 @@ EXPECTED_DIGEST = { "ppocr_rec": "8c16a8702aa7a1e7b4d94787d089616ca4bc3d8aaeebb0b0159eabc56af3ba08", "vits_dec": "ac3fa714b9c0074e7fb7fa1d5f5b65e30bf558df0817b014897cd56b6e850020", "vits_enc": "93ee24f70b490334d11b383f043e81284a3e781bc263597830c50f8df14db2c1",+ "vits_flow": "38cecda81bcfd4eb98782395905ddbe4637aa7f55fecb2de996d09fc530e2e6d", } # Graphs that are one **module** of a larger export, keyed by the node-name prefix that@@ -132,6 +134,7 @@ EXPECTED_DIGEST = { MODULES = { "vits_dec": "/dec/", "vits_enc": "/enc_p/",+ "vits_flow": "/flow/", } # `outputs` are the graph outputs the Rust forward pass corresponds to; the export may@@ -204,6 +207,14 @@ EXPECTED_OPS = { "ReduceMean": 24, "Relu": 6, "Reshape": 96, "Shape": 25, "Slice": 42, "Softmax": 6, "Split": 1, "Sqrt": 12, "Sub": 42, "Transpose": 73, "Unsqueeze": 130, "Where": 6, },+ # Counted within `/flow/` only. The 16 gated activations are NOT here: their Tanh and+ # Sigmoid nodes carry auto-generated names with no module path, so a prefix cannot see+ # them. `ConstantOfShape`/`Neg`/`Exp` are the mean-only coupling''s absent log-scale,+ # which is `exp(-0)`; the 32 `Mul`s are the padding mask and the identity multiply by it.+ "vits_flow": {+ "Add": 28, "Concat": 4, "ConstantOfShape": 24, "Conv": 40, "Exp": 4, "Mul": 32,+ "Neg": 4, "Shape": 24, "Slice": 28, "Split": 4, "Sub": 4,+ }, }
scripts/ml/onnx_parity.py
diff --git a/scripts/ml/onnx_parity.py b/scripts/ml/onnx_parity.pyindex 4e586b72f6..1bd3e73f93 100644--- a/scripts/ml/onnx_parity.py+++ b/scripts/ml/onnx_parity.py@@ -56,6 +56,7 @@ PROBE = { # 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",+ "vits_flow": None, } # Graphs that are one module of a larger export, and have to be cut out of it before they can@@ -66,7 +67,19 @@ PROBE = { # would not even agree with each other. `onnx.utils.extract_model` cuts the subgraph at the # vocoder's first convolution instead, and the input is random latents. SUBGRAPH = {- "vits_dec": {"first": "/dec/conv_pre/Conv", "channels": 192},+ "vits_dec": {"first": "/dec/conv_pre/Conv", "channels": 192, "prefix": "/dec/"},+ # The flow's first node is the leading flip, whose data input is the sampled prior. It+ # also needs the padding mask cut out and fed as ones: the mask is derived from+ # `input_lengths` and `scales`, so leaving it in drags the whole graph before the flow in+ # with it. `nets::vits_flow` omits the mask for the same reason `nets::vits_enc` does —+ # for one unpadded utterance it is the identity, which was verified bit-identically on the+ # encoder's copy of the same tensor.+ "vits_flow": {+ "first": "/flow/flows.7/Slice",+ "channels": 192,+ "prefix": "/flow/",+ "ones": "/Cast_2_output_0",+ }, } @@ -144,10 +157,19 @@ def main(): feed = None if cut is not None:- # Random latents, deterministic. The vocoder is not a classifier, so there is no+ # Random latents, deterministic. These nets are not classifiers, 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)+ if cut.get("ones"):+ session_inputs = {i.name: i for i in model.graph.input}+ mask = session_inputs[cut["ones"]]+ rank = len(mask.type.tensor_type.shape.dim)+ shape = [1] * (rank - 1) + [args.width]+ feed = {+ model.graph.input[0].name: x,+ cut["ones"]: np.ones(shape, dtype=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.@@ -209,6 +231,34 @@ def main(): report("the runtime", want, got) +def inline_constants(model):+ """Turn every `Constant` node into an initializer, in place.++ Cutting a module out of a larger export breaks whenever a node inside it reads a+ `Constant` produced outside it — the flow's four channel reversals each read three+ constants that belong to the encoder, so extracting the flow alone leaves them dangling.+ An initializer travels with any subgraph that references it, so inlining first makes the+ cut work wherever it is placed.+ """+ keep = []+ for node in model.graph.node:+ if node.op_type == "Constant":+ for attribute in node.attribute:+ if attribute.name == "value":+ tensor = onnx.TensorProto()+ tensor.CopyFrom(attribute.t)+ tensor.name = node.output[0]+ model.graph.initializer.append(tensor)+ break+ else:+ keep.append(node)+ else:+ keep.append(node)+ del model.graph.node[:]+ model.graph.node.extend(keep)+ return model++ def extract(path, model, cut, work): """Cut one module out of a larger export, so it can be run on its own. @@ -218,11 +268,16 @@ def extract(path, model, cut, work): first = next((n for n in model.graph.node if n.name == cut["first"]), None) if first is None: raise SystemExit(f"{cut['first']} is not in this export")- outputs = [- o for o in (n.output[0] for n in model.graph.node if n.name.startswith("/dec/"))- ]+ prefix = cut["prefix"]+ outputs = [n.output[0] for n in model.graph.node if n.name.startswith(prefix)]+ # Inline first, then write the whole model back out: `extract_model` reads from a path.+ flattened = os.path.join(work, "flattened.onnx")+ onnx.save(inline_constants(onnx.load(path)), flattened) target = os.path.join(work, "subgraph.onnx")- onnx.utils.extract_model(path, target, [first.input[0]], [outputs[-1]])+ inputs = [first.input[0]]+ if cut.get("ones"):+ inputs.append(cut["ones"])+ onnx.utils.extract_model(flattened, target, inputs, [outputs[-1]]) return onnx.load(target)