File size: 2,736 Bytes
ebf8f81 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | """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)
|