Index Ai Academy
Foundation · Statistics and information

KL divergence: how far one distribution is from another

KL by hand, cross-entropy as entropy plus KL, why it isn't symmetric, and a soft-target loss.

About 35 minutes · Free lesson

What it covers6

Why it matters

The last lesson's model paid 1.75 bits of surprise per outcome on average, where the truth itself needs only 1.5. The extra quarter of a bit has a name: the KL divergence, how far the model's chances sit from the truth's. Cross-entropy is always the truth's own entropy plus this gap, and the data fixes the entropy, so when training lowers a model's cross-entropy, what really shrinks is the KL. It's a loss in its own right too. A small model learns to copy a large one by shrinking it, variational and diffusion models are trained on bounds built from it, and when a chat model is tuned on people's preferences, a KL term keeps it from drifting far from where it started.

What you'll be able to do

  • Compute KL(p ‖ q) by hand: each outcome's gap, log(p ÷ q), weighted by the truth's chance p and added
  • Show that cross-entropy is entropy plus KL, so lowering one lowers the other by the same amount
  • See that KL is 0 only when the two distributions match, and that KL(p ‖ q) and KL(q ‖ p) differ
  • Compute a soft-target loss, the KL a small model learns from a large one, in NumPy and with F.kl_div
Quick check
Have a guess before you start. A model's cross-entropy on some data is 1.75 bits, and the data's own entropy is 1.5 bits. Can more training bring the model's cross-entropy down to 1.2 bits?
  1. No: 1.5 bits is the floor
  2. Yes, but only with a bigger model
  3. Yes, given enough training steps
  4. Yes, if the data is shuffled first
Show the answer

No: 1.5 bits is the floor

The entropy is the smallest average surprise anyone can have about this data, even knowing the true chances exactly. Training can only close the 0.25 bits above it. That gap is the KL divergence, and this lesson takes it apart.

The math: the gap between two distributions

Purpose. Measure how far a model's chances q are from the truth's chances p, outcome by outcome, then in one number.

Take lesson 105's example again. The truth gives fire, tent and trail the chances p = (0.5, 0.25, 0.25), and a model guesses q = (0.25, 0.25, 0.5). For each outcome, set two surprises side by side: the model's, log₂(1/q), and the truth's own, log₂(1/p). Their difference is the outcome's gap: how much more the model is surprised than it needs to be. A log law turns the difference of two logs into one:

log⁡21qi−log⁡21pi=log⁡2piqi\log_2 \frac{1}{q_i} - \log_2 \frac{1}{p_i} = \log_2 \frac{p_i}{q_i}

In plain words: an outcome's gap is the log of how many times more chance the truth gives it than the model does.

Quick check
From lesson 25: log₂ 8 − log₂ 2 is the log₂ of what?
  1. 6, which is 8 − 2
  2. 3, which is log₂ 8
  3. 16, which is 8 × 2
  4. 4, which is 8 ÷ 2
Show the answer

4, which is 8 ÷ 2

Subtracting logs divides inside them: log₂ 8 − log₂ 2 = log₂(8 ÷ 2) = log₂ 4 = 2. The same law turns the model's surprise minus the truth's into log₂(p ÷ q).

Fire's gap: the model gives it 0.25 where the truth gives 0.5, so log₂(0.5 ÷ 0.25) = log₂ 2 = 1 bit. Giving an outcome half the chance it deserves costs one extra bit each time it happens. Tent's gap is log₂ 1 = 0: the model has it right. Trail's is log₂(0.25 ÷ 0.5) = −1. The model gives trail double its chance, so trail surprises the model less than it surprises the truth. Weight each gap by how often its outcome really happens, p, and add: that total is the KL divergence.

The picture. Step through it. The cells write each outcome's two surprises and the gap between them. The picture starts with p and q side by side, then draws each gap as a bar: above the line where the model gave too little chance, below it where it gave too much. The last step shrinks each bar by its chance p and adds them up.

Try it now

Then set the model's chances to the truth's, 0.5, 0.25, 0.25, and press Use these numbers: every gap is 0, and so is the KL.

Symbols and formula. For a truth p and a model q over the same outcomes:

KL(p ∥ q)=∑ipilog⁡2piqi=H(p,q)−H(p)≥0\text{KL}(p \,\|\, q) = \sum_i p_i \log_2 \frac{p_i}{q_i} = H(p, q) - H(p) \ge 0

In plain words: KL is each outcome's gap weighted by how often it really happens. It is also the cross-entropy minus the entropy, the extra surprise of using q when the truth is p, and it is never negative.

The flow's last step showed both forms: the gaps weighted by p give 0.25, and the same weights give the model's average surprise, 1.75, and the truth's, 1.5. So cross-entropy = entropy + KL. The data fixes the entropy; only the KL depends on the model. Lowering a model's cross-entropy and lowering its KL are the same job, step for step.

Zero only for a match. If q = p, every ratio is 1, every gap log₂ 1 = 0, and the KL is 0. Any other q gives a positive KL, though some of its gaps are negative, like trail's. Why don't they win?

Quick check
Trail's gap was −1 bit, yet KL is never negative. Why don't the negative gaps win?
  1. The log of a chance is always a positive number
  2. KL adds up the size of each gap, ignoring the sign
  3. Negative gaps are dropped before the weighted sum
  4. Negative gaps sit where p is below q, so p weighs them less
Show the answer

Negative gaps sit where p is below q, so p weighs them less

The model's chances add to 1, like the truth's, so any extra it gives one outcome it takes from another. A negative gap sits where q is above p, so its weight p is the smaller of the two chances; a positive gap sits where p is above q, so its weight is the bigger. Weighted by p, the positive gaps always come out ahead, or tie at 0 when q matches p.

Not symmetric. KL compares in one direction. The first distribution, p, supplies the weights, and it sits on top of every ratio. Swap the two and both change. The camp log shows rain on 1 night in 10, p = (0.9, 0.1) for dry and rain, and a lazy forecaster always says 50%, q = (0.5, 0.5). Then KL(p ‖ q) is 0.531 bits: what the 50% forecast costs on the camp's real nights. KL(q ‖ p) is 0.737: what the true chances would cost if nights really went 50/50. Different questions, different answers. That's why KL is called a divergence, not a distance.

Quick check
A colleague computes KL(q ‖ p) where the task asked for KL(p ‖ q). When does that give the same number?
  1. Only in special cases, like q = p; usually the two differ
  2. Never: they can't be equal
  3. Only when both are measured in nats
  4. Always: KL is a distance, the same both ways
Show the answer

Only in special cases, like q = p; usually the two differ

Swapping changes the weights and flips every ratio, so the two usually differ: 0.531 against 0.737 bits for the camp-log pair. They agree when q = p, both 0, and in a few lucky cases. The fire, tent and trail pair is one: swapped, it gives 0.25 × (−1) + 0.25 × 0 + 0.5 × 1 = 0.25, the same as before.

In your own words
In your own words: why is the KL divergence 0 when the model's chances match the truth's, and positive otherwise?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: KL in one line

Purpose. Compute KL with NumPy in one line, and check that it equals cross-entropy minus entropy.

The formula's Σ pᵢ × log₂(pᵢ ÷ qᵢ) is a dot product (lesson 50): p dotted with the log of the ratios, p / q taken entry by entry.

import numpy as np

p = np.array([0.5, 0.25, 0.25])
q = np.array([0.25, 0.25, 0.5])
kl = p @ np.log2(p / q)
H = p @ np.log2(1 / p)
CE = p @ np.log2(1 / q)
print(kl, CE - H, H + kl)

The one line gives 0.25 bits, the flow's answer. Cross-entropy minus entropy gives 0.25 too, and entropy plus KL gives back the cross-entropy, 1.75: the identity, in numbers.

Code flow. Here is that one line taken apart. Step through it and watch the boxes: the ratios, then the gaps, then each gap weighted by its chance, then the total. They are the flow's numbers.

Worked example

Worked example: the identity on three pairs

Check cross-entropy − entropy = KL on three pairs: the fire, tent and trail pair, and the camp log's rain forecast both ways round.

import numpy as np

def kl(p, q):
    return float(p @ np.log2(p / q))

def cross_entropy(p, q):
    return float(p @ np.log2(1 / q))

ps = [[0.5, 0.25, 0.25], [0.9, 0.1], [0.5, 0.5]]
qs = [[0.25, 0.25, 0.5], [0.5, 0.5], [0.9, 0.1]]
for i in range(3):
    p = np.array(ps[i])
    q = np.array(qs[i])
    gap = cross_entropy(p, q) - cross_entropy(p, p)
    print(round(kl(p, q), 3), round(gap, 3))
In the lesson you can change this and run it.

cross_entropy(p, p) is the entropy: a model that matches the truth. On every pair the two columns agree: 0.25, then 0.531, then 0.737. The last two pairs are the same forecast, swapped, so they also show the asymmetry: 0.531 bits one way and 0.737 the other. Neither number is wrong; they answer different questions. KL(p ‖ q) asks how much q costs when the truth is p.

Quick check
What does this print?
import numpy as np

p = np.array([0.9, 0.1])
q = np.array([0.5, 0.5])
print(round(float(q @ np.log2(q / p)), 3), round(float(p @ np.log2(p / q)), 3))
  1. 0.531 0.737
  2. 0.737 0.737
  3. 0.737 0.531
  4. 0.531 0.531
Show the answer

0.737 0.531

The first is KL(q ‖ p): q gives the weights and sits on top of the ratios, 0.737. The second is KL(p ‖ q), 0.531. Same two distributions, two answers.

A named mistake: a zero in q where p isn't zero. Watch the KL as the model's chance for trail shrinks toward 0, while trail still really happens a quarter of the time:

import numpy as np

p = np.array([0.5, 0.25, 0.25])
for tiny in [0.1, 0.01, 0.0001, 0.00000001]:
    q = np.array([0.75 - tiny, 0.25, tiny])
    print(tiny, round(float(p @ np.log2(p / q)), 3))

The KL climbs from 0.141 to 0.878, 2.53 and 5.851 bits, and it has no ceiling. At exactly 0 there is no answer at all: dividing by 0 inside the log is an error.

import math

print(0.25 * math.log2(0.25 / 0.0))

A model that says "impossible" about something that happens is infinitely wrong. That's one reason losses are built from log-chances, which lesson 104's F.log_softmax keeps finite, and why code that takes the log of chances often clips them first, with np.clip(q, 1e-12, 1). A zero in p is different: an outcome that never happens adds nothing, so skip it, as the last lesson's entropy did with p[p > 0].

Drill

KL in both directions

Fix kl(p, q) so it returns KL(p ‖ q) in bits and skips outcomes where p is 0. Then set forward and backward to KL(p ‖ q) and KL(q ‖ p) for the camp-log pair, rounded to 3 places, and hot to the KL of the one-hot truth from the model below, rounded to 4. The starter has two slips.

import numpy as np

def kl(p, q):
    return float(q @ np.log2(q / p))

p = np.array([0.9, 0.1])
q = np.array([0.5, 0.5])
forward = round(kl(p, q), 3)
backward = round(kl(q, p), 3)
hot = round(kl(np.array([0.0, 1.0, 0.0]), np.array([0.2, 0.7, 0.1])), 4)
print(forward, backward, hot)
In the lesson, your code is checked as you write it.
In your own words
For the camp-log forecast, KL(p ‖ q) is 0.531 bits and KL(q ‖ p) is 0.737. Judging the 50% forecaster against the camp's real weather, which would you report, and why?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI and ML: learning from a teacher's chances

Purpose. Use KL as a loss: a small model learns to copy a large model's softened chances.

A teacher and a student. The trail club has a large sign reader that is accurate but slow, and wants a small one that runs on a phone. Distillation trains the small model, the student, to copy the large one's chances, not just its answers. Take one photo of an arrow sign. The teacher scores it (4.0, 1.5, 0.5) for arrow, tent and trail; the student, so far, (2.0, 1.0, 1.0). Both are softened with a temperature of 2 from lesson 104, and the KL is taken in nats, with the natural log, as libraries do:

import numpy as np

def softmax(z, t):
    z = z / t
    e = np.exp(z - z.max())
    return e / e.sum()

teacher = np.array([4.0, 1.5, 0.5])
student = np.array([2.0, 1.0, 1.0])
print(softmax(teacher, 1.0).round(3).tolist())
p = softmax(teacher, 2.0)
q = softmax(student, 2.0)
print(p.round(3).tolist(), q.round(3).tolist())
print(round(float(p @ np.log(p / q)), 4))

At temperature 1 the teacher is 0.899 sure of arrow, and its other two chances are too small to say much. At 2 the same scores give 0.685, 0.196 and 0.119: an arrow, but one that looks far more like a tent than a trail sign. The student's softened chances, 0.452, 0.274 and 0.274, tie tent and trail. Its KL from the teacher is 0.1198 nats, and training pushes that toward 0: arrow up, and tent above trail.

Quick check
Why soften the teacher's chances with a temperature above 1 before the student copies them?
  1. It lets the student stop learning the arrow class
  2. It shows which wrong answers the teacher finds close
  3. Softmax needs a temperature above 1 to add up to 1
  4. It makes the teacher's top answer more accurate
Show the answer

It shows which wrong answers the teacher finds close

At temperature 1 the teacher's 0.899 for arrow drowns out the rest. Softened, tent's 0.196 against trail's 0.119 says what the teacher has learned: an arrow looks more like a tent than a trail sign. Copying that teaches the student more than the label alone.

In PyTorch. F.kl_div computes the KL, with two things to watch. Its first argument is the student's log-chances, log q, which F.log_softmax gives directly, and its second is the target chances, p: the reverse of the order KL(p ‖ q) is written in. reduction="sum" adds up the terms. The cell also checks the identity once more: F.cross_entropy takes target chances as well as right answers, and with the teacher's chances as targets, its cross-entropy minus the teacher's entropy is the KL.

import torch
import torch.nn.functional as F

teacher = torch.tensor([[4.0, 1.5, 0.5]])
student = torch.tensor([[2.0, 1.0, 1.0]])
p = F.softmax(teacher / 2, dim=-1)
log_q = F.log_softmax(student / 2, dim=-1)
print(round(F.kl_div(log_q, p, reduction="sum").item(), 4))
soft_ce = F.cross_entropy(student / 2, p)
entropy = -(p * torch.log(p)).sum()
print(round(soft_ce.item(), 4), round(entropy.item(), 4), round((soft_ce - entropy).item(), 4))

F.kl_div gives 0.1198, the NumPy cell's KL. The soft-target cross-entropy is 0.952 nats, the teacher's entropy 0.8321, and their difference 0.1198 again. The student can't change the teacher's entropy, so training on either loss moves it the same way. Real distillation also multiplies the softened loss by the temperature squared, 4 here: softening shrinks the slopes by about that much, and the factor puts them back on the scale of the ordinary loss that is usually trained alongside it.

Quick check
What does this print?
import torch
import torch.nn.functional as F

p = torch.tensor([0.5, 0.25, 0.25])
q = torch.tensor([0.25, 0.25, 0.5])
print(round(F.kl_div(torch.log(q), p, reduction="sum").item(), 4), round(F.kl_div(q, p, reduction="sum").item(), 4))
  1. 0.1733 -1.3522
  2. 0.25 0.25
  3. 0.25 -1.3522
  4. 0.1733 0.1733
Show the answer

0.1733 -1.3522

The math part's KL was 0.25 bits, and in nats that's 0.25 × 0.6931 = 0.1733. Given q itself instead of log q, F.kl_div still runs, but it returns a number that isn't a KL at all: a negative one, which a real KL never is.

Drill

A soft-target loss

Fix soft_loss(teacher, student, t) so it softens both sets of scores with the temperature t and returns KL(teacher's chances ‖ student's) in nats with F.kl_div. Then set cool and warm to the loss at t = 1 and t = 2, rounded to 4 places. The starter has two slips.

import torch
import torch.nn.functional as F

def soft_loss(teacher, student, t):
    p = F.softmax(teacher, dim=-1)
    q = F.softmax(student / t, dim=-1)
    return F.kl_div(q, p, reduction="sum").item()

teacher = torch.tensor([4.0, 1.5, 0.5])
student = torch.tensor([2.0, 1.0, 1.0])
cool = round(soft_loss(teacher, student, 1.0), 4)
warm = round(soft_loss(teacher, student, 2.0), 4)
print(cool, warm)
In the lesson, your code is checked as you write it.
In your own words
A student model reaches the same answers as its teacher on every photo, but its KL from the teacher's softened chances is still well above 0. What hasn't it learned yet?

Write a sentence or two, then compare it with a good answer in the lesson.

Goes deeper in

  • Distillation: training a small model to imitate a large one.
  • Cross-entropy from logits: the loss whose gap above entropy is a KL divergence.
  • RLHF: the KL term that keeps a tuned chat model near where it started.

Practice what you just read

  • 6 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

What does KL(p ‖ q) measure?

  1. The extra surprise of using q when the truth is p
  2. The chance that p and q pick the same outcome
  3. How many outcomes p and q disagree about
  4. The entropy of the model's chances q

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Foundation · about 96 hours of study

Foundation math

From whole numbers to the math inside a neural network: each idea by hand, in Python, and in AI 118 lessons All free
  1. Numbers and place value FreeWhat a digit's place is worth, the number line, and Python as a calculator that never tires.36 min
  2. Multiplying and dividing: groups FreeEqual groups, quotient and remainder, and cutting training data into batches.35 min
  3. Order of operations, and names for numbers FreeBrackets, powers, then multiply and divide, then add and subtract; variables hold numbers.36 min
  4. Numbers below zero FreeThe number line through zero, sign rules, distance from zero, and an error's direction and size.37 min
  5. Fractions: equal parts, equal fractions, adding FreePieces of a whole, equal fractions, and re-cutting to add; accuracy as a fraction.45 min
  6. Multiplying and dividing fractions FreeA share of a share, dividing by flipping, and why chances in a row get small.35 min
  7. Decimals and rounding FreeFractions in place value, rounding, and why 0.1 + 0.2 isn't exactly 0.3.36 min
  8. Percentages FreePer hundred, percent change, percentage points, and the accuracy and error rates of models.35 min
  9. Ratios, rates and proportion FreeSharing in a ratio, rates per unit, scaling, and splitting data 80/10/10.35 min
  10. Powers and roots FreeRepeated multiplying, the laws of exponents, square roots, and squared error.43 min
  11. Very big and very small numbers FreePowers of ten, e-notation like 3e-4, orders of magnitude, and a model's size in memory.36 min
  12. Bits, bytes and floats: how numbers are stored FreeBase 2, what n bits can hold, a float as sign, power and digits, and a tensor's memory.35 min
  13. Review: find the slip (numbers) FreeBroken calculations to fix, mixed practice from the whole module, and its formula sheet.34 min
  14. Letters for numbers FreeVariables, terms and like terms, substitution, and a model's formula as a Python function.41 min
  15. Expanding and factoring FreeBrackets as areas, pulling out common factors, and a squared error expanded into a bowl.41 min
  16. Solving equations: keep the balance FreeThe same move on both sides, undoing steps in reverse, and running a model's formula backward.41 min
  17. Rearranging a formula FreeMaking any letter the subject, round-trip checks, and planning a training run.36 min
  18. Inequalities and true-or-false FreeRanges, flipping the sign, if and elif, and the thresholds, clips and ReLU inside a model.42 min
  19. Functions: a rule from input to output Freef(x) notation, tables and graphs, domain and range, loops over lists, and loss as a function.42 min
  20. Chaining and undoing functions Freeg(f(x)), inverses that undo, scaling and unscaling, and a network as a chain.42 min
  21. Straight lines: slope and intercept FreeRise over run, the line through two points, and a model's weight and bias as slope and intercept.42 min
  22. Two equations, two unknowns FreeSubstitution and elimination, where lines cross, and why models are fitted, not solved.42 min
  23. Quadratics: bowls and their lowest point FreeRoots by factoring and by formula, the discriminant, the vertex, and the best weight of a model.42 min
  24. Exponentials: growth and decay FreeThe same factor each step, the number e, and decaying learning rates.43 min
  25. Logarithms: the power question FreeTo what power?, the laws of logs, and adding log-probabilities instead of multiplying.45 min
  26. Sequences and Σ FreeArithmetic and geometric sequences, Σ as a loop that adds, and mean squared error.40 min
  27. Weighted and moving averages FreeWeights that add to 1, a window average, the exponential moving average, and smoothing a loss curve.35 min
  28. Sets, and reading the symbols FreeSets, union and intersection, ℝⁿ and f : ℝⁿ → ℝᵐ, and reading a paper's first equation.41 min
  29. Review: find the slip (algebra) FreeBroken algebra and code to fix, mixed practice from the whole module, and its formula sheet.34 min
  30. Transposing step by step: undo in reverse order FreeA formula's layers, the opposite of each, peeling from the outside in, conditions, and round-trip checks.35 min
  31. Formulas with fractions: clear them first FreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
  32. When the letter appears twice: collect and factor FreeGathering the letter on one side, factoring it out, dividing by the bracket, and rearranging precision and F1.35 min
  33. Squares, roots and powers FreeSquare roots with ±, squaring to undo a root, cube and nth roots, and the √d inside attention.40 min
  34. When the letter is squared and plain: quadratics FreeRearranging into ax² + bx + c = 0, the formula, completing the square, and choosing the root that fits.35 min
  35. Letters in the power: exponentials and logarithms FreeTaking logs to bring a power down, exponentiating to free a letter, and the logit that undoes the sigmoid.40 min
  36. Rearranging inequalities: when the sign flips FreeThe four moves on an inequality, negatives and reciprocals that flip it, logs below 1, and sample sizes.35 min
  37. Inverse functions, lines and scaling FreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
  38. Sequences and sums: find n, a, d and r FreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
  39. Combining formulas: substitute and eliminate FreePutting one formula inside another to remove a letter, and sizing a training run from a time or money budget.35 min
  40. Review: rearrange anything (algebra) FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
  41. Coordinates and distance FreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
  42. Angles, degrees and radians FreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
  43. Sine and cosine FreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
  44. Waves: height, speed and shift FreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
  45. Review: find the slip (shapes and waves) FreeBroken geometry and code to fix, mixed practice from the module, and its formula sheet.29 min
  46. Angles, triangles and waves: rearranging with sin, cos and tan FreeSides and angles from SOH CAH TOA, principal values, arcs, polar coordinates, and a wave's time and period.45 min
  47. Vectors: lists of numbers that point FreeA list, a point and an arrow; components, dimension, NumPy arrays, and data as vectors.42 min
  48. Adding and scaling vectors FreeComponent-wise sums, scalar multiples, mixes, and the weight update w − ηg.43 min
  49. Length and distance: norms FreeL2, L1 and max norms, unit vectors, distance, and the norms inside losses and clipping.42 min
  50. The dot product FreeMultiply in pairs and add; a·a as squared length; a @ b; one neuron as a dot product.43 min
  51. Angle, cosine similarity and projection FreeDirection without length, perpendicular vectors, shadows, and search by meaning.45 min
  52. Perpendicular directions: bases and coordinates FreeOrthonormal directions, coordinates as dot products, rebuilding a vector, and taking a direction out.35 min
  53. Matrices: tables of numbers FreeRows, columns and entries; two-dimensional arrays and slices; a data set as a matrix.41 min
  54. Adding, scaling and transposing matrices FreeEntry-by-entry sums and scalings, the transpose, mean images, and tables turned around.36 min
  55. A matrix times a vector FreeEach row dotted with the vector, the size rule, A @ x, and a layer acting on one example.42 min
  56. Matrix multiplication FreeRow meets column, the size rule, order matters, and a batch through a layer: X W + b.45 min
  57. Identity, diagonal, triangular and symmetric FreeFour patterns and their jobs: rescaling, distance tables, and the causal mask.37 min
  58. Matrices as movements of space FreeStretches, flips, shears and rotations; columns as landing spots; chaining; a layer moving data.42 min
  59. Determinant and inverse FreeThe area factor ad − bc, singular matrices, undoing a matrix, and redundant features.42 min
  60. Solving systems by elimination FreeAugmented matrices, row moves, back-substitution, the three outcomes, and fitting weights.45 min
  61. Independence, span and rank FreeRedundant vectors, span, rank, outer products, and low-rank updates like LoRA.42 min
  62. Eigenvectors: directions that only stretch FreeAv = λv, checking candidates, np.linalg.eig, and the main direction of a data cloud.41 min
  63. SVD and PCA: the important directions first FreeA matrix as pieces by size, the best rank-k copy, compression, and PCA maps of data.45 min
  64. Tensors, shapes and broadcasting FreeAxes and shapes, reshape, axis=, broadcasting, and shapes through a small model.43 min
  65. One-hot vectors and lookup tables: embeddings FreeA one-hot row picks a table's row, a sentence looked up as vectors, and a score for every word.35 min
  66. Sliding dot products: convolution FreeA small pattern slid along a list and over a grid, output sizes, stride and padding, and shared weights.40 min
  67. Review: find the slip (vectors and matrices) FreeShape slips to fix, mixed practice from the module, and its formula sheet with shapes.36 min
  68. Vector equations: rearranging with arrows FreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
  69. Matrix equations: multiply by the inverse, on the correct side FreeNo dividing by a matrix: inverses from the left or right, order, transposes, and the normal equations.40 min
  70. Rates of change FreeChange over change, secants, rates from readings with np.diff, and reading a loss curve.41 min
  71. Limits: what a value heads toward FreeApproaching from both sides, holes, corners and jumps, epsilon, and judging activations.37 min
  72. The derivative: slope at a point FreeShrinking secants, f′(x) and dy/dx, Δy ≈ f′Δx, and which way a weight should move.45 min
  73. Derivative rules FreeConstants, powers, multiples, sums, eˣ and ln x, checked numerically, and a squared error's slope.41 min
  74. The product rule and the chain rule FreeProducts and chains of functions, forward then backward, and one neuron's dL/dw.45 min
  75. Lowest points and curvature Freef′ = 0, the second-derivative test, tables, local and global minima, and convex losses.43 min
  76. Standing in for a curve near a point FreeTangent lines, a curvature term, growing error, and why learning rates must be small.37 min
  77. Partial derivatives FreeOne input at a time, ∂, nudging in Python, and the two slopes of a line's loss.41 min
  78. The gradient FreeAll the slopes as a vector, steepest climb and descent, a numerical gradient, and the loss gradient.42 min
  79. Gradient descent FreeStepping against the gradient, the learning rate, a training loop, and fitting a line.45 min
  80. Faster descent: momentum and Adam FreeMomentum and Adam by hand, the bias correction, and three optimizers down one narrow valley.40 min
  81. The chain rule with many paths: backpropagation by hand FreeGraphs, multiply along paths and add across them, gradient checks, and a 2-2-1 network by hand.45 min
  82. Automatic differentiation: how PyTorch finds every slope FreeA tape of steps walked backward, and requires_grad, backward(), .grad, zero_grad() and no_grad().40 min
  83. Jacobians and Hessians FreeSlopes of vector functions, a layer's Jacobian, second partials, and bowls, domes and saddles.42 min
  84. Integrals: adding up thin slices FreeStrip and trapezoid sums, summing undoes differencing, probability as area, and AUC.43 min
  85. Review: find the slip (calculus) FreeCalculus slips to fix, mixed practice from the module, and its formula sheet.36 min
  86. Rearranging in calculus: slopes, steps and constants FreeSetting a slope to zero, Newton's step, the chain rule turned around, constants from a point, and learning rates.45 min
  87. Counting: choices, orders and groups FreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
  88. Probability: from counts to chances FreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
  89. Combining events: and, or, independent FreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
  90. Conditional probability and Bayes' rule FreeConditionals from tables, why P(A | B) isn't P(B | A), Bayes' rule, and precision and recall.45 min
  91. Random variables and distributions FreeUncertain numbers, the probability of a range, sampling by slices, and sampling versus argmax.42 min
  92. Expected value, variance and standard deviation FreeProbability-weighted averages, spread in the data's own units, and a training loss as an expected value.42 min
  93. Bernoulli, binomial, uniform and normal FreeYes-or-no trials, counts of yeses, the 68-95-99.7 rule, z-scores, and an accuracy's error bar.45 min
  94. Two variables at once: covariance and correlation FreeJoint tables and marginals, covariance, correlation, the covariance matrix, and features that carry the same information.45 min
  95. Review: find the slip (probability) FreeProbability slips to fix, mixed practice from the module, and its formula sheet.36 min
  96. Probability formulas: solve for the missing chance FreeConditionals, Bayes' rule for the prior, the or rule, expected values, variance, and z-scores turned around.45 min
  97. Describing data: center, spread and scale FreeMean, median and mode, variance and standard deviation, percentiles, outliers, and standardizing features.42 min
  98. Samples, the law of large numbers and the central limit theorem FreeSamples and populations, the standard error σ/√n, the bell of averages, and error bars on test scores.43 min
  99. Is the difference real? Comparing two models FreePaired differences, a bootstrap interval, what a p-value is and isn't, and why many tries make lucky wins.40 min
  100. Maximum likelihood FreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
  101. Linear regression: the best line FreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
  102. Logistic regression: a line that answers yes or no FreeThe sigmoid, the log loss, its slope p − y, a training loop, and choosing a threshold.45 min
  103. Scoring a classifier: confusion table, precision, recall, F1 FreeThe four cells, accuracy, precision, recall and F1, and what moving a threshold does to each.35 min
  104. Softmax: scores into probabilities FreeExponentiate and share out, shifting and temperature, the safe softmax, and a classifier's last step.43 min
  105. Surprise, entropy and cross-entropy FreeSurprise in bits, entropy, cross-entropy and KL divergence, perplexity, and a language model's loss.45 min
  106. KL divergence: how far one distribution is from another FreeKL by hand, cross-entropy as entropy plus KL, why it isn't symmetric, and a soft-target loss.35 min
  107. Review: find the slip (statistics and information) FreeStatistics slips to fix, mixed practice from the module, and its formula sheet.38 min
  108. Statistics and information: n, z, logits and bits FreeSample sizes from error bars, inputs from probabilities, logit gaps from softmax, and chances from bits and losses.40 min
  109. One neuron, start to finish FreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
  110. A layer and a small network as matrices FreeTwo layers on a batch, the shape of every matrix, adding a hidden unit, and XOR solved.45 min
  111. Training a small network FreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
  112. The same network in PyTorch Freenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
  113. Attention as matrix math FreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
  114. Residual connections and layer norm FreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
  115. A transformer block, start to finish FreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
  116. Planning a model: rearranging the formulas of a working network FreeLayer widths from parameter counts, sizes from memory and compute, the attention scale, and a training plan.40 min
  117. Final test: transpose any formula FreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
  118. Capstone: a sign reader from the formulas FreeBuild, train and test a trail-sign classifier with NumPy alone, and report its accuracy with an error bar.45 min
Part of a free course 118 lessons

The Foundation Math For Ai & ML: from arithmetic to attention

Learn the math behind AI from arithmetic up: numbers, algebra, vectors and matrices, calculus, probability and statistics, each shown as numbers moving and checked in Python, ending with a network you build and train from the formulas.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write