Beginner about 8 h
The picture
01
Vectors
dot product = similarity
02
Matrices
linear maps, shapes
03
Derivatives
chain rule
04
Probability
distributions, softmax
05
Information
cross-entropy, perplexity
The three ideas that carry everything
1. Dot products measure alignment. Attention scores, embedding similarity and a neuron's pre-activation are all dot products: .
2. The chain rule is backpropagation. If then . A network is a long composition, so training is the chain rule applied systematically.
3. Models output distributions. The softmax turns raw scores (logits) into probabilities, and cross-entropy measures how surprised the model was by the right answer.
Perplexity is the exponential of the average per-token cross-entropy. A perplexity of 10 means the model is as uncertain as a fair 10-sided die.
Shapes are the whole game
Most bugs are shape bugs. Practise predicting shapes:
import torch
x = torch.randn(32, 128, 512) # (batch, tokens, features)
W = torch.randn(512, 2048)
y = x @ W # (32, 128, 2048): matmul over the last dim
b = torch.randn(2048)
z = y + b # broadcast: b is added to every row
print(y.shape, z.shape)
logits = torch.randn(4, 10)
p = torch.softmax(logits, dim=-1) # normalise over the class dimension
assert torch.allclose(p.sum(-1), torch.ones(4))
Numerical stability: log-sum-exp
exp overflows. Subtract the max before exponentiating, which does not change the softmax:
def stable_softmax(z):
z = z - z.max(dim=-1, keepdim=True).values
e = z.exp()
return e / e.sum(dim=-1, keepdim=True)
def cross_entropy(logits, targets):
logp = logits - logits.logsumexp(dim=-1, keepdim=True)
return -logp[torch.arange(len(targets)), targets].mean()
Information theory in two lines
- Entropy is the average surprise of a distribution.
- KL divergence measures how far is from . You will meet it again in RLHF, DPO and distillation.
Common mistakes
- Softmax over the wrong dimension.
- Taking
log(softmax(x))instead of using a fused log-softmax, which loses precision. - Forgetting that the loss is averaged over tokens when comparing runs with different sequence lengths.
Exercises
- Derive for softmax followed by cross-entropy.
- Verify your result against
torch.autograd.grad.
You are done when you can…
- Predict the output shape of a matrix product and a broadcast without running code
- Derive the gradient of a two-layer network by applying the chain rule
- Compute cross-entropy and perplexity from logits by hand