Index Ai Academy
Foundation · Numbers

Bits, bytes and floats: how numbers are stored

Base 2, what n bits can hold, a float as sign, power and digits, and a tensor's memory.

About 35 minutes · Free lesson

What it covers6

Why it matters

Inside a computer, every number is a row of tiny switches, each on or off. How many switches a number gets decides how big it can be and how exact. That's why 0.1 + 0.2 isn't quite 0.3, why a model's memory is its number of weights times 4 bytes, and why engineers run models in "half precision" or squeeze them into 8 bits. This lesson opens the box: counting in twos, then floats, then what it all costs a model.

What you'll be able to do

  • Read and write whole numbers in base 2, and say how many values n bits can hold (2ⁿ)
  • Explain a float as a sign, a power of two and a fixed number of binary digits, and why that limits precision
  • Use bin() and int(text, 2) in Python, and see why testing floats with == goes wrong
  • Work out a model's memory from its count of numbers and the bytes each takes, and the error 8-bit rounding adds
Quick check
Have a guess before you start. A byte is 8 switches in a row, each on or off. How many different on-off patterns can it show?
  1. 256
  2. 16
  3. 8
  4. 255
Show the answer

256

One switch gives 2 patterns. Each switch you add doubles them, because every old pattern can go on with the new switch on or off: 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 = 256.

The math: counting in twos

Purpose. Write numbers with only two digits, 0 and 1, and see what a fixed number of them can hold.

In base ten, from lesson 1, each place is worth ten times the place on its right: ones, tens, hundreds. Base two works the same way with twos. Each place is worth twice the place on its right: 1, 2, 4, 8, 16 and so on, the powers of two from lesson 10. Its only digits are 0 and 1, so each place is either used or not. A binary digit is called a bit.

11012=1×8+1×4+0×2+1×1=131101_2 = 1 \times 8 + 1 \times 4 + 0 \times 2 + 1 \times 1 = 13

In plain words: label the places from the right 1, 2, 4, 8. Add up the worth of every place that holds a 1. The small 2 says the digits are in base 2.

Quick check
From an earlier lesson: in 4,072, what is the 7 worth?
  1. 70
  2. 7,000
  3. 700
  4. 7
Show the answer

70

The 7 sits in the tens place, so it's worth 7 × 10 = 70. Base 2 reads places the same way, with 1, 2, 4, 8 where base ten has 1, 10, 100, 1,000.

From a number to bits. To write 13 in base 2, start at the biggest place that fits, 8, and work down. Each place gets a 1 if its worth fits into what's left, and a 0 if it doesn't; a 1 takes that worth out. The picture shows 13 as squares: each step pulls a row of 8, 4, 2 or 1 out of what's left, and the strip on top fills in that place's bit.

Try it now

Then type 200 in the number box and press Use these numbers: 200 needs eight places, a whole byte.

How much n bits can hold. One bit has two patterns, 0 and 1. Two bits have four: 00, 01, 10 and 11. Every bit you add doubles the count, because each old pattern can carry on with a 0 or with a 1.

values in n bits=2nlargest whole number=2n−1\text{values in } n \text{ bits} = 2^n \qquad \text{largest whole number} = 2^n - 1

In plain words: n bits make 2ⁿ patterns. Counting from 0, the biggest number they can write is one less.

Eight bits make a byte: 2⁸ = 256 patterns, the whole numbers 0 to 255. Computer memory is counted in bytes, and the prefixes from lesson 11 scale them: a megabyte is 10⁶ bytes, and a gigabyte is 10⁹.

Quick check
How many different values can 4 bits hold?
  1. 4
  2. 16
  3. 8
  4. 15
Show the answer

16

2⁴ = 2 × 2 × 2 × 2 = 16 patterns, from 0000 to 1111: the numbers 0 to 15.

Floats: scientific notation in base 2. Whole numbers are simple: bits in places. A number like 3.75 or 0.1 is stored as a float, short for floating point. It's the scientific notation of lesson 11, with 2 in place of 10:

x=± 1.d1d2d3…×2kx = \pm\, 1.d_1 d_2 d_3 \ldots \times 2^{k}

In plain words: a sign, a power of two, and a fixed number of binary digits starting with 1. The power says where the point really goes, so the point "floats".

After the point, base 2 places keep halving: ½, ¼, ⅛. So 3.75 = 2 + 1 + ½ + ¼ is 11.11 in base 2. Moving the point one place left halves it, and × 2¹ doubles it back: 3.75 = 1.111 × 2¹. Check it: 1.111 in base 2 is 1 + ½ + ¼ + ⅛ = 1.875, and 1.875 × 2 = 3.75.

A float32 spends its 32 bits as 1 for the sign, 8 for the power and 23 for the digits after the point. The leading 1 is always there, so it isn't stored, and float32 keeps 24 digits in all. A float16 has 1, 5 and 10 bits, so it keeps 11 digits. The picture draws both at the same scale.

Why 0.1 can't be stored exactly. In base ten, 1/3 never ends: 0.333… In base two, 1/10 never ends either. Doubling moves the point one place right, so each doubling brings the next digit in front of the point. Double 0.1 again and again: 0.2, 0.4 and 0.8 stay under 1, so the digits are 0, 0, 0. Then 1.6 passes 1: a digit 1, and taking the 1 off leaves 0.6. That doubles to 1.2: another 1, leaving 0.2, the value after the first doubling. So the same digits come round forever: 0.1 is 0.000110011001100… in base 2, with 0011 repeating. A float keeps only its 24 or 11 digits and rounds off the rest, so the stored 0.1 is a hair off. That's the crumb behind 0.1 + 0.2 in lesson 7.

Fixed digits, fixed precision. 24 binary digits are worth about 7 decimal digits, and 11 are worth about 3. Whole numbers are exact only while they fit in the digits: float32 holds every whole number up to 2²⁴ = 16,777,216, and float16 only up to 2¹¹ = 2,048. Past that, neighboring floats are more than 1 apart. The Python part checks each of these numbers.

Quick check
Why can't a float store 0.1 exactly?
  1. Its base 2 digits never end
  2. Its sign bit gets in the way
  3. Floats hold whole numbers only
  4. 0.1 is too small for 32 bits
Show the answer

Its base 2 digits never end

1/10 in base 2 is 0.000110011…, with 0011 repeating forever, like 1/3 in base ten. A float keeps a fixed number of digits, so it rounds, and the stored value is a hair off 0.1.

Quick check
float32 keeps 24 binary digits. Which is the first whole number it can't hold exactly?
  1. 2³² + 1
  2. 2²⁴
  3. 2²⁴ + 1
  4. 2²³ + 1
Show the answer

2²⁴ + 1

2²⁴ is a 1 followed by 24 zeros: one digit times a power of two, so it fits. 2²⁴ + 1 is a 1, 23 zeros and a 1, which is 25 digits, one too many, so it's rounded to a neighbor.

In your own words
In your own words: why does each extra bit double how many values fit, and what does a float's fixed number of digits cost it?

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

In Python: bits, and the crumbs in a float

Purpose. Ask Python for any number's bits, and watch a float's rounding happen.

bin(n) writes a whole number in base 2, and int(text, 2) reads text in base 2 back into a number. The 2 says which base the text is in:

print(bin(13))
print(int("1101", 2))
print(2 ** 8, 2 ** 8 - 1)
It runs right here in your browser, with nothing to install.

The answer from bin is text that starts with 0b, Python's mark for "the digits that follow are in base 2". int reads the 0b too, so int(bin(13), 2) gives back 13. The last line is a byte: 256 patterns, the largest 255.

Quick check
What does this print?
print(bin(6), int("110", 2) + 1)
  1. 110 7
  2. 0b011 7
  3. 0b110 111
  4. 0b110 7
Show the answer

0b110 7

6 = 4 + 2, so bin(6) is 0b110. int("110", 2) reads the same bits back as 6, and adding 1 gives 7.

Floats, close up. Python's own floats are float64: 64 bits, with 53 binary digits. Print 0.1 to 20 decimal places, with the f-string format from lesson 7, and the crumb shows. The other lines check the math part's numbers: 3.75 as 11.11 and as 1.111 × 2¹, the whole-number edges of float32 and float16, and what 24 and 11 binary digits are worth in decimal digits.

import math

print(f"{0.1:.20f}")
print(2 + 1 + 1/2 + 1/4, (1 + 1/2 + 1/4 + 1/8) * 2)
print(2 ** 24, 2 ** 11)
print(math.log10(2 ** 24), math.log10(2 ** 11))

The stored 0.1 is 0.10000000000000000555, a hair over. Both ways of writing 3.75 add up. 2²⁴ = 16,777,216 and 2¹¹ = 2,048 are the edges. And log10 says 2²⁴ is about 10⁷·², so 24 binary digits are worth about 7.2 decimal digits, and 11 about 3.3.

Adding 0.1 ten times. In lesson 19 you'll repeat a line with a loop. For now, ten plus signs do the same job:

total = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1
print(total)
print(total == 1.0)

Ten tenths should make 1, but each add rounds to the nearest float, and the crumbs pile up. Step through the same adds one at a time, and watch the box for total.

A named mistake: testing floats with ==. You met math.isclose in lesson 7. Now you can see why == fails, and that it fails both ways. It says False for sums that should match. And past 2⁵³, where Python's floats run out of digits, it says True for numbers that differ:

import math

total = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1
print(math.isclose(total, 1.0), abs(total - 1.0) < 1e-9)
print(2.0 ** 53 + 1 == 2.0 ** 53)

Both tests with a tolerance say True. The last line says True as well, and it's wrong: 2⁵³ + 1 needs 54 digits, so Python rounds it back to 2⁵³. Compare floats with a tolerance. Keep counts as whole numbers (ints, with no point), which Python stores exactly at any size.

Quick check
What does this print?
print(0.5 + 0.25 == 0.75)
  1. False
  2. True
  3. 0.75
  4. 0.7500000000000001
Show the answer

True

0.5 is 1/2 and 0.25 is 1/4: in base 2 they're 0.1 and 0.01, with nothing cut off. Their sum, 0.11 in base 2, is exactly 0.75, so == says True. Only numbers whose digits run on, like 0.1, get rounded.

The biggest whole number a float holds exactly. A float keeps every whole number exactly until the numbers need more digits than it has. To find the edge, search through powers of two: add 1, take the power away again, and see whether the 1 survived.

print(2.0 ** 20 + 1 - 2.0 ** 20)
print(2.0 ** 60 + 1 - 2.0 ** 60)

At 2²⁰ the 1 still counts; at 2⁶⁰ it's lost. The edge for Python's floats is somewhere between, and the drill at the end of this part has you find it. PyTorch, the library most models are built with, stores numbers as float32 unless asked otherwise. Here float32 is asked to store 2²³ + 1 and 2²⁴ + 1, one power below its edge and one at it:

Worked example

Worked example: how many bits for a vocabulary?

A language model gives every word piece it knows a number. With 50,000 word pieces, how many bits does each number need, and how many bytes?

vocab = 50000
print(2 ** 15, 2 ** 16)
print(bin(vocab))
In the lesson you can change this and run it.

15 bits make 32,768 values, too few for 50,000. 16 bits make 65,536, enough. bin agrees: after the 0b, 0b1100001101010000 has 16 digits. 16 bits are 2 bytes, so each word piece's number fits in 2 bytes.

Drill

Search for the edge

Find the edge for Python's own floats. Change n until it's the first power where adding 1 to 2.0 ** n is lost (the tests say whether you're too low or too high). Then set edge to 2 ** n, that power of two as a whole number: the largest whole number up to which Python's floats miss none.

n = 20
lost = 2.0 ** n + 1 == 2.0 ** n
print(n, lost)
edge = 0
print(edge)
In the lesson, your code is checked as you write it.
In your own words
Why can == say True for two different whole numbers, and False for ten 0.1s added up and 1.0?

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

In AI and ML: memory, half precision and 8 bits

Purpose. A model's weights are floats. The bytes each one gets set how much memory the model takes and how exact its math is.

Memory is count × bytes.

memory=count of numbers×bytes per number\text{memory} = \text{count of numbers} \times \text{bytes per number}

In plain words: count the numbers, and give each one its bytes: 4 in float32, 2 in float16, 1 in 8 bits.

In lesson 11 every number took 4 bytes. Those were float32's 32 bits, and now the bytes can change. The trail club's sign reader looks at 5 × 5 signs, as in lesson 1: 25 numbers each. A small language model has about 120 million weights. Here's the memory for 1,000 signs, and for that model at 4, 2 and 1 byte per weight:

signs = 1000 * 5 * 5
print(signs * 4, "bytes for 1000 signs in float32")
weights = 120e6
print(weights * 4 / 1e6, "MB in float32")
print(weights * 2 / 1e6, "MB in float16")
print(weights * 1 / 1e6, "MB in 8 bits")

Halving the bytes halves the memory: 480 MB, then 240, then 120. That's why big models are often run in 16-bit floats, and squeezed into 8 bits when memory is tight.

Quick check
What does this print?
weights = 3e9
print(weights * 2 / 1e9)
  1. 3.0
  2. 6.0
  3. 6
  4. 12.0
Show the answer

6.0

3 × 10⁹ weights × 2 bytes = 6 × 10⁹ bytes, and dividing by 10⁹ gives 6 gigabytes. It's a float, so 6.0.

In the real tools. PyTorch keeps a tensor's number type in x.dtype, and .to(torch.float16) makes a half-precision copy. Here are 1,000 copies of 0.1, stored both ways, with their memory and the first number as stored:

Rounding weights to 8 bits. Squeezing a model into 8 bits is called quantizing. 8 bits give 2⁸ = 256 levels. Cut the range from the smallest weight to the largest into 255 equal steps (256 levels have 255 gaps between them), and round each weight to the nearest level. Say the sign reader's weights run from −0.66 to 0.91, and round the weight 0.42:

lo = -0.66
hi = 0.91
step = (hi - lo) / 255
w = 0.42
level = round((w - lo) / step)
back = lo + level * step
print(step)
print(level, back)
print(abs(w - back), step / 2)

The weight is stored as level 175, in one byte, and read back as 0.4175, off by 0.0025. Rounding to the nearest level is never off by more than half a step, 0.0031 here, so the error is small and known before you start.

Drill

Round a weight to 8 bits

Another layer's weights run from −0.5 to 0.7. Fix the starter so step is the gap between the 256 levels, level is the weight 0.345 rounded to the nearest level, back is that level read back as a weight, and err is the size of the miss. Each line from step on has a slip.

lo = -0.5
hi = 0.7
step = (hi - lo) / 256
w = 0.345
level = (w - lo) / step
back = level * step
err = w - back
print(step, level, back, err)
In the lesson, your code is checked as you write it.
In your own words
When would you store a model in float16 or 8 bits instead of float32, and what do you give up?

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

Goes deeper in

  • Quantization: storing a real model's weights in fewer bits, and measuring what it costs.
  • PyTorch tensors: dtypes, .to() and memory on real tensors.

Practice what you just read

  • 8 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

How many different values can 12 bits hold?

  1. 4,096
  2. 24
  3. 4,095
  4. 144

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