File size: 4,382 Bytes
ac5c307 | 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | """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())
|