Chapter 5 / 16

Building and Training a Small GPT from Scratch

Advanced 5โ€“6 h ยท Prerequisites: Transformer Architecture and Attention

Learning objectives

  • Build a character-level tokenizer and data pipeline
  • Assemble embeddings, transformer blocks and a language-model head
  • Train and sample from a small GPT on CPU or a single GPU
  • Distinguish educational training from production-scale LLM training

Introduction

In chapter 4 you built attention and a transformer block. Now you put everything together into a complete GPT-style language model: tokenizer, data pipeline, embeddings, stacked transformer blocks, a language-model head, a training loop and text generation. The model is deliberately tiny โ€“ about 100,000 parameters โ€“ so it trains on a laptop CPU in well under a minute. Its architecture is the same as that of GPT-2; what separates it from today's large models is scale: data, parameters and compute.

Building a language model once yourself removes the mystery. You will see that "predicting the next token" is literally a cross-entropy loss on shifted sequences, that generation is a loop of sampling from a softmax, and that temperature, context length and training data directly shape what comes out. This understanding is what lets you reason about real LLMs: why they hallucinate, why context windows matter, why fine-tuning works (chapter 6) and why serving them is expensive (chapters 7 and 14).

Tokenizer and training data

This chapter uses a character-level tokenizer: every distinct character is one token. It needs no library and makes every step visible. Real LLMs use subword tokenizers (byte-pair encoding and variants, chapter 4) with vocabularies of tens of thousands of tokens, so they need far fewer tokens per text.

The training text must be split so that validation measures generalisation. A classic mistake is to repeat a small text many times and then split it: the validation set is a copy of training data, and a low validation loss only proves memorisation. The script therefore generates sentences from a small grammar at random โ€“ validation sentences are new combinations the model has not seen.

Training examples are windows of block_size tokens. The targets are the same window shifted by one position, so a window of 64 characters yields 64 next-token predictions at once โ€“ causal masking (chapter 4) makes each position see only its past.

From embeddings to the language-model head

Token embeddings map each token ID to a vector; position embeddings (learned, as in GPT-2) add the position. Their sum enters a stack of pre-norm transformer blocks: causal self-attention and an MLP, each with a residual connection.

After the last block, a final LayerNorm and a linear head map each position to logits over the vocabulary. The loss is the cross-entropy between these logits and the next tokens, averaged over all positions in the batch.

A sanity check before training: with random weights the model predicts all tokens roughly uniformly, so the loss should start near ln(vocab_size). The script prints this value; a much higher start loss points to an initialisation or loss bug.

Training the model

The training loop is the one from chapter 3 with three common additions: AdamW (Adam with decoupled weight decay), gradient clipping to keep rare large gradients from destabilising training, and a regular estimate of training and validation loss averaged over several batches.

Watch both curves. When training loss keeps falling and validation loss rises, the model memorises (chapter 3). In this chapter both stay close because the validation data consists of new combinations from the same grammar.

Every dataset has a floor: the randomness that no model can predict. The grammar makes about 8.03 nats of random choices per sentence of about 46.5 characters โ€“ at best about 0.17 nats per character. The model reaches about 0.22: most remaining error is unavoidable, which is why a bigger model barely helps here (lab 3).

Generating text: sampling and temperature

Generation is a loop: feed the context, take the logits of the last position, turn them into probabilities, draw one token, append it, repeat. The context is cut to the last block_size tokens โ€“ the model has never learned positions beyond that.

Temperature divides the logits before the softmax. Below 1 the distribution sharpens (more predictable, more repetitive), above 1 it flattens (more varied, more errors). Top-k and top-p (nucleus) sampling restrict sampling to the most likely tokens; greedy decoding always takes the most likely one.

The model produces fluent sentences that were never in the training data โ€“ including nonsensical ones such as 'a container trains the metrics'. It has learned form, not meaning or truth. This is the same mechanism behind hallucinations in large models.

Educational model versus production LLM

The architecture here matches GPT-2. Production LLMs differ in scale and engineering: subword tokenizers, billions of parameters, trillions of training tokens, RoPE positions, grouped-query attention, mixed-precision training across many GPUs, and careful data curation.

Scaling-law studies found that loss falls predictably as parameters, data and compute grow together; for a fixed compute budget, models are best trained on many more tokens than early large models used. Pre-training at that scale costs far more than most organisations spend โ€“ which is why chapter 6 adapts existing pretrained models instead.

After pre-training, chat models are further trained on instructions and human preferences. A pre-trained model like the one in this chapter only continues text; it does not follow instructions.

Key terminology

Character-level tokenizer
Tokenizer that maps every character to its own token ID.
Block size (context length)
Maximum number of tokens the model sees at once; also the length of training windows.
Language-model head
Final linear layer mapping each position's vector to logits over the vocabulary.
AdamW
Adam optimiser with decoupled weight decay; the standard optimiser for transformers.
Gradient clipping
Scaling gradients down when their norm exceeds a threshold, to stabilise training.
Temperature
Factor dividing the logits before softmax; controls how random sampling is.
Irreducible loss
The part of the loss caused by genuine randomness in the data; no model can go below it.
Scaling laws
Empirical relations between model size, data, compute and achievable loss.

Architecture diagrams

Training pipeline of the small GPT

flowchart LR
  T[Training text] --> TK[Character tokenizer]
  TK --> W[Windows of 64 tokens]
  W --> X[Inputs x]
  W --> Y[Targets y = x shifted by one]
  X --> M[Embeddings + 2 transformer blocks + LM head]
  M --> L[Cross-entropy loss]
  Y --> L
  L --> O[Backward pass + AdamW step]
  O --> M
Targets are the inputs shifted by one token; every position predicts its next token.

The generation loop

flowchart LR
  P[Prompt tokens] --> C[Crop to last block_size tokens]
  C --> F[Forward pass]
  F --> LG[Logits of last position]
  LG --> TMP[Divide by temperature]
  TMP --> SM[Softmax]
  SM --> S[Sample one token]
  S --> A[Append to context]
  A --> C
Each new token is appended to the context and fed back in.

Practical examples

Autocompletion. Code and text completion use exactly this loop: the editor sends the context, the model samples continuations, usually at a low temperature for predictable suggestions.

Why hallucinations happen. The small model writes 'a container trains the metrics' โ€“ grammatical, plausible in form, meaningless. Large models make the same kind of error at a higher level: fluent statements without a factual basis.

Working code

Project: a small GPT-style model from scratch

Tested with: Python 3.13, PyTorch 2.15 (CPU)

# pip install torch
# python ch5_small_gpt.py
"""Chapter 5 โ€“ a small character-level GPT, trained from scratch on CPU (under a minute)."""
import math
import random
import torch
from torch import nn
from torch.nn import functional as F

torch.manual_seed(0)

# 1. Data: sentences from a small grammar, combined at random. Validation sentences are new
#    combinations, so a low validation loss means the model learned the structure, not the text.
rng = random.Random(0)
subjects = ["the server", "the cluster", "a pod", "the model", "an engineer", "the service", "the pipeline", "a container"]
verbs = ["restarts", "scales", "logs", "routes", "trains", "monitors", "deploys", "measures"]
objects = ["the traffic", "every request", "the metrics", "a new version", "the data", "the latency", "each error", "the secrets"]
endings = ["every night", "after each change", "in production", "within seconds", "before the release", "on demand"]
def sentence():
    return f"{rng.choice(subjects)} {rng.choice(verbs)} {rng.choice(objects)} {rng.choice(endings)}.".capitalize()
text = "\n".join(sentence() for _ in range(3000))

chars = sorted(set(text))
vocab_size = len(chars)
stoi = {ch: i for i, ch in enumerate(chars)}
itos = {i: ch for ch, i in stoi.items()}
encode = lambda s: [stoi[c] for c in s]
decode = lambda ids: "".join(itos[i] for i in ids)

data = torch.tensor(encode(text), dtype=torch.long)
split = int(0.9 * len(data))
train_data, val_data = data[:split], data[split:]

# 2. Hyperparameters: tiny on purpose, so it trains on a laptop CPU.
block_size, batch_size = 64, 32
d_model, n_heads, n_layers, dropout = 64, 4, 2, 0.1
steps, lr = 1500, 3e-3

def get_batch(split_name):
    source = train_data if split_name == "train" else val_data
    ix = torch.randint(len(source) - block_size - 1, (batch_size,))
    x = torch.stack([source[i:i + block_size] for i in ix])
    y = torch.stack([source[i + 1:i + block_size + 1] for i in ix])   # targets = inputs shifted by one
    return x, y

# 3. The model: embeddings + N pre-norm transformer blocks + language-model head.
class Block(nn.Module):
    def __init__(self):
        super().__init__()
        self.ln1, self.ln2 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)
        self.qkv = nn.Linear(d_model, 3 * d_model)
        self.proj = nn.Linear(d_model, d_model)
        self.mlp = nn.Sequential(nn.Linear(d_model, 4 * d_model), nn.GELU(), nn.Linear(4 * d_model, d_model), nn.Dropout(dropout))
        self.drop = nn.Dropout(dropout)

    def forward(self, x):
        b, t, c = x.shape
        q, k, v = self.qkv(self.ln1(x)).split(c, dim=-1)
        q, k, v = (z.view(b, t, n_heads, c // n_heads).transpose(1, 2) for z in (q, k, v))
        y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=dropout if self.training else 0.0)
        x = x + self.drop(self.proj(y.transpose(1, 2).contiguous().view(b, t, c)))
        return x + self.mlp(self.ln2(x))

class SmallGPT(nn.Module):
    def __init__(self):
        super().__init__()
        self.tok = nn.Embedding(vocab_size, d_model)
        self.pos = nn.Embedding(block_size, d_model)       # learned positions, as in GPT-2
        self.blocks = nn.Sequential(*[Block() for _ in range(n_layers)])
        self.ln_f = nn.LayerNorm(d_model)
        self.head = nn.Linear(d_model, vocab_size)

    def forward(self, idx, targets=None):
        t = idx.size(1)
        x = self.tok(idx) + self.pos(torch.arange(t))
        logits = self.head(self.ln_f(self.blocks(x)))       # (batch, time, vocab)
        loss = None if targets is None else F.cross_entropy(logits.view(-1, vocab_size), targets.view(-1))
        return logits, loss

    @torch.no_grad()
    def generate(self, idx, max_new_tokens, temperature=0.8):
        for _ in range(max_new_tokens):
            logits, _ = self(idx[:, -block_size:])          # never more context than trained on
            probs = F.softmax(logits[:, -1, :] / temperature, dim=-1)
            idx = torch.cat([idx, torch.multinomial(probs, 1)], dim=1)
        return idx

model = SmallGPT()
print(f"vocabulary: {vocab_size} characters, parameters: {sum(p.numel() for p in model.parameters()):,}")
print(f"loss before training should be close to ln({vocab_size}) = {math.log(vocab_size):.2f}")

@torch.no_grad()
def estimate_loss():
    model.eval()
    out = {}
    for name in ("train", "val"):
        out[name] = torch.stack([model(*get_batch(name))[1] for _ in range(20)]).mean().item()
    model.train()
    return out

# 4. Training loop โ€“ the same four steps as in chapter 3.
optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
for step in range(steps + 1):
    if step % 500 == 0:
        losses = estimate_loss()
        print(f"step {step:4d}  train loss {losses['train']:.3f}  val loss {losses['val']:.3f}")
    if step == steps:
        break
    x, y = get_batch("train")
    _, loss = model(x, y)
    optimizer.zero_grad(set_to_none=True)
    loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    optimizer.step()

# 5. Sampling: start from a prompt and let the model continue.
model.eval()
prompt = torch.tensor([encode("The ")], dtype=torch.long)
print("sample:", decode(model.generate(prompt, 120)[0].tolist()).replace("\n", " "))
Expected output
vocabulary: 27 characters, parameters: 107,675
loss before training should be close to ln(27) = 3.30
step    0  train loss 3.444  val loss 3.445
step  500  train loss 0.233  val loss 0.233
step 1000  train loss 0.219  val loss 0.221
step 1500  train loss 0.216  val loss 0.222
sample: The cluster monitors the latency every night. A container trains the metrics after each change. The pipeline routes the metr

The loss falls from about ln(27) โ‰ˆ 3.3 to 0.22, close to the data's floor of about 0.17. Training and validation loss stay together because validation sentences are new combinations. The sample consists of new, grammatical sentences. Losses and samples can differ slightly across PyTorch versions and hardware; on a laptop CPU the run takes well under a minute.

Practice Lab

The exercises change one thing at a time. Predict the effect before you run the script.

Temperature

Beginner

After training, generate 100 characters from the prompt 'The ' with temperature 0.2 and with 1.5 (same random seed). Compare the two texts.

  • model.generate(prompt, 100, temperature=0.2)
  • Set torch.manual_seed(1) before each call so only the temperature differs.
Show solution
for temp in (0.2, 1.5):
    torch.manual_seed(1)
    print(temp, decode(model.generate(prompt, 100, temperature=temp)[0].tolist()))
# 0.2: clean, predictable sentences.
# 1.5: spelling errors appear ("dvery request", "satency") and sentences run together โ€“
#      unlikely characters are sampled more often.

Compute the irreducible loss

Intermediate

Each sentence makes four independent random choices (8 subjects, 8 verbs, 8 objects, 6 endings). Compute the minimum possible loss per character and compare it with the trained model.

  • A uniform choice among n options carries ln(n) nats.
  • Divide by the average number of characters per sentence (including the newline).
Show solution
import math
nats = 3 * math.log(8) + math.log(6)        # 8.03 nats per sentence
chars = len(text) / 3000                    # 46.5 characters per sentence
print(nats / chars)                         # 0.173 nats per character
# The model reaches about 0.22: most of the remaining loss cannot be learned at all.

Does a deeper model help?

Advanced

Change n_layers from 2 to 4 and train again. Compare the final validation loss and the training time. Explain the result.

  • Measure time with the shell's time command.
  • Compare the result with the floor from the previous exercise.
Show solution
# n_layers = 4: validation loss about 0.217 instead of 0.222, training time about twice as long.
# The data โ€“ not the model capacity โ€“ is the limit: the model is already close to the
# irreducible loss of about 0.17. More parameters only pay off when there is more to learn.

Practise with OOHM

Reinforce the chapter's vocabulary and concepts with dictation, rapid typing and quizzes on this topic.

Please log in to use this AI feature.

Knowledge check

1. What are the training targets of a GPT-style language model?
2. With random weights and a vocabulary of 27 tokens, the initial loss should be about โ€ฆ
3. Why can repeating a small text and then splitting it be misleading?
4. What does a temperature below 1 do?
5. Why is the context cropped to block_size during generation?
6. What does gradient clipping prevent?
7. The model's loss is close to the data's irreducible loss. What follows?
8. What mainly distinguishes this model from a production LLM?
9. Why does the model write sentences like 'a container trains the metrics'?
10. What does a pre-trained model without instruction tuning do with a question?

Common mistakes and troubleshooting

Validation loss is suspiciously low from the start.
Cause: Training and validation data overlap (duplicated text, or a split after shuffling repeated content).
Fix: Split before any repetition or augmentation; check that validation contains genuinely unseen material.
IndexError in the position embedding during generation.
Cause: The context grew beyond block_size.
Fix: Crop the context to the last block_size tokens before each forward pass.
Generated text is the same phrase over and over.
Cause: Greedy decoding or a very low temperature.
Fix: Sample with temperature around 0.7โ€“1.0, or use top-k / top-p sampling.

Summary

  • A GPT is embeddings + causal transformer blocks + LM head, trained with cross-entropy on shifted sequences.
  • Honest validation needs unseen data; repeated text only measures memorisation.
  • Every dataset has an irreducible loss; more capacity helps only where something is left to learn.
  • Generation is a sampling loop; temperature trades predictability for variety.

Learning outcomes

  • You can build, train and sample from a GPT-style model and interpret its loss curves.
  • You can explain hallucinations, context limits and sampling settings from first principles.

Official documentation