Memory and Precision

Dive into Deep Learning · §13.4

Memory Hierarchy, Precision, and Checkpointing
parameter & activation budgets · mixed precision (bf16/tf32) · activation checkpointing · gradient accumulation

A 1B-Parameter GPT Fills 15 of 24 GiB Before Any Data

Motivation

  • Fixed parameter state (16N = 15.1\text{ GiB}): On a 18-block, 1B GPT, fp32 weights (4N), gradients (4N), and Adam moments (8N) leave only 8.9\text{ GiB} on a 24\text{ GiB} RTX 4090.
  • Per-token activations (\sim 3\text{--}4\text{ MiB/tok}): Retaining 18 blocks of forward activations fits only 2–3 sequences of 1{,}024 tokens per micro-batch.
  • Closing the batch gap: Reaching 0.5\text{M+} token global batches requires mixed precision, activation checkpointing, and gradient accumulation.

Fixed Training State: 16 Bytes per Parameter in Adam

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 Lifecycle: Peak at Backward Pass Start

Activation Memory

  • Forward accumulation, backward release: Each forward layer stashes activations needed by its backward VJP; during backpropagation, each layer consumes and frees its saved activations as it materializes parameter gradients.
  • Where memory peaks: Total allocated memory reaches its maximum right at the transition from the forward loss to the start of the backward pass.

Three Differentiation Rules Govern Saved Activations

Backpropagation Storage

  • Linear layer (\mathbf{Y} = \mathbf{X}\mathbf{W}): Must save input \mathbf{X} because the weight gradient \nabla_{\mathbf{W}}\mathcal{L} = \mathbf{X}^\top(\nabla_{\mathbf{Y}}\mathcal{L}) multiplies by \mathbf{X}.
  • Elementwise nonlinearity (\mathbf{y} = f(\mathbf{x})): Saves \mathbf{x} (or \mathbf{y}) to evaluate the derivative f'(\mathbf{x}).
  • Hadamard product (\mathbf{z} = \mathbf{p} \odot \mathbf{q}): Saves both \mathbf{p} and \mathbf{q}, which is why SwiGLU alone stores four hidden vectors (\approx 10.7d values/token).

Tallying a Transformer Block: ~20d Values per Token

Per-Token Tally

  • Norms & Attention (8d\text{--}9d): Two RMSNorms + residual inputs save 4d, while fused FlashAttention saves \mathbf{Q}, \mathbf{K}, \mathbf{V}, \mathbf{O} (4d\text{--}5d, avoiding T \times T).
  • SwiGLU FFN (\approx 10.7d): Saves gate \mathbf{g}, \textrm{SiLU}(\mathbf{g}), up \mathbf{u}, and their product at width \frac{8}{3}d, bringing each block to a \approx 18.7d\text{--}20d (149\text{--}160\text{ KiB/tok} in fp32).
  • Output head (a_{\textrm{out}} + \Delta): Final norm, V fp32 log-probs (212\text{ KiB/tok}), plus whatever excess \Delta the measured peak shows above this count.

Verifying Saved Bytes: 18.7d per Fused Block

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
  • Exact match to theory: Because PyTorch runs 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}.

The Step Memory Budget on a 24 GiB GPU

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}}

  • Fixed parameter floor (N = 1.01 \times 10^9): 16N = 15.1\text{ GiB}, leaving only M_{\textrm{GPU}} - 16N = \mathbf{8.9\text{ GiB}} for activations and backward temporaries on a 24\text{ GiB} RTX 4090.
  • Maximum micro-batch token count (L = 18 blocks): At La + a_{\textrm{out}} \approx 2.8\text{--}4.3\text{ MiB/token}, at most 2{,}000\text{--}3{,}200 tokens (2 or 3 sequences of length 1{,}024) can fit in a single micro-batch.
  • Doubling depth to 36 blocks (N = 1.92\text{B}): Fixes 16N = 28.6\text{ GiB} > 24\text{ GiB}—not even a single token fits without sharding the 16N state across multiple GPUs (§13.7).

Measured Peak Memory: The 8V Cross-Entropy Excess

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
  • Where the extra 393\text{ KiB/token} comes from: At the very start of 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}).

Allocation Timeline Across Forward, Backward, and Step

Allocator Trace

Recording every CUDA caching-allocator event across one Adam step on 4{,}096 tokens visualizes the sawtooth lifecycle of activations and gradients:

  • Three distinct phases: Memory starts at 12N (weights + two Adam moments), climbs staircase-fashion across the blocks during the forward pass, spikes at the logits and initial backward loss gradients, steps down as activations are freed, and briefly allocates temporaries during the optimizer step.

Mixed Precision: Master fp32 State with bf16 Compute

Mixed Precision

  • Linear & Attention Matmuls in bfloat16 (2\text{ B}): Doubles Tensor Core throughput to 165\text{ TFLOP/s} and cuts per-block activation storage by \sim 40\%.
  • Master State & Reductions in 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.
  • No loss scaling needed: bfloat16 shares the 8-bit exponent of float32 (\sim 10^{\pm 38} range).

bf16 Cuts Block Activations by 40% but Adds 2N State

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
  • Why total token capacity barely grows (\sim 15\text{--}25\%): Caching 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.

Tensor Core Speedup: Scalar fp32 vs. tf32 vs. bf16

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
  • Scalar 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.
  • Tensor Core 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: O(L) Inputs, One Block Live

Activation Checkpointing

\textrm{Peak/tok} \;=\; L \cdot 4d \;+\; a \;+\; a_{\textrm{out}} \;+\; \Delta

  • Forward pass: Stores only the 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}).
  • Backward pass: Re-runs block \ell’s forward pass just before backpropagating through block \ell, keeping only 1 block’s internal activations (a) live at a time for \le 33\% extra FLOPs.

Token Capacity Across Precision and Checkpointing

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
  • More than 3\times larger micro-batches: Per-block checkpointing expands capacity from \sim 2{,}800 tokens to \sim 10{,}000\text{--}15{,}000 tokens.
  • Surprising interaction: Under full per-block checkpointing, 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.

Measuring Checkpointing: 40 KiB/Token and +25% Time

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
  • Exact storage & modest overhead: Saved bytes drop to the exact 40\text{ KiB/token} prediction, peak memory falls sharply, and step time increases by only \sim 25\% (below the 33\% FLOP bound because fused backward kernels absorb elementwise recomputation).

Selective Recomputation and Chunked Cross-Entropy Loss

Targeted Recomputation

Once per-block checkpointing reduces all 18 blocks to 144\text{ KiB/token}, two refinements target the remaining bottlenecks:

  • Selective recomputation (Korthikanti et al., 2022): Matrix multiplications take most of a block’s FLOPs while elementwise ops (SwiGLU’s \sim 5d activated gate and product, or unfused T \times T attention scores) take most of its activation bytes. Caching mm outputs and recomputing only cheap elementwise ops saves significant memory for almost zero extra FLOPs.
  • Chunked output projection & cross-entropy loss: Because the output logits and loss (a_{\textrm{out}} + \Delta \approx 605\text{ KiB/token}) now use 4\times more memory per token than all 18 checkpointed blocks combined, evaluating the output projection and cross-entropy on chunks of 1{,}024 tokens inside a checkpoint eliminates the V-wide spike for only 2dV / (6N) \approx 3\% extra FLOPs.

Gradient Accumulation and the 2I*/n Traffic Overhead

Gradient Accumulation

\frac{t_{\textrm{accumulator traffic}}}{t_{\textrm{micro-batch compute}}} \;=\; \frac{12N / \beta}{6Nn / P} \;=\; \frac{2 I^*}{n}

  • Reaching large global batches (B_{\textrm{global}} = m\,B_{\textrm{micro}}): Sums \frac{1}{m}\nabla\mathcal{L}_i across m sequential micro-batches of n tokens before stepping Adam once.
  • The 2I^*/n traffic tax: Each micro-batch reads old grads (4N), new grads (4N), and writes their sum (4N); always use the largest micro-batch n that fits without extra checkpointing.

Measuring Accumulation: Halved Peak, Exact Gradients

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
  • Peak memory & step time: Peak memory above the weights drops by roughly half (to the 4N = 0.77\text{ GiB} persistent gradient buffer plus 1{,}024 tokens of activations), and step time increases by \sim 10\text{--}18\% as predicted by 2I^*/n.

Concept Check: Memory Budgets, Remat, and Accumulation

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}):

  1. Suppose we want a global batch of 524{,}288 tokens on one 24\text{ GiB} RTX 4090 in 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?
  2. At 6N\text{ FLOPs/token} and 165\text{ TFLOP/s} peak, what is the minimum compute time of one 524{,}288-token global step on a single RTX 4090?

Answers:

  1. 2 sequences without checkpointing (m = 256) is faster: Its accumulator overhead is \frac{2 I^*}{n} = \frac{2 \times 164}{2048} \approx \mathbf{16\%}, whereas 4 sequences with checkpointing pays 8\% accumulator overhead plus \sim 25\% recomputation (\approx \mathbf{33\%} total overhead). Never turn on checkpointing if a large enough micro-batch already fits.
  2. 6 \times (1.01 \times 10^9) \times 524{,}288 \approx 3.18 \times 10^{15}\text{ FLOPs/step}, taking at least \ge 19.2\text{ s/step} at 100\% peak (\sim 22\text{ s} with accumulation), or over 25 days for 100{,}000 steps. One GPU can hold the step, but finishing the run requires multiple GPUs.

Summary: Memory Breakdown and Optimization Techniques

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