Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsNumerical Computing

Big-O and compute cost

P1.G435 min●○○ BeginnerReviewed Dec 1, 2026

Why this matters for machine learning

Machine learning runs on large inputs, and the cost of a method grows with the size of the input in a pattern that decides whether it is affordable at all. Big-O names that pattern, and FLOP counts turn it into numbers you can compare.

  • Self-attention compares every token with every other token, so its cost grows with the square of the sequence length: four times as many tokens means sixteen times as many pairs. (P7.12: The cost of attention, coming soon)
  • Counting FLOPs and bytes tells you before training whether a model fits on your hardware and roughly how long it will take: about 2 FLOPs per parameter per token for a forward pass, and about 6 for a training step. (P10.B4: Counting compute and memory, coming soon)
  • Brute-force k-nearest neighbors compares a query with every training example, so one prediction costs about N·d operations and slows down as the data grows. (P3.B1: k-Nearest Neighbors)
  • Newton's method needs memory for an n×n Hessian and about n³ operations per step, which is why networks with billions of parameters use first-order optimizers. (P1.F6: Second-order methods)

Before this: Exponents and logarithms, Summation, products and indices, Matrix multiplication

After this lesson you can

  • Count the basic steps of a small piece of code with loops, and say its growth rate in Big-O notation
  • Say what Big-O keeps and what it drops, and when the dropped constants still matter in practice
  • Compare O(1), O(log n), O(n), O(n log n), O(n²), O(n³) and O(2ⁿ) with numbers, and name an ML task for each
  • Count the FLOPs of a dot product, a matrix-vector product and a matrix-matrix product, and the memory of an array
  • Explain why a NumPy call can be much faster than a Python loop with the same Big-O

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 nn (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 nn numbers:

total = 0
for i in range(n):
    total += x[i]       # one addition per item

The loop body runs nn times, so the cost is about nn 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 nn times for each of the nn values of ii: n⋅n=n2n\cdot n=n^2 steps. If you only need each unordered pair once (start the inner loop at i+1i+1), the count is n(n−1)/2n(n-1)/2, which is 499,500 for n=1000n=1000. That is about half of n2n^2 and still grows like n2n^2.

Halving. Keep cutting the problem in half until one item is left:

while n > 1:
    n = n // 2

For n=1000n=1000 the loop runs 9 times (1000→500→250→125→62→31→15→7→3→11000\to500\to250\to125\to62\to31\to15\to7\to3\to1). The number of halvings is about log⁡2n\log_2 n, and a logarithm grows very slowly: a million items need only about 20 halvings.

So the three patterns are a pass (nn), a loop inside a loop (n2n^2) and repeated halving (log⁡2n\log_2 n). Most of the costs in this lesson are built from these three.

Big-O: keep the shape, drop the details

Suppose a program does 3n2+5n+203n^2+5n+20 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 nn the n2n^2 term wins. At n=1000n=1000 the count is 3,005,0203{,}005{,}020, and 3,000,0003{,}000{,}000 of it (99.8%) comes from the 3n23n^2 term.

Big-O notation keeps only the fastest-growing term and drops its constant factor. We write 3n2+5n+20=O(n2)3n^2+5n+20=O(n^2) and say “order n2n^2”.

The formal statement says “grows no faster than, up to a constant”:

f(n)=O(g(n)) means:f(n)≤C g(n) for all n≥n0.\begin{aligned} &f(n)=O(g(n))\ \text{means:}\\ &f(n)\le C\,g(n)\ \text{for all } n\ge n_0 . \end{aligned}

for some constants C>0C>0 and n0n_0. For f(n)=3n2+5n+20f(n)=3n^2+5n+20 and g(n)=n2g(n)=n^2: for n≥1n\ge1 we have 5n≤5n25n\le5n^2 and 20≤20n220\le20n^2, so f(n)≤(3+5+20)n2=28n2f(n)\le(3+5+20)n^2=28n^2. The definition holds with C=28C=28 and n0=1n_0=1. A tighter pair also works: C=4C=4 and n0=8n_0=8, because f(8)=252≤256=4⋅82f(8)=252\le256=4\cdot 8^2, while at n=7n=7 it fails (202>196202>196).

Three rules follow:

  • Drop constant factors. 5n5n and 1000n1000n are both O(n)O(n). A faster machine changes the constant and does not change the shape. The base of a logarithm is a constant factor too (log⁡2n\log_2 n is about 1.44ln⁡n1.44\ln n), so O(log⁡n)O(\log n) needs no base.
  • Drop lower-order terms. n2+nn^2+n is O(n2)O(n^2). The nn is a rounding error once nn is large.
  • Add for steps one after the other, multiply for steps inside steps. A pass (nn) followed by a pairs loop (n2n^2) costs O(n+n2)=O(n2)O(n+n^2)=O(n^2). A pairs loop where each pair costs dd steps (the distance between two vectors of length dd) costs O(n2d)O(n^2 d).

Big-O is an upper bound, so a program that does nn steps is technically also O(n2)O(n^2). That is true and useless. When people say “the cost is O(n2)O(n^2)” they mean the tightest bound they know.

When the dropped constants matter

Big-O describes what happens as nn grows without limit. For a fixed, modest nn, constants decide. Take a program that does 100n100n steps and one that does n2n^2. At n=50n=50 the “worse” n2n^2 program wins (2,5002{,}500 against 5,0005{,}000). They tie at n=100n=100. Above 100 the 100n100n program wins, and at n=1000n=1000 it is ten times faster (100,000100{,}000 against 1,000,0001{,}000{,}000). In practice this is why a simple O(n2)O(n^2) method can beat a clever O(nlog⁡n)O(n\log n) 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 nn. Searching an unsorted list of nn items for a value: if the value is last (or missing), you compare with all nn items, the worst case. If it is equally likely to be anywhere, you compare with about (n+1)/2(n+1)/2 items on average (500.5 for n=1000n=1000), the average case. Both are O(n)O(n) 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 O(nlog⁡n)O(n\log n) on average and O(n2)O(n^2) in its worst case.)

The common classes

CostTypical exampleIn ML
O(1)O(1)read item ii of an arraylook up a token’s embedding row by its ID
O(log⁡n)O(\log n)binary search in a sorted listfind a value in a sorted array of thresholds
O(n)O(n)one pass over the dataloss over NN examples; one full-batch gradient (P1.F4)
O(nlog⁡n)O(n\log n)sortingsort predictions to find the top kk or a percentile
O(n2)O(n^2)all pairspairwise distances; attention (P7.12)
O(n3)O(n^3)triple loopdense matrix product (standard method); dense solve (P1.B9)
O(2n)O(2^n)all subsetstry every subset of nn 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 log⁡2n+1\log_2 n+1 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: 2⋅2⋯2=2n2\cdot2\cdots2=2^n choices. For 20 features that is 1,048,5761{,}048{,}576 subsets. For 30 it is 1,073,741,8241{,}073{,}741{,}824. 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 nlog⁡2nn\log_2 n row is rounded):

Stepsn=10n=10n=103n=10^3n=106n=10^6
log⁡2n\log_2 n31020
nn101,00010610^6
nlog⁡2nn\log_2 n339,9662.0×1072.0\times10^7
n2n^210010610^6101210^{12}
n3n^31,00010910^9101810^{18}

The row for 2n2^n is 1,0241{,}024 at n=10n=10; at n=1000n=1000 it is a number with 302 digits (about 1.1×103011.1\times10^{301}); at n=106n=10^6 it has 301,030 digits.

To feel the sizes, imagine a computer that does 10910^9 basic steps per second (a round number chosen for illustration, not a real machine). At n=106n=10^6:

CostTime at 10910^9 steps per second
nn0.001 seconds
nlog⁡2nn\log_2 n0.02 seconds
n2n^21,000 seconds, about 17 minutes
n3n^310910^9 seconds, about 32 years

And 2n2^n at only n=50n=50 is 1.1×10151.1\times10^{15} steps, about 13 days. At n=100n=100 it is about 4×10134\times10^{13} years. That is why an exponential cost means “do not even try”.

The photo problem from the start: 1,000 photos give 10610^6 pair comparisons; 10610^6 photos give 101210^{12}. If one comparison takes a microsecond (again, an illustrative number), the first run is one second and the second is 10610^6 seconds, about 12 days.

The widget: five growth curves

The chart plots the five costs against the input size nn. Slide nn 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 nn, and by what factor it grows when you multiply nn by 2, 4 or 10.

Five growth curves: how the cost of a job grows with its size n

5010005001000input size ncost
Multiply n by
Cost at n = 100 and the factor by which it grows when n is multiplied by 2
CurveCost at n = 100Cost grows ×, when n × 2
n100×2
n log₂ n664×2.3
n²10,000×4
n³1×10⁶×8
2ⁿ1.27×10³⁰×1.27×10³⁰

At n = 100, n², n³, 2ⁿ leave the top of the chart (the curves keep rising above the frame).

Attention preview. A sequence of 100 tokens has 10,000 token pairs (n²). With 200 tokens there are 40,000 pairs: ×4.

The chart ends at your n; dots mark where each curve ends when it is still inside the chart. Cost means a count of basic steps. The linear axis runs from 0 to 2·n·log₂ n, so the steeper curves leave the top quickly; the log axis gives each power of 10 the same height. 2ⁿ is computed from its logarithm, so it never overflows.

Five curves, cost against input size n: n (blue), n log₂ n (green, dash-dot), n² (pink), n³ (dark, dashed) and 2ⁿ (red, dotted). Slide n from 2 to 1,000,000. The linear axis shows how quickly n², n³ and 2ⁿ leave the chart; the log axis gives every power of ten the same height. The table shows the cost at your n and the factor when n is multiplied by 2, 4 or 10. The Attention preset sets n = 1,000 and multiplies it by 4.

Things to try (each checked against the widget’s own formulas):

  • n = 10, linear axis. At n=10n=10 the values are still small and within about a factor of 10 of each other (100100, 1,0001{,}000, 1,0241{,}024), yet on the linear axis three curves already leave the top between n≈4n\approx4 and 88. Small tests hide how fast the cost grows.
  • n = 1,000, log axis. The nn and nlog⁡2nn\log_2 n curves are lines near the bottom (1,0001{,}000 and 9,9669{,}966). n2n^2 is at 10610^6 and n3n^3 at 10910^9. 2n2^n leaves the top of the chart at about n=30n=30.
  • Multiply n by 2. The factors in the table are ×2\times2 for nn, about ×2.2\times2.2 for nlog⁡2nn\log_2 n at n=1000n=1000 (×2.6\times2.6 at n=10n=10, ×2.1\times2.1 at n=106n=10^6), ×4\times4 for n2n^2 and ×8\times8 for n3n^3. For 2n2^n the factor is itself 2n2^n: doubling nn squares the cost.
  • Attention preset. At n=1,000n=1{,}000 tokens the n2n^2 row shows 10610^6 pairs; multiplied by 4 (4,000 tokens) it grows by ×16\times16 to 1.6×1071.6\times10^7 pairs. The line under the table says so.
  • n = 1,000,000. The linear axis goes up to 4×1074\times10^7, so the n2n^2 curve reaches the top at a tiny fraction of the width; 101210^{12} and 101810^{18} 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 n×nn\times n matrix in float32 takes 4n24n^2 bytes:

  • n=10,000n=10{,}000: 4×1084\times10^8 bytes, 400 MB. Fits on a laptop.
  • n=100,000n=100{,}000: 4×10104\times10^{10} bytes, 40 GB. Does not fit on most laptops.

Ten times larger nn, a hundred times more memory. The Hessian of a model with n=106n=10^6 parameters has 101210^{12} entries, 4 TB (P1.C8, P1.F6). Compare all pairwise distances between n=104n=10^4 points: the time is about n2d=108dn^2d=10^8d operations for vectors of length dd, and storing the whole n×nn\times n 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 nn (P1.B3) has nn multiplications and n−1n-1 additions: 2n−12n-1 FLOPs, about 2n2n. For n=3n=3 that is 55.

A matrix-vector product of an m×nm\times n matrix with a vector is mm dot products of length nn: m(2n−1)m(2n-1), about 2mn2mn FLOPs. For 1000×10001000\times1000 that is 1,999,0001{,}999{,}000, about 2×1062\times10^6.

A matrix-matrix product (m×n)(n×p)(m\times n)(n\times p) has m⋅pm\cdot p dot products of length nn: mp(2n−1)mp(2n-1), about 2mnp2mnp FLOPs (P1.B6 counts it as mnpmnp multiply-adds; one multiply-add is two FLOPs). For (200×300)(300×400)(200\times300)(300\times400) that is 200⋅400⋅599=47,920,000200\cdot400\cdot599=47{,}920{,}000, about 4.8×1074.8\times10^7. For two 1000×10001000\times1000 matrices it is about 2×1092\times10^9 FLOPs, and for square matrices the standard method is O(n3)O(n^3) (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 n3/3n^3/3 multiplications for an LU solve is the same work as P1.F6’s 2n3/32n^3/3 operations for LU, because a multiply-add is 2 FLOPs. Cholesky needs half of that, about n3/3n^3/3 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 101110^{11} FLOP/s (an illustrative round number, not a particular chip), a 1000×10001000\times1000 matrix product, 2×1092\times10^9 FLOPs, would take at best 0.020.02 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 n2n^2 matrix entries once and does only about 2 FLOPs for each, which is about 0.50.5 FLOPs per byte in float32. Memory speed limits it, and a faster arithmetic unit would not help. A matrix-matrix product of two n×nn\times n matrices does 2n32n^3 FLOPs on 3n23n^2 numbers, at best about n/6n/6 FLOPs per byte in float32 (about 167 for n=1000n=1000), 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 dind_{\text{in}} inputs and doutd_{\text{out}} outputs, applied to a batch of BB examples, is the matrix product (B×din)(din×dout)(B\times d_{\text{in}})(d_{\text{in}}\times d_{\text{out}}). By the formula above, the forward pass costs about 2 B din dout2\,B\,d_{\text{in}}\,d_{\text{out}} FLOPs. For B=32B=32, din=1024d_{\text{in}}=1024 and dout=4096d_{\text{out}}=4096 that is 268,435,456268{,}435{,}456, about 2.7×1082.7\times10^8.

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: 805,306,368805{,}306{,}368 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 dindout=4,194,304d_{\text{in}}d_{\text{out}}=4{,}194{,}304 weights, and per example the forward pass costs 22 FLOPs for each weight and a training step 66. Scaled to a whole network with NN parameters trained on DD tokens, this gives the widely used estimate of about 6ND6ND 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 10910^9 parameters trained on 101110^{11} tokens is about 6×10206\times10^{20} 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 NN examples and costs about NN units, a mini-batch step costs about BB. One epoch (one pass over the data) is N/BN/B steps of BB each, so about NN units whatever BB is; this ignores that tiny batches use the hardware less efficiently.

Attention: a preview of the n2n^2 cost

A transformer reads a sequence of TT tokens (the lessons on transformers write TT where this lesson writes nn). Self-attention gives every token a score for every other token (P7.2), so there are T2T^2 scores per attention head. With head dimension dkd_k, the score matrix QK⊤\mathbf{Q}\mathbf{K}^\top is a (T×dk)(dk×T)(T\times d_k)(d_k\times T) product, 2T2dk2T^2d_k 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 O(T2 dk)O(T^2\,d_k) per head: quadratic in the length.

The numbers: for T=1000T=1000 and dk=64d_k=64 that is about 2.6×1082.6\times10^8 FLOPs for the two products of one head. Four times longer, T=4000T=4000, means 1616 times as many token pairs (1,000,000→16,000,0001{,}000{,}000\to16{,}000{,}000) and 1616 times the FLOPs. If the whole T×TT\times T score matrix is stored in 16-bit numbers (2 bytes each), T=4096T=4096 takes 16,777,216×216{,}777{,}216\times2 bytes, about 34 MB for one head of one sequence in one layer, and T=32,768T=32{,}768 takes 2,147,483,6482{,}147{,}483{,}648 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 O(n)O(n) and differ in speed by a factor of 100. A Python for loop does nn 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 nn multiplications and n−1n-1 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 1,2,4,8,…1,2,4,8,\dots, and their total is less than twice the final size. For 10610^6 appends with doubling the copies add up to 1,048,5751{,}048{,}575, about 1.051.05 per append. This average over a whole sequence of operations is the amortized cost, O(1)O(1) 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: f(n)=Ω(g(n))f(n)=\Omega(g(n)) means f(n)≥c g(n)f(n)\ge c\,g(n) for all n≥n0n\ge n_0, for some c>0c>0. When both hold, ff is Big-Theta of gg, written Θ(g(n))\Theta(g(n)), and the growth rate is pinned down. Our example is Θ(n2)\Theta(n^2): 3n2≤3n2+5n+20≤28n23n^2\le3n^2+5n+20\le28n^2 for n≥1n\ge1. A famous lower bound: any sorting method that works only by comparing two items at a time needs Ω(nlog⁡n)\Omega(n\log n) comparisons in the worst case, so O(nlog⁡n)O(n\log n) 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 nn: the work of nn doubles, of n2n^2 quadruples, of n3n^3 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

f(n)=O(g(n))f(n)=O(g(n)): there are C>0C>0 and n0n_0 with f(n)≤C g(n)f(n)\le C\,g(n) for all n≥n0n\ge n_0. Example: 3n2+5n+20≤28n23n^2+5n+20\le28n^2 for n≥1n\ge1, so it is O(n2)O(n^2). Doubling: O(n)→×2O(n)\to\times2, O(n2)→×4O(n^2)\to\times4, O(n3)→×8O(n^3)\to\times8, O(nlog⁡n)→×2(1+log⁡2/log⁡n)O(n\log n)\to\times2(1+\log 2/\log n), which is ×2.2\times2.2 at n=1000n=1000 (logs in any one base), O(2n)→O(2^n)\to squared.

FLOPs: dot product 2n−12n-1; matrix-vector m(2n−1)≈2mnm(2n-1)\approx2mn; (m×n)(n×p)(m\times n)(n\times p): mp(2n−1)≈2mnpmp(2n-1)\approx2mnp. Memory: count ×\times bytes per number. Dense layer: forward ≈2Bdindout\approx2Bd_{\text{in}}d_{\text{out}}, backward ≈2×\approx2\times forward, step ≈3×\approx3\times forward =6Bdindout=6Bd_{\text{in}}d_{\text{out}}. Self-attention: O(T2dk)O(T^2d_k) time, T2T^2 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 FLOPs

Never write the for loop version of these in numerical code. Cell three below times it.

Try it: count the steps of three loops, and check the Big-O bound

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.

Try it: FLOPs, memory, one layer and 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.

Try it: a Python loop against NumPy, same Big-O

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Check your understanding

  1. A program does 3n2+5n+203n^2+5n+20 basic steps. What is its cost in Big-O notation?

  2. The input size grows from n=1000n=1000 to n=2000n=2000. By roughly what factor does the work grow for a method that costs O(n2)O(n^2)?

  3. About how many FLOPs does the product of a 200×300200\times300 matrix and a 300×400300\times400 matrix need?

  4. A transformer's sequence grows from 1,000 tokens to 4,000. How does the number of token pairs that self-attention scores change?

  5. Method X takes 100n100n steps and method Y takes n2n^2 steps. For which input size is Y the faster one?

Exercises

  1. Three nested loops each run nn times, one inside the next. How many times does the innermost body run, and what is its Big-O?
    Show answern⋅n⋅n=n3n\cdot n\cdot n=n^3 times, so it is O(n3)O(n^3). For n=100n=100 that is 1,000,0001{,}000{,}000 runs.
  2. Show that 2n2+10n=O(n2)2n^2+10n=O(n^2) by finding CC and n0n_0.
    Show answerFor n≥1n\ge1, 10n≤10n210n\le10n^2, so 2n2+10n≤12n22n^2+10n\le12n^2. Take C=12C=12 and n0=1n_0=1. (Other pairs work too, for example C=3C=3 and n0=10n_0=10: 2⋅100+100=300≤3⋅1002\cdot100+100=300\le3\cdot100.)
  3. A sorted list has 1,000,0001{,}000{,}000 items. How many looks does binary search need at most, and how many does a plain scan need at most?
    Show answerBinary search: ⌊log⁡2106⌋+1=20\lfloor\log_2 10^6\rfloor+1=20. A scan: up to 1,000,0001{,}000{,}000.
  4. How many FLOPs does a 50×8050\times80 matrix times a vector of length 8080 need, about?
    Show answerAbout 2mn=2⋅50⋅80=8,0002mn=2\cdot50\cdot80=8{,}000 FLOPs (exactly m(2n−1)=50⋅159=7,950m(2n-1)=50\cdot159=7{,}950).
  5. An n×nn\times n matrix of float32 numbers takes 4 GB. What is nn approximately?
    Show answer4n2=4×1094n^2=4\times10^9 bytes gives n2=109n^2=10^9 and n≈31,623n\approx31{,}623.
  6. 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 answerForward 2⋅64⋅512⋅2048=134,217,7282\cdot64\cdot512\cdot2048=134{,}217{,}728, about 1.3×1081.3\times10^8. With the backward pass at about twice that, about three times in all: 402,653,184402{,}653{,}184, about 4.0×1084.0\times10^8.

Next: P1 is complete: you now have the math foundations. Part 2 turns to the programming toolkit. Part 7 returns to the n2n^2 cost of attention (P7.12), and P10.B4 counts compute and memory for whole language models.

Key takeaways

  • Count the basic steps as a function of the input size n. Big-O keeps the fastest-growing term and drops constants: 3n² + 5n + 20 is O(n²), because 3n² + 5n + 20 ≤ 28n² for every n ≥ 1.
  • Doubling n multiplies the work by 2 for O(n), about 2.2 for O(n log n) at n = 1,000, 4 for O(n²) and 8 for O(n³). O(2ⁿ) squares itself when n doubles, so it is hopeless beyond a few dozen items.
  • Big-O is about growth, not speed: 100n steps beat n² only when n is above 100, and two programs with the same Big-O can differ by a factor of a hundred (a Python loop against NumPy).
  • Time and memory are counted separately. Memory is the count of numbers times the bytes per number: an n×n float32 matrix takes 4n² bytes, 400 MB for n = 10,000.
  • A FLOP is one addition, subtraction, multiplication or division of floating-point numbers. A dot product of length n is 2n − 1 FLOPs, a matrix-vector product about 2mn, and an (m×n)(n×p) product about 2mnp. FLOPs count work, FLOP/s measures speed.
  • A training step of a dense layer costs about three times its forward pass (the backward pass is about twice the forward pass; the first layer is slightly cheaper because it needs no input gradient). Roughly, this is the origin of the rule of thumb of about 6 FLOPs per parameter per token.
  • Self-attention over n tokens makes n² token pairs: 1,000 tokens give 1,000,000 pairs, 4,000 tokens give 16,000,000.
Found a mistake? Tell us