"""Train the storyteller. Works on a CPU (slow) or a GPU. python train.py --minutes 180 # start fresh, train for 3 hours python train.py --resume --minutes 180 --lr 1e-3 # keep training the saved ckpt.pt python train.py --steps 30000 --batch 64 # count steps instead of minutes (for a GPU) Add --fast on a GPU, or on a recent Intel CPU (one that lists "amx_bf16" in /proc/cpuinfo). It does the big multiplications with 16-bit numbers and compiles the model. On the CPU this was built on that is about 2.5 times the speed, and the model learns the same way. Every 1000 steps it prints a sample story and measures the loss on stories it has never seen ("val", lower is better). It saves ckpt.pt every 250 steps, so you can stop it any time with Ctrl+C. """ import argparse, math, os, shutil, sys, time, json, numpy as np, torch from model import Config, Storyteller from tokenizer import Tokenizer p = argparse.ArgumentParser() p.add_argument("--data", default="data") p.add_argument("--tok", default="data/tok4096.json") p.add_argument("--out", default="ckpt.pt") p.add_argument("--dim", type=int, default=256) p.add_argument("--layers", type=int, default=6) p.add_argument("--heads", type=int, default=8) p.add_argument("--hidden", type=int, default=640) p.add_argument("--vocab", type=int, default=4096) p.add_argument("--ctx", type=int, default=256) p.add_argument("--batch", type=int, default=32) p.add_argument("--lr", type=float, default=2e-3) p.add_argument("--steps", type=int, default=0, help="0 = use --minutes") p.add_argument("--minutes", type=float, default=60) p.add_argument("--eval_every", type=int, default=1000) p.add_argument("--save_every", type=int, default=250, help="save ckpt.pt this often, so a crash loses little") p.add_argument("--keep", type=int, default=0, help="also keep copies of the last N saves in snaps/ (for avg_snaps.py)") p.add_argument("--resume", action="store_true", help="continue from --out with a fresh learning-rate schedule") p.add_argument("--tag", default="", help="a name for this round. If the saved round with this name was cut short, " "--resume finishes it instead of starting a new one") p.add_argument("--bf16", action="store_true", help="do the big multiplications with 16-bit numbers") p.add_argument("--compile", action="store_true", help="compile the model with torch.compile") p.add_argument("--fast", action="store_true", help="same as --bf16 --compile") p.add_argument("--log", default="train_log.jsonl") a = p.parse_args() a.bf16, a.compile = a.bf16 or a.fast, a.compile or a.fast dev = "cuda" if torch.cuda.is_available() else "cpu" torch.manual_seed(0) train = np.memmap(f"{a.data}/train.bin", dtype=np.uint16, mode="r") val = np.memmap(f"{a.data}/val.bin", dtype=np.uint16, mode="r") tok = Tokenizer.load(a.tok) ck = torch.load(a.out, map_location=dev) if a.resume and os.path.exists(a.out) else None cfg = Config(**ck["config"]) if ck else Config(a.vocab, a.dim, a.layers, a.heads, a.hidden, a.ctx) model = Storyteller(cfg).to(dev) print(f"{sum(p.numel() for p in model.parameters())/1e6:.2f}M parameters on {dev}, {len(train)/1e6:.0f}M training tokens") decay = [p for n, p in model.named_parameters() if p.dim() >= 2] nodecay = [p for n, p in model.named_parameters() if p.dim() < 2] opt = torch.optim.AdamW([{"params": decay, "weight_decay": 0.1}, {"params": nodecay, "weight_decay": 0.0}], lr=a.lr, betas=(0.9, 0.95)) step, t_used, sched = 0, 0.0, None if ck: model.load_state_dict(ck["model"]); opt.load_state_dict(ck["opt"]) step, t_used = ck["step"], ck.get("seconds", 0.0) print("resumed at step", step) old = ck.get("sched") if a.tag and old and old.get("tag") == a.tag: if old.get("done"): print(f"round '{a.tag}' is already finished, nothing to do"); sys.exit(0) sched = old print(f"finishing round '{a.tag}' that was cut short") if sched is None: # the plan for this run: where it starts, how long it lasts, how fast it learns sched = {"tag": a.tag, "step0": step, "used0": t_used, "budget": a.minutes * 60, "steps": a.steps, "lr": a.lr, "done": False} def get(d, ix): x = torch.from_numpy(np.stack([d[i:i + cfg.ctx].astype(np.int64) for i in ix])) y = torch.from_numpy(np.stack([d[i + 1:i + 1 + cfg.ctx].astype(np.int64) for i in ix])) return x.to(dev), y.to(dev) def batch(d, bs): return get(d, np.random.randint(0, len(d) - cfg.ctx - 1, bs)) # the same 30 batches of unseen stories every time, so the "val" numbers can be compared with each other val_ix = np.random.default_rng(1234).integers(0, len(val) - cfg.ctx - 1, (30, a.batch)) @torch.no_grad() def evaluate(): model.eval() # always measured the plain way (32-bit, not compiled), like the browser runs it l = sum(model(*get(val, ix)).item() for ix in val_ix) / len(val_ix) model.train() return l warm = 200 def progress(): if sched["steps"]: return (step - sched["step0"]) / sched["steps"] return (t_used - sched["used0"]) / sched["budget"] def lr_now(): # learning rate: ramp up for 200 steps, then glide down to a tenth by the end of the run k = step - sched["step0"] if k < warm: return sched["lr"] * (k + 1) / warm return sched["lr"] * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * min(progress(), 1.0)))) def save(): torch.save({"model": model.state_dict(), "opt": opt.state_dict(), "step": step, "seconds": t_used, "config": cfg.__dict__, "sched": sched}, a.out + ".tmp") os.replace(a.out + ".tmp", a.out) # swap it in whole, so a crash never leaves half a file if a.keep: d = os.path.join(os.path.dirname(a.out), "snaps"); os.makedirs(d, exist_ok=True) shutil.copyfile(a.out, os.path.join(d, f"{step:08d}.pt")) for f in sorted(x for x in os.listdir(d) if x.endswith(".pt"))[:-a.keep]: os.remove(os.path.join(d, f)) def forward(m, x, y): with torch.autocast(dev, dtype=torch.bfloat16, enabled=a.bf16): return m(x, y) net = model if a.compile: try: net = torch.compile(model) forward(net, *batch(train, a.batch)).backward() # compiles here; nothing is learned from this one model.zero_grad(set_to_none=True) except Exception as e: print("could not compile the model, carrying on without it:", str(e)[:300]) net = model print(f"bf16 {a.bf16}, compiled {net is not model}", flush=True) log = open(a.log, "a") seen, total = 0, 0.0 t0 = time.time() while progress() < 1.0: while os.path.exists("PAUSE"): # make a file called PAUSE to borrow the CPU for something else; time.sleep(2); t0 = time.time() # the wait does not count as training time for g in opt.param_groups: g["lr"] = lr_now() loss = forward(net, *batch(train, a.batch)) lv = loss.item() if not math.isfinite(lv): print(f"step {step}: the loss is {lv}. Stopping; ckpt.pt still holds the last good save.", flush=True) sys.exit(1) opt.zero_grad(set_to_none=True) loss.backward() gn = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() step += 1; seen += 1; total += lv now = time.time(); t_used += now - t0; t0 = now if step % 100 == 0: print(f"step {step} loss {lv:.3f} lr {lr_now():.2e} grad {gn:.2f} {t_used/60:.1f} min", flush=True) if step % a.save_every == 0 and step % a.eval_every: save(); t0 = time.time() if step % a.eval_every == 0: vl = evaluate() model.eval() sample = tok.decode(model.generate(torch.tensor([tok.encode("Once upon a time")], device=dev), 80)[0].tolist()) model.train() print(f"== step {step} val {vl:.3f} train {total/seen:.3f}\n{sample}\n", flush=True) log.write(json.dumps({"step": step, "val": vl, "train": total / seen, "min": t_used / 60, "lr": lr_now(), "tag": sched["tag"], "sample": sample}) + "\n"); log.flush() seen, total = 0, 0.0 save() t0 = time.time() sched["done"] = True save() print("final val loss", evaluate(), "at step", step, flush=True)