Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / nnfp_reference.py
nnfp_reference.py177 lines · 7.0 KiBRaw
| 1 | """Reference values for `library/ml/src/main/rust/src/microfrontend.rs`'s tests. |
| 2 | |
| 3 | Independently written: this computes the log-mel pipeline from the formulas in |
| 4 | `detector/ARCHITECTURE.md` using numpy's FFT, with no reference to the Rust. It prints a |
| 5 | Rust test module, which is pasted into `microfrontend.rs` rather than read at test time so |
| 6 | that `cargo test` needs no fixture file. |
| 7 | |
| 8 | python scripts/ml/nnfp_reference.py <path to music_detector.sound_model> |
| 9 | """ |
| 10 | |
| 11 | import sys |
| 12 | |
| 13 | import numpy as np |
| 14 | from tflite.Model import Model |
| 15 | |
| 16 | F32 = np.float32 |
| 17 | SAMPLE_RATE, FFT_SIZE, CHANNELS = 16000, 512, 32 |
| 18 | WINDOW, HOP, WINDOW_BITS = 400, 160, 12 |
| 19 | LOWER, UPPER, CORRECTION, CEILING = 60.0, 3800.0, 3, 15.0 |
| 20 | # The fixed-point kissfft the device uses halves at each radix-2 stage, so its forward |
| 21 | # transform carries a 1/N. See `Config::fft_gain` in microfrontend.rs. |
| 22 | FFT_GAIN = 1.0 / FFT_SIZE |
| 23 | FRAMES = 40 |
| 24 | |
| 25 | |
| 26 | def mel(hz): |
| 27 | return F32(F32(1127.0) * F32(np.log1p(F32(F32(hz) / F32(700.0))))) |
| 28 | |
| 29 | |
| 30 | def hann(): |
| 31 | i = np.arange(WINDOW) |
| 32 | return np.floor((0.5 - 0.5 * np.cos(2 * np.pi * (i + 0.5) / WINDOW)) * (1 << WINDOW_BITS) + 0.5) |
| 33 | |
| 34 | |
| 35 | def breakpoints(): |
| 36 | hz_per_bin = F32(F32(SAMPLE_RATE) / F32(FFT_SIZE)) |
| 37 | low, high = mel(LOWER), mel(UPPER) |
| 38 | spacing = F32((high - low) / F32(CHANNELS + 1)) |
| 39 | centres = [F32(low + spacing * F32(c + 1)) for c in range(CHANNELS + 1)] |
| 40 | start = int(1.5 + LOWER / float(hz_per_bin)) |
| 41 | end = start |
| 42 | while mel(end * float(hz_per_bin)) <= high: |
| 43 | end += 1 |
| 44 | widths = [0] * (CHANNELS + 1) |
| 45 | weights, unweights = [], [] |
| 46 | band = 0 |
| 47 | for b in range(start, end): |
| 48 | here = mel(b * float(hz_per_bin)) |
| 49 | while band < CHANNELS and here > centres[band]: |
| 50 | band += 1 |
| 51 | rising = F32((centres[band] - here) / spacing) |
| 52 | weights.append(int(F32(rising) * (1 << WINDOW_BITS))) |
| 53 | unweights.append(int(F32(F32(1.0) - rising) * (1 << WINDOW_BITS))) |
| 54 | widths[band] += 1 |
| 55 | starts, at = [], start |
| 56 | for width in widths: |
| 57 | starts.append(at) |
| 58 | at += width |
| 59 | return widths, starts, weights, unweights, start, end |
| 60 | |
| 61 | |
| 62 | def synthetic(count): |
| 63 | """A deterministic i16 signal both sides can produce bit-identically. |
| 64 | |
| 65 | Integer only, on purpose: a sine would go through `sin`, and a one-ulp difference between |
| 66 | numpy's and Rust's would round a sample differently and make the comparison meaningless. |
| 67 | A square wave at 16000/36 Hz gives a strong fundamental and odd harmonics across the band, |
| 68 | and the linear-congruential noise keeps every mel channel occupied. The amplitudes are |
| 69 | chosen to land the log-mel values inside 0..CEILING rather than pinned to the clamp, so |
| 70 | that the comparison actually tests the arithmetic. |
| 71 | """ |
| 72 | out = np.zeros(count, dtype=np.int64) |
| 73 | seed = 12345 |
| 74 | for n in range(count): |
| 75 | seed = (seed * 1664525 + 1013904223) & 0xFFFFFFFF |
| 76 | noise = ((seed >> 16) & 0x1FF) - 256 |
| 77 | square = 900 if (n // 18) % 2 == 0 else -900 |
| 78 | out[n] = max(-32768, min(32767, square + noise)) |
| 79 | return out.astype(np.int16) |
| 80 | |
| 81 | |
| 82 | def log_mel(pcm, window, widths, starts, weights, unweights, first, last): |
| 83 | frames = [] |
| 84 | at = 0 |
| 85 | while at + WINDOW <= len(pcm): |
| 86 | block = pcm[at : at + WINDOW].astype(np.int64) |
| 87 | # `>>` on a negative in Rust is arithmetic, which is a floor. numpy's is too. |
| 88 | windowed = (block * window.astype(np.int64)) >> WINDOW_BITS |
| 89 | padded = np.zeros(FFT_SIZE) |
| 90 | padded[:WINDOW] = windowed |
| 91 | spectrum = np.fft.rfft(padded) * FFT_GAIN |
| 92 | power = np.zeros(FFT_SIZE // 2 + 1) |
| 93 | power[first:last] = np.abs(spectrum[first:last]) ** 2 |
| 94 | rising = np.zeros(len(widths)) |
| 95 | falling = np.zeros(len(widths)) |
| 96 | j = 0 |
| 97 | for band, width in enumerate(widths): |
| 98 | bins = power[starts[band] : starts[band] + width] |
| 99 | rising[band] = np.dot(np.array(weights[j : j + width], dtype=float), bins) |
| 100 | falling[band] = np.dot(np.array(unweights[j : j + width], dtype=float), bins) |
| 101 | j += width |
| 102 | frame = [] |
| 103 | for c in range(CHANNELS): |
| 104 | energy = rising[c + 1] + falling[c] |
| 105 | value = np.log((1 << CORRECTION) * np.sqrt(energy)) if energy > 0 else -np.inf |
| 106 | frame.append(float(np.clip(value, 0.0, CEILING))) |
| 107 | frames.append(frame) |
| 108 | at += HOP |
| 109 | return frames |
| 110 | |
| 111 | |
| 112 | def model_tables(path): |
| 113 | raw = open(path, "rb").read() |
| 114 | offset = 0 if raw[4:8] == b"TFL3" else raw.find(b"TFL3") - 4 |
| 115 | model = Model.GetRootAsModel(raw[offset:], 0) |
| 116 | graph = model.Subgraphs(2) |
| 117 | out = {} |
| 118 | for index in (1, 2, 3, 4, 5, 6): |
| 119 | tensor = graph.Tensors(index) |
| 120 | buffer = model.Buffers(tensor.Buffer()) |
| 121 | out[index] = np.frombuffer(buffer.DataAsNumpy().tobytes(), dtype=np.int16) |
| 122 | return out |
| 123 | |
| 124 | |
| 125 | def rust_slice(name, kind, values, per_line=12): |
| 126 | body = "" |
| 127 | for start in range(0, len(values), per_line): |
| 128 | row = ", ".join(str(int(v)) for v in values[start : start + per_line]) |
| 129 | body += f" {row},\n" |
| 130 | return f" const {name}: [{kind}; {len(values)}] = [\n{body} ];\n" |
| 131 | |
| 132 | |
| 133 | def main(): |
| 134 | if len(sys.argv) != 2: |
| 135 | raise SystemExit(__doc__) |
| 136 | tables = model_tables(sys.argv[1]) |
| 137 | window = hann() |
| 138 | widths, starts, weights, unweights, first, last = breakpoints() |
| 139 | |
| 140 | for label, mine, theirs in [ |
| 141 | ("window", window, tables[1]), |
| 142 | ("widths", widths, tables[2]), |
| 143 | ("weight_starts", np.cumsum([0] + widths[:-1]), tables[3]), |
| 144 | ("freq_starts", starts, tables[4]), |
| 145 | ("unweights", unweights, tables[5]), |
| 146 | ("weights", weights, tables[6]), |
| 147 | ]: |
| 148 | same = np.array_equal(np.array(mine, dtype=np.int64), theirs.astype(np.int64)) |
| 149 | print(f"# {label:14s} reproduces the model exactly: {same}", file=sys.stderr) |
| 150 | if not same: |
| 151 | raise SystemExit(f"{label} does not match the shipped tensor") |
| 152 | |
| 153 | samples = WINDOW + HOP * (FRAMES - 1) |
| 154 | pcm = synthetic(samples) |
| 155 | frames = log_mel(pcm, window, widths, starts, weights, unweights, first, last) |
| 156 | print(f"# {len(frames)} frames from {samples} samples", file=sys.stderr) |
| 157 | |
| 158 | probes = [0, 1, 19, FRAMES - 1] |
| 159 | print(" // Generated by scripts/ml/nnfp_reference.py; see its docstring.") |
| 160 | print(rust_slice("MODEL_WINDOW", "i32", tables[1])) |
| 161 | print(rust_slice("MODEL_WIDTHS", "u16", tables[2], 16)) |
| 162 | print(rust_slice("MODEL_FREQ_STARTS", "u16", tables[4], 16)) |
| 163 | print(rust_slice("MODEL_UNWEIGHTS", "u16", tables[5], 12)) |
| 164 | print(rust_slice("MODEL_WEIGHTS", "u16", tables[6], 12)) |
| 165 | print(f" const PROBE_FRAMES: [usize; {len(probes)}] = {list(probes)};".replace("[", "[").replace("]", "]")) |
| 166 | flat = [v for p in probes for v in frames[p]] |
| 167 | body = "" |
| 168 | for start in range(0, len(flat), 6): |
| 169 | # Nine significant digits: f32 carries about seven, so the printed value is not what |
| 170 | # limits the comparison. At six the fixture's own rounding dominated the residual. |
| 171 | row = ", ".join(f"{v:.9}" for v in flat[start : start + 6]) |
| 172 | body += f" {row},\n" |
| 173 | print(f" const PROBE_LOG_MEL: [f32; {len(flat)}] = [\n{body} ];") |
| 174 | |
| 175 | |
| 176 | if __name__ == "__main__": |
| 177 | main() |