Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / ml / fetch_supertonic.py

fetch_supertonic.py171 lines · 7.0 KiBRaw
1#!/usr/bin/env python3
2"""Fetch Supertonic 3's ONNX export and build the bundle `:speech` ships.
3
4Supertonic was the one model in this tree with **no recorded provenance**. Every other one is
5pinned by upstream revision and file SHA-256 in `scripts/ml/fetch_and_convert.sh`, with a README
6beside the asset; Supertonic's four exports were fetched by hand, so nothing said where they came
7from and the bundle could not be rebuilt from a fresh checkout. This closes that.
8
9It is not folded into `fetch_and_convert.sh` because the shape is different: that script is one
10ONNX to one `.maml` per model, while this is one upstream repo to *four* `.maml` plus a codepoint
11table and ten voice styles, through two converters. It also needs `huggingface_hub`, which the
12shell script deliberately does not.
13
14# The licence is use-restricted
15
16Supertonic 3 is **OpenRAIL**, the first such licence in this tree - everything else here is
17Apache-2.0, MIT, ODbL or InsightFace's non-commercial research terms. Because the bundle ships
18inside the APK rather than being downloaded by a user who went looking for it, the restriction
19travels with every release. See `SUPPLY_CHAIN_RISKS.md`.
20
21# What is verified, and what that catches
22
23Two independent checks, and they fail for different reasons:
24
25* The **file SHA-256** of each ONNX, below. Catches an upstream re-export at the same revision, or
26 a truncated download.
27* The **layer table digest** each converter pins in `maml_convert.EXPECTED_DIGEST`. Catches an
28 export whose *structure* moved - a reordered or re-padded layer - which is what would make the
29 hardcoded Rust forward passes read the right shapes holding the wrong numbers.
30
31Neither checks the numbers. `scripts/ml/onnx_parity.py` does, and is worth running after any
32change here; the four correlations it reported for this revision are in the table at the bottom.
33
34Usage:
35
36 python scripts/ml/fetch_supertonic.py # verify digests, rebuild the bundle
37 python scripts/ml/fetch_supertonic.py --work DIR # keep the ONNX somewhere specific
38 python scripts/ml/fetch_supertonic.py --print-digests # after an intentional upstream bump
39"""
40
41import argparse
42import hashlib
43import os
44import subprocess
45import sys
46import tempfile
47
48REPO = "Supertone/supertonic-3"
49
50# Pinned to a commit rather than to `main`, for the reason `fetch_and_convert.sh` gives: the
51# digests below would catch a silent upstream change anyway, but a pinned revision tells you the
52# upstream *revision* that moved rather than just that some bytes differ.
53REVISION = "3cadd1ee6394adea1bd021217a0e650ede09a323"
54
55HERE = os.path.dirname(os.path.abspath(__file__))
56ROOT = os.path.dirname(os.path.dirname(HERE))
57ASSETS = os.path.join(ROOT, "speech", "src", "main", "assets", "supertonic")
58
59# graph id -> the ONNX in the upstream repo it is folded from.
60GRAPHS = {
61 "supertonic_dp": "onnx/duration_predictor.onnx",
62 "supertonic_ttl": "onnx/text_encoder.onnx",
63 "supertonic_ve": "onnx/vector_estimator.onnx",
64 "supertonic_voc": "onnx/vocoder.onnx",
65}
66
67# The codepoint table and the ten voice styles, which are inputs rather than weights and so are
68# not `.maml`. See `supertonic_bundle.py`.
69INDEXER = "onnx/unicode_indexer.json"
70STYLES = "voice_styles"
71
72# SHA-256 of every file this reads, at REVISION. Not the whole repo: the 11 MB of audio samples and
73# hero images upstream ships are not fetched, so pinning them would pin something never downloaded.
74DIGESTS = {
75 "onnx/duration_predictor.onnx":
76 "c3eb91414d5ff8a7a239b7fe9e34e7e2bf8a8140d8375ffb14718b1c639325db",
77 "onnx/text_encoder.onnx":
78 "c7befd5ea8c3119769e8a6c1486c4edc6a3bc8365c67621c881bbb774b9902ff",
79 "onnx/vector_estimator.onnx":
80 "883ac868ea0275ef0e991524dc64f16b3c0376efd7c320af6b53f5b780d7c61c",
81 "onnx/vocoder.onnx":
82 "085de76dd8e8d5836d6ca66826601f615939218f90e519f70ee8a36ed2a4c4ba",
83}
84
85# Only what the two converters read. The ONNX is 398 MB against the ~198 MB of fp16 `.maml` it
86# becomes, and nothing reads it at run time, so it stays out of the repo - the same rule
87# `fetch_and_convert.sh` applies to every other model here.
88WANTED = list(GRAPHS.values()) + [INDEXER, f"{STYLES}/*.json", "LICENSE", "config.json"]
89
90
91def sha256(path):
92 digest = hashlib.sha256()
93 with open(path, "rb") as handle:
94 for block in iter(lambda: handle.read(1 << 20), b""):
95 digest.update(block)
96 return digest.hexdigest()
97
98
99def convert(script, *args):
100 """Run one of the sibling converters, letting its own output and exit code through.
101
102 `check=True` matters: `supertonic_fold.py` exits non-zero when a layer table digest does not
103 match, and that is the check that must stop a bundle being built from the wrong export.
104 """
105 subprocess.run([sys.executable, os.path.join(HERE, script), *args], check=True, cwd=ROOT)
106
107
108def main():
109 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
110 parser.add_argument("--work", help="where to keep the ONNX (default: a temp directory)")
111 parser.add_argument("-o", "--out", default=ASSETS, help="where to write the bundle")
112 parser.add_argument(
113 "--print-digests",
114 action="store_true",
115 help="print the fetched files' SHA-256 instead of checking them, to re-pin after a bump",
116 )
117 args = parser.parse_args()
118
119 try:
120 from huggingface_hub import snapshot_download
121 except ImportError:
122 raise SystemExit("needs huggingface_hub: python -m pip install huggingface_hub")
123
124 work = args.work or os.path.join(tempfile.gettempdir(), "supertonic-3")
125 local = snapshot_download(
126 repo_id=REPO, revision=REVISION, allow_patterns=WANTED, local_dir=work
127 )
128 print(f"{REPO}@{REVISION[:12]} in {local}")
129
130 if args.print_digests:
131 for name in sorted(GRAPHS.values()):
132 print(f' "{name}":\n "{sha256(os.path.join(local, name))}",')
133 return 0
134
135 for name, expected in sorted(DIGESTS.items()):
136 got = sha256(os.path.join(local, name))
137 if got != expected:
138 raise SystemExit(
139 f"{name}\n sha256 {got}\n pinned {expected}\n"
140 "The upstream export changed. Re-read it, check the Rust forward pass still\n"
141 "matches, then re-pin with --print-digests."
142 )
143 print(f"{len(DIGESTS)} ONNX digests match")
144
145 os.makedirs(args.out, exist_ok=True)
146 for graph, onnx in sorted(GRAPHS.items()):
147 convert(
148 "supertonic_fold.py",
149 os.path.join(local, onnx),
150 "--graph", graph,
151 "-o", os.path.join(args.out, f"{graph}.maml"),
152 )
153 convert(
154 "supertonic_bundle.py",
155 "--indexer", os.path.join(local, INDEXER),
156 "--styles", os.path.join(local, STYLES),
157 "-o", args.out,
158 )
159
160 total = 0
161 for name in sorted(os.listdir(args.out)):
162 path = os.path.join(args.out, name)
163 if not os.path.isfile(path) or name.endswith(".md"):
164 continue
165 total += os.path.getsize(path)
166 print(f"\n{args.out}: {total} bytes ({total / (1 << 20):.1f} MiB)")
167 return 0
168
169
170if __name__ == "__main__":
171 raise SystemExit(main())