Part I · Foundations
Chapter 2
The Math Toolkit
Six small pieces of mathematics that do almost all the work in modern AI.
In one sentenceVectors, probability, derivatives, optimization, statistics and information theory are the working language of machine learning — each exists to solve a specific problem.
Before you start
How to use this chapter
If mathematics has ever felt like a wall of symbols, this chapter is built for you. It covers six small toolkits, and each one exists because AI needed to solve a specific problem:
| Tool | The problem it solves in AI |
|---|---|
| Linear algebra | How do we represent data and transform it, millions of numbers at a time? |
| Probability | How does a model express — and learn from — uncertainty? |
| Calculus | Which way should each parameter move to reduce the error? |
| Optimization | How do we actually take those steps, reliably and fast? |
| Statistics | Is a measured improvement real, or noise? |
| Information theory | How do we score a prediction that's a probability distribution? |
Every idea follows the same pattern: intuition → picture → tiny numbers → the equation → what the equation is doing → where it appears in AI → something to try. The sections are independent. Do them in order, or jump in when a later chapter sends you back here.
The chain this chapter builds toward
- Vectors
- Dot Product
- Matrix Multiplication
- Softmax
- Cross-Entropy Loss
- Gradient Descent
- Training a neural network
2.1 · The shape of data
Linear algebra
The problem: a model can only compute with numbers, and it needs to process a lot of them at once.
The answer is to turn everything — a house, a word, an image — into a vector: a list of numbers, pictured as an arrow or a point in space. Once things are points, "similar" can mean "pointing the same way", and the dot product measures exactly that.
A vector is an ordered list of numbers, and in machine learning it is how every object — a house, a word, an image — becomes something a model can compute with.
Open the concept page →
The dot product multiplies two vectors entry by entry and adds the results, giving one number that is large when the vectors point the same way.
Open the concept page →
The second big idea: a matrix is a machine that transforms vectors. Every output number is a dot product of one row of the matrix with the input, and geometrically the whole plane gets rotated, stretched, sheared or squashed. That is literally what one layer of a neural network does — plus a nonlinearity, which you can toggle below.
Try it
Edit a 2×2 matrix and watch it stretch, rotate, shear or collapse the plane — then add ReLU and see how a neural-network layer folds space.
Multiplying a vector by a matrix transforms it — every output number is a dot product of one matrix row with the input — and that is exactly what a neural-network layer does.
Open the concept page →
In deep learning a tensor is just an n-dimensional array of numbers, and keeping track of its shape — batch × sequence × features — is most of the practical work of reading and writing models.
Open the concept page →
Where linear algebra leads
2.2 · Reasoning with uncertainty
Probability
The problem: the world is uncertain, and a model that outputs one hard answer can't say how sure it is — or learn from being "a bit wrong".
Modern models output distributions: "72% cat, 25% dog, 3% car"; a probability for each of 50,000 possible next tokens. Softmax turns raw scores into such a distribution.
A probability distribution assigns a likelihood to every possible outcome — and nearly every modern model's output is a distribution rather than a single answer.
Open the concept page →
Softmax turns any list of scores into a probability distribution — positive numbers that sum to 1 — giving exponentially more weight to larger scores.
Open the concept page →
Conditional probability is the heart of it: how likely is A given B? A language model is nothing but an estimator of . And Bayes' theorem tells you how to reverse a condition — which is where intuition most often fails:
Try it
A rare condition, an imperfect test: see why a positive result can still mean you're probably fine — Bayes' theorem as counting.
Conditional probability asks how likely something is given what you already know, and Bayes' theorem tells you how to flip it — from P(evidence | cause) to P(cause | evidence).
Open the concept page →
Chain conditional probabilities together and you can score an entire sentence, one token at a time. This identity is the mathematical reason "predict the next token" is a complete recipe for modelling language.
The probability of a whole sequence equals the product of each element's probability given everything before it — the identity that turns 'model language' into 'predict the next token'.
Open the concept page →
The expected value is the probability-weighted average outcome, and the variance measures how far outcomes typically spread around it.
Open the concept page →
Where probability leads
- Probability and Distributions
- Conditional Probability and Bayes' Theorem
- Probability of Sequences
- Language modeling
- Next-token prediction
- LLMs
2.3 · Which way is downhill?
Calculus
The problem: a model has millions of parameters and one number — the loss — that says how wrong it is. For each parameter we need to know: if I nudge you, does the loss go up or down, and how much?
That's a derivative. Collect one for every parameter and you have the gradient, an arrow pointing uphill. Shrink the nudge below until the secant becomes the tangent — then use it to step downhill.
Try it
Shrink a secant line until it becomes the tangent — the derivative — then use it to take a gradient-descent step downhill.
A derivative measures how much a function's output changes when you nudge its input, and the gradient collects those rates for every input at once — pointing in the direction of steepest increase.
Open the concept page →
A network is a long chain of functions — layer after layer — and the loss sits at the end. The chain rule says the sensitivity of the end to the beginning is the product of the sensitivities along the way. Walk that product backward from the loss and you have backpropagation, the algorithm that trains every neural network (Chapter 4).
The chain rule says the rate of change through a chain of functions is the product of the rates of change of each link — which is exactly how gradients flow backward through the layers of a network.
Open the concept page →
Where calculus leads
- Derivatives and Gradients
- The Chain Rule
- Backpropagation
- Neural-network training
2.4 · Learning as walking downhill
Optimization
The problem: "make the model better" isn't an instruction a computer can follow.
First make it precise: a loss function turns every prediction into a number, and learning becomes minimize the average loss. Then minimize it the only way that scales to billions of parameters: compute the gradient, take a small step against it, repeat. That's gradient descent, and nearly everything in modern AI is trained with some version of it.
Try it · toy model
Drop a point on a loss landscape and watch gradient descent, momentum and Adam race to the bottom. Push the learning rate until training diverges; add noise to see stochastic gradient descent.
Three things to notice in the playground. The learning rate is a knife-edge: too small and nothing happens, too large and training explodes. Ravines — steep one way, flat the other — make plain gradient descent zig-zag, which is exactly why momentum and Adam exist. And on the two-valley surface, where you start decides where you end.
A loss function turns 'how wrong is the model?' into a single number, so that learning becomes the problem of making that number small.
Open the concept page →
Gradient descent minimizes a loss by repeatedly nudging every parameter a small step in the direction that decreases the loss fastest — the negative gradient.
Open the concept page →
Stochastic gradient descent estimates the gradient from a small random batch of examples instead of the whole dataset, trading a little noise for enormous speed.
Open the concept page →
Momentum smooths gradient steps by keeping a running average of past gradients, and Adam adds a per-parameter step size based on how large each parameter's gradients have been.
Open the concept page →
2.5 · Not fooling yourself
Statistics
The problem: every number you measure — an accuracy, a benchmark score — comes from a finite sample, so it wobbles. A paper that reports 81.3% vs 80.9% on a small test set may be reporting noise.
Try it · toy model
Evaluate the same model on hundreds of random test sets and watch the measured accuracy wobble — why small benchmarks can't separate close models.
Every measured number — an accuracy, a benchmark score, a loss — is computed from a sample, so it carries uncertainty, and a difference smaller than that uncertainty isn't evidence of anything.
Open the concept page →
Chapter 3 builds on this with training, validation and test splits, overfitting and generalization — the statistics of learning rather than of measurement.
2.6 · Scoring a guess
Information theory
The problem: a model's prediction is a whole probability distribution. How do we score it against the one thing that actually happened?
Claude Shannon's 1948 answer starts with surprise: an outcome you gave probability surprises you by . Entropy is average surprise — how uncertain a distribution is. Cross-entropy is the surprise of what actually happened, under the model's predictions — and it is the loss every language model is trained to minimize.
Try it · toy model
Adjust a model's scores for the next word and watch cross-entropy loss and perplexity respond — the exact quantity language models are trained to minimize.
Entropy measures how uncertain a distribution is — the average surprise of its outcomes — and it sets the lower limit on how compactly you can encode them.
Open the concept page →
Cross-entropy loss is the negative log of the probability a model assigned to the correct answer — near zero when the model is confidently right, large when it is confidently wrong.
Open the concept page →
Two relatives complete the toolkit. Perplexity is cross-entropy made human-readable: roughly how many tokens the model is choosing between. KL divergence measures how far one distribution is from another; you'll meet it as a penalty in RLHF and as the target in distillation.
Perplexity is the exponential of the average cross-entropy per token — roughly, the number of options a language model is effectively choosing between at each step.
Open the concept page →
KL divergence measures how much one probability distribution differs from another — the extra surprise you pay for using the wrong distribution.
Open the concept page →
Putting it together
One training step, in six tools
Here is a single training step of a language model, told entirely with this chapter:
Linear algebra
Token vectors flow through stacks of matrix multiplications — shapes [batch × tokens × d_model].Probability
Softmax turns the final scores into a distribution over the next token, for every position, via the chain rule of probability.Information theory
Cross-entropy scores those distributions against the actual next tokens; its exponential is the perplexity you'll see reported.Calculus
The chain rule carries the gradient of that loss back to every one of the parameters.Optimization
AdamW nudges each parameter against its gradient, using a random mini-batch.Statistics
Validation loss on held-out text — with its sampling noise in mind — tells you whether it's really improving.
That loop, repeated hundreds of thousands of times over trillions of tokens, is how a modern LLM is pretrained. Everything in the rest of this site is detail on top of it.
Concepts in this chapter
Mark each one as you go. Must-know concepts are the core path.
- Conditional Probability and Bayes' TheoremConditional probability asks how likely something is given what you already know, and Bayes' theorem tells you how to flip it — from P(evidence | cause) to P(cause | evidence).Know wellMust know
- Probability of SequencesThe probability of a whole sequence equals the product of each element's probability given everything before it — the identity that turns 'model language' into 'predict the next token'.Know wellMust know
- The Chain RuleThe chain rule says the rate of change through a chain of functions is the product of the rates of change of each link — which is exactly how gradients flow backward through the layers of a network.Know wellMust know
- Cross-Entropy LossCross-entropy loss is the negative log of the probability a model assigned to the correct answer — near zero when the model is confidently right, large when it is confidently wrong.ImplementMust know
- Derivatives and GradientsA derivative measures how much a function's output changes when you nudge its input, and the gradient collects those rates for every input at once — pointing in the direction of steepest increase.Know wellMust know
- Dot ProductThe dot product multiplies two vectors entry by entry and adds the results, giving one number that is large when the vectors point the same way.ImplementMust know
- EntropyEntropy measures how uncertain a distribution is — the average surprise of its outcomes — and it sets the lower limit on how compactly you can encode them.Know wellMust know
- Expected Value and VarianceThe expected value is the probability-weighted average outcome, and the variance measures how far outcomes typically spread around it.Know wellMust know
- Gradient DescentGradient descent minimizes a loss by repeatedly nudging every parameter a small step in the direction that decreases the loss fastest — the negative gradient.ImplementMust know
- KL DivergenceKL divergence measures how much one probability distribution differs from another — the extra surprise you pay for using the wrong distribution.UnderstandMust know
- Loss FunctionsA loss function turns 'how wrong is the model?' into a single number, so that learning becomes the problem of making that number small.Know wellMust know
- Matrix MultiplicationMultiplying a vector by a matrix transforms it — every output number is a dot product of one matrix row with the input — and that is exactly what a neural-network layer does.ImplementMust know
- Momentum and AdamMomentum smooths gradient steps by keeping a running average of past gradients, and Adam adds a per-parameter step size based on how large each parameter's gradients have been.UnderstandMust know
- PerplexityPerplexity is the exponential of the average cross-entropy per token — roughly, the number of options a language model is effectively choosing between at each step.Know wellMust know
- Probability and DistributionsA probability distribution assigns a likelihood to every possible outcome — and nearly every modern model's output is a distribution rather than a single answer.Know wellMust know
- Sampling and UncertaintyEvery measured number — an accuracy, a benchmark score, a loss — is computed from a sample, so it carries uncertainty, and a difference smaller than that uncertainty isn't evidence of anything.UnderstandMust know
- SoftmaxSoftmax turns any list of scores into a probability distribution — positive numbers that sum to 1 — giving exponentially more weight to larger scores.ImplementMust know
- Stochastic Gradient Descent (SGD)Stochastic gradient descent estimates the gradient from a small random batch of examples instead of the whole dataset, trading a little noise for enormous speed.Know wellMust know
- Tensors and ShapesIn deep learning a tensor is just an n-dimensional array of numbers, and keeping track of its shape — batch × sequence × features — is most of the practical work of reading and writing models.Know wellMust know
- VectorsA vector is an ordered list of numbers, and in machine learning it is how every object — a house, a word, an image — becomes something a model can compute with.Know wellMust know
What do I actually need to remember?
- Everything becomes a vector; similarity is a dot product; a layer is a matrix multiplication (plus a nonlinearity).
- Shapes rule: [m × n] · [n × p] = [m × p]. Write shapes down when reading models.
- Models output probability distributions; softmax turns scores into one.
- A language model estimates P(next token | previous tokens); chaining those gives the probability of any text.
- Bayes: posterior ∝ likelihood × prior — base rates matter.
- The gradient points uphill; the chain rule multiplies local slopes, which is how backpropagation works.
- Training = minimize the average loss with (stochastic) gradient descent; the learning rate is the key knob; AdamW is the default.
- Every measured score has sampling noise: ±2·√(p(1−p)/n) is a quick sanity check.
- Cross-entropy = −log p(correct); it is the LLM training loss, and exp(loss) is perplexity.
- KL divergence measures how far one distribution is from another — a penalty (RLHF) or a target (distillation).
You do not need to memorize everything else. This list is the revision sheet.
Key papers
A Mathematical Theory of Communication
C. E. Shannon · 1948 · Bell System Technical Journal
Founded information theory: it defined entropy as a measure of uncertainty and showed how much any message can be compressed. Cross-entropy loss and perplexity come straight from here.
- Problem
- There was no precise way to measure information, or to say how efficiently it could be encoded and transmitted over a noisy channel.
- What was new
- Entropy H = −Σ p log p as the average information of a source, plus limits on compression and reliable communication. It even includes early statistical models of English text built from n-gram frequencies.
- Influenced
- On Information and Sufficiency
How to read it: Don't read it cover to cover. Part I (sections 1–7) contains entropy and the famous 'series of approximations to English' — a 1948 language model.
A Stochastic Approximation Method
Herbert Robbins, Sutton Monro · 1951 · The Annals of Mathematical Statistics
The mathematical ancestor of stochastic gradient descent: it showed that noisy, step-by-step updates can still converge to the right answer.
- Problem
- How do you find the root of a function when you can only observe noisy measurements of it?
- What was new
- An iterative procedure with decreasing step sizes that provably converges despite the noise.
How to read it: A pure mathematics paper. Knowing it exists — and that SGD's convergence story starts here — is enough for now.
On Information and Sufficiency
S. Kullback, R. A. Leibler · 1951 · The Annals of Mathematical Statistics
Introduced the divergence now called KL divergence — used in distillation, RLHF's penalty term, variational methods and more.
- Problem
- How do you measure how different one probability distribution is from another, in information-theoretic terms?
- What was new
- A directed measure of the information lost when one distribution is used to approximate another.
Adam: A Method for Stochastic Optimization
Diederik P. Kingma, Jimmy Ba · 2014 · ICLR 2015
The default optimizer (with its AdamW variant) for training neural networks, including essentially all Transformers.
- Problem
- Plain stochastic gradient descent needs careful per-problem tuning and handles noisy, badly-scaled gradients poorly.
- What was new
- Adapt each parameter's step size using running averages of the gradient and its square.
An overview of gradient descent optimization algorithms
Sebastian Ruder · 2016
The standard readable survey of SGD, momentum, RMSprop, Adam and friends — one paper that explains the whole optimizer family tree.
- Problem
- Optimizers were used as black boxes; their motivations and differences were scattered across many papers.
- What was new
- A single, intuitive comparison of gradient-descent variants, their update rules and when each helps.
How to read it: Very approachable. Read it after trying the Gradient Descent Playground.
Decoupled Weight Decay Regularization
Ilya Loshchilov, Frank Hutter · 2017 · ICLR 2019
Introduced AdamW, the variant of Adam used to train most modern Transformers and LLMs.
- Problem
- With Adam, the usual L2 regularization doesn't behave like true weight decay, hurting generalization.
- What was new
- Apply weight decay directly to the weights, separately ('decoupled') from Adam's adaptive gradient step.
Watch
3Blue1Brown
Vectors | Chapter 1, Essence of linear algebra
Builds the picture you need for everything else: a vector as an arrow, as a list of numbers, and why both views matter.
Covers: Vectors, vector addition, scaling.
3Blue1Brown
Linear transformations and matrices | Chapter 3, Essence of linear algebra
The single best explanation of why a matrix is a transformation of space — which is exactly what a neural-network layer does.
Covers: Matrices as functions that move vectors; matrix–vector multiplication.
3Blue1Brown
Matrix multiplication as composition | Chapter 4, Essence of linear algebra
Shows why multiplying matrices means applying one transformation after another — exactly what stacking neural-network layers does.
Covers: Matrix–matrix multiplication as composition of linear maps.
3Blue1Brown
Dot products and duality | Chapter 9, Essence of linear algebra
Explains why the dot product measures alignment, connecting the arithmetic to the geometry.
Covers: Dot product, projection, the link between dot products and linear maps.
3Blue1Brown
Bayes theorem, the geometry of changing beliefs
Turns Bayes from a formula into a picture of restricting your view to the evidence.
Covers: Prior, likelihood, posterior, and the area picture of Bayes theorem.
3Blue1Brown
The essence of calculus
Rebuilds the idea of a derivative from scratch, visually, without assuming you remember school calculus.
Covers: What derivatives and integrals are really about.
3Blue1Brown
Visualizing the chain rule and product rule | Chapter 4, Essence of calculus
The chain rule is the engine of backpropagation; this makes it feel obvious rather than memorized.
Covers: Chain rule and product rule as nudges propagating through functions.
3Blue1Brown
Gradient descent, how neural networks learn | Deep Learning Chapter 2
Connects the abstract idea of minimizing a function to how a real network learns to recognise digits.
Covers: Cost functions, gradients in many dimensions, gradient descent.
StatQuest with Josh Starmer
Gradient Descent, Step-by-Step
Works gradient descent out by hand on a tiny regression problem, one step at a time.
Covers: Loss, derivatives, step size, stochastic gradient descent.
StatQuest with Josh Starmer
Confidence Intervals, Clearly Explained!!!
Short and concrete — what a confidence interval actually tells you, via bootstrapping.
Covers: Bootstrapping, confidence intervals.
Aurélien Géron
A Short Introduction to Entropy, Cross-Entropy and KL-Divergence
Ten minutes that tie entropy, cross-entropy and KL divergence together — the three quantities behind language-model training.
Covers: Entropy as average surprise, cross-entropy as loss, KL as the gap between them.
3Blue1Brown
Solving Wordle using information theory
A playful but rigorous introduction to information and entropy as expected bits of surprise.
Covers: Information in bits, entropy, choosing actions that maximize expected information.
What came next?
Chapter 3
How can a program improve at a task by looking at examples instead of following rules?