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

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

ppocr_fold.py960 lines · 42.5 KiBRaw
1#!/usr/bin/env python3
2"""Fold a PP-OCRv5 `paddle2onnx` export into `.maml`, ahead of time.
3
4PP-OCRv5's official ONNX (Apache-2.0, `PaddlePaddle/PP-OCRv5_*_onnx`) is PP-HGNetV2 as
5`paddle2onnx` spells it, which is not a form `:library:ml` can lower. Every convolution
6arrives as a chain:
7
8 Conv (no bias)
9 -> Add(bias, shape [1, C, 1, 1])
10 -> Mul(scalar) -> Add(scalar) a "learnable affine block"
11 -> HardSigmoid(alpha=1/6) -> Mul(self) a HardSwish, spelled out
12 -> Mul(scalar) -> Add(scalar) another affine block
13
14with 192 `Identity` nodes threaded through it. In the detection export that is 62
15convolutions, 117 `Add`s, 86 `Mul`s and 34 `HardSigmoid`s, of which only about a dozen
16`Add`/`Mul` pairs are real ops \u2014 the feature-pyramid residuals and the squeeze-excite
17gates. Everything else is constant.
18
19# Why this is a separate script
20
21`maml_convert.py`'s contract is that a `.maml` is the ONNX's tensors *verbatim*, so the
22Rust can index them positionally and nothing has to agree about a rewrite. Teaching it to
23constant-fold a graph would make that contract "verbatim, except for these seven
24rewrites", and the rewrites would then run on every model it converts.
25
26So the fold happens here instead, once, ahead of time. The output is a `.maml` whose
27tensors are the folded weights and biases, and the input is the official export with its
28SHA-256 recorded in the header exactly as before. Provenance is unchanged; only the place
29the arithmetic happens moves.
30
31# What is folded, and why it is exact
32
33At inference every one of these is an affine map on a convolution's output, and an affine
34map composed with a convolution is a convolution:
35
36* `Add(x, bias)` becomes the bias the shaders already add.
37* `Mul(x, s)` for a scalar or per-channel `s` scales the weight and the bias.
38* `Add(x, t)` adds to the bias.
39* `BatchNormalization` is `gamma * (x - mean) / sqrt(var + eps) + beta`, so it is the
40 same shape of thing.
41* `HardSigmoid(alpha=1/6, beta=0.5)` followed by `Mul` against its own input is the
42 definition of `HardSwish`, which the runtime fuses into the convolution's store.
43
44None of that is an approximation. The one thing deliberately **not** folded is an affine
45block that sits *after* an activation: pushing it through the next convolution needs
46`b' += t * sum(W)` over each output row, which is only valid when the tensor feeds
47convolutions and nothing else. Rather than depend on that, those are emitted as an
48`Affine` op the runtime runs as an elementwise pass. There are a couple of dozen, and
49detection runs once per OCR request rather than per frame.
50
51 ./scripts/ml/ppocr_fold.py det.onnx --graph ppocr_det -o out.maml
52 ./scripts/ml/ppocr_fold.py det.onnx --graph ppocr_det --print-graph
53"""
54
55import argparse
56import hashlib
57import os
58import sys
59
60import numpy as np
61import onnx
62from onnx import numpy_helper
63
64sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
65import maml_convert # noqa: E402 (needs the path above)
66
67# ONNX `HardSigmoid` defaults to alpha 0.2; Paddle's hard-swish uses 1/6. Both appear in
68# these graphs, so the value is read per node and checked rather than assumed.
69HARDSWISH_ALPHA = 1.0 / 6.0
70TOLERANCE = 1e-4
71
72# Ops that only rearrange or relabel, and are therefore aliases in `.maml`'s layout.
73#
74# This runtime's tensors are `[c, h, w]` with batch always 1, and `nets::ppocr_rec` keeps a
75# transformer's sequence as `[d_model, 1, T]` precisely so that the export's reshapes and
76# permutes are no-ops. Nine `Transpose`s, 52 `Reshape`s and nine `Squeeze`s in the
77# recognition graph are exactly that: `[1, 120, 1, T]` to `[1, T, 120]` and back, and the
78# five-dimensional shuffle that splits a fused QKV projection into heads.
79#
80# Aliasing them is a **claim**, not an observation: nothing here checks that a given
81# `Transpose` is a no-op in the target layout. What checks it is that the forward pass in
82# `nets::ppocr_rec` was written from a reading of this same graph, and that the layer table
83# digest below pins every weight's shape. A permute that mattered would show up as a net
84# that infers nonsense, so `--print-graph` is worth reading when this list changes.
85SHAPE_ONLY = ("Reshape", "Transpose", "Squeeze", "Unsqueeze", "Flatten")
86
87# The shape-computation subgraph that feeds those reshapes: `Shape` into `Slice` into
88# `Concat`. Once the reshapes are aliased away nothing reads it, so it is dropped as dead
89# code rather than recognised.
90SHAPE_MACHINERY = ("Shape", "ConstantOfShape")
91
92
93class Op:
94 """One op in the normalised graph, as the Rust forward pass will see it."""
95
96 def __init__(self, kind, inputs, output, **extra):
97 self.kind = kind
98 self.inputs = inputs
99 self.output = output
100 self.extra = extra
101
102 def __str__(self):
103 detail = " ".join(f"{k}={v}" for k, v in self.extra.items())
104 return f"{self.kind:14s} {self.inputs} -> {self.output} {detail}"
105
106
107def resolve(name, alias):
108 """Follow an `Identity` alias chain to the tensor that actually produced it."""
109 seen = set()
110 while name in alias and name not in seen:
111 seen.add(name)
112 name = alias[name]
113 return name
114
115
116def normalise(model, quantise=False, graph=""):
117 """Strip `Identity`, fold the constant affine chains, and return the ops and tensors.
118
119 Returns `(ops, layers, tensors)`: the normalised op list for transcription, the
120 `Layer` records the digest is taken over, and the fp16 tensors in `.maml` order.
121 """
122 graph = model.graph
123 inits = {i.name: numpy_helper.to_array(i) for i in graph.initializer}
124 # The recognition export puts its weights in `Constant` *nodes* rather than in the
125 # initializer list — 330 of them — so those count as constants too. Detection uses
126 # initializers, so both have to work.
127 for node in graph.node:
128 if node.op_type == "Constant":
129 for attribute in node.attribute:
130 if attribute.name == "value":
131 inits[node.output[0]] = numpy_helper.to_array(attribute.t)
132
133 # Rewire Identity without mutating the nodes: build an alias map and read every
134 # input through it. `Cast` is aliased too — paddle2onnx inserts one in front of every
135 # transposed convolution's weight, and it is a no-op between two float types. So are
136 # the pure shape ops; see `SHAPE_ONLY`.
137 alias = {}
138 for node in graph.node:
139 if node.op_type == "Identity" or (
140 node.op_type == "Cast" and node.input and node.input[0] in inits
141 ):
142 alias[node.output[0]] = node.input[0]
143 elif node.op_type in SHAPE_ONLY and node.input:
144 alias[node.output[0]] = node.input[0]
145 elif node.op_type in ("Add", "Mul") and len(node.input) == 2:
146 # `Add(x, 0)` and `Mul(x, 1)`. paddle2onnx emits three of these around the
147 # sequence pool, where Paddle's `assign` became an unsqueeze, an add of zero
148 # and a squeeze. Folding them as affines would work and would leave an
149 # elementwise pass over 115,200 elements that does nothing.
150 for position, name in enumerate(node.input):
151 value = inits.get(name)
152 if value is None:
153 continue
154 flat = np.array(value, dtype=np.float64).flatten()
155 identity = 0.0 if node.op_type == "Add" else 1.0
156 if flat.size == 1 and abs(flat[0] - identity) < 1e-12:
157 alias[node.output[0]] = node.input[1 - position]
158 break
159
160 # The fused QKV projection, and the three slices that split it. Resolved here rather
161 # than during the walk because the alias map has to be complete before any input is
162 # read through it; this adds the slice outputs to it.
163 fused, keep = split_fused_qkv(graph, inits, alias)
164
165 nodes = [
166 n
167 for n in graph.node
168 if n.op_type not in ("Identity", "Constant")
169 and n.op_type not in SHAPE_MACHINERY
170 and not (n.output and n.output[0] in alias)
171 ]
172 # Whatever is left of the shape machinery reads a `Shape` that is now gone, so it is
173 # dead. Reverse reachability from the graph's output is what removes it.
174 nodes = live_nodes(nodes, graph, alias, fused, keep)
175 inputs_of = {id(n): [resolve(i, alias) for i in n.input] for n in nodes}
176
177 producer = {}
178 consumers = {}
179 for node in nodes:
180 for name in inputs_of[id(node)]:
181 consumers.setdefault(name, []).append(node)
182 for name in node.output:
183 producer[name] = node
184
185 def constant(node, index):
186 """The constant operand of a binary node, or `(None, None)`."""
187 names = inputs_of[id(node)]
188 for position, name in enumerate(names):
189 if name in inits:
190 other = names[1 - position] if len(names) == 2 else None
191 if index is None or position == index:
192 return inits[name], other
193 return None, None
194
195 consumed = set()
196 ops = []
197 layers = []
198 tensors = []
199 # Layer indices that could be read as int8, filled by `emit_conv` and used only after all
200 # folding has finished. See [`quantise_convs`].
201 quantisable = []
202
203 def emit_conv(node, weight, bias, act, act_alpha, output):
204 first = len(tensors)
205 tensors.append(weight.astype(np.float32))
206 tensors.append(bias.astype(np.float32))
207 attrs = {a.name: a for a in node.attribute}
208
209 def ints(name, default):
210 return list(attrs[name].ints) if name in attrs else list(default)
211
212 key = (
213 f"{node.op_type} w={list(weight.shape)} b={list(bias.shape)} "
214 f"k={ints('kernel_shape', weight.shape[2:])} "
215 f"d={ints('dilations', (1, 1))} p={ints('pads', (0, 0, 0, 0))} "
216 f"s={ints('strides', (1, 1))} "
217 f"g={attrs['group'].i if 'group' in attrs else 1} act={act}"
218 )
219 layers.append(
220 maml_convert.Layer(len(layers), node.op_type, output, key, first, 2)
221 )
222 # Only an ordinary convolution with no PRelu can be int8: `Builder::conv_int8` refuses
223 # a PRelu because its per-channel slope wants the push offset the dequantisation scale
224 # occupies, and there is no int8 `ConvTranspose` at all. Recorded here and acted on
225 # after folding; see [`quantise_convs`].
226 if node.op_type == "Conv" and act != "PRelu":
227 quantisable.append(len(layers) - 1)
228 ops.append(
229 Op(
230 node.op_type,
231 [inputs_of[id(node)][0]],
232 output,
233 w=list(weight.shape),
234 k=ints("kernel_shape", weight.shape[2:]),
235 s=ints("strides", (1, 1)),
236 p=ints("pads", (0, 0, 0, 0)),
237 g=attrs["group"].i if "group" in attrs else 1,
238 act=act,
239 t=first,
240 )
241 )
242
243 def emit_linear(node, weight, bias, act, source, output, already_transposed=False):
244 """A `MatMul` against a constant, as the 1x1 convolution the runtime lowers it to.
245
246 ONNX spells `x[..., in] @ W[in, out]`, so the weight arrives transposed relative to
247 a convolution's `[out, in, kh, kw]`. Transposing here rather than in the shader is
248 what lets every projection in the transformer be an ordinary `Kind::Conv`.
249 """
250 kernel = weight if already_transposed else transposed(weight)
251 first = len(tensors)
252 tensors.append(kernel.astype(np.float32))
253 tensors.append(bias.astype(np.float32))
254 key = (
255 f"Linear w={list(kernel.shape)} b={list(bias.shape)} "
256 f"k=[1, 1] d=[1, 1] p=[0, 0, 0, 0] s=[1, 1] g=1 act={act}"
257 )
258 layers.append(maml_convert.Layer(len(layers), "MatMul", output, key, first, 2))
259 # A `MatMul` against a constant is a 1x1 convolution in the runtime, so it quantises on
260 # exactly the same terms as `emit_conv`'s output. These are the recogniser's transformer
261 # projections and its largest tensors, so leaving them out would give up most of the
262 # saving.
263 if act != "PRelu":
264 quantisable.append(len(layers) - 1)
265 ops.append(
266 Op("Linear", [source], output, w=list(kernel.shape), act=act, t=first)
267 )
268
269 def emit_layer_norm(gamma, beta, epsilon, source, output):
270 """One `LayerNorm` layer from the nine nodes the export decomposes it into."""
271 first = len(tensors)
272 tensors.append(np.array(gamma, dtype=np.float32).flatten())
273 tensors.append(np.array(beta, dtype=np.float32).flatten())
274 key = f"LayerNorm c={gamma.size} eps={epsilon:.9g}"
275 layers.append(maml_convert.Layer(len(layers), "LayerNorm", output, key, first, 2))
276 ops.append(Op("LayerNorm", [source], output, c=int(gamma.size), eps=epsilon, t=first))
277
278 def absorb(cursor, weight, bias, channels, is_transpose):
279 """Pull every constant that follows `cursor` into `weight` and `bias`.
280
281 Stops at the activation, because an affine applied *after* one cannot move before
282 it. Returns the updated weight and bias, the activation found, and the name of the
283 last tensor absorbed — which becomes the layer's output.
284
285 Shared by the convolutions and the `MatMul` linears: the recognition export spells
286 a feed-forward layer as `MatMul -> Add(bias) -> Sigmoid -> Mul(self)`, which is the
287 same chain a convolution gets, so recognising it twice would be two chances to
288 recognise it differently.
289 """
290 act = "None"
291 while True:
292 following = consumers.get(cursor, [])
293 if act != "None":
294 break
295 # `x * HardSigmoid(x)` is not a single-consumer chain: the tensor feeds
296 # both the HardSigmoid and the Mul that combines them. Matching it before
297 # the branch test below is the difference between fusing 24 HardSwishes
298 # and emitting 48 extra ops for them.
299 gate = next((n for n in following if n.op_type in ("HardSigmoid", "Sigmoid")), None)
300 if len(following) == 2 and gate is not None:
301 other = following[0] if following[1] is gate else following[1]
302 after = consumers.get(gate.output[0], [])
303 if (
304 other.op_type == "Mul"
305 and len(after) == 1
306 and after[0] is other
307 and gate.output[0] in inputs_of[id(other)]
308 and cursor in inputs_of[id(other)]
309 ):
310 if gate.op_type == "Sigmoid":
311 act = "Swish"
312 else:
313 attrs = {a.name: a.f for a in gate.attribute}
314 alpha = attrs.get("alpha", 0.2)
315 beta = attrs.get("beta", 0.5)
316 if (
317 abs(alpha - HARDSWISH_ALPHA) > TOLERANCE
318 or abs(beta - 0.5) > TOLERANCE
319 ):
320 raise SystemExit(
321 f"{gate.output[0]}: x * HardSigmoid(x) with "
322 f"alpha={alpha} beta={beta}; the runtime's HardSwish "
323 "is alpha=1/6 beta=0.5"
324 )
325 act = "HardSwish"
326 consumed.add(id(gate))
327 consumed.add(id(other))
328 cursor = other.output[0]
329 continue
330 if len(following) != 1:
331 break
332 step = following[0]
333 if step.op_type == "Add":
334 value, _ = constant(step, None)
335 if value is None:
336 break
337 bias = bias + np.array(value, dtype=np.float64).flatten()
338 elif step.op_type == "Mul":
339 value, _ = constant(step, None)
340 if value is None:
341 break
342 scale = np.array(value, dtype=np.float64).flatten()
343 if scale.size == 1:
344 weight = weight * scale[0]
345 bias = bias * scale[0]
346 elif scale.size == channels:
347 shape = [1] * weight.ndim
348 axis = 1 if is_transpose else 0
349 shape[axis] = channels
350 weight = weight * scale.reshape(shape)
351 bias = bias * scale
352 else:
353 break
354 elif step.op_type == "BatchNormalization":
355 weight, bias = fold_batch_norm(
356 step, inits, weight, bias, "ConvTranspose" if is_transpose else "Conv"
357 )
358 elif step.op_type == "Relu":
359 act = "Relu"
360 elif step.op_type == "Sigmoid":
361 act = "Sigmoid"
362 elif step.op_type == "HardSigmoid":
363 # A HardSigmoid with a single consumer is a standalone gate — the
364 # excite half of a squeeze-excite block, whose Mul takes a different
365 # tensor. The self-multiplying kind was matched above.
366 #
367 # Its alpha and beta fold into the convolution:
368 # `clamp(alpha * (Wx + b) + beta, 0, 1)` is `clamp(W'x + b', 0, 1)`.
369 # Both 0.2 and 1/6 appear in this graph, so an activation carrying the
370 # two parameters would have to put them in the push block; this way the
371 # runtime needs one parameterless clamp.
372 attrs = {a.name: a.f for a in step.attribute}
373 alpha = attrs.get("alpha", 0.2)
374 beta = attrs.get("beta", 0.5)
375 weight = weight * alpha
376 bias = bias * alpha + beta
377 act = "Clip01"
378 else:
379 break
380 consumed.add(id(step))
381 cursor = step.output[0]
382 return weight, bias, act, cursor
383
384 for node in nodes:
385 if id(node) in consumed:
386 continue
387 if node.op_type in ("Conv", "ConvTranspose"):
388 names = inputs_of[id(node)]
389 weight = np.array(inits[names[1]], dtype=np.float64)
390 channels = weight.shape[1] if node.op_type == "ConvTranspose" else weight.shape[0]
391 bias = (
392 np.array(inits[names[2]], dtype=np.float64).flatten()
393 if len(names) > 2
394 else np.zeros(channels, dtype=np.float64)
395 )
396 weight, bias, act, cursor = absorb(
397 node.output[0], weight, bias, channels, node.op_type == "ConvTranspose"
398 )
399 emit_conv(node, weight, bias, act, None, cursor)
400 elif node.op_type == "MatMul":
401 names = inputs_of[id(node)]
402 constants = [n for n in names if n in inits]
403 if not constants:
404 # Both operands are activations, so this is one of attention's two
405 # products — the scores or the weighted sum. `nets::ppocr_rec` lowers
406 # those to `AttnScores` and `AttnApply`, which read no weights.
407 ops.append(Op("MatMul", names, node.output[0]))
408 continue
409 weight = np.array(inits[constants[0]], dtype=np.float64)
410 if weight.ndim != 2:
411 raise SystemExit(
412 f"{node.output[0]}: a MatMul against a {list(weight.shape)} constant"
413 )
414 source = next(n for n in names if n not in inits)
415 outputs = weight.shape[1]
416 bias, bias_node = following_bias(node, consumers, inputs_of, inits, outputs)
417 if bias_node is not None:
418 consumed.add(id(bias_node))
419 cursor = bias_node.output[0] if bias_node is not None else node.output[0]
420 parts = fused.get(node.output[0])
421 if parts is not None:
422 # A fused QKV projection: one `[d, 3d]` weight that the export slices into
423 # query, key and value after a five-dimensional shuffle. Split here into
424 # three ordinary linears, because `nets::ppocr_rec` projects them
425 # separately and a channel slice of a constant is exact.
426 width = outputs // 3
427 for index, name in enumerate(parts):
428 emit_linear(
429 node,
430 weight[:, index * width : (index + 1) * width],
431 bias[index * width : (index + 1) * width],
432 "None",
433 source,
434 name,
435 )
436 continue
437 weight, bias, act, cursor = absorb(cursor, transposed(weight), bias, outputs, False)
438 emit_linear(node, weight, bias, act, source, cursor, already_transposed=True)
439 elif node.op_type == "ReduceMean":
440 matched = match_layer_norm(node, consumers, inputs_of, inits)
441 if matched is None:
442 ops.append(Op(node.op_type, inputs_of[id(node)], node.output[0]))
443 continue
444 chain, gamma, beta, epsilon, source, output = matched
445 for member in chain:
446 consumed.add(id(member))
447 emit_layer_norm(gamma, beta, epsilon, source, output)
448 elif node.op_type == "Softmax":
449 axis = next((a.i for a in node.attribute if a.name == "axis"), -1)
450 if node.output[0] in {o.name for o in graph.output}:
451 # The classifier's softmax over the 838 classes. Deliberately dropped:
452 # `post::ctc::decode` takes the argmax, which a softmax cannot change, and
453 # recovers the winner's probability from the raw logits directly. See the
454 # module docs in `nets::ppocr_rec`.
455 ops.append(Op("DroppedSoftmax", inputs_of[id(node)], node.output[0], axis=axis))
456 continue
457 ops.append(Op(node.op_type, inputs_of[id(node)], node.output[0], axis=axis))
458 elif node.op_type in ("Add", "Mul"):
459 value, other = constant(node, None)
460 if value is not None:
461 # A leftover constant affine: it follows an activation, so it could not be
462 # folded above. One elementwise pass rather than a weight rewrite whose
463 # validity depends on what the tensor feeds.
464 scalar = np.array(value, dtype=np.float64).flatten()
465 if scalar.size != 1:
466 raise SystemExit(
467 f"{node.output[0]}: a leftover {node.op_type} against a "
468 f"{list(np.array(value).shape)} constant, which is not a scalar affine"
469 )
470 scale = float(scalar[0]) if node.op_type == "Mul" else 1.0
471 shift = float(scalar[0]) if node.op_type == "Add" else 0.0
472 ops.append(Op("Affine", [other], node.output[0], scale=scale, shift=shift))
473 else:
474 ops.append(Op(node.op_type, inputs_of[id(node)], node.output[0]))
475 else:
476 ops.append(Op(node.op_type, inputs_of[id(node)], node.output[0]))
477
478 ops = merge_affines(ops, consumers)
479 ops = fold_affine_into_convs(ops, tensors)
480 if quantise:
481 layers, tensors = quantise_convs(layers, tensors, quantisable, graph)
482 return ops, layers, tensors
483
484
485def quantise_convs(layers, tensors, eligible, graph):
486 """Rewrite the eligible convolutions as int8 triples, in place.
487
488 **A post-fold pass, deliberately.** `fold_affine_into_convs` mutates `tensors[first]` and
489 `tensors[first + 1]` after every layer has been emitted, on the assumption that a
490 convolution owns exactly two tensors: its weight and its bias. An int8 convolution owns
491 three, and `first + 1` is then the *scale* — so quantising at emit time would have the fold
492 silently multiply a scale vector by an affine and leave the bias untouched. Nothing would
493 fail; the file would just be wrong.
494
495 Doing it here, after all folding has finished, also means the numbers quantised are the
496 ones the device actually reads rather than an intermediate.
497
498 Inserting a tensor shifts every later layer's `first_tensor`, so the table is rebuilt
499 rather than patched.
500 """
501 fidelity = maml_convert.Fidelity()
502 rebuilt_tensors = []
503 rebuilt_layers = []
504 eligible = set(eligible)
505 for layer in layers:
506 first = len(rebuilt_tensors)
507 span = tensors[layer.first_tensor: layer.first_tensor + layer.tensor_count]
508 if layer.index in eligible:
509 weight, bias = span
510 kernel, scale = fidelity.quantise(layer.name, np.asarray(weight, dtype=np.float32))
511 rebuilt_tensors.extend([kernel, scale, bias])
512 # `Conv ` for a convolution, `Linear ` for a folded MatMul; both become the same
513 # three-tensor int8 layout the Rust reads with `Builder::conv_int8`.
514 key = layer.key()
515 key = key.replace("Conv ", "ConvInt8 ", 1) if key.startswith("Conv ") else key
516 key = key.replace("Linear ", "LinearInt8 ", 1) if key.startswith("Linear ") else key
517 rebuilt_layers.append(
518 maml_convert.Layer(
519 len(rebuilt_layers),
520 "ConvInt8",
521 layer.name,
522 key + " zp=0 dtype=int8",
523 first,
524 3,
525 )
526 )
527 else:
528 rebuilt_tensors.extend(span)
529 rebuilt_layers.append(
530 maml_convert.Layer(
531 len(rebuilt_layers),
532 layer.op,
533 layer.name,
534 layer.key(),
535 first,
536 layer.tensor_count,
537 )
538 )
539 fidelity.report()
540 print(f"{graph}: {len(eligible)} of {len(layers)} layers read as int8")
541 return rebuilt_layers, rebuilt_tensors
542
543
544def transposed(weight):
545 """`[in, out]` as a convolution kernel `[out, in, 1, 1]`."""
546 return np.ascontiguousarray(weight.T).reshape(weight.shape[1], weight.shape[0], 1, 1)
547
548
549def following_bias(node, consumers, inputs_of, inits, outputs):
550 """The `Add(matmul, bias)` that follows a linear, as `(bias, node)`.
551
552 Raises rather than defaulting to zeros. Every `MatMul` in this export carries its bias
553 as a following `Add`, so failing to find one means the graph is not the shape this
554 script thinks — and a silently zeroed bias is invisible: it survives every shape check,
555 the layer table digest and the tensor count, and shows up only as lost accuracy.
556 """
557 following = consumers.get(node.output[0], [])
558 if len(following) == 1 and following[0].op_type == "Add":
559 for name in inputs_of[id(following[0])]:
560 if name in inits:
561 value = np.array(inits[name], dtype=np.float64).flatten()
562 if value.size == outputs:
563 return value, following[0]
564 raise SystemExit(
565 f"{node.output[0]}: a MatMul with {outputs} outputs and no following Add against a "
566 f"[{outputs}] constant, so its bias cannot be read"
567 )
568
569
570def split_fused_qkv(graph, inits, alias):
571 """Find each fused QKV projection and alias its three slices to per-part names.
572
573 PaddleOCR's attention projects query, key and value in one `[d, 3d]` `MatMul`, then
574 reshapes to `[batch, T, 3, heads, head_dim]`, permutes and slices the leading axis.
575 `nets::ppocr_rec` projects the three separately, so this records which slice is which
576 and lets the walk emit three linears from the one weight.
577
578 It also drops the `Mul(q, 1/sqrt(head_dim))` the export applies to the query, after
579 checking the constant really is that: `Kind::AttnScores` derives the same scale from
580 the head geometry, so leaving it here would apply it twice.
581
582 Mutates `alias`, and returns `({matmul_output: [q_name, k_name, v_name]}, keep)`, where
583 `keep` is the set of output names that must survive dead-code elimination.
584 """
585 def resolved(name):
586 return resolve(name, alias)
587
588 constants = dict(inits)
589 consumers = {}
590 for node in graph.node:
591 for name in node.input:
592 consumers.setdefault(resolved(name), []).append(node)
593
594 fused = {}
595 keep = set()
596 for node in graph.node:
597 if node.op_type != "MatMul":
598 continue
599 weights = [resolved(n) for n in node.input if resolved(n) in constants]
600 if not weights:
601 continue
602 weight = np.array(constants[weights[0]])
603 if weight.ndim != 2 or weight.shape[1] != weight.shape[0] * 3:
604 continue
605
606 width = weight.shape[0]
607 names = [f"{node.output[0]}#{part}" for part in ("q", "k", "v")]
608 # The slices read the bias `Add`'s output through the aliased reshape and permute.
609 bias_node = next(
610 (n for n in consumers.get(node.output[0], []) if n.op_type == "Add"), None
611 )
612 if bias_node is None:
613 raise SystemExit(f"{node.output[0]}: a fused QKV projection with no bias")
614 # Aliasing the three slices below orphans this `Add` — nothing in the graph reads
615 # its output any more — so without pinning it here the dead-code pass removes it
616 # and the walk reads a zero bias for all three projections.
617 #
618 # Pinned by output *name*, not by `id()`: protobuf's upb backend hands out a fresh
619 # Python wrapper on each access to a repeated field, so an id taken here does not
620 # match the one `normalise` sees. Names are unique — ONNX graphs are SSA.
621 keep.add(bias_node.output[0])
622 split_source = resolved(bias_node.output[0])
623 found = {}
624 for candidate in graph.node:
625 if candidate.op_type != "Slice":
626 continue
627 if not candidate.input or resolved(candidate.input[0]) != split_source:
628 continue
629 starts = next((list(a.ints) for a in candidate.attribute if a.name == "starts"), [])
630 if len(starts) != 1 or not 0 <= starts[0] < 3:
631 continue
632 found[starts[0]] = candidate
633 if len(found) != 3:
634 raise SystemExit(
635 f"{node.output[0]}: a [{width}, {width * 3}] projection with "
636 f"{len(found)} slices, expected three (query, key, value)"
637 )
638 for part, candidate in found.items():
639 alias[candidate.output[0]] = names[part]
640 fused[node.output[0]] = names
641
642 # The query's scale. `heads` is not known here, so the check is that the constant
643 # is `1/sqrt(width / heads)` for the integer head count that makes it so.
644 scale_node = next(
645 (
646 n
647 for n in graph.node
648 if n.op_type == "Mul" and any(resolved(i) == names[0] for i in n.input)
649 ),
650 None,
651 )
652 if scale_node is None:
653 raise SystemExit(f"{node.output[0]}: the query is not scaled at all")
654 value = next(
655 (np.array(constants[resolved(i)]).flatten() for i in scale_node.input
656 if resolved(i) in constants),
657 None,
658 )
659 if value is None or value.size != 1:
660 raise SystemExit(f"{scale_node.output[0]}: the query's scale is not a scalar")
661 head_dim = 1.0 / float(value[0]) ** 2
662 if abs(head_dim - round(head_dim)) > 1e-3 or not width % max(round(head_dim), 1) == 0:
663 raise SystemExit(
664 f"{scale_node.output[0]}: a query scale of {value[0]} is not "
665 f"1/sqrt(head_dim) for any head count dividing {width}"
666 )
667 alias[scale_node.output[0]] = names[0]
668 return fused, keep
669
670
671def live_nodes(nodes, graph, alias, fused, keep):
672 """`nodes`, restricted to those that transitively feed a graph output, plus `keep`.
673
674 Aliasing the reshapes away orphans the `Shape`/`Slice`/`Concat` subgraphs that computed
675 their target shapes — 52 reshapes' worth. Reverse reachability removes them without
676 this script having to recognise what each one was for.
677
678 `fused` has to be threaded through: a fused QKV projection's three parts are named for
679 slices that no longer exist, so without registering the `MatMul` as their producer the
680 walk backwards stops dead there and takes both attentions and the two layer norms in
681 front of them with it. `keep` carries the output names of nodes that are unreachable
682 *by construction* but still hold data the walk needs — those projections' bias `Add`s.
683 """
684 producer = {}
685 for node in nodes:
686 for name in node.output:
687 producer[name] = node
688 for part in fused.get(node.output[0] if node.output else "", []):
689 producer[part] = node
690 live = set()
691 queue = [resolve(o.name, alias) for o in graph.output]
692 queue.extend(keep)
693 while queue:
694 name = queue.pop()
695 node = producer.get(name)
696 if node is None or id(node) in live:
697 continue
698 live.add(id(node))
699 queue.extend(resolve(i, alias) for i in node.input)
700 return [n for n in nodes if id(n) in live]
701
702
703def match_layer_norm(first_mean, consumers, inputs_of, inits):
704 """Match `ReduceMean/Sub/Pow/ReduceMean/Add/Sqrt/Div/Mul/Add` as one layer norm.
705
706 The export decomposes each of the recogniser's five layer norms into nine nodes. Left
707 alone that is 45 ops, most of them reductions over a dynamic axis. Returns
708 `(chain, gamma, beta, epsilon, source, output)`, or `None` if this `ReduceMean` is
709 something else.
710
711 Matched forwards from the *first* `ReduceMean` rather than from the `Div`, because the
712 walk reaches it first and would otherwise have emitted it as a standalone op.
713 """
714 def only(name, kind):
715 following = consumers.get(name, [])
716 if len(following) == 1 and following[0].op_type == kind:
717 return following[0]
718 return None
719
720 def other_input(node, known):
721 return next((n for n in inputs_of[id(node)] if n != known), None)
722
723 source = next(iter(inputs_of[id(first_mean)]), None)
724 if source is None:
725 return None
726 # `Sub(x, mean)` reads both the layer norm's input and this mean.
727 centre = next(
728 (
729 n
730 for n in consumers.get(first_mean.output[0], [])
731 if n.op_type == "Sub" and source in inputs_of[id(n)]
732 ),
733 None,
734 )
735 if centre is None:
736 return None
737 power = next(
738 (n for n in consumers.get(centre.output[0], []) if n.op_type == "Pow"), None
739 )
740 if power is None:
741 return None
742 exponent = next(
743 (np.array(inits[n]).flatten() for n in inputs_of[id(power)] if n in inits), None
744 )
745 if exponent is None or exponent.size != 1 or abs(exponent[0] - 2.0) > 1e-9:
746 return None
747 variance = only(power.output[0], "ReduceMean")
748 if variance is None:
749 return None
750 stabilised = only(variance.output[0], "Add")
751 if stabilised is None:
752 return None
753 epsilon = next(
754 (np.array(inits[n]).flatten() for n in inputs_of[id(stabilised)] if n in inits), None
755 )
756 if epsilon is None or epsilon.size != 1:
757 return None
758 root = only(stabilised.output[0], "Sqrt")
759 if root is None:
760 return None
761 divide = next(
762 (
763 n
764 for n in consumers.get(root.output[0], [])
765 if n.op_type == "Div" and centre.output[0] in inputs_of[id(n)]
766 ),
767 None,
768 )
769 if divide is None:
770 return None
771 scale = only(divide.output[0], "Mul")
772 if scale is None:
773 return None
774 gamma_name = other_input(scale, divide.output[0])
775 if gamma_name not in inits:
776 return None
777 shift = only(scale.output[0], "Add")
778 if shift is None:
779 return None
780 beta_name = other_input(shift, scale.output[0])
781 if beta_name not in inits:
782 return None
783
784 gamma = np.array(inits[gamma_name]).flatten()
785 beta = np.array(inits[beta_name]).flatten()
786 if gamma.size != beta.size:
787 return None
788 chain = [first_mean, centre, power, variance, stabilised, root, divide, scale, shift]
789 return chain, gamma, beta, float(epsilon[0]), source, shift.output[0]
790
791
792def fold_affine_into_convs(ops, tensors):
793 """Push each scalar `Affine` into the convolutions it feeds, where that is exact.
794
795 `conv(a * x + t)[m]` is `a * conv(x)[m] + t * sum(W[m])`, so an affine on a
796 convolution's *input* folds into its weight and bias just as one on its output does.
797 The sum is over every weight axis but the output-channel one, which for a grouped or
798 depthwise convolution is exactly the channels that output reads.
799
800 # Only when the convolution is unpadded
801
802 That identity holds at an interior pixel and **fails at a border one**. A padded
803 convolution reads zero outside the input, not `t`, so the constant's true contribution
804 there is `t * sum(W over the in-bounds taps)` — position-dependent, and smaller than
805 `t * sum(W)` by whatever hangs over the edge. Folding anyway biases the whole border
806 of every feature map, which is 27% of the pixels of a 12x16 map at a 3x3 kernel, and
807 compounds through the backbone.
808
809 There is no fix that keeps the fold: the correction varies per output position, so it
810 is not a bias. Padding the input with `t` instead of zero would make the identity exact
811 and is not what the graph says. So an affine feeding a padded convolution stays an op,
812 which is what ncnn's conversion of these models does with all of them.
813
814 Also only when the affine's result is not needed anywhere else, so every consumer has
815 to be a convolution as well.
816 """
817 consumers = {}
818 for op in ops:
819 for name in op.inputs:
820 consumers.setdefault(name, []).append(op)
821
822 def foldable(op):
823 if op.kind not in ("Conv", "ConvTranspose"):
824 return False
825 # `Linear` is a 1x1 with no padding by construction, but it is spelled as its own
826 # kind and is deliberately not folded into: it would mean this function had to know
827 # that a `MatMul`'s weight is stored transposed.
828 return not any(op.extra.get("p", (0, 0, 0, 0)))
829
830 dropped = set()
831 for op in ops:
832 if op.kind != "Affine":
833 continue
834 following = consumers.get(op.output, [])
835 if not following or not all(foldable(f) for f in following):
836 continue
837 scale = op.extra["scale"]
838 shift = op.extra["shift"]
839 for conv in following:
840 first = conv.extra["t"]
841 weight = tensors[first]
842 bias = tensors[first + 1]
843 # The row sum comes from the *unscaled* weight, so compute it first.
844 axes = (0, 2, 3) if conv.kind == "ConvTranspose" else (1, 2, 3)
845 tensors[first + 1] = bias + shift * weight.sum(axis=axes)
846 tensors[first] = weight * scale
847 # The convolution now reads what fed the affine.
848 conv.inputs = [op.inputs[0] if i == op.output else i for i in conv.inputs]
849 dropped.add(id(op))
850 return [op for op in ops if id(op) not in dropped]
851
852
853def merge_affines(ops, consumers):
854 """Collapse a `Mul(scalar)` immediately followed by an `Add(scalar)` into one op.
855
856 `paddle2onnx` spells a learnable affine block as two nodes, so folding leaves them as
857 two `Affine`s in a row. One op is one pass over the data instead of two.
858 """
859 by_input = {}
860 for index, op in enumerate(ops):
861 for name in op.inputs:
862 by_input.setdefault(name, []).append(index)
863
864 merged = []
865 absorbed = set()
866 for index, op in enumerate(ops):
867 if index in absorbed:
868 continue
869 if op.kind == "Affine":
870 followers = by_input.get(op.output, [])
871 if len(followers) == 1:
872 nxt = ops[followers[0]]
873 # Only when the second is the other half: a scale then a shift.
874 if (
875 nxt.kind == "Affine"
876 and len(consumers.get(op.output, [])) <= 1
877 and (op.extra["shift"] == 0.0 or nxt.extra["scale"] == 1.0)
878 ):
879 op = Op(
880 "Affine",
881 op.inputs,
882 nxt.output,
883 # `(x * a + s) * a2 + s2`, with one of the two halves the identity.
884 scale=op.extra["scale"] * nxt.extra["scale"],
885 shift=op.extra["shift"] * nxt.extra["scale"] + nxt.extra["shift"],
886 )
887 absorbed.add(followers[0])
888 merged.append(op)
889 return merged
890
891
892def fold_batch_norm(node, inits, weight, bias, op_type):
893 """`gamma * (x - mean) / sqrt(var + eps) + beta`, pushed into a weight and bias."""
894 attrs = {a.name: a.f for a in node.attribute}
895 epsilon = attrs.get("epsilon", 1e-5)
896 gamma, beta, mean, var = (
897 np.array(inits[n], dtype=np.float64) for n in node.input[1:5]
898 )
899 scale = gamma / np.sqrt(var + epsilon)
900 shape = [1] * weight.ndim
901 shape[1 if op_type == "ConvTranspose" else 0] = scale.size
902 return weight * scale.reshape(shape), (bias - mean) * scale + beta
903
904
905def main():
906 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
907 parser.add_argument("onnx")
908 parser.add_argument("--graph", required=True, choices=sorted(maml_convert.GRAPHS))
909 parser.add_argument("-o", "--out", help="where to write the .maml")
910 parser.add_argument("--print-graph", action="store_true", help="dump the folded ops")
911 parser.add_argument("--print-layers", action="store_true")
912 parser.add_argument("--print-digest", action="store_true")
913 args = parser.parse_args()
914
915 with open(args.onnx, "rb") as f:
916 raw = f.read()
917 onnx_sha256 = hashlib.sha256(raw).digest()
918
919 model = onnx.load(args.onnx)
920 ops, layers, tensors = normalise(
921 model, quantise=args.graph in maml_convert.INT8_GRAPHS, graph=args.graph
922 )
923
924 if args.print_graph:
925 for index, op in enumerate(ops):
926 print(f"{index:4d} {op}")
927 if args.print_layers:
928 for layer in layers:
929 print(f"{layer.index:4d} t{layer.first_tensor:<4d} {layer.key()} # {layer.name}")
930
931 digest = maml_convert.layer_table_digest(layers)
932 if args.print_digest:
933 print(f' "{args.graph}": "{digest}",')
934 pinned = maml_convert.EXPECTED_DIGEST.get(args.graph, "")
935 if digest != pinned and not args.print_digest:
936 raise SystemExit(
937 f"layer table digest {digest}\n pinned {pinned}\n"
938 "The folded layer table changed, so the hardcoded forward pass no longer\n"
939 "matches this export. Re-read it with --print-graph, update the Rust, then\n"
940 "re-pin with --print-digest."
941 )
942
943 blob, count = maml_convert.build(
944 layers, tensors, maml_convert.GRAPHS[args.graph], onnx_sha256
945 )
946 if args.out:
947 with open(args.out, "wb") as f:
948 f.write(blob)
949 kinds = {}
950 for op in ops:
951 kinds[op.kind] = kinds.get(op.kind, 0) + 1
952 print(
953 f"{args.graph}: {count} folded layers, {len(tensors)} tensors, "
954 f"{len(blob)} bytes ({len(raw)} fp32 in)"
955 )
956 print(f" normalised ops: {kinds}")
957
958
959if __name__ == "__main__":
960 main()