PyTorch & Resource Accounting

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.

Fit and time a training run

70B
15T
1,024

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

The Budget Problem

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.

Turn GPU time into FLOPs

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.

8
14 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.

The road

  1. Tensors: memory is the number of values times the bytes per value.
  2. Dtypes: exponent bits buy range, mantissa bits buy precision.
  3. Matmul FLOPs: 2 × m × k × n, and how close you get to peak.
  4. Backward: twice the forward, so training costs 6 × N × D.
  5. Parameters: initialize with 1/√d, and count 12 × L × d².
  6. Optimizer: AdamW keeps 16 bytes per parameter.
  7. Time: divide the FLOPs by GPUs, peak and utilization.
  8. Showcase: run the lecture's training loop and break it.
  9. Field guide: the table, the code and the checks.
A friend says "our GPUs do 1015 FLOPs". What is wrong with the sentence?

Chapter 1

Tensors: Values Times Bytes

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:

Say it aloud

M equals n times b.

M
M the tensor's memory, in bytes.
n
n the number of values: multiply the sizes of all dimensions.
b
b bytes per value: 4 for float32, 2 for bf16, 1 for fp8.
In plain words

Multiply the shape's sizes to get n. Look up b for the dtype. Multiply n by b to get M.

With numbers

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.

Find an element in storage

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.

2
3

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.

A weight matrix of shape [4096, 4096] is stored in float32. How much memory does it take?

Chapter 2

Dtypes: Range Against Precision

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.

DtypeBytesExponent, mantissaLargestSmallest normalStep near 1
float3248, 233.4 × 10³⁸1.2 × 10⁻³⁸1.2 × 10⁻⁷
float1625, 1065,5046.1 × 10⁻⁵0.00098
bfloat1628, 73.4 × 10³⁸1.2 × 10⁻³⁸0.0078
fp8 E4M314, 34480.0160.125
fp8 E5M215, 257,3446.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.

Round one number five ways

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.

1e−8

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:

Say it aloud

Epsilon equals two to the minus m.

ε
epsilon the step from 1 to the next number the dtype holds. A change smaller than half of it rounds away.
2
two the base: each mantissa bit halves the step.
−m
minus m m is the number of mantissa bits: 23, 10, 7, 3 or 2.
In plain words

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 ε.

With numbers

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).

Why does 10−8 survive in bfloat16 but become 0 in float16?

Chapter 3

Matmul FLOPs and the Peak

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.

Say it aloud

C equals two times m times k times n.

C
C the FLOPs of one matrix product.
2
two one multiply and one add per triple.
m
m rows of A: in a model, the tokens in the batch.
k
k the inner size, shared by A's columns and B's rows.
n
n columns of B.
In plain words

Count the triples: m times k times n. Each triple is one multiply and one add, so double it.

With numbers

[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.

Price one matrix product

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.

1,024
4,096
4,096

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.

A feed-forward block maps 8 × 512 tokens from width 1,024 to 4,096 and back. How many FLOPs do its two forward matmuls cost?

Chapter 4

The Backward Pass Costs Twice the Forward

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.

Step the forward and backward passes

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:

Say it aloud

C equals six times N times D.

C
C the total training FLOPs.
6
six 2 FLOPs per parameter per token forward, plus 4 backward (2 for the weight's gradient, 2 for the input's).
N
N the number of parameters.
D
D the number of training tokens.
In plain words

Each token meets each of the N parameters once forward (2 FLOPs) and twice backward (4 FLOPs). Multiply 6 by N by D.

With numbers

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.

Where does the 6 in 6 × N × D come from?

Chapter 5

Parameters: Initialize, Then Count

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:

Say it aloud

Var of y equals d times sigma squared times Var of x.

Var(y)
var of y the variance of one output: its spread, squared.
d
d the input size: how many terms each output adds.
σ2
sigma squared the variance of each weight. torch.randn gives 1.
Var(x)
var of x the variance of each input value.
In plain words

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.

With numbers

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.

Stack layers, watch the spread

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.

12 layers

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:

Say it aloud

P is about twelve times L times d squared.

P
P the parameters in the Transformer blocks, without embeddings, biases or norms.
12
twelve 4 for the attention matrices (query, key, value, output) plus 8 for the two feed-forward matrices.
L
L the number of blocks (layers).
d2
d squared the model width times itself.
In plain words

One block holds 12 matrices' worth of d by d weights. Multiply by d² for the block, then by L for the stack.

With numbers

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.

Why divide random weights by √din?

Chapter 6

The Optimizer Keeps 16 Bytes per Parameter

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:

Say it aloud

M equals b-w plus b-g plus b-s, all times N.

M
M the static training memory in bytes, before activations.
bw
b-w bytes per weight: 4 in float32.
bg
b-g bytes per gradient: 4 in float32.
bs
b-s bytes of optimizer state per weight: 0 for SGD, 4 for momentum or AdaGrad, 8 for Adam's m and v.
N
N the number of parameters.
In plain words

Add the bytes each parameter needs for its weight, its gradient and its optimizer state. Multiply by N.

With numbers

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.

Stack the memory on one GPU

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.

7.0B

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.

A 7B-parameter model trains with AdamW, everything in float32. How much static memory does it need?

Chapter 7

Time on the Clock, and Mixed Precision

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).

Say it aloud

t equals six N D, divided by G times F times u.

t
t the training time in seconds; divide by 86,400 for days.
6ND
six N D the training FLOPs from Chapter 4.
G
G the number of GPUs.
F
F one GPU's peak FLOP/s for the dtype the matmuls use.
u
u the utilization (MFU): the share of the peak you achieve, about 0.5.
In plain words

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.

With numbers

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.

Time a run in three dtypes

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.

1,024
50%

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.

Why does mixed precision run the forward pass in bf16 but update float32 weights?

Chapter 8

Showcase: Run the Training Loop

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.

Train 16 weights

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.

0.01

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

Field Guide

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.

QuantityFormulaExample
Tensor memoryvalues × bytes per value[4096, 4096] float32: 67.1 MB
Machine epsilon2−mbf16: 0.0078; 1 + 0.001 rounds to 1
Matmul FLOPs2 × m × k × n[1024 × 4096] @ [4096 × 4096]: 3.4 × 10¹⁰
MFUachieved FLOP/s ÷ peak FLOP/s0.5 or more is good
Training FLOPs6 × N × D70B on 15T tokens: 6.3 × 10²⁴
Block parameters12 × L × d²GPT-2 small: 84.9M (124M with embeddings)
Static memory(4 + 4 + 8) × N for AdamW8 H100s: at most 40B parameters
Time6ND ÷ (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

Before a run

  1. Does it fit? 16 bytes per parameter, plus activations. Check torch.cuda.memory_allocated() after the first optimizer step.
  2. Does it finish? 6ND ÷ (G × F × u), with a measured u and the dense peak.
  3. Can you repeat it? Seed torch, numpy and Python's random.
  4. Is the GPU waiting for data? Use memmap, pinned memory and non_blocking=True.
  5. Can you resume? Save and load the model and the optimizer state, then check the loss continues.

Keep going

Read next

The habit. Before you change a model, ask two questions: how many bytes per parameter does this add, and how many FLOPs per token?
You have 8 H100s for two weeks at 50% MFU. Which plan is honest?

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.

PyTorch & Resource Accounting · Stanford CS336, Lecture 2
Previous: Overview and Tokenization · Next: Architectures and Hyperparameters · Course site · Back to Gleams