Modern Apps git

← Modern-Apps.git

library:ml: Piper's HiFi-GAN vocoder, and a standalone leaky ReLU

Commit
3b46baf055720e48e20db13955094e874f63213d
Author
vayun-mathur <[email protected]>
When
2026-08-27 22:16 UTC (3 months ago)
Parents
9c6a236

Diff

library/ml/src/main/rust/shaders/common.glsl
diff --git a/library/ml/src/main/rust/shaders/common.glsl b/library/ml/src/main/rust/shaders/common.glslindex bc2f11e5a8..fc0d87d276 100644--- a/library/ml/src/main/rust/shaders/common.glsl+++ b/library/ml/src/main/rust/shaders/common.glsl@@ -79,6 +79,7 @@ layout(push_constant) uniform Push { #define ACT_PRELU 4u #define ACT_CLIP01 5u #define ACT_SWISH 6u+#define ACT_TANH 7u  // This invocation's output element, across a 2D grid of workgroups. //@@ -130,6 +131,12 @@ float activate(float x, uint kind, uint channel) {         // both, and substituting one for the other is a plausible-looking accuracy loss.         return x / (1.0 + exp(-x));     }+    if (kind == ACT_TANH) {+        // The last thing Piper's vocoder does, which is what bounds the waveform to+        // -1..1. GLSL's `tanh` is a built-in; writing it as two exponentials would+        // overflow fp32 for the large inputs a badly-conditioned voice can produce.+        return tanh(x);+    }     return x; } 
library/ml/src/main/rust/shaders/leaky_relu.comp
diff --git a/library/ml/src/main/rust/shaders/leaky_relu.comp b/library/ml/src/main/rust/shaders/leaky_relu.compnew file mode 100644index 0000000000..7d78c52728--- /dev/null+++ b/library/ml/src/main/rust/shaders/leaky_relu.comp@@ -0,0 +1,39 @@+#version 450+//! `x < 0 ? alpha * x : x`, as a standalone pass. 16 uses in Piper's HiFi-GAN vocoder.+//!+//! # Why this is an op and not an activation+//!+//! Every other activation in this runtime fuses into the layer that produced its input, so+//! there is no standalone pass at all — see `common.glsl`'s `activate`. HiFi-GAN's+//! LeakyReLUs cannot, for two reasons, and both had to be read out of the graph rather than+//! assumed:+//!+//! * They are **pre**-activations. A ResBlock is `h = h + conv(lrelu(h))`, so the LeakyReLU+//!   sits in front of its convolution, not behind one.+//! * The tensor it reads is *also* the residual's other operand. Folding it into the `Add`+//!   that produced `h` would consume `h`, and the skip connection needs it unchanged.+//!+//! # Alpha travels+//!+//! In `param0_bits`, because this export uses **two** different slopes: 0.1 for the fifteen+//! inside the upsampling stages and 0.01 for the one in front of `conv_post`. A hardcoded+//! 0.1 would be wrong for the last layer before the waveform, which is exactly the kind of+//! error that survives every shape check and comes out as a quieter, duller sound.+//!+//! Distinct from `ACT_PRELU`, which is the same function with a *learned* slope per channel+//! read from the weights buffer. Here the slope is one constant for the whole tensor and is+//! not in the file at all.++#include "common.glsl"++void main() {+    uint index = global_index();+    if (index >= p.count) {+        return;+    }+    float value = float(arena[p.in0 + index]);+    float alpha = uintBitsToFloat(p.param0_bits);+    // The branch is on the sign of a loaded value, so it diverges within a wave. A `mix`+    // on the comparison would too, and this reads as the definition does.+    arena[p.out_at + index] = float16_t(value < 0.0 ? value * alpha : value);+}
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 08c75eabaf..1d1707c0ab 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 u2netp;+pub mod vits_dec;  /// 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)]@@ -102,6 +103,12 @@ pub enum Act {     /// Seven uses in PP-OCRv5 recognition, where the export spells it out as     /// `Mul(x, Sigmoid(x))`; the fold recognises that the way it recognises HardSwish.     Swish,+    /// `tanh(x)`.+    ///+    /// One use: the last thing Piper's HiFi-GAN vocoder does, which is what bounds its+    /// output to a waveform. It follows `conv_post` directly, so unlike that net's+    /// LeakyReLUs it does fuse — see [`Kind::LeakyRelu`].+    Tanh, }  impl Act {@@ -114,6 +121,7 @@ impl Act {             Act::PRelu(_) => 4,             Act::Clip01 => 5,             Act::Swish => 6,+            Act::Tanh => 7,         }     } }@@ -213,10 +221,27 @@ pub enum Kind {     Softmax,     /// `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`, attention's weighted sum.     ///+    /// `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`, attention's weighted sum.+    ///     /// Writes `[d_model, 1, T]`, so the head concatenation that normally follows     /// attention is not an op: output channel `c` belongs to head `c / head_dim` and     /// lands where the concatenated result wants it. Head count in [`Push::group`].     AttnApply,+    /// `x < 0 ? alpha * x : x`, as a standalone pass. 16 uses in Piper's HiFi-GAN vocoder.+    ///+    /// The only activation here that is **not** fused into the layer before it, because in+    /// a HiFi-GAN ResBlock it is not behind a layer at all: the block is+    /// `h = h + conv(lrelu(h))`, so it sits in front of its convolution, and the tensor it+    /// reads is also the residual's other operand — folding it backwards would consume the+    /// skip connection.+    ///+    /// `alpha` arrives in [`Push::param0_bits`] rather than being hardcoded, because the+    /// export uses two slopes: 0.1 for the fifteen inside the upsampling stages and 0.01+    /// for the one in front of `conv_post`.+    ///+    /// Distinct from [`Act::PRelu`], which is the same function with a *learned* slope per+    /// channel read from the weights file.+    LeakyRelu, }  /// The push-constant block every shader declares.@@ -464,6 +489,11 @@ enum Node {         input: Id,         out: Id,     },+    LeakyRelu {+        input: Id,+        out: Id,+        alpha: f32,+    },     AttnApply {         probs: Id,         v: Id,@@ -876,6 +906,15 @@ impl<'a> Builder<'a> {         out     } +    /// `x < 0 ? alpha * x : x`, as its own pass. See [`Kind::LeakyRelu`] for why it is not+    /// fused into the layer before it.+    pub fn leaky_relu(&mut self, input: Id, alpha: f32) -> Id {+        let shape = self.shape_of(input);+        let out = self.tensor(shape);+        self.nodes.push(Node::LeakyRelu { input, out, alpha });+        out+    }+     /// Apply `probs`, a `[heads, T, T]` score map, to `v`, a `[d_model, 1, T]` sequence.     pub fn attn_apply(&mut self, probs: Id, v: Id, heads: u32) -> Id {         let (sp, sv) = (self.shape_of(probs), self.shape_of(v));@@ -1278,6 +1317,26 @@ impl<'a> Builder<'a> {                     invocations: so.len(),                 });             }+            Node::LeakyRelu { input, out, alpha } => {+                let so = shape(*out);+                ops.push(Op::Dispatch {+                    kind: Kind::LeakyRelu,+                    push: Push {+                        in0: at(*input)?,+                        out: at(*out)?,+                        in_c: so.c,+                        in_h: so.h,+                        in_w: so.w,+                        out_c: so.c,+                        out_h: so.h,+                        out_w: so.w,+                        param0_bits: alpha.to_bits(),+                        count: so.len(),+                        ..Push::default()+                    },+                    invocations: so.len(),+                });+            }         }         Ok(())     }@@ -1296,6 +1355,7 @@ impl Node {             | Node::LayerNorm { out, .. }             | Node::AttnScores { out, .. }             | Node::Softmax { out, .. }+            | Node::LeakyRelu { out, .. }             | Node::AttnApply { out, .. }             | Node::Concat { out, .. } => *out,         }@@ -1310,6 +1370,7 @@ impl Node {             | Node::Affine { input, .. }             | Node::LayerNorm { input, .. }             | Node::Softmax { input, .. }+            | Node::LeakyRelu { input, .. }             | Node::GlobalAvgPool { input, .. } => vec![*input],             Node::Binary { a, b, .. } => vec![*a, *b],             Node::AttnScores { q: a, k: b, .. } | Node::AttnApply { probs: a, v: b, .. } => {
library/ml/src/main/rust/src/nets/reference.rs
diff --git a/library/ml/src/main/rust/src/nets/reference.rs b/library/ml/src/main/rust/src/nets/reference.rsindex 596dc69acb..4d3ae88b6f 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -59,6 +59,8 @@ mod act {     pub const CLIP01: u32 = 5;     /// `x * sigmoid(x)`.     pub const SWISH: u32 = 6;+    /// `tanh(x)`.+    pub const TANH: u32 = 7; }  /// The fused activation, mirroring `activate` in `common.glsl`.@@ -79,6 +81,7 @@ fn activate(x: f32, kind: u32, slope: f32) -> f32 {         }         act::CLIP01 => x.clamp(0.0, 1.0),         act::SWISH => x / (1.0 + (-x).exp()),+        act::TANH => x.tanh(),         _ => x,     } }@@ -183,6 +186,7 @@ impl Reference {                     Kind::AttnScores => self.attn_scores(push),                     Kind::Softmax => self.softmax(push),                     Kind::AttnApply => self.attn_apply(push),+                    Kind::LeakyRelu => self.leaky_relu(push),                 },             };             result.map_err(|e| format!("step {step} ({op:?}): {e}"))?;@@ -458,6 +462,16 @@ impl Reference {         Ok(())     } +    /// `x < 0 ? alpha * x : x`, elementwise, with `alpha` carried as raw bits.+    fn leaky_relu(&mut self, p: &Push) -> Result<(), String> {+        let alpha = f32::from_bits(p.param0_bits);+        for i in 0..p.count {+            let value = self.load(p.in0, i)?;+            self.store(p.out, i, if value < 0.0 { value * alpha } else { value })?;+        }+        Ok(())+    }+     /// `out = in * scale + shift`, both scalars carried as raw bits in the push block.     fn affine(&mut self, p: &Push) -> Result<(), String> {         let scale = f32::from_bits(p.param0_bits);@@ -1125,6 +1139,7 @@ mod tests {         assert_eq!(Act::PRelu(0).code(), act::PRELU);         assert_eq!(Act::Clip01.code(), act::CLIP01);         assert_eq!(Act::Swish.code(), act::SWISH);+        assert_eq!(Act::Tanh.code(), act::TANH);     }      #[test]@@ -1554,6 +1569,46 @@ mod tests {         assert!(error.contains("height above"), "{error}");     } +    #[test]+    fn a_leaky_relu_scales_only_the_negative_side() {+        // HiFi-GAN's slope. A standalone pass rather than a fused activation, because in a+        // ResBlock it sits in front of its convolution; see `Kind::LeakyRelu`.+        let got = one(Shape::new(1, 1, 5), &[-4.0, -1.0, 0.0, 1.0, 4.0], &[], |b, x| {+            b.leaky_relu(x, 0.1)+        });+        close(&got, &[-0.4, -0.1, 0.0, 1.0, 4.0]);+    }++    #[test]+    fn a_leaky_relu_carries_its_own_slope() {+        // The vocoder uses 0.1 for fifteen of its sixteen and 0.01 for the one in front of+        // `conv_post`, so a hardcoded slope would be wrong for the last layer before the+        // waveform — quieter and duller, and caught by nothing else.+        let steep = one(Shape::new(1, 1, 2), &[-2.0, 2.0], &[], |b, x| b.leaky_relu(x, 0.1));+        let shallow = one(Shape::new(1, 1, 2), &[-2.0, 2.0], &[], |b, x| b.leaky_relu(x, 0.01));+        close(&steep, &[-0.2, 2.0]);+        close(&shallow, &[-0.02, 2.0]);+        // At slope zero it is a ReLU, and at one the identity.+        close(&one(Shape::new(1, 1, 2), &[-3.0, 3.0], &[], |b, x| b.leaky_relu(x, 0.0)), &[0.0, 3.0]);+        close(&one(Shape::new(1, 1, 2), &[-3.0, 3.0], &[], |b, x| b.leaky_relu(x, 1.0)), &[-3.0, 3.0]);+    }++    #[test]+    fn tanh_bounds_its_output_to_the_unit_interval() {+        // What makes the vocaster's last layer a waveform. Saturates rather than clipping,+        // so the ends are not exactly +/-1.+        let inputs = [-8.0f32, -1.0, 0.0, 1.0, 8.0];+        let got = one(+            Shape::new(1, 1, 5),+            &inputs,+            &[(vec![1, 1, 1, 1], vec![1.0]), (vec![1], vec![0.0])],+            |b, x| b.conv_same(x, 0, 1, 1, 1, Act::Tanh),+        );+        let want: Vec<f32> = inputs.iter().map(|&x| x.tanh()).collect();+        close(&got, &want);+        assert!(got.iter().all(|v| (-1.0..=1.0).contains(v)), "{got:?}");+    }+     #[test]     fn relu_clamps_at_zero_without_touching_positives() {         let got = one(
library/ml/src/main/rust/src/nets/vits_dec.rs
diff --git a/library/ml/src/main/rust/src/nets/vits_dec.rs b/library/ml/src/main/rust/src/nets/vits_dec.rsnew file mode 100644index 0000000000..de6d531e0e--- /dev/null+++ b/library/ml/src/main/rust/src/nets/vits_dec.rs@@ -0,0 +1,379 @@+//! Piper's HiFi-GAN vocoder: the `dec` half of VITS, and the expensive half of speaking.+//!+//! # What it is+//!+//! 192 channels of latent at one frame per 256 output samples, upsampled 8x, 8x and 4x into+//! a single-channel waveform. Sixty-seven ONNX nodes and 23 weight layers — the smallest+//! part of the VITS graph by a wide margin, and by far the most arithmetic, because every+//! layer after the first upsample runs at audio rate.+//!+//! # Why this one first+//!+//! The full VITS export is 2755 nodes and cannot be a hardcoded plan: its duration+//! predictor samples noise and builds a monotonic alignment out of `NonZero`, `ScatterND`+//! and `GatherND`, and its output length depends on the durations it predicts. But the graph+//! keeps its Torch module paths, and they split it exactly the way the ncnn build already+//! did:+//!+//! | module  | nodes | shape                                            |+//! |---------|-------|--------------------------------------------------|+//! | `enc_p` |   865 | text encoder, near-static                        |+//! | `dp`    |  1455 | stochastic duration predictor — all the dynamism |+//! | `flow`  |   196 | normalising flow, static                         |+//! | `dec`   |    67 | this                                             |+//!+//! The dynamism is confined to `dp`, which is also the cheapest part: a few small+//! convolutions producing one number per phoneme. So `dp` and the alignment glue belong on+//! the CPU, and `enc_p`, `flow` and this belong on the GPU.+//!+//! # Everything here was already expressible+//!+//! The `Div` by 3 that averages the residual blocks is [`Kind::Affine`] at scale `1/3`. The+//! 1-D convolutions are `(1, k)` kernels. `Tanh` follows `conv_post` directly, so it fuses.+//! The one genuinely new op is [`super::Kind::LeakyRelu`], which cannot fuse: a ResBlock is+//! `h = h + conv(lrelu(h))`, so it sits in *front* of its convolution and reads the tensor+//! the skip connection also needs.+//!+//! # Length+//!+//! `frames` is a parameter because the utterance length is data-dependent — it comes from+//! the durations `dp` predicted, not from anything the caller chose. A plan is one fixed+//! shape, so the host has to pick a bucket and trim the tail; see the note on+//! `vulkan::run::Net`.++use super::{Act, Builder, Id, Plan, Shape, WeightSource};++/// Latent channels in, which is VITS's `inter_channels`.+pub const LATENT: u32 = 192;++/// Channels after `conv_pre`, halving at each upsample.+pub const INITIAL: u32 = 256;++/// Total upsampling, so the output is `frames * SAMPLES_PER_FRAME` samples long.+pub const SAMPLES_PER_FRAME: u32 = 256;++/// Output sample rate, from the voice's `.onnx.json`. Carried here because a caller that+/// played the waveform at the wrong rate would get a working but wrongly-pitched voice.+pub const SAMPLE_RATE: u32 = 16_000;++/// The three upsampling stages, as `(kernel, stride)` on the width.+///+/// `8 * 8 * 4` is [`SAMPLES_PER_FRAME`]. The kernel is twice the stride in each case, which+/// is what makes the transposed convolutions overlap evenly rather than leaving a comb.+const UPSAMPLES: [(u32, u32); 3] = [(16, 8), (16, 8), (8, 4)];++/// Each stage's three residual blocks, as `(kernel, [dilation, dilation])`.+///+/// HiFi-GAN's ResBlock2: two convolutions per block, run at three kernel widths in parallel+/// and averaged. The dilations grow with the kernel so all three see a similar span.+const RESBLOCKS: [(u32, [u32; 2]); 3] = [(3, [1, 2]), (5, [2, 6]), (7, [3, 12])];++/// The slope of the fifteen LeakyReLUs inside the upsampling stages.+const SLOPE: f32 = 0.1;++/// The slope of the sixteenth, in front of `conv_post`.+///+/// A different value, and the reason [`super::Kind::LeakyRelu`] carries its alpha rather+/// than hardcoding one. Getting this wrong makes the last layer before the waveform quieter+/// and duller, which no shape or range check would notice.+const FINAL_SLOPE: f32 = 0.01;++/// Tensors the `.vkml` must hold: 23 layers, each a weight and a bias.+///+/// `conv_pre`, three transposed convolutions, `3 * 2` convolutions per stage, and+/// `conv_post` — `(1 + 3 + 18 + 1) * 2`. `conv_post` carries no bias in the export, so the+/// converter writes a zero one and the runtime stays uniform.+pub const TENSORS: usize = 46;++/// Hands out `.vkml` tensor indices in the order the layers appear.+struct Layers {+    next: usize,+}++impl Layers {+    fn take(&mut self) -> usize {+        let index = self.next;+        self.next += 2;+        index+    }+}++/// A `1 x k` convolution along the waveform, dilated and padded to hold the length.+///+/// `pad = dilation * (k - 1) / 2` on each side, which is size-preserving for the odd kernels+/// this net uses and is what the export's pads say.+fn along(b: &mut Builder, l: &mut Layers, x: Id, out: u32, kernel: u32, dilation: u32) -> Id {+    let pad = dilation * (kernel - 1) / 2;+    b.conv(+        x,+        l.take(),+        out,+        (1, kernel),+        (1, 1),+        (1, dilation),+        (0, pad, 0, pad),+        1,+        Act::None,+    )+}++/// One ResBlock2: `h = h + conv(lrelu(h))`, twice.+///+/// `first` is the shared LeakyReLU of the block's input. All three blocks in a stage read the+/// same tensor, so the export computes that activation once and so does this — three+/// identical passes over an audio-rate tensor is not free.+fn resblock(+    b: &mut Builder,+    l: &mut Layers,+    input: Id,+    first: Id,+    channels: u32,+    kernel: u32,+    dilations: [u32; 2],+) -> Id {+    let inner = along(b, l, first, channels, kernel, dilations[0]);+    let residual = b.add(inner, input);+    let activated = b.leaky_relu(residual, SLOPE);+    let inner = along(b, l, activated, channels, kernel, dilations[1]);+    b.add(inner, residual)+}++/// Build the vocoder for an utterance of `frames` latent frames.+///+/// The output is `[1, 1, frames * 256]` in `-1..1`.+pub fn build(weights: &dyn WeightSource, frames: u32) -> Result<Plan, String> {+    if frames == 0 {+        return Err("a vocoder 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(LATENT, 1, frames));++    // `conv_pre` has no activation of its own; the first LeakyReLU belongs to stage 0.+    let mut x = along(b, l, input, INITIAL, 7, 1);+    let mut channels = INITIAL;+    for (kernel, stride) in UPSAMPLES {+        let activated = b.leaky_relu(x, SLOPE);+        // `pads` are `stride / 2` each side, which with `kernel == 2 * stride` makes the+        // output exactly `stride` times longer.+        let pad = stride / 2;+        channels /= 2;+        let upsampled = b.conv_transpose(+            activated,+            l.take(),+            channels,+            (1, kernel),+            (1, stride),+            (0, pad, 0, pad),+            Act::None,+        );++        // The three blocks run in parallel on the same tensor and are averaged, so the+        // shared activation is computed once here rather than inside each.+        let first = b.leaky_relu(upsampled, SLOPE);+        let mut total: Option<Id> = None;+        for (kernel, dilations) in RESBLOCKS {+            let block = resblock(b, l, upsampled, first, channels, kernel, dilations);+            total = Some(match total {+                Some(sum) => b.add(sum, block),+                None => block,+            });+        }+        let summed = total.ok_or("a stage with no residual blocks")?;+        // The mean of the three. An `Affine` rather than a divide op: this runtime has no+        // scalar division, and multiplying by the reciprocal is what one would compile to.+        x = b.affine(summed, 1.0 / RESBLOCKS.len() as f32, 0.0);+    }++    let activated = b.leaky_relu(x, FINAL_SLOPE);+    // Down to one channel, bounded into a waveform. `Tanh` fuses because it follows its+    // convolution rather than preceding one.+    let waveform = b.conv(+        activated,+        l.take(),+        1,+        (1, 7),+        (1, 1),+        (1, 1),+        (0, 3, 0, 3),+        1,+        Act::Tanh,+    );++    if l.next != TENSORS {+        return Err(format!("the forward pass claims {} tensors, not {TENSORS}", l.next));+    }+    builder.finish(&[waveform])+}++#[cfg(test)]+mod tests {+    use super::super::tests::{assert_no_aliasing, Shapes};+    use super::super::{Kind, Op};+    use super::*;++    /// About a second of speech at 16 kHz, which is 62.5 frames; 64 is the bucket above it.+    const FRAMES: u32 = 64;++    fn plan(frames: u32) -> (Shapes, Plan) {+        let source = Shapes::new(TENSORS);+        let plan = build(&source, frames).expect("the vocoder 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_output_is_one_channel_of_audio_at_256_samples_a_frame() {+        let (_, plan) = plan(FRAMES);+        assert_eq!(+            plan.output().expect("one output").shape,+            Shape::new(1, 1, FRAMES * SAMPLES_PER_FRAME)+        );+        assert_eq!(+            plan.input().expect("one input").shape,+            Shape::new(LATENT, 1, FRAMES)+        );+    }++    #[test]+    fn the_three_stages_upsample_by_exactly_eight_eight_and_four() {+        // 8 * 8 * 4 is 256. A transposed convolution whose pads did not match its stride+        // would drift by a few samples per stage, which compounds into a length that is+        // close to right and a waveform that is not.+        for frames in [1u32, 5, 64, 512] {+            let (_, plan) = plan(frames);+            assert_eq!(+                plan.output().expect("one output").shape.w,+                frames * SAMPLES_PER_FRAME,+                "at {frames} frames"+            );+        }+    }++    #[test]+    fn every_convolution_holds_the_length_it_was_given() {+        // Each dilated kernel is padded by `dilation * (k - 1) / 2`, so nothing but the+        // three transposed convolutions changes the width. One wrong pad would shorten the+        // audio and misalign every residual after it.+        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, push.in_w, "step {step} changed the length");+                assert_eq!(push.out_h, 1, "step {step} is not 1-D");+            }+        }+    }++    #[test]+    fn the_op_inventory_matches_the_export() {+        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;+            }+        }+        // 19 convolutions: `conv_pre`, 18 in the residual blocks, and `conv_post`. That is+        // 20 — `conv_post` is one of them, so 1 + 18 + 1.+        assert_eq!(counts.get("Conv"), Some(&20), "{counts:?}");+        assert_eq!(counts.get("ConvTranspose"), Some(&3), "{counts:?}");+        // Sixteen LeakyReLUs: one before each upsample, one shared per stage, one inside+        // each of the nine blocks, and one before `conv_post`.+        assert_eq!(counts.get("LeakyRelu"), Some(&(3 + 3 + 9 + 1)), "{counts:?}");+        // Two residual adds per block, plus two to sum each stage's three blocks.+        assert_eq!(counts.get("Add"), Some(&(9 * 2 + 3 * 2)), "{counts:?}");+        // One mean per stage.+        assert_eq!(counts.get("Affine"), Some(&3), "{counts:?}");+        assert_eq!(counts.len(), 5, "{counts:?}");+    }++    #[test]+    fn the_leaky_relu_slopes_are_the_exports_two_values() {+        // Fifteen at 0.1 and the last at 0.01. A single slope everywhere is the mistake this+        // pins, and it is inaudible in a spectrogram and audible in the output.+        let (_, plan) = plan(FRAMES);+        let slopes: Vec<f32> = plan+            .ops+            .iter()+            .filter_map(|op| match op {+                Op::Dispatch { kind: Kind::LeakyRelu, push, .. } => {+                    Some(f32::from_bits(push.param0_bits))+                }+                _ => None,+            })+            .collect();+        assert_eq!(slopes.len(), 16);+        assert_eq!(slopes.iter().filter(|s| **s == SLOPE).count(), 15);+        assert_eq!(slopes.last().copied(), Some(FINAL_SLOPE));+    }++    #[test]+    fn each_stage_averages_its_three_blocks_rather_than_summing_them() {+        // Summing would make the signal three times too loud at every stage, which is 27x+        // by the output — clipped by the final tanh into something that sounds like speech+        // through a fuzz pedal.+        let (_, plan) = plan(FRAMES);+        for op in &plan.ops {+            if let Op::Dispatch { kind: Kind::Affine, push, .. } = op {+                let scale = f32::from_bits(push.param0_bits);+                assert!((scale - 1.0 / 3.0).abs() < 1e-6, "{scale}");+                assert_eq!(f32::from_bits(push.param1_bits), 0.0);+            }+        }+    }++    #[test]+    fn the_tensor_table_matches_the_export() {+        // Every weight and bias the `dec` module of `en_GB-alan-low.onnx` holds, summed:+        // 23 layers, one of which (`conv_post`) carries no bias, so the converter writes a+        // zero one and this counts it.+        //+        // The same check `ppocr_rec` leans on, and the same reason: a channel count, kernel+        // width or dilation that is wrong here disagrees with the export, while every+        // structural test above would still pass.+        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, 1_662_977);+    }++    #[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);+        let seconds = (FRAMES * SAMPLES_PER_FRAME) as f32 / SAMPLE_RATE as f32;+        println!(+            "vits_dec at {FRAMES} frames ({seconds:.2}s of audio): {} 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 a4c1519db6..7e3365c55f 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -40,9 +40,10 @@ const LAYERNORM: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/layernorm.com const ATTN_SCORES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/attn_scores.comp.spv")); const SOFTMAX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/softmax.comp.spv")); const ATTN_APPLY: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/attn_apply.comp.spv"));+const LEAKY_RELU: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/leaky_relu.comp.spv"));  /// Every shader, in the order [`Pipelines::create`] destructures them.-const SPIRV: [&[u8]; 14] = [+const SPIRV: [&[u8]; 15] = [     CONV,     CONV_TRANSPOSE,     MAXPOOL,@@ -57,6 +58,7 @@ const SPIRV: [&[u8]; 14] = [     ATTN_SCORES,     SOFTMAX,     ATTN_APPLY,+    LEAKY_RELU, ];  /// `local_size_x` in `shaders/common.glsl`. A dispatch covers `ceil(invocations / this)`@@ -94,6 +96,7 @@ pub struct Pipelines {     attn_scores: vk::Pipeline,     softmax: vk::Pipeline,     attn_apply: vk::Pipeline,+    leaky_relu: vk::Pipeline, }  impl Pipelines {@@ -230,6 +233,7 @@ impl Pipelines {             attn_scores,             softmax,             attn_apply,+            leaky_relu,         ] = match <[vk::Pipeline; SPIRV.len()]>::try_from(built) {             Ok(all) => all,             Err(built) => {@@ -260,6 +264,7 @@ impl Pipelines {             attn_scores,             softmax,             attn_apply,+            leaky_relu,         })     } @@ -280,6 +285,7 @@ impl Pipelines {             Kind::AttnScores => self.attn_scores,             Kind::Softmax => self.softmax,             Kind::AttnApply => self.attn_apply,+            Kind::LeakyRelu => self.leaky_relu,         }     } @@ -302,6 +308,7 @@ impl Pipelines {             self.attn_scores,             self.softmax,             self.attn_apply,+            self.leaky_relu,         ] {             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 e96fcdffa1..cab53f19b4 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -39,6 +39,12 @@ pub mod graph {     pub const PPOCR_DET: u32 = 5;     /// PP-OCRv5 mobile text recognition, 48 tall.     pub const PPOCR_REC: u32 = 6;+    /// Piper's VITS vocoder — the `dec` module, 192 latent channels to a 16 kHz waveform.+    ///+    /// Only the vocoder: the text encoder, the flow and the duration predictor are separate+    /// 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; }  /// One tensor's entry in the table: where it is and what shape it is.
scripts/ml/vkml_convert.py
diff --git a/scripts/ml/vkml_convert.py b/scripts/ml/vkml_convert.pyindex 02a2ffb173..175ad4b7c5 100644--- a/scripts/ml/vkml_convert.py+++ b/scripts/ml/vkml_convert.py@@ -97,6 +97,7 @@ GRAPHS = {     # Folded ahead of time by `scripts/ml/ppocr_fold.py`, not by this script.     "ppocr_det": 5,     "ppocr_rec": 6,+    "vits_dec": 7, }  # SHA-256 over the ordered layer table (see `layer_table_digest`). Regenerate with@@ -108,6 +109,7 @@ EXPECTED_DIGEST = {     "mobilefacenet": "40987839aec03378958581deba29ce9fd9dd1ae9aa88d0c7ad04a885a2e2122c",     "ppocr_det": "51b0c9ed871526fa270b4bfa53b393c056db21c58193849fb83d44768f69ef9b",     "ppocr_rec": "8c16a8702aa7a1e7b4d94787d089616ca4bc3d8aaeebb0b0159eabc56af3ba08",+    "vits_dec": "", }  # What each graph is exported at, as `[channels, height, width]` after the batch