Two napkin numbers plan a training run. Compute is 6 FLOPs per parameter per token, so 70 billion parameters on 15 trillion tokens take 144 days on 1,024 H100s. Memory is 16 bytes per parameter with AdamW, so 8 H100s hold at most 40 billion.
Pick one of the lecture's questions. Then drag the model size until it no longer fits, and add GPUs until it does. Then we build both numbers from zero: bytes per tensor, FLOPs per matmul, the backward pass, and the optimizer's state.
You need a little Python and a matrix product. We build the rest from zero.
Lecture 2 of Stanford CS336, Language Modeling from Scratch (Spring 2025, Percy Liang and Tatsunori Hashimoto). Previous: Lecture 1, Overview and Tokenization. Next: Lecture 3, Architectures and Hyperparameters.
Napkin math, as the lecture does it: 16 bytes per parameter (float32 weights, gradients and two AdamW states), activations not counted. Time uses NVIDIA's H100 SXM datasheet peak of 989.5 TFLOP/s in bf16 without sparsity, at 50% utilization.
Chapter 0
Turn a GPU budget into FLOPs and bytes before you write any training code
You get 32 H100 GPUs for two weeks. What is the biggest model you can train, and on how much text? Lecture 1 asked that question. Lecture 2 gives you the arithmetic to answer it.
Two resources decide every run. Memory is the bytes the GPUs must hold: weights, gradients, optimizer state and activations. Compute is the arithmetic they must do, counted in FLOPs: floating-point operations, one add or one multiply each.
The lecture opens with two napkin questions. How long does a 70-billion-parameter model take on 15 trillion tokens with 1,024 H100s? About 144 days. What is the largest model 8 H100s can train with AdamW, done naively? About 40 billion parameters. By the end of this lesson you can derive both in a minute.
Start with the size of a budget. A GPU's best speed is its peak, in FLOPs per second (FLOP/s). NVIDIA's datasheet gives the H100 SXM 1,979 TFLOP/s in bf16 "with sparsity"; dense training gets half of that, 989.5. Real runs reach about half of the dense peak.
The pink bar is your budget on a log ruler; each tick is ten times the last. The yellow marks are real runs. Drag the GPUs and the days.
Budget = GPUs × 989.5 TFLOP/s × 50% × seconds. GPT-3's 3.14 × 10²³ FLOPs is from Brown et al. (2020), Appendix D. The 70B run is the lecture's Question 1.
Eight H100s for two weeks at 50% give 4.8 × 10²¹ FLOPs. GPT-3 used 3.14 × 10²³, 66 times more. A run that needs more FLOPs than the budget holds cannot finish, even with perfect code.
Symptom: a run planned for two weeks is 40% done when the two weeks end.
Measure: divide the FLOPs one step needs by the step's measured time. Compare that speed with the speed you planned with.
Fix: plan with a measured utilization from the first hour, not with the datasheet peak.
Chapter 1
Count a tensor's memory from its shape and dtype, and tell a free view from a costly copy
Everything a run stores is a tensor: parameters, gradients, optimizer state, activations and data. A tensor is a block of numbers with a shape, such as 4 by 8. Its memory depends on two things: how many numbers it holds and how many bytes each one takes.
python x = torch.zeros(4, 8) # float32 by default assert x.numel() == 32 # number of values assert x.element_size() == 4 # bytes per float32 assert x.numel() * x.element_size() == 128
Call the number of values n: the product of the shape. Call the bytes per value b, set by the dtype. The memory M is:
M equals n times b.
Multiply the shape's sizes to get n. Look up b for the dtype. Multiply n by b to get M.
One feed-forward matrix of GPT-3 (the lecture's example) has shape 49,152 by 12,288, so n = 603,979,776. In float32, M = 603,979,776 × 4 = 2,415,919,104 bytes, 2.42 GB. GPT-3 has 96 layers with two such matrices each: 464 GB for these alone.
Where does each value live? A PyTorch tensor is a pointer into a flat block of storage, plus a shape and a stride. The stride says how many slots to skip to move one step along each dimension. A 4 by 4 tensor has stride (4, 1), so element [1][2] sits at slot 1 × 4 + 2 × 1 = 6.
Top: the tensor as you index it. Bottom: its storage, one slot per value. The arrow follows the stride arithmetic for one element. Transpose it, then make it contiguous.
The same rules as PyTorch's stride(), is_contiguous() and contiguous(), drawn for a small tensor holding 0, 1, 2, … in storage order.
Many operations make a view: a new shape and stride over the same storage. x[0], x.view(3, 2) and x.transpose(1, 0) copy nothing, so they are free. A transposed tensor is not contiguous: its rows are not side by side in storage. Then .view() fails, and .contiguous() makes a real copy.
Symptom: RuntimeError: view size is not compatible with input tensor's size and stride.
Measure: y.is_contiguous() is False after a transpose; its stride is (1, 3), not (2, 1).
Fix: call .contiguous() first, or .reshape(), which copies only when it must. Count the copy's bytes in your budget.
Chapter 2
Spend 32, 16 or 8 bits on exponent and mantissa, and see which numbers survive
A floating-point number has three parts. One sign bit. Exponent bits, which choose a power of two and so set the range: how big and how small a number can be. Mantissa bits, which choose a point between that power of two and the next, and so set the precision.
| Dtype | Bytes | Exponent, mantissa | Largest | Smallest normal | Step near 1 |
|---|---|---|---|---|---|
| float32 | 4 | 8, 23 | 3.4 × 10³⁸ | 1.2 × 10⁻³⁸ | 1.2 × 10⁻⁷ |
| float16 | 2 | 5, 10 | 65,504 | 6.1 × 10⁻⁵ | 0.00098 |
| bfloat16 | 2 | 8, 7 | 3.4 × 10³⁸ | 1.2 × 10⁻³⁸ | 0.0078 |
| fp8 E4M3 | 1 | 4, 3 | 448 | 0.016 | 0.125 |
| fp8 E5M2 | 1 | 5, 2 | 57,344 | 6.1 × 10⁻⁵ | 0.25 |
The table is torch.finfo for each dtype. float32 is the default and costs 4 bytes. float16 halves that, but its 5 exponent bits lose small numbers. Google Brain made bfloat16 in 2018: float16's size with float32's 8 exponent bits, so float32's range. Industry groups standardized FP8 in 2022, and the H100 runs both of its variants.
Each row is a dtype; the blue strip is its width in bits. The number on the right is what the dtype stores. Red means the value was lost. Drag the value, then try adding an update to 1.
Computed live: each format rounds to its nearest value, with subnormals, as torch does. fp8 E4M3 here is PyTorch's float8_e4m3fn.
How fine is a dtype near 1? Call the mantissa bits m. The gap from 1 to the next number the dtype can hold is ε, its machine epsilon:
Epsilon equals two to the minus m.
Start at 1. Each mantissa bit halves the gap to the next number. After m bits the gap is 1 halved m times: that is ε.
bfloat16 has m = 7, so ε = 1/128 = 0.0078. A weight of 1 plus an update of 0.001 is 1.001. bfloat16 rounds it back to 1.0, so the update is lost. float32 (m = 23, ε = 1.2 × 10⁻⁷) keeps it.
The lecture's two checks: torch.tensor([1e-8], dtype=torch.float16) is 0, an underflow, because float16 stops at 6 × 10⁻⁸ even with subnormals. In bfloat16 it is 1.0012 × 10⁻⁸. Deep learning tolerates coarse steps far better than lost values.
Symptom: the loss stops falling, though the gradients are not zero.
Measure: compare a weight before and after the step in its own dtype. In bfloat16, 1 + 0.001 is 1.0.
Fix: keep a float32 master copy of the weights and apply updates there (Chapter 7).
Chapter 3
Count one multiply and one add per triple, then compare your speed with the datasheet
Almost all of a language model's compute is matrix multiplication. The lecture says no other operation in deep learning costs as much, for large matrices. Adding two m by n matrices costs m × n FLOPs. A matrix product costs far more.
Multiply A, with m rows and k columns, by B, with k rows and n columns. The result C has m by n entries. Each entry is a sum over k: for every index triple (row, inner, column) there is one multiply and one add.
C equals two times m times k times n.
Count the triples: m times k times n. Each triple is one multiply and one add, so double it.
[1024 × 4096] @ [4096 × 4096]: C = 2 × 1,024 × 4,096 × 4,096 = 34,359,738,368, about 3.4 × 10¹⁰ FLOPs. At the H100's dense bf16 peak of 989.5 TFLOP/s, that is 34.7 µs.
The boxes are A, B and C, drawn to scale. The bars are the time at peak on each chip; the outline is the time at 50% of peak. Drag the sizes.
Peaks from NVIDIA datasheets: H100 SXM 989.5 TFLOP/s bf16 dense (1,979 with sparsity) and 67 TFLOP/s float32; A100 312 TFLOP/s bf16. Times at peak are a lower bound.
The lecture's linear model makes this general. Its input is B points of size D, and its weight is D by K. The forward pass is 2 × B × D × K FLOPs: 2 × (number of tokens) × (number of parameters). That holds for Transformers too, to a first approximation.
How close do you get to the peak? Model FLOPs utilization, or MFU, is the FLOP/s you achieve divided by the peak FLOP/s. With a made-up timing of 70 µs, the product above runs at 4.9 × 10¹⁴ FLOP/s, an MFU of 0.50. The lecture rates 0.5 or more as good.
Symptom: your timer says a matmul ran faster than the GPU's peak.
Measure: CUDA calls return at once and the GPU works in the background, so the timer saw only the launch.
Fix: call torch.cuda.synchronize() before you start the timer and before you stop it, as the lecture's time_matmul does.
Chapter 4
Count the two matmuls every weight needs on the way back, and get 6 FLOPs per parameter per token
The forward pass gives a loss. The backward pass gives each weight's gradient: how much the loss changes when that weight moves a little. Mark a tensor with requires_grad=True and PyTorch's autograd records each operation; loss.backward() walks the record in reverse with the chain rule.
python x = torch.tensor([1., 2, 3]) w = torch.tensor([1., 1, 1], requires_grad=True) loss = 0.5 * (x @ w - 5).pow(2) # x @ w = 6, loss = 0.5 loss.backward() assert torch.equal(w.grad, torch.tensor([1., 2, 3])) # (6 - 5) * x
What does backward cost? Take the lecture's model. The input x holds B points of width d. Then w1 (d by d) makes h1, w2 (d by K) makes h2, and a loss follows. Forward is two matmuls: 2Bd² + 2BdK. For w2, backward needs two matmuls of the same size: one for w2.grad and one for h1.grad, which the layer below needs.
The chain runs from x to the loss. Each press runs the next matmul: forward to the right, backward to the left. The bars add up the FLOPs.
The lecture's CPU sizes: B = 1,024, d = 256, K = 64. The device counts FLOPs; it does not time them. The lecture counts x.grad too, so every layer counts as if a layer sat below it.
Every weight costs 2 FLOPs per token forward and 4 backward: 6 in total. Call the parameters N and the training tokens D. The training compute is:
C equals six times N times D.
Each token meets each of the N parameters once forward (2 FLOPs) and twice backward (4 FLOPs). Multiply 6 by N by D.
The device: N = 256 × 256 + 256 × 64 = 81,920, and a step sees 1,024 points. One step is 6 × 81,920 × 1,024 = 503,316,480 FLOPs. Question 1: 6 × 70 × 10⁹ × 15 × 10¹² = 6.3 × 10²⁴ FLOPs.
Kaplan et al. (2020) use the same rule for Transformers. It counts only the weight matmuls. Attention scores add a term that grows with context length, small when the context is short next to the model width.
Symptom: the loss jumps around after a few steps, and gradient norms grow every step.
Measure: call backward twice on the same batch: w.grad doubles. PyTorch adds new gradients to old ones.
Fix: clear gradients after each step: optimizer.zero_grad(set_to_none=True), as the lecture's loop does.
Chapter 5
Scale random weights so signals keep their size, and count a Transformer's weights from its width and depth
A parameter in PyTorch is an nn.Parameter: a tensor that autograd and the optimizer track. How you fill it matters. Draw each weight from a standard normal, multiply an input of size d by it, and each output is a sum of d random terms.
Call the input size d, the spread of each weight σ (its standard deviation), and the variance of the input Var(x). The variance of each output is:
Var of y equals d times sigma squared times Var of x.
Each output adds d products of a weight and an input. Independent variances add, so multiply d by σ² by Var(x). To keep Var(y) equal to Var(x), set σ² to 1/d.
The lecture's d = 16,384 with σ = 1: Var(y) = 16,384, a spread of √16,384 = 128. Our torch run measured 128.5. Divide the weights by √d = 128 and the spread is 1.00.
Each bar is the spread of the activations after one layer, on a log scale. The yellow line is a spread of 1. Switch the scale, the width and the depth.
Illustrative toy, computed live: 32 random inputs through linear layers with no activation function, fresh random weights per layer, seeded.
With σ = 1 and d = 64, each layer multiplies the spread by about √64 = 8. After 12 layers it is about 8¹², near 7 × 10¹⁰: the values overflow and gradients blow up. The lecture's fix is the scale 1/√d, which is Xavier initialization up to a constant. It also truncates the normal to [−3, 3] to rule out outliers.
Now count. A Transformer block has four d by d attention matrices and two feed-forward matrices of d by 4d: 4d² + 8d² = 12d². Call the number of blocks L:
P is about twelve times L times d squared.
One block holds 12 matrices' worth of d by d weights. Multiply by d² for the block, then by L for the stack.
GPT-2 small: L = 12, d = 768. P = 12 × 12 × 768² = 84.9 million. Add token embeddings (50,257 × 768 = 38.6 million) and positions (0.8 million): 124.3 million, against the released 124 million.
Symptom: the loss is NaN or inf at the first step.
Measure: print each layer's activation spread at initialization. Growth near √d per layer means unscaled weights.
Fix: draw weights with standard deviation 1/√din, truncated, as the lecture's Linear does.
Chapter 6
Add up weights, gradients and the optimizer's state, and see what fits on a GPU
SGD moves each weight against its gradient: w ← w − η × g, with a learning rate η. It keeps no extra state. Better optimizers remember the past, and each memory is a full tensor the size of the weights.
The lecture builds the family in four lines. Momentum is SGD plus a running average of gradients. AdaGrad (Duchi et al., 2011) divides by the running sum of squared gradients. RMSProp is AdaGrad with an exponential average instead of a sum. Adam (Kingma and Ba, 2015) is RMSProp plus momentum: two states per weight, m and v. AdamW (Loshchilov and Hutter, 2019) changes only how it applies weight decay.
python # the lecture's AdaGrad step, for one parameter p (state: g2, same shape as p) g2 = state.get("g2", torch.zeros_like(grad)) g2 += torch.square(grad) p.data -= lr * grad / torch.sqrt(g2 + 1e-5)
Call the bytes per weight bw, per gradient bg, and for the optimizer state bs. The memory that does not depend on the batch is:
M equals b-w plus b-g plus b-s, all times N.
Add the bytes each parameter needs for its weight, its gradient and its optimizer state. Multiply by N.
Question 2: AdamW in float32 is 4 + 4 + 8 = 16 bytes. Eight H100s hold 8 × 80 GB = 640 GB, so N = 640 × 10⁹ / 16 = 40 billion parameters, before any activations.
The bar is one GPU's share of the static memory; the yellow line is its 80 GB. Choose an optimizer and a precision, drag the model size, then add GPUs.
Static memory only; activations come on top. "Sharded" splits every tensor evenly across the GPUs, as ZeRO stage 3 does (Rajbhandari et al., 2019). Plain data parallelism keeps a full copy on every GPU.
Mixed precision does not save this memory. The lecture's caveat: bf16 weights and gradients (2 + 2), a float32 master copy (4) and Adam (8) still make 16 bytes. It is faster, not smaller. Activations, the values saved for backward, come on top and grow with batch size and sequence length. The lecture's toy keeps B × d × L of them.
Symptom: "CUDA out of memory" at the first optimizer.step(), after forward and backward ran fine.
Measure: PyTorch's Adam creates m and v on its first step: 8 more bytes per parameter appear at once.
Fix: plan with 16 bytes per parameter from the start, or shard the state. ZeRO over 64 GPUs puts a 70B model's 1,120 GB at 17.5 GB per GPU.
Chapter 7
Divide the FLOPs by what the GPUs deliver, and see why the forward pass runs in bf16
Chapter 4 gave the work; Chapter 3 gave the speed. Time is one divided by the other. Call the number of GPUs G, each GPU's peak F in FLOP/s, and the utilization u (the MFU).
t equals six N D, divided by G times F times u.
Find the FLOPs the run needs: 6 × N × D. Find the FLOP/s the cluster delivers: G × F × u. Divide the first by the second.
Question 1: 6.3 × 10²⁴ FLOPs over 1,024 × 989.5 × 10¹² × 0.5 = 5.07 × 10¹⁷ FLOP/s gives 1.24 × 10⁷ seconds: 144 days.
Each bar is the run's days at one dtype's H100 peak, on a log scale. The yellow line is two weeks. Pick a run, then drag GPUs and utilization.
Dense peaks from the H100 SXM datasheet: 67 TFLOP/s float32, 989.5 bf16, 1,979 fp8 (half the "with sparsity" figures). The small run is d = 2,048, L = 24, a 32,000-token vocabulary: 1.27B parameters.
The H100 does bf16 matmuls 14.8 times faster than float32 ones. The small run takes 6.7 days in bf16 and 99 in float32. That is why mixed precision (Micikevicius et al., 2018) exists. The lecture's plan: run the forward pass, and so the activations, in bf16 or fp8. Keep the parameters and gradients in float32, so small updates are not lost (Chapter 2).
python with torch.autocast(device_type="cuda", dtype=torch.bfloat16): loss = model(x, y) # matmuls in bf16, activations stored in bf16 loss.backward() # gradients land on the float32 parameters optimizer.step() # the update happens in float32
Symptom: a run takes twice as long as planned.
Measure: check which peak you used. The datasheet's large bf16 number, 1,979 TFLOP/s, assumes sparse matrices. Question 1 at that peak says 72 days.
Fix: use the dense peak, half the sparsity figure, for dense training.
Chapter 8
Train the lecture's linear model in your browser, count every step, and break it on purpose
Every training loop is the same five lines: get a batch, run forward to a loss, run backward, step the optimizer, clear the gradients. The lecture trains a linear model with 16 weights on data from the line y = x · (0, 1, …, 15). The device runs that loop live.
Left: the loss of each batch, log scale. Right: the learned weights (purple) against the true ones (teal). Press Play, then change one thing and run again.
Illustrative, computed live: the lecture's train_loop (D = 16, mean squared error, weights drawn as randn / √16), 200 steps at most. The seed fixes the weights and every batch.
Things to try. Seed 0, B = 4, learning rate 0.01: the 10th batch's loss is 1,126, down from 2,326; at step 200 it is 0.62. Raise the rate to 0.1 and the loss is 0.011 by step 50. At 0.2 it never settles: at step 200 the loss is still near 1,000. With B = 1 at 0.1 it diverges, because one example per step is too noisy for that rate. Press Reset with the same seed and the run repeats exactly.
The counters are this lesson in miniature. Each step costs 6 × B × 16 FLOPs. Memory is 4 bytes for each weight, gradient and state: 128 bytes with SGD, 192 with AdaGrad. AdaGrad needs a rate near 3 here, because its step shrinks as squared gradients pile up.
python data = np.memmap("tokens.npy", dtype=np.int32) # read lazily: LLaMA's data is 2.8 TB torch.manual_seed(0); np.random.seed(0); random.seed(0) # all three, for a run you can repeat for step in range(num_steps): x = get_batch(data, B, T) # random windows of T tokens x = x.pin_memory().to("cuda", non_blocking=True) # copy while the GPU works loss = model(x) # forward: 2 N FLOPs per token loss.backward() # backward: 4 N FLOPs per token optimizer.step() # reads the state: 16 bytes per parameter optimizer.zero_grad(set_to_none=True) if step % 1000 == 0: # runs crash: save model AND optimizer state torch.save({"model": model.state_dict(), "optimizer": optimizer.state_dict()}, "ckpt.pt")
Symptom: you tune the learning rate and nothing changes.
Measure: print optimizer.param_groups[0]["lr"]. The lecture's own train() takes an lr argument but builds SGD(..., lr=0.01), so its 0.1 run trains at 0.01.
Fix: pass the argument through, and log the rate the optimizer uses.
Chapter 9
Keep the formulas, the napkin code, the checks, and where the accounting goes next
A training run spends two things. Memory is values times bytes: 16 bytes per parameter for weights, gradients and AdamW state, plus activations. Compute is 6 FLOPs per parameter per token, and time is that divided by GPUs, peak and utilization.
| Quantity | Formula | Example |
|---|---|---|
| Tensor memory | values × bytes per value | [4096, 4096] float32: 67.1 MB |
| Machine epsilon | 2−m | bf16: 0.0078; 1 + 0.001 rounds to 1 |
| Matmul FLOPs | 2 × m × k × n | [1024 × 4096] @ [4096 × 4096]: 3.4 × 10¹⁰ |
| MFU | achieved FLOP/s ÷ peak FLOP/s | 0.5 or more is good |
| Training FLOPs | 6 × N × D | 70B on 15T tokens: 6.3 × 10²⁴ |
| Block parameters | 12 × L × d² | GPT-2 small: 84.9M (124M with embeddings) |
| Static memory | (4 + 4 + 8) × N for AdamW | 8 H100s: at most 40B parameters |
| Time | 6ND ÷ (G × F × u) | Question 1: 144 days on 1,024 H100s |
The napkin, as code. Every number on this page comes out of these four lines.
python H100_BF16 = 1979e12 / 2 # datasheet: 1,979 with sparsity, dense is half def train_flops(N, D): return 6 * N * D def days(N, D, gpus, mfu=0.5): return train_flops(N, D) / (gpus * H100_BF16 * mfu * 86400) def max_params(gpus, gb=80, bytes_per_param=4 + 4 + (4 + 4)): return gpus * gb * 1e9 / bytes_per_param assert round(days(70e9, 15e12, 1024)) == 144 assert max_params(8) == 40e9
torch.cuda.memory_allocated() after the first optimizer step.non_blocking=True.Now teach it: press Present or Teach. Derive 6 × N × D from two matmuls per weight, and 16 bytes from AdamW's state. Then go back to the run planner and find the largest model 32 H100s can train in two weeks before you drag there.