Foundations to Frontier
Tests
F. NLP and Large Language Models › F4 Transformer Language Models

Building a GPT from Scratch

A GPT is a stack of Transformer decoder blocks trained to predict the next token. Token embeddings plus positional information enter a series of blocks, each with causal self-attention (every position mixes information from earlier positions) and an MLP, joined by residual connections and layer normalisation. A final linear layer produces logits over the vocabulary, and training minimises cross-entropy on every position of every sequence at once. This page builds one up piece by piece: embeddings, positions, causal attention, the block, the loss, training, parameter counts and generation. In the exercises you implement causal attention, cross-entropy and gradient checking, then train a one-layer GPT with hand-written backpropagation in NumPy. Each token copies the token 8 positions back with probability 0.9. A bigram model stayed at the uniform loss (2.30 nats). The GPT without positional embeddings reached only 2.19. With them it reached 0.61, close to the 0.50 floor, and put 99.5% of its attention on the token being copied.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A machine that keeps guessing the next word

A GPT reads text and, at every position, guesses the next token. To guess well it must look back at earlier tokens and decide which ones matter: that is what attention does. It must also know where each token is, or “the dog bit the man” and “the man bit the dog” would look the same. Stack a few of these attention steps, train on lots of text, and the guesses get remarkably good. The demo shows the causal mask: each token can look only at itself and earlier tokens.

LLM lab
Row i shows what token i may attend to: itself and earlier tokens only (36 of 64 pairs). This is what lets one forward pass train on every next-token prediction at once.
Why engineers care

Understanding a GPT at the level of its matrices is what lets engineers size models for onboard hardware, debug training, and judge claims about what a model can and cannot do.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A GPT is trained to…
  2. 2. Attention lets a token…
  3. 3. Positional information tells the model…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Embeddings: token ids → vectors via a V × d table, plus a learned (or sinusoidal, or rotary) position vector.
  • Causal self-attention: Q = XW_q, K = XW_k, V = XW_v; A = softmax(QKᵀ/√d + M) where M is −∞ above the diagonal; output A V W_o. Multi-head attention runs h such heads of size d/h in parallel.
  • Block: x ← x + Attn(LN(x)); x ← x + MLP(LN(x)), with the MLP expanding to 4d and back (pre-norm, as in GPT-2).
  • Output: logits = LN(x) W_out (often tied to the embedding table); loss = mean cross-entropy over all positions. A fresh model should start near ln V (10.8 for V = 50,257).
  • Parameters: about V·d + T·d + 12·d²·L (attention 4d², MLP 8d² per layer): GPT-2 small (V = 50,257, T = 1024, d = 768, L = 12) has about 124M.
  • Generation: feed the prompt, sample the next token from the last position’s distribution, append, repeat.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Initial loss for a vocabulary of 50,257:
  2. 2. Parameters per layer (attention + MLP):
  3. 3. Training predicts…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

A GPT in code

Exercise 1.

  • Implement causal attention; changing the last token cannot change earlier outputs.
  • Implement cross-entropy (uniform logits give ln V).
  • Check gradients with finite differences.

Practice.

  • Karpathy’s nanoGPT and minGPT are compact reference implementations; Hugging Face GPT2LMHeadModel is the production equivalent.
  • Sanity checks: initial loss ≈ ln V; the model can overfit one batch to near zero; loss falls smoothly with a warm-up then cosine learning-rate schedule.
  • Use AdamW, gradient clipping (norm 1.0), mixed precision and fused attention (scaled_dot_product_attention).
  • Tie input and output embeddings to save V·d parameters.
class Block(nn.Module):
    def __init__(self, d, h):
        super().__init__(); self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
        self.attn = nn.MultiheadAttention(d, h, batch_first=True)
        self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
    def forward(self, x):
        T = x.size(1); mask = torch.triu(torch.ones(T, T, dtype=torch.bool), 1)
        a = self.ln1(x); x = x + self.attn(a, a, a, attn_mask=mask, need_weights=False)[0]
        return x + self.mlp(self.ln2(x))
🐍 Exercise 1: causal attention, loss and gradient checking
Implement causal self-attention, cross-entropy and finite-difference gradients.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A compact reference GPT implementation:
  2. 2. A good first sanity check is that the model can…
  3. 3. Gradient clipping usually uses a norm of…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why positions are necessary. Self-attention without positional information is permutation-equivariant: shuffling the earlier tokens permutes the attention weights but not their set, so the model cannot know which token was 8 steps back. Position embeddings break this symmetry. In a causal model, the mask itself leaks some positional information (a token can count how many tokens it sees), which is why the no-position model in exercise 2 still gained a little (2.19 vs 2.30).

Why attention can implement lookups. With position embeddings, the query at position t can be aligned with the key at position t − 8 (a learned relative offset), so the softmax concentrates there and the value copies that token’s identity. This is the simplest form of the induction and copying circuits found in trained LLMs (F15).

Parallel training. The causal mask lets one forward pass compute the loss for all T positions, which is why decoders train efficiently, while generation stays sequential.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Attention without positions is…
  2. 2. The causal mask leaks positional information because…
  3. 3. Training is parallel over positions thanks to…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Can a one-layer GPT learn to look back exactly eight tokens?

History.

  • A. Vaswani et al., “Attention is all you need” (NeurIPS 2017).
  • A. Radford et al., “Improving language understanding by generative pre-training” (2018), GPT-1; “Language models are unsupervised multitask learners” (2019), GPT-2.
  • A. Karpathy, nanoGPT (2023).

Exercise 2.

  • Data: sequences of 16 tokens over a vocabulary of 10. Each token copies the token 8 positions back with probability 0.9, otherwise it is random. Loss is measured on positions where the copied token exists; the floor (entropy of the noise) is 0.50 nats.
  • Models:
    • bigram counts;
    • a one-layer, one-head GPT (d = 32, causal attention, residual, linear read-out), with or without learned positional embeddings.
  • Training: hand-written backpropagation, Adam, 600 steps of 32 sequences.
model held-out loss (nats)
uniform guess 2.303
bigram 2.304
GPT without positions 2.187
GPT with positions 0.611
entropy floor 0.500
  • The previous token is useless here: the bigram model is no better than guessing uniformly.
  • Attention needs positions to find the right token: without them the GPT barely improves. The small gain comes from the causal mask’s implicit position signal.
  • With positions it learns a lookup: attention from position t to the copied token at t − 7 (which predicts token t + 1) averages 0.995, and the loss approaches the floor.
  • Seed 1 gave the same picture (bigram 2.304, no positions 2.187, positions 0.621, attention 0.995).
🐍 Exercise 2 (research): can a one-layer GPT learn to look back exactly eight tokens?
Train bigram counts and a one-layer GPT with and without positional embeddings on copy-8-back sequences; measure loss and attention.

GPTs in AI, robotics and aerospace

  • Onboard assistants: sizing small decoder models for edge hardware from parameter and FLOP counts.
  • Sequence modelling: the same decoder architecture models telemetry, trajectories and robot action sequences.
  • Design lesson: build the model piece by piece and check each piece (initial loss, overfitting one batch, attention patterns).

References

  1. A. Vaswani et al. (2017). “Attention is all you need.” NeurIPS.
  2. A. Radford, J. Wu, R. Child, D. Luan, D. Amodei and I. Sutskever (2019). “Language models are unsupervised multitask learners.” OpenAI technical report.
  3. A. Karpathy (2023). nanoGPT. github.com/karpathy/nanoGPT.