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

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

fetch_whisper.py318 lines · 14.4 KiBRaw
1#!/usr/bin/env python3
2"""Fetch whisper-base's checkpoint and build the `whisper_base.maml` `:speech` bundles.
3
4# Why this exists
5
6It replaces `scripts/speech/fetch_whisper_onnx.sh`, which vendored two int8 ONNX exports from
7`onnx-community/whisper-base` and pinned their digests. Those exports are gone with ONNX Runtime;
8this reads the fp32 checkpoint they were quantised from and quantises it here instead.
9
10# The fp32 checkpoint, not the int8 export
11
12`onnx-community/whisper-base` is an ONNX Runtime **dynamic** int8 quantisation, and it quantises per
13*tensor*. That is the same coarseness that moved SMaLL-100 onto `alirezamsh/small100`'s checkpoint
14for a factor-of-four resolution gain on its embedding — see `CHECKPOINTS` in
15`scripts/ml/maml_convert.py`. `maml_convert.quantise_per_channel` gives every kernel here a
16per-output-channel scale, and the worst measured per-tensor correlation against fp32 is 0.99979.
17
18`openai/whisper-base` is **Apache-2.0**. It is a build-host dependency only: 290 MB downloaded here,
19nothing at run time.
20
21# The pins, and what each one catches
22
23* **File SHA-256**, below. Catches an upstream re-export at the same revision, or a truncated
24 download.
25* **`config.json`**, checked against [`ARCHITECTURE`] rather than trusted. `nets::whisper` hardcodes
26 6 encoder layers, 6 decoder layers, `d_model` 512, 8 heads and a 2048-wide feed-forward.
27* **`preprocessor_config.json`**, checked against [`FEATURES`]. `WhisperFeatures.kt` hardcodes the
28 mel front end, and a wrong `n_fft` or `hop_length` produces fluent, confident nonsense rather than
29 an error. The old shell script asserted the same constants; this keeps that.
30* **`generation_config.json`**, checked against [`DECODING`]. The special-token ids and the
31 suppression lists are what `post::whisper` is written against, and `<|notimestamps|>` in particular
32 changes the output to timestamped text if it moves or is dropped.
33* **The parameter inventory** `maml_convert.check_checkpoint` asserts — every name and every shape.
34 It is also what catches the two absences the port depends on: no `k_proj.bias` anywhere, and no
35 `proj_out` because the head is tied.
36* **The layer table digest** `maml_convert.EXPECTED_DIGEST` pins, over the emitted order.
37
38`vocab.json` and `generation_config.json` are **checked, not rewritten**. Both already ship beside
39the model, vendored from `onnx-community/whisper-base` by the script this replaces, and both are
40byte-for-byte what the runtime reads: `WhisperTokenizer` decodes with the vocabulary directly and
41`post::whisper` reads the ids and suppression lists out of the generation config. Copying upstream's
42copies over them would rewrite 50,000 lines of identically-meaning JSON, so instead this proves the
43two mirrors **agree** — same token for every id below 50,257, same value for every decoding field —
44which is a stronger statement than a copy and leaves the shipped bytes alone.
45
46Usage:
47
48 python scripts/ml/fetch_whisper.py # verify digests, write the assets
49 python scripts/ml/fetch_whisper.py --work DIR # keep the 290 MB checkpoint somewhere
50 python scripts/ml/fetch_whisper.py --print-digests # after an intentional upstream bump
51"""
52
53import argparse
54import hashlib
55import json
56import os
57import subprocess
58import sys
59import tempfile
60
61REPO = "openai/whisper-base"
62
63# Pinned to a commit rather than to `main`, for the reason `fetch_and_convert.sh` gives: the digests
64# below would catch a silent upstream change anyway, but a pinned revision tells you the upstream
65# *revision* that moved rather than just that some bytes differ.
66REVISION = "e37978b90ca9030d5170a5c07aadb050351a65bb"
67
68HERE = os.path.dirname(os.path.abspath(__file__))
69ROOT = os.path.dirname(os.path.dirname(HERE))
70
71# A bundled asset directory, unlike `fetch_small100.py`'s runtime downloads.
72OUT = os.path.join(ROOT, "speech", "src", "main", "assets", "whisper-base")
73
74CHECKPOINT = "model.safetensors"
75CONFIG = "config.json"
76PREPROCESSOR = "preprocessor_config.json"
77GENERATION = "generation_config.json"
78VOCAB = "vocab.json"
79
80# SHA-256 of every file this reads, at the pinned revision. Not the whole repo: `pytorch_model.bin`,
81# `flax_model.msgpack` and `tf_model.h5` say the same thing as the checkpoint, so pinning them would
82# pin something never downloaded.
83DIGESTS = {
84 CHECKPOINT: "07cadb9f25677c8d50df603e66a98fbd842cce45047139baeb16e6219a1e807b",
85 CONFIG: "a153c53883a6799b6f056b4a8d1a515c9926d03994682ba88a7616618d7da0c1",
86 PREPROCESSOR: "9b5cd03a36fbb8a627c64d98a5b5b126ead95a77720723944487311f0110b666",
87 GENERATION: "444b3f636d2fff89dd9ecf549e2a085b61f7ff0fa0246d4628bac6a3b8cc9ba4",
88 VOCAB: "8f680bba319e01a653d2e8a5dbc17a9157179e0576e6ce74ce0c06356c6e24f9",
89}
90
91# Transcribed from the pinned `config.json`, and asserted against it below rather than trusted.
92# `nets::whisper` is written against these; `maml_convert.CHECKPOINTS` restates the subset the tensor
93# table depends on.
94ARCHITECTURE = {
95 "d_model": 512,
96 "encoder_layers": 6,
97 "decoder_layers": 6,
98 "encoder_attention_heads": 8,
99 "decoder_attention_heads": 8,
100 "encoder_ffn_dim": 2048,
101 "decoder_ffn_dim": 2048,
102 "vocab_size": 51_865,
103 "max_source_positions": 1500,
104 "max_target_positions": 448,
105 "num_mel_bins": 80,
106 "activation_function": "gelu",
107 # No `sqrt(d_model)` on the embedding, unlike M2M-100. Asserted because the converter relies on
108 # it: a checkpoint with `scale_embedding: true` would need the scale folded into the table.
109 "scale_embedding": False,
110}
111
112# From the pinned `preprocessor_config.json`, and the constants `WhisperFeatures.kt` hardcodes. The
113# old `fetch_whisper_onnx.sh` asserted these; a wrong mel is the one error in this pipeline that
114# produces confident nonsense rather than a failure, so the check survives the port.
115FEATURES = {
116 "feature_size": 80,
117 "n_fft": 400,
118 "hop_length": 160,
119 "sampling_rate": 16000,
120 "n_samples": 480_000,
121 "nb_max_frames": 3000,
122 "chunk_length": 30,
123}
124
125# From the pinned `generation_config.json`, and the ids `post::whisper` is written against.
126#
127# `no_timestamps_token_id` is the one to watch: it is part of the step-0 prompt, and dropping it
128# changes the output from plain text to `<|0.00|>`-style timestamped text. That is the same shape of
129# hazard as SMaLL-100's "the language token goes on the source side".
130DECODING = {
131 "decoder_start_token_id": 50258,
132 "eos_token_id": 50257,
133 "pad_token_id": 50257,
134 "no_timestamps_token_id": 50363,
135 "max_length": 448,
136 "is_multilingual": True,
137}
138
139# `task_to_id`, `lang_to_id` and the two suppression lists, checked by size and by spot value rather
140# than transcribed in full: 99 languages and 88 suppressed ids would be a list checked against
141# itself, but a list that changed *length* is a different model.
142DECODING_SIZES = {
143 "lang_to_id": 99,
144 "suppress_tokens": 88,
145 "begin_suppress_tokens": 2,
146}
147
148# Ids at or above this are special or timestamp tokens with no text form, and are not in
149# `vocab.json`. The same constant as `WhisperTokenizer.FIRST_SPECIAL_ID`.
150FIRST_SPECIAL_ID = 50_257
151
152
153def sha256(path):
154 digest = hashlib.sha256()
155 with open(path, "rb") as handle:
156 for block in iter(lambda: handle.read(1 << 20), b""):
157 digest.update(block)
158 return digest.hexdigest()
159
160
161def convert(script, *args):
162 """Run one of the sibling converters, letting its own output and exit code through.
163
164 `check=True` matters: `maml_convert.py` exits non-zero when a layer table digest does not match,
165 and that is the check that must stop an asset being written from the wrong checkpoint.
166 """
167 subprocess.run([sys.executable, os.path.join(HERE, script), *args], check=True, cwd=ROOT)
168
169
170def check_json(path, expected, label):
171 """Fail if `path` does not hold every key of `expected` with that value."""
172 held = json.load(open(path, encoding="utf-8"))
173 wrong = {k: (held.get(k), v) for k, v in expected.items() if held.get(k) != v}
174 if wrong:
175 lines = "\n".join(f" {k}: {got!r} against {want!r}" for k, (got, want) in wrong.items())
176 raise SystemExit(
177 f"{path} is not the {label} the runtime hardcodes:\n{lines}\n"
178 "Re-read it and check the Rust and Kotlin still match before re-pinning."
179 )
180 print(f"{os.path.basename(path)} matches {len(expected)} hardcoded {label} constants")
181 return held
182
183
184def check_decoding(path):
185 held = check_json(path, DECODING, "decoding")
186 wrong = {}
187 for key, count in DECODING_SIZES.items():
188 got = len(held.get(key) or [])
189 if got != count:
190 wrong[key] = (got, count)
191 # `transcribe` rather than `translate`: this is a recogniser, and the two ids are adjacent, so
192 # reading one for the other is a one-digit mistake that produces English for every language.
193 tasks = held.get("task_to_id") or {}
194 if tasks.get("transcribe") != 50359:
195 wrong["task_to_id.transcribe"] = (tasks.get("transcribe"), 50359)
196 if wrong:
197 lines = "\n".join(f" {k}: {got!r} against {want!r}" for k, (got, want) in wrong.items())
198 raise SystemExit(f"{path}'s decoding tables moved:\n{lines}")
199 print(f"generation_config.json has {DECODING_SIZES['lang_to_id']} languages and "
200 f"{DECODING_SIZES['suppress_tokens']} suppressed ids")
201 return held
202
203
204def check_bundled_vocabulary(upstream, bundled):
205 """Fail unless the shipped `vocab.json` is the same token table as `upstream`'s.
206
207 Not a digest comparison: the two mirrors serialise the same map differently — one key per line
208 against compact — so the bytes differ and the meaning does not. What `WhisperTokenizer` reads is
209 the token for each id below [`FIRST_SPECIAL_ID`], so that is what is compared.
210
211 This is the only provenance the bundled table has ever had. The script this replaces pinned the
212 digest of `onnx-community/whisper-base`'s copy, which said the bytes had not changed without
213 saying they were right.
214 """
215 if not os.path.isfile(bundled):
216 raise SystemExit(f"{bundled} is missing; it ships beside the model and is not rebuilt here")
217 want = json.load(open(upstream, encoding="utf-8"))
218 got = json.load(open(bundled, encoding="utf-8"))
219
220 def table(mapping):
221 out = [None] * FIRST_SPECIAL_ID
222 for token, index in mapping.items():
223 if 0 <= index < FIRST_SPECIAL_ID:
224 out[index] = token
225 return out
226
227 a, b = table(want), table(got)
228 differing = [index for index in range(FIRST_SPECIAL_ID) if a[index] != b[index]]
229 missing = [index for index in range(FIRST_SPECIAL_ID) if b[index] is None]
230 if differing or missing:
231 raise SystemExit(
232 f"{bundled} is not {REPO}'s token table:\n"
233 f" {len(differing)} ids differ, first {differing[:6]}\n"
234 f" {len(missing)} ids absent, first {missing[:6]}\n"
235 "A wrong token table produces wrong text rather than an error."
236 )
237 print(f"the bundled vocab.json agrees with {REPO} on all {FIRST_SPECIAL_ID} text ids")
238
239
240def check_bundled_generation(upstream, bundled):
241 """Fail unless the shipped `generation_config.json` decodes the same way as `upstream`'s.
242
243 Every field `post::whisper` reads, plus the three tables, compared by value. The bundled copy also
244 carries a `trust_remote_code` key upstream's does not, which nothing reads and which is therefore
245 not compared.
246 """
247 if not os.path.isfile(bundled):
248 raise SystemExit(f"{bundled} is missing; it ships beside the model and is not rebuilt here")
249 want = json.load(open(upstream, encoding="utf-8"))
250 got = json.load(open(bundled, encoding="utf-8"))
251 keys = list(DECODING) + list(DECODING_SIZES) + ["task_to_id"]
252 wrong = {k: (got.get(k), want.get(k)) for k in keys if got.get(k) != want.get(k)}
253 if wrong:
254 lines = "\n".join(f" {k}: bundled {g!r} against upstream {w!r}" for k, (g, w) in wrong.items())
255 raise SystemExit(f"{bundled} is not {REPO}'s generation config:\n{lines}")
256 print(f"the bundled generation_config.json agrees with {REPO} on all {len(keys)} decoding fields")
257
258
259def main():
260 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
261 parser.add_argument("--work", help="where to keep the checkpoint (default: a temp directory)")
262 parser.add_argument("-o", "--out", default=OUT, help="where to write the assets")
263 parser.add_argument(
264 "--print-digests",
265 action="store_true",
266 help="print the fetched files' SHA-256 instead of checking them, to re-pin after a bump",
267 )
268 args = parser.parse_args()
269
270 try:
271 from huggingface_hub import snapshot_download
272 except ImportError:
273 raise SystemExit("needs huggingface_hub: python -m pip install huggingface_hub")
274
275 work = args.work or os.path.join(tempfile.gettempdir(), "whisper")
276 local = snapshot_download(
277 repo_id=REPO, revision=REVISION, allow_patterns=list(DIGESTS), local_dir=work
278 )
279 print(f"{REPO}@{REVISION[:12]} in {local}")
280
281 if args.print_digests:
282 for name in DIGESTS:
283 print(f' {name}: "{sha256(os.path.join(local, name))}",')
284 return 0
285
286 for name, expected in DIGESTS.items():
287 got = sha256(os.path.join(local, name))
288 if got != expected:
289 raise SystemExit(
290 f"{name}\n sha256 {got}\n pinned {expected}\n"
291 "The upstream checkpoint changed. Re-read it, check the Rust forward pass still\n"
292 "matches, then re-pin with --print-digests."
293 )
294 print(f"{len(DIGESTS)} upstream digests match")
295 check_json(os.path.join(local, CONFIG), ARCHITECTURE, "architecture")
296 check_json(os.path.join(local, PREPROCESSOR), FEATURES, "mel front end")
297 check_decoding(os.path.join(local, GENERATION))
298
299 os.makedirs(args.out, exist_ok=True)
300 graph = os.path.join(args.out, "whisper_base.maml")
301 convert("maml_convert.py", os.path.join(local, CHECKPOINT), "--graph", "whisper", "-o", graph)
302 # Checked rather than rewritten. See the module docstring.
303 check_bundled_vocabulary(os.path.join(local, VOCAB), os.path.join(args.out, VOCAB))
304 check_bundled_generation(
305 os.path.join(local, GENERATION), os.path.join(args.out, GENERATION)
306 )
307
308 print(f"\n{args.out}")
309 for name in sorted(os.listdir(args.out)):
310 path = os.path.join(args.out, name)
311 if os.path.isfile(path):
312 size = os.path.getsize(path)
313 print(f" {name}: {size} bytes ({size / (1 << 20):.1f} MiB) {sha256(path)}")
314 return 0
315
316
317if __name__ == "__main__":
318 raise SystemExit(main())