NERDDISCO's picture
kale-tts-1
f21d6eb
Raw History Blame Contribute Delete
9.09 kB
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Kale
"""ettin-q: per-group weight precision on top of D-fixed (prec.py: its decoder is already the earlier tiny's int8 and te fp16; every other
weight fp32). The release groups: config/precision.json "ettin_q".
Weight-only quantisation: int8 = symmetric, one scale per OUTPUT channel on the right axis for each consumer (MatMul B [in,out] -> axis 1;
Conv [out,..] / Gemm transB [out,in] -> axis 0; LSTM W/R [dirs,4H,in] -> one scale per (dir, gate row); Gather tables -> per row), then
DequantizeLinear back to fp32 in the graph (activations stay fp32). fp16 = Cast back to fp32.
groups (by consumer node): table (Ettin word table), et (Ettin layers), st (phoneme encoder + word projection), tenc (predictor text encoder
LSTMs lstms.0/2/4 + their AdaLayerNorm fc lstms.1/3/5), dlstm (/lstm/ duration LSTM), dproj (duration_proj), shared (/shared/ LSTM),
f0n (F0.* / N.* / F0_proj / N_proj), te (decoder text encoder: te.* fp16 tensors re-quantised from fp16 + /lstm_1/).
table modes: fp32 | fp16 | int8 (per row: Gather int8 rows + Gather their scales) | hyb<K> (rows of the K most frequent tokens fp32, the rest int8
per row; frequency = Ettin token counts over the text side's training sentences, ties by id).
Token counts for hyb<K>: --counts config/ettin_token_counts.json (the release run's counts, shipped) or --freq-text work/sents_us.jsonl
(recount; needs --tokenizer ../../models/kale-tts-1-tiny/ettin-tokenizer.json and `pip install tokenizers`).
usage: prec2.py D-fixed.onnx out.onnx [--counts f.json | --freq-text sents.jsonl --tokenizer ettin-tokenizer.json] group=mode ...
(mode fp32|fp16|int8; table also hyb<K>)"""
import sys, os, json, collections, numpy as np, onnx
from onnx import numpy_helper as nh, helper as h, TensorProto as TP
args = sys.argv[1:]; OPT = {}
for k in ("--counts", "--freq-text", "--tokenizer"):
if k in args: i = args.index(k); OPT[k] = args[i + 1]; del args[i:i + 2]
src, dst = args[0], args[1]; P = dict(a.split("=") for a in args[2:])
m = onnx.load(src); g = m.graph
cons = {}
for n in g.node:
for k, i in enumerate(n.input): cons.setdefault(i, []).append((n, k))
TABLE = "et.embeddings.tok_embeddings.weight"
def group(name):
if name == TABLE: return "table"
us = cons.get(name, [])
if name.endswith("_16") and name.startswith(("te.", "onnx::")): # fp16 tensors: follow the Cast
c = [n for n, _ in us if n.op_type == "Cast"]
return "te" if name.startswith("te.") else None
segs = {n.name.strip("/").split("/")[0] for n, _ in us}
if not segs: return None
s = sorted(segs)[0]
if s == "et": return "et"
if s == "st": return "st"
if s in ("lstms.0", "lstms.1", "lstms.2", "lstms.3", "lstms.4", "lstms.5"): return "tenc"
if s == "lstm": return "dlstm"
if s == "duration_proj": return "dproj"
if s == "shared": return "shared"
if s.startswith(("F0", "N.", "N_")) or s in ("F0_proj", "N_proj"): return "f0n"
if s == "lstm_1": return "te"
return None
pre, after, stat = [], [], collections.Counter()
def q8(w, axis):
wm = np.moveaxis(w, axis, 0); sc = np.abs(wm.reshape(wm.shape[0], -1)).max(1) / 127; sc[sc == 0] = 1
q = np.clip(np.round(wm / sc.reshape((-1,) + (1,) * (w.ndim - 1))), -127, 127).astype(np.int8)
return np.moveaxis(q, 0, axis), sc.astype(np.float32)
def axis_for(name, w):
us = cons[name]; ax = set()
for n, k in us:
if n.op_type == "MatMul" and k == 1: ax.add(w.ndim - 1)
elif n.op_type in ("Conv",) and k == 1: ax.add(0)
elif n.op_type == "Gemm" and k == 1: ax.add(0 if any(a.name == "transB" and a.i == 1 for a in n.attribute) else 1)
elif n.op_type == "Gather" and k == 0: ax.add(0)
elif n.op_type == "LSTM" and k in (1, 2): ax.add(-1)
else: return None
return ax.pop() if len(ax) == 1 else None
def freq_order():
c = collections.Counter()
if "--counts" in OPT:
c.update({int(k): v for k, v in json.load(open(OPT["--counts"]))["counts"].items()})
else:
from tokenizers import Tokenizer
tok = Tokenizer.from_file(OPT["--tokenizer"])
for l in open(OPT["--freq-text"]):
c.update(tok.encode(json.loads(l)["text"]).ids)
return sorted(range(50368), key=lambda i: (-c[i], i)), c
for init in list(g.initializer):
name = init.name; grp = None if name.startswith(("dec.", "head.", "kdec.")) else group(name); mode = P.get(grp)
if not mode or mode == "fp32" and not name.endswith("_16"): continue
w = nh.to_array(init)
if name.endswith("_16"): # te's fp16 tensor: fp16 stays, int8 re-quantises from it
if mode != "int8": continue
base = name[:-3]; c = [n for n, _ in cons[name] if n.op_type == "Cast"][0]
w = w.astype(np.float32); g.initializer.remove(init); g.node.remove(c); cons[base] = cons.get(base, []); name = base
else:
g.initializer.remove(init)
if grp == "table" and mode != "fp16":
V, D = w.shape; ids_users = cons[TABLE]
if mode == "int8": order, K = list(range(V)), 0
else: K = int(mode[3:]); order, cnt = freq_order(); stat["table_K_cover"] = round(sum(cnt[i] for i in order[:K]) / max(1, sum(cnt.values())), 6)
order = np.array(order); remap = np.empty(V, np.int64); remap[order] = np.arange(V)
hi, lo = w[order[:K]], w[order[K:]]; q, sc = q8(lo, 0)
g.initializer.extend([nh.from_array(q, "tab_q8"), nh.from_array(sc, "tab_rs")])
if K: g.initializer.extend([nh.from_array(hi.astype(np.float32), "tab_hi"), nh.from_array(remap, "tab_remap"), nh.from_array(np.array(K, np.int64), "tab_K"),
nh.from_array(np.array(0, np.int64), "tab_0"), nh.from_array(np.array(K - 1, np.int64), "tab_Km1")])
for n, k in ids_users:
assert n.op_type == "Gather" and k == 0
out, ids, p = n.output[0], n.input[1], n.name + "_q"
g.node.remove(n); ns = []
if K:
ns += [h.make_node("Gather", ["tab_remap", ids], [p + "_r"], name=p + "_remap"),
h.make_node("Less", [p + "_r", "tab_K"], [p + "_ishi"], name=p + "_less"),
h.make_node("Min", [p + "_r", "tab_Km1"], [p + "_rh"], name=p + "_min"),
h.make_node("Sub", [p + "_r", "tab_K"], [p + "_rl0"], name=p + "_sub"),
h.make_node("Max", [p + "_rl0", "tab_0"], [p + "_rl"], name=p + "_max"),
h.make_node("Gather", ["tab_hi", p + "_rh"], [p + "_h"], name=p + "_gh")]
li, lo_out = p + "_rl", p + "_l"
else:
li, lo_out = ids, out
ns += [h.make_node("Gather", ["tab_q8", li], [p + "_q8"], name=p + "_gq"), h.make_node("Cast", [p + "_q8"], [p + "_f"], to=TP.FLOAT, name=p + "_cast"),
h.make_node("Gather", ["tab_rs", li], [p + "_s"], name=p + "_gs"), h.make_node("Unsqueeze", [p + "_s", "prec2_m1"], [p + "_su"], name=p + "_un"),
h.make_node("Mul", [p + "_f", p + "_su"], [lo_out], name=p + "_mul")]
if K: ns += [h.make_node("Unsqueeze", [p + "_ishi", "prec2_m1"], [p + "_c"], name=p + "_unc"), h.make_node("Where", [p + "_c", p + "_h", p + "_l"], [out], name=p + "_where")]
after.append((ns))
stat["table"] = mode; continue
if mode == "fp16":
g.initializer.append(nh.from_array(w.astype(np.float16), name + "_16")); pre.append(h.make_node("Cast", [name + "_16"], [name], to=TP.FLOAT)); stat[grp + ":fp16"] += 1; continue
ax = axis_for(name, w) if w.ndim >= 2 and w.size >= 1024 else None
if mode != "int8" or ax is None: # small / odd tensors stay fp32
g.initializer.append(nh.from_array(w, name)); stat[grp + ":kept32"] += 1; continue
if ax == -1: # LSTM [dirs, 4H, in]: one scale per (dir, row)
q, sc = q8(w.reshape(-1, w.shape[-1]), 0)
g.initializer.extend([nh.from_array(q, name + "_q"), nh.from_array(sc, name + "_s"), nh.from_array(np.zeros(len(sc), np.int8), name + "_z"),
nh.from_array(np.array(w.shape, np.int64), name + "_shape")])
pre += [h.make_node("DequantizeLinear", [name + "_q", name + "_s", name + "_z"], [name + "_dq"], axis=0), h.make_node("Reshape", [name + "_dq", name + "_shape"], [name])]
else:
q, sc = q8(w, ax)
g.initializer.extend([nh.from_array(q, name + "_q"), nh.from_array(sc, name + "_s"), nh.from_array(np.zeros(len(sc), np.int8), name + "_z")])
pre.append(h.make_node("DequantizeLinear", [name + "_q", name + "_s", name + "_z"], [name], axis=ax))
stat[grp + ":int8"] += 1
g.initializer.append(nh.from_array(np.array([-1], np.int64), "prec2_m1"))
nodes = list(g.node)
for ns in after: # table lookups go right before their first consumer
first = min(i for i, n in enumerate(nodes) if any(o in n.input for o in [ns[-1].output[0]]))
nodes[first:first] = ns
g.ClearField("node"); g.node.extend(pre + nodes)
onnx.save(m, dst); stat["mb"] = round(os.path.getsize(dst) / 1e6, 2); print(dst, dict(stat), flush=True)