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.
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.
- 1. A GPT is trained to…
- 2. Attention lets a token…
- 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.
- 1. Initial loss for a vocabulary of 50,257:
- 2. Parameters per layer (attention + MLP):
- 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
GPT2LMHeadModelis 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))- 1. A compact reference GPT implementation:
- 2. A good first sanity check is that the model can…
- 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.
- 1. Attention without positions is…
- 2. The causal mask leaks positional information because…
- 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).
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
- A. Vaswani et al. (2017). “Attention is all you need.” NeurIPS.
- A. Radford, J. Wu, R. Child, D. Luan, D. Amodei and I. Sutskever (2019). “Language models are unsupervised multitask learners.” OpenAI technical report.
- A. Karpathy (2023). nanoGPT. github.com/karpathy/nanoGPT.