The maths you actually use

Vectors and matrices, the chain rule, and probability with cross-entropy: just enough to read any LLM paper.

Beginner about 8 h

The picture

  1. 01

    Vectors

    dot product = similarity

  2. 02

    Matrices

    linear maps, shapes

  3. 03

    Derivatives

    chain rule

  4. 04

    Probability

    distributions, softmax

  5. 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: a⋅b=∑iaibi=∥a∥∥b∥cos⁡θa \cdot b = \sum_i a_i b_i = \lVert a\rVert \lVert b\rVert \cos\theta.

2. The chain rule is backpropagation. If L=f(g(x))L = f(g(x)) then dLdx=dLdg⋅dgdx\frac{dL}{dx} = \frac{dL}{dg}\cdot\frac{dg}{dx}. 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.

softmax(z)i=ezi∑jezj,L=−log⁡pθ(y∣x),PPL=eL\mathrm{softmax}(z)_i = \frac{e^{z_i}}{\sum_j e^{z_j}}, \qquad \mathcal{L} = -\log p_\theta(y \mid x), \qquad \mathrm{PPL} = e^{\mathcal{L}}

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 H(p)=−∑plog⁡pH(p) = -\sum p \log p is the average surprise of a distribution.
  • KL divergence DKL(p∥q)=∑plog⁡pqD_{KL}(p\Vert q)=\sum p\log\frac{p}{q} measures how far qq is from pp. 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

  1. Derive ∂L/∂zi=pi−yi\partial L/\partial z_i = p_i - y_i for softmax followed by cross-entropy.
  2. 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