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

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

onnx_parity.py410 lines · 19.1 KiBRaw
1#!/usr/bin/env python3
2"""Check a `.maml` forward pass against onnxruntime, numerically.
3
4Nothing else in this repo compares the *numbers* `:library:ml` produces against the export
5they came from. The per-op fixtures in `nets::reference` check each op against hand
6arithmetic, and the layer table digest checks that the shapes still line up, but neither
7notices a weight that is subtly wrong. Both bugs this script found were exactly that shape:
8
9* `ppocr_fold.py` folded a scalar affine into a **padded** convolution, which is only exact
10 at interior pixels. That biased the border of every feature map in both PP-OCRv5 models
11 and changed 5% of the shipped detection weights.
12* A fused QKV projection's bias `Add` became unreachable once its slices were rewritten, so
13 dead-code elimination removed it and all three projections got a zero bias. Every shape
14 check, the tensor count and the digest passed.
15
16So this exists, and is worth running whenever `ppocr_fold.py` or a net module changes.
17
18# How to run it
19
20 ./scripts/ml/fetch_and_convert.sh # produce the .maml first
21 python scripts/ml/onnx_parity.py <graph> <inference.onnx> [--width N]
22
23It writes a scratch directory, runs onnxruntime, then asks the Rust reference interpreter
24for the same tensor and reports the difference. `onnxruntime` is an extra dependency:
25
26 python -m pip install onnxruntime
27
28# What "agreeing" means
29
30`.maml` is fp16, so the two cannot agree exactly. The bar is that the difference is no
31larger than fp16 weight quantisation alone accounts for, which this script measures by
32running onnxruntime a second time with every weight rounded through fp16. A difference
33materially above that line is a bug, not precision.
34"""
35
36import argparse
37import os
38import subprocess
39import sys
40import tempfile
41
42import numpy as np
43import onnx
44import onnxruntime
45from onnx import numpy_helper
46
47# The tensor to compare per graph, and why it rather than the network's output.
48#
49# Detection ends in a sigmoid over a text-probability map, which on a synthetic input is
50# saturated to zero everywhere — comparing it would compare zeros. Its backbone output is
51# where all fourteen of its surviving affines live, so that is the informative tensor.
52PROBE = {
53 "ppocr_rec": None,
54 "ppocr_det": "p2o.pd_op.hardswish.23.0",
55 "supertonic_voc": None,
56 # The sentence encoder's output, before the CLS slice. The graph's own output is a single
57 # scalar, and a correlation over one value is not a number - this is where all but 25k of
58 # the parameters are, and it is `[64, T + 1]` so a structural error has nowhere to hide.
59 "supertonic_dp": "/sentence_encoder/Add_output_0",
60 # The graph's own output, which is the whole conditioning sequence.
61 "supertonic_ttl": None,
62 # `denoised_latent`, the graph's own output. That is a whole Euler step over both guidance
63 # branches, so the runtime side runs the plan twice - which is the point worth checking.
64 "supertonic_ve": None,
65 # TinyCLIP is two towers in one graph, so it appears twice: the key selects which one, and the
66 # runtime side branches on the same key.
67 #
68 # The probe is each projection's **raw output**, not the graph's `image_embeds`/`text_embeds` —
69 # `CLIPModel` L2-normalises those before returning them, and comparing unit vectors would hide a
70 # uniform scale error, which per-output-channel quantisation is exactly the kind of thing to
71 # produce. `ClipEmbedder.l2Normalize` does the normalisation on the host either way.
72 "tinyclip": "/visual_projection/MatMul_output_0",
73 "tinyclip_text": "/text_projection/MatMul_output_0",
74 # whisper's encoder, against the bundled int8 export it replaces. Its own output, which is the
75 # `[1500, 512]` hidden states the decoder cross-attends over — so the conv stem's stride, the
76 # position add and all six 1500-position attentions are inside it.
77 #
78 # Both sides are int8 here, quantised differently, so the "fp16 weights alone" bar below measures
79 # nothing useful for this graph: there is no fp32 ONNX for whisper. What a low correlation would
80 # mean is a structural error, which is what this is for.
81 "whisper": None,
82 # MODNet photographic portrait matting: the graph's own output, the 512x512
83 # alpha matte. Run with `--width 512` — the export is dynamic-shape and the
84 # Rust is lowered at SIZE=512, so any other width compares different grids.
85 # Pass the folded `.maml` via `--maml` (a runtime download, not a bundled
86 # asset at parity time).
87 "modnet": None,
88}
89
90# Graphs whose input is a latent rather than an image, and how wide it is. One that is a
91# module of a larger export also names its `first` node, and `onnx.utils.extract_model` cuts
92# the subgraph there so it can be run at all; the cut promotes that node's input to a graph
93# input, which is then fed random latents.
94SUBGRAPH = {
95 # A whole file, not a module: no `first`, so nothing is extracted. 144 latent channels.
96 "supertonic_voc": {"channels": 144},
97}
98
99# TinyCLIP's fixed input side, and the two special tokens `ClipTokenizer` brackets a query with.
100# 49,406 and 49,407 are the last two entries of the 49,408-word vocabulary, which is what makes the
101# export's `ArgMax` over `input_ids` find the end-of-text position.
102TINYCLIP_IMAGE = 224
103TINYCLIP_SOT = 49_406
104TINYCLIP_EOT = 49_407
105
106# whisper's fixed mel window: 80 bins over 3000 frames, which is 30 seconds at a 160-sample hop.
107WHISPER_MELS = 80
108WHISPER_FRAMES = 3000
109
110
111def ramp_image(channels, height, width):
112 """A deterministic `[1, c, h, w]` input, free of transcendentals so both sides read the same
113 bytes."""
114 count = channels * height * width
115 ramp = ((np.arange(count, dtype=np.int64) * 37) % 255).astype(np.float32) / 255.0 - 0.5
116 return ramp.reshape(1, channels, height, width)
117
118
119def rounded_to_fp16(model):
120 """`model` with every weight put through fp16, to measure quantisation on its own."""
121 clone = onnx.ModelProto()
122 clone.CopyFrom(model)
123 for node in clone.graph.node:
124 if node.op_type != "Constant":
125 continue
126 for attribute in node.attribute:
127 if attribute.name != "value":
128 continue
129 value = numpy_helper.to_array(attribute.t)
130 if value.dtype == np.float32 and value.size >= 8:
131 attribute.t.CopyFrom(
132 numpy_helper.from_array(
133 value.astype(np.float16).astype(np.float32), attribute.t.name
134 )
135 )
136 for initializer in clone.graph.initializer:
137 value = numpy_helper.to_array(initializer)
138 if value.dtype == np.float32 and value.size >= 8:
139 initializer.CopyFrom(
140 numpy_helper.from_array(
141 value.astype(np.float16).astype(np.float32), initializer.name
142 )
143 )
144 return clone
145
146
147def final_logits(model):
148 """The name of the tensor before a trailing `Softmax`, or the graph's own output.
149
150 `nets::ppocr_rec` deliberately does not run the classifier's softmax, so the comparable
151 tensor is its input.
152 """
153 outputs = {o.name for o in model.graph.output}
154 for node in model.graph.node:
155 if node.op_type == "Softmax" and node.output[0] in outputs:
156 return node.input[0]
157 return next(iter(outputs))
158
159
160def run(model, probe, x, feed=None):
161 session = onnxruntime.InferenceSession(
162 model.SerializeToString(), providers=["CPUExecutionProvider"]
163 )
164 names = [o.name for o in session.get_outputs()]
165 inputs = feed if feed is not None else {session.get_inputs()[0].name: x}
166 outputs = session.run(None, inputs)
167 return np.squeeze(np.asarray(outputs[names.index(probe)]))
168
169
170def main():
171 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
172 parser.add_argument("graph", choices=sorted(PROBE))
173 parser.add_argument("onnx")
174 parser.add_argument("--width", type=int, default=64)
175 parser.add_argument("--maml", help="the .maml, for a graph that is a runtime download")
176 parser.add_argument(
177 "--probe",
178 help="compare this tensor instead of the graph's usual one, for isolating a layer",
179 )
180 args = parser.parse_args()
181
182 onnxruntime.set_default_logger_severity(3)
183 model = onnx.load(args.onnx)
184 work = tempfile.mkdtemp(prefix="maml_parity_")
185
186 cut = SUBGRAPH.get(args.graph)
187 # A cut without a `first` is a whole-graph model that merely needs a non-image input
188 # shape - Supertonic ships its vocoder as its own file rather than as a module of a
189 # larger one, so there is nothing to extract.
190 if cut is not None and cut.get("first"):
191 model = extract(args.onnx, model, cut, work)
192 probe = args.probe or PROBE[args.graph] or final_logits(model)
193 if probe not in {o.name for o in model.graph.output}:
194 model.graph.output.append(
195 onnx.helper.make_tensor_value_info(probe, onnx.TensorProto.FLOAT, None)
196 )
197
198 feed = None
199 if cut is not None:
200 # Random latents, deterministic. These nets are not classifiers, so there is no
201 # "sensible" input; what matters is that both sides see the same one.
202 rng = np.random.default_rng(20240827)
203 x = rng.standard_normal((1, cut["channels"], args.width)).astype(np.float32)
204 if cut.get("ones"):
205 session_inputs = {i.name: i for i in model.graph.input}
206 mask = session_inputs[cut["ones"]]
207 rank = len(mask.type.tensor_type.shape.dim)
208 shape = [1] * (rank - 1) + [args.width]
209 feed = {
210 model.graph.input[0].name: x,
211 cut["ones"]: np.ones(shape, dtype=np.float32),
212 }
213 if cut.get("noise"):
214 # Two channels of already-scaled noise, written out for the runtime to read after
215 # the conditioning input.
216 draw = rng.standard_normal((1, 2, args.width)).astype(np.float32) * 0.8
217 feed[cut["noise"]] = draw
218 draw.tofile(os.path.join(work, "noise.f32"))
219 elif args.graph in ("supertonic_dp", "supertonic_ttl"):
220 # Character ids and a voice's style. The ids go past 2048, where fp16 stops holding
221 # every integer, so the runtime reads them as two lanes - which is the whole reason
222 # `embed_lanes` exists.
223 rng = np.random.default_rng(20240827)
224 ids = rng.integers(0, 8322, size=(1, args.width), dtype=np.int64)
225 if args.graph == "supertonic_dp":
226 # `[1, 8, 16]`, which flattens row-major to 128.
227 style = rng.standard_normal((1, 8, 16)).astype(np.float32)
228 feed = {"text_ids": ids, "style_dp": style}
229 else:
230 # `[1, 50, 256]` position-major, which the runtime reads transposed. Writing the
231 # transpose here is what the voice bundle will hold.
232 style = rng.standard_normal((1, 50, 256)).astype(np.float32)
233 feed = {"text_ids": ids, "style_ttl": style}
234 style = np.ascontiguousarray(style.reshape(50, 256).T)
235 feed["text_mask"] = np.ones((1, 1, args.width), dtype=np.float32)
236 x = ids.astype(np.float32)
237 style.tofile(os.path.join(work, "style.f32"))
238 elif args.graph == "supertonic_ve":
239 # A latent, a text conditioning and a voice. `--width` is the latent length; the text is
240 # deliberately a different length, because the rotary angles normalise each sequence by
241 # its own and a square case would hide a swap.
242 rng = np.random.default_rng(20240827)
243 chars = max(4, args.width // 2)
244 latent = rng.standard_normal((1, 144, args.width)).astype(np.float32)
245 text = rng.standard_normal((1, 256, chars)).astype(np.float32)
246 style = rng.standard_normal((1, 50, 256)).astype(np.float32)
247 feed = {
248 "noisy_latent": latent,
249 "text_emb": text,
250 "style_ttl": style,
251 "latent_mask": np.ones((1, 1, args.width), dtype=np.float32),
252 "text_mask": np.ones((1, 1, chars), dtype=np.float32),
253 "current_step": np.array([5.0], dtype=np.float32),
254 "total_step": np.array([16.0], dtype=np.float32),
255 }
256 x = latent
257 text.tofile(os.path.join(work, "text.f32"))
258 # Channel-major, which is how the runtime holds a sequence.
259 np.ascontiguousarray(style.reshape(50, 256).T).tofile(os.path.join(work, "style.f32"))
260 os.environ["PARITY_CHARS"] = str(chars)
261 elif args.graph in ("tinyclip", "tinyclip_text"):
262 # The export is one graph with three inputs, and every call needs all of them even though
263 # only one tower is read - which is exactly why `ClipEmbedder` passed a dummy for the other
264 # side. So both cases below feed pixels *and* ids, and differ only in which is meaningful.
265 #
266 # `attention_mask` is all ones, as `ClipEmbedder` sends: CLIP's text tower is causal and
267 # pools at the end-of-text position, so there is nothing for a padding mask to do.
268 pixels = ramp_image(3, TINYCLIP_IMAGE, TINYCLIP_IMAGE)
269 if args.graph == "tinyclip":
270 # The shortest possible prompt, so the text side is cheap and unread.
271 ids = np.array([[TINYCLIP_SOT, TINYCLIP_EOT]], dtype=np.int64)
272 x = pixels
273 else:
274 # A short query, `<|startoftext|>` then pieces then `<|endoftext|>`. The ids stop at the
275 # end-of-text token rather than padding to 77: the causal mask makes the pooled vector
276 # identical either way, and the runtime relies on that to run `eot + 1` positions.
277 rng = np.random.default_rng(20240827)
278 pieces = rng.integers(0, TINYCLIP_SOT, size=args.width, dtype=np.int64)
279 ids = np.concatenate(
280 [[TINYCLIP_SOT], pieces, [TINYCLIP_EOT]]
281 ).reshape(1, -1)
282 # The runtime reads these from `input.f32` as f32, which is exact: every id is under
283 # 49,408 and fp32 holds every integer to 2^24.
284 x = ids.astype(np.float32)
285 feed = {
286 "pixel_values": pixels,
287 "input_ids": ids,
288 "attention_mask": np.ones_like(ids),
289 }
290 elif args.graph == "whisper":
291 # The log-mel window, `[1, 80, 3000]`. A ramp rather than real audio: what matters is that
292 # both sides read identical bytes, and `WhisperFeatures` is tested against HuggingFace
293 # separately by `WhisperFeaturesTest`.
294 x = ramp_image(1, WHISPER_MELS, WHISPER_FRAMES).reshape(1, WHISPER_MELS, WHISPER_FRAMES)
295 feed = {"input_features": x}
296 else:
297 height = 48 if args.graph == "ppocr_rec" else args.width
298 x = ramp_image(3, height, args.width)
299 x.tofile(os.path.join(work, "input.f32"))
300
301 reference = run(model, probe, x, feed)
302 quantised = run(rounded_to_fp16(model), probe, x, feed)
303
304 environment = dict(os.environ, PARITY_DIR=work, PARITY_GRAPH=args.graph)
305 environment["PARITY_WIDTH"] = str(args.width)
306 if args.maml:
307 environment["PARITY_MAML"] = os.path.abspath(args.maml)
308 subprocess.run(
309 [
310 "cargo", "test", "--release", "-p", "modelrunner", "--lib",
311 "dump_reference_output", "--", "--ignored", "--nocapture",
312 ],
313 check=True,
314 env=environment,
315 )
316 got = np.fromfile(os.path.join(work, "reference.f32"), dtype=np.float32)
317
318 # The runtime writes `[c, h, w]`; reshape the ONNX tensor to match by element count.
319 want = np.ascontiguousarray(reference).flatten()
320 # Supertonic's sampler runs both classifier-free-guidance branches in one batch of two, so
321 # an *internal* probe of it has twice the runtime's element count. The conditional branch is
322 # the first half. The graph's own output is already combined, so this does not fire there.
323 if want.size == got.size * 2 and args.graph == "supertonic_ve":
324 want = want[: got.size]
325 quantised = np.ascontiguousarray(quantised).flatten()[: got.size]
326 if want.size != got.size:
327 raise SystemExit(f"{probe}: onnx has {want.size} values, the runtime {got.size}")
328 if args.graph == "ppocr_rec":
329 # `[1, T, 838]` against the runtime's class-major `[838, T]`.
330 want = np.ascontiguousarray(reference.T).flatten()
331 if args.graph == "whisper":
332 # `[1500, 512]` against the runtime's channel-major `[512, 1500]`.
333 want = np.ascontiguousarray(reference.T).flatten()
334 quantised = np.ascontiguousarray(np.squeeze(quantised).T).flatten()
335
336 def report(label, a, b):
337 d = np.abs(a - b)
338 print(
339 f" {label:28s} max {d.max():.6f} mean {d.mean():.7f} "
340 f"corr {np.corrcoef(a, b)[0, 1]:.8f}"
341 )
342
343 bound = np.ascontiguousarray(
344 quantised.T if args.graph == "ppocr_rec" else quantised
345 ).flatten()
346 # The tensor's own scale, because "max 0.008" means nothing on its own: the bar measures
347 # fp16 *weights* against fp32 activations, and this runtime holds activations in fp16 too,
348 # so a difference of order `eps * |tensor|` is the format rather than a bug.
349 print(
350 f"{args.graph} at {args.width} wide, tensor {probe}: "
351 f"|values| max {np.abs(want).max():.4f}"
352 )
353 report("fp16 weights alone (the bar)", want, bound)
354 report("the runtime", want, got)
355
356
357def inline_constants(model):
358 """Turn every `Constant` node into an initializer, in place.
359
360 Cutting a module out of a larger export breaks whenever a node inside it reads a
361 `Constant` produced outside it — the flow's four channel reversals each read three
362 constants that belong to the encoder, so extracting the flow alone leaves them dangling.
363 An initializer travels with any subgraph that references it, so inlining first makes the
364 cut work wherever it is placed.
365 """
366 keep = []
367 for node in model.graph.node:
368 if node.op_type == "Constant":
369 for attribute in node.attribute:
370 if attribute.name == "value":
371 tensor = onnx.TensorProto()
372 tensor.CopyFrom(attribute.t)
373 tensor.name = node.output[0]
374 model.graph.initializer.append(tensor)
375 break
376 else:
377 keep.append(node)
378 else:
379 keep.append(node)
380 del model.graph.node[:]
381 model.graph.node.extend(keep)
382 return model
383
384
385def extract(path, model, cut, work):
386 """Cut one module out of a larger export, so it can be run on its own.
387
388 The module's input is whatever fed its first layer, which `onnx.utils.extract_model`
389 promotes to a graph input.
390 """
391 first = next((n for n in model.graph.node if n.name == cut["first"]), None)
392 if first is None:
393 raise SystemExit(f"{cut['first']} is not in this export")
394 prefix = cut["prefix"]
395 outputs = [n.output[0] for n in model.graph.node if n.name.startswith(prefix)]
396 # Inline first, then write the whole model back out: `extract_model` reads from a path.
397 flattened = os.path.join(work, "flattened.onnx")
398 onnx.save(inline_constants(onnx.load(path)), flattened)
399 target = os.path.join(work, "subgraph.onnx")
400 inputs = [first.input[0]]
401 for extra in ("ones", "noise"):
402 if cut.get(extra):
403 inputs.append(cut[extra])
404 wanted = [cut.get("output") or outputs[-1]]
405 onnx.utils.extract_model(flattened, target, inputs, wanted)
406 return onnx.load(target)
407
408
409if __name__ == "__main__":
410 main()