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

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

maml_precision_eval.py229 lines · 8.9 KiBRaw
1#!/usr/bin/env python3
2"""What a lower precision does to whisper's and Supertonic's *outputs*, on the shipped weights.
3
4`quant_task_eval.py` answers this for the ONNX-sourced graphs by running onnxruntime twice.
5Whisper and Supertonic have no usable ONNX in the tree — whisper is a checkpoint and Supertonic
6is heavily folded before conversion — so this takes the other route: rewrite the shipped
7`.maml` with requantised weights and run **the Rust reference interpreter** over both.
8
9That is a stronger measurement than the onnxruntime one in two ways: it is the exact forward
10pass the device runs, and it is the exact weights that ship. It is slower, which is why the
11other script exists.
12
13# How a lower precision is simulated without a new dtype
14
15There is no int4 or int6 in the `.maml` format and this does not add one. A tensor is
16dequantised, rounded to the target width's grid, and then re-encoded in **its original dtype** —
17an int8 slot stays int8, an fp16 slot stays fp16. The values carry the coarser grid; the
18container does not change. So the layout, the tensor count and every offset are untouched, and
19the Rust net loads it without knowing anything happened.
20
21Re-encoding int4 values into an int8 slot is near-lossless: 15 levels inside the same absmax
22are all representable in 255, so what is measured is the int4 rounding and not the round trip.
23
24 python scripts/ml/maml_precision_eval.py --graph whisper --bits 6
25"""
26
27import argparse
28import json
29import os
30import struct
31import subprocess
32import sys
33
34import numpy as np
35
36HERE = os.path.dirname(os.path.abspath(__file__))
37ROOT = os.path.dirname(os.path.dirname(HERE))
38sys.path.insert(0, HERE)
39
40import maml_convert # noqa: E402
41import maml_survey # noqa: E402
42
43# The graphs `reference.rs::dump_reference_output` can drive, with the asset each reads and the
44# input it expects. `PARITY_WIDTH` means different things per graph; these are the values
45# `onnx_parity.py` uses.
46GRAPHS = {
47 "whisper": {
48 "asset": "speech/src/main/assets/whisper-base/whisper_base.maml",
49 "shape": (1, 80, 3000),
50 "width": 3000,
51 "what": "encoder hidden states over a 30s window",
52 },
53 "supertonic_voc": {
54 "asset": "speech/src/main/assets/supertonic/supertonic_voc.maml",
55 "shape": (144, 64),
56 "width": 64,
57 "what": "waveform samples",
58 },
59}
60
61
62def read_maml(path):
63 """`(header, entries, data)` for a `.maml`, with entries as mutable lists."""
64 with open(path, "rb") as handle:
65 blob = handle.read()
66 if blob[:4] != b"MAML":
67 raise SystemExit(f"{path} is not a .maml")
68 count = struct.unpack("<I", blob[12:16])[0]
69 at = maml_survey.HEADER_BYTES
70 entries = []
71 for _ in range(count):
72 rank = struct.unpack("<I", blob[at:at + 4])[0]
73 dims = list(struct.unpack("<4I", blob[at + 4:at + 20]))[:rank]
74 dtype, offset, numel = struct.unpack("<III", blob[at + 20:at + 32])
75 entries.append({"dims": dims, "dtype": dtype, "offset": offset, "numel": numel})
76 at += maml_survey.ENTRY_BYTES
77 return blob[:at], entries, bytearray(blob[at:])
78
79
80def requantised_copy(path, out_path, bits):
81 """Write `path` to `out_path` with every eligible weight rounded to `bits`, dtype preserved."""
82 header, entries, data = read_maml(path)
83
84 def load(entry):
85 if entry["dtype"] == maml_survey.DTYPE_I8:
86 raw = data[entry["offset"]:entry["offset"] + entry["numel"]]
87 return np.frombuffer(bytes(raw), dtype=np.int8).astype(np.float32)
88 raw = data[entry["offset"]:entry["offset"] + entry["numel"] * 2]
89 return np.frombuffer(bytes(raw), dtype=np.float16).astype(np.float32)
90
91 limit = float(2 ** (bits - 1) - 1)
92 touched = 0
93 worst = 1.0
94 for index, entry in enumerate(entries):
95 dims = entry["dims"]
96 if not maml_survey.quantisable(dims, entry["numel"]):
97 continue
98 values = load(entry)
99 if entry["dtype"] == maml_survey.DTYPE_I8:
100 following = entries[index + 1]
101 if following["numel"] != dims[0]:
102 raise SystemExit(f"tensor {index} is int8 but is not followed by its scale")
103 scale = load(following)
104 values = (values.reshape(dims[0], -1) * scale[:, None]).ravel()
105 rows = values.reshape(dims[0], -1)
106
107 absmax = np.abs(rows).max(axis=1)
108 grid = np.where(absmax > 0, absmax / limit, 1.0).astype(np.float32)
109 codes = np.clip(
110 np.floor(np.abs(rows) / grid[:, None] + 0.5) * np.sign(rows), -limit, limit
111 )
112 rounded = codes * grid.astype(np.float16).astype(np.float32)[:, None]
113 cosine = float(
114 np.dot(rows.ravel(), rounded.ravel())
115 / max(np.linalg.norm(rows) * np.linalg.norm(rounded), 1e-30)
116 )
117 worst = min(worst, cosine)
118 touched += 1
119
120 # Back into the slot it came from, in the dtype it came in.
121 if entry["dtype"] == maml_survey.DTYPE_I8:
122 kernel, scale = maml_convert.quantise_per_channel(rounded.reshape(dims))
123 data[entry["offset"]:entry["offset"] + entry["numel"]] = kernel.astype(
124 np.int8
125 ).tobytes()
126 following = entries[index + 1]
127 data[following["offset"]:following["offset"] + following["numel"] * 2] = (
128 scale.astype(np.float16).tobytes()
129 )
130 else:
131 data[entry["offset"]:entry["offset"] + entry["numel"] * 2] = (
132 rounded.astype(np.float16).tobytes()
133 )
134
135 with open(out_path, "wb") as handle:
136 handle.write(header)
137 handle.write(data)
138 return touched, worst
139
140
141def build_reference_binary():
142 crate = os.path.join(ROOT, "library", "ml", "src", "main", "rust")
143 finished = subprocess.run(
144 [
145 "cargo", "test", "--release", "-p", "modelrunner", "--lib",
146 "--no-run", "--message-format=json",
147 ],
148 check=True, cwd=crate, capture_output=True, text=True,
149 )
150 for line in finished.stdout.splitlines():
151 try:
152 message = json.loads(line)
153 except json.JSONDecodeError:
154 continue
155 if (
156 message.get("reason") == "compiler-artifact"
157 and message.get("executable")
158 and message.get("target", {}).get("name") == "modelrunner"
159 ):
160 return message["executable"]
161 raise SystemExit("cargo did not report a test binary")
162
163
164def run_reference(binary, work, graph, maml, width):
165 written = os.path.join(work, "reference.f32")
166 if os.path.exists(written):
167 os.remove(written)
168 subprocess.run(
169 [binary, "dump_reference_output", "--ignored", "--nocapture"],
170 check=True,
171 env=dict(
172 os.environ,
173 PARITY_DIR=work,
174 PARITY_GRAPH=graph,
175 PARITY_WIDTH=str(width),
176 PARITY_MAML=os.path.abspath(maml),
177 ),
178 )
179 if not os.path.exists(written):
180 raise SystemExit("the reference wrote nothing; the test filter matched nothing")
181 return np.fromfile(written, dtype=np.float32)
182
183
184def main():
185 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
186 parser.add_argument("--graph", required=True, choices=sorted(GRAPHS))
187 parser.add_argument("--bits", type=int, required=True, choices=[4, 5, 6])
188 parser.add_argument("--work", default=os.path.join(ROOT, "build", "precision"))
189 args = parser.parse_args()
190
191 spec = GRAPHS[args.graph]
192 asset = os.path.join(ROOT, spec["asset"])
193 work = os.path.abspath(args.work)
194 os.makedirs(work, exist_ok=True)
195
196 # A deterministic ramp, as `onnx_parity.py` uses: what matters is that both runs see
197 # identical bytes, not that the input is realistic.
198 total = int(np.prod(spec["shape"]))
199 feed = (np.arange(total, dtype=np.float32) % 255.0) / 255.0 - 0.5
200 feed.tofile(os.path.join(work, "input.f32"))
201
202 low_path = os.path.join(work, f"{args.graph}_int{args.bits}.maml")
203 touched, worst = requantised_copy(asset, low_path, args.bits)
204 print(
205 f"{args.graph}: int{args.bits}, {touched} tensors rounded, "
206 f"worst weight cosine {worst:.6f}"
207 )
208
209 binary = build_reference_binary()
210 reference = run_reference(binary, work, args.graph, asset, spec["width"])
211 low = run_reference(binary, work, args.graph, low_path, spec["width"])
212 if reference.size != low.size:
213 raise SystemExit(f"{reference.size} against {low.size} values")
214
215 spread = float(reference.max() - reference.min())
216 correlation = float(np.corrcoef(reference, low)[0, 1])
217 deviation = float(np.abs(reference - low).max())
218 rms = float(np.sqrt(np.mean((reference - low) ** 2)))
219 signal = float(np.sqrt(np.mean(reference**2)))
220 snr = 20.0 * np.log10(signal / rms) if rms > 0 else float("inf")
221 print(f" {spec['what']}: {reference.size} values")
222 print(f" correlation {correlation:.6f}")
223 print(f" worst deviation {deviation:.5f} ({100 * deviation / spread:.2f}% of range)")
224 print(f" error SNR {snr:.1f} dB")
225 return 0
226
227
228if __name__ == "__main__":
229 raise SystemExit(main())