pocket-storyteller / code /quant_eval.py
Redhanuman's picture
Pocket Storyteller: 4.6 MB story model, browser demo, weights and training code
ebf8f81 verified
Raw History Blame Contribute Delete
2.74 kB
"""Measure how much story quality is lost when the weights are squeezed to fewer bits.
python quant_eval.py ckpt.pt # prints validation loss for several bit widths
"""
import sys, numpy as np, torch
from model import Config, Storyteller
torch.set_num_threads(int(sys.argv[2]) if len(sys.argv) > 2 else 1)
ck = torch.load(sys.argv[1], map_location="cpu")
cfg = Config(**ck["config"])
val = np.memmap("data/val.bin", dtype=np.uint16, mode="r")
rng = np.random.default_rng(1234)
NB, BS = 24, 32
starts = rng.integers(0, len(val) - cfg.ctx - 1, (NB, BS))
def quant(w, bits, clip_search=False):
"""Symmetric per-row quantization to `bits` bits. Returns the de-quantized tensor."""
q = 2 ** (bits - 1) - 1
mx = w.abs().amax(1, keepdim=True) + 1e-12
if not clip_search:
s = mx / q
return (w / s).round().clamp(-q, q) * s
best, best_err = None, None
for r in (1.0, 0.9, 0.8, 0.7, 0.6, 0.5):
s = mx * r / q
d = (w / s).round().clamp(-q, q) * s
err = (d - w).pow(2).sum(1, keepdim=True)
if best is None:
best, best_err = d, err
else:
m = err < best_err
best = torch.where(m, d, best); best_err = torch.where(m, err, best_err)
return best
def evaluate(sd):
m = Storyteller(cfg); m.load_state_dict(sd); m.eval()
tot = 0.0
with torch.no_grad():
for b in range(NB):
x = torch.from_numpy(np.stack([val[i:i + cfg.ctx].astype(np.int64) for i in starts[b]]))
y = torch.from_numpy(np.stack([val[i + 1:i + 1 + cfg.ctx].astype(np.int64) for i in starts[b]]))
tot += m(x, y).item()
return tot / NB
def variant(emb_bits, body_bits, clip=False):
sd, nbytes = {}, 0
for k, w in ck["model"].items():
if w.dim() == 2:
bits = emb_bits if k == "emb.weight" else body_bits
sd[k] = quant(w.float(), bits, clip) if bits < 32 else w
nbytes += w.numel() * bits / 8 + w.shape[0] * 4
else:
sd[k] = w; nbytes += w.numel() * 4
return sd, nbytes
base = None
for name, e, b, clip in [("float32", 32, 32, False), ("8-bit", 8, 8, False), ("7-bit", 7, 7, False),
("emb8 body6", 8, 6, False), ("emb8 body6 clip", 8, 6, True),
("6-bit", 6, 6, False), ("6-bit clip", 6, 6, True),
("emb8 body5 clip", 8, 5, True), ("5-bit clip", 5, 5, True),
("emb8 body4 clip", 8, 4, True), ("4-bit clip", 4, 4, True)]:
sd, nbytes = variant(e, b, clip)
loss = evaluate(sd)
base = loss if base is None else base
print(f"{name:18s} {nbytes/1e6:6.2f} MB val loss {loss:.4f} ({loss-base:+.4f})", flush=True)