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

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

modnet_fold.py293 lines · 13.2 KiBRaw
1#!/usr/bin/env python3
2"""Fold a MODNet photographic-portrait export into `.maml`, ahead of time.
3
4The official MODNet weights (Apache-2.0, `ZHKKKe/MODNet`, mirrored for this
5repo) export with two constructs `:library:ml` cannot lower verbatim:
6
7* `IBNorm`: every branch convolution is followed by a channel split whose
8 first half runs through a frozen `BatchNormalization` and whose second half
9 runs through an `InstanceNormalization(affine=False)`, re-concatenated.
10 `maml_convert.collect_layers` only folds a batch norm that directly follows
11 its convolution (`BatchNormalization` after a `Slice` is rejected), and the
12 slice between them blocks the fold.
13* The SE block's two projections arrive as `MatMul` against 2-D constants,
14 which `collect_layers` does not emit (only `Gemm`-over-`Flatten` is
15 lowered, and these feed `Reshape`, not `Flatten`).
16
17# Why this is a separate script
18
19Same reason as `ppocr_fold.py`: `maml_convert.py`'s contract is that a
20`.maml` is the ONNX's tensors *verbatim*, so teaching it slice-aware folds
21and MatMul rewrites would tax every other model. The fold happens here, once,
22ahead of time; the Rust transcribes the folded table.
23
24# What is folded, and why it is exact
25
26* Each `Conv -> Slice[0:k] -> BatchNormalization(frozen)` half is pushed into
27 the producer convolution's weight rows `[0:k)` and bias rows, in fp64:
28 `W'[o] = W[o] * s[o]`, `b'[o] = (b[o] - mean[o]) * s[o] + beta[o]` with
29 `s = gamma / sqrt(var + eps)`. At inference a frozen batch norm is a
30 per-channel affine, so this is exact, and the slice survives untouched —
31 only which rows are scaled changes, which the digest records via the
32 unchanged shapes plus the folded values' provenance in `--print-graph`.
33* Each SE `MatMul(x, W)` with a constant 2-D `W` becomes a `Conv` node with
34 kernel `[out, in, 1, 1]` and a synthesised zero bias: a matrix product over
35 a `[1, C]` row vector is a 1x1 convolution, exactly. The surrounding
36 `Unsqueeze`/`Concat`/`Reshape` shape scaffolding is left in place and dies
37 as dead code — the Rust never transcribes it, the way U^2-Netp's 266
38 `Constant` + 114 `Shape` nodes are ignored.
39
40Deliberately **not** folded:
41
42* `InstanceNormalization(affine=False)`: per-inference statistics, so there
43 is nothing to fold. The runtime implements it as `Kind::InstanceNorm`
44 (see `nets/modnet.rs`); the fold script only verifies every one is
45 `affine=False` (scale 1, bias 0) with the export's epsilon.
46* `Clip(0, 6)` (ReLU6): a real nonlinearity, fused into the producing
47 convolution as `Act::Relu6` by the Rust transcription, not rewritten here.
48* Standalone `Relu` after a `Concat` (the 16 IBNorm rejoins): no convolution
49 produced that value, so the Rust runs it as `Kind::Activate`.
50
51 ./scripts/ml/modnet_fold.py model.onnx --graph modnet -o out.maml
52 ./scripts/ml/modnet_fold.py model.onnx --graph modnet --print-graph
53"""
54
55import argparse
56import copy
57import hashlib
58import os
59import sys
60
61import numpy as np
62import onnx
63from onnx import numpy_helper
64
65sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
66import maml_convert # noqa: E402 (needs the path above)
67
68# Every IBNorm in this export: BatchNorm over channels [0:k), InstanceNorm
69# over [k:), epsilon from the InstanceNorm2d default.
70IBN_EPSILON = 1e-5
71TOLERANCE = 1e-6
72
73
74def const_arrays(model):
75 """Every constant tensor by name, from initializers and Constant nodes."""
76 inits = {i.name: i for i in model.graph.initializer}
77 consts = {}
78 for node in model.graph.node:
79 if node.op_type == "Constant":
80 for attr in node.attribute:
81 if attr.name == "value":
82 consts[node.output[0]] = attr.t
83 def array(name):
84 t = inits.get(name, consts.get(name))
85 return numpy_helper.to_array(t) if t is not None else None
86 return inits, consts, array
87
88
89def fold_ibnorm(model):
90 """Push each Slice-fed frozen BatchNorm into its producer Conv's rows.
91
92 Returns the count of folded sites. Verifies the full IBNorm shape at each
93 site: Conv -> Slice[0:k] -> BN -> Concat <- IN <- Slice[k:] with the IN
94 affine-free, and the Concat feeding only the post-join Relu path.
95 """
96 inits, consts, array = const_arrays(model)
97 nodes = list(model.graph.node)
98 out2node = {}
99 for n in nodes:
100 for o in n.output:
101 out2node[o] = n
102 consumers = {}
103 for n in nodes:
104 for i in n.input:
105 consumers.setdefault(i, []).append(n)
106
107 folded = 0
108 for bn in [n for n in nodes if n.op_type == "BatchNormalization"]:
109 # The BN half must hang off a channel-axis Slice [0:k) of a Conv.
110 sl = out2node.get(bn.input[0])
111 if sl is None or sl.op_type != "Slice":
112 raise SystemExit(f"{bn.output[0]}: batch norm input is not a Slice")
113 axes = array(sl.input[3])
114 if axes is None or list(axes) != [1]:
115 raise SystemExit(f"{sl.output[0]}: IBNorm slice is not channel-axis")
116 starts, ends = array(sl.input[1]), array(sl.input[2])
117 if starts is None or list(starts) != [0] or ends is None or len(ends) != 1:
118 raise SystemExit(f"{sl.output[0]}: BN slice is not [0:k)")
119 k = int(ends[0])
120 conv = out2node.get(sl.input[0])
121 if conv is None or conv.op_type != "Conv":
122 raise SystemExit(f"{sl.output[0]}: BN slice source is not a Conv")
123 # The sibling slice [k:] must feed an affine-free InstanceNorm, and
124 # both halves must rejoin at one Concat.
125 sib = [c for c in consumers.get(sl.input[0], []) if c is not sl]
126 if len(sib) != 1 or sib[0].op_type != "Slice":
127 raise SystemExit(f"{sl.input[0]}: expected exactly two Slice consumers")
128 sib = sib[0]
129 s_starts, s_ends = array(sib.input[1]), array(sib.input[2])
130 if list(s_starts) != [k]:
131 raise SystemExit(f"{sib.output[0]}: IN slice does not start at {k}")
132 inorm = consumers.get(sib.output[0], [])
133 if len(inorm) != 1 or inorm[0].op_type != "InstanceNormalization":
134 raise SystemExit(f"{sib.output[0]}: IN slice does not feed InstanceNorm")
135 inorm = inorm[0]
136 sc, bi = array(inorm.input[1]), array(inorm.input[2])
137 if sc is None or bi is None or not np.all(sc == 1) or not np.all(bi == 0):
138 raise SystemExit(f"{inorm.output[0]}: InstanceNorm is not affine-free")
139 eps = next((a.f for a in inorm.attribute if a.name == "epsilon"), 1e-5)
140 if abs(eps - IBN_EPSILON) > TOLERANCE:
141 raise SystemExit(f"{inorm.output[0]}: epsilon {eps} is not {IBN_EPSILON}")
142 bn_cons = consumers.get(bn.output[0], [])
143 in_cons = consumers.get(inorm.output[0], [])
144 if len(bn_cons) != 1 or len(in_cons) != 1 or bn_cons[0] is not in_cons[0]:
145 raise SystemExit(f"{bn.output[0]}: BN/IN halves do not rejoin at one Concat")
146 if bn_cons[0].op_type != "Concat":
147 raise SystemExit(f"{bn.output[0]}: halves rejoin at {bn_cons[0].op_type}")
148 # Fold: scale Conv rows [0:k) and bias rows by the BN affine, fp64.
149 attrs = {a.name: a for a in bn.attribute}
150 epsilon = attrs["epsilon"].f if "epsilon" in attrs else 1e-5
151 gamma = array(bn.input[1]).astype(np.float64)
152 beta = array(bn.input[2]).astype(np.float64)
153 mean = array(bn.input[3]).astype(np.float64)
154 var = array(bn.input[4]).astype(np.float64)
155 if any(v is None for v in (gamma, beta, mean, var)):
156 raise SystemExit(f"{bn.output[0]}: batch norm parameter is computed")
157 if gamma.shape[0] != k:
158 raise SystemExit(f"{bn.output[0]}: BN channels {gamma.shape[0]} != slice {k}")
159 w_name, b_name = conv.input[1], conv.input[2] if len(conv.input) > 2 else None
160 if b_name is None:
161 raise SystemExit(f"{conv.output[0]}: IBNorm Conv has no bias to fold into")
162 w = array(w_name).astype(np.float64)
163 b = array(b_name).astype(np.float64)
164 scale = gamma / np.sqrt(var + epsilon)
165 w[:k] = w[:k] * scale.reshape([-1] + [1] * (w.ndim - 1))
166 b[:k] = (b[:k] - mean) * scale + beta
167 folded_w = numpy_helper.from_array(w.astype(np.float32), name=w_name)
168 folded_b = numpy_helper.from_array(b.astype(np.float32), name=b_name)
169 if w_name in inits:
170 model.graph.initializer.remove(inits[w_name])
171 model.graph.initializer.append(folded_w)
172 else:
173 raise SystemExit(f"{w_name}: IBNorm Conv weight is not an initializer")
174 if b_name in inits:
175 model.graph.initializer.remove(inits[b_name])
176 model.graph.initializer.append(folded_b)
177 else:
178 raise SystemExit(f"{b_name}: IBNorm Conv bias is not an initializer")
179 # Drop the BN node, rewiring its consumer to read the Slice directly.
180 for c in bn_cons:
181 c.input[:] = [sl.output[0] if i == bn.output[0] else i for i in c.input]
182 model.graph.node.remove(bn)
183 folded += 1
184 return folded
185
186
187def rewrite_se_matmuls(model):
188 """Rewrite the SE block's constant MatMuls as 1x1 Convs with zero bias.
189
190 A `MatMul(x, W)` over a row vector is a 1x1 convolution with kernel
191 `[out, in, 1, 1]`; the surrounding Unsqueeze/Concat/Reshape scaffolding
192 stays and is ignored structurally, like U^2-Netp's shape machinery.
193 """
194 inits, consts, array = const_arrays(model)
195 rewritten = 0
196 for node in list(model.graph.node):
197 if node.op_type != "MatMul":
198 continue
199 if len(node.input) != 2 or array(node.input[1]) is None:
200 raise SystemExit(f"{node.output[0]}: non-constant SE MatMul")
201 w = array(node.input[1])
202 if w.ndim != 2:
203 raise SystemExit(f"{node.output[0]}: SE weight is {w.ndim}-D")
204 out_c, in_c = w.shape[1], w.shape[0]
205 kernel = w.T.reshape(out_c, in_c, 1, 1).astype(np.float32)
206 k_name = node.input[1] + "__conv1x1_weight"
207 b_name = node.input[1] + "__conv1x1_bias"
208 model.graph.initializer.append(
209 numpy_helper.from_array(kernel, name=k_name))
210 model.graph.initializer.append(
211 numpy_helper.from_array(np.zeros(out_c, dtype=np.float32), name=b_name))
212 node.op_type = "Conv"
213 node.input[:] = [node.input[0], k_name, b_name]
214 del node.attribute[:]
215 rewritten += 1
216 return rewritten
217
218
219def fold(model):
220 """Folded copy of `model`: BNs pushed into Convs, MatMuls as Convs."""
221 model = copy.deepcopy(model)
222 n_bn = fold_ibnorm(model)
223 n_mm = rewrite_se_matmuls(model)
224 return model, n_bn, n_mm
225
226
227def main():
228 parser = argparse.ArgumentParser()
229 parser.add_argument("onnx")
230 parser.add_argument("--graph", required=True, choices=sorted(maml_convert.GRAPHS))
231 parser.add_argument("-o", "--out", help="where to write the .maml")
232 parser.add_argument("--print-graph", action="store_true", help="dump the folded op flow")
233 parser.add_argument("--print-layers", action="store_true")
234 parser.add_argument("--print-digest", action="store_true")
235 args = parser.parse_args()
236
237 model = onnx.load(args.onnx)
238 folded, n_bn, n_mm = fold(model)
239 if args.print_graph:
240 print(f"folded {n_bn} IBNorm batch norms, rewrote {n_mm} SE MatMuls as 1x1 Conv")
241 for n in folded.graph.node:
242 if n.op_type not in ("Constant",):
243 print(f" {n.op_type:22s} {n.name}")
244
245 onnx_sha256 = hashlib.sha256()
246 with open(args.onnx, "rb") as f:
247 for block in iter(lambda: f.read(1 << 20), b""):
248 onnx_sha256.update(block)
249 layers, tensors = maml_convert.collect_layers(
250 folded, quantise=args.graph in maml_convert.INT8_GRAPHS
251 )
252 if args.print_layers:
253 for layer in layers:
254 print(f"{layer.index:4d} t{layer.first_tensor:<4d} {layer.key()} # {layer.name}")
255 if args.print_digest:
256 print(f' "{args.graph}": "{maml_convert.layer_table_digest(layers)}",')
257 maml_convert.check_graph(folded, args.graph)
258
259 digest = maml_convert.layer_table_digest(layers)
260 pinned = maml_convert.EXPECTED_DIGEST.get(args.graph)
261 if pinned is None:
262 message = (
263 f"{args.graph} has no pinned layer table digest. Add\n"
264 f' "{args.graph}": "{digest}",\n'
265 "to EXPECTED_DIGEST once the Rust net agrees with this table, so that a later\n"
266 "change to either side fails loudly instead of shifting every tensor."
267 )
268 if not args.print_digest:
269 raise SystemExit(message)
270 print(message, file=sys.stderr)
271 elif digest != pinned:
272 message = (
273 f"layer table digest {digest}\n"
274 f" pinned {pinned}\n"
275 "The ordered Conv/ConvTranspose table changed, so the hardcoded forward\n"
276 f"pass in library/ml/src/main/rust/src/nets/{args.graph}.rs no longer\n"
277 "matches this export. Re-read it with --print-layers, update the Rust,\n"
278 "then re-pin with --print-digest."
279 )
280 if not args.print_digest:
281 raise SystemExit(message)
282 print(message, file=sys.stderr)
283 if args.out:
284 blob, count = maml_convert.build(
285 layers, tensors, maml_convert.GRAPHS[args.graph], onnx_sha256.digest()
286 )
287 with open(args.out, "wb") as f:
288 f.write(blob)
289 print(f"wrote {args.out} ({len(blob)} bytes, {count} tensors)")
290
291
292if __name__ == "__main__":
293 main()