nanoglimmer / training /src /train.py
apullin's picture
nanoGlimmer: checkpoint, tokenizer, model card and training code
6b665d1 verified
Raw History Blame Contribute Delete
26.5 kB
"""Train one ablation arm and report val loss at matched core-parameter budget."""
import argparse
from bisect import bisect_right
import json
import math
import os
import time
import numpy as np
import torch
from model import Config, TinyLM, make_model
HERE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(HERE, "..", "data")
RUNS = os.path.join(HERE, "..", "runs")
def get_device():
if torch.backends.mps.is_available():
return "mps"
if torch.cuda.is_available():
return "cuda"
return "cpu"
class Batcher:
def __init__(self, split, batch_size, seq_len, device, suffix="", path=None,
seed=None):
self.data = np.memmap(path or os.path.join(DATA, f"{split}{suffix}.bin"), dtype=np.uint16, mode="r")
self.bs, self.sl, self.device = batch_size, seq_len, device
self.rng = np.random.default_rng(1234 if split == "val" else seed)
def __call__(self):
ix = self.rng.integers(0, len(self.data) - self.sl - 1, self.bs)
x = np.stack([self.data[i : i + self.sl] for i in ix]).astype(np.int64)
y = np.stack([self.data[i + 1 : i + 1 + self.sl] for i in ix]).astype(np.int64)
return torch.from_numpy(x).to(self.device), torch.from_numpy(y).to(self.device)
@torch.no_grad()
def evaluate(model, batcher, iters):
model.eval()
batcher.rng = np.random.default_rng(1234) # same val batches for every arm
losses = [model(*batcher())[1].item() for _ in range(iters)]
model.train()
return sum(losses) / len(losses)
def lr_at(step, total, peak, warmup):
if step < warmup:
return peak * (step + 1) / warmup
p = (step - warmup) / max(1, total - warmup)
return 0.1 * peak + 0.9 * peak * 0.5 * (1 + math.cos(math.pi * p))
def build_sequence_curriculum(raw_stages, train_seq_len, model_seq_len,
base_batch_size, steps):
"""Validate an LM length curriculum with constant tokens per update.
``base_batch_size`` applies to the first (shortest) stage. Later batch
sizes shrink inversely with sequence length. This makes architecture and
curriculum comparisons see the same token and optimizer-update budgets;
elapsed time and FLOPs remain deliberately reported rather than conflated
with the data budget.
"""
if raw_stages and train_seq_len is not None:
raise ValueError("train-seq-len and train-seq-stage are mutually exclusive")
if raw_stages:
curriculum = []
for value in raw_stages:
try:
start_text, length_text = value.split(":", 1)
start, length = int(start_text), int(length_text)
except ValueError as exc:
raise ValueError(
f"invalid train sequence stage {value!r}; expected START:LENGTH"
) from exc
curriculum.append({"start": start, "seq_len": length})
else:
curriculum = [{
"start": 0,
"seq_len": train_seq_len or model_seq_len,
}]
starts = [stage["start"] for stage in curriculum]
lengths = [stage["seq_len"] for stage in curriculum]
if not starts or starts[0] != 0 or starts != sorted(set(starts)):
raise ValueError("train sequence stages must be unique, increasing, and begin at 0")
if starts[-1] >= steps:
raise ValueError("last train sequence stage starts after training ends")
if lengths != sorted(lengths):
raise ValueError("train sequence lengths must be nondecreasing")
if any(length < 1 or length > model_seq_len for length in lengths):
raise ValueError("train sequence length must be within model seq-len")
tokens_per_step = base_batch_size * lengths[0]
for stage in curriculum:
length = stage["seq_len"]
if tokens_per_step % length:
raise ValueError(
f"{tokens_per_step} tokens/update is not divisible by sequence length {length}"
)
stage["batch_size"] = tokens_per_step // length
if stage["batch_size"] < 1:
raise ValueError("sequence stage requires a zero-sized batch")
return curriculum, tokens_per_step
def apply_weight_qat(model, dense_bits=4, table_bits=None, group=128,
fp16_scales=True, skip_names=(),
core_format="groupwise", ternary_includes=(),
quantize_convolution=False):
"""Parametrize matrices with the exact format they will use at deployment.
By default dense core/head weights use ``dense_bits``. With
``core_format="ternary"``, only true core Linears use the tensor-absmean
ternary oracle; the output head remains at ``dense_bits``. Untied token
embeddings and PLE tables optionally use ``table_bits``. Returns unique
parameter counts by access class plus the legacy dense/table totals.
"""
import torch.nn.utils.parametrize as parametrize
from quantize import (is_sparse_deployment_weight, quantize_groupwise,
quantize_ternary_tensorwise)
if core_format not in ("groupwise", "ternary"):
raise ValueError("core_format must be 'groupwise' or 'ternary'")
class STEQuant(torch.nn.Module):
def __init__(self, bits):
super().__init__()
self.bits = bits
def forward(self, w):
q = quantize_groupwise(w, self.bits, group,
fp16_scales=fp16_scales)
return w + (q - w).detach()
class TernarySTEQuant(torch.nn.Module):
def forward(self, w):
q = quantize_ternary_tensorwise(w)
# ``w + (q - w).detach()`` has the right gradient but can miss q
# by one fp32 ULP because the subtraction/addition do not cancel
# in the same precision order. Keep the zero-valued STE term
# parenthesized: forward is bit-exact q, backward is identity.
return q.detach() + (w - w.detach())
# Classify before registering anything: parametrizing one side of a tied
# embedding/head changes the module attribute wrappers, but not its deploy
# role. The initial identities are the authority.
candidates = []
head_id = id(model.head.weight)
for name, mod in model.named_modules():
# Historical Mamba depthwise scan kernels deliberately ship fp32 and
# therefore retain the old default. LFM2's short convolution is an
# ordinary backend-quantized deployment weight and opts in explicitly.
if isinstance(mod, torch.nn.Conv1d) and not quantize_convolution:
continue
if any(s in name for s in skip_names):
continue
w = getattr(mod, "weight", None)
if isinstance(w, torch.nn.Parameter) and w.ndim >= 2:
sparse = is_sparse_deployment_weight(model, name, w)
role = "table" if sparse else ("head" if id(w) == head_id else "core")
candidates.append((name, mod, w, role))
counts = {"dense": 0, "core": 0, "head": 0, "table": 0,
"ternary_core": 0, "groupwise_core": 0}
seen = set()
for name, mod, w, role in candidates:
if parametrize.is_parametrized(mod, "weight"):
continue
ternary = (core_format == "ternary" and role == "core"
and (not ternary_includes
or any(value in name for value in ternary_includes)))
if ternary:
quantizer = TernarySTEQuant()
else:
bits = (table_bits if role == "table" and table_bits is not None
else dense_bits)
quantizer = STEQuant(bits)
parametrize.register_parametrization(mod, "weight", quantizer)
if id(w) not in seen:
counts[role] += w.numel()
if role != "table":
counts["dense"] += w.numel()
if role == "core":
counts["ternary_core" if ternary
else "groupwise_core"] += w.numel()
seen.add(id(w))
return counts
def latent_state_dict(model):
"""Plain-key fp32 latent state, loadable into an unparametrized TinyLM."""
return {k.replace(".parametrizations.weight.original", ".weight"):
v.detach().cpu()
for k, v in model.state_dict().items()}
def configure_compiler():
"""Keep compiled QAT complete and bit-exact across parameter shapes."""
import torch._dynamo.config as dynamo_config
import torch._inductor.config as inductor_config
# Parametrization creates one module wrapper per weight. With Dynamo's
# defaults, the shared STE forward specializes on each static weight shape
# and hits the eight-entry cache after only a fraction of this model,
# silently leaving most QAT linears eager.
dynamo_config.force_parameter_static_shapes = False
dynamo_config.recompile_limit = 64
# Required for compiled fake quantization to reproduce fp16-rounded scales.
inductor_config.emulate_precision_casts = True
def verify_compiled_quantization(device, bits_values, group):
"""Refuse training if dynamic/ragged compiled QAT changes shipped codes."""
from quantize import quantize_groupwise
shapes = ((64, 256), (17, 66), (31, 96), (7, 512))
for bits in bits_values:
compiled = torch.compile(quantize_groupwise)
for shape in shapes:
probe = torch.randn(*shape, device=device)
reference = quantize_groupwise(
probe, bits, group, fp16_scales=True)
actual = compiled(probe, bits, group, fp16_scales=True)
if not torch.equal(reference, actual):
raise RuntimeError(
f"compiled i{bits} fake-quant differs from shipped codes "
f"at shape {shape}; refusing to train")
def verify_compiled_ternary(device):
"""Refuse training if a compiled caller changes canonical ternary values.
``quantize_ternary_tensorwise`` is an eager deployment oracle protected by
``torch.compiler.disable``. Compiling that disabled function *as the root
frame* bypasses the boundary in Torch 2.13 and lets Inductor reassociate the
tensor-wide mean (one FP32 ULP was observed on CUDA). The QAT model instead
calls it from a compiled forward, where the boundary is honored. Exercise
that real topology so this guard checks the path training actually uses.
"""
from quantize import quantize_ternary_tensorwise
def compiled_caller(w):
return quantize_ternary_tensorwise(w)
compiled = torch.compile(compiled_caller)
for shape in ((64, 256), (17, 66), (31, 96), (7, 512)):
probe = torch.randn(*shape, device=device)
reference = quantize_ternary_tensorwise(probe)
actual = compiled(probe)
if not torch.equal(reference, actual):
raise RuntimeError(
"compiled ternary fake-quant differs from the tensor-absmean "
f"oracle at shape {shape}; refusing to train")
def parameter_uses_weight_decay(name, parameter):
"""Dense transforms decay; norms and sparse lookup tables do not."""
sparse_names = ("table", "tok_emb", "position_control")
return parameter.ndim >= 2 and not any(value in name
for value in sparse_names)
def main():
ap = argparse.ArgumentParser()
ap.add_argument(
"--arm",
required=True,
choices=["baseline", "ple", "ple_notable", "fatembed", "bigcore"],
)
ap.add_argument("--architecture", default="tinylm",
choices=["tinylm", "glimmer"])
ap.add_argument("--target-core", type=int, default=1_500_000)
ap.add_argument("--init-from", default=None,
help="checkpoint to continue from (mid-training); its shape "
"replaces the arm flags, --seq-len may change")
ap.add_argument("--steps", type=int, default=4000)
ap.add_argument("--batch-size", type=int, default=32)
ap.add_argument("--seq-len", type=int, default=512)
ap.add_argument("--train-seq-len", type=int, default=None,
help="sample this many LM tokens while constructing a "
"model with --seq-len maximum context")
ap.add_argument(
"--train-seq-stage", action="append", default=[], metavar="START:LENGTH",
help="repeat for sequence-length warmup; batch size scales inversely "
"to keep tokens per optimizer step fixed",
)
ap.add_argument("--lr", type=float, default=1e-3)
ap.add_argument("--warmup", type=int, default=200)
ap.add_argument("--eval-every", type=int, default=250)
ap.add_argument("--eval-iters", type=int, default=40)
ap.add_argument("--ple-dim", type=int, default=64)
ap.add_argument("--d-model", type=int, default=128)
ap.add_argument("--n-layers", type=int, default=6)
ap.add_argument("--n-heads", type=int, default=4)
ap.add_argument("--loops", type=int, default=1,
help="apply the block stack this many times per token "
"with shared weights (depth without parameters)")
ap.add_argument("--feedback", choices=("none", "shift"), default="none",
help="what extra passes are fed: the token stream again, "
"or the previous position's last-pass output through "
"a gated merge (one-step truncated RLT recurrence)")
ap.add_argument("--n-kv-heads", type=int, default=1,
help="Glimmer KV heads (query heads come from --n-heads)")
ap.add_argument("--glimmer-window", type=int, default=64)
ap.add_argument("--qk-scale-factor", type=float, default=3.87)
ap.add_argument("--output-multiplier", type=float,
default=0.19611613513818404)
ap.add_argument("--logit-softcap", type=float, default=20.0)
ap.add_argument("--fixed-ffn", type=int, default=None,
help="pin ffn_hidden and skip the core solver (table-scaling sweep)")
ap.add_argument("--vocab", type=int, default=4096)
ap.add_argument("--mamba-layers", default="",
help='comma-sep layer indices whose mixer is Mamba, e.g. "0,5"')
ap.add_argument("--attn-window", type=int, default=0,
help="sliding-window width for attention layers (0 = full)")
ap.add_argument("--abc-layers", default="",
help="comma-separated causal Linformer/ABC mixer layers")
ap.add_argument("--abc-rank", type=int, default=16)
ap.add_argument("--abc-control", choices=("mlp", "linformer"),
default="mlp")
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--tag", default="")
# Train-split override for dataset-scaling runs (e.g. the full-TinyStories
# extension). Val ALWAYS stays the vocab-derived bin: every model in the
# ablation series is scored on the same frozen batches or the series breaks.
ap.add_argument("--train-bin", default=None)
# QAT (IDEAS #25): straight-through-estimator fake-quant in the forward pass,
# wrapping the EXISTING quantize_groupwise -- so training sees the exact shipped
# format (group 128, optionally fp16-rounded scales, ragged rows) rather than an
# approximation of it. Norms and biases (ndim < 2) stay fp32, as at export.
ap.add_argument("--qat", action="store_true")
ap.add_argument("--qat-bits", type=int, default=4)
ap.add_argument("--qat-core-format", choices=("groupwise", "ternary"),
default="groupwise",
help="ternary uses BitNet tensor-absmean only on core "
"Linears; tied head and sparse tables stay groupwise")
ap.add_argument("--qat-ternary-include", default="",
help="optional comma-separated module-name substrings; "
"with ternary core format, unmatched core Linears "
"remain groupwise --qat-bits")
ap.add_argument("--qat-table-bits", type=int, choices=(4, 8), default=None,
help="separate width for sparse untied embeddings/PLE tables")
ap.add_argument("--qat-group", type=int, default=128)
ap.add_argument("--qat-fp16-scales", action="store_true", default=True)
# Comma-separated name substrings excluded from fake-quant (they ship at
# higher precision via the backend's per-op format ladder). Motivation:
# Mamba's dt_proj/x_proj generate the decay -- weight error there is
# EXPONENTIATED and compounds across the scan, and they are ~8.5K params,
# so precision is nearly free exactly where sensitivity is highest.
ap.add_argument("--qat-skip", default="",
help='e.g. "dt_proj,x_proj" to keep those linears fp32')
# The step is dispatch-bound, not compute-bound (~100x off the 4080's
# roofline: the chunked scan + STE fake-quant launch dozens of micro-
# kernels). torch.compile fuses them; "reduce-overhead" adds CUDA graphs,
# which kills the launch cost itself. In-place Module.compile() keeps
# state-dict keys plain so the latent-save path below is untouched.
ap.add_argument("--compile", default="",
choices=["", "default", "reduce-overhead", "max-autotune"])
args = ap.parse_args()
if args.qat_ternary_include and args.qat_core_format != "ternary":
ap.error("--qat-ternary-include requires --qat-core-format ternary")
torch.manual_seed(args.seed)
device = get_device()
os.makedirs(RUNS, exist_ok=True)
# vocab 4096 uses the original train.bin/val.bin; other vocabs use suffixed bins.
suffix = "" if args.vocab == 4096 else f"_v{args.vocab}"
sequence_curriculum, tokens_per_step = build_sequence_curriculum(
args.train_seq_stage, args.train_seq_len, args.seq_len,
args.batch_size, args.steps)
base = Config(seq_len=args.seq_len, ple_dim=args.ple_dim, vocab_size=args.vocab,
d_model=args.d_model, n_layers=args.n_layers, n_heads=args.n_heads,
mamba_layers=args.mamba_layers, attn_window=args.attn_window,
abc_layers=args.abc_layers, abc_rank=args.abc_rank,
abc_control=args.abc_control,
architecture=args.architecture, n_kv_heads=args.n_kv_heads,
glimmer_window=args.glimmer_window,
qk_scale_factor=args.qk_scale_factor,
output_multiplier=args.output_multiplier,
final_logit_softcapping=args.logit_softcap,
loops=args.loops, feedback=args.feedback)
if args.init_from:
# Mid-training: continue a finished run on new text, usually at a
# longer context. The shape comes from the checkpoint, not the arm
# flags; only seq_len (RoPE tables are recomputed, not stored) and
# the data change. The checkpoint's state is the fp32 latent, so QAT
# re-wraps it below exactly as it would a fresh model.
source = torch.load(args.init_from, map_location="cpu", weights_only=False)
config = dict(source["cfg"])
config["seq_len"] = args.seq_len
cfg = Config(**config)
model = TinyLM(cfg).to(device)
model.load_state_dict(source["state"])
base = cfg
print(f"init from {args.init_from}: arm={cfg.arm} layers={cfg.n_layers} "
f"d_model={cfg.d_model} seq_len {source['cfg'].get('seq_len')}->{cfg.seq_len}")
else:
model = make_model(args.arm, args.target_core, base, fixed_ffn=args.fixed_ffn).to(device)
qat_meta = None
if args.qat:
# Parametrisation, not a hook: `weight` becomes fq(latent) everywhere it is
# read, including tied uses, and the optimiser steps the fp32 latent. The
# STE is w + (q(w) - w).detach(): forward sees the quantised value, backward
# sees identity.
skip_names = [s for s in args.qat_skip.split(",") if s.strip()]
ternary_includes = [
s for s in args.qat_ternary_include.split(",") if s.strip()]
counts = apply_weight_qat(
model, args.qat_bits, args.qat_table_bits, args.qat_group,
args.qat_fp16_scales, skip_names, args.qat_core_format,
ternary_includes)
table_bits = (args.qat_table_bits if args.qat_table_bits is not None
else args.qat_bits)
qat_meta = {"dense_bits": args.qat_bits, "table_bits": table_bits,
"group": args.qat_group,
"fp16_scales": args.qat_fp16_scales,
"core_format": args.qat_core_format,
"ternary_include": ternary_includes,
"skip": skip_names}
core_label = ("ternary" if args.qat_core_format == "ternary"
else f"i{args.qat_bits}")
print(f"QAT: fake-quant core={counts['core'] / 1e6:.1f}M "
f"at {core_label}, head={counts['head'] / 1e6:.1f}M "
f"at i{args.qat_bits}, sparse-table={counts['table'] / 1e6:.1f}M "
f"at i{table_bits}, group {args.qat_group}, "
f"fp16_scales={args.qat_fp16_scales}, "
f"ternary_core={counts['ternary_core'] / 1e6:.3f}M, "
f"groupwise_core={counts['groupwise_core'] / 1e6:.3f}M")
if args.compile:
# Round fp16 cast intermediates instead of carrying them in fp32
# registers -- required for compiled fake-quant to match the shipped
# codes bit-for-bit (see STEQuant above).
configure_compiler()
if args.qat:
verify_compiled_quantization(
device, {args.qat_bits,
args.qat_table_bits or args.qat_bits},
args.qat_group)
if args.qat_core_format == "ternary":
verify_compiled_ternary(device)
model.compile(mode=args.compile)
budget = model.param_budget()
cfg = model.cfg
# No weight decay on 1-D params (norms) or on lookup tables.
decay, no_decay = [], []
for n, p in model.named_parameters():
(decay if parameter_uses_weight_decay(n, p) else no_decay).append(p)
opt = torch.optim.AdamW(
[{"params": decay, "weight_decay": 0.1}, {"params": no_decay, "weight_decay": 0.0}],
lr=args.lr,
betas=(0.9, 0.95),
)
# Validation is frozen at the final curriculum length and a matching token
# batch. Early-stage losses can therefore be compared directly with the
# final model rather than silently changing their prediction horizon.
final_stage = sequence_curriculum[-1]
val_b = Batcher("val", final_stage["batch_size"],
final_stage["seq_len"], device, suffix)
family = args.arm if args.architecture == "tinylm" else f"glimmer-{args.arm}"
name = f"{family}{'-' + args.tag if args.tag else ''}-s{args.seed}"
history, best = [], float("inf")
t0 = time.time()
stage_starts = [stage["start"] for stage in sequence_curriculum]
active_stage_index = None
train_b = None
for step in range(args.steps):
lr = lr_at(step, args.steps, args.lr, args.warmup)
for g in opt.param_groups:
g["lr"] = lr
stage_index = bisect_right(stage_starts, step) - 1
stage = sequence_curriculum[stage_index]
if stage_index != active_stage_index:
train_b = Batcher(
"train", stage["batch_size"], stage["seq_len"], device,
suffix, path=args.train_bin, seed=args.seed + stage["start"])
active_stage_index = stage_index
print(f"activated LM context={stage['seq_len']} "
f"batch={stage['batch_size']} at step={step}", flush=True)
x, y = train_b()
_, loss = model(x, y)
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
if step % args.eval_every == 0 or step == args.steps - 1:
# Under CUDA graphs (--compile reduce-overhead) the loss tensor's
# buffer is recycled by the next model call, so read the scalar
# BEFORE evaluate() re-invokes the model.
tr = loss.item()
vl = evaluate(model, val_b, args.eval_iters)
best = min(best, vl)
tok = (step + 1) * tokens_per_step
history.append({"step": step, "tokens": tok, "train": tr, "val": vl,
"train_seq_len": stage["seq_len"],
"train_batch_size": stage["batch_size"]})
print(
f"{name} step {step:5d} | ctx {stage['seq_len']:4d} "
f"| tok {tok / 1e6:6.1f}M | train {tr:.4f} "
f"| val {vl:.4f} | ppl {math.exp(vl):7.2f} | {time.time() - t0:5.0f}s",
flush=True,
)
result = {
"arm": args.arm,
"architecture": args.architecture,
"seed": args.seed,
"tag": args.tag,
"config": {k: v for k, v in cfg.__dict__.items()},
"params": budget,
"final_val": history[-1]["val"],
"best_val": best,
"final_ppl": math.exp(history[-1]["val"]),
"tokens_seen": args.steps * tokens_per_step,
"tokens_per_step": tokens_per_step,
"train_seq_len": final_stage["seq_len"],
"train_sequence_curriculum": sequence_curriculum,
"steps": args.steps,
"train_bin": args.train_bin,
"wall_seconds": time.time() - t0,
"quantization": qat_meta,
"history": history,
}
with open(os.path.join(RUNS, f"{name}.json"), "w") as f:
json.dump(result, f, indent=2)
# QAT parametrisation renames weights to parametrizations.weight.original in the
# state dict; save the fp32 LATENT under plain names so quantize.py/export.py
# load into a vanilla TinyLM -- their PTQ of the latent reproduces exactly the
# codes training saw, which is the whole point of QAT'ing in the shipped format.
_state = latent_state_dict(model)
torch.save({"cfg": cfg.__dict__, "state": _state,
"quantization": qat_meta},
os.path.join(RUNS, f"{name}.pt"))
print(f"{name} DONE core={budget['core']:,} table={budget['table']:,} "
f"val={result['final_val']:.4f} ppl={result['final_ppl']:.2f}")
if __name__ == "__main__":
main()