"""Train Kat on the tokenised DailyDialog stream. Saves the BEST checkpoint by validation loss, not the last one -- on a dataset this small val loss starts rising well before max_steps. """ import csv import math import sys import time import numpy as np import torch from config import DATA_DIR, ROOT, ModelConfig, TrainConfig from model import Kat CKPT_PATH = ROOT / "kat.pt" LOG_PATH = ROOT / "trainlog.csv" def load_split(name: str) -> np.ndarray: # memmap: the arrays are small, but this keeps batching allocation-free. return np.memmap(DATA_DIR / f"{name}.bin", dtype=np.uint16, mode="r") def get_batch(data: np.ndarray, cfg: ModelConfig, batch_size: int, gen: torch.Generator): ix = torch.randint(len(data) - cfg.block_size - 1, (batch_size,), generator=gen) x = torch.stack([ torch.from_numpy(data[i:i + cfg.block_size].astype(np.int64)) for i in ix ]) y = torch.stack([ torch.from_numpy(data[i + 1:i + 1 + cfg.block_size].astype(np.int64)) for i in ix ]) return x, y @torch.no_grad() def estimate_loss(model, data, cfg, tcfg, gen): model.eval() losses = torch.zeros(tcfg.eval_batches) for i in range(tcfg.eval_batches): x, y = get_batch(data, cfg, tcfg.batch_size, gen) _, loss = model(x, y) losses[i] = loss.item() model.train() return losses.mean().item() def lr_at(step: int, tcfg: TrainConfig) -> float: """Linear warmup, then cosine decay to 10% of peak.""" if step < tcfg.warmup_steps: return tcfg.lr * (step + 1) / tcfg.warmup_steps progress = (step - tcfg.warmup_steps) / max(1, tcfg.max_steps - tcfg.warmup_steps) return tcfg.lr * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * min(progress, 1.0)))) def configure_optimizer(model, tcfg: TrainConfig): # Decay matrices, not biases or LayerNorm gains -- weight decay on 1-D # params just fights the normalisation. decay = [p for p in model.parameters() if p.dim() >= 2] no_decay = [p for p in model.parameters() if p.dim() < 2] return torch.optim.AdamW( [{"params": decay, "weight_decay": tcfg.weight_decay}, {"params": no_decay, "weight_decay": 0.0}], lr=tcfg.lr, betas=(0.9, 0.95), ) def main() -> None: cfg, tcfg = ModelConfig(), TrainConfig() torch.manual_seed(tcfg.seed) torch.set_num_threads(12) gen = torch.Generator().manual_seed(tcfg.seed) train_data, val_data = load_split("train"), load_split("val") model = Kat(cfg) opt = configure_optimizer(model, tcfg) print(f"params {model.num_params():,} | train {len(train_data):,} tokens " f"| {tcfg.max_steps} steps @ batch {tcfg.batch_size}", flush=True) log = LOG_PATH.open("w", newline="") writer = csv.writer(log) writer.writerow(["step", "lr", "train_loss", "val_loss", "elapsed_s"]) best_val, best_step = float("inf"), 0 t0 = time.time() model.train() for step in range(tcfg.max_steps + 1): lr = lr_at(step, tcfg) for group in opt.param_groups: group["lr"] = lr x, y = get_batch(train_data, cfg, tcfg.batch_size, gen) _, loss = model(x, y) opt.zero_grad(set_to_none=True) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), tcfg.grad_clip) opt.step() if step % tcfg.eval_every == 0 or step == tcfg.max_steps: train_loss = estimate_loss(model, train_data, cfg, tcfg, gen) val_loss = estimate_loss(model, val_data, cfg, tcfg, gen) elapsed = time.time() - t0 writer.writerow([step, f"{lr:.6f}", f"{train_loss:.4f}", f"{val_loss:.4f}", f"{elapsed:.1f}"]) log.flush() marker = "" if val_loss < best_val: best_val, best_step = val_loss, step torch.save({"model": model.state_dict(), "cfg": cfg, "step": step, "val_loss": val_loss}, CKPT_PATH) marker = " <- saved" print(f"step {step:5d} | lr {lr:.5f} | train {train_loss:.4f} " f"| val {val_loss:.4f} | {elapsed/60:5.1f}m{marker}", flush=True) print(f"\nbest val {best_val:.4f} at step {best_step} -> {CKPT_PATH.name}") print(f"perplexity {math.exp(best_val):.1f}") log.close() if __name__ == "__main__": sys.exit(main())