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

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

supertonic_fold.py913 lines · 39.5 KiBRaw
1#!/usr/bin/env python3
2"""Supertonic 3's ONNX nets to `.maml`, folding their per-channel affines away.
3
4`nets::supertonic_vocoder` is a hardcoded forward pass of convolutions, layer norms, GELUs and
5residual adds — and nothing else. The export has three per-channel affines that are not any of
6those, and rather than adding an op for each, all three fold into a convolution:
7
8 input Mul by [24] then Add by [24] -> folds into `embed`
9 block Mul by a [512] layer scale -> folds into that block's `pwconv2`
10 tail BatchNormalization over [512] -> folds into `head/layer1`
11
12# Why the fold is legal here and not in ppocr_fold.py
13
14`conv(a x + b)` is `conv_{aW}(x) + sum(W b)` at an interior position, and the constant term is a
15per-output-channel bias. At a *border* it depends on what the padding supplies. With zero padding
16the pad contributes `0` rather than `b`, the fold is wrong at the edge, and
17`ppocr_fold.fold_affine_into_convs` refuses padded convolutions for exactly that reason — it was
18a real bug in a shipped asset.
19
20Every convolution in this vocoder is preceded by an ONNX `Pad` with **`mode=edge`**. A replicated
21border supplies `a x_border + b`, which is what the fold assumes, so it holds everywhere. The
22`pwconv2` case is unconditional anyway: a 1x1 has no border.
23
24# Two smaller shape fixes
25
26* `head/act` is a `PRelu` with a single shared slope. The runtime's `Act::PRelu` reads one slope
27 per channel, so the scalar is widened to 2048 copies. 4 KB, and it keeps the shader branchless.
28* `head/layer2` has no bias in the export. A zero one is synthesised, as `maml_convert`
29 already does for a biasless convolution.
30
31# The duration predictor
32
33`--graph supertonic_dp` collects `duration_predictor.onnx` instead, which needs three fixes of
34its own rather than the vocoder's three:
35
36 sentence_token [1, 64, 1] -> appended to the embedding table as its last row
37 block gamma [1, 64, 1] -> folds into that block's `pwconv2`
38 proj_out -> a zero bias is synthesised
39
40Prepending a learned token to the sequence is a `Concat` this runtime has no op for along the
41sequence axis, and needs none: the token becomes row 8322 of the table and the caller prepends
42that id. See `nets::supertonic_duration`.
43
44Unlike the vocoder this graph is **not** entirely edge-padded — twelve of its eighteen `Pad`s are
45the relative-attention skew and are `constant`. What matters is that every pad feeding a
46*convolution* replicates, which is checked separately.
47
48# The text encoder
49
50`--graph supertonic_ttl` is the same shape again, four times wider, with two additions:
51
52 block gamma [1, 256, 1] -> folds into that block's `pwconv2`, as above
53 tanh(W_key . style_key + b) -> folded to one `[256, 50]` tensor per style attention
54 W_query -> scaled by sqrt(128)/16, since the export's own scale is
55 sqrt(256) and `Builder::attn_scores` uses sqrt(head_dim)
56
57Every projection in its style path is a `MatMul` whose weight is `[in, out]`, so all eight are
58**transposed** here. They are all 256x256, where a missed transpose is invisible in the shape.
59
60Usage:
61 ./scripts/ml/supertonic_fold.py vocoder.onnx --graph supertonic_voc -o vocoder.maml
62 ./scripts/ml/supertonic_fold.py duration_predictor.onnx --graph supertonic_dp -o dp.maml
63 ./scripts/ml/supertonic_fold.py text_encoder.onnx --graph supertonic_ttl -o text.maml
64 ./scripts/ml/supertonic_fold.py vector_estimator.onnx --graph supertonic_ve -o sampler.maml
65"""
66
67import argparse
68import hashlib
69import os
70import sys
71
72import numpy as np
73import onnx
74from onnx import numpy_helper
75
76sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
77import maml_convert # noqa: E402 (needs the path above)
78
79# The vocoder's stack width, and the widening inside each block.
80CHANNELS = 512
81INNER = CHANNELS * 4
82
83# The duration predictor's, and the counts `nets::supertonic_duration` hardcodes.
84DP_CHANNELS = 64
85DP_INNER = 256
86DP_BLOCKS = 6
87DP_ATTN_LAYERS = 2
88DP_HIDDEN = 128
89DP_PREFIX = "tts.dp.sentence_encoder"
90
91# The text encoder's, likewise.
92TE_CHANNELS = 256
93TE_INNER = 1024
94TE_BLOCKS = 6
95TE_ATTN_LAYERS = 4
96TE_STYLE_TOKENS = 50
97TE_STYLE_HEADS = 2
98TE_PREFIX = "tts.ttl.text_encoder"
99TE_STYLE_PREFIX = "tts.ttl.speech_prompted_text_encoder"
100TE_STYLE_KEY = "tts.ttl.style_encoder.style_token_layer.style_key"
101
102# The sampler's. `VE_PREFIX` is where every one of its parameters lives.
103VE_LATENT = 144
104VE_CHANNELS = 512
105VE_INNER = 2048
106VE_TEXT = 256
107VE_STYLE = 256
108VE_STYLE_TOKENS = 50
109VE_TEXT_HEADS = 8
110VE_STYLE_HEADS = 2
111VE_TIME = 64
112VE_TIME_INNER = 256
113VE_MAIN_BLOCKS = 4
114VE_LEADING = [1, 2, 4, 8]
115VE_TRAILING = 4
116VE_PREFIX = "vector_estimator.tts.ttl.vector_field"
117VE_UNCOND = "vector_estimator.tts.ttl.uncond_masker"
118
119
120def constants(graph):
121 """Every initializer and `Constant` node output, by name."""
122 held = {i.name: numpy_helper.to_array(i) for i in graph.initializer}
123 for node in graph.node:
124 if node.op_type == "Constant":
125 for attribute in node.attribute:
126 if attribute.name == "value":
127 held[node.output[0]] = numpy_helper.to_array(attribute.t)
128 return held
129
130
131def edge_padded(graph):
132 """Whether every `Pad` in the graph replicates its border.
133
134 Checked rather than assumed: the folds below are only valid for `edge`, and a future export
135 that switched to `constant` would otherwise fold silently and wrongly.
136 """
137 modes = set()
138 for node in graph.node:
139 if node.op_type != "Pad":
140 continue
141 mode = "constant"
142 for attribute in node.attribute:
143 if attribute.name == "mode":
144 mode = attribute.s.decode()
145 modes.add(mode)
146 return modes == {"edge"}
147
148
149def convolutions_edge_padded(graph):
150 """Whether every `Pad` that feeds a convolution replicates its border.
151
152 Laxer than [`edge_padded`], and it has to be: the duration predictor's relative-attention
153 skew spends twelve `constant` pads on `Slice`s and `Reshape`s, which are not convolutions and
154 are not transcribed. The six that matter are the depthwise ones.
155 """
156 consumers = {}
157 for node in graph.node:
158 for name in node.input:
159 consumers.setdefault(name, []).append(node)
160 for node in graph.node:
161 if node.op_type != "Pad":
162 continue
163 if not any(c.op_type == "Conv" for c in consumers.get(node.output[0], [])):
164 continue
165 mode = "constant"
166 for attribute in node.attribute:
167 if attribute.name == "mode":
168 mode = attribute.s.decode()
169 if mode != "edge":
170 return False
171 return True
172
173
174def fold_into(weight, bias, scale, shift):
175 """`conv(scale * x + shift)` as a convolution on `x`.
176
177 `weight` is `[out, in, k]`, `scale` and `shift` are per **input** channel. The scale rides on
178 the weight; the shift becomes a constant per output channel, which is where the `k` sum
179 comes from.
180 """
181 scaled = weight * scale.reshape(1, -1, 1)
182 added = (weight * shift.reshape(1, -1, 1)).sum(axis=(1, 2))
183 return scaled, bias + added
184
185
186def fold_output(weight, bias, scale, shift):
187 """`scale * conv(x) + shift` as a convolution, for a per-**output**-channel affine."""
188 return weight * scale.reshape(-1, 1, 1), bias * scale + shift
189
190
191def batchnorm_affine(node, held, epsilon=1e-5):
192 """A `BatchNormalization`'s inference-time per-channel scale and shift."""
193 gamma, beta, mean, variance = (held[name] for name in node.input[1:5])
194 for attribute in node.attribute:
195 if attribute.name == "epsilon":
196 epsilon = attribute.f
197 scale = gamma / np.sqrt(variance + epsilon)
198 return scale, beta - mean * scale
199
200
201def collect(graph):
202 """The vocoder's layers and tensors, folded, in the order the Rust reads them."""
203 held = constants(graph)
204 if not edge_padded(graph):
205 raise SystemExit(
206 "this export does not pad every convolution with mode=edge, so the affine folds "
207 "below are not valid; see the module docstring"
208 )
209
210 # The input affine, which precedes `embed`.
211 input_scale = input_shift = None
212 for node in graph.node:
213 if node.op_type in ("Mul", "Add"):
214 sized = [i for i in node.input if i in held and held[i].size == 24]
215 if not sized:
216 continue
217 value = np.asarray(held[sized[0]], dtype=np.float64).reshape(-1)
218 if node.op_type == "Mul" and input_scale is None:
219 input_scale = value
220 elif node.op_type == "Add" and input_shift is None:
221 input_shift = value
222 if input_scale is None or input_shift is None:
223 raise SystemExit("no [24] input affine found ahead of embed")
224
225 # And a scalar divisor at the very head - `normalizer.scale` in tts.json. Folded into the
226 # per-channel scale rather than left for the runtime: dividing by it is multiplying the
227 # affine''s slope, and the shift is applied after the division so it is untouched.
228 divisor = None
229 for node in graph.node:
230 if node.op_type == "Div":
231 scalars = [i for i in node.input if i in held and np.size(held[i]) == 1]
232 if scalars:
233 divisor = float(np.asarray(held[scalars[0]]).reshape(-1)[0])
234 break
235 if divisor is None or divisor == 0.0:
236 raise SystemExit("no scalar Div found at the head of the graph")
237 input_scale = input_scale / divisor
238
239 # Each block's layer scale, and the tail's BatchNormalization.
240 layer_scales = []
241 for node in graph.node:
242 if node.op_type == "Mul" and "convnext" in node.name:
243 sized = [i for i in node.input if i in held and held[i].size == CHANNELS]
244 if sized:
245 layer_scales.append(np.asarray(held[sized[0]], dtype=np.float64).reshape(-1))
246 norm = next((n for n in graph.node if n.op_type == "BatchNormalization"), None)
247 if norm is None:
248 raise SystemExit("no BatchNormalization found ahead of head/layer1")
249 tail_scale, tail_shift = batchnorm_affine(norm, held)
250
251 layers, tensors = [], []
252 scales = iter(layer_scales)
253
254 def add(op, name, weight, bias, key, int8=False):
255 first = len(tensors)
256 if int8:
257 # The three-tensor layout `Builder::conv_int8` reads: kernel, per-output-channel
258 # scale, bias. `Table.conv` emits the same thing for the other graphs; this one
259 # cannot use it because it walks ONNX nodes rather than named parameters.
260 quantised, kernel_scale = maml_convert.quantise_per_channel(weight)
261 tensors.append(quantised)
262 tensors.append(np.ascontiguousarray(kernel_scale, dtype=np.float32))
263 tensors.append(np.ascontiguousarray(bias, dtype=np.float32))
264 layers.append(maml_convert.Layer(len(layers), op, name, key, first, 3))
265 return
266 tensors.append(np.ascontiguousarray(weight, dtype=np.float32))
267 tensors.append(np.ascontiguousarray(bias, dtype=np.float32))
268 layers.append(maml_convert.Layer(len(layers), op, name, key, first, 2))
269
270 for node in graph.node:
271 if node.op_type == "LayerNormalization":
272 # Each block's norm sits between its depthwise and its `pwconv1`, so walking the
273 # graph in order puts its pair in exactly the right place in the table.
274 gamma = np.asarray(held[node.input[1]], dtype=np.float64)
275 beta = np.asarray(held[node.input[2]], dtype=np.float64)
276 add(
277 "LayerNorm",
278 node.name,
279 gamma,
280 beta,
281 f"LayerNorm g={list(gamma.shape)} b={list(beta.shape)}",
282 )
283 continue
284 if node.op_type != "Conv":
285 continue
286 weight = np.asarray(held[node.input[1]], dtype=np.float64)
287 if len(node.input) > 2:
288 bias = np.asarray(held[node.input[2]], dtype=np.float64)
289 else:
290 # `head/layer2` has none; the Rust reads a pair for every layer.
291 bias = np.zeros(weight.shape[0], dtype=np.float64)
292 note = ""
293
294 if "embed" in node.name:
295 weight, bias = fold_into(weight, bias, input_scale, input_shift)
296 note = " folded=input_affine"
297 elif "pwconv2" in node.name:
298 weight, bias = fold_output(weight, bias, next(scales), 0.0)
299 note = " folded=layer_scale"
300 elif "head/layer1" in node.name:
301 weight, bias = fold_into(weight, bias, tail_scale, tail_shift)
302 note = " folded=final_norm"
303 elif len(node.input) == 2:
304 note = " b0=synthesised"
305
306 lifted, _ = maml_convert.lift_to_2d(weight, node)
307 group = 1
308 for attribute in node.attribute:
309 if attribute.name == "group":
310 group = attribute.i
311 # The two `1 x 1`s per block and `head/layer2` are read as int8; `embed`, the depthwise
312 # convolutions and `head/layer1` cannot be. See `nets::supertonic_vocoder::INT8_CONVS`,
313 # which spells out why for each, and must agree with this list.
314 int8 = any(
315 marker in node.name for marker in ("pwconv1", "pwconv2", "head/layer2")
316 )
317 if int8 and (group != 1 or tuple(lifted.shape[2:]) != (1, 1)):
318 raise SystemExit(
319 f"{node.name}: marked int8 but it is g={group} k={list(lifted.shape[2:])};"
320 " only an ungrouped 1x1 can be quantised"
321 )
322 key = (
323 f"{'ConvInt8' if int8 else 'Conv'} w={list(lifted.shape)} b={list(bias.shape)}"
324 f" g={group} pad=edge{note}{' zp=0 dtype=int8' if int8 else ''}"
325 )
326 add("ConvInt8" if int8 else "Conv", node.name, lifted, bias, key, int8=int8)
327
328 # The PReLU sits between the two head convolutions, and its slope is one tensor.
329 if "head/layer1" in node.name:
330 prelu = next(n for n in graph.node if n.op_type == "PRelu")
331 slope = np.asarray(held[prelu.input[1]], dtype=np.float64).reshape(-1)
332 if slope.size != 1:
333 raise SystemExit(f"{prelu.name}: a {slope.size}-element slope, expected one")
334 widened = np.full((INNER, 1, 1), float(slope[0]), dtype=np.float32)
335 first = len(tensors)
336 tensors.append(widened)
337 layers.append(
338 maml_convert.Layer(
339 len(layers),
340 "PRelu",
341 prelu.name,
342 f"PRelu s={list(widened.shape)} shared={float(slope[0]):.6f}",
343 first,
344 1,
345 )
346 )
347
348 remaining = list(scales)
349 if remaining:
350 raise SystemExit(f"{len(remaining)} layer scales were never folded into a pwconv2")
351 return layers, tensors
352
353
354class Table:
355 """The `.maml` layer table under construction, for a graph collected by parameter name.
356
357 The vocoder is a plain stack where walking the ONNX nodes lands each tensor in the right
358 slot. The duration predictor and the text encoder are not: each attention layer interleaves
359 two relative-position tables, several mask multiplies and a twenty-node skew, so naming each
360 tensor is both shorter and checkable against the Rust line by line.
361 """
362
363 def __init__(self, held):
364 self.held = held
365 self.layers = []
366 self.tensors = []
367
368 def at(self, name):
369 if name not in self.held:
370 raise SystemExit(f"{name} is not in this export")
371 return np.asarray(self.held[name], dtype=np.float64)
372
373 def add(self, op, name, key, *values):
374 first = len(self.tensors)
375 for value in values:
376 # int8 goes through as int8: `maml_convert.build` switches on the dtype to decide the
377 # payload, and casting a quantised kernel to fp32 here would make it fp16 in the file
378 # and silently double the size this exists to halve.
379 if getattr(value, "dtype", None) == np.int8:
380 self.tensors.append(np.ascontiguousarray(value))
381 else:
382 self.tensors.append(np.ascontiguousarray(value, dtype=np.float32))
383 self.layers.append(
384 maml_convert.Layer(len(self.layers), op, name, key, first, len(values))
385 )
386
387 def quantised_conv(self, name, key, weight, bias):
388 """Add a convolution whose kernel is quantised, from arrays already in hand.
389
390 The int8 half of [`conv`], factored out because the sampler's attention projections come
391 from `MatMul` weights rather than a named `.weight` - they are transposed, and the query has
392 a scale folded in - so they cannot go through `conv` but must emit the identical
393 three-tensor layout. Two copies of that layout would be two chances to order the scale and
394 the bias differently, and they are the same length, so nothing downstream would notice.
395 """
396 quantised, kernel_scale = maml_convert.quantise_per_channel(weight)
397 self.add("ConvInt8", name, f"{key} zp=0 dtype=int8", quantised, kernel_scale, bias)
398
399 def conv(self, name, out_channels, fold_scale=None, synthesise_bias=False,
400 pads=(0, 0, 0, 0), kernel=(1, 1), group=1, transpose=False, scale=None,
401 int8=False):
402 """One convolution's pair, lifted to the rank-4 `[out, in, 1, k]` the Rust indexes.
403
404 `transpose` is for the style path's `MatMul`s, whose weight is `[in, out]` — all eight of
405 them are 256x256, where a missed transpose is invisible in the shape.
406
407 `int8` emits **three** tensors rather than two — the quantised kernel, its
408 per-output-channel scale, then the bias — for `Builder::conv_int8` rather than
409 `Builder::conv`. It shifts every later tensor index by one, which is why it is opt-in per
410 call site: the Rust side has to move with it.
411
412 The caller decides, because the runtime cannot quantise everything. An int8 convolution
413 has no edge padding and refuses `Act::PRelu`, so only the ungrouped `1 x 1`s are eligible
414 — which is where 92% of the parameters are anyway.
415 """
416 weight = self.at(f"{name}.weight")
417 if synthesise_bias:
418 bias = np.zeros(out_channels, dtype=np.float64)
419 else:
420 bias = self.at(f"{name}.bias")
421 if transpose:
422 weight = weight.T
423 if fold_scale is not None:
424 weight, bias = fold_output(weight, bias, fold_scale, 0.0)
425 if scale is not None:
426 weight, bias = weight * scale, bias * scale
427 if weight.ndim == 2:
428 # A `Gemm`'s `[out, in]`, at `transB=1`, is already the convolution's layout.
429 weight = weight.reshape(weight.shape[0], weight.shape[1], 1, 1)
430 elif weight.ndim == 3:
431 weight = weight.reshape(weight.shape[0], weight.shape[1], 1, weight.shape[2])
432 note = " b0=synthesised" if synthesise_bias else ""
433 note += " folded=layer_scale" if fold_scale is not None else ""
434 note += " transposed" if transpose else ""
435 note += f" scaled={scale:.6f}" if scale is not None else ""
436 if not int8:
437 self.add(
438 "Conv",
439 name,
440 f"Conv w={list(weight.shape)} b={list(bias.shape)} k={list(kernel)}"
441 f" p={list(pads)} g={group} pad=edge{note}",
442 weight,
443 bias,
444 )
445 return
446 # Every quantisation this script performs must be one the shaders can serve, and both
447 # int8 shaders zero-pad and index the kernel ungrouped. Refusing here rather than in the
448 # Rust means a wrong call site fails at conversion, when there is still a `.maml` to
449 # compare against, instead of at `Builder::finish` with the tensor indices already shifted.
450 if group != 1 or tuple(kernel) != (1, 1) or tuple(pads) != (0, 0, 0, 0):
451 raise SystemExit(
452 f"{name}: only an ungrouped, unpadded 1x1 can be int8 — this is "
453 f"k={list(kernel)} p={list(pads)} g={group}"
454 )
455 quantised, kernel_scale = maml_convert.quantise_per_channel(weight)
456 self.add(
457 "ConvInt8",
458 name,
459 f"ConvInt8 w={list(weight.shape)} scale={list(kernel_scale.shape)}"
460 f" b={list(bias.shape)} k={list(kernel)} p={list(pads)} g={group}"
461 f" zp=0 dtype=int8{note}",
462 quantised,
463 kernel_scale,
464 bias,
465 )
466
467 def layer_norm(self, name):
468 gamma = self.at(f"{name}.weight")
469 beta = self.at(f"{name}.bias")
470 self.add(
471 "LayerNorm",
472 name,
473 f"LayerNorm g={list(gamma.shape)} b={list(beta.shape)}",
474 gamma,
475 beta,
476 )
477
478 def convnext(self, at, channels, inner, dilation, int8=False):
479 """One ConvNeXt block: depthwise, norm, widening 1x1, narrowing 1x1 with the gamma.
480
481 Symmetric padding, `2 * dilation` each side. The vocoder's is causal instead, and that
482 difference cost real debugging time once already.
483
484 `int8` quantises the two `1 x 1`s and not the depthwise one, which is the only split the
485 shaders allow: `conv_int8.comp` zero-pads where this block replicates, and a 5-tap depthwise
486 has a border to get wrong where a `1 x 1` has none.
487 """
488 each = dilation * 4 // 2
489 self.conv(
490 f"{at}.dwconv",
491 channels,
492 pads=(0, each, 0, each),
493 kernel=(1, 5),
494 group=channels,
495 )
496 self.layer_norm(f"{at}.norm.norm")
497 self.conv(f"{at}.pwconv1", inner, int8=int8)
498 # The block's gamma rides on `pwconv2`, which is a 1x1 and so has no border.
499 self.conv(
500 f"{at}.pwconv2",
501 channels,
502 fold_scale=self.at(f"{at}.gamma").reshape(-1),
503 int8=int8,
504 )
505
506 def relative_attention(self, at, layer, channels, inner, head_dim, int8=False):
507 """One post-norm relative-attention layer, in the order the export declares it.
508
509 `int8` quantises all six convolutions - every one is an ungrouped `1 x 1`. The two relative
510 position tables stay fp16: they are read by `attn_scores_relative.comp` rather than by a
511 convolution, and there is no int8 path through it.
512 """
513 attn = f"{at}.attn_layers.{layer}"
514 for projection in ("conv_q", "conv_k", "conv_v"):
515 self.conv(f"{attn}.{projection}", channels, int8=int8)
516 # `[1, 9, head_dim]` in the export; the Rust reads `[offsets, head_dim]`.
517 for table_name in ("emb_rel_k", "emb_rel_v"):
518 relative = self.at(f"{attn}.{table_name}").reshape(9, -1)
519 if relative.shape[1] != head_dim:
520 raise SystemExit(f"{attn}.{table_name} is {list(relative.shape)}, not [9, {head_dim}]")
521 self.add("RelPos", f"{attn}.{table_name}", f"RelPos t={list(relative.shape)}", relative)
522 self.conv(f"{attn}.conv_o", channels, int8=int8)
523 self.layer_norm(f"{at}.norm_layers_1.{layer}.norm")
524 self.conv(f"{at}.ffn_layers.{layer}.conv_1", inner, int8=int8)
525 self.conv(f"{at}.ffn_layers.{layer}.conv_2", channels, int8=int8)
526 self.layer_norm(f"{at}.norm_layers_2.{layer}.norm")
527
528
529def collect_duration(graph):
530 """The duration predictor's layers and tensors, folded, in the order the Rust reads them."""
531 held = constants(graph)
532 if not convolutions_edge_padded(graph):
533 raise SystemExit(
534 "this export does not pad every convolution with mode=edge, so the layer-scale "
535 "fold below is not valid; see the module docstring"
536 )
537 table = Table(held)
538
539 # The embedding table, with `sentence_token` as its last row. The token is prepended to the
540 # sequence in the export and read back out of position 0 at the end; making it a row of the
541 # table is how a plan with no sequence-axis concat expresses that.
542 rows = table.at(f"{DP_PREFIX}.text_embedder.char_embedder.weight")
543 token = table.at(f"{DP_PREFIX}.sentence_token").reshape(1, -1)
544 if token.shape[1] != rows.shape[1]:
545 raise SystemExit(f"a {list(token.shape)} sentence token for a {list(rows.shape)} table")
546 rows = np.concatenate([rows, token], axis=0)
547 table.add(
548 "Embed", "char_embedder+sentence_token", f"Embed t={list(rows.shape)} token=last", rows
549 )
550
551 for block in range(DP_BLOCKS):
552 table.convnext(f"{DP_PREFIX}.convnext.convnext.{block}", DP_CHANNELS, DP_INNER, 1, int8=True)
553 for layer in range(DP_ATTN_LAYERS):
554 table.relative_attention(
555 f"{DP_PREFIX}.attn_encoder", layer, DP_CHANNELS, DP_INNER, 32, int8=True
556 )
557
558 # `proj_out` has no bias in the export; the Rust reads a pair for every convolution.
559 table.conv(f"{DP_PREFIX}.proj_out.net", DP_CHANNELS, synthesise_bias=True)
560 table.conv("tts.dp.predictor.layers.0", DP_HIDDEN)
561
562 prelu = next(n for n in graph.node if n.op_type == "PRelu")
563 slope = np.asarray(held[prelu.input[1]], dtype=np.float64).reshape(-1)
564 if slope.size != 1:
565 raise SystemExit(f"{prelu.name}: a {slope.size}-element slope, expected one")
566 widened = np.full((DP_HIDDEN, 1, 1), float(slope[0]), dtype=np.float32)
567 table.add(
568 "PRelu",
569 prelu.name,
570 f"PRelu s={list(widened.shape)} shared={float(slope[0]):.6f}",
571 widened,
572 )
573
574 table.conv("tts.dp.predictor.layers.1", 1)
575 return table.layers, table.tensors
576
577
578def style_attention(table, graph, which):
579 """One of the text encoder's two cross-attentions over the 50 style tokens.
580
581 Four entries: `W_query` (scaled), the folded constant keys, `W_value` and `out_fc`.
582 """
583 at = f"{TE_STYLE_PREFIX}.attention{which}"
584 linears = matmul_weights(
585 graph, table.held, f"/speech_prompted_text_encoder/attention{which}/"
586 )
587 head_dim = TE_CHANNELS // TE_STYLE_HEADS
588 # The export divides the scores by 16 = sqrt(256), not by sqrt(head_dim) = sqrt(128), so
589 # `Builder::attn_scores`'s own scale is sqrt(2) too large. Folding the difference into the
590 # query projection is exact and costs no op.
591 scale = np.sqrt(head_dim) / 16.0
592 square = [TE_CHANNELS, TE_CHANNELS, 1, 1]
593 table.add(
594 "Conv",
595 f"{at}.W_query",
596 f"Conv w={square} b={[TE_CHANNELS]} k={[1, 1]} p={[0, 0, 0, 0]} g=1 pad=edge"
597 f" transposed scaled={scale:.6f}",
598 (linears["W_query"].T * scale).reshape(*square),
599 table.at(f"{at}.W_query.linear.bias") * scale,
600 )
601
602 # `tanh(W_key . style_key + b_key)` is entirely constant, so it folds to one tensor. Stored
603 # channel-major as `[256, 1, 50]`, which is what `Kind::Constant` loads and
604 # `Kind::AttnScores` contracts.
605 style_key = table.at(TE_STYLE_KEY).reshape(-1, TE_CHANNELS)
606 keys = np.tanh(style_key @ linears["W_key"] + table.at(f"{at}.W_key.linear.bias"))
607 if keys.shape != (TE_STYLE_TOKENS, TE_CHANNELS):
608 raise SystemExit(f"{at}: folded keys are {list(keys.shape)}")
609 keys = np.ascontiguousarray(keys.T).reshape(TE_CHANNELS, 1, TE_STYLE_TOKENS)
610 table.add(
611 "Constant",
612 f"{at}.keys",
613 f"Constant t={list(keys.shape)} folded=tanh(W_key.style_key+b_key)",
614 keys,
615 )
616
617 for name in ("W_value", "out_fc"):
618 table.add(
619 "Conv",
620 f"{at}.{name}",
621 f"Conv w={square} b={[TE_CHANNELS]} k={[1, 1]} p={[0, 0, 0, 0]} g=1 pad=edge"
622 " transposed",
623 linears[name].T.reshape(*square),
624 table.at(f"{at}.{name}.linear.bias"),
625 )
626
627
628def matmul_weights(graph, held, prefix):
629 """The four `MatMul` weights under the node-name `prefix`, by the linear they belong to.
630
631 They are `onnx::MatMul_3680` and friends rather than named parameters, so each is found
632 through the node that consumes it.
633 """
634 wanted = ("W_query", "W_key", "W_value", "out_fc")
635 found = {}
636 for node in graph.node:
637 if node.op_type != "MatMul" or not node.name.startswith(prefix):
638 continue
639 for name in wanted:
640 if f"/{name}/" not in node.name:
641 continue
642 weights = [i for i in node.input if i in held]
643 if len(weights) != 1:
644 raise SystemExit(f"{node.name} has {len(weights)} held inputs, expected one")
645 found[name] = np.asarray(held[weights[0]], dtype=np.float64)
646 missing = set(wanted) - set(found)
647 if missing:
648 raise SystemExit(f"{prefix}: no MatMul found for {sorted(missing)}")
649 return found
650
651
652def collect_text(graph):
653 """The text encoder's layers and tensors, folded, in the order the Rust reads them."""
654 held = constants(graph)
655 if not convolutions_edge_padded(graph):
656 raise SystemExit(
657 "this export does not pad every convolution with mode=edge, so the layer-scale "
658 "fold below is not valid; see the module docstring"
659 )
660 table = Table(held)
661
662 rows = table.at(f"{TE_PREFIX}.text_embedder.char_embedder.weight")
663 table.add("Embed", "char_embedder", f"Embed t={list(rows.shape)}", rows)
664
665 # 1, 1, 2, 2, 4, 4 - pairs, and the pad follows the dilation.
666 for block, dilation in enumerate([1, 1, 2, 2, 4, 4]):
667 table.convnext(f"{TE_PREFIX}.convnext.convnext.{block}", TE_CHANNELS, TE_INNER, dilation)
668 for layer in range(TE_ATTN_LAYERS):
669 table.relative_attention(f"{TE_PREFIX}.attn_encoder", layer, TE_CHANNELS, TE_INNER, 64)
670
671 for which in (1, 2):
672 style_attention(table, graph, which)
673 table.layer_norm(f"{TE_STYLE_PREFIX}.norm.norm")
674 return table.layers, table.tensors
675
676
677def collect_sampler(graph):
678 """The sampler's layers and tensors, folded, in the order the Rust reads them.
679
680 Four main blocks of `convnext x4, timestep shift, convnext, text attention, convnext, style
681 attention`, then four trailing ConvNeXt blocks, between two unbiased projections. The
682 export flattens the four into `main_blocks.0` .. `main_blocks.23`, six entries each.
683 """
684 held = constants(graph)
685 if not convolutions_edge_padded(graph):
686 raise SystemExit(
687 "this export does not pad every convolution with mode=edge, so the layer-scale "
688 "fold below is not valid; see the module docstring"
689 )
690 table = Table(held)
691
692 def matmul(prefix, name):
693 return matmul_weights(graph, held, prefix)[name]
694
695 def linear(at, prefix, name, out_channels):
696 """One `MatMul` plus its bias, as a quantised 1x1 convolution. The weight is `[in, out]`."""
697 weight = matmul(prefix, name).T
698 bias = table.at(f"{at}.{name}.linear.bias")
699 if weight.shape[0] != out_channels:
700 raise SystemExit(f"{at}.{name} is {list(weight.shape)}, not [{out_channels}, in]")
701 table.quantised_conv(
702 f"{at}.{name}",
703 f"Conv w={[*weight.shape, 1, 1]} b={list(bias.shape)} k={[1, 1]}"
704 f" p={[0, 0, 0, 0]} g=1 pad=edge transposed",
705 weight.reshape(weight.shape[0], weight.shape[1], 1, 1),
706 bias,
707 )
708
709 def scaled_query(at, prefix, out_channels, heads):
710 """`W_query`, with the difference between the export's /16 and 1/sqrt(head_dim) folded in.
711
712 Both attentions divide by 16. `Builder::attn_scores` divides by `sqrt(head_dim)`, so the
713 query carries `sqrt(head_dim) / 16` - exact, and safe across the rotary because a
714 rotation commutes with a scalar.
715 """
716 scale = np.sqrt(out_channels / heads) / 16.0
717 weight = matmul(prefix, "W_query").T * scale
718 bias = table.at(f"{at}.W_query.linear.bias") * scale
719 table.quantised_conv(
720 f"{at}.W_query",
721 f"Conv w={[*weight.shape, 1, 1]} b={list(bias.shape)} k={[1, 1]}"
722 f" p={[0, 0, 0, 0]} g=1 pad=edge transposed scaled={scale:.6f}",
723 weight.reshape(weight.shape[0], weight.shape[1], 1, 1),
724 bias,
725 )
726
727 table.conv(f"{VE_PREFIX}.proj_in.net", VE_CHANNELS, synthesise_bias=True, int8=True)
728 for block in range(VE_MAIN_BLOCKS):
729 base = block * 6
730 for layer, dilation in enumerate(VE_LEADING):
731 table.convnext(
732 f"{VE_PREFIX}.main_blocks.{base}.convnext.{layer}",
733 VE_CHANNELS,
734 VE_INNER,
735 dilation,
736 int8=True,
737 )
738 # `main_blocks.{base + 1}` is the timestep `Linear`, evaluated on the host.
739 table.convnext(
740 f"{VE_PREFIX}.main_blocks.{base + 2}.convnext.0", VE_CHANNELS, VE_INNER, 1, int8=True
741 )
742
743 at = f"{VE_PREFIX}.main_blocks.{base + 3}.attn"
744 prefix = f"/vector_estimator/vector_field/main_blocks.{base + 3}/attn/"
745 scaled_query(at, prefix, VE_CHANNELS, VE_TEXT_HEADS)
746 linear(at, prefix, "W_key", VE_CHANNELS)
747 linear(at, prefix, "W_value", VE_CHANNELS)
748 linear(at, prefix, "out_fc", VE_CHANNELS)
749 table.layer_norm(f"{VE_PREFIX}.main_blocks.{base + 3}.norm.norm")
750
751 table.convnext(
752 f"{VE_PREFIX}.main_blocks.{base + 4}.convnext.0", VE_CHANNELS, VE_INNER, 1, int8=True
753 )
754
755 at = f"{VE_PREFIX}.main_blocks.{base + 5}.attention"
756 prefix = f"/vector_estimator/vector_field/main_blocks.{base + 5}/attention/"
757 scaled_query(at, prefix, VE_STYLE, VE_STYLE_HEADS)
758 linear(at, prefix, "W_value", VE_STYLE)
759 linear(at, prefix, "out_fc", VE_CHANNELS)
760 table.layer_norm(f"{VE_PREFIX}.main_blocks.{base + 5}.norm.norm")
761
762 for layer in range(VE_TRAILING):
763 table.convnext(
764 f"{VE_PREFIX}.last_convnext.convnext.{layer}", VE_CHANNELS, VE_INNER, 1, int8=True
765 )
766 table.conv(f"{VE_PREFIX}.proj_out.net", VE_LATENT, synthesise_bias=True, int8=True)
767
768 # Everything from here is read on the host. `nets::Builder::host_tensor` names each, so an
769 # accidentally unread weight is still an error.
770 theta = table.at(f"{VE_PREFIX}.main_blocks.3.attn.theta").reshape(-1)
771 table.add("Host", "rotary theta", f"Host t={list(theta.shape)} rotary=theta", theta)
772 frequencies = table.at(
773 "/vector_estimator/vector_field/time_encoder/sinusoidal/Constant_3_output_0"
774 ).reshape(-1)
775 table.add(
776 "Host", "time frequencies", f"Host t={list(frequencies.shape)} time=frequencies", frequencies
777 )
778
779 for which, (rows, columns) in (("mlp.0", (VE_TIME_INNER, VE_TIME)), ("mlp.2", (VE_TIME, VE_TIME_INNER))):
780 at = f"{VE_PREFIX}.time_encoder.mlp.{which.split('.')[1]}.linear"
781 weight = table.at(f"{at}.weight")
782 bias = table.at(f"{at}.bias")
783 if list(weight.shape) != [rows, columns]:
784 raise SystemExit(f"{at} is {list(weight.shape)}, not {[rows, columns]}")
785 table.add(
786 "Host",
787 at,
788 f"Host w={list(weight.shape)} b={list(bias.shape)} time={which}",
789 weight,
790 bias,
791 )
792
793 for block in range(VE_MAIN_BLOCKS):
794 base = block * 6 + 1
795 at = f"{VE_PREFIX}.main_blocks.{base}.linear.linear"
796 prefix = f"/vector_estimator/vector_field/main_blocks.{base}/linear/linear/"
797 node = next(n for n in graph.node if n.name == f"{prefix}MatMul")
798 weight = np.asarray(held[next(i for i in node.input if i in held)], dtype=np.float64).T
799 bias = table.at(f"{at}.bias")
800 table.add(
801 "Host",
802 at,
803 f"Host w={list(weight.shape)} b={list(bias.shape)} time=shift{block} transposed",
804 weight,
805 bias,
806 )
807
808 token = table.at(f"{VE_UNCOND}.text_special_token").reshape(-1)
809 table.add("Host", "text_special_token", f"Host t={list(token.shape)} uncond=text", token)
810 style = np.ascontiguousarray(
811 table.at(f"{VE_UNCOND}.style_value_special_token").reshape(-1, VE_STYLE).T
812 )
813 table.add("Host", "style_value_special_token", f"Host t={list(style.shape)} uncond=style", style)
814
815 # The two branches' style keys, `tanh(W_key . style_key + b_key)`, entirely constant. The
816 # conditional key is a nameless initializer reached through the `Tile` that broadcasts it.
817 for label, source in (("conditional", conditional_style_key(graph, held)), ("unconditional", f"{VE_UNCOND}.style_key_special_token")):
818 # One `style_key` but four `W_key`s, so four folded tensors per branch, stacked along
819 # channels for `Builder::slice_channels` to cut apart. Folding only the first left the
820 # net exact through ten sub-blocks and then wrong, which is what the bisect found.
821 stacked = []
822 for block in range(VE_MAIN_BLOCKS):
823 index = block * 6 + 5
824 keys = matmul_weights(
825 graph, held, f"/vector_estimator/vector_field/main_blocks.{index}/attention/"
826 )["W_key"]
827 bias = table.at(f"{VE_PREFIX}.main_blocks.{index}.attention.W_key.linear.bias")
828 folded = np.tanh(table.at(source).reshape(-1, VE_STYLE) @ keys + bias)
829 if folded.shape != (VE_STYLE_TOKENS, VE_STYLE):
830 raise SystemExit(f"{label} keys for block {block} folded to {list(folded.shape)}")
831 stacked.append(np.ascontiguousarray(folded.T))
832 folded = np.concatenate(stacked, axis=0)
833 table.add(
834 "Host",
835 f"style keys {label}",
836 f"Host t={list(folded.shape)} folded=tanh(W_key.style_key+b) {label}",
837 folded,
838 )
839 return table.layers, table.tensors
840
841
842def conditional_style_key(graph, held):
843 """The name of the conditional `style_key`, which the export leaves nameless.
844
845 It reaches `W_key` through a `Concat` of a `Tile` of itself and an `Expand` of the
846 unconditional token, so it is found rather than spelled.
847 """
848 producer = {o: n for n in graph.node for o in n.output}
849 node = next(
850 n
851 for n in graph.node
852 if n.name == "/vector_estimator/vector_field/main_blocks.5/attention/W_key/linear/MatMul"
853 )
854 concat = producer[node.input[0]]
855 for branch in concat.input:
856 broadcast = producer[branch]
857 for name in broadcast.input:
858 if name in held and list(np.asarray(held[name]).shape) == [1, VE_STYLE_TOKENS, VE_STYLE]:
859 if "uncond" not in name:
860 return name
861 raise SystemExit("no conditional style_key found ahead of the style W_key")
862
863
864def main():
865 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
866 parser.add_argument("onnx")
867 parser.add_argument("--graph", required=True, choices=sorted(maml_convert.GRAPHS))
868 parser.add_argument("-o", "--out")
869 parser.add_argument("--print-layers", action="store_true")
870 parser.add_argument("--print-digest", action="store_true")
871 args = parser.parse_args()
872
873 raw = open(args.onnx, "rb").read()
874 onnx_sha256 = hashlib.sha256(raw).digest()
875 model = onnx.load(args.onnx)
876 if args.graph == "supertonic_dp":
877 layers, tensors = collect_duration(model.graph)
878 elif args.graph == "supertonic_ttl":
879 layers, tensors = collect_text(model.graph)
880 elif args.graph == "supertonic_ve":
881 layers, tensors = collect_sampler(model.graph)
882 else:
883 layers, tensors = collect(model.graph)
884
885 if args.print_layers:
886 for layer in layers:
887 print(f"{layer.index:4d} t{layer.first_tensor:<4d} {layer.key()} # {layer.name}")
888 digest = maml_convert.layer_table_digest(layers)
889 if args.print_digest:
890 print(f' "{args.graph}": "{digest}",')
891 pinned = maml_convert.EXPECTED_DIGEST.get(args.graph, "")
892 if digest != pinned and not args.print_digest:
893 raise SystemExit(
894 f"layer table digest {digest}\n pinned {pinned}\n"
895 "The folded layer table changed, so the hardcoded forward pass no longer\n"
896 "matches this export. Re-read it, update the Rust, then re-pin with\n"
897 "--print-digest."
898 )
899
900 blob, count = maml_convert.build(
901 layers, tensors, maml_convert.GRAPHS[args.graph], onnx_sha256
902 )
903 if args.out:
904 with open(args.out, "wb") as f:
905 f.write(blob)
906 print(
907 f"{args.graph}: {count} folded layers, {len(tensors)} tensors, "
908 f"{len(blob)} bytes ({len(raw)} fp32 in)"
909 )
910
911
912if __name__ == "__main__":
913 main()