nanoglimmer / training /src /quantize.py
apullin's picture
nanoGlimmer: checkpoint, tokenizer, model card and training code
6b665d1 verified
Raw History Blame Contribute Delete
17 kB
"""Post-training 4-bit quantization check for the deploy models.
The last sim-side unknown: everything trained so far is fp32, but the chip stores
weights in 4-bit. Does PLE's +9.3% edge survive naive group-wise PTQ, or does it
need QAT? We quantize -> dequantize every large weight (group-wise symmetric int4,
the GGUF-Q4 style you'd actually flash) and re-measure val loss.
Crucially this quantizes the 25M-param TABLE too -- the thing we're betting the
flash budget on. If the table is the fragile part under 4-bit, we need to know.
Norms stay fp32 (tiny, and quantizing them is never worth it).
"""
import argparse
import glob
import json
import math
import os
import numpy as np
import torch
import torch.nn as nn
from model import Config, TinyLM
HERE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(HERE, "..", "data")
RUNS = os.path.join(HERE, "..", "runs")
# This is a deployment-format oracle as well as a training primitive. Inductor
# may fuse away the explicit fp16 scale round-trip (and one observed Triton
# fusion generated invalid code), so QAT must cross an eager graph boundary.
@torch.compiler.disable
def quantize_groupwise(w, bits=4, group=64, fp16_scales=False):
"""Symmetric group-wise quant along the last dim; returns dequantized fp32.
Simulates storage in `bits` with one fp scale per `group` consecutive weights
of each row -- the standard edge format. qmax = 2^(bits-1)-1.
"""
orig_shape = w.shape
x = w.reshape(-1, orig_shape[-1]).float()
out, cols = x.shape
pad = (group - cols % group) % group
if pad:
x = torch.cat([x, torch.zeros(out, pad, device=x.device)], dim=1)
x = x.reshape(out, -1, group) # (out, n_groups, group)
qmax = 2 ** (bits - 1) - 1 # 7 for 4-bit
scale = x.abs().amax(dim=2, keepdim=True) / qmax
if fp16_scales:
# Match the flash artifact: round stored group scales to IEEE fp16
# before quantizing and dequantizing the weights.
scale = scale.half().float()
# Match the backend packer: a zero (or fp16-underflowed) stored scale uses
# 1 only for code selection, then multiplies those codes by the real zero
# scale. This makes an all-zero group exactly zero instead of NaN.
safe = torch.where(scale > 0, scale, torch.ones_like(scale))
q = torch.clamp(torch.round(x / safe), -qmax, qmax)
dq = (q * scale).reshape(out, -1)[:, :cols]
return dq.reshape(orig_shape).to(w.dtype)
@torch.compiler.disable
def quantize_ternary_tensorwise(w, eps=1e-5):
"""BitNet-style {-1, 0, +1} fake quantization for one weight tensor.
This intentionally does *not* route through ``quantize_groupwise(bits=1)``:
that symmetric integer formula has qmax=0 at one bit and is undefined.
TorchAO's BitNet training path instead uses one FP32 abs-mean scale for the
complete Linear weight, rounds ``w / scale`` and clips the codes to
``[-1, 1]``. Keep that definition here so model experiments and a future
ESP32 packed-ternary format share one explicit oracle.
The returned tensor is dequantized, as with ``quantize_groupwise``. A
zero tensor retains scale zero and therefore returns exact zeros; ``eps``
protects only the division.
"""
latent = w.float()
scale = latent.abs().mean()
safe = scale.clamp_min(eps)
codes = torch.round(latent / safe).clamp(-1, 1)
return (codes * scale).to(w.dtype)
def is_sparse_deployment_weight(model, name, weight):
"""Whether one matrix is row-gathered rather than streamed every token.
A tied TinyLM token embedding is also the output head, so it must retain the
dense/head format. Glimmer and fatembed use untied token tables and can store
those sparse rows at a different width.
"""
return ("ple_table" in name
or "position_control" in name
or ("tok_emb" in name and id(weight) != id(model.head.weight)))
def resolve_quantization_format(metadata=None, *, bits=None, table_bits=None,
group=None, skip_names=None, core_format=None,
ternary_includes=None):
"""Merge CLI overrides with the format recorded in a checkpoint.
Selective ternary is part of the deployed format, not merely a training
option. Evaluating its latent checkpoint as ordinary i4 silently measures
a different model, so every metadata-aware evaluator routes through this
resolver. ``None`` means inherit; an explicit empty iterable clears a
recorded selector and therefore requests all-core ternary.
"""
metadata = metadata or {}
selected_core = (core_format if core_format is not None
else metadata.get("core_format", "groupwise"))
if selected_core not in ("groupwise", "ternary"):
raise ValueError(f"unknown checkpoint core format {selected_core!r}")
includes = (ternary_includes if ternary_includes is not None
else metadata.get("ternary_include", ()))
if isinstance(includes, str):
includes = [value.strip() for value in includes.split(",")
if value.strip()]
else:
includes = [str(value).strip() for value in includes
if str(value).strip()]
if includes and selected_core != "ternary":
raise ValueError("ternary selectors require core_format='ternary'")
skips = (skip_names if skip_names is not None
else metadata.get("skip", ()))
if isinstance(skips, str):
skips = [value.strip() for value in skips.split(",") if value.strip()]
else:
skips = [str(value).strip() for value in skips if str(value).strip()]
return {
"dense_bits": bits if bits is not None else metadata.get("dense_bits", 0),
"table_bits": (table_bits if table_bits is not None
else metadata.get("table_bits")),
"group": group if group is not None else metadata.get("group", 128),
"skip": skips,
"core_format": selected_core,
"ternary_include": includes,
}
def quantize_model(model, bits=4, group=64, quant_table=True, fp16_scales=False,
skip_names=(), table_bits=None, core_format="groupwise",
ternary_includes=()):
if core_format not in ("groupwise", "ternary"):
raise ValueError("core_format must be 'groupwise' or 'ternary'")
head_id = id(model.head.weight)
n_q = 0
with torch.no_grad():
for name, p in model.named_parameters():
if p.ndim < 2:
continue # norms, biases -> leave fp32
# Mamba scan internals ship fp32 like norms (~4K params), matching
# train.py's QAT skip exactly -- A_log is a 2-D raw Parameter and the
# depthwise conv weight is 3-D, so both would otherwise slip in here
# and quantize what training never fake-quantised.
if "A_log" in name or "conv1d" in name:
continue
# Mirror of train.py's --qat-skip: tensors shipping at higher
# precision must be excluded here too, or the eval prices a format
# the arm never trained for.
if any(s in name for s in skip_names):
continue
if "table" in name and not quant_table:
continue
sparse = is_sparse_deployment_weight(model, name, p)
# Canonical BitNet applies ternary quantization to Linear weights,
# while this project's tied embedding/head must remain one shared
# higher-precision tensor. Therefore only true dense CORE weights
# take the ternary path; the head and sparse tables keep the exact
# group-wise format already deployed by the backend.
ternary = (core_format == "ternary" and not sparse
and id(p) != head_id
and (not ternary_includes
or any(value in name
for value in ternary_includes)))
if ternary:
p.copy_(quantize_ternary_tensorwise(p.data))
else:
use_bits = table_bits if sparse and table_bits is not None else bits
p.copy_(quantize_groupwise(
p.data, use_bits, group, fp16_scales))
n_q += p.numel()
return n_q
def load(path, device):
ck = torch.load(path, map_location=device, weights_only=False)
m = TinyLM(Config(**ck["cfg"])).to(device)
m.load_state_dict(ck["state"])
m.eval()
return m
@torch.no_grad()
def val_loss(model, vocab, device, iters=60, bs=16, sl=256, seed=1234):
suffix = "" if vocab == 4096 else f"_v{vocab}"
data = np.memmap(os.path.join(DATA, f"val{suffix}.bin"), dtype=np.uint16, mode="r")
rng = np.random.default_rng(seed)
losses = []
for _ in range(iters):
ix = rng.integers(0, len(data) - sl - 1, bs)
x = torch.from_numpy(np.stack([data[i:i+sl] for i in ix]).astype(np.int64)).to(device)
y = torch.from_numpy(np.stack([data[i+1:i+1+sl] for i in ix]).astype(np.int64)).to(device)
losses.append(model(x, y)[1].item())
return sum(losses) / len(losses)
def get_device():
if torch.backends.mps.is_available():
return "mps"
if torch.cuda.is_available():
return "cuda"
return "cpu"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--bits", type=int, default=4)
ap.add_argument("--core-format", choices=("groupwise", "ternary"),
default="groupwise",
help="ternary applies tensor-absmean {-1,0,+1} only to "
"core weights; head/tables retain --bits")
ap.add_argument("--ternary-include", default="",
help="optional comma-separated parameter-name substrings; "
"unmatched core weights retain --bits")
ap.add_argument("--group", type=int, default=64)
ap.add_argument("--tag", default="cleandeploy")
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--fp16-scales", action="store_true",
help="round quantization scales to fp16 like the flash format")
ap.add_argument("--skip", default="",
help='name substrings left fp32, mirroring train.py --qat-skip')
ap.add_argument("--run", nargs="*", default=None,
help="checkpoint paths; bypass the historical arm/tag lookup")
ap.add_argument("--eval-iters", type=int, default=60)
ap.add_argument("--batch-size", type=int, default=16)
ap.add_argument("--dynamic-qk", action="store_true",
help="also simulate the backend's per-vector int8 Glimmer Q@K")
ap.add_argument("--table-bits", type=int, choices=(4, 8), default=None,
help="quantize sparse untied embeddings/PLE tables separately")
ap.add_argument("--no-softcap", action="store_true",
help="also ablate Glimmer's final tanh softcap")
args = ap.parse_args()
if args.ternary_include and args.core_format != "ternary":
ap.error("--ternary-include requires --core-format ternary")
device = get_device()
if args.dynamic_qk and device == "cuda":
# dynamic_i8_qk uses fp32 GEMM on integer-valued codes. With TF32 the
# accumulation is no longer the backend's exact int32 dot product.
torch.set_float32_matmul_precision("highest")
if args.run:
meta_path = os.path.join(DATA, "sweep_meta.json")
if os.path.exists(meta_path):
with open(meta_path) as f:
meta = json.load(f)
else:
meta = {}
for path in args.run:
ck = torch.load(path, map_location="cpu", weights_only=False)
cfg = Config(**ck["cfg"])
sl = cfg.seq_len
m = load(path, device)
fp = val_loss(m, cfg.vocab_size, device, args.eval_iters,
args.batch_size, sl)
m = load(path, device)
nq = quantize_model(
m, args.bits, args.group, quant_table=True,
fp16_scales=args.fp16_scales,
skip_names=[s for s in args.skip.split(",") if s.strip()],
table_bits=args.table_bits,
core_format=args.core_format,
ternary_includes=[
s for s in args.ternary_include.split(",") if s.strip()])
q = val_loss(m, cfg.vocab_size, device, args.eval_iters,
args.batch_size, sl)
q_dyn = None
if args.dynamic_qk and cfg.architecture == "glimmer":
m.cfg.dynamic_qk = True
q_dyn = val_loss(m, cfg.vocab_size, device, args.eval_iters,
args.batch_size, sl)
q_nocap = q_both = None
if args.no_softcap and cfg.architecture == "glimmer":
m.cfg.dynamic_qk = False
m.cfg.final_logit_softcapping = 0.0
q_nocap = val_loss(m, cfg.vocab_size, device, args.eval_iters,
args.batch_size, sl)
if args.dynamic_qk:
m.cfg.dynamic_qk = True
q_both = val_loss(m, cfg.vocab_size, device,
args.eval_iters, args.batch_size, sl)
bits_token = q / math.log(2)
bytes_token = meta.get(str(cfg.vocab_size), {}).get("val_bpt")
bits_byte = bits_token / bytes_token if bytes_token else float("nan")
dyn = ""
if q_dyn is not None:
dyn_bpt = q_dyn / math.log(2)
dyn_bpb = dyn_bpt / bytes_token if bytes_token else float("nan")
dyn = (f" q+dynqk={q_dyn:.4f} qk_deg={q_dyn-q:+.4f}"
f" dyn_bits/token={dyn_bpt:.4f}"
f" dyn_bits/byte={dyn_bpb:.4f}")
nocap = ""
if q_nocap is not None:
nc_bpb = ((q_nocap / math.log(2)) / bytes_token
if bytes_token else float("nan"))
nocap = (f" q+nosoft={q_nocap:.4f} soft_deg={q_nocap-q:+.4f}"
f" nosoft_bits/byte={nc_bpb:.4f}")
both = ""
if q_both is not None:
both_bpb = ((q_both / math.log(2)) / bytes_token
if bytes_token else float("nan"))
both = (f" q+dyn+nosoft={q_both:.4f}"
f" both_deg={q_both-q:+.4f}"
f" both_bits/byte={both_bpb:.4f}")
ternary_label = ""
if args.core_format == "ternary":
ternary_label = (f"ternary[{args.ternary_include}]-core/"
if args.ternary_include
else "ternary-core/")
form = (ternary_label
+ (f"i{args.bits}"
if args.table_bits is None
else f"i{args.bits}/table-i{args.table_bits}"))
print(f"{os.path.basename(path):32s} fp={fp:.4f} q={q:.4f}{dyn} "
f"{nocap}{both} format={form} deg={q-fp:+.4f} "
f"bits/token={bits_token:.4f} "
f"bits/byte={bits_byte:.4f} quantized={nq/1e6:.2f}M")
return
rows = {}
for arm in ["baseline", "ple", "fatembed"]:
path = os.path.join(RUNS, f"{arm}-{args.tag}-s{args.seed}.pt")
if not os.path.exists(path):
continue
cfg_vocab = torch.load(path, map_location="cpu", weights_only=False)["cfg"]["vocab_size"]
m = load(path, device)
fp = val_loss(m, cfg_vocab, device)
m = load(path, device) # fresh copy
nq = quantize_model(m, args.bits, args.group, quant_table=True,
fp16_scales=args.fp16_scales,
skip_names=[s for s in args.skip.split(",") if s.strip()],
core_format=args.core_format,
ternary_includes=[
s for s in args.ternary_include.split(",")
if s.strip()])
q = val_loss(m, cfg_vocab, device)
rows[arm] = (fp, q, nq)
print(f"{arm:9s} fp32 val {fp:.4f} (ppl {math.exp(fp):.2f}) | "
f"{args.bits}-bit val {q:.4f} (ppl {math.exp(q):.2f}) | "
f"deg {q-fp:+.4f} | quantized {nq/1e6:.1f}M params")
if "baseline" in rows and "ple" in rows:
print(f"\n--- does PLE's edge survive {args.bits}-bit? ---")
fp_gap = rows["baseline"][0] - rows["ple"][0]
q_gap = rows["baseline"][1] - rows["ple"][1]
print(f" PLE vs baseline, fp32 : {fp_gap:+.4f} nats")
print(f" PLE vs baseline, {args.bits}-bit : {q_gap:+.4f} nats")
print(f" edge retained : {100*q_gap/fp_gap:.0f}%")
if __name__ == "__main__":
main()