← Back to the learning path

THE MATH OF AI / LAYER TWO

You already read the symbols.
Now build the mathematics.

The layer above taught you to translate an equation into a sentence. This one builds the subject underneath it, in the order the ideas actually depend on each other — starting from what a number is and ending at the questions nobody has answered yet.

01
Numbers & variablesWhat you are manipulating
02
Algebra & functionsHow to manipulate it
03
Linear algebraThe forward pass
04
CalculusHow training knows which way to go
05
ProbabilityWhat a prediction claims
06
OptimizationWhere all of it meets
BEFORE ANY OF THE DETAIL

A universe of mathematics. Find your constellation.

Explore 265 ideas across 16 constellations, from numbers and logic to geometry, dynamics and learning theory. Select a star to see its meaning, connections and available lessons.

The brighter stars have an AI connection listed here. Follow a guided path, search for a topic, or explore a branch. This is a curated atlas with an emphasis on AI foundations; its proportions do not measure how much of all mathematics AI uses.

FOLLOW A PATH

265 of 265 matching ideas

Skip to the selected idea ↓
THE MATHEMATICAL UNIVERSE16 constellations. Endless connections.
CountingZeroIntegersRational numbersReal numbersComplex numbersPrime numbersModular arithmeticExponentsLogarithmsOrders of magnitudeInfinity & cardinalityFloating pointVariableExpressionEquationRearrangingInequalitiesPolynomialsFactoringSystems of equationsSequences & seriesBinomial theoremGroupsRings & fieldsGalois theoryFunctionDomain & rangeCompositionInverse functionsLinear functionsExponential functionTrigonometric functionsSigmoid & tanhPiecewise linear & ReLUContinuityConvergenceReal analysisFourier analysisFunctional analysisPoint, line, planeDistance & metricPythagorasCoordinatesCircle & angleConvex setsHyperplanesHigh-dimensional geometryManifoldsCurvatureTopologyDifferential geometryNon-Euclidean geometrySymmetryVectorVector spaceDot productNormsMatrixMatrix multiplicationTransposeIdentity & inverseLinear independenceSpan & basisRankDeterminantColumn & null spaceOrthogonalityProjectionEigenvalues & eigenvectorsSingular value decompositionQR, LU & CholeskyPositive definitenessTraceTensors & broadcastingRate of changeLimitDerivativeDifferentiation rulesChain rulePartial derivativesGradientJacobianHessianTaylor seriesIntegralFundamental theoremMultiple integralsDifferential equationsStochastic differential equationsVector calculusCalculus of variationsAutomatic differentiationOutcome & eventProbability axiomsConditional probabilityIndependenceBayes' ruleRandom variableExpectationVariance & standard deviationCovarianceDistributionBernoulli & binomialCategoricalUniformGaussian (normal)PoissonExponential distributionBeta & DirichletJoint & marginalCentral limit theoremLaw of large numbersMarkov chainsMonte CarloMCMCStochastic processesMeasure-theoretic probabilityConcentration inequalitiesSample & populationMean, median, modeEstimatorBias & varianceMaximum likelihoodMAP estimationRegressionCorrelationGeneralisationCross-validationConfidence intervalsHypothesis testingBootstrapBayesian inferenceCausal inferenceThe bitEntropyCross-entropyKL divergenceMutual informationPerplexityCoding & compressionChannel capacityRate–distortionMinimum description lengthMinimum & maximumObjective functionGradient descentLearning rateStochastic gradient descentMomentumAdaptive methods (Adam)ConvexityLocal vs global minimaSaddle pointsNewton's methodRegularisationConstrained optimizationLagrange multipliersKKT conditionsLinear programmingOptimal transportLoss landscapeSetsLogicProofInductionCombinatoricsPermutations & combinationsGraphsTreesRecursionBoolean algebraRelations & ordersCountabilityComputabilityCategory theoryAlgorithmBig-O complexityNumerical precisionNumerical stabilityConditioningIterative solversVectorisation & parallelismPseudorandom numbersDiscretisationFixed-point iterationMatrix-free methodsDivisibility & the Euclidean algorithmDiophantine equationsChinese remainder theoremFinite fieldsElliptic curvesAnalytic number theoryQuantifiers: for all & existsContradiction & counterexamplesAxiomatic systemsIncompleteness theoremsType theoryFormal verificationPartial differential equationsInitial & boundary conditionsPhase space & trajectoriesLyapunov stabilityChaos & bifurcationsControl theoryBrownian motionFokker–Planck equationEmpirical & population riskPAC learningVC dimensionRademacher complexityPAC-Bayes boundsUniversal approximationKernels & feature spacesGaussian processesDouble descentBellman equationsPrincipal component analysisLeast squares & pseudoinverseChange of variablesConvolutionLaplace transformHomology & persistent homologyGroup representationsStandard errorCalibrationMultiple comparisonsJensen's inequalityEvidence lower bound (ELBO)Softmax & log-sum-expNumerical PDE methodsFast Fourier transformRMSPropAdamW & decoupled decayEarly stoppingOptimization dualityDynamic programmingGraph LaplacianChanceOdds & log-oddsData as a tableHistogramsSignal, message & noiseSurpriseChoosing the best optionTrade-offs & constraintsSteps & instructionsArrays, lists & tablesArrays & indexingDifference & changeChange over timeDifference equationsExamples & labelsTraining & held-out dataHypothesis classPairs & tuplesPigeonhole principleExtremal combinatoricsEven & oddPrime factorisationSolving a quadraticStructure-preserving mapsRandom matrix theoryLebesgue integrationp-adic numbers
100%

Select a star to explore. Zoom in, then drag to travel. Arrow keys move between matching stars. Rings mark study level; narrow the filters to name every matching star, or read them all in the topic index below.

IdeaAI connectionLesson availableBuilt onLeads to
  1. 0Starting ideas
  2. 1School foundations
  3. 2Core university
  4. 3Deeper connections
  5. 4Advanced study

Distance suggests a study level, not a difficulty score or a count of prerequisites. Stars in the background are decorative; the selectable stars are catalogue entries.

Calculus / Core university

Gradient

All the partial derivatives collected into a vector pointing steepest uphill.

In AI · ∇L(θ). The direction training walks away from.

In the world · A ball on a hillside rolls along the negative gradient.

Study this idea in this guide →
Browse the topic index · 265 matching ideas

Number & arithmetic12

Number theory10

Algebra16

Functions & analysis16

Geometry & topology15

Linear algebra25

Calculus19

Differential equations & dynamics12

Probability29

Statistics20

Information theory13

Optimization24

Learning theory13

Discrete mathematics11

Logic & foundations14

Computation & numerics16

READ IT OUTWARD

Study from the inside out

The inner region begins with familiar objects. Outer stars introduce more advanced connections. These are approximate study levels, not exact prerequisites; active research exists at every level.

READ IT AROUND

Branches are conveniences

A branch gives an idea a home on the map. Connections cross those boundaries: eigenvalues appear in linear algebra, probability, physics and optimization. Select a star to distinguish what it builds on from what it leads to.

FOLLOW THE CONNECTIONS

An application is a starting point

The AI filter highlights the applications recorded in this atlas. An unmarked star may still have applications elsewhere. A ring around a star means there is a lesson you can open from its detail card.

There is one more thing worth noticing before you scroll on. Trace any glowing dot back through what it is built on and you will land, within a few steps, in the middle of the circle — at counting, at sets, at the idea of a variable. There is no separate advanced mathematics that AI runs on. It is the ordinary material, composed further than usual.

No prior mathematics assumed15 chapters17 interactive labsOpen questions reviewed
CHAPTER 01

Start with what a number even is.

It is tempting to skip this. Do not. Every rounding error, every NaN in a training run, and every choice between float32 and bfloat16 is a consequence of the gap between the numbers mathematics describes and the numbers a machine can hold.

CLIMB THE LADDER

Every number system was invented because an equation had no answer.

Do not learn these as a list of definitions. Learn them as a sequence of failures: at each rung somebody asked a reasonable question, found the numbers they had could not answer it, and invented the ones that could.

RUNG 01 · NATURAL NUMBERS

Solvex + 3 = 5givesx = 2
What is in it
0, 1, 2, 3, 4, …
Why it was needed
Counting. How many sheep, how many days, how many examples in the batch.
Where it runs out
x + 5 = 3 has no answer here. You cannot take five from three and still be counting things.
Where you meet it in AI
Array indices, batch sizes, token counts, the number of layers. Anything you could point at and tally.

And then there is what your computer has instead

A weight is a real number in the mathematics and a floating-point approximation in the machine — a fixed budget of bits, so only finitely many values exist and everything else is rounded to the nearest one.

float64 · 52 mantissa bits0.10000000000000001What JavaScript and NumPy default to.
float32 · 23 mantissa bits0.10000000149011612The long-standing default for training.
bfloat16 · 7 mantissa bits0.099609375000000000Half the memory, same exponent range. Widely used in large-model training.

A tenth cannot be written exactly in binary, just as a third cannot be written exactly in decimal. Relative error at bfloat16: 0.391%.

0.1 + 0.20.30000000000000004
Is that 0.3?no

This is not a bug in JavaScript; every language using IEEE 754 agrees. It is why loss curves are compared with tolerances rather than equality, why the order of a summation can change its result, and why mixed-precision training needs care about which numbers stay wide.

Think it through: Why does it matter that ℝ has no gaps?

Calculus is built on limits, and a limit is the value a sequence is heading towards. If the line had holes in it, a sequence could head straight at a hole and have nowhere to land — the limit would not exist. Completeness is the property that guarantees the destination is always there.

That is the whole reason the reals are the setting for derivatives, and therefore for training. The floating-point numbers below are full of holes, which is why the machine can only ever approximate the thing the mathematics describes.

Two operations worth more than the rest

Exponents and logarithms carry more weight in this field than anything else at this level, and they are usually rushed. An exponent is repeated multiplication; a logarithm answers the reverse question, what power produces this number? Four rules follow, and each one earns its place later on this page.

RuleWhat it doesWhy AI needs it
log(ab) = log a + log bTurns multiplying into adding.Why the likelihood of a whole dataset becomes a sum you can differentiate.
log(a/b) = log a − log bTurns dividing into subtracting.KL divergence is an average of log(p/q), which is why it reads as a difference of surprises.
log(aⁿ) = n log aPulls an exponent down to the front.How a product over n tokens becomes an average, and how perplexity is defined.
log is monotonicBigger in, bigger out — always.Maximising the log-likelihood and maximising the likelihood give the same answer, so you may always take the log.

The first rule is the one that matters most. The probability of a whole dataset is a product of millions of small numbers, which underflows to zero in any real arithmetic and has a useless derivative besides. Take the log and the product becomes a sum: numerically stable, and differentiable term by term. Almost every loss function you will meet is a log for that reason alone.

CHAPTER 02

A letter is just a name.

Everything symbolic begins here. The moment you can write x instead of a particular number, you can state a rule that holds for every number at once — and that generality is the whole reason mathematics is worth the notation.

THE FIRST ABSTRACTION

A letter is a name for a number you have not fixed yet.

Three letters, three different jobs. Move each slider and watch which part of the picture responds.

y = wx + b
=1.4×2.0+-0.5=2.30
x = 2.0y = 2.30
w tilts the line. b slides it up and down. x only moves the dot along a line that is already fixed.
Constant
A value that never changes: 2, π, e. Write the number.
Variable
A named quantity that takes different values — here x, one value per example.
Parameter
Fixed while predicting, adjusted while training: w and b. Collectively written θ.
Index
A counter pointing at one item: xᵢ is the i-th input, x⁽ⁱ⁾ the i-th example.
Think it through: If w and b are variables too, why call them parameters?

Because of when they change. Within one prediction, x varies from example to example while w and b sit still — so the line is fixed and the input moves along it. During training it reverses: the data is held fixed and w and b are the things being adjusted. Same symbols, two different roles depending on which loop you are inside. Getting that straight removes most of the confusion in reading an ML paper.

The equation in that lab is y = wx + b, which is the same equation the layer above translated as “take the input, multiply it by its importance, add an adjustment.” It is also, exactly, one neuron. Everything from here is that expression scaled up and composed with itself.

CHAPTER 03

State the objects. Then state the claim.

Sets tell us what belongs. Logic tells us which statements follow. These ideas sit underneath array masks, probability events, graph structures and mathematical proofs.

SETS BECOME CONDITIONS IN CODE

Which observations pass the rule?

Universe U = {1, 2, 3, 4, 5, 6}. Let A contain the even numbers and B contain the numbers greater than 3. A complement is always relative to a stated universe.

1Outside A · Outside BExcluded
2In A · Outside BExcluded
3Outside A · Outside BExcluded
4In A · In BIncluded
5Outside A · In BExcluded
6In A · In BIncluded
Resulting set{4, 6}
Cardinality · number of elements2
Think it through: Is A ∩ B the same as A ∪ B?

Intersection requires both conditions, giving {4, 6}. Union requires at least one, giving {2, 4, 5, 6}. Logical OR includes the case where both conditions hold.

A claim needs its quantifiers

“For every input x, there exists a suitable model θ” permits a different model for each input. “There exists one model θ that works for every input x” asks for a single shared model. Switching ∀ and ∃ changes the problem.

Proof and counterexample

A proof establishes a claim from stated assumptions. One counterexample defeats a universal claim: x = −2 refutes “x² ≥ x implies x ≥ 0.” Checking many examples is useful evidence, but does not prove a statement about all real numbers.

Mathematical induction

Prove a base case, then show that truth at n implies truth at n + 1. For example, 1 + … + n = n(n + 1)/2 extends by adding n + 1 to both sides. This is a proof method, distinct from statistical induction from observations.

A graph connects objects without requiring geometry

A graph G = (V, E) has vertices V and edges E. A directed computational graph records which operations depend on which earlier values. A connected undirected graph without cycles is a tree; choosing a root gives it a hierarchy. A graph adjacency matrix and a neural weight matrix are both arrays, but their entries have different meanings.

Further study: MIT Mathematics for Computer Science ↗
CHAPTER 04

Algebra is not a bag of tricks.

It is a very short list of moves you are permitted to make, plus the judgement of which one gets you closer. Most people who believe they are bad at algebra were taught the tricks without the list.

THE ONLY RULE THERE IS

Algebra is a balance you are not allowed to tip.

Start from 3x + 4 = 19. Do the same thing to both sides and the scales stay level, whatever that thing is. Your goal is to reach the one arrangement that reads x = something.

left3x + 4
right19
Moves used—
Still balancedyes
Solvednot yet
Think it through: Every move keeps it balanced. So why do most of them get you nowhere?

Legal and useful are different tests. Any operation applied to both sides preserves the truth of the equation, so × 2 is perfectly valid — it just leaves you no closer to x on its own. Solving is a search through legal moves toward one particular shape: x alone on one side. That distinction reappears everywhere in this field. A gradient step is always legal; whether it helps depends on the step size. A model is always allowed to fit the training set; whether that helps depends on what you were trying to do.

Five moves. Everything else is a combination of them.
MoveWhy it is allowedWhat it is for
Add the same thing to both sidesThe two sides were equal; adding equally to each keeps them equal.Move a term across the equals sign.
Subtract the same thing from both sidesSame reason, running backwards.Strip away a bias term to isolate what multiplies x.
Multiply both sides by the same non-zero numberScaling both sides by the same factor preserves equality. Zero is excluded because it destroys information: 0 = 0 is true of everything.Clear a fraction.
Divide both sides by the same non-zero numberThe inverse of the move above.Turn 3x into x.
Replace anything with something equal to itSubstitution. If u = 2x + 1, then anywhere you see 2x + 1 you may write u.This one move is what makes the chain rule readable.

The three shapes worth recognising on sight

Linear · ax + b
A straight line. One neuron before its activation, and the whole of a layer in matrix form.
Quadratic · ax² + bx + c
A parabola, with exactly one turning point. Squared-error loss has this shape, which is why it is the example everyone uses.
Exponential · aᵇˣ
Growth proportional to current size. Softmax, learning-rate decay, and the scaling laws in the frontier chapter all live here.
CHAPTER 05

A function is a machine with one output per input.

That is the entire definition, and the “one” is the load-bearing word: feed in the same input twice and you must get the same answer. A neural network, all hundred billion parameters of it, is one function.

DOMAIN

What you may put in

√x refuses negatives over the reals; log x refuses zero and below; division refuses a zero denominator. Most NaN losses are a function being handed something outside its domain.

RANGE

What can come out

A sigmoid can only emit values in (0, 1), which is exactly why it can stand for a probability. Matching a range to a meaning is most of the reason to choose one activation over another.

COMPOSITION

Feeding one into the next

f(g(x)) means do g, then f. A deep network is composition repeated dozens of times, and the chain rule is how you differentiate through it.

Composition is the idea that makes depth mean something — and it comes with a warning. Compose two affine layers and you get another affine layer: W₂(W₁x + b₁) + b₂ = (W₂W₁)x + (W₂b₁ + b₂), which is one affine layer with different weights and bias. A hundred stacked linear layers are worth exactly one. Putting a nonlinear function between them is what buys you depth, and it is the only reason activation functions exist.

FamilyShapeWhere it shows up in AI
LinearA straight line through the spaceEvery layer's matrix multiply
PolynomialCurves with turning pointsSquared-error loss; Taylor approximations of everything else
ExponentialDoubling, then doubling againsoftmax, decay schedules, likelihoods
LogarithmThe exponential run backwardsCross-entropy, log-likelihood, perplexity
Sigmoid / tanhAn S, squashed into a fixed rangeGates, binary probabilities, older hidden layers
Piecewise linearStraight segments joined at cornersReLU — cheap, and non-linear enough to work
CHAPTER 06

Learn this before calculus.

People are told that calculus is the mathematics of machine learning. Linear algebra is the one you will read on day one — it is what every shape in your code means, and what a forward pass is written in. Calculus explains how training works; linear algebra explains what is being trained.

THE LANGUAGE OF THE FORWARD PASS

One number that answers “how much do these agree?”

A vector is an ordered list of numbers — and also an arrow. Both readings matter: the list is what the machine stores, the arrow is what lets you reason about it.

ab
The thick segment along a is b's shadow on a. Its length is the dot product divided by ‖a‖.
a · b7.58
‖a‖ ‖b‖7.91
cos θ0.958
b's shadow on a2.40

Nearly aligned: the dot product is close to its largest possible value.

Now stack them: that is a layer

Two neurons, three inputs. Each neuron has its own row of weights, and each output is one dot product plus a bias. Writing the rows as a matrix W turns both neurons into the single expression Wx + b.

NEURON 10.5×1.0 + -1×2.0 + 2×0.5 + 0.1= -0.400
NEURON 21.5×1.0 + 0.25×2.0 + -0.5×0.5 + -0.2= 1.550

Three multiplications and two additions per neuron. A real layer does the identical thing with matrices of millions of entries, which is the entire reason GPUs matter: not because the mathematics is hard, but because there is so much of it and all of it can run at once.

Think it through: Why is the dot product the operation that appears everywhere?

Because it is the cheapest honest answer to “how much of this is in that?”. It collapses two lists into a single number measuring alignment, it is linear in each argument, and on modern hardware thousands of them run at once. Attention scores are dot products. Cosine similarity is a dot product with the lengths divided out. A neuron is a dot product plus a bias. A matrix product is a grid of dot products. Learn this one operation properly and a surprising share of the notation in a paper stops being notation.

Four things a matrix is, all at once

A grid of numbers
The storage view. Shape (rows, columns), and the shapes must line up: (m × n) times (n × p) gives (m × p).
A stack of dot products waiting to happen
The computational view. Entry (i, j) of a product is row i of the first dotted with column j of the second.
A function that moves vectors
The geometric view. A matrix rotates, stretches, flattens or reflects space. This is the view that makes eigenvectors obvious.
A whole dataset
The practical view. One row per example, one column per feature. Shape (batch, features) is the first thing you will print when something breaks.

The vocabulary you will actually meet

These are the words a paper will use without explaining. None is difficult; each is a small fact about what a matrix does.

TermWhat it isWhere it shows up
Transpose · AᵀFlip the grid across its diagonal; rows become columns.For a linear operation, its backward pass multiplies by the transpose of the forward matrix. That is not a coincidence — it is what the chain rule requires.
Identity · IOnes down the diagonal, zeros elsewhere. It changes nothing.A residual block x + F(x) has Jacobian I + JF, giving an additional gradient route without guaranteeing stable gradients.
Inverse · A⁻¹For a square matrix, the inverse exists exactly when its columns are linearly independent.Solving least squares in closed form; whitening a covariance.
RankHow many genuinely independent directions the matrix has.LoRA freezes the big weight matrix and learns a low-rank update instead — fine-tuning gets cheap because the update turns out not to need full rank.
Determinant · det AThe factor by which volume is scaled. Zero means space gets flattened.The change-of-variables term in a normalising flow.
Span & basisEverything reachable by combining a set, and a smallest set that reaches it all.What a layer can represent at all; the axes PCA selects.
Trace · tr ASum of the diagonal, which also equals the sum of the eigenvalues.Appears throughout matrix calculus identities.

Length has more than one meaning

“How big is this vector” has several answers, and the choice is not cosmetic — it decides what a penalty does to your model.

NormIts unit ballWhat it does in AI
L1 · Σ|vᵢ|A diamondAn L1 penalty can favor exact zeros at an optimum. Sparsity depends on the objective, penalty strength and solver.
L2 · √Σvᵢ²A circleOrdinary length. Weight decay, gradient clipping, the distance behind cosine similarity.
L∞ · max|vᵢ|A squareWorst-case bounds; the radius used in adversarial robustness.
Frobenius · √ΣAᵢⱼ²L2, applied to a matrixHow far two weight matrices are apart; the size of an update.
THE DECOMPOSITION THAT EARNS ITS KEEP

Every matrix is a rotation, a stretch, and another rotation.

The singular value decomposition writes any matrix as a sum of simple rank-one pieces, ordered by how much they matter. Keep the first few and you keep most of the content. This gives an optimal low-rank approximation in Frobenius norm. PCA applies related geometry to centered data; LoRA learns low-rank weight updates rather than computing a truncated SVD.

Original · 16×16
Rebuilt from 4 singular directions
Numbers stored132 of 256
Content kept95.0%
Typical pixel error0.1231
True rank of this matrix7

The first singular value alone carries 53% of the content. Note what happens past rank 8: you are storing more numbers than the original had, so compression stops being a saving. Low rank saves storage only when k is small enough relative to the matrix dimensions; whether the approximation is useful depends on the singular-value spectrum and task.

Think it through: Why does this make fine-tuning cheap?

LoRA starts from an observation: the change a fine-tune makes to a big weight matrix is close to low-rank. So instead of learning all d×d numbers, you learn two thin matrices whose product has rank r, and add it on. With d = 4096 and r = 8 that is 65 thousand numbers instead of 17 million — the same trade you are making with the slider, applied to a weight update rather than a picture. It only works because real matrices, like the letter above, carry most of their content in their first few singular directions.

Two uses of the same geometry

Least squares

Choose w to minimize ‖Xw − y‖². The residual at an optimum is orthogonal to the column space: Xᵀ(Xw − y) = 0. A unique coefficient solution requires full column rank; the pseudoinverse selects a minimum-norm solution otherwise. In code, use a solver instead of forming an explicit inverse.

Principal component analysis

Center the feature columns, write X = UΣVᵀ, and project onto the first k columns of V. Their squared singular values, divided by n − 1, are sample covariance eigenvalues. PCA preserves maximal variance among rank-k orthogonal projections; large variance need not be useful predictive signal.

CHAPTER 07

Calculus is one idea, approached carefully.

It has a reputation for difficulty that comes almost entirely from how it is taught: rules first, meaning later, if ever. There is really one question — when this changes a little, how much does that change? — and everything else is technique for answering it without doing arithmetic by hand every time.

  1. STEP 01A rate you already understand

    Drive 120 km in 2 hours and your average speed is 60 km/h. You divided a change in position by a change in time. Every derivative you will ever meet is that same division.

    average rate = change in output ÷ change in input
  2. STEP 02The awkward question

    What is your speed at one instant? In an instant, no time passes and you travel no distance, so the division becomes 0 ÷ 0 — which is not a number. The question is good; the arithmetic is not ready for it.

    0 ÷ 0 is undefined
  3. STEP 03Do not divide by zero. Shrink instead.

    Measure over an interval of width h, which is a perfectly ordinary division. Then ask what the answer approaches as h gets smaller. Not what it is at h = 0 — what it is heading towards.

    (f(x + h) − f(x)) ÷ h
  4. STEP 04That destination is the derivative

    For f(x) = x², the quotient works out to exactly 2x + h. There is no mystery about where it is going: as h shrinks, it heads to 2x. That limit is the slope of the curve at that point.

    f′(x) = lim(h→0) (f(x + h) − f(x)) / h
  5. STEP 05Read it as sensitivity

    f′(x) = 2x says: nudge the input near x, and the output moves about 2x times as much. At x = 3 the output moves six times as fast as the input. That is the reading that matters for AI.

    f′(x) ≈ (output nudge) ÷ (input nudge)
  6. STEP 06Many inputs: hold the rest still

    A loss depends on millions of weights. Ask about one at a time: nudge w₇ and hold everything else fixed. That is a partial derivative. Collect one per weight and you have the gradient.

    ∇L = (∂L/∂w₁, ∂L/∂w₂, …, ∂L/∂wₙ)
  7. STEP 07The gradient points uphill

    The gradient vector aims in the direction of steepest increase, and its length says how steep. To reduce the loss, step the other way. That single sentence is gradient descent, and the whole of training.

    θ ← θ − α∇L(θ)
THE IDEA THE WHOLE FIELD RESTS ON

You cannot divide by zero. So creep up on it instead.

Average speed is easy: distance ÷ time. Speed at an instant looks impossible, because in an instant nothing happens — you get 0 ÷ 0, which is not a number. The move that rescues it is to refuse the impossible division and watch where the possible ones are heading.

Dashed: the secant through two points a distance h apart. Solid: the tangent, the line the secant is heading towards.
Secant slope (measured)4.000000
True slope (the limit)3.000000
Error1.00e+0
(f(x + h) − f(x)) / h
= (6.250000 − 2.250000) / 1e+0
= 4.000000

A wide gap measures the average slope across a whole stretch of curve, which is not yet the slope at a point. Shrink h.

DO THE ALGEBRA AND THE MYSTERY DISAPPEARS
((1.5+h)² − 1.5²) / h = 2·1.5 + h = 4.000000
f′(x) = 2x, so at x = 1.5 the exact answer is 3.000000

For x² the quotient simplifies to exactly 2x + h — no limit language needed to see where it is going. As h shrinks, the h on the end shrinks with it and 2x is what remains. That is the derivative, and every rule you will memorise later is this same calculation done once, in general, so you never have to repeat it.

The reading that matters for AI

f′(x) is a sensitivity. It says: nudge the input a little near x, and the output moves about f′(x) times as much. At x = 3 on the curve x², the output moves six times as fast as the input. Training asks exactly this question about a loss and a weight — if I nudge this number, how much does the error move, and in which direction? — a few hundred billion times per step.

Think it through: If the limit is exact, why does shrinking h too far make the answer worse?

Because two different things are happening at once. Mathematically, smaller h means a better estimate, all the way down. Numerically, f(x+h) and f(x) are two nearly identical floating-point numbers, and subtracting them throws away almost every significant digit you had — then you divide that wreckage by a tiny number, which magnifies it.

Watch the error fall to roughly 1e-8 and then climb again. The best h is a compromise between the two effects, near the square root of machine precision. This is why real frameworks do not estimate gradients this way: backpropagation applies the chain rule with floating-point arithmetic, and finite differences are kept for checking that the exact code is right.

The rules, and why you do not have to memorise them first

Every differentiation rule is the limit above, worked out once in general so nobody has to repeat it. Knowing that they are derived rather than decreed is worth more than knowing the list.

RuleStatementRead it as
Powerd/dx (xⁿ) = n·xⁿ⁻¹The one you will use constantly.
Sum(f + g)′ = f′ + g′Sensitivities add. This is why a loss summed over a batch has a gradient summed over the batch.
Product(fg)′ = f′g + fg′Vary one factor at a time, then add the two effects.
Chain(f∘g)′ = f′(g(x))·g′(x)The important one. Sensitivities multiply along a chain.
Exponentiald/dx (eˣ) = eˣA function that is its own rate of change — which is what makes e the natural base.
Logarithmd/dx (ln x) = 1/xWhy log-losses are pleasant to differentiate.
BACKPROPAGATION, WITHOUT THE NAME

A nudge travels through a chain, and each stage multiplies it.

Three stages in a row. Push a nudge of size δ into the front and measure what arrives at each stage. Nothing here is more advanced than multiplication — the point is what gets multiplied.

Product of the three rates36.1200
Measured overall rate36.1200
Exact dy/dx = 12(2x+1)36.0000
  1. STAGE 1u = 2x + 1
    1.0000→3.0000

    du/dx ≈ 2.0000 · exactly 2.0000

  2. STAGE 2v = u²
    3.0000→9.0000

    dv/du ≈ 6.0200 · exactly 6.0000

  3. STAGE 3y = 3v
    9.0000→27.0000

    dy/dv ≈ 3.0000 · exactly 3.0000

dy/dx = (dy/dv) × (dv/du) × (du/dx)
= 3.0000 × 6.0200 × 2.0000 = 36.1200

The overall sensitivity is the product of the local sensitivities. That is the entire chain rule, and it is why deep networks have the failure modes they do: multiply many numbers below one and the gradient vanishes before it reaches the early layers; multiply many above one and it explodes. Careful initialisation, normalisation layers and residual connections are all, at bottom, attempts to keep this product near one.

Think it through: Why compute the chain from the output backwards?

A network has one loss and millions of weights. Going forwards, you would trace a separate chain from every weight to the loss — millions of passes. Going backwards, you compute how the loss responds to the last layer, then reuse that to get the layer before it, and so on: every weight's gradient falls out of a single sweep. That reuse is the whole algorithm. Backpropagation is not a different rule from the chain rule; it is the chain rule evaluated in the order that shares the most work.

EVERY HARD FUNCTION, LOCALLY EASY

Near a point, anything smooth is a polynomial.

Pick a function and add terms one at a time. The polynomial grips the curve at zero first, then bends to match its slope, then its curvature, then creeps outward.

Solid: the real function. Dashed: the polynomial. The dot is where they are forced to agree.
Terms used4
Error part-way out0.55695
Order 1 isa gradient step
Order 2 isNewton's method
f(x) ≈ f(0) + f′(0)x + f″(0)x²/2! + …
+ 1x − 0.1667x^3

Converges everywhere, but you need more terms the further out you look.

Think it through: What has this got to do with training?

Everything, and it is usually left unsaid. Gradient descent replaces the loss near your current weights with its first-order Taylor approximation — a flat plane — and steps along it; the learning rate exists because that plane is only trustworthy nearby. Newton's method keeps the second-order term as well, so it models the curve as a bowl and can jump straight to its bottom, which is why it needs far fewer steps and why each one costs a Hessian. Every optimiser you will meet is a choice about how many Taylor terms you can afford.

More than one input, more than one output

Three words get used constantly and are rarely distinguished. They are the same derivative, arranged differently as the number of inputs and outputs grows.

ObjectShapeAnswersIn AI
Gradient ∇fA vector, one entry per inputHow one output responds to every inputWhat an optimiser steps along.
Jacobian JA matrix, outputs × inputsHow every output responds to every inputReverse-mode backpropagation propagates a vector–Jacobian product (equivalently Jᵀv in column notation), without building the full Jacobian.
Hessian HA matrix, inputs × inputsHow the gradient responds to every input — curvatureDescribes local curvature. For a positive-definite quadratic, its largest eigenvalue sets the plain-gradient-descent stability bound. Large models often use Hessian–vector products.

Curvature is worth dwelling on, because it explains a daily frustration. If the loss curves sharply in one direction and gently in another, a single learning rate cannot suit both: large enough to make progress along the flat direction, it oscillates along the sharp one. For a positive-definite quadratic, the ratio of the largest to smallest Hessian eigenvalue measures this conditioning. Neural losses need not have a positive-definite Hessian, and adaptive updates do not directly compute this curvature.

How derivatives are actually computed

Not by hand, not symbolically, and not by finite differences. A framework records every operation you perform into a computational graph, then applies the chain rule backwards through it — reverse-mode automatic differentiation. The results are exact to floating-point precision, and one backward sweep produces the gradient for every parameter at once.

SYMBOLIC

Manipulate the formula

Exact, and the expressions explode in size for anything deep. Fine for a textbook, hopeless for a network.

FINITE DIFFERENCES

Nudge and measure

What the lab above does. Simple, approximate, and needs one forward pass per parameter — useless at a billion of them, but still the standard way to check that a gradient is right.

AUTOMATIC

Chain rule on the graph

Exact, and one sweep covers every parameter. This is what PyTorch and JAX do, and why .backward() is a single line.

And the other half: integration

The derivative breaks a total into rates. The integral puts rates back into a total, and the fundamental theorem of calculus says the two operations undo each other — which is genuinely surprising, because “slope of a curve” and “area under a curve” have no obvious reason to be related.

You need far less of it than of differentiation. It matters where it defines something: an expectation E[X] = ∫ x p(x) dx is an integral, a continuous probability is an area under a density, and the evidence term in Bayes' rule is an integral that is usually impossible to compute — which is precisely why variational methods and sampling exist. You will need to recognise integrals constantly and evaluate them almost never.

CHAPTER 08

A prediction is a claim about uncertainty.

A probabilistic classifier can output a distribution over possible labels, and training grades how surprised that distribution was by the truth. Probability is what makes both halves of that sentence precise.

TURNING SCORES INTO A CLAIM

Why the loss is a logarithm, and not something friendlier.

A network's last layer emits raw scores, which can be any real numbers. Two steps turn them into a claim you can grade: softmax makes them a probability distribution, then cross-entropy measures how surprised that distribution is by the truth.

cat
78.6%
dog
17.5%
bird
3.9%
softmax(z)ᵢ = exp(zᵢ) / Σⱼ exp(zⱼ)
they sum to 1.000000 — a distribution, by construction

Now say which answer was actually correct. The loss looks only at the probability given to that one.

p = 1p = 0
−log p. Certain and right costs nothing; certain and wrong costs without bound.
Probability given to “cat”78.56%
Loss · −log p0.2413
In bits · −log₂ p0.3481

Roughly right but unconvinced. There is a real gradient here, which is where learning happens.

Read the loss in bits and it has a plain meaning: the number of yes/no questions' worth of surprise the model felt on seeing the right answer. Zero bits means it already knew.

Think it through: Why not just use “1 − p” as the loss? It is simpler.

Three reasons, and they all matter. First, a model that assigns probability 0.001 to the truth is far worse than one assigning 0.3, but 1 − p barely distinguishes them (0.999 against 0.7); −log p rates them 6.9 against 1.2. Confident and wrong is the failure worth punishing hardest, and only the log punishes it without limit.

Second, independent probabilities multiply, and logs turn multiplication into addition — so the loss over a whole dataset becomes a sum, which is what makes it differentiable and cheap to work with. Third, minimising −log p is exactly maximising likelihood, so the training objective inherits a century of statistics rather than being invented for the occasion.

RANDOM VARIABLE

A quantity that depends on chance

A random variable maps outcomes to values. Before observing the outcome we describe its distribution; after observing it we have a realization.

EXPECTATION

The long-run average

E[X] weights every possible value by its probability. Nearly every loss you will meet is an expectation estimated from a sample — which is exactly what a mini-batch is.

BAYES

Updating a belief with evidence

P(A|B) = P(B|A)P(A) / P(B). New evidence reweights what you already believed; it does not replace it.

Two ideas from information theory follow immediately and are worth meeting by name. Entropy is the average surprise of a distribution — how uncertain it is. Cross-entropy is the average surprise your predicted distribution feels when reality is drawn from the true one. Minimising it is the same as maximising likelihood, which is why the standard classification loss is not an arbitrary choice but the statistically principled one.

Spread, and how two quantities move together

The mean says where a distribution sits. Variance says how widely it spreads, and its square root, the standard deviation, puts that back in the original units. Covariance measures how two centered quantities vary together. Collect the pairwise covariances into a matrix: PCA diagonalizes it, and whitening transforms it toward identity when the required directions are nondegenerate. A multivariate Gaussian requires both a mean vector and a covariance matrix.

WHY THE BELL CURVE IS UNAVOIDABLE

Average enough of anything and you get the same shape.

Draw n numbers uniformly between 0 and 1 and average them. At n = 1 the histogram is flat, because that is what uniform means. Watch what happens as n grows — nothing about the underlying distribution has changed.

00.51
Bars: 4,000 measured averages. Dashed: the Gaussian the central limit theorem predicts, with no fitting.
Measured mean0.4922
Measured spread0.2863
Predicted √(1/12n)0.2887
Shapeflat
Var(X₁ + … + Xₙ) = n·Var(X) for independent terms
so Var(mean) = Var(X)/n, and the spread shrinks as 1/√n

Two things are happening, and they are worth separating. The spread narrows like 1/√n — that is the law of large numbers, and it is why a bigger mini-batch gives a steadier gradient. The shape becomes Gaussian regardless of what you started from — that is the central limit theorem, and it is why the bell curve describes measurement error, heights, and the sum of many small effects in almost any system you look at. Nobody chose the Gaussian for its convenience. It is what averaging does.

Think it through: Why does initialisation scale weights by 1 over the square root of the fan-in?

A neuron sums n terms, each roughly independent. Variances of independent things add, so the sum's variance is about n times one term's — meaning the signal grows by √n at every layer, and after thirty layers it has exploded or vanished. Scaling weight standard deviation proportionally to 1/√n controls this factor under the independence and activation assumptions; it does not guarantee preserved variance throughout training. Xavier and He initialisation are this argument with the activation function accounted for. It is one of the highest-value things on this page: a two-line variance calculation that decides whether a deep network trains at all.

The distributions worth knowing by name

A distribution is a shape of uncertainty. You do not need many.

NameSet byWhat it describesWhere it appears in AI
BernoullipOne flip of a biased coin.Binary classification; a dropout mask on one unit.
Categoricalp₁…p_kOne choice among k options.Exactly what softmax emits, and what next-token sampling draws from.
Uniforma, bEvery value in a range equally likely.Shuffling, random initialisation, the raw material of every sampler.
Gaussianμ, σ²The bell curve, fixed entirely by its mean and variance.Weight initialisation, VAE latents, and the noise a diffusion model adds and then learns to remove.
PoissonλCounts of rare events in a fixed window.Modelling arrival counts; some token-frequency models.
ExponentialλWaiting time to the next event, with no memory of how long you have waited.Survival and time-to-event models.
Beta / DirichletαDistributions over probabilities themselves.Bayesian priors; topic models; Dirichlet routing in some mixtures of experts.

Choosing parameters: maximum likelihood

Given data and a family of distributions, which member produced it? Maximum likelihood answers: pick the parameters maximizing the observed data's probability mass or density. Take the log — by that first rule from chapter one — and for independent observations the product over examples becomes a sum, and maximising it becomes minimising its negative. That negative log-likelihood is cross-entropy. The standard loss was not invented for neural networks; it is a century-old statistical principle arriving under a different name.

Add a prior belief about the parameters and you get MAP estimation instead — and a Gaussian prior on the weights turns out to be exactly an L2 penalty. This equivalence is between particular penalty terms and log priors; not every regularization method is simply MAP estimation.

THE MISSING HALF OF CROSS-ENTROPY

How far one distribution is from another.

Reality is fixed at P. Move the model's scores to change Q and watch three quantities that are usually taught as separate things turn out to be one equation.

cat
50%
45.1%
dog
25%
24.7%
bird
15%
16.6%
fish
10%
13.6%

P · what actually happens    Q · what the model predicts

ONE EQUATION, THREE FAMILIAR QUANTITIES
H(P, Q) = H(P) + KL(P ‖ Q)
1.2166 = 1.2080 + 0.0086
H(P) · irreducible1.2080
H(P,Q) · your loss1.2166
KL(P ‖ Q)0.0086
The other direction0.0091

This is the payoff of the previous lab. Cross-entropy — the loss you actually minimise — splits cleanly into the entropy of the data, which no model can do anything about, and the KL divergence, which is entirely the model's fault. Training can only ever drive the second term down. When a loss curve flattens above zero, that floor is H(P): the data was ambiguous and no parameters will fix it.

Think it through: If KL is a distance, why is it not symmetric?

Because it asks a one-sided question: how much extra surprise do you suffer by using Q when reality is P. Swapping the roles asks a different question, so it gets a different number — try the swap button and watch them diverge. It is not a metric, and calling it a distance is a convenient lie.

The asymmetry has teeth. Minimising KL(P‖Q) over the data punishes Q for assigning near-zero probability to anything that really happens, so Q spreads out to cover everything — that is maximum likelihood, and it is why generative models produce blurry averages. Minimising KL(Q‖P) instead punishes Q for putting mass where P has none, so Q collapses onto one mode and ignores the rest. Same two distributions, opposite failure modes, chosen by which way round you write it.

CHAPTER 09

A sample is evidence, with uncertainty.

Probability starts with a model and asks what observations it produces. Statistics uses observations to estimate quantities, compare explanations and assess uncertainty under assumptions.

Population and sample

The population is the group or distribution you want to describe. A sample is what you observed. Its mean x̄ = Σxᵢ/n summarizes its center; a median is a middle ordered value and is less sensitive to extreme observations. Neither summary repairs selection bias.

Estimator, bias and variance

An estimator is a rule applied to a sample. Its bias is E[θ̂] − θ; its variance describes changes across repeated samples. For squared error, MSE(θ̂) = bias² + variance. These expectations are over the sampling process.

SPREAD IS NOT THE SAME AS UNCERTAINTY

Watch the uncertainty in a mean shrink.

Assume IID normal observations with mean μ = 10 and known standard deviation σ = 2. Each line is an illustrative interval x̄ ± 1.96σ/√n from a simulated sample mean. We reuse 40 fixed standardized draws as n changes to isolate the effect of sample size.

51015
Vertical line: true mean. Amber intervals miss it. This small, fixed simulation need not have exactly 95% coverage.
Individual-observation SD2.000
Standard error of the mean0.400
Selected sample mean9.818
Selected 95% interval[9.034, 10.602]

Four times as many observations halves the standard error under these assumptions. With unknown σ, estimate it from the sample and use an appropriate method, such as a t interval for IID normal data. Dependence or a biased sample needs additional care.

Think it through: Does a 95% confidence interval assign a 95% probability to the fixed true mean?

In this frequentist model, the mean is fixed and the interval varies with the sample. The procedure covers the true mean in 95% of repeated independent samples under the model. A realized interval either covers it or does not.

Keep the target risk separate from the sample loss

Empirical risk: R̂(f) = (1/n) Σᵢ ℓ(f(xᵢ), yᵢ)
Population risk: R(f) = E₍X,Y₎[ℓ(f(X), Y)]

The first is measured on particular rows. The second is an expectation under the target distribution. Fitting the first does not automatically minimize the second. A representative held-out sample estimates future performance; distribution shift can break that connection.

ToolWhat it answersImportant condition
Confidence intervalUncertainty from a specified repeated-sampling procedureSampling and model assumptions determine coverage.
Hypothesis testHow unusual a statistic is under a specified null modelA p-value is not the probability that the null is true. Many comparisons require error control.
Cross-validationDevelopment performance across held-out foldsFit preprocessing inside each training fold. Use group or time splits when observations require them.
Final test setAn evaluation after selecting the procedureDo not use its outcomes to select parameters or stopping times.

Learning theory formalizes when empirical performance transfers to population performance. PAC learning specifies error and confidence; VC dimension measures the capacity of binary hypothesis classes. These are useful next destinations in the map, with assumptions that deserve as much attention as the formulas.

Further study: Understanding Machine Learning, chapters 2–6 ↗
CHAPTER 10

Everything so far, running in a loop.

Optimisation is where the previous chapters stop being separate subjects. A function built from matrix operations, differentiated by the chain rule, against a loss defined using probability — and then stepped downhill, over and over.

WHERE ALL OF IT MEETS

Read the slope, step against it, repeat.

The loss is L(w) = (w − 3)² + 1, its slope is L′(w) = 2(w − 3), and the rule is w ← w − α·L′(w). Everything in this chapter and the last two now runs at once: a function, its derivative, and a step size.

minimum at w = 3
Each dot is one step. The largest dot is where you end up.
Position after the steps2.8134
Loss there1.0348
Error multiplier |1 − 2α|0.60

Converging, approaching from one side.

For this loss the arithmetic is transparent: each step multiplies the distance from the minimum by exactly 1 − 2α. Below 0.5 you approach steadily; at 0.5 you arrive in one step; between 0.5 and 1 you overshoot but still shrink; at 1 you bounce forever; above 1 you leave. A learning rate is not a vague dial for how fast you learn — it is a concrete multiplier on your remaining error, and in a real network it is one of these per direction of curvature at once.

Think it through: Why not just solve for the minimum directly?

For this parabola you can: set the derivative to zero, get w = 3, done. That works because the function is simple and convex. A neural network's loss has hundreds of billions of parameters, no closed-form solution, and a landscape that is not bowl-shaped, so there is no equation to solve — only a direction to follow. Descent asks the cheap local question, which way is down from here?, and accepts that it will never prove it found the best point. That it works as well as it does is genuinely not fully explained, which is why it appears in the open-questions chapter below.

CONVEX

Bowl-shaped, and honest about it

For a convex objective on a convex domain, every local minimum is global. Least-squares linear regression and standard logistic negative log-likelihood are convex in their coefficients. Step sizes and regularity still matter for convergence.

NON-CONVEX

What deep learning actually is

A landscape of valleys, ridges and saddles. Typical neural-network objectives are non-convex. A local improvement does not certify global optimality; guarantees depend on specific assumptions about the objective and algorithm.

STOCHASTIC

Estimating the slope from a sample

The full empirical gradient averages the whole dataset. Uniform minibatch sampling estimates it at lower cost per update; sampling noise can help or hinder, depending on the problem. That is the S in SGD.

The optimiser zoo, in four lines

Each rule turns a gradient into an update. Plain SGD has no optimizer memory; momentum and adaptive methods keep state across steps.

OptimiserUpdateThe idea
SGDθ ← θ − α·gThe plain step. g is the gradient from one mini-batch.
Momentumv ← βv + g; θ ← θ − α·vAccumulate an exponentially weighted sum of past gradients. Consistent directions reinforce one another; β controls how fast history decays.
RMSProps ← βs + (1−β)g²; θ ← θ − α·g/(√s + ε)Divide by the recent size of each parameter's gradient, so every parameter gets a step scaled to its own terrain.
Adamboth, plus bias correctionMomentum on the gradient and RMSProp on its square, with a correction because both averages start at zero and are biased low early on.

Second-order methods use curvature as well as slope. A Newton step solves HΔ = −g. Fast local convergence requires conditions on smoothness, curvature and the starting point; an indefinite Hessian may not produce a descent direction. Quasi-Newton and matrix-free methods reduce the cost. Adam instead tracks gradient moments: it is not a Hessian approximation.

HOW A CONSTRAINT CHANGES THE FIT

A budget on the weights, and the shape of that budget.

Two weights. The ellipses are the loss, lowest at the dot in the middle. The shaded shape is your budget: the weights must stay inside it. The answer is wherever the smallest reachable ellipse touches the shape — and the shape of the budget decides where that touch happens.

unpenalised bestw₁w₂
The display searches 1,600 points on the boundary for an approximate constrained minimum, or uses the unconstrained optimum when it is feasible.
w₁1.200
w₂0.000
Loss at the solution2.076
A weight within 10⁻¹⁰ of zeroyes

The diamond has corners on the axes, and a corner is where a shrinking ellipse touches first. w₂ is not small — it is zero, and that feature has been removed from the model entirely.

L1 can select: the constraint has corners on the axes, which can favor sparse optima. L2 constrains overall length: it usually gives a dense solution. Effects on generalization require evaluation; neither shape guarantees that the resulting model will improve.

Think it through: So is weight decay the same as L2 regularisation?

For plain SGD without momentum, adding (λ/2)‖w‖² gives w ← (1 − αλ)w − αg. This equals decoupled shrinkage with the matching coefficient and learning rate. For Adam they come apart, because Adam divides by the recent gradient magnitude and that division also rescales the penalty term, so the effective decay differs per parameter. AdamW exists precisely to fix this: it applies the shrinkage separately, outside the adaptive scaling. That is the entire content of a paper people cite constantly, and it is a consequence of the algebra rather than a new idea.

CHAPTER 11

The computer evaluates an approximation.

Equivalent formulas can behave differently with finite precision. Separate the sensitivity of the mathematical problem from the numerical behavior of the method used to solve it.

Conditioning belongs to the problem

An ill-conditioned problem can amplify small input perturbations even when solved carefully. For an invertible matrix, κ₂(A) = σmax(A)/σmin(A). A nearly zero smallest singular value means some information is almost lost.

Stability belongs to the algorithm

A numerically stable method controls the effect of rounding. Subtracting nearly equal quantities can lose relative accuracy; exponentiating a large number can overflow. A stable algorithm cannot remove a problem's inherent ill-conditioning.

SAME FORMULA, DIFFERENT NUMERICAL BEHAVIOR

Add 1,000 to every score. What should change?

Start with scores [1, 2, 3]. Adding the same constant to all scores cannot change their softmax probabilities mathematically. Direct exponentiation can overflow in the browser's floating-point arithmetic.

ClassLogitDirect softmaxShifted softmax
110.0900310.090031
220.2447280.244728
330.6652410.665241
Stable probability sum1.000000
Log loss for class 3 · nats0.407606
Direct computationFinite
Think it through: Why does subtracting the maximum preserve softmax?

Every numerator and the denominator are multiplied by the same positive factor e⁻ᵐ, so the ratio is unchanged in exact arithmetic. The shifted exponents are at most zero, avoiding exponential overflow. Very small probabilities can still underflow; log-sum-exp lets us compute log losses directly.

Choose the computation as carefully as the formula

Further study: Mathematics for Machine Learning ↗
CHAPTER 12

Which combinations build which parts.

This is the chapter the rest of the guide exists for. No component of an AI system is built from one branch of mathematics; each one is a specific recipe, and seeing the recipes is what turns a pile of topics into a subject.

NOTHING HERE IS USED ALONE

No single branch of mathematics builds an AI system.

Look up a part of a system to see what it is made of, or look up a concept to see everywhere it turns up. The second direction is the more useful one once you start learning: it tells you what a week of study actually buys.

One neuron

Turns several inputs into one number.

VariablesMultiplicationAdditionFunctions

w₁x₁ + w₂x₂ + … + b is arithmetic with named quantities. Nothing more advanced is happening at this level.

Think it through: Which one should you learn first, then?

Linear algebra, without much doubt. It appears in more rows of this map than anything else, it is what the shapes in your code actually mean, and it is the language the forward pass is written in — you meet it on the first day and never stop. Calculus is second because it explains training rather than architecture, and probability third because it explains the loss and what a prediction claims. Optimisation is last because it is where the other three combine, and it is hard to appreciate before you have them.

The whole map at once.
PartWhat it doesMathematics it combines
One neuronTurns several inputs into one number.Variables · Multiplication · Addition · Functions
A layerRuns thousands of neurons at once.Linear algebra · Functions
A nonlinearityLets depth actually buy you something.Functions · Composition
A lossTurns “how wrong” into one number.Probability · Information theory · Logarithms
TrainingImproves the parameters.Calculus · Chain rule · Linear algebra · Optimization · Probability
AttentionLets a position read from other positions.Linear algebra · Dot products · Probability · Exponentials
Embeddings and retrievalMakes meaning comparable.Vectors · Inner products · Norms · Geometry
ConvolutionRecognises a pattern anywhere in an image.Linear algebra · Symmetry · Signal processing
Diffusion modelsGenerates an image from noise.Probability · Stochastic processes · Differential equations · Calculus
Numerical stabilityStops the arithmetic from ruining the model.Real analysis · Floating-point arithmetic · Logarithms
CHAPTER 13

None of this was invented for AI.

Every tool in this guide predates the field, most of them by centuries, and was built to answer a question about the physical world. That is not trivia — it is the strongest evidence that you are learning something durable rather than the notation of one passing technology.

The derivative

In AI: How much the loss moves when a weight moves.

In the world: Velocity is the derivative of position; acceleration is the derivative of velocity. Marginal cost in economics, reaction rate in chemistry, the slope of an epidemic curve — all the same operation.

Gradient descent

In AI: Step downhill on the loss surface until the model stops improving.

In the world: Water finds the valley. A soap film pulls itself to minimal area. Light takes the fastest path. Physics is full of systems that settle into a minimum, and the mathematics is the same mathematics.

Eigenvalues

In AI: Principal components, spectral norms, whether a recurrent network explodes or forgets.

In the world: The frequencies a bridge will resonate at, the stable modes of a vibrating drum, the ranking behind PageRank, the long-run state of a Markov chain.

The exponential and the log

In AI: Softmax, cross-entropy, log-likelihood, learning-rate decay.

In the world: Compound interest, radioactive half-life, bacterial growth, the decibel scale, the Richter scale. Wherever a quantity's rate of change is proportional to itself, e shows up.

Probability distributions

In AI: The model outputs a distribution; the loss is its surprise at the truth.

In the world: Statistical mechanics describes a gas by a distribution over states rather than by tracking every molecule. Insurance, polling, quality control and quantum mechanics all take that same step.

Convolution

In AI: The core operation of a vision network.

In the world: A camera blurring an image, a room adding echo to a sound, a moving average smoothing a noisy time series. All one operation: slide, multiply, add.

Optimal transport

In AI: Wasserstein distances between distributions; the transport view of diffusion models.

In the world: Its original question, posed in 1781, was how to move a pile of earth into a new shape with the least total effort. The logistics problem and the generative-model problem are the same problem.

There is a genuine puzzle underneath this, and it is worth sitting with rather than resolving too quickly. Mathematics developed for one purpose keeps turning out to describe something else entirely — the physicist Eugene Wigner called it the unreasonable effectiveness of mathematics in the natural sciences. Complex numbers were a bookkeeping device for solving cubics before they were the language of quantum mechanics. Non-Euclidean geometry was a curiosity before it was general relativity. Whatever you learn here has a strong track record of being useful somewhere you did not expect.

CHAPTER 14

Deeper paths and research questions.

Deep learning works considerably better than the theory explains. The gap between what practitioners can build and what mathematicians can prove is the honest state of the field, and it is wider than most introductions admit. Each area below lists the level it asks of you, because “open problem” is not the same as “inaccessible”.

Reviewed on . These are directions of sustained work rather than a snapshot of this month, and each links the paper that framed the question rather than the latest result — deliberately, because the framing outlives the leaderboard.

OPEN QUESTION 01

Why does an overparameterised network generalise at all?

A network with far more parameters than training examples can fit random labels perfectly — so classical capacity bounds cannot explain why the same network generalises on real labels. Test error can even fall again after the interpolation point, which the classical bias–variance picture does not predict.

Level: Entry: undergraduate probability and statistics. Frontier: high-dimensional probability, concentration inequalities, PAC-Bayes.

Zhang et al., Rethinking generalization ↗
OPEN QUESTION 02

What is gradient descent actually doing in a non-convex landscape?

There is no theorem promising that SGD finds a good minimum of a deep network's loss, yet it reliably does. Training also tends to drift to the boundary of stability rather than settling somewhere comfortable, which ordinary optimisation theory does not predict.

Level: Entry: multivariable calculus. Frontier: dynamical systems, stochastic differential equations, random matrix theory.

Cohen et al., Edge of Stability ↗
OPEN QUESTION 03

Which limits of a network can we actually solve exactly?

As width goes to infinity, training behaves like a fixed kernel method — the Neural Tangent Kernel — which is exactly solvable. It is also the wrong regime for explaining feature learning, so the open work is finding limits that stay tractable while keeping what matters.

Level: Entry: linear algebra and calculus. Frontier: kernel methods, functional analysis, tensor programs.

Jacot et al., Neural Tangent Kernel ↗
OPEN QUESTION 04

Why are scaling laws so clean, and what sets the exponents?

Loss falls as a power law in parameters, data and compute across many orders of magnitude, and those curves are accurate enough to plan training runs against. What mechanism produces a power law, and what determines its exponent, is not settled.

Level: Entry: logarithms and curve fitting. Frontier: statistical physics, approximation theory, information theory.

Hoffmann et al., Training compute-optimal LLMs ↗
OPEN QUESTION 05

What can a Transformer represent, and what does it learn in context?

Universal approximation says a large enough network can represent almost anything, which is nearly useless as engineering guidance — it says nothing about what training will find. Sharper work asks what attention can compute at a given depth and width, and why examples in a prompt change behaviour without changing a single weight.

Level: Entry: linear algebra and probability. Frontier: approximation theory, circuit complexity, learning theory.

von Oswald et al., Transformers learn in-context by gradient descent ↗
OPEN QUESTION 06

Can generative modelling be stated as transport between distributions?

Diffusion and flow-matching models are increasingly described as learning to move one probability distribution onto another along a path. That framing has produced faster samplers and cleaner objectives, and connects image generation to a problem first posed about moving piles of earth.

Level: Entry: probability and calculus. Frontier: optimal transport, measure theory, SDEs.

Song et al., Score-based generative modeling through SDEs ↗
OPEN QUESTION 07

How much does symmetry buy you?

Convolution works because a cat is a cat wherever it appears in the frame. Geometric deep learning takes that observation seriously and derives architectures from the symmetries of the data — grids, graphs, groups, manifolds — rather than discovering them by trial.

Level: Entry: linear algebra. Frontier: group and representation theory, differential geometry.

Bronstein et al., Geometric Deep Learning ↗
OPEN QUESTION 08

What are the features, mathematically?

Interpretability work increasingly treats a network's internal state as a sparse combination of directions, with more features packed in than there are dimensions to hold them. Recovering those directions is a dictionary-learning problem, and how far the linear picture holds is open.

Level: Entry: linear algebra. Frontier: sparse coding, compressed sensing, high-dimensional geometry.

Elhage et al., Toy Models of Superposition ↗
CHAPTER 15

A concrete order, and how to know you are ready.

The most common mistake is starting with calculus because that is what the field is said to require. The second is trying to be rigorous before anything means anything. Here is the order that works, with a test for each stage so you are not guessing.

  1. STEP 01Get comfortable rearranging

    Before anything else: move terms across an equals sign without hesitating, handle fractions, and read powers and logs as operations rather than decoration. This is the layer everything else silently assumes.

    You are ready to move on when: You can rearrange y = wx + b to solve for w without thinking about it.

  2. STEP 02Learn linear algebra before calculus

    This is the order people get wrong. The forward pass of every network is a matrix product; you will read shapes and dot products on day one and derivatives on day thirty. Vectors, dot products, matrix multiplication, and what a matrix does to space.

    You are ready to move on when: Given shapes (32, 784) and (784, 128), you can say what comes out and why.

  3. STEP 03Then the derivative, slowly

    One idea, approached properly: the derivative as sensitivity of output to input. Then the chain rule, then partial derivatives, then the gradient. Do not detour into integration techniques — they are beautiful and you do not need them yet.

    You are ready to move on when: You can explain why backpropagation is the chain rule, out loud, to someone else.

  4. STEP 04Add probability

    Random variables, distributions, expectation, independence, conditional probability and Bayes' rule, then likelihood and log-likelihood. This is what turns a score into a loss and a prediction into a claim about uncertainty.

    You are ready to move on when: You can say why cross-entropy loss is −log(p) and why the log belongs there.

  5. STEP 05Finish with optimisation

    Gradient descent, learning rates, momentum, why convexity matters and why deep learning does not have it. At this point the four earlier layers combine and the training loop stops being a black box.

    You are ready to move on when: You can explain what a learning rate that is too large actually does to the update.

  6. STEP 06Now go back and be rigorous

    Only once the machinery makes sense is it worth the formal treatment: proofs, epsilon–delta limits, measure-theoretic probability, convex analysis. Doing it in this order means the abstractions land on something you already understand.

    You are ready to move on when: You want the proof, rather than being told you need it.

Where to actually learn it

Full course

Harvard Stat 110

Blitzstein's probability course. Strong on building intuition for distributions.

Free book

Convex Optimization

Boyd and Vandenberghe. The reference once optimisation becomes the thing you care about.

Twenty terms, in plain language
Variable
A name for a quantity that can take different values.
Parameter
A value the model adjusts during training, such as a weight.
Function
A rule assigning exactly one output to each input.
Vector
An ordered list of numbers; also a point or an arrow in space.
Matrix
A rectangular grid of numbers; also a function that maps vectors to vectors.
Dot product
Multiply matching entries of two vectors and add the results. One number out.
Norm
The length of a vector, written ‖v‖.
Limit
The value an expression approaches as its input approaches something, whether or not it arrives.
Derivative
The rate at which an output changes as an input changes.
Partial derivative
The derivative with respect to one variable, holding the others fixed.
Gradient
The vector of partial derivatives; under Euclidean geometry it gives steepest first-order increase when nonzero.
Chain rule
The derivative of a composition is the product of the derivatives of its stages.
Integral
Accumulated total; the reverse of the derivative.
Random variable
A quantity whose value depends on the outcome of a random process.
Expectation
The long-run average value of a random variable, written E[X].
Likelihood
The data probability mass or density, considered as a function of the parameters.
Entropy
The average surprise of a distribution; how uncertain it is.
Convex
Bowl-shaped: every local minimum is the global one. Deep networks are not.
Floating point
The computer's finite approximation of a real number.
Eigenvector
A direction a matrix only stretches, without rotating it; the stretch factor is its eigenvalue.
NEXT FOUNDATION

Continue to Physics →

Take the mathematical language into the physical world.