Modern Apps git

← Modern-Apps.git

speech: pin and rebuild the Supertonic bundle from its upstream export

Commit
3ffe276029a7cb426c2a5adf85b6bd263e22c4f4
Author
vayun-mathur <[email protected]>
When
2026-08-29 00:05 UTC (3 months ago)
Parents
f8eaeb7

Diff

.gitignore
diff --git a/.gitignore b/.gitignoreindex d1dd7fe6b1..15d626557c 100644--- a/.gitignore+++ b/.gitignore@@ -65,6 +65,18 @@ health/src/main/assets/staging.db # every listing image twice. Remove this ignore if you ever want # `validate<Variant>ScreenshotTest` to act as UI regression testing. **/src/screenshotTest*/reference/+# Supertonic 3's TTS bundle - 189 MiB of fp16 .maml plus its codepoint table and ten voice+# styles. Rebuild byte for byte with `python scripts/ml/fetch_supertonic.py`, which pins the+# upstream revision and every ONNX SHA-256. Ignored for the same reason as the two above: it is+# the largest asset in the tree, it is derived rather than authored, and committing it would put+# it in history permanently - including the fp16 blobs that an int8 conversion would supersede.+#+# Consequence worth knowing: a fresh checkout builds a :speech APK with **no voices**, and the+# TTS engine then advertises no languages (SupertonicBundle.isPresent is false) rather than+# failing on the first utterance. Run the script before cutting a release.+speech/src/main/assets/supertonic/*.maml+speech/src/main/assets/supertonic/*.bin+ # Apple WPS scraping experiment (research scratch: crawler DBs, samples, artifacts) wtfps-experiment/ wtfps/
SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdindex 4fc53f3d96..5a06577058 100644--- a/SUPPLY_CHAIN_RISKS.md+++ b/SUPPLY_CHAIN_RISKS.md@@ -53,7 +53,9 @@ These servers provide data/functionality that is NOT intrinsically tied to a sin - **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** 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. -  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.+  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 and no runtime dependency at all: upstream is **`Supertone/supertonic-3`** on HuggingFace, pinned to revision `3cadd1ee` with all four ONNX SHA-256s in `scripts/ml/fetch_supertonic.py`, which fetches it and drives both converters. The ONNX is not vendored - it is 398 MB against the 189 MiB of fp16 `.maml` it becomes, and nothing reads it at run time. The `.maml` are not committed either, for the reason `/.gitignore` gives, so `fetch_supertonic.py` is the only record of where the weights came from and the only way to rebuild them.++  Two independent checks guard a bad rebuild, and they fail for different reasons: the pinned file SHA-256s catch a re-export or a truncated download, and each converter's layer-table digest in `maml_convert.EXPECTED_DIGEST` catches an export whose *structure* moved - which is what would make the hardcoded Rust forward passes read the right shapes holding the wrong numbers. Neither checks the numbers; `scripts/ml/onnx_parity.py` does, and at the pinned revision all four nets correlate with onnxruntime above 0.999.    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. 
library/ml/src/main/rust/tests/assets.rs
diff --git a/library/ml/src/main/rust/tests/assets.rs b/library/ml/src/main/rust/tests/assets.rsindex 47a42df1f0..b0b1cd4869 100644--- a/library/ml/src/main/rust/tests/assets.rs+++ b/library/ml/src/main/rust/tests/assets.rs@@ -13,7 +13,10 @@  use std::path::{Path, PathBuf}; -use modelrunner::nets::{mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, u2netp};+use modelrunner::nets::{+    mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration, supertonic_sampler,+    supertonic_text, supertonic_vocoder, u2netp,+}; use modelrunner::post::ctc; use modelrunner::weights::{graph, Weights}; @@ -214,3 +217,88 @@ fn report_the_device_memory_each_net_needs() {         assert!(weight_bytes + arena_bytes < 128 * 1024 * 1024);     } }++/// One of Supertonic's four `.maml`, or `None` when the bundle has not been built.+///+/// Unlike every other asset here, Supertonic's is **not committed**: the four nets come to 189 MiB+/// at fp16, which is more than belongs in git history for something a pinned script can rebuild+/// byte for byte. So a fresh checkout does not have it, and this returns `None` rather than+/// panicking — the test below then reports that it was skipped instead of failing for the one+/// reason that is not a bug.+///+/// A file that is *present but wrong* is still a hard failure. That is the case worth catching:+/// a bundle rebuilt from a moved upstream, or converted by a `supertonic_fold.py` whose layer+/// ordering has drifted from the Rust.+fn supertonic(name: &str, graph_id: u32) -> Option<Weights> {+    let path = repo_root().join("speech/src/main/assets/supertonic").join(name);+    let bytes = std::fs::read(&path).ok()?;+    Some(+        Weights::parse(&bytes, graph_id)+            .unwrap_or_else(|e| panic!("{} is not a usable .maml: {e}", path.display())),+    )+}++#[test]+fn the_bundled_supertonic_assets_build_all_four_forward_passes() {+    // The four hardcoded passes against the four converted files, which is the strongest automatic+    // check that the bundle `:speech` ships is the one the Rust was written for: `Builder::finish`+    // refuses a plan that does not read every tensor in its file, and each `build` walks its+    // tensors through `Weights::shaped`, so a reordered or re-shaped layer fails here naming the+    // tensor rather than producing silent nonsense on a phone.+    //+    // Widths are arbitrary but non-trivial: every Supertonic plan is utterance-shaped, so a build+    // at one length exercises the shape arithmetic that `Net::rebuild` repeats per sentence.+    let (frames, chars) = (32u32, 16u32);++    let Some(duration) = supertonic("supertonic_dp.maml", graph::SUPERTONIC_DP) else {+        println!(+            "skipped: no bundle in speech/src/main/assets/supertonic. \+             Run python scripts/ml/fetch_supertonic.py to build it."+        );+        return;+    };+    assert_eq!(duration.len(), supertonic_duration::TENSORS);+    assert!(!supertonic_duration::build(&duration, chars).expect("the duration pass").ops.is_empty());++    let text = supertonic("supertonic_ttl.maml", graph::SUPERTONIC_TTL).expect("the text encoder");+    assert_eq!(text.len(), supertonic_text::TENSORS);+    assert!(!supertonic_text::build(&text, chars).expect("the text pass").ops.is_empty());++    let sampler = supertonic("supertonic_ve.maml", graph::SUPERTONIC_VE).expect("the sampler");+    assert_eq!(sampler.len(), supertonic_sampler::TENSORS);+    assert!(+        !supertonic_sampler::build(&sampler, frames, chars).expect("the sampler pass").ops.is_empty()+    );++    let vocoder = supertonic("supertonic_voc.maml", graph::SUPERTONIC_VOC).expect("the vocoder");+    assert_eq!(vocoder.len(), supertonic_vocoder::TENSORS);+    assert!(!supertonic_vocoder::build(&vocoder, frames).expect("the vocoder pass").ops.is_empty());++    let total: usize = [&duration, &text, &sampler, &vocoder].iter().map(|w| w.data().len()).sum();+    println!("supertonic: {} MiB of weights across four nets", total / (1 << 20));+}++/// The six files `SupertonicBundle.isPresent` requires before `:speech` will advertise a voice.+///+/// Kotlin's check is a directory listing, so it cannot notice a file that is the right name and the+/// wrong size. This is the counterpart that does: the codepoint table is a fixed 65,536 `int16` and+/// each voice style a fixed 12,928 fp16, both fixed by the architecture rather than by the export,+/// so a length check here is as strong as a digest would be.+#[test]+fn the_bundled_supertonic_inputs_are_the_sizes_the_runtime_assumes() {+    let dir = repo_root().join("speech/src/main/assets/supertonic");+    let Ok(indexer) = std::fs::read(dir.join("unicode_indexer.bin")) else {+        println!("skipped: no bundle. Run python scripts/ml/fetch_supertonic.py to build it.");+        return;+    };+    // `post::supertonic::INDEXER_ENTRIES` int16, one per BMP codepoint.+    assert_eq!(indexer.len(), 65_536 * 2, "the codepoint table");++    // `style_ttl` transposed to [256, 50] then `style_dp` flattened to 128, as fp16.+    let style_elems = 256 * 50 + 128;+    for voice in ["F1", "F2", "F3", "F4", "F5", "M1", "M2", "M3", "M4", "M5"] {+        let name = format!("style_{voice}.bin");+        let bytes = std::fs::read(dir.join(&name)).unwrap_or_else(|e| panic!("{name}: {e}"));+        assert_eq!(bytes.len(), style_elems * 2, "{name}");+    }+}
scripts/ml/fetch_supertonic.py
diff --git a/scripts/ml/fetch_supertonic.py b/scripts/ml/fetch_supertonic.pynew file mode 100644index 0000000000..c32b2e73a1--- /dev/null+++ b/scripts/ml/fetch_supertonic.py@@ -0,0 +1,171 @@+#!/usr/bin/env python3+"""Fetch Supertonic 3's ONNX export and build the bundle `:speech` ships.++Supertonic was the one model in this tree with **no recorded provenance**. Every other one is+pinned by upstream revision and file SHA-256 in `scripts/ml/fetch_and_convert.sh`, with a README+beside the asset; Supertonic's four exports were fetched by hand, so nothing said where they came+from and the bundle could not be rebuilt from a fresh checkout. This closes that.++It is not folded into `fetch_and_convert.sh` because the shape is different: that script is one+ONNX to one `.maml` per model, while this is one upstream repo to *four* `.maml` plus a codepoint+table and ten voice styles, through two converters. It also needs `huggingface_hub`, which the+shell script deliberately does not.++# The licence is use-restricted++Supertonic 3 is **OpenRAIL**, the first such licence in this tree - everything else here is+Apache-2.0, MIT, ODbL or InsightFace's non-commercial research terms. Because the bundle ships+inside the APK rather than being downloaded by a user who went looking for it, the restriction+travels with every release. See `SUPPLY_CHAIN_RISKS.md`.++# What is verified, and what that catches++Two independent checks, and they fail for different reasons:++* The **file SHA-256** of each ONNX, below. Catches an upstream re-export at the same revision, or+  a truncated download.+* The **layer table digest** each converter pins in `maml_convert.EXPECTED_DIGEST`. Catches an+  export whose *structure* moved - a reordered or re-padded layer - which is what would make the+  hardcoded Rust forward passes read the right shapes holding the wrong numbers.++Neither checks the numbers. `scripts/ml/onnx_parity.py` does, and is worth running after any+change here; the four correlations it reported for this revision are in the table at the bottom.++Usage:++    python scripts/ml/fetch_supertonic.py                 # verify digests, rebuild the bundle+    python scripts/ml/fetch_supertonic.py --work DIR      # keep the ONNX somewhere specific+    python scripts/ml/fetch_supertonic.py --print-digests # after an intentional upstream bump+"""++import argparse+import hashlib+import os+import subprocess+import sys+import tempfile++REPO = "Supertone/supertonic-3"++# Pinned to a commit rather than to `main`, for the reason `fetch_and_convert.sh` gives: the+# digests below would catch a silent upstream change anyway, but a pinned revision tells you the+# upstream *revision* that moved rather than just that some bytes differ.+REVISION = "3cadd1ee6394adea1bd021217a0e650ede09a323"++HERE = os.path.dirname(os.path.abspath(__file__))+ROOT = os.path.dirname(os.path.dirname(HERE))+ASSETS = os.path.join(ROOT, "speech", "src", "main", "assets", "supertonic")++# graph id -> the ONNX in the upstream repo it is folded from.+GRAPHS = {+    "supertonic_dp": "onnx/duration_predictor.onnx",+    "supertonic_ttl": "onnx/text_encoder.onnx",+    "supertonic_ve": "onnx/vector_estimator.onnx",+    "supertonic_voc": "onnx/vocoder.onnx",+}++# The codepoint table and the ten voice styles, which are inputs rather than weights and so are+# not `.maml`. See `supertonic_bundle.py`.+INDEXER = "onnx/unicode_indexer.json"+STYLES = "voice_styles"++# SHA-256 of every file this reads, at REVISION. Not the whole repo: the 11 MB of audio samples and+# hero images upstream ships are not fetched, so pinning them would pin something never downloaded.+DIGESTS = {+    "onnx/duration_predictor.onnx":+        "c3eb91414d5ff8a7a239b7fe9e34e7e2bf8a8140d8375ffb14718b1c639325db",+    "onnx/text_encoder.onnx":+        "c7befd5ea8c3119769e8a6c1486c4edc6a3bc8365c67621c881bbb774b9902ff",+    "onnx/vector_estimator.onnx":+        "883ac868ea0275ef0e991524dc64f16b3c0376efd7c320af6b53f5b780d7c61c",+    "onnx/vocoder.onnx":+        "085de76dd8e8d5836d6ca66826601f615939218f90e519f70ee8a36ed2a4c4ba",+}++# Only what the two converters read. The ONNX is 398 MB against the ~198 MB of fp16 `.maml` it+# becomes, and nothing reads it at run time, so it stays out of the repo - the same rule+# `fetch_and_convert.sh` applies to every other model here.+WANTED = list(GRAPHS.values()) + [INDEXER, f"{STYLES}/*.json", "LICENSE", "config.json"]+++def sha256(path):+    digest = hashlib.sha256()+    with open(path, "rb") as handle:+        for block in iter(lambda: handle.read(1 << 20), b""):+            digest.update(block)+    return digest.hexdigest()+++def convert(script, *args):+    """Run one of the sibling converters, letting its own output and exit code through.++    `check=True` matters: `supertonic_fold.py` exits non-zero when a layer table digest does not+    match, and that is the check that must stop a bundle being built from the wrong export.+    """+    subprocess.run([sys.executable, os.path.join(HERE, script), *args], check=True, cwd=ROOT)+++def main():+    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+    parser.add_argument("--work", help="where to keep the ONNX (default: a temp directory)")+    parser.add_argument("-o", "--out", default=ASSETS, help="where to write the bundle")+    parser.add_argument(+        "--print-digests",+        action="store_true",+        help="print the fetched files' SHA-256 instead of checking them, to re-pin after a bump",+    )+    args = parser.parse_args()++    try:+        from huggingface_hub import snapshot_download+    except ImportError:+        raise SystemExit("needs huggingface_hub: python -m pip install huggingface_hub")++    work = args.work or os.path.join(tempfile.gettempdir(), "supertonic-3")+    local = snapshot_download(+        repo_id=REPO, revision=REVISION, allow_patterns=WANTED, local_dir=work+    )+    print(f"{REPO}@{REVISION[:12]} in {local}")++    if args.print_digests:+        for name in sorted(GRAPHS.values()):+            print(f'    "{name}":\n        "{sha256(os.path.join(local, name))}",')+        return 0++    for name, expected in sorted(DIGESTS.items()):+        got = sha256(os.path.join(local, name))+        if got != expected:+            raise SystemExit(+                f"{name}\n  sha256 {got}\n  pinned {expected}\n"+                "The upstream export changed. Re-read it, check the Rust forward pass still\n"+                "matches, then re-pin with --print-digests."+            )+    print(f"{len(DIGESTS)} ONNX digests match")++    os.makedirs(args.out, exist_ok=True)+    for graph, onnx in sorted(GRAPHS.items()):+        convert(+            "supertonic_fold.py",+            os.path.join(local, onnx),+            "--graph", graph,+            "-o", os.path.join(args.out, f"{graph}.maml"),+        )+    convert(+        "supertonic_bundle.py",+        "--indexer", os.path.join(local, INDEXER),+        "--styles", os.path.join(local, STYLES),+        "-o", args.out,+    )++    total = 0+    for name in sorted(os.listdir(args.out)):+        path = os.path.join(args.out, name)+        if not os.path.isfile(path) or name.endswith(".md"):+            continue+        total += os.path.getsize(path)+    print(f"\n{args.out}: {total} bytes ({total / (1 << 20):.1f} MiB)")+    return 0+++if __name__ == "__main__":+    raise SystemExit(main())
speech/src/main/assets/supertonic/README.md
diff --git a/speech/src/main/assets/supertonic/README.md b/speech/src/main/assets/supertonic/README.mdindex 4ee9c87779..ec25daac6f 100644--- a/speech/src/main/assets/supertonic/README.md+++ b/speech/src/main/assets/supertonic/README.md@@ -1,17 +1,18 @@ # Supertonic 3, bundled  `SupertonicSynthesizer.inAssets` reads these six files, and `SupertonicBundle.isPresent` refuses to-advertise the TTS engine unless they are all here. They are **not in version control** — the four-`.maml` come to ~105 MB — so a fresh checkout has to build them:+advertise the TTS engine unless they are all here. They are **not in version control** — see the+entry in `/.gitignore` for why — so a fresh checkout has to build them:  ```-./scripts/ml/supertonic_fold.py duration_predictor.onnx --graph supertonic_dp  -o supertonic_dp.maml-./scripts/ml/supertonic_fold.py text_encoder.onnx       --graph supertonic_ttl -o supertonic_ttl.maml-./scripts/ml/supertonic_fold.py vector_estimator.onnx   --graph supertonic_ve  -o supertonic_ve.maml-./scripts/ml/supertonic_fold.py vocoder.onnx            --graph supertonic_voc -o supertonic_voc.maml-./scripts/ml/supertonic_bundle.py --indexer <ttl.json> --styles voice_styles/ -o .+python scripts/ml/fetch_supertonic.py ``` +That fetches `Supertone/supertonic-3` pinned to one revision, checks all four ONNX SHA-256s, and+runs both converters. Each converter also checks its own layer-table digest against+`maml_convert.EXPECTED_DIGEST`, so a bundle built from a moved upstream fails loudly rather than+producing a net that reads the right shapes holding the wrong numbers.+ | File | What it is | | :--- | :--- | | `supertonic_dp.maml` | duration predictor — one number, the utterance's length in seconds |@@ -21,6 +22,16 @@ advertise the TTS engine unless they are all here. They are **not in version con | `unicode_indexer.bin` | 65,536 `int16`, one per BMP codepoint; the whole front end | | `style_F1.bin` … `style_M5.bin` | ten voices, ~25 KB each; two style tensors, not a model | +At fp16 the four nets come to 189 MiB, which with Whisper's 74 MiB puts `:speech`'s assets at+263 MiB. Quantising the ungrouped `1 x 1` convolutions to int8 would take the four nets to ~100 MiB;+`Builder::conv_int8` and `conv_point_int8.comp` exist for it, but no net has been switched over yet.++Verified by `library/ml/src/main/rust/tests/assets.rs`, which builds all four forward passes against+these files and checks the codepoint table and every style is the size the runtime assumes. Those+tests **skip** when the bundle is absent, so they pass on a fresh checkout and fail on a wrong one.+The numbers are checked separately by `scripts/ml/onnx_parity.py`; at the pinned revision all four+nets correlate with onnxruntime above 0.999, the vocoder better than its own fp16 bar.+ ## Uncompressed, and it has to stay that way  `noCompress += "maml"` in `speech/build.gradle.kts` is load-bearing rather than an optimisation: