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

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

maml_survey.py369 lines · 14.6 KiBRaw
1#!/usr/bin/env python3
2"""What is already int8 in the shipped `.maml` assets, and what quantising the rest would cost.
3
4A survey, not a converter. It reads each file's tensor table, reports how many bytes sit in
5int8 kernels against how many are still fp16, and then simulates per-output-channel int8 on
6every fp16 tensor that could take it — so a decision about quantising anything further starts
7from the file rather than from a guess about it.
8
9The simulation reads fp16 and quantises *that*, where a real conversion would read the fp32
10export. That is very slightly pessimistic and needs no re-fetch of anything.
11
12**These are upper bounds, and two of them were measured wrong.** Two corrections found by
13running the real converter against the fp32 ONNX:
14
15* **It ignores what the runtime refuses.** A convolution feeding a `PRelu` cannot be int8 (the
16 slope wants the push offset the scale occupies), nor can a `ConvTranspose`, nor a padded
17 convolution in an edge-padded graph. This file cannot see any of that — it sees weights.
18 For `mobilefacenet`, a PReLU architecture, that is the difference between the 3.2 MiB
19 predicted here and the 0.76 MiB actually available: only 15 of its 49 convolutions qualify.
20* **It reads fp16, not fp32.** The shipped weights have already been rounded once, so
21 quantising them is measurably kinder than quantising the export. `u2netp`'s worst tensor
22 reads 0.99929 here and 0.998891 from the fp32 ONNX — which is the wrong side of the gate.
23
24So treat a green row as "worth measuring properly", never as "worth shipping". The honest
25number for any graph comes from running `maml_convert.py` with it in `INT8_GRAPHS`.
26
27 python scripts/ml/maml_survey.py
28"""
29
30import argparse
31import glob
32import os
33import struct
34import sys
35
36import numpy as np
37
38sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
39
40import maml_convert # noqa: E402
41
42HERE = os.path.dirname(os.path.abspath(__file__))
43ROOT = os.path.dirname(os.path.dirname(HERE))
44
45# `weights.rs`: MAGIC, then version/graph/count, a 64-byte header, then 32-byte table entries.
46HEADER_BYTES = 64
47ENTRY_BYTES = 32
48DTYPE_I8 = 1
49
50# Every bundled asset, by the directory each app keeps it in.
51PATTERNS = (
52 "camera/src/main/assets/*.maml",
53 "photos/src/main/assets/*.maml",
54 "photos/src/main/assets/clip/*.maml",
55 "library/ocr/src/main/assets/*.maml",
56 "speech/src/main/assets/supertonic/*.maml",
57 "speech/src/main/assets/whisper-base/*.maml",
58 "games/chess/src/main/assets/*.maml",
59)
60
61
62def quantisable(dims, numel):
63 """Whether a tensor is the kind a converter would quantise.
64
65 Rank 2 or more and an output axis worth having a scale per: convolution kernels and
66 embedding tables. Norms, biases and per-channel scales are rank 1 and stay fp16 in every
67 graph here — they are a rounding error of the file and a scale has nowhere to live.
68
69 Deliberately **no size floor**. An earlier version of this skipped tensors under 4096
70 elements on the grounds that their saving is negligible, and it therefore reported
71 `supertonic_ttl` as passing comfortably — when the whole reason that graph is fp16 is one
72 small tensor that quantises at 0.99212. The saving is negligible; the veto is not.
73 """
74 return len(dims) >= 2 and dims[0] > 1
75
76
77# Below this a tensor is counted in the fidelity check but not in the reported saving, because
78# one byte per weight of a 1 KiB tensor is not why anyone would do this work.
79WORTH_SAVING = 4096
80
81
82def survey(path):
83 with open(path, "rb") as handle:
84 blob = handle.read()
85 if blob[:4] != b"MAML":
86 raise SystemExit(f"{path} is not a .maml")
87 _version, graph, count = struct.unpack("<III", blob[4:16])
88
89 at = HEADER_BYTES
90 entries = []
91 for _ in range(count):
92 rank = struct.unpack("<I", blob[at:at + 4])[0]
93 dims = struct.unpack("<4I", blob[at + 4:at + 20])[:rank]
94 dtype, offset, numel = struct.unpack("<III", blob[at + 20:at + 32])
95 entries.append((dims, dtype, offset, numel))
96 at += ENTRY_BYTES
97 data = blob[at:]
98
99 int8_tensors = int8_bytes = fp16_tensors = fp16_bytes = 0
100 # What an int8 pass over the remaining fp16 would save, and what it would cost in fidelity.
101 savable = 0
102 worst = (1.0, None)
103 failing = []
104 largest = []
105 for dims, dtype, offset, numel in entries:
106 if dtype == DTYPE_I8:
107 int8_tensors += 1
108 int8_bytes += numel
109 largest.append((numel, "int8", dims))
110 continue
111 fp16_tensors += 1
112 fp16_bytes += numel * 2
113 largest.append((numel * 2, "fp16", dims))
114 if not quantisable(dims, numel):
115 continue
116 raw = data[offset:offset + numel * 2]
117 weight = np.frombuffer(raw, dtype=np.float16).astype(np.float32).reshape(dims)
118 kernel, scale = maml_convert.quantise_per_channel(weight)
119 back = kernel.astype(np.float32).reshape(dims[0], -1) * scale[:, None]
120 flat = weight.reshape(dims[0], -1)
121 cosine = float(
122 np.dot(flat.ravel(), back.ravel())
123 / max(np.linalg.norm(flat) * np.linalg.norm(back), 1e-30)
124 )
125 if cosine < worst[0]:
126 worst = (cosine, list(dims))
127 if cosine < maml_convert.MIN_INT8_COSINE:
128 failing.append((cosine, list(dims)))
129 # One byte instead of two, plus an fp16 scale per output channel.
130 if numel >= WORTH_SAVING:
131 savable += numel * 2 - (numel + dims[0] * 2)
132
133 largest.sort(reverse=True)
134 return {
135 "graph": graph,
136 "size": len(blob),
137 "int8_tensors": int8_tensors,
138 "int8_bytes": int8_bytes,
139 "fp16_tensors": fp16_tensors,
140 "fp16_bytes": fp16_bytes,
141 "savable": savable,
142 "worst": worst,
143 "failing": failing,
144 "largest": largest[:3],
145 }
146
147
148def weights_in(path):
149 """Every weight tensor in `path` as float, whatever it is stored as.
150
151 An int8 kernel is returned multiplied by the fp16 per-output-channel scale that follows it,
152 so a graph that is already quantised can be screened at a lower precision on the same
153 footing as one that is not. That reconstruction is what the shaders do, so it is the right
154 starting point — it is one quantisation removed from the fp32 export, which makes this
155 slightly pessimistic for the already-int8 graphs and is fine for a screen.
156
157 Yields `(dims, values, stored)` and skips the scale tensors it has consumed.
158 """
159 with open(path, "rb") as handle:
160 blob = handle.read()
161 if blob[:4] != b"MAML":
162 raise SystemExit(f"{path} is not a .maml")
163 _version, _graph, count = struct.unpack("<III", blob[4:16])
164
165 at = HEADER_BYTES
166 entries = []
167 for _ in range(count):
168 rank = struct.unpack("<I", blob[at:at + 4])[0]
169 dims = struct.unpack("<4I", blob[at + 4:at + 20])[:rank]
170 dtype, offset, numel = struct.unpack("<III", blob[at + 20:at + 32])
171 entries.append((dims, dtype, offset, numel))
172 at += ENTRY_BYTES
173 data = blob[at:]
174
175 def read(index):
176 dims, dtype, offset, numel = entries[index]
177 if dtype == DTYPE_I8:
178 return np.frombuffer(data[offset:offset + numel], dtype=np.int8).astype(np.float32)
179 return np.frombuffer(data[offset:offset + numel * 2], dtype=np.float16).astype(np.float32)
180
181 skip = set()
182 for index, (dims, dtype, _offset, numel) in enumerate(entries):
183 if index in skip:
184 continue
185 values = read(index)
186 if dtype == DTYPE_I8:
187 # The scale is the tensor after the kernel, one entry per output channel.
188 following = entries[index + 1] if index + 1 < len(entries) else None
189 if following is None or following[3] != dims[0]:
190 raise SystemExit(f"{path}: int8 tensor {index} is not followed by its scale")
191 scale = read(index + 1)
192 values = (values.reshape(dims[0], -1) * scale[:, None]).ravel()
193 skip.add(index + 1)
194 yield dims, values.reshape(dims), "int8" if dtype == DTYPE_I8 else "fp16"
195
196
197def screen(path, bits, group):
198 """`(before, after, worst, failures)` for re-quantising everything in `path` at `bits`."""
199 before = os.path.getsize(path)
200 packed = 0
201 other = 0
202 worst = (1.0, None)
203 failures = 0
204 considered = 0
205 for dims, values, _stored in weights_in(path):
206 if not quantisable(dims, values.size):
207 other += values.size * 2
208 continue
209 rows = values.reshape(dims[0], -1)
210 width = rows.shape[1]
211 span = width if not group else min(group, width)
212 rebuilt = np.empty_like(rows)
213 spans = 0
214 limit = float(2 ** (bits - 1) - 1)
215 for start in range(0, width, span):
216 block = rows[:, start:start + span]
217 absmax = np.abs(block).max(axis=1)
218 scale = np.where(absmax > 0, absmax / limit, 1.0).astype(np.float32)
219 codes = np.clip(
220 np.floor(np.abs(block) / scale[:, None] + 0.5) * np.sign(block), -limit, limit
221 )
222 scale = scale.astype(np.float16).astype(np.float32)
223 rebuilt[:, start:start + span] = codes * scale[:, None]
224 spans += 1
225 cosine = float(
226 np.dot(rows.ravel(), rebuilt.ravel())
227 / max(np.linalg.norm(rows) * np.linalg.norm(rebuilt), 1e-30)
228 )
229 considered += 1
230 if cosine < worst[0]:
231 worst = (cosine, list(dims))
232 if cosine < maml_convert.MIN_INT8_COSINE:
233 failures += 1
234 packed += int(np.ceil(values.size * bits / 8.0)) + dims[0] * spans * 2
235 return before, packed + other, worst, failures, considered
236
237
238def run_screen(paths, bits, group):
239 grouping = "per output channel" if not group else f"per {group} weights"
240 print(f"int{bits}, {grouping}, screened against each file's own weights\n")
241 header = f"{'asset':34s} {'now':>7s} {'int%d' % bits:>7s} {'saved':>7s} {'worst cos':>10s} {'fails':>6s}"
242 print(header)
243 print("-" * len(header))
244 total_before = total_after = 0
245 for path in paths:
246 before, after, worst, failures, considered = screen(path, bits, group)
247 total_before += before
248 total_after += after
249 flag = "" if failures == 0 else f"{failures}/{considered}"
250 print(
251 f"{os.path.basename(path):34s} {before / (1 << 20):7.1f} {after / (1 << 20):7.1f} "
252 f"{(before - after) / (1 << 20):7.1f} {worst[0]:10.5f} {flag:>6s}"
253 )
254 print()
255 print(
256 f"total {total_before / (1 << 20):.1f} -> {total_after / (1 << 20):.1f} MiB, "
257 f"saving {(total_before - total_after) / (1 << 20):.1f} MiB"
258 )
259 print(f"'fails' counts tensors under the {maml_convert.MIN_INT8_COSINE} gate.")
260 print()
261 print(
262 "Cosine is a screen, not a verdict. Maia's int4 passed nothing like this bar and still\n"
263 "changed 1 move in 9; a graph that looks fine here still needs a task-level check."
264 )
265 return 0
266
267
268def main():
269 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
270 parser.add_argument(
271 "--bits",
272 type=int,
273 default=0,
274 choices=[0, 2, 3, 4, 5, 6],
275 help="screen re-quantising everything at this width instead of reporting int8 headroom",
276 )
277 parser.add_argument(
278 "--group",
279 type=int,
280 default=0,
281 help="weights per scale within an output row; 0 means one scale for the whole row",
282 )
283 args = parser.parse_args()
284
285 paths = []
286 for pattern in PATTERNS:
287 paths.extend(sorted(glob.glob(os.path.join(ROOT, pattern))))
288 if not paths:
289 raise SystemExit("no .maml assets found; run the fetch scripts first")
290
291 if args.bits:
292 return run_screen(paths, args.bits, args.group)
293
294 header = (
295 f"{'asset':34s} {'MiB':>6s} {'after':>6s} {'int8 t':>6s} {'fp16 t':>6s} "
296 f"{'fp16 MiB':>9s} {'worst cos':>12s}"
297 )
298 print(header)
299 print("-" * len(header))
300 total_fp16 = 0
301 total_size = 0
302 total_savable = 0
303 rows = []
304 for path in paths:
305 found = survey(path)
306 total_fp16 += found["fp16_bytes"]
307 total_size += found["size"]
308 total_savable += found["savable"]
309 rows.append((found["savable"], os.path.basename(path), found))
310 cosine, _dims = found["worst"]
311 gate = maml_convert.MIN_INT8_COSINE
312 if cosine == 1.0:
313 verdict = "n/a"
314 else:
315 verdict = f"{cosine:.5f}" + ("" if cosine >= gate else " FAIL")
316 print(
317 f"{os.path.basename(path):34s} {found['size'] / (1 << 20):6.1f} "
318 f"{(found['size'] - found['savable']) / (1 << 20):6.1f} "
319 f"{found['int8_tensors']:6d} {found['fp16_tensors']:6d} "
320 f"{found['fp16_bytes'] / (1 << 20):9.1f} {verdict:>12s}"
321 )
322
323 print()
324 for _savable, name, found in sorted(rows, reverse=True):
325 if not found["failing"]:
326 continue
327 print(f"{name}: {len(found['failing'])} tensor(s) under the gate")
328 for cosine, dims in sorted(found["failing"])[:4]:
329 print(f" {cosine:.5f} {dims}")
330
331 print()
332 print(
333 f"{total_size / (1 << 20):.1f} MiB bundled, of which {total_fp16 / (1 << 20):.1f} MiB "
334 f"is fp16 ({100.0 * total_fp16 / total_size:.0f}%)"
335 )
336 print(
337 f"quantising every eligible fp16 tensor: "
338 f"{total_size / (1 << 20):.1f} -> {(total_size - total_savable) / (1 << 20):.1f} MiB, "
339 f"saving {total_savable / (1 << 20):.1f} MiB"
340 )
341 # The aggregate understates the per-model effect, because most of the bundle is already
342 # int8: a graph that has not been quantised yet does roughly halve, and a graph that has
343 # been cannot move. Reporting both stops the total from reading as "not worth it".
344 untouched = [(n, f) for _s, n, f in rows if f["int8_tensors"] == 0]
345 if untouched:
346 before = sum(f["size"] for _n, f in untouched)
347 after = sum(f["size"] - f["savable"] for _n, f in untouched)
348 print(
349 f"of which the {len(untouched)} graphs with no int8 at all: "
350 f"{before / (1 << 20):.1f} -> {after / (1 << 20):.1f} MiB "
351 f"({100.0 * (before - after) / before:.0f}% off)"
352 )
353 print(f"'FAIL' marks a file holding a tensor under the {maml_convert.MIN_INT8_COSINE} gate.")
354 print()
355 print("where the remaining saving is:")
356 rows.sort(reverse=True)
357 for savable, name, found in rows[:5]:
358 if savable < (1 << 20):
359 continue
360 print(f" {name} ({savable / (1 << 20):.1f} MiB)")
361 for size, kind, dims in found["largest"]:
362 if kind != "fp16" or size < (1 << 18):
363 continue
364 print(f" {size / (1 << 20):7.2f} MiB {list(dims)}")
365 return 0
366
367
368if __name__ == "__main__":
369 sys.exit(main())