"""`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("