Read the core equations of modern ML (vectors, dot products, matrices, gradients, loss, gradient descent, softmax and scaled dot-product attention) symbol by symbol, and know where each is an idealisation of real training and inference systems.
Vectors and embeddings: meaning as a list of numbers
A vector in ML is first of all a list of numbers: x=(x1,x2,…,xd). Bold lower-case letters usually mean vectors; d is the dimension (how many numbers). A token embedding is a vector of a few thousand numbers that the model learned to assign to that token.
The geometric view is what makes vectors useful for thought: each list is a point (or arrow) in d-dimensional space, and directions in that space can carry meaning. Interpretability research finds that many concepts correspond, approximately, to directions.
▲Empirical regularity
In trained language models, many human-interpretable features can be found as approximately linear directions in activation space (for example via sparse autoencoders). This is well supported but not universal: some features appear nonlinear or entangled, and "how many features" depends on the method.
The dot product a⋅b multiplies matching entries and adds them up. It is the summation loop from Module 1 with two arrays. Geometrically it measures how aligned two vectors are: big and positive when they point the same way, zero when perpendicular, negative when opposed.
a⋅b=i=1∑daibi=∥a∥∥b∥cosϕ
let dot = 0;
for (let i = 0; i < a.length; i++) {
dot += a[i] * b[i];
}
Loading interactive…
Drag the arrow tips. Watch the dot product go to zero when the vectors are perpendicular and negative when they oppose. Cosine similarity divides out the lengths so only direction matters, which is why retrieval systems use it to compare embeddings.
Three places you have already met a dot product without the name: a weighted average (weights · values), a neuron's pre-activation (weights · inputs, plus bias), and an attention score (query · key). The notation q⊤k (a transposed column vector times a column vector) is the same dot product written in matrix form. See transpose and dot.
Matrices: many dot products at once
A matrixW is a grid of numbers. Multiplying a matrix by a vector, Wx, computes one dot product per row of W: each row is a "detector" and the output lists how strongly x matches each detector. A neural-network layer is then:
A dense layer■Established
h=σ(Wx+b)
Take input x, compute many weighted sums at once (Wx), shift each by a bias b, then apply a nonlinear squashing function σ elementwise. Here σ is an activation function, not a standard deviation; Greek letters are reused.
import numpy as np
h = np.maximum(0, W @ x + b) # ReLU as the nonlinearity
Does not say: Modern transformers use variants (GELU or SwiGLU activations, layer normalisation, residual connections) but the multiply-add-squash skeleton is the same.
Derivatives and gradients: which way is downhill?
A derivativedθdL is a rate: if you nudge θ a little, how much does L change, per unit of nudge? A partial derivative∂θj∂L asks the same thing about one knob θj while holding all the others fixed. The gradient∇θL collects every partial derivative into one vector, one entry per parameter:
The gradient■Established
∇θL=(∂θ1∂L,∂θ2∂L,…,∂θn∂L)
A list of sensitivities: for every parameter, how much the loss would rise if that parameter increased slightly. It points in the direction of steepest increase, so its negative points steepest downhill.
■Established
Backpropagation is the chain rule of calculus applied efficiently through the layers of a network to compute the gradient. It computes which direction to step; gradient descent is the rule for taking the step.
Loss functions: what "better" means
Before you can descend, you need a landscape. The lossL(θ) is a single number that measures how wrong the model is with parameters θ. For language models the standard choice is cross-entropy: the average of −logpθ(actual next token) over training text. It is small when the model assigns high probability to what actually came next. (Module 4 builds this from Shannon entropy; see the cross-entropy inspector.)
Next-token cross-entropy■Established
L(θ)=−N1t=1∑Nlogpθ(xt∣x<t)
Average, over N positions in the text, of the "surprise" (−logp) the model felt at the token that actually occurred, given everything before it.
let loss = 0;
for (let t = 0; t < N; t++) {
loss += -Math.log(model.prob(tokens[t], tokens.slice(0, t)));
}
loss /= N;
Does not say: This is the pre-training objective. Post-training (instruction tuning, RLHF, RLAIF) optimises different objectives on top of it.
All the model’s parameters (weights and biases) as one long vector
theta — a Float32Array with billions of entries
$t$ (subscript)
Which step of training we are on
Loop counter
$\eta$ (eta)
Learning rate: step size
A hyperparameter, e.g. 3e-4
$\nabla_\theta$
"Gradient with respect to θ": all partial derivatives
autograd / loss.backward()
$\mathcal{L}$
The loss: one number scoring how wrong the model is
A function returning a scalar
$-$
Step against the gradient, i.e. downhill
The sign that makes it descent, not ascent
Loading interactive…
Change the learning rate. Too small and progress crawls; well chosen and the point slides into the valley; too large and it overshoots, zig-zags across the valley, or diverges. Each step uses only the local slope.
Softmax: scores into probabilities
Softmax with temperature■Established
softmax(z)i=∑jezj/Tezi/T
Exponentiate each raw score (logit) zi so all are positive, then divide by the total so they sum to 1. Temperature T sharpens (T<1) or flattens (T>1) the distribution.
const exps = logits.map(z => Math.exp(z / T));
const Z = exps.reduce((a, b) => a + b, 0); // the Σ in the denominator
const probs = exps.map(e => e / Z);
Adjust temperature and sample. Low temperature nearly always picks the top token; high temperature spreads probability onto unlikely tokens. The logits here are hand-set for illustration, not taken from a real model.
Go deeper: The same formula in physics
Replace zi/T with −Ei/(kBT) and softmax becomes the Boltzmann distribution of statistical mechanics: the probability of a state with energy Ei at temperature T, with the denominator called the partition functionZ. This is a genuine Level 2 connection: the same mathematical object. ML borrowed the word "temperature" from physics for that reason. It is not a claim that token sampling involves thermal energy. See the Boltzmann inspector.
Attention: the equation behind transformers
Scaled dot-product attention (Vaswani et al. 2017)■Established
Attention(Q,K,V)=softmax(dkQK⊤)V
Each token asks a question (query), every token offers a label (key) and a payload (value). Score every query against every key with dot products, scale, turn each row of scores into weights with softmax, and output a weighted average of the values.
scores = Q @ K.T / np.sqrt(d_k) # every query · every key
weights = softmax(scores, axis=-1) # each row sums to 1
out = weights @ V # weighted average of values
Three learned linear projections of the same token vectors
$QK^{\top}$
n×n
All pairwise dot products: how relevant is token j to token i
$\div\sqrt{d_k}$
n×n
Keeps scores from growing with dimension, so softmax doesn’t saturate
softmax (rows)
n×n
Each row becomes a probability distribution: the attention pattern
$\cdot V$
n×dv
Each output is a weighted mix of value vectors
Loading interactive…
A toy sentence with hand-chosen 2D query and key vectors. Select a token to see its row of scores become a softmax distribution. Real models learn Q, K and V projections in hundreds of dimensions, run many heads in parallel, and apply a causal mask so tokens cannot attend to the future.
Training versus inference
Training changes θ: forward pass, loss, backward pass, update, billions of times. Inference freezes θ and only runs forward passes: compute logits, softmax, sample a token, append it, repeat.
Production inference adds engineering that the equations omit. A KV cache stores past keys and values so each new token does not recompute attention over the whole prefix. Batching, quantisation, speculative decoding and sampling settings (temperature, top-p) all change cost or output without changing the learned parameters.
■Established
At inference, a standard transformer’s parameters do not change. Apparent "learning" within a conversation (in-context learning) happens through activations computed from the prompt, not through weight updates.
To see these equations in their original habitat, open the guided reading of Attention Is All You Need.
Connections, with their levels
Physics≅Level 2 · Shared math
Softmax and the Boltzmann distribution
Softmax with temperature is mathematically the Boltzmann distribution with logits playing the role of negative energies.
Why this level: Identical functional form and a shared vocabulary ("temperature", "partition function"). There is no shared physical mechanism: no heat bath in a GPU’s sampler.
Physics≅Level 2 · Shared math
Gradient descent and energy minimisation
A ball in a viscous fluid rolling down a potential obeys an equation closely resembling continuous-time gradient descent (gradient flow).
Why this level: Gradient flow is the shared mathematics. Physical systems do not compute gradients; they respond to forces. Momentum and noise make the analogy richer, and also more approximate.
Biology≈Level 1 · Analogy
Artificial vs biological neurons
The weighted-sum-plus-threshold neuron was inspired by biological neurons, which integrate synaptic inputs and fire.
Why this level: Biological neurons spike in time, have dendritic computation, neuromodulation and plasticity rules unlike backpropagation. The historical inspiration is real; the equivalence is not.
Skeptic’s corner: Schematic equations vs. real systems
The equations in this module are correct as mathematics and accurate as descriptions of the core of modern ML. They are not complete descriptions of how any specific frontier model was trained or served, and much of that is unpublished.
Is the explanation using textbook SGD where the system actually uses Adam, schedules and minibatches, and does that difference matter for the claim?
Does a claim about "what the model attends to" rest on attention maps alone, or on causal interventions?
Is a claim about a proprietary model’s training sourced to a paper or system card, or inferred?
Do the matrix shapes in the explanation actually work out?
The cleanest picture of a network as layers of numbers, weights as knobs, and a layer as a matrix-vector product followed by a nonlinearity.
Watch for: The moment the weights are written as a matrix W times a vector a, plus a bias b. That single line is the equation inside every dense layer you will meet on arXiv.
Features as directions, found with sparse autoencoders in a production model. Limitation: dictionary results depend on SAE size and method; coverage of all model computation is far from complete.
BookSimon J. D. Prince · 2023 · MIT Press (free PDF)
The dot product a⋅b=∑iaibi is a Σ loop: multiply matching entries, then add. It equals ∥a∥∥b∥cosθ, so it is large when the vectors point the same way, zero when they are perpendicular, and negative when they oppose. Embeddings have hundreds or thousands of entries instead of two, but the loop is identical. That is why attention scores and “cosine similarity” are both dot products.
Gradient descent landscape
step t0
θ(-2.60, 1.40)
L(θ)6.3870
‖∇L‖8.409
Each step applies θt+1=θt−η∇θL(θt): compute the slope at the current point and move a distance η times that slope, downhill. In the narrow valley a large η overshoots across the steep walls and zig-zags or diverges, while a small one crawls along the floor. Momentum (a running average of past steps) is one of the fixes used by real optimisers such as Adam. A real model has billions of θ dimensions rather than two, and the gradient is estimated from minibatches, so this is an idealisation.
Token probabilities
The transformer was introduced in a paper titled “Attention Is All You▁
Need
95.9%z=9.1
Want
1.9%z=5.2
Get
0.9%z=4.4
Have
0.6%z=4.1
Know
0.3%z=3.2
Require
0.2%z=2.9
need
0.1%z=2.4
Deserve
0.1%z=1.6
Entropy of next-token distribution0.33 bits
Loss if true token is “Need”0.042 nats
T → 0 behaves likeargmax (greedy)
A model outputs one score (logit) zi per vocabulary token. Softmax, pi=ezi/T/∑jezj/T, turns the scores into probabilities that sum to 1. Temperature T rescales the scores before the exponent: low T sharpens the distribution, high T flattens it. These eight logits were written by hand for teaching, and a real vocabulary has tens of thousands of tokens. The training loss on this step would be −lnp(“ Need”).
Scaled dot-product attention
Choose a query token:
Thecatsatonthematbecauseitwastired
“it” attends most to“cat” · 56%
Raw score (top)2.80
Row entropy (spread)2.07 bits
softmax(dkQKT)V. Each row of the grid is one query token. Its scores are dot products with every key, which softmax turns into weights summing to 1, and the output is that weighted mix of value vectors. These 4-dimensional vectors were written by hand so that “it” looks for an animate noun. Trained models learn their own features, and they are rarely this tidy. Turn off the dk scaling and raise dk: the softmax saturates to one-hot, which is the problem the scaling was introduced to prevent.