Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / gate_reference.py
gate_reference.py340 lines · 13.6 KiBRaw
| 1 | """Extract Google's music-detection gate and generate its Rust test fixtures. |
| 2 | |
| 3 | The gate is `music_detector.sound_model` subgraph 3: the always-on, 8,200-parameter |
| 4 | classifier that answers "is this music?" once per 10 ms hop. It is a different network |
| 5 | from `sound_model_2`, the 172,576-parameter fingerprinter that `nnfp_reference.py` |
| 6 | covers, and the two are not interchangeable. |
| 7 | |
| 8 | Two jobs, both driven off the same parse so they cannot disagree: |
| 9 | |
| 10 | 1. Write `library/ml/src/main/rust/src/gate.bin` - the ordered weight blob that |
| 11 | `gate.rs` embeds. Every quantization scale in `gate.rs` is asserted against the |
| 12 | flatbuffer here, so a wrong constant fails this script rather than silently |
| 13 | producing wrong scores. |
| 14 | |
| 15 | 2. Print a Rust `#[cfg(test)]` fixture module to stdout. The reference forward pass |
| 16 | below is written from `detector/ARCHITECTURE.md` section 3 in numpy float64 and |
| 17 | shares no code with the Rust; pasting its output into `gate.rs` pins the port |
| 18 | against an independently-written implementation, which is the same arrangement |
| 19 | `nnfp_reference.py` has with `microfrontend.rs`. |
| 20 | |
| 21 | Usage: |
| 22 | |
| 23 | python scripts/ml/gate_reference.py <path to music_detector.sound_model> |
| 24 | |
| 25 | Add `--no-write` to print the fixtures without touching `gate.bin`. |
| 26 | """ |
| 27 | |
| 28 | import pathlib |
| 29 | import sys |
| 30 | |
| 31 | import numpy as np |
| 32 | from tflite.Model import Model |
| 33 | |
| 34 | GATE_SUBGRAPH = 3 |
| 35 | |
| 36 | # Quantization, from ARCHITECTURE.md section 3.3. Asserted against the model below, so |
| 37 | # this table is a check on the flatbuffer and on `gate.rs`, not a second source of truth. |
| 38 | INPUT_SCALE = 0.000625 # i16 log-mel, == 1/1600, FilterBankLog's output_scale |
| 39 | FEATURE_SCALE = 0.05882353 # i8 after QUANTIZE |
| 40 | FEATURE_ZERO = -128 |
| 41 | LOGIT_SCALE = 0.078431375 # i8 FC2 output |
| 42 | LOGIT_ZERO = -1 |
| 43 | SCORE_SCALE = 0.0006103702 # i16 handed to the latching classifier |
| 44 | SCORE_ZERO = 16383 |
| 45 | |
| 46 | # Per-block (depthwise out, pointwise out) activation scales and zero points, in op order. |
| 47 | BLOCK_QUANT = [ |
| 48 | ((0.09264124, 0), (0.041850865, 0)), |
| 49 | ((0.0057760403, 0), (0.031403266, -1)), |
| 50 | ((0.00901962, 0), (0.029606337, 0)), |
| 51 | ((0.0073377984, 0), (0.024098465, 0)), |
| 52 | ((0.011312435, 0), (0.025132196, 0)), |
| 53 | ((0.010261553, 0), (0.020659184, 0)), |
| 54 | ] |
| 55 | FC1_QUANT = (0.026163183, -1) |
| 56 | |
| 57 | CHANNELS = 32 |
| 58 | TAPS = 4 |
| 59 | BLOCKS = 6 |
| 60 | HEAD_FRAMES = 5 # the last circular buffer is 5 deep, not 4 |
| 61 | HIDDEN = 8 |
| 62 | |
| 63 | |
| 64 | def load(path): |
| 65 | """Return the gate subgraph and the model it belongs to.""" |
| 66 | raw = pathlib.Path(path).read_bytes() |
| 67 | offset = 0 if raw[4:8] == b"TFL3" else raw.find(b"TFL3") - 4 |
| 68 | model = Model.GetRootAsModel(raw[offset:], 0) |
| 69 | if model.SubgraphsLength() <= GATE_SUBGRAPH: |
| 70 | raise SystemExit(f"{path} has {model.SubgraphsLength()} subgraphs, not a sound_model") |
| 71 | return model, model.Subgraphs(GATE_SUBGRAPH) |
| 72 | |
| 73 | |
| 74 | def constant(model, graph, index, dtype): |
| 75 | tensor = graph.Tensors(index) |
| 76 | data = model.Buffers(tensor.Buffer()).DataAsNumpy() |
| 77 | if isinstance(data, int) or data.size == 0: |
| 78 | raise SystemExit(f"t{index} is not a constant") |
| 79 | return np.frombuffer(data.tobytes(), dtype=dtype).astype(np.int64) |
| 80 | |
| 81 | |
| 82 | def quant(graph, index): |
| 83 | q = graph.Tensors(index).Quantization() |
| 84 | scale = float(q.ScaleAsNumpy()[0]) |
| 85 | zero = int(q.ZeroPointAsNumpy()[0]) if q.ZeroPointLength() else 0 |
| 86 | return scale, zero |
| 87 | |
| 88 | |
| 89 | def close(got, want, what): |
| 90 | """ARCHITECTURE.md prints scales to ~8 digits; the model stores full float32.""" |
| 91 | if abs(got - want) > 1e-6 * max(1.0, abs(want)): |
| 92 | raise SystemExit(f"{what}: model says {got!r}, the table says {want!r}") |
| 93 | |
| 94 | |
| 95 | def parse(model, graph): |
| 96 | """Pull the twelve convolutions and two dense layers out in execution order. |
| 97 | |
| 98 | Read structurally - operand 1 of each op is its weights and operand 2 its bias - |
| 99 | rather than by the tensor indices in ARCHITECTURE.md, so a re-export that renumbers |
| 100 | tensors still works and a change of topology fails loudly. |
| 101 | """ |
| 102 | codes = [] |
| 103 | for i in range(model.OperatorCodesLength()): |
| 104 | code = model.OperatorCodes(i) |
| 105 | custom = code.CustomCode() |
| 106 | codes.append(custom.decode() if custom else code.BuiltinCode()) |
| 107 | |
| 108 | layers = [] |
| 109 | for i in range(graph.OperatorsLength()): |
| 110 | op = graph.Operators(i) |
| 111 | kind = codes[op.OpcodeIndex()] |
| 112 | if kind not in (3, 4, 9): # CONV_2D, DEPTHWISE_CONV_2D, FULLY_CONNECTED |
| 113 | continue |
| 114 | weights, bias = op.Inputs(1), op.Inputs(2) |
| 115 | layers.append((kind, weights, bias, op.Outputs(0))) |
| 116 | |
| 117 | expected = [4, 3] * BLOCKS + [9, 9] |
| 118 | if [k for k, _, _, _ in layers] != expected: |
| 119 | raise SystemExit(f"unexpected op sequence {[k for k, _, _, _ in layers]}") |
| 120 | return layers |
| 121 | |
| 122 | |
| 123 | def extract(model, graph, layers): |
| 124 | """Weights and biases in blob order, with every scale checked.""" |
| 125 | close(quant(graph, graph.Inputs(0))[0], INPUT_SCALE, "input scale") |
| 126 | tensors = [] |
| 127 | |
| 128 | for block in range(BLOCKS): |
| 129 | depthwise, pointwise = layers[block * 2], layers[block * 2 + 1] |
| 130 | (dw_scale, dw_zero), (pw_scale, pw_zero) = BLOCK_QUANT[block] |
| 131 | close(quant(graph, depthwise[3])[0], dw_scale, f"block {block} depthwise scale") |
| 132 | close(quant(graph, depthwise[3])[1], dw_zero, f"block {block} depthwise zero point") |
| 133 | close(quant(graph, pointwise[3])[0], pw_scale, f"block {block} pointwise scale") |
| 134 | close(quant(graph, pointwise[3])[1], pw_zero, f"block {block} pointwise zero point") |
| 135 | for kind, weights, bias, _ in (depthwise, pointwise): |
| 136 | shape = [ |
| 137 | graph.Tensors(weights).Shape(j) |
| 138 | for j in range(graph.Tensors(weights).ShapeLength()) |
| 139 | ] |
| 140 | want = [1, TAPS, 1, CHANNELS] if kind == 4 else [CHANNELS, 1, 1, CHANNELS] |
| 141 | if shape != want: |
| 142 | raise SystemExit(f"block {block} kernel is {shape}, not {want}") |
| 143 | tensors.append(("i8", constant(model, graph, weights, np.int8))) |
| 144 | tensors.append(("i32", constant(model, graph, bias, np.int32))) |
| 145 | |
| 146 | fc1, fc2 = layers[-2], layers[-1] |
| 147 | close(quant(graph, fc1[3])[0], FC1_QUANT[0], "fc1 scale") |
| 148 | close(quant(graph, fc1[3])[1], FC1_QUANT[1], "fc1 zero point") |
| 149 | close(quant(graph, fc2[3])[0], LOGIT_SCALE, "logit scale") |
| 150 | close(quant(graph, fc2[3])[1], LOGIT_ZERO, "logit zero point") |
| 151 | for _, weights, bias, _ in (fc1, fc2): |
| 152 | tensors.append(("i8", constant(model, graph, weights, np.int8))) |
| 153 | tensors.append(("i32", constant(model, graph, bias, np.int32))) |
| 154 | |
| 155 | return tensors |
| 156 | |
| 157 | |
| 158 | def weight_scales(graph, layers): |
| 159 | return [quant(graph, weights)[0] for _, weights, _, _ in layers] |
| 160 | |
| 161 | |
| 162 | def blob(tensors): |
| 163 | out = bytearray() |
| 164 | for dtype, values in tensors: |
| 165 | if dtype == "i8": |
| 166 | out += values.astype(np.int8).tobytes() |
| 167 | else: |
| 168 | out += values.astype(np.int32).tobytes() |
| 169 | return bytes(out) |
| 170 | |
| 171 | |
| 172 | # --- reference forward pass ------------------------------------------------------- |
| 173 | # float64 throughout, written from ARCHITECTURE.md section 3.1. The accumulators are |
| 174 | # exact integers; only the requantization multiply is floating point, which is what |
| 175 | # TFLite's own reference kernels do. |
| 176 | |
| 177 | |
| 178 | def requantize(acc, multiplier, zero, relu): |
| 179 | """Integer accumulator to int8, TFLite's affine requantization. |
| 180 | |
| 181 | Rounds half away from zero, which is what TFLite's `MultiplyByQuantizedMultiplier` |
| 182 | does and what Rust's `f64::round` does, so the two sides agree on ties. |
| 183 | """ |
| 184 | x = np.asarray(acc, dtype=np.float64) * multiplier |
| 185 | q = np.sign(x) * np.floor(np.abs(x) + 0.5) + zero |
| 186 | return np.clip(q, zero if relu else -128, 127).astype(np.int64) |
| 187 | |
| 188 | |
| 189 | class Reference: |
| 190 | def __init__(self, tensors, scales, activations): |
| 191 | self.scales = scales |
| 192 | self.activations = activations |
| 193 | self.w = [] |
| 194 | for i in range(BLOCKS): |
| 195 | dw = tensors[i * 4 + 0][1].reshape(TAPS, CHANNELS) |
| 196 | dwb = tensors[i * 4 + 1][1] |
| 197 | pw = tensors[i * 4 + 2][1].reshape(CHANNELS, CHANNELS) |
| 198 | pwb = tensors[i * 4 + 3][1] |
| 199 | self.w.append((dw, dwb, pw, pwb)) |
| 200 | self.fc1 = tensors[24][1].reshape(HIDDEN, HEAD_FRAMES * CHANNELS) |
| 201 | self.fc1b = tensors[25][1] |
| 202 | self.fc2 = tensors[26][1].reshape(1, HIDDEN) |
| 203 | self.fc2b = tensors[27][1] |
| 204 | self.reset() |
| 205 | |
| 206 | def reset(self): |
| 207 | # TFLM memsets a CIRCULAR_BUFFER's variable tensor to raw zero, not to the |
| 208 | # tensor's zero point, so a cold buffer decodes to `-zp * scale` rather than to |
| 209 | # silence. ARCHITECTURE.md section 3.2 records this as verified. It only shows |
| 210 | # up during the 23-frame warm-up, which `Gate` refuses to report. |
| 211 | self.buffers = [np.zeros((TAPS, CHANNELS), dtype=np.int64) for _ in range(BLOCKS)] |
| 212 | self.buffers.append(np.zeros((HEAD_FRAMES, CHANNELS), dtype=np.int64)) |
| 213 | |
| 214 | @staticmethod |
| 215 | def push(buffer, frame): |
| 216 | buffer[:-1] = buffer[1:] |
| 217 | buffer[-1] = frame |
| 218 | return buffer |
| 219 | |
| 220 | def score(self, logmel16): |
| 221 | """One i16 log-mel frame in, one i16 latching-classifier score out.""" |
| 222 | feature = np.asarray(logmel16, dtype=np.float64) * INPUT_SCALE / FEATURE_SCALE |
| 223 | feature = np.sign(feature) * np.floor(np.abs(feature) + 0.5) + FEATURE_ZERO |
| 224 | feature = np.clip(feature, -128, 127).astype(np.int64) |
| 225 | self.push(self.buffers[0], feature) |
| 226 | |
| 227 | in_scale, in_zero = FEATURE_SCALE, FEATURE_ZERO |
| 228 | for block in range(BLOCKS): |
| 229 | dw, dwb, pw, pwb = self.w[block] |
| 230 | (dw_scale, dw_zero) = self.activations[block * 2] |
| 231 | (pw_scale, pw_zero) = self.activations[block * 2 + 1] |
| 232 | buffer = self.buffers[block] |
| 233 | acc = ((buffer - in_zero) * dw).sum(axis=0) + dwb |
| 234 | multiplier = in_scale * self.scales[block * 2] / dw_scale |
| 235 | mid = requantize(acc, multiplier, dw_zero, relu=False) |
| 236 | |
| 237 | acc = (pw * (mid - dw_zero)).sum(axis=1) + pwb |
| 238 | multiplier = dw_scale * self.scales[block * 2 + 1] / pw_scale |
| 239 | out = requantize(acc, multiplier, pw_zero, relu=True) |
| 240 | |
| 241 | self.push(self.buffers[block + 1], out) |
| 242 | in_scale, in_zero = pw_scale, pw_zero |
| 243 | |
| 244 | fc1_scale, fc1_zero = self.activations[12] |
| 245 | logit_scale, logit_zero = self.activations[13] |
| 246 | flat = self.buffers[-1].reshape(-1) |
| 247 | acc = (self.fc1 * (flat - in_zero)).sum(axis=1) + self.fc1b |
| 248 | multiplier = in_scale * self.scales[12] / fc1_scale |
| 249 | hidden = requantize(acc, multiplier, fc1_zero, relu=True) |
| 250 | |
| 251 | acc = (self.fc2 * (hidden - fc1_zero)).sum(axis=1) + self.fc2b |
| 252 | multiplier = fc1_scale * self.scales[13] / logit_scale |
| 253 | logit8 = requantize(acc, multiplier, logit_zero, relu=False) |
| 254 | |
| 255 | real = (logit8[0] - logit_zero) * logit_scale |
| 256 | q = real / SCORE_SCALE |
| 257 | q = int(np.sign(q) * np.floor(abs(q) + 0.5)) + SCORE_ZERO |
| 258 | return int(np.clip(q, -32768, 32767)) |
| 259 | |
| 260 | |
| 261 | def synthetic(frames): |
| 262 | """Deterministic i16 log-mel frames, integer-only so both sides agree bit for bit. |
| 263 | |
| 264 | Not real audio - a mel ridge that sweeps upward, plus LCG hiss, in `ln * 1600` units. |
| 265 | `gate.rs`'s test module reimplements this exactly, so only the resulting scores need |
| 266 | to be carried across as a fixture. Generating features rather than PCM keeps this |
| 267 | independent of the front end, which `microfrontend.rs` already pins separately. |
| 268 | """ |
| 269 | state = 0x2545F491 |
| 270 | out = [] |
| 271 | for t in range(frames): |
| 272 | row = [] |
| 273 | for c in range(CHANNELS): |
| 274 | state = (state * 1103515245 + 12345) & 0x7FFFFFFF |
| 275 | peak = (t * 3 + 7) % CHANNELS |
| 276 | ridge = max(0, 12 - 3 * abs(c - peak)) |
| 277 | row.append(int((ridge * 1600) + (state >> 20) % 1600)) |
| 278 | out.append(row) |
| 279 | return out |
| 280 | |
| 281 | |
| 282 | def rust_fixture(reference, frames): |
| 283 | reference.reset() |
| 284 | scores = [reference.score(frame) for frame in frames] |
| 285 | |
| 286 | lines = [] |
| 287 | for i in range(0, len(scores), 12): |
| 288 | lines.append(" " + " ".join(f"{v}," for v in scores[i : i + 12])) |
| 289 | body = "\n".join(lines) |
| 290 | return f""" /// The i16 score `synthetic()`'s first {len(scores)} frames produce, from the float64 |
| 291 | /// reference in `scripts/ml/gate_reference.py`. Bit-exact rather than approximate: |
| 292 | /// the accumulators are integers and both sides round halves away from zero. |
| 293 | #[rustfmt::skip] |
| 294 | const PROBE_SCORES: [i16; {len(scores)}] = [ |
| 295 | {body} |
| 296 | ]; |
| 297 | """ |
| 298 | |
| 299 | |
| 300 | def main(): |
| 301 | args = [a for a in sys.argv[1:] if not a.startswith("--")] |
| 302 | if len(args) != 1: |
| 303 | raise SystemExit(__doc__) |
| 304 | model, graph = load(args[0]) |
| 305 | layers = parse(model, graph) |
| 306 | tensors = extract(model, graph, layers) |
| 307 | scales = weight_scales(graph, layers) |
| 308 | |
| 309 | payload = blob(tensors) |
| 310 | i8 = sum(v.size for d, v in tensors if d == "i8") |
| 311 | i32 = sum(v.size for d, v in tensors if d == "i32") |
| 312 | if (i8, i32) != (8200, 393): |
| 313 | raise SystemExit(f"extracted {i8} weights and {i32} biases, expected 8200 and 393") |
| 314 | |
| 315 | if "--no-write" not in sys.argv: |
| 316 | out = ( |
| 317 | pathlib.Path(__file__).resolve().parents[2] |
| 318 | / "library/ml/src/main/rust/src/gate.bin" |
| 319 | ) |
| 320 | out.write_bytes(payload) |
| 321 | print(f"// wrote {out} ({len(payload)} bytes)", file=sys.stderr) |
| 322 | |
| 323 | activations = [quant(graph, out) for _, _, _, out in layers] |
| 324 | print("// Generated by scripts/ml/gate_reference.py. Do not edit by hand.") |
| 325 | print(" /// Weight scales, in blob order: dw/pw for each of the six blocks, then FC1, FC2.") |
| 326 | print(" const WEIGHT_SCALES: [f32; 14] = [") |
| 327 | print(" " + ", ".join(f"{s!r}" for s in scales)) |
| 328 | print(" ];") |
| 329 | print() |
| 330 | print(" /// Output scale and zero point of each of those fourteen layers.") |
| 331 | print(" const OUTPUT_QUANT: [(f32, i32); 14] = [") |
| 332 | for scale, zero in activations: |
| 333 | print(f" ({scale!r}, {zero}),") |
| 334 | print(" ];") |
| 335 | print() |
| 336 | print(rust_fixture(Reference(tensors, scales, activations), synthetic(40))) |
| 337 | |
| 338 | |
| 339 | if __name__ == "__main__": |
| 340 | main() |