Build and train a GPT from scratch

Data loading, the training loop, evaluation and generation: a working language model on your own text.

Intermediate about 8 h

The picture

  1. 01

    Corpus

    your text

  2. 02

    Tokenise

    ids, train/val split

  3. 03

    Batches

    (x, y shifted by 1)

  4. 04

    Train

    AdamW, cosine LR

  5. 05

    Evaluate

    val loss

  6. 06

    Generate

    sample tokens

The objective

A language model is trained to predict the next token. Given a block of text of length TT, the input is tokens 0..T−10..T-1 and the target is the same block shifted by one. One forward pass gives TT training signals.

L(θ)=−1T∑t=1Tlog⁡pθ(xt∣x<t)\mathcal{L}(\theta) = -\frac{1}{T}\sum_{t=1}^{T}\log p_\theta(x_t \mid x_{<t})

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

  1. Train three sizes (width 128, 256, 384) with the same steps and plot validation loss against parameter count.
  2. Replace the character vocabulary with your BPE from the tokenization topic and compare bits per character.
  3. 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