Skip to content
Road to Intelligence

Part I · Foundations

Chapter 2

The Math Toolkit

Six small pieces of mathematics that do almost all the work in modern AI.

5 h core path20 concepts7 interactives

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:

ToolThe problem it solves in AI
Linear algebraHow do we represent data and transform it, millions of numbers at a time?
ProbabilityHow does a model express — and learn from — uncertainty?
CalculusWhich way should each parameter move to reduce the error?
OptimizationHow do we actually take those steps, reliably and fast?
StatisticsIs a measured improvement real, or noise?
Information theoryHow 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

  1. Vectors
  2. Dot Product
  3. Matrix Multiplication
  4. Softmax
  5. Cross-Entropy Loss
  6. Gradient Descent
  7. 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.

ConceptVectorsKnow wellMust know

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 →

ConceptDot ProductImplementMust know

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

Matrix as Transformation

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.

Know well8 min
ConceptMatrix MultiplicationImplementMust know

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 →

ConceptTensors and ShapesKnow wellMust know

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

  1. Vectors
  2. Dot Product
  3. Embeddings
  4. Attention
  5. Self-Attention

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.

ConceptProbability and DistributionsKnow wellMust know

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 →

ConceptSoftmaxImplementMust know

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 P(next token∣everything so far)P(\text{next token} \mid \text{everything so far}). And Bayes' theorem tells you how to reverse a condition — which is where intuition most often fails:

Try it

Bayes with 1,000 People

A rare condition, an imperfect test: see why a positive result can still mean you're probably fine — Bayes' theorem as counting.

Know well6 min
ConceptConditional Probability and Bayes' TheoremKnow wellMust know

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.

P(the cat sat)=P(the)⋅P(cat∣the)⋅P(sat∣the cat)P(\text{the cat sat}) = P(\text{the}) \cdot P(\text{cat} \mid \text{the}) \cdot P(\text{sat} \mid \text{the cat})
ConceptProbability of SequencesKnow wellMust know

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 →

ConceptExpected Value and VarianceKnow wellMust know

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

  1. Probability and Distributions
  2. Conditional Probability and Bayes' Theorem
  3. Probability of Sequences
  4. Language modeling
  5. Next-token prediction
  6. 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

Slopes and Steps

Shrink a secant line until it becomes the tangent — the derivative — then use it to take a gradient-descent step downhill.

Know well6 min
ConceptDerivatives and GradientsKnow wellMust know

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

ConceptThe Chain RuleKnow wellMust know

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

  1. Derivatives and Gradients
  2. The Chain Rule
  3. Backpropagation
  4. 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

Gradient Descent Playground

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.

Know well15 min

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.

ConceptLoss FunctionsKnow wellMust know

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 →

ConceptGradient DescentImplementMust know

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 →

ConceptStochastic Gradient Descent (SGD)Know wellMust know

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 →

ConceptMomentum and AdamUnderstandMust know

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

How Sure Is That Accuracy?

Evaluate the same model on hundreds of random test sets and watch the measured accuracy wobble — why small benchmarks can't separate close models.

Understand5 min
ConceptSampling and UncertaintyUnderstandMust know

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 pp surprises you by −log⁡p-\log p. 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

Confident and Wrong

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.

Know well6 min
ConceptEntropyKnow wellMust know

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 →

ConceptCross-Entropy LossImplementMust know

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.

ConceptPerplexityKnow wellMust know

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 →

ConceptKL DivergenceUnderstandMust know

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:

  1. Linear algebra

    Token vectors flow through stacks of matrix multiplications — shapes [batch × tokens × d_model].
  2. Probability

    Softmax turns the final scores into a distribution over the next token, for every position, via the chain rule of probability.
  3. Information theory

    Cross-entropy scores those distributions against the actual next tokens; its exponential is the perplexity you'll see reported.
  4. Calculus

    The chain rule carries the gradient of that loss back to every one of the parameters.
  5. Optimization

    AdamW nudges each parameter against its gradient, using a random mini-batch.
  6. 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.

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

Important

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.

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.

~2 h readdoi:10.1002/j.1538-7305.1948.tb01338.x✓ verified 2026-09-26
Optional

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.

~45 min readdoi:10.1214/aoms/1177729586✓ verified 2026-09-26
Optional

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.
~45 min readdoi:10.1214/aoms/1177729694✓ verified 2026-09-26
Essential

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.
~40 min readarXiv:1412.6980✓ verified 2026-09-26
Important

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.

~40 min readarXiv:1609.04747✓ verified 2026-09-26
Important

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.
~40 min readarXiv:1711.05101✓ verified 2026-09-26

Watch

17 min

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.

Must know
24 min

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.

Should know
31 min

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.

Should know

What came next?

Chapter 3

Machine Learning →

How can a program improve at a task by looking at examples instead of following rules?