# SPDX-License-Identifier: Apache-2.0 # Copyright 2026 Kale """precision variants of an fp32 one-file graph (same weights). The release used it once: A (fp32 export + exact decoder rewrites) -> D-fixed with `--dec int8 --text fp16 --keep32 et,st,pred --table fp32` (config/precision.json "d_fixed"): the tiny decoder's int8 tensors (the earlier tiny's 31, bit-identical), the decoder text encoder fp16, everything else fp32. prec2.py then works on D-fixed. --dec int8|fp32 decoder weights (dec.* / head.* initializers, >= 1024 values): int8 per OUTPUT row (axis 0 for Conv [out,..] and Gemm transB [out,in], as the release small_copy), or fp32 --text fp16|fp32 every other float initializer >= 64 values (LSTM weights included) fp16 (Cast) or fp32 --table int8|fp16|fp32 Ettin's word table (et.embeddings.tok_embeddings.weight, 50368x256): int8 per ROW (Gather int8 rows + their scales), fp16, or fp32 usage: prec.py in.onnx out.onnx --dec .. --text .. --table ..""" import argparse, numpy as np, onnx from onnx import numpy_helper as nh, helper as h, TensorProto as TP ap = argparse.ArgumentParser(); ap.add_argument("src"); ap.add_argument("dst") ap.add_argument("--keep32", default="", help="comma list of blocks kept fp32 when --text fp16: et, st, pred, te (by consumer node name)"); ap.add_argument("--dec", default="int8"); ap.add_argument("--text", default="fp16"); ap.add_argument("--table", default="int8"); a = ap.parse_args() m = onnx.load(a.src); g = m.graph cons = {} for n in g.node: for k, i in enumerate(n.input): cons.setdefault(i, []).append((n, k)) lstm_w = {n.input[i] for n in g.node if n.op_type == "LSTM" for i in (1, 2)} KEEP = [x for x in a.keep32.split(",") if x] def block(name): # the block an initializer belongs to, from its name or its first consumer's node name if name in lstm_w and any(n.name.strip("/").split("/")[0] not in ("et", "st", "te", "lstm_1") for n, _ in cons.get(name, [])): return "plstm" for b in ("et", "st", "pred", "te"): if name.startswith(b + "."): return b for n, _ in cons.get(name, []): seg = n.name.strip("/").split("/")[0] if seg in ("et", "st", "te"): return seg if seg.startswith(("lstm", "duration_proj", "F0", "N", "shared", "text_encoder", "pred")) or "predictor" in n.name: return "pred" return None TABLE = "et.embeddings.tok_embeddings.weight" new, stat = [], dict(int8=0, fp16=0, table=a.table) for init in list(g.initializer): w = nh.to_array(init); name = init.name if w.dtype != np.float32: continue is_dec = name.startswith(("dec.", "head.")) or name.startswith(("kdec.",)) if is_dec and any(x in name for x in (".fwd", ".inv", ".w2")): # exact DFT bases / window sums: never quantised (the old graph generates them in fp32) continue if name == TABLE: if a.table == "int8": sc = (np.abs(w).max(1) / 127).astype(np.float32); sc[sc == 0] = 1 q = np.clip(np.round(w / sc[:, None]), -127, 127).astype(np.int8) g.initializer.remove(init); g.initializer.extend([nh.from_array(q, name + "_q8"), nh.from_array(sc, name + "_rs")]) for n, k in cons[name]: # Gather(table, ids) -> Cast(Gather(q, ids)) * Unsqueeze(Gather(scale, ids)) assert n.op_type == "Gather" and k == 0 out = n.output[0]; ids = n.input[1]; p = n.name + "_pr" n.input[0] = name + "_q8"; n.output[0] = p + "_q" new.append(("after", n, [h.make_node("Cast", [p + "_q"], [p + "_f"], to=TP.FLOAT, name=p + "_cast"), h.make_node("Gather", [name + "_rs", ids], [p + "_s"], name=p + "_gs"), h.make_node("Unsqueeze", [p + "_s", "prec_m1"], [p + "_su"], name=p + "_un"), h.make_node("Mul", [p + "_f", p + "_su"], [out], name=p + "_mul")])) stat["table_mb"] = round((q.size + sc.size * 4) / 1e6, 2) elif a.table == "fp16": g.initializer.remove(init); g.initializer.append(nh.from_array(w.astype(np.float16), name + "_16")) new.append(("pre", None, [h.make_node("Cast", [name + "_16"], [name], to=TP.FLOAT)])); stat["fp16"] += 1 continue if is_dec and a.dec == "int8" and w.ndim >= 2 and w.size >= 1024 and name not in lstm_w: uses = cons.get(name, []) ok = all(n.op_type == "Conv" or (n.op_type == "Gemm" and k == 1 and any(x.name == "transB" and x.i == 1 for x in n.attribute)) for n, k in uses) if ok: sc = np.abs(w).reshape(w.shape[0], -1).max(1) / 127; sc[sc == 0] = 1 q = np.clip(np.round(w / sc.reshape((-1,) + (1,) * (w.ndim - 1))), -127, 127).astype(np.int8); g.initializer.remove(init) g.initializer.extend([nh.from_array(q, name + "_q"), nh.from_array(sc.astype(np.float16), name + "_s16"), nh.from_array(np.zeros(len(sc), np.int8), name + "_z")]) new.append(("pre", None, [h.make_node("Cast", [name + "_s16"], [name + "_s"], to=TP.FLOAT), h.make_node("DequantizeLinear", [name + "_q", name + "_s", name + "_z"], [name], axis=0)])) stat["int8"] += 1; continue if not is_dec and a.text == "fp16" and w.size >= 64 and np.abs(w).max() < 6e4 and block(name) not in KEEP and not (block(name) == "plstm" and "pred" in KEEP) and not (block(name) == "pred" and "pnolstm" in KEEP): g.initializer.remove(init); g.initializer.append(nh.from_array(w.astype(np.float16), name + "_16")) new.append(("pre", None, [h.make_node("Cast", [name + "_16"], [name], to=TP.FLOAT)])); stat["fp16"] += 1 g.initializer.append(nh.from_array(np.array([-1], np.int64), "prec_m1")) nodes = list(g.node); pre = [x for t, _, ns in new if t == "pre" for x in ns] for t, anchor, ns in new: if t == "after": i = nodes.index(anchor); nodes[i + 1:i + 1] = ns g.ClearField("node"); g.node.extend(pre + nodes) onnx.save(m, a.dst); import os; stat["mb"] = round(os.path.getsize(a.dst) / 1e6, 2); print(a.dst, stat)