Skip to content
Science, DecodedContext Jamming

Module 6 · suggested week 6

The Mathematics Inside Modern AI

Decode the equations behind the models.

~3 focused hoursBuilds on modules 1, 4 (advisory)
0 of 9 sections read

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)\mathbf{x} = (x_1, x_2, \ldots, x_d). Bold lower-case letters usually mean vectors; dd 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 dd-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.

Source: Templeton et al. 2024, Scaling Monosemanticity

Dot products: multiply, then add

Recognition

A dot product is a Σ loop

The dot product a⋅b\mathbf{a}\cdot\mathbf{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=1daibi=∥a∥ ∥b∥cos⁡ϕ\mathbf{a}\cdot\mathbf{b} = \sum_{i=1}^{d} a_i b_i = \|\mathbf{a}\|\,\|\mathbf{b}\|\cos\phi
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\mathbf{q}^{\top}\mathbf{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 matrix WW is a grid of numbers. Multiplying a matrix by a vector, WxW\mathbf{x}, computes one dot product per row of WW: each row is a "detector" and the output lists how strongly x\mathbf{x} matches each detector. A neural-network layer is then:

A dense layerEstablished
h=σ ⁣(Wx+b)\mathbf{h} = \sigma\!\left(W\mathbf{x} + \mathbf{b}\right)

Take input x\mathbf{x}, compute many weighted sums at once (WxW\mathbf{x}), shift each by a bias b\mathbf{b}, then apply a nonlinear squashing function σ\sigma elementwise. Here σ\sigma 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 derivative dLdθ\frac{dL}{d\theta} is a rate: if you nudge θ\theta a little, how much does LL change, per unit of nudge? A partial derivative ∂L∂θj\frac{\partial L}{\partial \theta_j} asks the same thing about one knob θj\theta_j while holding all the others fixed. The gradient ∇θL\nabla_\theta L collects every partial derivative into one vector, one entry per parameter:

The gradientEstablished
∇θL=(∂L∂θ1,∂L∂θ2,…,∂L∂θn)\nabla_\theta \mathcal{L} = \left(\frac{\partial \mathcal{L}}{\partial \theta_1}, \frac{\partial \mathcal{L}}{\partial \theta_2}, \ldots, \frac{\partial \mathcal{L}}{\partial \theta_n}\right)

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 loss L(θ)\mathcal{L}(\theta) is a single number that measures how wrong the model is with parameters θ\theta. For language models the standard choice is cross-entropy: the average of −log⁡pθ(actual next token)-\log p_\theta(\text{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-entropyEstablished
L(θ)=−1N∑t=1Nlog⁡pθ(xt∣x<t)\mathcal{L}(\theta) = -\frac{1}{N}\sum_{t=1}^{N} \log p_\theta(x_t \mid x_{<t})

Average, over NN positions in the text, of the "surprise" (−log⁡p-\log p) 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.

Inspect symbol by symbol →

Gradient descent: the update rule, symbol by symbol

Gradient descentMathematical model
θt+1=θt−η ∇θL(θt)\theta_{t+1} = \theta_t - \eta\,\nabla_\theta \mathcal{L}(\theta_t)

New parameters = old parameters minus a small step (size η\eta) in the direction the loss increases fastest. Subtracting means going downhill.

for (let t = 0; t < steps; t++) {
  const g = gradient(loss, theta);       // ∇θ L(θt)
  for (let j = 0; j < theta.length; j++) {
    theta[j] = theta[j] - eta * g[j];    // θ ← θ − η g
  }
}

Does not say: The textbook form. Real training uses minibatch estimates of the gradient and adaptive optimisers such as Adam, as discussed below.

Inspect symbol by symbol →

Every symbol

SymbolRead it asProgramming analogue
$\theta$All the model’s parameters (weights and biases) as one long vectortheta — a Float32Array with billions of entries
$t$ (subscript)Which step of training we are onLoop counter
$\eta$ (eta)Learning rate: step sizeA hyperparameter, e.g. 3e-4
$\nabla_\theta$"Gradient with respect to θ": all partial derivativesautograd / loss.backward()
$\mathcal{L}$The loss: one number scoring how wrong the model isA function returning a scalar
$-$Step against the gradient, i.e. downhillThe 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 temperatureEstablished
softmax⁡(z)i=ezi/T∑jezj/T\operatorname{softmax}(z)_i = \frac{e^{z_i / T}}{\sum_{j} e^{z_j / T}}

Exponentiate each raw score (logit) ziz_i so all are positive, then divide by the total so they sum to 1. Temperature TT sharpens (T<1T<1) or flattens (T>1T>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);

Inspect symbol by symbol →

Loading interactive…

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/Tz_i/T with −Ei/(kBT)-E_i/(k_B T) and softmax becomes the Boltzmann distribution of statistical mechanics: the probability of a state with energy EiE_i at temperature TT, with the denominator called the partition function ZZ. 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⁡ ⁣(QK⊤dk)V\operatorname{Attention}(Q,K,V) = \operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right) 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

Inspect symbol by symbol →

Unpacking attention

PieceShape (one head, n tokens)What it does
$Q, K, V$n×dkn \times d_k, n×dkn \times d_k, n×dvn \times d_vThree learned linear projections of the same token vectors
$QK^{\top}$n×nn \times nAll pairwise dot products: how relevant is token j to token i
$\div\sqrt{d_k}$n×nn \times nKeeps scores from growing with dimension, so softmax doesn’t saturate
softmax (rows)n×nn \times nEach row becomes a probability distribution: the attention pattern
$\cdot V$n×dvn \times d_vEach 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 θ\theta: forward pass, loss, backward pass, update, billions of times. Inference freezes θ\theta 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

PhysicsLevel 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.

PhysicsLevel 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.

BiologyLevel 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?

Watch & explore

Video10 min3Blue1Brown

Vectors (Essence of linear algebra, ch. 1)

Three views of a vector (arrow, list of numbers, abstract object) and why ML mostly uses the second while reasoning with the first.

Watch for: The "list of numbers" view. An embedding is exactly that, just with thousands of entries.

Verified: YouTube oEmbed title+channel check, 2026-10-30

Video14 min3Blue1Brown

Dot products and duality (ch. 9)

Why multiply-and-add measures alignment. Attention scores are dot products.

Watch for: The projection picture. Pair it with the Vectors and Dot Products interactive.

Verified: YouTube oEmbed title+channel check, 2026-10-30

Video11 min3Blue1Brown

Linear transformations and matrices (ch. 3)

A matrix is a function that moves space around. That reframing makes "weight matrix" stop sounding like a spreadsheet.

Watch for: Columns of the matrix as "where the basis vectors land".

Verified: YouTube oEmbed title+channel check, 2026-10-30

Video19 min3Blue1Brown

But what is a neural network? (Deep learning, ch. 1)

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.

Verified: YouTube oEmbed title+channel check, 2026-10-30

Video21 min3Blue1Brown

Gradient descent, how neural networks learn (ch. 2)

Makes the cost function concrete and shows the gradient as a direction in a space with thousands of dimensions.

Watch for: How "the negative gradient" is presented as a list of nudges, one per weight, ranked by how much each nudge matters.

Verified: YouTube oEmbed title+channel check, 2026-10-30

Video13 min3Blue1Brown

Backpropagation, intuitively (ch. 3)

Explains how the gradient is actually computed: blame flows backward from the loss through each layer.

Watch for: The difference between what gradient descent does (take a step) and what backpropagation does (compute which step).

Verified: YouTube oEmbed title+channel check, 2026-10-30

Video27 min3Blue1Brown

Transformers, the tech behind LLMs (ch. 5)

Embeddings as directions, softmax with temperature, and the unembedding step that turns a vector back into token probabilities.

Watch for: The softmax-with-temperature segment. Compare it with the Token Probabilities interactive in Module 6.

Verified: YouTube oEmbed title+channel check, 2026-10-30

Video26 min3Blue1Brown

Attention in transformers, step-by-step (ch. 6)

The best visual walkthrough of Q, K, V and the attention pattern as a grid of dot products.

Watch for: Where the √d_k scaling and the softmax appear. Then open the attention equation in the Equation Inspector.

Verified: YouTube oEmbed title+channel check, 2026-10-30

ArticleJay Alammar

The Illustrated Transformer

Diagram-first walkthrough of the 2017 Transformer, matrix shapes included.

Watch for: Matrix dimensions at each step. Shapes are the fastest way to sanity-check an equation.

Verified: HTTP 200 + page content checked, 2026-10-30

InteractiveGabriel Goh · Distill

Why Momentum Really Works

An interactive article on optimisation dynamics, and the model for how a good interactive explainer behaves.

Watch for: The step-size slider. The same oscillation you see in Module 6 appears here with theory behind it.

Verified: HTTP 200 + page content checked, 2026-10-30

Free bookDeisenroth, Faisal & Ong

Mathematics for Machine Learning

Free PDF. The best single reference for ML notation: vectors, matrices, gradients, probability.

Watch for: Use the index as a dictionary. Look up a symbol when a paper uses it rather than reading front to back.

Verified: HTTP 200 + page content checked, 2026-10-30

Free bookSimon J. D. Prince

Understanding Deep Learning

Free PDF plus notebooks. The clearest modern bridge from equations to architectures, including transformers.

Watch for: Chapters on loss functions and on transformers. The notation table at the front is worth bookmarking.

Verified: HTTP 200 + page content checked, 2026-10-30

CourseMIT OpenCourseWare

18.06 Linear Algebra (Gilbert Strang)

The reference course. Use individual lectures (matrix multiplication, eigenvalues, SVD) as a library, not a syllabus.

Watch for: Lectures on eigenvalues and the SVD. They are the vocabulary behind "low-rank", "spectrum" and "subspace" in ML papers.

Verified: HTTP 200 + page content checked, 2026-10-30

Research & references

  • Conference paperAshish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, et al. · 2017 · NeurIPS 2017 (arXiv:1706.03762)

    Attention Is All You Need

    Origin of the scaled dot-product attention equation. Limitation: evaluated on machine translation; the decoder-only LLM era came later.

  • WebAdly Templeton et al. (Anthropic) · 2024 · transformer-circuits.pub

    Scaling Monosemanticity

    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)

    Understanding Deep Learning

    Clear derivations of loss functions, optimisers and transformers. Limitation: a textbook; frontier practice moves faster.

Reflect

There are no right answers to check against. These questions are for thinking on the page, and your answers go to your notebook.

In your own words, what does the minus sign in the gradient-descent update do, and what would happen if it were a plus?

Not saved yetAll reflections →

Pick a prompt you use often. Which part of your workflow is training, and which is inference, from the model’s point of view?

Not saved yetAll reflections →

An LLM tells you "attention lets the model understand which words matter." Rewrite that sentence so it is accurate about what the equation computes.

Not saved yetAll reflections →

Where does the analogy between softmax temperature and physical temperature help you, and where could it mislead you?

Not saved yetAll reflections →