A friend has 1,000 photos and a program that finds the most similar pair by comparing every photo with every other photo. Say it takes one second. She loads 1,000,000 photos and starts the same program. Does it take a thousand seconds? No. A thousand times more photos means a million times more pairs, so it takes a million times longer: about 12 days (the numbers are worked out below).
This lesson gives you a way to see that coming before you press Run. Count the work. See how the count grows with the size of the input. Compare it with what your hardware can do.
Counting steps
The first skill is to count the basic steps of a piece of code. Call the size of the input (the number of items, tokens, parameters or pixels, whatever the loop runs over). Count one basic step for each addition, multiplication or comparison.
One pass. Add up numbers:
total = 0
for i in range(n):
total += x[i] # one addition per item
The loop body runs times, so the cost is about steps. Ten items, ten steps. A million items, a million steps. Double the input and the work doubles.
A loop inside a loop. Compare every item with every other item:
for i in range(n):
for j in range(n):
compare(x[i], x[j]) # runs n × n times
The inner body runs times for each of the values of : steps. If you only need each unordered pair once (start the inner loop at ), the count is , which is 499,500 for . That is about half of and still grows like .
Halving. Keep cutting the problem in half until one item is left:
while n > 1:
n = n // 2
For the loop runs 9 times (). The number of halvings is about , and a logarithm grows very slowly: a million items need only about 20 halvings.
So the three patterns are a pass (), a loop inside a loop () and repeated halving (). Most of the costs in this lesson are built from these three.
Big-O: keep the shape, drop the details
Suppose a program does steps. The exact count is not very useful, because the “3”, the “5” and the “20” change with the programming language, the compiler and the chip. What does not change is the shape: for large the term wins. At the count is , and of it (99.8%) comes from the term.
Big-O notation keeps only the fastest-growing term and drops its constant factor. We write and say “order ”.
The formal statement says “grows no faster than, up to a constant”:
for some constants and . For and : for we have and , so . The definition holds with and . A tighter pair also works: and , because , while at it fails ().
Three rules follow:
- Drop constant factors. and are both . A faster machine changes the constant and does not change the shape. The base of a logarithm is a constant factor too ( is about ), so needs no base.
- Drop lower-order terms. is . The is a rounding error once is large.
- Add for steps one after the other, multiply for steps inside steps. A pass () followed by a pairs loop () costs . A pairs loop where each pair costs steps (the distance between two vectors of length ) costs .
Big-O is an upper bound, so a program that does steps is technically also . That is true and useless. When people say “the cost is ” they mean the tightest bound they know.
When the dropped constants matter
Big-O describes what happens as grows without limit. For a fixed, modest , constants decide. Take a program that does steps and one that does . At the “worse” program wins ( against ). They tie at . Above 100 the program wins, and at it is ten times faster ( against ). In practice this is why a simple method can beat a clever one on small inputs, and why “which is faster” needs a measurement and not only a Big-O.
Worst case and average case
The cost may depend on the data, not only on . Searching an unsorted list of items for a value: if the value is last (or missing), you compare with all items, the worst case. If it is equally likely to be anywhere, you compare with about items on average (500.5 for ), the average case. Both are here. Big-O is usually quoted for the worst case unless the text says “average”. (Some methods differ a lot: the common sorting method quicksort is on average and in its worst case.)
The common classes
| Cost | Typical example | In ML |
|---|---|---|
| read item of an array | look up a token’s embedding row by its ID | |
| binary search in a sorted list | find a value in a sorted array of thresholds | |
| one pass over the data | loss over examples; one full-batch gradient (P1.F4) | |
| sorting | sort predictions to find the top or a percentile | |
| all pairs | pairwise distances; attention (P7.12) | |
| triple loop | dense matrix product (standard method); dense solve (P1.B9) | |
| all subsets | try every subset of features |
The names, in order: constant, logarithmic, linear, “n log n”, quadratic, cubic, exponential.
Binary search works on a sorted list. Look at the middle item. If your target is smaller, throw away the upper half; otherwise the lower half. Each look halves what is left, so at most about looks are needed: 20 for a sorted list of 1,000,000 items, against up to 1,000,000 looks for a plain scan.
All subsets blow up because each item is either in or out: choices. For 20 features that is subsets. For 30 it is . Several methods in ML (greedy feature selection, L1 regularization) exist to avoid checking all of them.
Here is the same list with numbers. Counts of basic steps (the row is rounded):
| Steps | |||
|---|---|---|---|
| 3 | 10 | 20 | |
| 10 | 1,000 | ||
| 33 | 9,966 | ||
| 100 | |||
| 1,000 |
The row for is at ; at it is a number with 302 digits (about ); at it has 301,030 digits.
To feel the sizes, imagine a computer that does basic steps per second (a round number chosen for illustration, not a real machine). At :
| Cost | Time at steps per second |
|---|---|
| 0.001 seconds | |
| 0.02 seconds | |
| 1,000 seconds, about 17 minutes | |
| seconds, about 32 years |
And at only is steps, about 13 days. At it is about years. That is why an exponential cost means “do not even try”.
The photo problem from the start: 1,000 photos give pair comparisons; photos give . If one comparison takes a microsecond (again, an illustrative number), the first run is one second and the second is seconds, about 12 days.
The widget: five growth curves
The chart plots the five costs against the input size . Slide and switch between a linear and a log vertical axis. The table below the chart doubles as the legend and shows each cost at your , and by what factor it grows when you multiply by 2, 4 or 10.
Things to try (each checked against the widget’s own formulas):
- n = 10, linear axis. At the values are still small and within about a factor of 10 of each other (, , ), yet on the linear axis three curves already leave the top between and . Small tests hide how fast the cost grows.
- n = 1,000, log axis. The and curves are lines near the bottom ( and ). is at and at . leaves the top of the chart at about .
- Multiply n by 2. The factors in the table are for , about for at ( at , at ), for and for . For the factor is itself : doubling squares the cost.
- Attention preset. At tokens the row shows pairs; multiplied by 4 (4,000 tokens) it grows by to pairs. The line under the table says so.
- n = 1,000,000. The linear axis goes up to , so the curve reaches the top at a tiny fraction of the width; and appear in the table.
Memory: the second bill
Time is not the only cost. A program also needs memory (space): how many numbers it must hold at once. Time and memory are counted separately, and one can be fine while the other is not.
Memory is the count of numbers times the number of bytes per number (P1.G1). A float32 number takes 4 bytes. An matrix in float32 takes bytes:
- : bytes, 400 MB. Fits on a laptop.
- : bytes, 40 GB. Does not fit on most laptops.
Ten times larger , a hundred times more memory. The Hessian of a model with parameters has entries, 4 TB (P1.C8, P1.F6). Compare all pairwise distances between points: the time is about operations for vectors of length , and storing the whole table takes the 400 MB above. The memory can be avoided by computing the pairs in chunks, and the time cannot.
Memory and time can also be traded against each other. A training run keeps intermediate values from the forward pass so that the backward pass can use them (P4.8); keeping fewer and recomputing them later saves memory and costs time. That trade is a standard technique for big models (known as gradient checkpointing).
FLOPs: counting arithmetic
For numerical code the basic step is arithmetic on floating-point numbers (P1.G1). A FLOP (floating-point operation) is one addition, subtraction, multiplication or division of two floating-point numbers. (The plural “FLOPs” is a count of operations. “FLOP/s” is a speed, operations per second. Some texts write “FLOPS” for the speed, which is easily confused with the plural, so this course writes FLOP/s.)
A dot product of two vectors of length (P1.B3) has multiplications and additions: FLOPs, about . For that is .
A matrix-vector product of an matrix with a vector is dot products of length : , about FLOPs. For that is , about .
A matrix-matrix product has dot products of length : , about FLOPs (P1.B6 counts it as multiply-adds; one multiply-add is two FLOPs). For that is , about . For two matrices it is about FLOPs, and for square matrices the standard method is (faster algorithms exist, such as Strassen’s, P1.B6).
Some FLOP counts in the literature count a multiply-add as one operation, so check which convention a source uses. (P1.B9’s multiplications for an LU solve is the same work as P1.F6’s operations for LU, because a multiply-add is 2 FLOPs. Cholesky needs half of that, about FLOPs.)
FLOPs against speed
FLOPs measure work. How long the work takes depends on the machine’s speed in FLOP/s. If a machine could do FLOP/s (an illustrative round number, not a particular chip), a matrix product, FLOPs, would take at best seconds. Real programs reach only a fraction of a chip’s peak, because the numbers must also be moved around.
Go deeper Why memory speed can matter more than arithmetic speed
A chip must bring numbers from memory before it can add or multiply them. The number of FLOPs per byte moved is the arithmetic intensity. A matrix-vector product reads each of the matrix entries once and does only about 2 FLOPs for each, which is about FLOPs per byte in float32. Memory speed limits it, and a faster arithmetic unit would not help. A matrix-matrix product of two matrices does FLOPs on numbers, at best about FLOPs per byte in float32 (about 167 for ), so it can keep the arithmetic units busy. This is part of why neural networks are built from big matrix products, and why the same FLOP count can run at very different speeds. P10.B8 covers this properly under the name roofline model.
The cost of training a layer
A dense layer with inputs and outputs, applied to a batch of examples, is the matrix product . By the formula above, the forward pass costs about FLOPs. For , and that is , about .
The backward pass (P4.8) needs the gradient with respect to the weights and the gradient with respect to the inputs: two matrix products of the same size. So the backward pass costs about twice the forward pass, and a full training step about three times: here. This is a rule of thumb for dense layers (it ignores biases, activation functions and everything that is not a big matrix product).
The layer has weights, and per example the forward pass costs FLOPs for each weight and a training step . Scaled to a whole network with parameters trained on tokens, this gives the widely used estimate of about FLOPs for training. It appears in the scaling-law paper by Kaplan et al. (2020), which counts the non-embedding parameters, and it leaves out the terms that depend on the sequence length. For illustration, a model with parameters trained on tokens is about FLOPs. P10.B4 treats this carefully.
Full batch against mini-batch. The same counting explains the cost rule in P1.F4: a full-batch gradient step goes over all examples and costs about units, a mini-batch step costs about . One epoch (one pass over the data) is steps of each, so about units whatever is; this ignores that tiny batches use the hardware less efficiently.
Attention: a preview of the cost
A transformer reads a sequence of tokens (the lessons on transformers write where this lesson writes ). Self-attention gives every token a score for every other token (P7.2), so there are scores per attention head. With head dimension , the score matrix is a product, FLOPs, and applying the weights to the values is another product of the same size (when the value size equals the key size). In Big-O terms the cost is per head: quadratic in the length.
The numbers: for and that is about FLOPs for the two products of one head. Four times longer, , means times as many token pairs () and times the FLOPs. If the whole score matrix is stored in 16-bit numbers (2 bytes each), takes bytes, about 34 MB for one head of one sequence in one layer, and takes bytes, about 2.1 GB. Methods that avoid storing the whole matrix, or avoid computing all pairs, are why long contexts are possible at all (P7.12, P7.13).
Vectorization: same growth, very different speed
Two programs can both be and differ in speed by a factor of 100. A Python for loop does separate steps, and Python spends time on each one (looking up types, calling functions). NumPy runs a single call in compiled code over the whole array at once. This is called vectorization. It does not change Big-O (still multiplications and additions), it changes the constant, and on large arrays the constant is large.
Try it in the third cell below. The timings vary from machine to machine and run to run, so the cell prints “on this machine”.
Go deeper Amortized cost: appending to a list
Appending to a Python list is usually fast, but sometimes the list runs out of reserved space and must be copied into a bigger block, which can cost about as many steps as the list has items (the memory allocator can sometimes extend the block in place instead). Averaged over many appends the cost per append is still constant. The argument: if the list grows its storage by a fixed fraction (say it doubles), the copies happen at sizes , and their total is less than twice the final size. For appends with doubling the copies add up to , about per append. This average over a whole sequence of operations is the amortized cost, per append. (CPython grows lists by a smaller fraction than doubling, so the constant is larger, but the argument is the same.)
Go deeper Lower bounds and tight bounds: Big-Omega and Big-Theta
Big-O is an upper bound. The matching lower bound is Big-Omega: means for all , for some . When both hold, is Big-Theta of , written , and the growth rate is pinned down. Our example is : for . A famous lower bound: any sorting method that works only by comparing two items at a time needs comparisons in the worst case, so sorting cannot be beaten by cleverness (it can be by other means, such as counting sorts that use extra knowledge about the keys).
The recipe in one place
Intuition
Count the steps, look at how the count grows when the input doubles, and compare. Double : the work of doubles, of quadruples, of grows eightfold. A logarithm barely moves. An exponential squares itself. Then count memory separately (numbers times bytes), and for arithmetic-heavy code count FLOPs. Always check that the computation, and the numbers it needs, fit in the time and the memory you have.
Math
: there are and with for all . Example: for , so it is . Doubling: , , , , which is at (logs in any one base), squared.
FLOPs: dot product ; matrix-vector ; : . Memory: count bytes per number. Dense layer: forward , backward forward, step forward . Self-attention: time, scores per head.
Code
import numpy as np
n = 1_000_000
x, y = np.random.rand(n), np.random.rand(n)
dot = x @ y # about 2n FLOPs, in one compiled call
print(x.nbytes) # memory: 8 000 000 bytes (float64, 8 bytes per number)
A = np.random.rand(1000, 1000)
C = A @ A # about 2 * 1000**3 = 2e9 FLOPsNever write the for loop version of these in numerical code. Cell three below times it.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
The second cell counts FLOPs and memory, and shows the doubling factors.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The third cell times a Python loop against NumPy for the same dot product of two lists with 200,000 numbers each.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Check your understanding
A program does basic steps. What is its cost in Big-O notation?
For large the term dominates, and for every , so the cost is . Dropping to would be wrong, because outgrows any constant times . Big-O deliberately drops constants and smaller terms, so the full polynomial is not the usual form. is a valid upper bound but not the tightest one.
The input size grows from to . By roughly what factor does the work grow for a method that costs ?
The factor is . A factor of is the growth of a method with cost , and a factor of is that of a method with cost . A factor of has no basis in the arithmetic.
About how many FLOPs does the product of a matrix and a matrix need?
The result has entries, each a dot product of length costing about FLOPs, so about . The value counts multiply-adds, which is half the FLOPs. Sizes do not add, and the entries of the result are only the number of dot products, not their length.
A transformer's sequence grows from 1,000 tokens to 4,000. How does the number of token pairs that self-attention scores change?
There are pairs: at 1,000 tokens and at 4,000, a factor of . A factor of would be linear growth. The factor is what gives, which is not attention's pattern. The number of parameters does not change, but the number of pairs depends on the sequence length.
Method X takes steps and method Y takes steps. For which input size is Y the faster one?
At , Y takes steps and X takes . They tie at , and above that X wins (at , X needs steps and Y needs ). Big-O compares growth for large , not every size. A lower Big-O class does not guarantee a faster program on small inputs.
Exercises
- Three nested loops each run times, one inside the next. How many times does the innermost body run, and what is its Big-O?
Show answer
times, so it is . For that is runs. - Show that by finding and .
Show answer
For , , so . Take and . (Other pairs work too, for example and : .) - A sorted list has items. How many looks does binary search need at most, and how many does a plain scan need at most?
Show answer
Binary search: . A scan: up to . - How many FLOPs does a matrix times a vector of length need, about?
Show answer
About FLOPs (exactly ). - An matrix of float32 numbers takes 4 GB. What is approximately?
Show answer
bytes gives and . - A training step of a dense layer with batch size 64, 512 inputs and 2048 outputs: how many FLOPs for the forward pass, and about how many for forward plus backward?
Show answer
Forward , about . With the backward pass at about twice that, about three times in all: , about .
Next: P1 is complete: you now have the math foundations. Part 2 turns to the programming toolkit. Part 7 returns to the cost of attention (P7.12), and P10.B4 counts compute and memory for whole language models.