Dive into Deep Learning · §13.4
Memory Hierarchy, Precision, and Checkpointing
parameter & activation budgets · mixed precision (bf16/tf32) · activation checkpointing · gradient accumulation
Motivation
fp32 weights (4N), gradients (4N), and Adam moments (8N) leave only 8.9\text{ GiB} on a 24\text{ GiB} RTX 4090.Parameter Memory
The memory occupied by model parameters, gradients, and optimizer state depends only on parameter count N, optimizer choice, and precision—never on batch size:
| Optimizer & Precision Configuration | Stored Arrays per Parameter | Bytes / Param | 1.01B GPT State |
|---|---|---|---|
Plain SGD (float32) |
Weight (4\text{ B}) + Gradient (4\text{ B}) | 8\text{ B} | 7.5\text{ GiB} |
SGD + Momentum (float32) |
Weight + Gradient + Velocity (4\text{ B}) | 12\text{ B} | 11.3\text{ GiB} |
Adam / AdamW (float32) |
Weight + Gradient + 1st & 2nd Moments (8\text{ B}) | 16\text{ B} | 15.1\text{ GiB} |
Adam, Mixed Precision (bf16) |
All four in fp32 (16\text{ B}) + bf16 weight copy (2\text{ B}) |
18\text{ B} | 17.0\text{ GiB} |
1.01 billion parameters, 16N = 15.1 GiB
Activation Memory
Backpropagation Storage
Per-Token Tally
fp32).fp32 log-probs (212\text{ KiB/tok}), plus whatever excess \Delta the measured peak shows above this count.Autograd Storage Hook
By attaching torch.autograd.graph.saved_tensors_hooks and taking differences between 1 and 2 sequences and between 1 and 2 blocks, we isolate the exact bytes saved per token by one block (a) and by the output head (a_{\textrm{out}}):
one block: 149 KiB per token (18.7 fp32 values of width d)
embedding, output layer, and loss: 212 KiB per token
scaled_dot_product_attention, RMSNorm, and F.silu as single fused kernels, each block stores the theoretical minimum of 18.7d = 149\text{ KiB/token}.Memory Budget
Combining the fixed parameter state (16N bytes when gradients persist across micro-batches) with L blocks of a bytes/token and output head a_{\textrm{out}} bytes/token yields the total memory budget for n tokens:
M(n) \;\approx\; 16N \;+\; n\,(L a + a_{\textrm{out}}) \;\le\; M_{\textrm{GPU}}
Peak Memory vs. Tally
Measuring actual peak memory (torch.cuda.max_memory_allocated) across 1{,}024 to 8{,}192 tokens on a 2-block GPT reveals an extra \Delta \approx 393\text{ KiB/token} above the saved-activation tally:
1024 tokens: peak 1.53 GiB above the weights
2048 tokens: peak 1.77 GiB above the weights
4096 tokens: peak 3.53 GiB above the weights
8192 tokens: peak 7.06 GiB above the weights
2048 to 4096 tokens: measured 905 KiB per token; counted 511 KiB
4096 to 8192 tokens: measured 903 KiB per token; counted 511 KiB
backward(), while all forward activations and the V saved log-probabilities are still live, the cross-entropy backward pass materializes two float32 gradient tensors of width V = 50{,}257 (for log-probabilities and logits: 2 \times 4V = 8V \approx 393\text{ KiB/token}).Allocator Trace
Recording every CUDA caching-allocator event across one Adam step on 4{,}096 tokens visualizes the sawtooth lifecycle of activations and gradients:
Mixed Precision
bfloat16 (2\text{ B}): Doubles Tensor Core throughput to 165\text{ TFLOP/s} and cuts per-block activation storage by \sim 40\%.float32 (4\text{ B}): Prevents small updates (\eta g \sim 10^{-5}w) from rounding to zero and preserves RMSNorm, residual, and cross-entropy accuracy.bfloat16 shares the 8-bit exponent of float32 (\sim 10^{\pm 38} range).Precision & Capacity
In bfloat16 mixed precision, the two residual-stream inputs per block remain in float32 (4\text{ B}) while the other 18 of the \sim 20d saved vectors drop to bfloat16 (2\text{ B}), predicting (2 \cdot 4 + 18 \cdot 2) / (20 \cdot 4) = 0.55 of the float32 block activation size:
one block: 87 KiB per token in bf16, 0.58 of fp32
embedding, output layer, and loss: 306 KiB per token
bfloat16 weight copies during the step raises fixed parameter memory from 16N = 15.1\text{ GiB} to 18N = 17.0\text{ GiB} (shrinking activation headroom from 8.9 \to 7.0\text{ GiB}), and the large float32 loss log-probabilities (a_{\textrm{out}}) do not shrink.Precision & Throughput
Mixed precision is primarily a speed optimization. Benchmarking one SGD step of a compute-bound 3-layer width-8192 MLP (1.1 \times 10^{12}\text{ FLOPs/step}; compute floor 13.3\text{ ms} at 82.6\text{ TFLOP/s} and 6.7\text{ ms} at 165.2\text{ TFLOP/s}, plus 1.3\text{ ms} for the fp32 SGD update) separates Tensor Core execution from 16-bit operands:
fp32: 23.15 ms, 48 TFLOP/s
tf32: 15.01 ms, 73 TFLOP/s
bf16: 9.68 ms, 114 TFLOP/s
fp32 \to Tensor Core tf32 (1.45\times): Same 82.6\text{ TFLOP/s} theoretical ceiling and 32-bit storage, but Tensor Core tile instructions reach \sim 90\% utilization vs. \sim 60\% on scalar ALUs.tf32 \to bf16 (1.5\text{--}1.75\times): Matmul time halves to \sim 6.7\text{ ms}, while the bandwidth-bound fp32 SGD update (1.3\text{ ms}) and weight casts remain constant.Activation Checkpointing
\textrm{Peak/tok} \;=\; L \cdot 4d \;+\; a \;+\; a_{\textrm{out}} \;+\; \Delta
fp32 input at each of the L = 18 block boundaries (18 \times 8\text{ KiB} = \mathbf{144\text{ KiB/tok}}, down from 2.7\text{ MiB/tok}).Capacity Comparison
Evaluating M(n) \le 24\text{ GiB} for our 18-block, 1B-parameter GPT shows how checkpointing transforms activation capacity:
fp32, count : 2.83 MiB per token, room for 3,229 tokens
fp32, measured : 3.22 MiB per token, room for 2,844 tokens
bf16, measured : 2.21 MiB per token, room for 3,272 tokens
fp32, checkpointing: 0.88 MiB per token, room for 10,435 tokens
bf16, checkpointing: 0.91 MiB per token, room for 7,956 tokens
bf16 fits slightly fewer tokens than fp32 because its extra 2N = 1.9\text{ GiB} of bf16 weight copies outweigh the 60\text{ KiB/token} saved on the single currently recomputed block.Checkpointing Benchmark
On a 4-block stack (d = 2048 in float32), checkpointing stores only the 4 block inputs plus the final output (5 \times 4d = 40\text{ KiB/token}):
checkpointing=False: stores 606 KiB per token, peak 1.25 GiB, 47 ms per step
checkpointing=True : stores 40 KiB per token, peak 0.42 GiB, 59 ms per step
Targeted Recomputation
Once per-block checkpointing reduces all 18 blocks to 144\text{ KiB/token}, two refinements target the remaining bottlenecks:
mm outputs and recomputing only cheap elementwise ops saves significant memory for almost zero extra FLOPs.Gradient Accumulation
\frac{t_{\textrm{accumulator traffic}}}{t_{\textrm{micro-batch compute}}} \;=\; \frac{12N / \beta}{6Nn / P} \;=\; \frac{2 I^*}{n}
Accumulation Benchmark
Splitting 4{,}096 tokens on our 2-block GPT into m = 4 micro-batches of 1{,}024 tokens reproduces the exact full-batch gradient while cutting activation memory fourfold:
1 x 4096 tokens: peak 3.53 GiB above the weights, 83 ms per step (83 to 83), device busy 83 ms
matrix products 69 ms, other kernels 13 ms
4 x 1024 tokens: peak 1.92 GiB above the weights, 99 ms per step (99 to 99), device busy 99 ms
matrix products 74 ms, other kernels 25 ms
Check Your Understanding
Apply the memory and timing formulas of this section to two design questions for our 18-block, 1B-parameter GPT (d = 2048, bf16 ridge I^* = 164\text{ FLOP/byte}):
bfloat16. Micro-batches of 2 sequences (n = 2{,}048 tokens, m = 256) fit without checkpointing, whereas 4 sequences (n = 4{,}096 tokens, m = 128) require per-block checkpointing (\sim 25\% recomputation overhead). Which recipe finishes the global step faster?Answers:
Key Takeaways
| Technique / Component | Effect on Step Memory M(n) | Time / Compute Cost | When to Use It |
|---|---|---|---|
| Fixed Adam State | 16N\text{ B} (fp32), 18N\text{ B} (bf16) |
Fixed per step | Baseline parameter + gradient + 2 moment buffers |
| Block Activations (a) | \approx 20d values/token (160\text{ KiB} fp32) |
Baseline forward/backward | Linear inputs (4d) + attn (4d) + SwiGLU (11d) |
bf16 Mixed Precision |
Block activations \times 0.6, state +2N | 1.5\text{--}1.75\times faster | Always on Tensor Core GPUs (no loss scaling needed) |
| Block Checkpointing | Block storage La \to L \cdot 4d + a | +25\text{--}33\% step time | When useful micro-batch n does not fit in M_{\textrm{GPU}} |
| Chunked Cross-Entropy | Eliminates V-wide a_{\textrm{out}} + 8V peak | +3\% FLOPs (2dV) | When vocab V dominates checkpointed memory |
| Gradient Accumulation | Runs B_{\textrm{global}} = m \, B_{\textrm{micro}} in M(B_{\textrm{micro}}) | +\frac{2I^*}{n} accumulator traffic | To reach large global batches on limited GPUs |