Skip to content
AI from Scratch
EN

The minimum maths

Exactly what you need to understand a transformer. Not one formula more.

If notation scares you: everything here is something you have already used, running, in stages 00 to 06. This just gives it a name.


1. Vectors: a list of numbers with a direction

A vector is a list of numbers. That is it.

v = [0.3, -1.2, 0.8]

In a language model, each token is a vector of 768 to 12,288 numbers.

Dot product — the most important operation in the project

a · b  =  a₁b₁ + a₂b₂ + ... + aₙbₙ     (a number, not a vector)

What it means: how alike two vectors are in direction.

  • Large and positive → they point the same way.
  • Zero → perpendicular, unrelated.
  • Negative → opposite.

When attention computes "the compatibility between one token's query and another's key", that is a dot product. All of attention is this, repeated T² times.

Cosine similarity

The dot product depends on the length of the vectors. If only the direction matters, you normalize:

cos(a,b) = (a·b) / (|a| · |b|)          between -1 and 1

It is the standard measure for comparing embeddings. [Stages 04.2 and 12.1.]


2. Matrices: transforming vectors

A matrix is a table of numbers. Multiplying a vector by a matrix transforms it: stretches it, rotates it, projects it into another dimension.

y = x · W          x: (1×768)   W: (768×3072)   y: (1×3072)

Each column of W is a "detector": the result y[j] is the dot product of x with column j, that is, how much x resembles that pattern.

That is literally what a Linear layer does, and it accounts for 95% of a model's computation.

The shape rule

(a × b) · (b × c) = (a × c)

The inner dimensions have to touch and they disappear. 90% of the errors when programming neural networks are shapes that do not line up.

Cost

Multiplying (n×m) by (m×p) costs n·m·p multiplications. That is why doubling a model's dimension quadruples the computation.


3. Derivatives: the slope

The derivative answers: if I move the input a little, how much does the output change?

        f(x+h) - f(x)
f'(x) = ─────────────      with h very small
              h

The four you need:

functionderivativewhere it shows up
x²2xsquared loss
eˣeˣsoftmax
log x1/xcross-entropy
tanh x1 - tanh²xactivations

Partial derivative and gradient

With several variables, you differentiate with respect to one and hold the others fixed. The gradient is the vector of all the partials:

∇L = [∂L/∂w₁, ∂L/∂w₂, ..., ∂L/∂wₙ]

It points in the direction of steepest increase. That is why gradient descent goes against it:

w ← w - lr · ∇L

Those two lines are the engine of all modern AI. [Stage 00.1.]

w  ←  w  −  lr · ∇L
In plain English: move every number a little in the direction that brings the error down.
w
the parameter being learned (there are millions of them)
lr
how far you move on each step. The right value lives in an extremely narrow range
∇L
the gradient: the direction in which the error GROWS. That is why we go the other way, with the minus sign

4. The chain rule: the only trick that matters

If L depends on y, and y depends on x:

dL/dx = (dL/dy) · (dy/dx)

Read it as: "the total effect is the product of the effects along the way".

With many layers chained together:

dL/dx₁ = (dL/x₅)·(dx₅/dx₄)·(dx₄/dx₃)·(dx₃/dx₂)·(dx₂/dx₁)
dL/dx  =  (dL/dy) · (dy/dx)
In plain English: the total effect is the product of the effects along the way.
The chain rule
is ALL of backpropagation. You walk the graph backwards multiplying local derivatives. There is nothing else to it

That is backpropagation. There is nothing else to it. You walk the graph backwards multiplying local derivatives.

And it explains two pathologies along the way:

  • If every factor is < 1, the product of 100 factors is ~0 → vanishing gradient.
  • If every factor is > 1, it explodes.
  • The residual connection x + f(x) has derivative 1 + f'(x). That 1 is a motorway the gradient passes down intact. [Stage 07.2, measured.]

5. Probability: from scores to decisions

Softmax

Turns arbitrary numbers into probabilities that add up to 1:

              e^(zᵢ)
softmax(z)ᵢ = ────────
              Σ e^(zⱼ)
  • Exponential → everything positive, and it amplifies the differences.
  • Divide by the sum → adds up to 1.

Compulsory trick: subtract the maximum before exponentiating. e^1000 is infinity. Subtracting a constant does not change the result (it cancels out) and it avoids the overflow. [Implemented in mininn/tensor.py.]

Cross-entropy — the loss of every language model

L = -log P(correct token)
P(correct)loss
1.00.00
0.50.69
0.12.30
0.014.61
→ 0→ ∞

It punishes being confident and wrong enormously. That is what you want.

Perplexity

perplexity = e^L

"How many options the model is torn between, on average." Perplexity 8.7 = like choosing blind between 8.7 characters.

It is only comparable between models with the SAME tokenizer. Comparing the perplexity of a character model with a BPE one means nothing. It is mistake number one when reading comparisons.

The gradient of cross-entropy

∂L/∂logits  =  probabilities  −  one_hot(correct)
In plain English: push down what you predicted, push up what was correct.
This single line
is the heart of training any language model. Everything else is engineering detail around it

The prettiest result in the project. If p = softmax(z) and the target is y:

∂L/∂z = p - onehot(y)

Read it: "push down what you predicted, push up what was correct". That single line is the heart of training any LLM. [In cross_entropy.]


6. Statistics: why scale matters

Mean, variance, standard deviation

μ = (1/n)Σxᵢ          σ² = (1/n)Σ(xᵢ-μ)²          σ = √σ²

LayerNorm normalizes each vector to have μ=0 and σ=1, then applies a learned scale and shift. Without this, magnitudes drift as they cross 80 layers and training breaks.

Variance of a sum

If you add n independent variables with variance 1, the sum has variance n, and standard deviation √n.

That is where two of the transformer's most important constants come from:

  1. 1/√dk in attention: the dot product of two vectors of dimension dk has standard deviation √dk. Without dividing, at dk=64 the scores are ±8, the softmax saturates, and the gradient goes to zero. [Measured in stage 05.]
  1. 1/√fan_in in initialization: it keeps the variance of the activations constant as they propagate through the layers. [Measured in stage 07.2: with the wrong scale, the gradient at layer 1 is exactly 0.0.]

7. What you do NOT need

To understand a transformer you do not need:

  • Integrals.
  • Differential equations.
  • Real analysis, topology, measure theory.
  • Eigenvalues (except to understand the learning rate limit, which is a nice extra and is in stage 00.2).
  • Information theory beyond "cross-entropy = average surprise".
  • Bayesian statistics.

The complete list of maths that actually gets used fits on this page. The rest of the difficulty is engineering: memory, parallelism, data, and knowing how to diagnose why something is not converging.


Notation conversion table

Papers use symbols. This is what they mean:

SymbolNameIn the code
xinputx
W, θweights, parametersweight, parameters()
bbiasbias
L, ℒlossperdida
∇gradient.grad
η, α, lrlearning ratelr
σsigmoid (or standard deviation).sigmoid()
Q, K, Vquery, key, valueq, k, v
dₖ, d_headdimension per headdh
d_model, Cmodel dimensionn_embd
T, L, n_ctxsequence lengthblock_size
Bbatch sizetam_lote
Vvocabulary sizevocab_size
β₁, β₂Adam momentsbetas
KL(p‖q)Kullback-Leibler divergence(stage 10)

Next: 04-hardware-y-escala.md