pingo-ptbr / pingo /qpack.py
itxtoledo's picture
Add pingo-ptbr: 0.87 MB pt-BR TTS (MLX + ONNX + web demo)
27d8618 verified
Raw History Blame Contribute Delete
5.19 kB
"""`pingo-ptbr` packed weight format: per-layer quantized weights (5-8 bits, fp16 scales) in a single file.
python pingo/qpack.py pack mlx_dir weights/pingo-ptbr.bin # float32 (safetensors + config.json) -> .bin
python pingo/qpack.py verify mlx_dir weights/pingo-ptbr.bin # checks size and reconstruction error
Layout: b"PNGQ1" | uint32 header size | JSON header (config, voices, symbols, tensor table) | data.
Each 2-D+ tensor stores `bits` (5..8), `axis` (output channel), one fp16 scale per channel, and the signed values plus qmax packed `bits`
bits each (MSB first). 1-D tensors stay float32. API: `load_packed(path) -> (acoustic, vocoder, meta)` with dictionaries of dequantized
float32 arrays, ready for `model.update` / `Vocoder(w)`.
"""
import json, struct, sys
from pathlib import Path
import numpy as np
MAGIC = b"PNGQ1"
# scheme (see docs/EXPERIMENTS.md): acoustic encoder 5, decoder 6, durations 6, embeddings 8; vocoder 8 except the listed layers
VOC_BITS = {"pitch_gain.w": 6, "gru3.input": 5, "gru2.hidden": 5, "gru1.hidden": 6, "glu3": 5, "glu2": 6, "gru1.input": 6,
"cond.dense2": 6, "frame_glu": 5, "skip_glu": 6, "gru3.hidden": 5, "glu1": 6}
def ac_bits(k):
if k.startswith(("tokens", "voices", "stress")): return 8
if k.startswith("durations"): return 6
if k.startswith("decoder"): return 6
return 5
def voc_axis(k): # x @ W with W (in, out): channel = last axis; convolutions, embeddings and vectors (.w) on axis 0
return 0 if ("conv" in k or "embedding" in k or k.endswith(".w")) else -1
def pack_bits(u, bits):
u = u.astype(np.uint8).ravel()
b = ((u[:, None] >> np.arange(bits - 1, -1, -1)) & 1).astype(np.uint8)
return np.packbits(b.ravel()).tobytes()
def unpack_bits(buf, bits, n):
b = np.unpackbits(np.frombuffer(buf, np.uint8))[: n * bits].reshape(n, bits)
return (b << np.arange(bits - 1, -1, -1)).sum(1).astype(np.int64)
def quantize(a, bits, axis):
qmax = 2 ** (bits - 1) - 1
m = np.moveaxis(a, axis, 0); flat = m.reshape(m.shape[0], -1)
sc = (np.maximum(np.abs(flat).max(1), 1e-4) / qmax).astype(np.float16)
q = np.clip(np.rint(flat / sc.astype(np.float32)[:, None]), -qmax, qmax).astype(np.int64) + qmax
return q, sc
def dequantize(q, sc, bits, axis, shape):
qmax = 2 ** (bits - 1) - 1
flat = (q.reshape(len(sc), -1) - qmax) * sc.astype(np.float32)[:, None]
m_shape = np.moveaxis(np.empty(shape, np.float32), axis, 0).shape
return np.moveaxis(flat.reshape(m_shape), 0, axis).astype(np.float32)
def pack(mlx_dir, out):
from safetensors.numpy import load_file
d = Path(mlx_dir); meta = json.loads((d / "config.json").read_text())
header = {"meta": meta, "tensors": []}; blob = bytearray()
for part, bits_of, axis_of in (("acoustic", ac_bits, lambda k: 0), ("vocoder", lambda k: VOC_BITS.get(k, 8), voc_axis)):
for name, a in load_file(str(d / f"{part}.safetensors")).items():
a = np.asarray(a, np.float32); t = {"part": part, "name": name, "shape": list(a.shape), "offset": len(blob)}
if a.ndim < 2:
t.update(kind="f32"); blob += a.tobytes()
else:
bits, axis = bits_of(name), axis_of(name); q, sc = quantize(a, bits, axis)
t.update(kind="q", bits=bits, axis=axis, channels=len(sc)); blob += sc.tobytes()
payload = pack_bits(q, bits); t["payload"] = len(payload); blob += payload
t["size"] = len(blob) - t["offset"]; header["tensors"].append(t)
h = json.dumps(header, ensure_ascii=False, separators=(",", ":")).encode()
Path(out).write_bytes(MAGIC + struct.pack("<I", len(h)) + h + bytes(blob))
return len(h), len(blob)
def load_packed(path):
raw = Path(path).read_bytes(); assert raw[:5] == MAGIC, "not a pingo-ptbr file"
(n,) = struct.unpack("<I", raw[5:9]); header = json.loads(raw[9:9 + n]); base = 9 + n; out = {"acoustic": {}, "vocoder": {}}
for t in header["tensors"]:
shape = tuple(t["shape"]); o = base + t["offset"]
if t["kind"] == "f32":
a = np.frombuffer(raw, np.float32, int(np.prod(shape)), o).reshape(shape).copy()
else:
c = t["channels"]; sc = np.frombuffer(raw, np.float16, c, o); data = raw[o + 2 * c: o + 2 * c + t["payload"]]
a = dequantize(unpack_bits(data, t["bits"], int(np.prod(shape))), sc, t["bits"], t["axis"], shape)
out[t["part"]][t["name"]] = a
return out["acoustic"], out["vocoder"], header["meta"]
if __name__ == "__main__":
cmd, src, dst = sys.argv[1:4]
if cmd == "pack":
h, b = pack(src, dst); print(f"{dst}: header {h/1e3:.1f} KB + data {b/1e6:.3f} MB = {Path(dst).stat().st_size/1e6:.3f} MB")
else:
from safetensors.numpy import load_file
ac, voc, meta = load_packed(dst)
for part, w in (("acoustic", ac), ("vocoder", voc)):
ref = load_file(str(Path(src) / f"{part}.safetensors"))
rel = {k: float(np.abs(w[k] - ref[k]).max() / (np.abs(ref[k]).max() + 1e-12)) for k in ref}
worst = max(rel, key=rel.get); print(f"{part}: {len(ref)} tensores, pior erro relativo {rel[worst]:.4f} em {worst}")