speech: delete Piper, its three VITS nets and five post modules
- Commit
e90678f9ec3d77ef9e03d5e7e105fc5b2d87002a- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 22:26 UTC (3 months ago)
- Parents
abfbd31
Diff
SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdindex 409bf49bc0..4fc53f3d96 100644--- a/SUPPLY_CHAIN_RISKS.md+++ b/SUPPLY_CHAIN_RISKS.md@@ -48,12 +48,16 @@ These servers provide data/functionality that is NOT intrinsically tied to a sin `health` **no longer requests `android.permission.INTERNET` at all** — it is the first app here with no network access whatsoever. Its nutrition database ships inside the APK as a brotli-compressed columnar asset (`scripts/generate_food_db.py` → `health/src/main/assets/food.bin.br`, 10.9 MB for 465,000 products), which `FoodDatabase.kt` turns into a SQLite/FTS5 database on first launch. Upstream is the **Open Food Facts** daily CSV export (ODbL v1.0, attributed in-app) — a build-host dependency, not a runtime one: if it vanished the shipped database keeps working and only stops being refreshable. The older `/api/food/search` and `/api/food/data/:id` endpoints remain up for previously-shipped builds. -`speech` **no longer downloads a recogniser**, though TTS voices are still fetched:+`speech` **no longer downloads anything**: - **Speech-to-text** is `whisper-base` int8 ONNX (~77 MB) in `speech/src/main/assets/whisper-base/`, run on `onnxruntime-android` by `WhisperOnnxEngine.kt`. It replaced a 117 MB runtime download of the ncnn conversion from `data.vayunmathur.com/models/whisper-tiny/`. It was `whisper-tiny` until the swap to `base`, which roughly halves word error at the cost of about 36 MB of APK; the two exports declare identical operator sets, so the reduced ONNX Runtime build did not have to be regenerated. Upstream is **`onnx-community/whisper-base`** on HuggingFace (an ONNX Runtime dynamic quantization of `openai/whisper-base`, Apache-2.0), pinned to revision `1846881b` — a **build-host** dependency only, pinned by SHA-256 and refreshed by `scripts/speech/fetch_whisper_onnx.sh`. If it vanished, shipped builds keep transcribing. Note this moved the log-mel front end and the KV-cached decode loop into Kotlin (`WhisperFeatures.kt`, `WhisperOnnxEngine.kt`), because `onnx2ncnn` supports none of the quantized ops and the ncnn AAR expects a six-net decomposition HuggingFace does not export.-- **Text-to-speech** voices all remain SHA-256-pinned downloads from `data.vayunmathur.com/models/piper/` (29 languages, 28–80 MB each). Bundling the English one was considered and dropped: at 51 MB it was 40% of the APK, and the ncnn `Vits` is filesystem-only so it would also have cost a second 51 MB extracted copy on disk.+- **Text-to-speech** is **Supertonic 3** bundled in `speech/src/main/assets/supertonic/`, run on `:library:ml` - our own Vulkan compute runtime - by `SupertonicTtsService.kt`. It replaced Piper (VITS), whose voices were a **1,834 MB** runtime download across 42 SHA-256-pinned archives from `data.vayunmathur.com/models/piper/`, each needing a per-language espeak-ng dictionary generated on the build machine. One bundle of four networks now covers 31 languages and 10 voices; the `:library:downloadservice` and DataStore dependencies went with it, along with `scripts/speech/fetch_piper_model.sh`, `generate_piper_dict.py` and `generate_wordlist.py`. Reads stream out of the APK through a file descriptor, which is why `noCompress += "maml"` is load-bearing rather than an optimisation. -So a clean install transcribes with no network, but speaking still needs one voice download.+ Two things about this one are unlike every other model here. **Its licence is use-restricted**: Supertonic 3 is **OpenRAIL**, the first such licence in this tree - everything else is Apache-2.0, MIT, ODbL or InsightFace's non-commercial research terms. And because it is bundled rather than downloaded, the restriction ships in the APK rather than being fetched by a user who went looking for it. It is a **build-host** dependency for refreshing (`scripts/ml/supertonic_fold.py`, `supertonic_bundle.py`) and no runtime dependency at all.++ The language coverage is a deliberate regression as well as a gain: 42 languages became 31. TTS was **lost** for Chinese, Hebrew, Thai, Bengali, Telugu, Malayalam, Marathi, Urdu, Serbian, Norwegian, Catalan, Georgian, Kurdish, Luxembourgish, Nepali and Swahili, and **gained** for Estonian, Croatian, Lithuanian, Latvian and Slovenian. The dropped languages are absent from the engine's advertised voice list, so a user is never offered one that would be silent.++So a clean install both transcribes and speaks with no network at all. `photos` **semantic search no longer needs a second app**. It previously delegated image/text embedding to the OpenAssistant app over IPC, so search only worked if OpenAssistant was installed, recent enough, and had finished a ~452 MB SigLIP2 download. It now runs **TinyCLIP-ViT-8M/16 Text-3M** int8 in-process from `photos/src/main/assets/clip/model_int8.onnx` (24 MB), with the CLIP BPE table in `clip/bpe_simple_vocab_16e6.txt`. Upstream is **`onnx-community/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M-ONNX`** (MIT, an ONNX export of `wkcn/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M`) — a **build-host** dependency only. The int8 export costs almost nothing in fidelity (measured cosine vs fp32: 0.998 image, 0.9995 text, same latency), because TinyCLIP is a plain ViT and quantizes cleanly. The trade-off accepted here is accuracy in absolute terms: TinyCLIP-8M scores 41.1% zero-shot ImageNet-1k against SigLIP2-base's high-70s, so single-concept queries are noticeably weaker than the IPC path it replaces.
library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.ktindex cd81f91864..5ddd5560ba 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt@@ -80,56 +80,13 @@ internal object MlNative { width: Int, height: Int, ): String?- /**- * Bring up Piper (VITS) from its four `.maml` files plus a phoneme dictionary. Returns 0- * on failure.- *- * Five assets because the model is four networks and a lookup table: the text encoder,- * the normalising flow and the HiFi-GAN vocoder run on the GPU, and the stochastic- * duration predictor runs on the CPU because it is a bin search and a quadratic solve per- * phoneme. [dictionary] is the voice's `<lang>-word_id.bin`, built from espeak-ng on the- * build machine so nothing on-device needs it.- *- * [phonemesWide] and [frames] fix the two compiled shapes: a plan records its command- * buffer once, so the encoder is built for the longest utterance a request may hold and- * the flow and vocoder for one chunk. The three scales come from the voice's- * `config.json`.- *- * Freed by [destroyPiper], not [destroy] or [destroyOcr].- */- external fun createPiper(- encoder: ByteArray,- flow: ByteArray,- vocoder: ByteArray,- durations: ByteArray,- dictionary: ByteArray,- phonemesWide: Int,- frames: Int,- sampleRate: Int,- noise: Float,- length: Float,- durationNoise: Float,- ): Long- /**- * Synthesise [text] and return mono samples in `-1..1`, or null on failure.- *- * One call per utterance: the phoneme lookup, the encoder, the duration predictor, the- * alignment, the flow and the chunked vocoder all happen natively.- *- * [speed] above one is faster. An empty array means nothing pronounceable, which is not a- * failure - a string of emoji should say nothing.- *- * Two calls with the same text differ. VITS samples both its durations and its prior, and- * that is what stops it sounding mechanical.- */- external fun synthesize(handle: Long, text: String, speed: Float): FloatArray? /** * Bring up Supertonic 3 from its four `.maml` files, the codepoint table and one voice. * Returns 0 on failure. *- * No shape arguments: unlike [createPiper], every Supertonic plan is utterance-shaped, so each- * net is re-recorded per sentence rather than compiled once at a padded width. There is also no+ * No shape arguments: every Supertonic plan is utterance-shaped, so each net is re-recorded per+ * sentence rather than compiled once at a padded width. There is also no phoneme dictionary - * phoneme dictionary - the front end is [indexer], a flat 65,536-entry codepoint table, which is * why [synthesizeSupertonic] insists on NFD. *@@ -151,7 +108,7 @@ internal object MlNative { * [indexer] and [style] stay byte arrays: 128 KB and 25 KB, where streaming saves nothing. * [style] is separate from the plans and swappable through [setSupertonicVoice]. *- * Freed by [destroySupertonic], not [destroy], [destroyOcr] or [destroyPiper].+ * Freed by [destroySupertonic], not [destroy] or [destroyOcr]. */ external fun createSupertonic( fds: IntArray,@@ -232,21 +189,13 @@ internal object MlNative { * guesses. */ external fun destroyOcr(handle: Long)- /**- * Free Piper's three networks, its duration weights and its dictionary. Exactly once per- * non-zero handle from [createPiper].- *- * A third destroy function rather than one that guesses: the three handle types own- * different things, and passing one to the wrong destroy is undefined.- */- external fun destroyPiper(handle: Long) /** * Free Supertonic's four networks, its conditioning, its codepoint table and its voice. * Exactly once per non-zero handle from [createSupertonic]. *- * A fourth destroy function, for the same reason there is a third: the handle types own- * different things and passing one to the wrong destroy is undefined.+ * A third destroy function rather than one that guesses: the handle types own different things+ * and passing one to the wrong destroy is undefined. */ external fun destroySupertonic(handle: Long) }
library/ml/src/main/java/com/vayunmathur/library/ml/PiperSynthesizer.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/PiperSynthesizer.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/PiperSynthesizer.ktdeleted file mode 100644index 2984b85de6..0000000000--- a/library/ml/src/main/java/com/vayunmathur/library/ml/PiperSynthesizer.kt+++ /dev/null@@ -1,162 +0,0 @@-package com.vayunmathur.library.ml--import android.util.Log-import java.io.File--/**- * A Piper voice's inference settings, from its `config.json`.- *- * [noise] and [durationNoise] are what make two readings of the same sentence differ; VITS- * samples both its prior and its durations. [length] is the speaking rate, above one being- * slower - note that [PiperSynthesizer.synthesize]'s `speed` is the other way round, because- * a caller asking to go faster should pass a number above one.- */-data class PiperConfig(- val sampleRate: Int,- val noise: Float = 0.667f,- val length: Float = 1.0f,- val durationNoise: Float = 0.8f,-)--/**- * On-device text-to-speech: Piper (VITS) on the Vulkan compute runtime.- *- * Replaces the ncnn `Vits` path. The model is four parts, and where each runs is a- * deliberate choice rather than a convenience:- *- * - **Text encoder**, **normalising flow** and **HiFi-GAN vocoder** are compiled plans on the- * GPU. Together they are 15 million parameters and effectively all of the arithmetic.- * - **Stochastic duration predictor** runs on the **CPU**. It is 4% of the parameters and- * produces one number per phoneme, but its work is a ten-bin search and a quadratic solve- * per position - data-dependent branching, which is what a GPU is worst at.- *- * All four were checked numerically against onnxruntime; see- * `library/ml/src/main/rust/src/nets/vits_*.rs`.- *- * # Phonemes- *- * espeak-ng is **not** on the device and never was. `scripts/speech/generate_piper_dict.py`- * runs it on the build machine to turn a word list into a `<lang>-word_id.bin` lookup table,- * and that table ships with the voice. A word the table lacks is spelled out letter by letter.- *- * # Availability- *- * The constructor never throws. [isAvailable] is false when `libmodelrunner.so` is missing for- * this ABI, when a file is absent, or when the device cannot give us a Vulkan device with fp16- * compute - and then [synthesize] returns an empty array.- *- * # Threading- *- * Not thread-safe. A caller must hold a lock across [synthesize] and [close]: the handle is- * freed by [close] and reading it afterwards is a use-after-free.- */-class PiperSynthesizer(- directory: File,- voice: String,- config: PiperConfig,- private val maxPhonemes: Int = DEFAULT_MAX_PHONEMES,- chunkFrames: Int = DEFAULT_CHUNK_FRAMES,-) : AutoCloseable {- private var handle: Long = 0L-- /** The voice's output rate, so a caller cannot play it at the wrong pitch. */- val sampleRate: Int = config.sampleRate-- init {- handle = if (!MlNative.isAvailable) {- 0L- } else {- try {- val encoder = read(directory, "${voice}_enc_p.maml")- val flow = read(directory, "${voice}_flow.maml")- val vocoder = read(directory, "${voice}_dec.maml")- val durations = read(directory, "${voice}_dp.maml")- val dictionary = dictionaryOf(directory)- MlNative.createPiper(- encoder,- flow,- vocoder,- durations,- dictionary,- maxPhonemes,- chunkFrames,- config.sampleRate,- config.noise,- config.length,- config.durationNoise,- )- } catch (e: Throwable) {- Log.e(TAG, "cannot open the Piper voice in $directory", e)- 0L- }- }- }-- /** True if all four networks came up and the dictionary parsed. */- val isAvailable: Boolean get() = handle != 0L-- /**- * Synthesise [text] at [speed], where above one is faster.- *- * Returns an empty array when there is nothing pronounceable, when the engine is- * unavailable, or when the pass failed - all three are "no audio" to a caller, and the- * reason is in logcat under `ModelRunner`.- *- * Long text should be split into sentences first: the encoder is compiled for- * [maxPhonemes] and a longer utterance is refused rather than truncated, because- * truncating would silently drop the end of a paragraph.- */- fun synthesize(text: String, speed: Float = 1.0f): FloatArray {- if (handle == 0L || text.isBlank()) return FloatArray(0)- return MlNative.synthesize(handle, text, speed) ?: FloatArray(0)- }-- /** Free all four networks. Idempotent. */- override fun close() {- val live = handle- handle = 0L- if (live != 0L) MlNative.destroyPiper(live)- }-- private companion object {- private const val TAG = "PiperSynthesizer"-- /**- * Phonemes the encoder is compiled for.- *- * Attention is quadratic in this, but the arena at 400 phonemes measured 2.10 MiB, so- * the ceiling is set by how long a sentence a caller may pass rather than by memory.- * 400 phonemes is a long sentence; a paragraph should be split.- */- const val DEFAULT_MAX_PHONEMES = 400-- /**- * Latent frames per vocoder pass, matching `post::speech::CHUNK_FRAMES`.- *- * The vocoder's arena grows linearly with the utterance - 7.37 MiB per second of audio- * - so it runs in chunks. The overlap is exact rather than approximate: the network is- * convolutional with a bounded receptive field, so every kept sample is identical to- * what a whole-utterance pass would have produced.- */- const val DEFAULT_CHUNK_FRAMES = 128-- fun read(directory: File, name: String): ByteArray {- val file = File(directory, name)- require(file.isFile) { "$name is missing from $directory" }- return file.readBytes()- }-- /**- * The voice's `*-word_id.bin`, whatever language it is for.- *- * Matched by suffix rather than by name: a voice bundle carries its own language's- * dictionary, and older bundles also carry the English one for compatibility. Either- * works, so the first match wins.- */- fun dictionaryOf(directory: File): ByteArray {- val found = directory.listFiles()?.firstOrNull { it.name.endsWith("-word_id.bin") }- requireNotNull(found) { "no *-word_id.bin in $directory" }- return found.readBytes()- }- }-}
library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.ktindex 0b205bfb43..c5426118f5 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.kt@@ -10,9 +10,9 @@ import java.text.Normalizer /** * On-device text-to-speech: Supertonic 3 on the Vulkan compute runtime. *- * Replaces [PiperSynthesizer]. One bundle covers 30 languages and 10 voices, where Piper needed a- * separate model and phoneme dictionary per language. Four networks, all on the GPU and all checked- * numerically against onnxruntime — see `library/ml/src/main/rust/src/nets/supertonic_*.rs`:+ * One bundle covers 31 languages and 10 voices, and every one of the four networks runs on the GPU.+ * All four are checked numerically against onnxruntime — see+ * `library/ml/src/main/rust/src/nets/supertonic_*.rs`: * * - **Duration predictor** returns one number, the utterance's length in seconds, which fixes * every later shape.@@ -44,7 +44,7 @@ import java.text.Normalizer * # Voices * * A voice is two small style tensors, not a model, so [voice] switches without re-uploading- * anything. That is why a voice change is a method here and was a new object in Piper.+ * anything: all ten come to ~250 KB together. * * # Availability *
library/ml/src/main/rust/shaders/attn_apply_relative.comp
diff --git a/library/ml/src/main/rust/shaders/attn_apply_relative.comp b/library/ml/src/main/rust/shaders/attn_apply_relative.compindex b44e3f9769..caa4673ea3 100644--- a/library/ml/src/main/rust/shaders/attn_apply_relative.comp+++ b/library/ml/src/main/rust/shaders/attn_apply_relative.comp@@ -1,5 +1,5 @@ #version 450-//! Attention's weighted sum with VITS's relative-position term, in one pass.+//! Attention's weighted sum with a relative-position term, in one pass. //! //! `out[h][d][i] = sum_j P[h][i][j] * V[h][d][j] + sum_o P[h][i][i+o] * emb[o + window][d]` //!
library/ml/src/main/rust/shaders/attn_scores_relative.comp
diff --git a/library/ml/src/main/rust/shaders/attn_scores_relative.comp b/library/ml/src/main/rust/shaders/attn_scores_relative.compindex f66ba43615..0f19fdf86c 100644--- a/library/ml/src/main/rust/shaders/attn_scores_relative.comp+++ b/library/ml/src/main/rust/shaders/attn_scores_relative.comp@@ -1,11 +1,11 @@ #version 450-//! Attention scores with VITS's relative-position term, in one pass.+//! Attention scores with a relative-position term, in one pass. //! //! `scores[h][i][j] = scale * (Q[h,.,i] . K[h,.,j] + Q[h,.,i] . emb[j - i + window])` //! //! # Why the relative term is nine taps and not a skew //!-//! VITS learns a table of `2 * window + 1` offsets per attention layer and adds+//! The export learns a table of `2 * window + 1` offsets per attention layer and adds //! `Q . emb[j - i]` to every score. Its ONNX export computes that as a full //! `[heads, T, 2T-1]` product and then *skews* it into `[heads, T, T]` with a pad, a reshape //! and a slice — 48 `Pad`s, 96 `Reshape`s and 42 `Slice`s across the encoder, none of which@@ -20,7 +20,7 @@ //! # Layout //! //! `p.weight` points at the table as `[2 * window + 1, head_dim]`, shared across heads —-//! which is VITS's `heads_share` default, and was verified by reconstructing both heads from+//! which is the export's `heads_share` default, and was verified by reconstructing both heads from //! the one table. `p.kw` is the number of offsets, so the window is `(p.kw - 1) / 2`; a //! nine-wide kernel over the sequence is exactly what this is. //!
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 6dc952b520..e014a55774 100644--- a/library/ml/src/main/rust/shaders/common.glsl+++ b/library/ml/src/main/rust/shaders/common.glsl@@ -92,7 +92,6 @@ layout(push_constant) uniform Push { #define ACT_PRELU 4u #define ACT_CLIP01 5u #define ACT_SWISH 6u-#define ACT_TANH 7u #define ACT_GELU 8u // This invocation's output element, across a 2D grid of workgroups.@@ -176,12 +175,6 @@ float activate(float x, uint kind, uint channel) { float erf = sign * (1.0 - poly * exp(-a * a)); return 0.5 * x * (1.0 + erf); }- 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/embed.comp
diff --git a/library/ml/src/main/rust/shaders/embed.comp b/library/ml/src/main/rust/shaders/embed.compindex 5d523d758f..fcb88e9b86 100644--- a/library/ml/src/main/rust/shaders/embed.comp+++ b/library/ml/src/main/rust/shaders/embed.comp@@ -1,7 +1,7 @@ #version 450 //! An embedding lookup: `out[c][t] = table[id(t)][c]`. //!-//! VITS's text encoder starts by looking up one row of a `[symbols, d_model]` table per+//! A text encoder starts by looking up one row of a `[symbols, d_model]` table per //! phoneme. That is the only op in this runtime whose *addresses* depend on the data rather //! than on the plan. //!@@ -23,7 +23,7 @@ //! //! # The scale is in the table //!-//! VITS multiplies the embedding by `sqrt(d_model)`. The converter folds that into the table+//! An export that multiplies the embedding by `sqrt(d_model)` has that folded into the table //! itself, which is both one op fewer and one rounding fewer — `round(table * sqrt(d))` is //! closer than `round(table) * sqrt(d)`.
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.compdeleted file mode 100644index 687a78d508..0000000000--- a/library/ml/src/main/rust/shaders/flip_channels.comp+++ /dev/null@@ -1,33 +0,0 @@-#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.compdeleted file mode 100644index b1d4de4f7e..0000000000--- a/library/ml/src/main/rust/shaders/gated_tanh.comp+++ /dev/null@@ -1,32 +0,0 @@-#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/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.compdeleted file mode 100644index 7d78c52728..0000000000--- a/library/ml/src/main/rust/shaders/leaky_relu.comp+++ /dev/null@@ -1,39 +0,0 @@-#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/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsindex 0dea3a8513..21ba335609 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -30,17 +30,17 @@ use std::fs::File; use std::os::fd::FromRawFd; use jni::objects::{JByteArray, JClass, JFloatArray, JIntArray, JLongArray, JString};-use jni::sys::{jfloat, jfloatArray, jint, jlong, jstring};+use jni::sys::{jfloatArray, jint, jlong, jstring}; use jni::JNIEnv; use crate::nets::{ mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration, supertonic_sampler,- supertonic_text, supertonic_vocoder, u2netp, vits_dec, vits_enc, vits_flow, Plan,+ supertonic_text, supertonic_vocoder, u2netp, Plan, }; use crate::post::ctc::Dictionary; use crate::post::nms::{self, Face, Maps}; use crate::post::ocr::{self, Line};-use crate::post::{phonemes, speech, supertonic};+use crate::post::supertonic; use crate::preprocess::{ Letterbox, FACE_EMBED, IMAGENET, PPOCR_DET, PPOCR_REC, RESCALE_ONLY, SCRFD, };@@ -518,29 +518,11 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyOc drop(unsafe { Box::from_raw(handle as *mut OcrHandle) }); } -/// Piper's three networks, its duration weights, its dictionary and its scales.-///-/// A fourth handle type, and separately destroyed, for the same reason [`OcrHandle`] is: it-/// owns a different set of things, and one `destroy` guessing between them would be type-/// confusion waiting for a caller to mix them up.-struct SpeechHandle {- encoder: Net,- flow: Net,- vocoder: Net,- /// Read on the host: the duration predictor is a loop, not a plan.- durations: Weights,- dictionary: phonemes::Dictionary,- scales: speech::Scales,- sample_rate: u32,- /// Filled per request so a long utterance does not reallocate every chunk.- rng: SplitMix,-}- /// A small deterministic-per-seed generator, seeded from the clock per utterance. ///-/// Speech is *meant* to vary: VITS samples its durations and its prior, so two readings of-/// the same sentence differ. That is the model's design, not a defect. SplitMix64 is used-/// rather than a cryptographic source because nothing here is a secret and the sequence only+/// Speech is *meant* to vary: Supertonic's flow matching starts from a sampled latent, so two+/// readings of the same sentence differ. That is the model's design, not a defect. SplitMix64 is+/// used rather than a cryptographic source because nothing here is a secret and the sequence only /// has to be well-distributed. struct SplitMix { state: u64,@@ -556,10 +538,6 @@ impl SplitMix { } /// Box-Muller over two uniforms, which is exact rather than an approximation of normal.- ///- /// Inherent rather than only a [`speech::Noise`] method because Supertonic needs the same- /// generator and does not go through that trait — its flow matching samples one starting- /// latent per utterance, where VITS samples a prior and its durations. fn normal(&mut self, count: usize) -> Vec<f32> { let mut out = Vec::with_capacity(count); while out.len() < count {@@ -577,37 +555,6 @@ impl SplitMix { } } -impl speech::Noise for SplitMix {- fn normal(&mut self, count: usize) -> Vec<f32> {- SplitMix::normal(self, count)- }-}--/// The three plans, as `post::speech` wants them.-struct SpeechNets<'a> {- encoder: &'a mut Net,- flow: &'a mut Net,- vocoder: &'a mut Net,-}--impl speech::Networks for SpeechNets<'_> {- fn encode(&mut self, ids: &[f32]) -> Result<(Vec<f32>, Vec<f32>), String> {- let outputs = self.encoder.infer_raw(ids)?;- match <[Vec<f32>; 2]>::try_from(outputs) {- Ok([stats, hidden]) => Ok((stats, hidden)),- Err(other) => Err(format!("the encoder returned {} outputs, not two", other.len())),- }- }-- fn flow(&mut self, prior: &[f32], _frames: usize) -> Result<Vec<f32>, String> {- one_output(self.flow.infer_raw(prior)?)- }-- fn vocode(&mut self, latent: &[f32], _frames: usize) -> Result<Vec<f32>, String> {- one_output(self.vocoder.infer_raw(latent)?)- }-}- /// The single output of a plan that has exactly one. fn one_output(outputs: Vec<Vec<f32>>) -> Result<Vec<f32>, String> { match <[Vec<f32>; 1]>::try_from(outputs) {@@ -616,93 +563,7 @@ fn one_output(outputs: Vec<Vec<f32>>) -> Result<Vec<f32>, String> { } } -/// `PiperSynthesizer`'s constructor. Returns 0 on failure, having logged why.-///-/// Five assets: the three `.maml` plans, the duration predictor's weights, and the voice's-/// grapheme-to-phoneme dictionary. The three scales come from the voice's `config.json`,-/// which the Kotlin side has already parsed.-///-/// # Safety-///-/// Called only by the JVM, with a valid `env` and arrays it owns.-#[no_mangle]-#[allow(clippy::too_many_arguments)]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createPiper<'l>(- mut env: JNIEnv<'l>,- _class: JClass<'l>,- encoder: JByteArray<'l>,- flow: JByteArray<'l>,- vocoder: JByteArray<'l>,- durations: JByteArray<'l>,- dictionary: JByteArray<'l>,- phonemes_wide: jint,- frames: jint,- sample_rate: jint,- noise: jfloat,- length: jfloat,- duration_noise: jfloat,-) -> jlong {- let assets = [encoder, flow, vocoder, durations, dictionary];- let shapes = (phonemes_wide, frames, sample_rate);- let scales = speech::Scales {- noise,- length,- duration_noise,- };- match build_piper(&mut env, assets, shapes, scales) {- Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,- Err(e) => {- log(&format!("piper is unavailable: {e}"));- 0- }- }-}--fn build_piper<'l>(- env: &mut JNIEnv<'l>,- assets: [JByteArray<'l>; 5],- shapes: (jint, jint, jint),- scales: speech::Scales,-) -> Result<SpeechHandle, String> {- let (phonemes_wide, frames, sample_rate) = shapes;- if phonemes_wide <= 0 || frames <= 0 || sample_rate <= 0 {- return Err(format!("a voice at {phonemes_wide} phonemes, {frames} frames"));- }- let mut bytes = Vec::with_capacity(assets.len());- for asset in &assets {- bytes.push(- env.convert_byte_array(asset)- .map_err(|e| format!("cannot read an asset: {e}"))?,- );- }- let dictionary = phonemes::Dictionary::parse(&bytes[4])?;- let encoder_weights = Weights::parse(&bytes[0], graph::VITS_ENC)?;- let flow_weights = Weights::parse(&bytes[1], graph::VITS_FLOW)?;- let vocoder_weights = Weights::parse(&bytes[2], graph::VITS_DEC)?;- let durations = Weights::parse(&bytes[3], graph::VITS_DP)?;-- let shared = context::shared()?;- // Each plan is one fixed shape. The encoder is compiled at the longest phoneme count a- // request may hold and the flow and vocoder at the chunk size, so nothing is recompiled- // per utterance — see `post::speech` for why the vocoder is chunked at all.- let encoder_plan = vits_enc::build(&encoder_weights, phonemes_wide as u32)?;- let context_frames = speech::RECEPTIVE_FRAMES as u32 * 2;- let flow_plan = vits_flow::build(&flow_weights, frames as u32)?;- let vocoder_plan = vits_dec::build(&vocoder_weights, frames as u32 + context_frames)?;-- Ok(SpeechHandle {- encoder: Net::new(shared.clone(), encoder_plan, &encoder_weights, RESCALE_ONLY)?,- flow: Net::new(shared.clone(), flow_plan, &flow_weights, RESCALE_ONLY)?,- vocoder: Net::new(shared, vocoder_plan, &vocoder_weights, RESCALE_ONLY)?,- durations,- dictionary,- scales,- sample_rate: sample_rate as u32,- rng: SplitMix { state: seed() },- })-}--/// A seed from the clock, so two readings of a sentence differ as VITS intends.+/// A seed from the clock, so two readings of a sentence differ as the model intends. fn seed() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH)@@ -711,155 +572,13 @@ fn seed() -> u64 { | 1 } -/// Free the three networks and everything beside them.-///-/// # Safety-///-/// `handle` must be `0` or a value from-/// [`Java_com_vayunmathur_library_ml_MlNative_createPiper`], and must not be used again.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyPiper<'l>(- _env: JNIEnv<'l>,- _class: JClass<'l>,- handle: jlong,-) {- if handle == 0 {- return;- }- // SAFETY: the caller guarantees this came from `createPiper` and has not been destroyed.- drop(unsafe { Box::from_raw(handle as *mut SpeechHandle) });-}--/// Synthesise `text` and return the waveform, or null on failure.-///-/// One call per utterance: the phoneme lookup, the encoder, the duration predictor, the-/// alignment, the flow and the chunked vocoder all happen here, so the boundary is crossed-/// once rather than once per stage. An empty result means nothing pronounceable, which is not-/// a failure — a string of emoji should say nothing.-///-/// The samples are mono `-1..1` at the voice's rate. Two calls with the same text differ:-/// VITS samples both its durations and its prior, which is what stops it sounding-/// mechanical.-///-/// # Safety-///-/// `handle` must be `0` or a live value from-/// [`Java_com_vayunmathur_library_ml_MlNative_createPiper`].-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_synthesize<'l>(- mut env: JNIEnv<'l>,- _class: JClass<'l>,- handle: jlong,- text: JString<'l>,- speed: jfloat,-) -> jfloatArray {- let null = std::ptr::null_mut();- if handle == 0 {- return null;- }- // SAFETY: as `segment` — the caller guarantees the handle is live and serialises this- // against `destroyPiper`.- let state = unsafe { &mut *(handle as *mut SpeechHandle) };- let words: String = match env.get_string(&text) {- Ok(found) => found.into(),- Err(e) => {- log(&format!("cannot read the text: {e}"));- return null;- }- };- match speak(state, &words, speed) {- Ok(samples) => match new_float_array(&mut env, &samples) {- Ok(array) => array,- Err(e) => {- log(&e);- null- }- },- Err(e) => {- log(&format!("synthesis failed: {e}"));- null- }- }-}--/// The whole pipeline for one utterance.-fn speak(state: &mut SpeechHandle, text: &str, speed: jfloat) -> Result<Vec<f32>, String> {- let ids = phonemes::to_ids(text, &state.dictionary);- // `[BOS, EOS]` is nothing to say.- if ids.len() <= 2 {- return Ok(Vec::new());- }- let wide = state.encoder.input_shape()?.w as usize;- if ids.len() > wide {- return Err(format!(- "{} phonemes exceeds the {wide} this voice was compiled for; the caller should \- split the text into sentences",- ids.len()- ));- }- // The plan is one fixed width, so a short utterance is padded. The pad id is `PAD`, which- // is a phoneme the model knows rather than an out-of-range index.- let mut widened = vec![f32::from(phonemes::PAD); wide];- for (slot, &id) in widened.iter_mut().zip(&ids) {- *slot = f32::from(id);- }-- let outputs = state.encoder.infer_raw(&widened)?;- let [stats, hidden] = <[Vec<f32>; 2]>::try_from(outputs)- .map_err(|other| format!("the encoder returned {} outputs, not two", other.len()))?;-- // Only the real phonemes take part; the padding's statistics are discarded.- let phoneme_count = ids.len();- let trimmed_hidden = trim(&hidden, vits_enc::D_MODEL as usize, wide, phoneme_count);- let trimmed_stats = trim(&stats, vits_enc::STATS as usize, wide, phoneme_count);-- let noise = {- let rng = &mut state.rng;- speech::Noise::normal(rng, 2 * phoneme_count)- };- let scaled: Vec<f32> =- noise.iter().map(|&n| n * state.scales.duration_noise).collect();- let log_durations = crate::post::duration::log_durations(- &state.durations,- &trimmed_hidden,- phoneme_count,- &scaled,- )?;- // `speed` above one should sound faster, and `length_scale` above one is slower, so the- // caller's rate divides rather than multiplies.- let rate = if speed > 0.0 { state.scales.length / speed } else { state.scales.length };- let frames = crate::post::duration::frames(&log_durations, rate);-- let request = speech::Request {- ids: &ids,- scales: &state.scales,- sample_rate: state.sample_rate,- };- let SpeechHandle { encoder, flow, vocoder, rng, .. } = state;- let mut nets = SpeechNets { encoder, flow, vocoder };- let spoken = speech::synthesise(&request, &frames, &trimmed_stats, &mut nets, rng)?;- Ok(spoken.samples)-}--/// Keep the first `keep` positions of a `[channels, wide]` plane.-fn trim(values: &[f32], channels: usize, wide: usize, keep: usize) -> Vec<f32> {- let mut out = Vec::with_capacity(channels * keep);- for channel in 0..channels {- let from = channel * wide;- out.extend_from_slice(&values[from..from + keep]);- }- out-}- /// Supertonic's four nets, the conditioning read once, and the voice bundle. ///-/// Its own handle type for the same reason [`OcrHandle`] and [`SpeechHandle`] are: it owns a-/// different set of things, and one `destroy` guessing between them would be type confusion-/// waiting for a caller to mix them up.+/// Its own handle type for the same reason [`OcrHandle`] is: it owns a different set of things, and+/// one `destroy` guessing between them would be type confusion waiting for a caller to mix them up. /// /// Each net is a [`Reshaped`] rather than a [`Net`], because every Supertonic plan is-/// utterance-shaped and there is no width to compile once and pad to — unlike Piper, whose-/// encoder is built at the longest phoneme count a voice allows.+/// utterance-shaped and there is no width to compile once and pad to. struct SupertonicHandle { duration: Reshaped<u32>, text: Reshaped<u32>,
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 d04a1fb4c2..3ace3e1a51 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -41,9 +41,6 @@ pub mod supertonic_sampler; pub mod supertonic_text; pub mod supertonic_vocoder; 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)]@@ -117,16 +114,10 @@ pub enum Act { /// 4.7e-4 (at `x = 2.699`), and fp16's step there is 2.0e-3, so the difference is four /// times finer than the arena can represent. `erf` is used anyway for two reasons that are /// about agreement rather than accuracy — it is what the export computes, and- /// [`crate::nets::erf`] implements the same Abramowitz and Stegun 7.1.26 series for the host+ /// `nets::erf` implements the same Abramowitz and Stegun 7.1.26 series for the host /// interpreter, so the reference and the shader are the same function by construction rather /// than by coincidence. The cost is comparable either way. Gelu,- /// `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 {@@ -139,7 +130,6 @@ impl Act { Act::PRelu(_) => 4, Act::Clip01 => 5, Act::Swish => 6,- Act::Tanh => 7, Act::Gelu => 8, } }@@ -254,20 +244,16 @@ pub enum Kind { /// 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,- /// [`Kind::AttnScores`] plus VITS's relative-position term, which is nine taps rather- /// than the `[heads, T, 2T-1]` product and skew its export spells out. Table at- /// [`Push::weight`] as `[2 * window + 1, head_dim]`, offset count in [`Push::kw`].+ /// [`Kind::AttnScores`] plus a relative-position term, which is nine taps rather than the+ /// `[heads, T, 2T-1]` product and skew the export spells out. Table at [`Push::weight`] as+ /// `[2 * window + 1, head_dim]`, offset count in [`Push::kw`].+ ///+ /// Both of Supertonic's encoders use it: `supertonic_text` has four such layers and+ /// `supertonic_duration` two, all at `window_size` 4, so `OFFSETS` is 9 in each. AttnScoresRelative, /// [`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, /// A `1 x 1` convolution as a tiled matrix multiply, staging weights through shared memory. /// /// [`Kind::Conv`] reads each output element''s weights from global memory with no reuse, which@@ -298,9 +284,9 @@ pub enum Kind { /// `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- /// tensor, which is exact for the 130 phoneme symbols VITS uses — fp16 holds every- /// integer to 2048. Table at [`Push::weight`], its row count in [`Push::in_w`], and an- /// out-of-range id clamps rather than reading past the table.+ /// tensor, which is exact for a small vocabulary — fp16 holds every integer to 2048. Table at+ /// [`Push::weight`], its row count in [`Push::in_w`], and an out-of-range id clamps rather+ /// than reading past the table. /// /// # Vocabularies past 2048 ///@@ -309,21 +295,6 @@ pub enum Kind { /// SMaLL-100 has 128,112. Those arrive **split across two lanes**, `id = lo + 2048 * hi`, /// as a `[2, 1, T]` tensor; [`Push::in_c`] carries the lane count. See [`embed_lanes`]. Embed,- /// `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, /// `out[i] = weights[i]`, a learned tensor copied into the arena. /// /// The only op that produces a tensor from nothing but the weights file. It exists because@@ -465,8 +436,8 @@ pub struct Plan { /// Where the preprocessed inputs go, in the order they were declared. /// /// A `Vec` rather than one binding because the models this runtime is growing into- /// are not single-input: VITS's duration predictor takes three tensors and the- /// SMaLL-100 decoder four. Both shipping nets declare exactly one.+ /// are not single-input: Supertonic's sampler takes seven tensors and the SMaLL-100+ /// decoder four. Every vision net declares exactly one. pub inputs: Vec<Binding>, /// Where the results come back from, in the order [`Builder::finish`] was given. ///@@ -628,11 +599,6 @@ enum Node { input: Id, out: Id, },- LeakyRelu {- input: Id,- out: Id,- alpha: f32,- }, Constant { out: Id, weight: u32,@@ -649,14 +615,6 @@ enum Node { table: u32, rows: u32, },- GatedTanh {- input: Id,- out: Id,- },- FlipChannels {- input: Id,- out: Id,- }, SliceChannels { input: Id, out: Id,@@ -734,9 +692,13 @@ const CONV_POINT_TILE: u32 = 16; /// approximating the *activation* would be a different function. This approximates `erf` itself /// instead, well below fp16's resolution. ///-/// It lives beside `Act` rather than in `nets::reference` because that module is `#[cfg(test)]`,-/// and it began in `post::duration` for VITS's separable stacks — which is why it is here and not-/// there: `post::duration` goes when Piper does, and `Act::Gelu` does not.+/// Test-only now. It began in `post::duration` for VITS's separable stacks and was moved here so+/// that deleting Piper would not take it with it; with Piper gone its only remaining caller is+/// `nets::reference`, which is `#[cfg(test)]`. It stays beside [`Act::Gelu`] rather than moving+/// into that module because the two have to agree with `activate` in `common.glsl`, which is where+/// the *shipped* GELU is computed — the series here and the one there are the same coefficients,+/// and keeping them one scroll apart is what makes that checkable.+#[cfg(test)] pub(crate) fn erf(x: f32) -> f32 { const A: [f32; 5] = [0.254_829_6, -0.284_496_74, 1.421_413_7, -1.453_152, 1.061_405_4]; const P: f32 = 0.327_591_1;@@ -1277,29 +1239,6 @@ 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@@ -1387,8 +1326,8 @@ impl<'a> Builder<'a> { /// An embedding lookup: `out[c][t] = table[id(t)][c]`, over a `[1, 1, T]` id tensor, or a /// `[2, 1, T]` one when the table has more than [`EMBED_LANE`] rows. ///- /// `table` indexes a `[rows, channels]` tensor. The `sqrt(d_model)` scale VITS applies- /// after the lookup belongs in the table, not here; see [`Kind::Embed`].+ /// `table` indexes a `[rows, channels]` tensor. A `sqrt(d_model)` scale applied after the+ /// lookup belongs in the table, folded by the converter, not here; see [`Kind::Embed`]. pub fn embed(&mut self, ids: Id, table: usize, rows: u32, channels: u32) -> Id { let shape = self.shape_of(ids); let lanes = if rows > EMBED_LANE { 2 } else { 1 };@@ -1416,16 +1355,7 @@ 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- }-- /// [`Builder::attn_scores`] plus VITS's relative-position term.+ /// [`Builder::attn_scores`] plus a relative-position term. /// /// `table` is a `[offsets, head_dim]` tensor of learned offsets, shared across heads. /// `offsets` must be odd: it is `2 * window + 1`, centred on zero displacement.@@ -2018,38 +1948,6 @@ 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.@@ -2164,26 +2062,6 @@ 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(()) }@@ -2204,10 +2082,7 @@ impl Node { | Node::AttnScoresRelative { out, .. } | Node::AttnApplyRelative { out, .. } | Node::Softmax { out, .. }- | Node::LeakyRelu { out, .. } | Node::Embed { out, .. }- | Node::GatedTanh { out, .. }- | Node::FlipChannels { out, .. } | Node::SliceChannels { out, .. } | Node::ConvInt8 { out, .. } | Node::AttnApply { out, .. }@@ -2226,10 +2101,7 @@ impl Node { | Node::Affine { input, .. } | Node::LayerNorm { input, .. } | Node::Softmax { input, .. }- | Node::LeakyRelu { input, .. } | Node::Embed { ids: input, .. }- | Node::GatedTanh { input, .. }- | Node::FlipChannels { input, .. } | Node::SliceChannels { input, .. } | Node::ConvInt8 { input, .. } | Node::GlobalAvgPool { input, .. } => vec![*input],@@ -2451,8 +2323,6 @@ pub(crate) mod tests { Kind::ConvInt8 => vec![(push.in0, dense)], // count is tiles here, so the read span is the input plane. Kind::ConvPoint | Kind::ConvPointInt8 => vec![(push.in0, dense)],- // 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 52a9c4b0a8..adf52244ea 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -59,8 +59,6 @@ mod act { pub const CLIP01: u32 = 5; /// `x * sigmoid(x)`. pub const SWISH: u32 = 6;- /// `tanh(x)`.- pub const TANH: u32 = 7; /// The exact GELU. See `super::super::Act::Gelu`. pub const GELU: u32 = 8; }@@ -83,7 +81,6 @@ 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(), // The exact GELU, not the tanh approximation: [`super::erf`] is the same A&S 7.1.26 // series the shader uses, so the two agree well inside fp16. act::GELU => 0.5 * x * (1.0 + super::erf(x * std::f32::consts::FRAC_1_SQRT_2)),@@ -202,20 +199,17 @@ 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), Kind::AttnScoresRelative => self.attn_scores_relative(push), Kind::AttnApplyRelative => self.attn_apply_relative(push), Kind::Embed => self.embed(push), Kind::Constant => self.constant(push), Kind::AddBroadcast => self.add_broadcast(push), Kind::Rotary => self.rotary(push),- Kind::GatedTanh => self.gated_tanh(push), Kind::ConvPoint => self.conv_point(push), // The tiled int8 lowering computes exactly what the untiled one does, and // `Builder::emit` fills the geometry fields in for both, so there is one // implementation rather than two that have to be kept agreeing. Kind::ConvInt8 | Kind::ConvPointInt8 => self.conv_int8(push),- Kind::FlipChannels => self.flip_channels(push), }, }; result.map_err(|e| format!("step {step} ({op:?}): {e}"))?;@@ -587,30 +581,6 @@ 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, in one lane /// or in two (`lo + 2048 * hi`) for a table past `EMBED_LANE` rows. fn embed(&mut self, p: &Push) -> Result<(), String> {@@ -682,16 +652,6 @@ 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);@@ -828,7 +788,7 @@ impl Reference { Ok(()) } - /// [`Self::attn_scores`] plus VITS's relative-position term: nine taps of a learned+ /// [`Self::attn_scores`] plus a relative-position term: nine taps of a learned /// table indexed by `key - query`, in place of the export's product-and-skew. /// /// The scale multiplies both terms, because the export divides the query by@@ -1174,7 +1134,7 @@ fn uniform(state: &mut u32) -> f32 { mod tests { use super::super::{ embed_lanes, mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration, supertonic_sampler,- supertonic_text, supertonic_vocoder, u2netp, vits_dec, vits_enc, vits_flow, Act, Builder, EMBED_LANE,+ supertonic_text, supertonic_vocoder, u2netp, Act, Builder, EMBED_LANE, }; use super::*; @@ -1558,7 +1518,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);+ assert_eq!(Act::Gelu.code(), act::GELU); } #[test]@@ -1633,7 +1593,7 @@ mod tests { #[test] fn a_plan_can_declare_more_than_one_input_and_output() {- // SCRFD needs nine outputs and the VITS duration predictor three inputs, so the+ // SCRFD needs nine outputs and Supertonic's sampler seven inputs, so the // plan's bindings are lists. This checks both ends: two inputs land at distinct // arena offsets, and two outputs come back in the order `finish` was given. let given = Given::new(&[]).expect("no tensors");@@ -1988,64 +1948,6 @@ 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@@ -2503,7 +2405,7 @@ mod tests { fn a_relative_score_map_leaves_the_band_alone_outside_the_window() { // The whole reason this is nine taps and not a `[heads, T, 2T-1]` product and skew: // beyond the window the export's skewed tensor is exactly zero. Verified against- // onnxruntime on Piper's encoder, and pinned here.+ // onnxruntime on a relative-attention encoder, and pinned here. let table: Vec<f32> = vec![7.0, 7.0, 0.0, 0.0, 7.0, 7.0]; let got = two_weighted( (Shape::new(2, 1, 5), Shape::new(2, 1, 5)),@@ -2562,46 +2464,6 @@ mod tests { assert!(error.contains("no centre"), "{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(@@ -2950,59 +2812,6 @@ mod tests { ); return; }- if graph == "vits_dp" {- 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_DP)- .expect("the duration asset parses");- let raw = std::fs::read(dir.join("noise.f32")).expect("the noise");- let noise: Vec<f32> = raw- .chunks_exact(4)- .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))- .collect();- let logw =- crate::post::duration::log_durations(&weights, &input, width as usize, &noise)- .expect("the duration predictor runs");- write(&dir.join("reference.f32"), &logw);- println!("vits_dp at {width} phonemes: wrote {} log-durations", logw.len());- return;- }- 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}"));- 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");- // Two outputs since the duration predictor needed the pre-projection hidden state;- // the probe is the first, the prior''s statistics.- let outputs = run_multi(&plan, weights.data(), &[&input]).expect("the encoder runs");- let stats = outputs.first().expect("the statistics output");- 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}"));- let weights = crate::weights::Weights::parse(&bytes, crate::weights::graph::VITS_DEC)- .expect("the vocoder asset parses");- let plan = vits_dec::build(&weights, width).expect("vits_dec builds");- let audio = run(&plan, weights.data(), &input).expect("the vocoder runs");- write(&dir.join("reference.f32"), &audio);- println!("vits_dec at {width} frames: wrote {} samples", audio.len());- return;- } let (path, id) = match graph.as_str() { "ppocr_rec" => (
library/ml/src/main/rust/src/nets/supertonic_duration.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_duration.rs b/library/ml/src/main/rust/src/nets/supertonic_duration.rsindex a2b5a3b044..2a1d013abd 100644--- a/library/ml/src/main/rust/src/nets/supertonic_duration.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_duration.rs@@ -34,7 +34,7 @@ //! //! **The mask is not needed.** 58 `Mul` nodes multiply by the padding mask, which for one //! utterance is all ones — including the leading one the token's position gets. The same-//! argument as [`super::vits_enc`], and it is why `text_mask` is not an input here.+//! argument as [`super::supertonic_text`], and it is why `text_mask` is not an input here. //! //! # The whole net is one plan //!@@ -76,7 +76,7 @@ pub const INNER: u32 = 256; pub const HEADS: u32 = 2; /// Entries in each attention layer's relative position table: `2 * window + 1` at-/// `window_size` 4, as in [`super::vits_enc`].+/// `window_size` 4, as in [`super::supertonic_text`]. pub const OFFSETS: u32 = 9; /// ConvNeXt blocks.@@ -209,11 +209,11 @@ pub fn build(weights: &dyn WeightSource, chars: u32) -> Result<Plan, String> { 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, as in `vits_enc`: the residual is added first and normalised after.+ // Post-norm: the residual is added first and normalised after. let residual = b.add(x, attended); x = b.layer_norm(residual, l.take(), EPSILON); - // Both feed-forward convolutions are 1x1 here, unlike VITS's three-wide pair.+ // Both feed-forward convolutions are 1x1 here, so neither has a border. 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);
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.rsdeleted file mode 100644index ce697ddad9..0000000000--- a/library/ml/src/main/rust/src/nets/vits_dec.rs+++ /dev/null@@ -1,379 +0,0 @@-//! 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 `.maml` 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 `.maml` tensor indices in the order the layers appear.-struct Layers {- next: usize,-}--impl Layers {- fn take(&mut self) -> usize {- let index = self.next;- self.next += 2;- index- }-}--/// A `1 x 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(super::super::tests::name_of(*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/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.rsdeleted file mode 100644index 7f690fb924..0000000000--- a/library/ml/src/main/rust/src/nets/vits_enc.rs+++ /dev/null@@ -1,298 +0,0 @@-//! 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));- }- // Two outputs. The stats are the prior the flow samples; `x` is the hidden state *before*- // the projection, which is what the duration predictor conditions on — VITS's- // `TextEncoder` returns both for exactly that reason.- builder.finish(&[stats, x])-}--#[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_outputs_are_the_prior_and_the_hidden_state() {- // Two bindings, in that order: the 384-channel stats the flow samples, and the- // 192-channel hidden state the duration predictor conditions on. `post::duration`- // reads the second, so swapping them would feed it the wrong tensor at the right- // shape for half of it.- let (_, plan) = plan(PHONEMES);- let shapes: Vec<Shape> = plan.outputs.iter().map(|b| b.shape).collect();- assert_eq!(- shapes,- vec![Shape::new(STATS, 1, PHONEMES), Shape::new(D_MODEL, 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(super::super::tests::name_of(*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.outputs[0].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/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.rsdeleted file mode 100644index c134e5e63b..0000000000--- a/library/ml/src/main/rust/src/nets/vits_flow.rs+++ /dev/null@@ -1,275 +0,0 @@-//! 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(super::super::tests::name_of(*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/post/align.rs
diff --git a/library/ml/src/main/rust/src/post/align.rs b/library/ml/src/main/rust/src/post/align.rsdeleted file mode 100644index cd4a8f5f72..0000000000--- a/library/ml/src/main/rust/src/post/align.rs+++ /dev/null@@ -1,196 +0,0 @@-//! Expanding a per-phoneme prior to per-frame, and sampling it.-//!-//! The step between VITS's duration predictor and its flow. The encoder produced a-//! distribution per *phoneme*; the vocoder needs one per *frame*, and the durations say how-//! many frames each phoneme lasts.-//!-//! # The attention matrix is a gather-//!-//! The export builds this as a `[frames, phonemes]` matrix and multiplies by it — `Range`,-//! `CumSum`, `Less`, a `Pad`, a `Sub` and two `MatMul`s. But the matrix is the output of-//! `generate_path`, which is one-hot by construction: durations are whole numbers and-//! monotonic, so each phoneme owns a contiguous run of frames and every frame belongs to-//! exactly one phoneme. A one-hot matrix multiply is a gather, so this is a walk over the-//! frames with a cursor over the phonemes.-//!-//! Worth stating because the matrix form is quadratic — at 400 phonemes and 2000 frames it is-//! 800,000 entries of which 2000 are non-zero, and the two multiplies against it are 192-//! channels deep.--/// Where each phoneme's frames start and end, and the total.-///-/// Returned rather than recomputed by the caller so the frame count and the expansion cannot-/// disagree about the length of the utterance.-pub struct Alignment {- /// One entry per frame: the index of the phoneme it belongs to.- pub phoneme_of: Vec<u32>,-}--impl Alignment {- /// Frames in the whole utterance.- pub fn frames(&self) -> usize {- self.phoneme_of.len()- }-}--/// Assign every frame to a phoneme, given each phoneme's whole-frame duration.-///-/// A duration of zero is skipped rather than refused: [`super::duration::frames`] floors at-/// one, so a zero can only arrive from a caller that built durations some other way, and-/// dropping the phoneme is what the export's `cumsum` does with it anyway.-pub fn plan(durations: &[u32]) -> Result<Alignment, String> {- if durations.is_empty() {- return Err("an alignment over no phonemes".into());- }- let total: u64 = durations.iter().map(|&d| d as u64).sum();- if total == 0 {- return Err("an alignment whose durations are all zero".into());- }- if total > u32::MAX as u64 {- return Err(format!("{total} frames is longer than an index can hold"));- }- let mut phoneme_of = Vec::with_capacity(total as usize);- for (index, &duration) in durations.iter().enumerate() {- for _ in 0..duration {- phoneme_of.push(index as u32);- }- }- Ok(Alignment { phoneme_of })-}--/// Expand the encoder's prior to frame rate and sample it.-///-/// `stats` is the encoder's `[2 * channels, phonemes]` output: the mean in the first half and-/// the log standard deviation in the second. `noise` is `[channels, frames]` of standard-/// normal, and `noise_scale` is the voice's own setting.-///-/// Returns `[channels, frames]`, which is what the flow consumes.-pub fn sample(- stats: &[f32],- phonemes: usize,- alignment: &Alignment,- noise: &[f32],- noise_scale: f32,-) -> Result<Vec<f32>, String> {- if phonemes == 0 {- return Err("a prior over no phonemes".into());- }- if !stats.len().is_multiple_of(2 * phonemes) {- return Err(format!(- "{} statistics is not two halves of {phonemes} phonemes",- stats.len()- ));- }- let channels = stats.len() / (2 * phonemes);- let frames = alignment.frames();- if noise.len() != channels * frames {- return Err(format!(- "{} noise values for {channels} channels over {frames} frames",- noise.len()- ));- }-- let mut out = vec![0.0f32; channels * frames];- for channel in 0..channels {- let mean_row = channel * phonemes;- // The log standard deviation sits `channels` rows further on, because the encoder- // concatenates the two halves rather than interleaving them.- let deviation_row = (channels + channel) * phonemes;- for (frame, &phoneme) in alignment.phoneme_of.iter().enumerate() {- let at = phoneme as usize;- if at >= phonemes {- return Err(format!("frame {frame} points at phoneme {at} of {phonemes}"));- }- let mean = stats[mean_row + at];- let deviation = stats[deviation_row + at];- out[channel * frames + frame] =- mean + noise[channel * frames + frame] * deviation.exp() * noise_scale;- }- }- Ok(out)-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn each_phoneme_owns_a_contiguous_run_of_frames() {- let got = plan(&[3, 1, 2]).expect("plans");- assert_eq!(got.phoneme_of, vec![0, 0, 0, 1, 2, 2]);- assert_eq!(got.frames(), 6);- }-- #[test]- fn a_zero_duration_phoneme_takes_no_frames() {- // Not an error: `duration::frames` floors at one, so a zero can only come from- // elsewhere, and the export's cumulative sum drops it the same way.- let got = plan(&[2, 0, 1]).expect("plans");- assert_eq!(got.phoneme_of, vec![0, 0, 2]);- }-- #[test]- fn an_empty_or_silent_utterance_is_refused() {- assert!(plan(&[]).is_err());- assert!(plan(&[0, 0]).is_err());- }-- #[test]- fn sampling_repeats_a_phonemes_statistics_across_its_frames() {- // Two channels, two phonemes, durations 2 and 1. Zero noise, so the answer is the- // mean gathered to frame rate and nothing else — which is what pins the *gather*- // rather than the sampling.- let stats = vec![- 1.0, 2.0, // channel 0 mean, per phoneme- 10.0, 20.0, // channel 1 mean- 0.0, 0.0, // channel 0 log deviation- 0.0, 0.0, // channel 1 log deviation- ];- let alignment = plan(&[2, 1]).expect("plans");- let got = sample(&stats, 2, &alignment, &[0.0; 6], 1.0).expect("samples");- assert_eq!(got, vec![1.0, 1.0, 2.0, 10.0, 10.0, 20.0]);- }-- #[test]- fn sampling_scales_the_noise_by_the_exponentiated_deviation() {- // One channel, one phoneme, three frames. `exp(log_deviation)` is the standard- // deviation, and `noise_scale` multiplies it again — the export applies both.- let stats = vec![5.0, 0.0];- let alignment = plan(&[3]).expect("plans");- let got = sample(&stats, 1, &alignment, &[1.0, -1.0, 2.0], 0.5).expect("samples");- // deviation = exp(0) = 1, so each frame is 5 + noise * 1 * 0.5.- assert_eq!(got, vec![5.5, 4.5, 6.0]);-- // A non-zero log deviation is exponentiated, not used directly.- let stats = vec![0.0, (2.0f32).ln()];- let got = sample(&stats, 1, &alignment, &[1.0, 1.0, 1.0], 1.0).expect("samples");- for value in got {- assert!((value - 2.0).abs() < 1e-6, "{value}");- }- }-- #[test]- fn the_two_halves_of_the_statistics_are_not_interleaved() {- // The encoder concatenates the mean and the log deviation, so channel `c`'s deviation- // is row `channels + c` and not row `2c + 1`. Interleaving them would read one- // channel's deviation as another's and still produce plausible audio.- let stats = vec![- 0.0, // channel 0 mean- 0.0, // channel 1 mean- (3.0f32).ln(),- (7.0f32).ln(),- ];- let alignment = plan(&[1]).expect("plans");- let got = sample(&stats, 1, &alignment, &[1.0, 1.0], 1.0).expect("samples");- assert!((got[0] - 3.0).abs() < 1e-5, "{got:?}");- assert!((got[1] - 7.0).abs() < 1e-5, "{got:?}");- }-- #[test]- fn a_noise_buffer_of_the_wrong_length_is_refused() {- let stats = vec![0.0, 0.0];- let alignment = plan(&[4]).expect("plans");- let error = sample(&stats, 1, &alignment, &[0.0; 3], 1.0).expect_err("short noise");- assert!(error.contains("3 noise values"), "{error}");- }-}
library/ml/src/main/rust/src/post/duration.rs
diff --git a/library/ml/src/main/rust/src/post/duration.rs b/library/ml/src/main/rust/src/post/duration.rsdeleted file mode 100644index 89b5416479..0000000000--- a/library/ml/src/main/rust/src/post/duration.rs+++ /dev/null@@ -1,377 +0,0 @@-//! VITS's stochastic duration predictor, on the CPU.-//!-//! # What it decides-//!-//! How many output frames each phoneme lasts. Everything downstream depends on it: the-//! alignment that expands the encoder's per-phoneme prior to per-frame, and through that the-//! length of the audio. It is the only part of speaking that is *sampled* rather than-//! computed — a different noise draw gives a different rhythm for the same words.-//!-//! # Why it is here and not a plan-//!-//! 555,159 of the voice's parameters, which is 4%, and it produces one number per phoneme.-//! Its two distinctive pieces are a bin search and a quadratic solve per position (see-//! [`super::spline`]) — data-dependent branching over tens of values, which is what a GPU is-//! worst at. The encoder, the flow and the vocoder are plans; this is a loop.-//!-//! # Shape of it-//!-//! `pre`, a three-layer depthwise-separable convolution stack and `proj` turn the encoder's-//! hidden state into a conditioning signal. Then eight flows run **in reverse** over two-//! channels of noise:-//!-//! ```text-//! flip, spline, flip, spline, flip, spline, flip, elementwise affine-//! ```-//!-//! and the first of the two output channels is the log-duration. The order is the export's-//! own: VITS reverses its flow list at inference and drops the second-to-last entry, which is-//! why there are three spline couplings in the graph and four in the checkpoint.--use crate::preprocess::f16_to_f32;-use crate::weights::Weights;--use super::spline::{self, Spline};--/// Channels the conditioning stack works in, VITS's `filter_channels`.-pub const CHANNELS: usize = 192;--/// Bins in each spline coupling. The projection emits `3 * BINS - 1` channels: widths,-/// heights, and the interior slopes, whose two ends are pinned by the linear tails.-pub const BINS: usize = 10;--/// Half-width of the interval the splines act on, VITS's `tail_bound`.-const TAIL_BOUND: f64 = 5.0;--/// Layers in each depthwise-separable stack.-const DEPTH: usize = 3;--/// Spline coupling layers, after the export's reversal drops one.-const COUPLINGS: usize = 3;--/// The epsilon in all 24 of the layer norms.-const EPSILON: f32 = 1e-5;--/// Tensors the predictor reads: 56 weighted nodes, each a pair.-///-/// `pre`, twelve for the conditioning stack, `proj`, then 28 per spline coupling.-pub const TENSORS: usize = 112;--/// The shift of the final elementwise affine, `dp.flows.0.m`.-///-/// Four scalars, so they are here rather than in the `.maml` — the same argument as-/// [`crate::nets::ppocr_det`]'s affines. Read from `en_GB-alan-low`.-const AFFINE_SHIFT: [f32; 2] = [0.55072945, 0.00070224184];--/// `exp(-logs)` of that affine, which the export has already folded into a constant. So the-/// reverse direction is a subtract and a multiply, with no exponential at runtime.-const AFFINE_INVERSE_SCALE: [f32; 2] = [1.9522907, 1.1635983];--/// One tensor of the `.maml`, decoded to `f32`.-fn tensor(weights: &Weights, index: usize, dims: &[u32]) -> Result<Vec<f32>, String> {- let found = weights.shaped(index, dims)?;- let bytes = weights.data();- let start = found.offset as usize;- let end = start + (found.len as usize) * 2;- let raw = bytes- .get(start..end)- .ok_or_else(|| format!("tensor {index} runs past the data section"))?;- Ok(raw.chunks_exact(2).map(|c| f16_to_f32(u16::from_le_bytes([c[0], c[1]]))).collect())-}--/// `erf` now lives beside [`crate::nets::Act::Gelu`], which outlives this module: it goes when-/// Piper does, and the activation does not.-use crate::nets::erf;--/// The exact GELU, `0.5 x (1 + erf(x / sqrt(2)))`.-fn gelu(x: f32) -> f32 {- 0.5 * x * (1.0 + erf(x * std::f32::consts::FRAC_1_SQRT_2))-}--/// A `[channels, positions]` buffer, which is every intermediate here.-type Plane = Vec<f32>;--/// A depthwise convolution along the sequence, one `kernel`-wide filter per channel, padded-/// to hold the length.-fn depthwise(x: &Plane, positions: usize, weight: &[f32], bias: &[f32], dilation: usize) -> Plane {- let kernel = weight.len() / CHANNELS;- let pad = (kernel - 1) * dilation / 2;- let mut out = vec![0.0f32; CHANNELS * positions];- for channel in 0..CHANNELS {- for position in 0..positions {- let mut total = bias[channel];- for tap in 0..kernel {- let at = (position + tap * dilation) as isize - pad as isize;- if at < 0 || at >= positions as isize {- continue;- }- total += weight[channel * kernel + tap] * x[channel * positions + at as usize];- }- out[channel * positions + position] = total;- }- }- out-}--/// A 1x1 convolution, which is a matrix multiply per position.-fn pointwise(- x: &Plane,- inputs: usize,- positions: usize,- weight: &[f32],- bias: &[f32],-) -> Plane {- let outputs = bias.len();- let mut out = vec![0.0f32; outputs * positions];- for output in 0..outputs {- for position in 0..positions {- let mut total = bias[output];- for input in 0..inputs {- total += weight[output * inputs + input] * x[input * positions + position];- }- out[output * positions + position] = total;- }- }- out-}--/// Normalise over channels, one position at a time.-fn layer_norm(x: &mut Plane, channels: usize, positions: usize, gamma: &[f32], beta: &[f32]) {- for position in 0..positions {- let mut mean = 0.0f64;- for channel in 0..channels {- mean += x[channel * positions + position] as f64;- }- mean /= channels as f64;- let mut variance = 0.0f64;- for channel in 0..channels {- let centred = x[channel * positions + position] as f64 - mean;- variance += centred * centred;- }- variance /= channels as f64;- let inverse = 1.0 / (variance + EPSILON as f64).sqrt();- for channel in 0..channels {- let centred = x[channel * positions + position] as f64 - mean;- x[channel * positions + position] =- (centred * inverse) as f32 * gamma[channel] + beta[channel];- }- }-}--/// Three depthwise-separable residual layers, dilated 1, 3 and 9.-///-/// `base` is where this stack's 24 tensors start. Each layer is a separable convolution, a-/// norm, a GELU, a 1x1, a norm, a GELU and a residual add — the order VITS's `DDSConv` uses.-fn separable_stack(- weights: &Weights,- base: usize,- x: &mut Plane,- positions: usize,-) -> Result<(), String> {- let channels = CHANNELS as u32;- for layer in 0..DEPTH {- let at = base + layer * 8;- let dilation = 3usize.pow(layer as u32);- let sep_w = tensor(weights, at, &[channels, 1, 1, 3])?;- let sep_b = tensor(weights, at + 1, &[channels])?;- let n1_g = tensor(weights, at + 2, &[channels])?;- let n1_b = tensor(weights, at + 3, &[channels])?;- let pw_w = tensor(weights, at + 4, &[channels, channels, 1, 1])?;- let pw_b = tensor(weights, at + 5, &[channels])?;- let n2_g = tensor(weights, at + 6, &[channels])?;- let n2_b = tensor(weights, at + 7, &[channels])?;-- let mut y = depthwise(x, positions, &sep_w, &sep_b, dilation);- layer_norm(&mut y, CHANNELS, positions, &n1_g, &n1_b);- for value in &mut y {- *value = gelu(*value);- }- let mut y = pointwise(&y, CHANNELS, positions, &pw_w, &pw_b);- layer_norm(&mut y, CHANNELS, positions, &n2_g, &n2_b);- for value in &mut y {- *value = gelu(*value);- }- for (slot, added) in x.iter_mut().zip(&y) {- *slot += added;- }- }- Ok(())-}--/// The log-duration of each phoneme.-///-/// `hidden` is the encoder's pre-projection output, `[192, phonemes]`. `noise` is-/// `[2, phonemes]` of standar
Diff truncated.