Intermediate about 8 h
The picture
01
Corpus
your text
02
Tokenise
ids, train/val split
03
Batches
(x, y shifted by 1)
04
Train
AdamW, cosine LR
05
Evaluate
val loss
06
Generate
sample tokens
The objective
A language model is trained to predict the next token. Given a block of text of length , the input is tokens and the target is the same block shifted by one. One forward pass gives training signals.
Data
import torch
text = open("input.txt", encoding="utf-8").read()
chars = sorted(set(text)) # swap for BPE once it works
stoi = {c: i for i, c in enumerate(chars)}
data = torch.tensor([stoi[c] for c in text], dtype=torch.long)
n = int(0.9 * len(data))
train, val = data[:n], data[n:]
def get_batch(split, B=64, T=256, device="cpu"):
d = train if split == "train" else val
ix = torch.randint(len(d) - T - 1, (B,))
x = torch.stack([d[i : i + T] for i in ix])
y = torch.stack([d[i + 1 : i + T + 1] for i in ix]) # shifted by one
return x.to(device), y.to(device)
Training loop with a cosine schedule
import math
model = GPT(vocab=len(chars), d=384, n_layers=6, n_heads=6, block_size=256).to(device)
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1)
max_steps, warmup = 5000, 200
def lr_at(step):
if step < warmup:
return 3e-4 * (step + 1) / warmup
p = (step - warmup) / (max_steps - warmup)
return 3e-5 + 0.5 * (3e-4 - 3e-5) * (1 + math.cos(math.pi * p))
@torch.no_grad()
def estimate_loss(iters=50):
model.eval()
out = {s: sum(model(*get_batch(s, device=device))[1].item() for _ in range(iters)) / iters for s in ("train", "val")}
model.train()
return out
for step in range(max_steps):
for g in opt.param_groups:
g["lr"] = lr_at(step)
xb, yb = get_batch("train", device=device)
_, loss = model(xb, yb)
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
if step % 250 == 0:
print(step, estimate_loss())
Generation
@torch.no_grad()
def generate(model, idx, max_new_tokens, temperature=1.0, top_k=None):
model.eval()
for _ in range(max_new_tokens):
logits, _ = model(idx[:, -model.block_size:])
logits = logits[:, -1, :] / temperature
if top_k is not None:
v, _ = torch.topk(logits, top_k)
logits[logits < v[:, [-1]]] = float("-inf")
probs = torch.softmax(logits, dim=-1)
idx = torch.cat([idx, torch.multinomial(probs, 1)], dim=1)
return idx
Baselines that keep you honest
A model that predicts every character with its unigram frequency has a loss of about the entropy of the character distribution. If you cannot beat that, there is a bug. Compare also to a bigram model, which is just a lookup table: a transformer should beat it comfortably.
What you will see
Early on the output is gibberish with plausible spacing; later you get words, then sentences that sound right and mean nothing. If validation loss starts rising while training loss falls, the model is memorising your corpus. Small corpora overfit quickly, which is why real pre-training uses billions of tokens.
Common mistakes
- Evaluating with dropout or in train mode.
- Using the same slice for train and validation.
- Scaling to a big model before the small one overfits a single batch.
Exercises
- Train three sizes (width 128, 256, 384) with the same steps and plot validation loss against parameter count.
- Replace the character vocabulary with your BPE from the tokenization topic and compare bits per character.
- Add gradient accumulation to simulate a bigger batch.
You are done when you can…
- Train a model to a validation loss clearly below the unigram baseline
- Plot train and validation loss and say when you would stop
- Generate text autoregressively and explain every line of the loop