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

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

gemma4_audio_parity.py246 lines · 10.7 KiBRaw
1#!/usr/bin/env python3
2"""Golden for `library/ml/src/main/rust/src/logmel.rs`: what the real Gemma 4 extractor says.
3
4Drives `Gemma4AudioFeatureExtractor._extract_spectrogram` — the shipped one, from
5site-packages, not a reimplementation — over three reproducible signals and prints a Rust test
6module. The constants are pasted into `logmel.rs` rather than read at test time so that
7`cargo test` needs no fixture file, which is the arrangement `scripts/ml/nnfp_reference.py`
8already uses for `microfrontend.rs`.
9
10 python scripts/ml/gemma4_audio_parity.py
11
12# The signals are generated on both sides, not carried
13
14Same idea as `gemma4_vision_parity.py`: `tone` and `noise_burst` below are duplicated verbatim
15in `logmel.rs`'s tests, so the golden holds only the *output*. Both are quantised to i16 before
16scaling, so the two sides agree bit for bit rather than to within whatever `sin` does.
17
18The pure tone is the load-bearing case. A 440 Hz tone lands on mel channel 24 and on *linear*
19bin 7, and the two are so far apart that any disagreement between the window, the transform and
20the filter bank about what a frequency is shows up as a peak in the wrong place rather than as a
21small residual. The noise burst is broadband and half silence, so it covers the mel floor and
22the frames that straddle the onset. Silence needs no golden: every value is `ln(1e-3)`.
23
24# Importing transformers on this machine
25
26`import transformers` fails a huggingface-hub version check (needs >=1.5.0, found 1.4.1), so
27the package `__init__` is bypassed: `transformers` is registered as a bare module object with a
28`__path__` and a `__version__`, and the feature extractor's file is loaded straight off disk.
29Everything the extractor actually touches — `audio_utils`, `feature_extraction_utils` — then
30imports normally. Nothing about the numbers is stubbed, so this is the reference itself.
31"""
32import importlib.metadata
33import importlib.util
34import math
35import os
36import sys
37import types
38
39import numpy as np
40
41TRANSFORMERS = os.path.join(
42 os.path.expanduser("~"), "AppData", "Roaming", "Python", "Python312",
43 "site-packages", "transformers",
44)
45SAMPLE_RATE = 16000
46MELS = 128
47HOP = 160
48# `__call__`'s own defaults, and the units are the trap: `pad_to_multiple_of` counts SAMPLES,
49# not mel frames. Read as frames it gives 3072 and a downstream T of 768 instead of 750.
50MAX_SAMPLES = 480_000
51PAD_MULTIPLE = 128
52
53
54def load_extractor():
55 """The shipped `Gemma4AudioFeatureExtractor`, with the package `__init__` stepped around."""
56 root = os.environ.get("TRANSFORMERS_DIR", TRANSFORMERS)
57 if not os.path.isdir(root):
58 raise SystemExit(f"no transformers at {root}; set TRANSFORMERS_DIR")
59 for name, path in [
60 ("transformers", root),
61 ("transformers.models", os.path.join(root, "models")),
62 ("transformers.models.gemma4", os.path.join(root, "models", "gemma4")),
63 ]:
64 if name not in sys.modules:
65 module = types.ModuleType(name)
66 module.__path__ = [path]
67 module.__package__ = name
68 sys.modules[name] = module
69 sys.modules["transformers"].__version__ = importlib.metadata.version("transformers")
70 target = os.path.join(root, "models", "gemma4", "feature_extraction_gemma4.py")
71 spec = importlib.util.spec_from_file_location(
72 "transformers.models.gemma4.feature_extraction_gemma4", target
73 )
74 module = importlib.util.module_from_spec(spec)
75 sys.modules[spec.name] = module
76 spec.loader.exec_module(module)
77 return module.Gemma4AudioFeatureExtractor()
78
79
80def tone(count, hz, amplitude):
81 """`amplitude * sin(2 pi hz t)` at 16 kHz, quantised to i16 and scaled to `-1..1`.
82
83 `floor(x + 0.5)` rather than `round`, because numpy rounds halves to even and Rust rounds
84 them away from zero. Must stay identical to `tone` in `logmel.rs`.
85 """
86 out = np.zeros(count, dtype=np.float32)
87 for i in range(count):
88 value = amplitude * math.sin(math.tau * hz * i / SAMPLE_RATE)
89 out[i] = max(-32768, min(32767, math.floor(value + 0.5))) / 32768.0
90 return out
91
92
93def noise_burst(count):
94 """Full-scale hashed noise over the middle half, silence either side.
95
96 Integer only, so both sides produce identical samples. Must stay identical to `noise_burst`
97 in `logmel.rs`.
98 """
99 mask = 0xFFFFFFFF
100 out = np.zeros(count, dtype=np.float32)
101 for i in range(count):
102 if not count // 4 <= i < 3 * count // 4:
103 continue
104 h = (i * 73_856_093) & mask
105 h ^= h >> 13
106 h = (h * 1_274_126_177) & mask
107 h ^= h >> 16
108 out[i] = ((h & 0xFFFF) - 32768) / 32768.0
109 return out
110
111
112def spectrogram(extractor, waveform):
113 """`_extract_spectrogram` on one whole waveform, `[frames, 128]` in f64."""
114 mask = np.ones(len(waveform), dtype=np.int64)
115 mel, _ = extractor._extract_spectrogram(waveform.astype(np.float32), mask)
116 return mel
117
118
119def rust_floats(name, values, per_line=6):
120 body = ""
121 for start in range(0, len(values), per_line):
122 # Nine significant digits: f32 carries about seven, so the printed value is not what
123 # limits the comparison.
124 row = ", ".join(f"{v:.9}" for v in values[start : start + per_line])
125 body += f" {row},\n"
126 return f" const {name}: [f32; {len(values)}] = [\n{body} ];\n"
127
128
129def mask_rows(extractor, lengths):
130 """`(real, padded, total, valid)` per length, from the real `__call__` end to end.
131
132 This is the caller's side of the contract rather than the front end's: `__call__` truncates
133 at `MAX_SAMPLES`, zero-pads up to a multiple of `PAD_MULTIPLE` SAMPLES, and returns a mask
134 marking which mel rows came entirely from real audio. `logmel.rs` does none of that, so the
135 point of measuring it here is to pin the arithmetic the caller needs:
136
137 total = frame_count(padded) valid = frame_count(min(real, MAX_SAMPLES))
138
139 Note the waveform is passed as a LIST. Handing `__call__` a bare 1-D array trips a squeeze
140 on `_extract_spectrogram`'s batch axis in this version and raises for every length but 1.
141 """
142 rows = []
143 for real in lengths:
144 out = extractor([np.zeros(real, dtype=np.float32)])
145 total = np.asarray(out["input_features"][0]).shape[0]
146 valid = int(np.asarray(out["input_features_mask"][0]).sum())
147 padded = min(MAX_SAMPLES, -(-real // PAD_MULTIPLE) * PAD_MULTIPLE)
148 rows.append((real, padded, total, valid))
149 return rows
150
151
152def probes(name, frames):
153 """Which frames to carry, chosen per case so that every one of them measures something.
154
155 The tone is steady, so frame 0 (the only one the left pad reaches into) and the last frame
156 are the only ones that differ from the middle. The burst is not: it runs from sample 1250 to
157 3750, so frame 0 is silence, frame 8 straddles the onset, 15 is inside it and 24 straddles
158 the end. Probing 0, 1, mid and last there would have put three of the four in silence, which
159 is a comparison of two floors.
160 """
161 rows = {"TONE": [0, 1, frames // 2, frames - 1], "NOISE": [0, 8, 15, 24]}[name]
162 if max(rows) >= frames:
163 raise SystemExit(f"{name}: probe {max(rows)} past the {frames} frames it has")
164 return rows
165
166
167def main():
168 extractor = load_extractor()
169 if (extractor.frame_length, extractor.hop_length, extractor.fft_length) != (320, 160, 512):
170 raise SystemExit("the reference defaults have moved; re-derive the spec")
171 print(
172 f"# transformers {sys.modules['transformers'].__version__}: frame"
173 f" {extractor.frame_length}, hop {extractor.hop_length}, fft {extractor.fft_length},"
174 f" filters {extractor.mel_filters.shape}",
175 file=sys.stderr,
176 )
177
178 # Every count comes from the reference actually running, not from the formula. The
179 # 321-vs-320 unfold is exactly the kind of thing that is right in the formula and wrong in
180 # the code, or the other way round.
181 #
182 # 480000 is the reference's own `max_length`, 30 s, and it is here because the whole audio
183 # track's shapes rest on it: 480000 samples -> 2999 mel frames -> T = 750 after the two
184 # stride-2 convolutions of the subsample projection. It costs a second to run and it is the
185 # one length a wrong answer would propagate furthest from.
186 lengths = [0, 160, 161, 320, 321, 480, 481, 1000, 4000, 5000, 8000, 16000, 480000]
187 counts = [
188 spectrogram(extractor, np.zeros(length, dtype=np.float32)).shape[0] for length in lengths
189 ]
190 print(f"# frames from {lengths}: {counts}", file=sys.stderr)
191
192 mask_table = mask_rows(
193 extractor, [1, 160, 161, 500, 1000, 4000, 5000, 20000, 479999, 480000, 480001]
194 )
195 for real, padded, total, valid in mask_table:
196 print(f"# {real} real -> {padded} padded -> {total} rows, {valid} valid", file=sys.stderr)
197
198 cases = [
199 ("TONE", tone(8000, 440.0, 8192.0)),
200 ("NOISE", noise_burst(5000)),
201 ]
202 blocks = []
203 for name, waveform in cases:
204 mel = spectrogram(extractor, waveform)
205 rows = probes(name, mel.shape[0])
206 print(
207 f"# {name}: {len(waveform)} samples -> {mel.shape[0]} frames,"
208 f" probing {rows}, range {mel.min():.4f}..{mel.max():.4f}",
209 file=sys.stderr,
210 )
211 blocks.append(f" const REF_{name}_ROWS: [usize; {len(rows)}] = {rows};")
212 blocks.append(rust_floats(f"REF_{name}", [v for r in rows for v in mel[r]]))
213
214 # The argmax of a pure tone's first full frame, which is the one number that says the whole
215 # chain agrees about what a frequency is.
216 peaks = {}
217 for hz in (440.0, 3000.0):
218 mel = spectrogram(extractor, tone(8000, hz, 8192.0))
219 peaks[hz] = int(np.argmax(mel[10]))
220 linear = int(round(hz / 8000.0 * (MELS - 1)))
221 print(f"# {hz:.0f} Hz peaks at mel channel {peaks[hz]} (linear would be {linear})",
222 file=sys.stderr)
223
224 # The bank on its own, so a disagreement can be pinned on it or ruled out without the FFT.
225 sums = extractor.mel_filters.sum(axis=0)
226 print(f"# filter columns: {int((sums > 0).sum())} of {MELS} non-empty", file=sys.stderr)
227
228 print(" // Generated by scripts/ml/gemma4_audio_parity.py; see its docstring.")
229 print(
230 " const REF_FRAME_LENGTHS: [usize; "
231 f"{len(lengths)}] = [\n {', '.join(str(v) for v in lengths)},\n ];"
232 )
233 print(f" const REF_FRAME_COUNTS: [usize; {len(counts)}] = {counts};")
234 body = "".join(f" ({r}, {p}, {t}, {v}),\n" for r, p, t, v in mask_table)
235 print(
236 f" const REF_MASK_ROWS: [(usize, usize, usize, usize); {len(mask_table)}] = [\n{body} ];"
237 )
238 print(rust_floats("REF_FILTER_SUMS", [float(v) for v in sums], 6))
239 print(f" const REF_TONE_PEAKS: [(f32, usize); 2] = [(440.0, {peaks[440.0]}),"
240 f" (3000.0, {peaks[3000.0]})];")
241 for block in blocks:
242 print(block)
243
244
245if __name__ == "__main__":
246 main()