TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Memory, Mixed Precision and Multiple Devices

Memory, Mixed Precision and Multiple Devices

"CUDA out of memory" is the error that ends more training runs than any bug. To fix it without guessing, you need to know where the memory goes. During training a device holds four things: the weights, their gradients, the optimizer state, and the activations that the forward pass saves for the backward pass. The first three scale with the number of parameters, the last with the batch size and the depth. This lesson puts numbers on each, measures them on a real model, and then walks through the standard remedies: gradient accumulation, activation checkpointing, lower precision, and spreading the model state over several devices.

All recordings ran on a CPU, where memory is plentiful; the amounts are the same on a GPU, which is where they matter.

The memory budget

For a model with PP parameters trained with Adam in float32:

M≈4P⏟weights+4P⏟gradients+8P⏟Adam m, v+A(B)⏟activations=16P+A(B) bytesM \approx \underbrace{4P}_{\text{weights}} + \underbrace{4P}_{\text{gradients}} + \underbrace{8P}_{\text{Adam } m,\, v} + \underbrace{A(B)}_{\text{activations}} = 16P + A(B) \ \text{bytes}

Adam keeps two running averages per parameter, the first and second moments, so the optimizer alone needs twice the memory of the weights; SGD with momentum needs one copy, plain SGD none. Mixed precision with bf16 or float16 (mixed precision) stores 2-byte weights and gradients but keeps a 4-byte float32 master copy of the weights for the update, so the model state stays at 2+2+4+8=162 + 2 + 4 + 8 = 16 bytes per parameter. Its savings are in the activations and in speed, not in the model state.

The activations are what autograd saves to compute the gradients. For a stack of linear layers of widths h1,…,hLh_1, \dots, h_L on input dimension dd with CC classes, a batch of BB examples in bb-byte numbers saves roughly

A(B)≈B(d+∑l=1Lhl+C)bA(B) \approx B \left( d + \sum_{l=1}^{L} h_l + C \right) b

that is, every layer's output for every example. For convolutional and transformer models the same principle holds with larger per-example terms (a feature map per channel, a T×dT \times d matrix per token sequence, plus the T×TT \times T attention weights per head). Two rules follow: the activations grow linearly with the batch size, and they grow with the depth, so a deep network at a large batch is dominated by activations, while a large model at a small batch is dominated by its parameters.

float32 + Adam weights 4grads 4Adam 8 16 B/param bf16 mixed + Adam w 2g 2master 4Adam 8 16 B/param ZeRO-1, 8 devices w 2g 2 5.5 B/param ZeRO-2, 8 devices w 2 3.75 B/param ZeRO-3, 8 devices 2 B/param weightsgradientsfloat32 masterAdam moments activations come on top: batch size x activations per example

A calculator in NumPy

python · try it yourself
import numpy as np

GiB = 2**30
# bytes per parameter: weights, gradients, float32 master copy, optimizer state
RECIPES = {
    "float32, SGD":            (4, 4, 0, 0),
    "float32, SGD + momentum": (4, 4, 0, 4),
    "float32, Adam":           (4, 4, 0, 8),
    "bf16 mixed, Adam":        (2, 2, 4, 8),
}
P = 7e9                                            # a 7-billion-parameter model
print("model state for 7e9 parameters:")
for name, b in RECIPES.items():
    print(f"  {name:24s} {sum(b):2d} bytes/param  {P * sum(b) / GiB:6.1f} GiB")

# ZeRO / FSDP: shard parts of the mixed-precision Adam state over N devices
N = 8
stages = {"DDP (replicated)": (2, 2, 12),
          "ZeRO-1 (optimizer)": (2, 2, 12 / N),
          "ZeRO-2 (+ gradients)": (2, 2 / N, 12 / N),
          "ZeRO-3 / FSDP (+ weights)": (2 / N, 2 / N, 12 / N)}
print(f"per device with N = {N}:")
for name, b in stages.items():
    print(f"  {name:26s} {sum(b):5.2f} bytes/param  {P * sum(b) / GiB:6.1f} GiB")

# activations of the MLP 64-512-512-512-512-10 measured in the next example (float32)
widths = [512] * 4
per_example = 64 + sum(widths) + 10 + 2           # input, 4 ReLU outputs, log-softmax, int64 label
for B in (64, 256, 1024):
    print(f"batch {B:4d}: activations {B * per_example * 4 / 2**20:5.2f} MiB")
state_bytes = 826378 * 16                           # weights + grads + Adam, float32
print("batch size where activations equal the model state:", int(np.ceil(state_bytes / (per_example * 4))))
model state for 7e9 parameters:
  float32, SGD              8 bytes/param    52.2 GiB
  float32, SGD + momentum  12 bytes/param    78.2 GiB
  float32, Adam            16 bytes/param   104.3 GiB
  bf16 mixed, Adam         16 bytes/param   104.3 GiB
per device with N = 8:
  DDP (replicated)           16.00 bytes/param   104.3 GiB
  ZeRO-1 (optimizer)          5.50 bytes/param    35.9 GiB
  ZeRO-2 (+ gradients)        3.75 bytes/param    24.4 GiB
  ZeRO-3 / FSDP (+ weights)   2.00 bytes/param    13.0 GiB
batch   64: activations  0.52 MiB
batch  256: activations  2.07 MiB
batch 1024: activations  8.30 MiB
batch size where activations equal the model state: 1557

A 7-billion-parameter model needs 104.3 GiB just for weights, gradients and Adam state, before a single activation: no single GPU of today holds that. Plain SGD halves it to 52.2 GiB, one reason memory-saving optimizers (Adafactor, 8-bit Adam) exist. Data parallelism (data parallelism and all-reduce) replicates the full 16 bytes per parameter on every device, so it does not help at all with model size; sharding does. Splitting the optimizer state across 8 devices (ZeRO stage 1) brings each device down to 35.9 GiB, sharding the gradients as well (stage 2) to 24.4 GiB, and sharding the weights too (stage 3, which PyTorch implements as FSDP) to 13.0 GiB, one eighth of the total. The last three lines predict the activations of the model measured next, and the batch size at which they would equal its model state: 1557.

Measured on a real model

The next example builds an MLP with four hidden layers of 512 units (826 378 parameters), measures the weights, the gradients after backward() and Adam's state after one step(), and counts the bytes autograd saves for backward with torch.autograd.graph.saved_tensors_hooks, a hook that sees every tensor as it is saved.

python · try it yourself
import torch
from torch import nn

def nbytes(tensors):
    return sum(t.numel() * t.element_size() for t in tensors)

def make(width=512, depth=4):
    layers, d = [], 64
    for _ in range(depth):
        layers += [nn.Linear(d, width), nn.ReLU()]
        d = width
    return nn.Sequential(*layers, nn.Linear(d, 10))

def saved_bytes(model, x, y):
    """Bytes autograd keeps for the backward pass, counted as each tensor is saved."""
    params = {p.data_ptr() for p in model.parameters()}
    seen = {}
    def pack(t):
        if t.data_ptr() not in params:                 # weights are saved too, but already counted
            seen[t.data_ptr()] = t.numel() * t.element_size()   # each storage once
        return t
    with torch.autograd.graph.saved_tensors_hooks(pack, lambda t: t):
        loss = nn.functional.cross_entropy(model(x), y)
    return sum(seen.values()), loss

torch.manual_seed(0)
model = make()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
P = sum(p.numel() for p in model.parameters())
print(f"parameters {P}  -> weights {nbytes(model.parameters()) / 2**20:.2f} MiB (float32)")
x, y = torch.randn(64, 64), torch.randint(0, 10, (64,))
act, loss = saved_bytes(model, x, y)
loss.backward(); opt.step()
print(f"gradients      {nbytes(p.grad for p in model.parameters()) / 2**20:.2f} MiB")
state = [t for s in opt.state.values() for t in s.values() if t.dim() > 0]
print(f"Adam state     {nbytes(state) / 2**20:.2f} MiB (exp_avg + exp_avg_sq)")
for B in (64, 256, 1024):
    a, _ = saved_bytes(model, torch.randn(B, 64), torch.randint(0, 10, (B,)))
    print(f"batch {B:4d}: saved activations {a / 2**20:6.2f} MiB = {a / B / 4:.0f} floats per example")
parameters 826378  -> weights 3.15 MiB (float32)
gradients      3.15 MiB
Adam state     6.30 MiB (exp_avg + exp_avg_sq)
batch   64: saved activations   0.52 MiB = 2124 floats per example
batch  256: saved activations   2.07 MiB = 2124 floats per example
batch 1024: saved activations   8.30 MiB = 2124 floats per example

The prediction is exact: 3.15 MiB of weights, the same again for the gradients, twice that for Adam, and 2124 saved numbers per example, which is 64+4⋅512+10=212264 + 4 \cdot 512 + 10 = 2122 plus the int64 label (8 bytes, counted as 2 four-byte floats). The activations grow from 0.52 MiB at batch 64 to 8.30 MiB at batch 1024, still below the 12.6 MiB of model state; past a batch of about 1557 they would dominate. The hook also excludes the weights themselves, which nn.Linear saves for its backward pass but which are already counted. On a GPU, torch.cuda.memory_allocated() and torch.cuda.max_memory_allocated() give the same totals for a real run, and torch.cuda.memory_summary() breaks them down.

Fitting a big batch into small memory

Gradient accumulation. If KK micro-batches of equal size each give a mean loss Lˉk\bar{L}_k, the mean over the whole batch is Lˉ=1K∑k=1KLˉk\bar{L} = \frac{1}{K} \sum_{k=1}^{K} \bar{L}_k, and because gradients are linear,

∇Lˉ=∑k=1K∇(LˉkK)\nabla \bar{L} = \sum_{k=1}^{K} \nabla \left( \frac{\bar{L}_k}{K} \right)

So calling (loss / K).backward() on each micro-batch, without zeroing in between, accumulates exactly the gradient of the big batch, with the activations of one micro-batch at a time. (Batch normalisation is the exception: it computes its statistics per micro-batch.)

Activation checkpointing. Instead of saving every activation, save only the inputs of selected blocks and recompute the forward pass of a block during backward. For LL layers in L\sqrt{L} segments, memory falls from O(L)O(L) to O(L)O(\sqrt{L}) for about one extra forward pass, roughly a third more compute. torch.utils.checkpoint.checkpoint(block, x, use_reentrant=False) does it for one block.

Lower precision. torch.autocast runs matrix multiplications in bf16 or float16 while keeping the weights and numerically sensitive operations in float32, which halves the activation memory of those layers and is much faster on GPUs with tensor cores. The full story, including loss scaling for float16, is in mixed precision; here is only what it looks like.

python · try it yourself
import torch
from torch import nn
from torch.utils.checkpoint import checkpoint

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, 10))
x, y = torch.randn(64, 64), torch.randint(0, 10, (64,))
loss_fn = nn.CrossEntropyLoss()

def grads():
    return torch.cat([p.grad.flatten() for p in model.parameters()])

model.zero_grad()
loss_fn(model(x), y).backward()                    # one batch of 64
g_full = grads()

model.zero_grad()
for xb, yb in zip(x.split(16), y.split(16)):       # 4 micro-batches of 16
    (loss_fn(model(xb), yb) / 4).backward()        # divide: mean over the 4 means
g_acc = grads()
print(f"accumulated vs full batch: max difference {(g_acc - g_full).abs().max().item():.1e}, "
      f"relative {((g_acc - g_full).norm() / g_full.norm()).item():.1e}")

model.zero_grad()
for xb, yb in zip(x.split(16), y.split(16)):
    loss_fn(model(xb), yb).backward()              # forgot the / 4
print(f"without / 4 the gradient is {(grads().norm() / g_full.norm()).item():.2f} times too large")

def saved(fn):
    seen = {}
    params = {p.data_ptr() for p in model.parameters()}
    def pack(t):
        if t.data_ptr() not in params:
            seen[t.data_ptr()] = t.numel() * t.element_size()
        return t
    with torch.autograd.graph.saved_tensors_hooks(pack, lambda t: t):
        out = fn()
    return out, sum(seen.values())

body, head = model[:4], model[4]
model.zero_grad()
loss, plain = saved(lambda: loss_fn(model(x), y))
loss.backward(); g_plain = grads()
model.zero_grad()
loss, ckpt = saved(lambda: loss_fn(head(checkpoint(body, x, use_reentrant=False)), y))
loss.backward(); g_ckpt = grads()
print(f"saved for backward: plain {plain // 1024} KiB, checkpointed body {ckpt // 1024} KiB")
print("checkpointed gradients equal:", torch.equal(g_plain, g_ckpt))

with torch.autocast("cpu", dtype=torch.bfloat16):
    logits = model(x)
    loss_bf = loss_fn(logits, y)
print("autocast: logits", logits.dtype, "| loss", loss_bf.dtype, "| weights stay", model[0].weight.dtype)
print(f"loss float32 {loss_fn(model(x), y).item():.4f}  bf16 autocast {loss_bf.item():.4f}")
accumulated vs full batch: max difference 7.5e-09, relative 1.1e-07
without / 4 the gradient is 4.00 times too large
saved for backward: plain 147 KiB, checkpointed body 83 KiB
checkpointed gradients equal: True
autocast: logits torch.bfloat16 | loss torch.float32 | weights stay torch.float32
loss float32 2.3277  bf16 autocast 2.3277
  • Accumulation is exact up to rounding: four micro-batches of 16 give the gradient of the batch of 64 with a largest difference of 7.5e-09 (relative 1.1×10−71.1 \times 10^{-7}, the precision of float32). Forgetting the division by KK makes the gradient exactly 4.00 times too large, which acts like a four times larger learning rate.
  • Checkpointing gives identical gradients (torch.equal is True, bit for bit) while the saved activations drop from 147 KiB to 83 KiB: the two hidden ReLU outputs of the body (128 KiB) are no longer stored, only the body's input (16 KiB) and output (64 KiB) plus the head's few KiB. The price is running the body's forward pass twice.
  • Autocast changes the computation, not the model: inside the context the logits are bfloat16, the loss (autocast runs cross-entropy in float32) and the weights stay float32. Here the loss agrees to four decimals, 2.3277 in both. On a CPU, bf16 is mainly a way to test code; the speed and memory gains appear on accelerators.

Several devices: DataParallel, DDP, FSDP

When one device is not enough, either for speed or for memory, there are three standard tools in PyTorch. Their mechanics are taught in data parallelism and all-reduce (with a from-scratch all-reduce), model parallelism, and DDP and checkpointing (a real DDP run with torchrun, verified against a single process); this table puts them side by side with the memory view of this lesson.

nn.DataParallel DistributedDataParallel (DDP) FullyShardedDataParallel (FSDP) / ZeRO-3
processes one process, one thread per GPU one process per GPU one process per GPU
model state per device full replica full replica, 16 bytes per parameter with Adam one 1/N1/N shard, plus the layer being computed
gradient exchange gathered on GPU 0 every step all-reduce, overlapped with backward reduce-scatter of gradients, all-gather of weights per layer
scales to several machines no yes yes
status legacy, not recommended the default for models that fit on one device for models whose state does not fit

DDP gives each process its own data shard (DistributedSampler) and averages gradients during backward(), so every replica takes the same step: it buys speed, not memory. FSDP and DeepSpeed's ZeRO stages remove the redundancy in the replicas: each device stores only its shard of the optimizer state (stage 1), the gradients (stage 2) and the weights (stage 3), and gathers a layer's full weights just before computing it. The calculator above showed the effect: 16, 5.5, 3.75 and 2 bytes per parameter on 8 devices. The cost is communication, which is why stage 3 needs fast interconnects. Beyond that, tensor and pipeline parallelism split single layers and the layer sequence across devices (model parallelism).

Pitfalls

  • Counting only the weights. Training with Adam needs four times the weight memory before activations; inference needs only the weights.
  • Raising the batch size until it fits. Activations scale with it; if the model state alone does not fit, no batch size will. Accumulate gradients instead.
  • Accumulation without dividing the loss by KK, or zeroing the gradients inside the accumulation loop.
  • Checkpointing layers with randomness. Dropout inside a checkpointed block must draw the same mask in the recomputation; torch.utils.checkpoint restores the RNG state by default (preserve_rng_state=True), so do not turn that off.
  • Mixed precision expecting smaller optimizer memory. The float32 master weights and Adam moments remain; the savings are in activations and speed.
  • Using nn.DataParallel for new code. Use DDP, or FSDP when the model state does not fit on one device.

Practice

  1. A model has 350 million parameters and is trained with SGD with momentum in float32. How much memory does the model state need? And with Adam in bf16 mixed precision?
Answer

SGD with momentum: 4+4+4=124 + 4 + 4 = 12 bytes per parameter, 350×106⋅12=4.2×109350 \times 10^6 \cdot 12 = 4.2 \times 10^9 bytes, about 3.9 GiB. Adam with mixed precision: 16 bytes per parameter, 5.6×1095.6 \times 10^9 bytes, about 5.2 GiB, plus activations in both cases.

  1. The MLP of the recording saves 2124 floats per example. At batch 1024 with checkpointing of all four hidden layers as one block, roughly how many floats per example are saved?
Answer

Only the block's input (64) and output (512), plus the logits for the loss (10) and the label (2): about 588 floats per example, instead of 2124. During the backward pass, the block's internal activations exist again temporarily while it is recomputed.

  1. You want an effective batch of 256 but only 64 fit. Write the training step with gradient accumulation, and say what happens to batch normalisation.
Answer
python
K = 4
optimizer.zero_grad()
for k, (xb, yb) in enumerate(micro_batches):      # 4 batches of 64
    loss = loss_fn(model(xb), yb) / K
    loss.backward()
optimizer.step()

Batch norm still normalises with the statistics of each micro-batch of 64, so it does not behave exactly like a batch of 256; layer norm or group norm are unaffected.

Test yourself

How many bytes per parameter does float32 training with Adam need for weights, gradients and optimizer state?

  1. 4
  2. 8
  3. 12
  4. 16

Which quantity grows linearly with the batch size?

  1. The weights
  2. The Adam state
  3. The activations saved for backward
  4. The gradients

Four micro-batches of 16 replace one batch of 64. Which loss should you call backward() on in each micro-step?

  1. loss
  2. loss * 4
  3. loss / 4
  4. loss / 64

What does ZeRO stage 3 / FSDP shard across NN devices that DDP replicates?

  1. Only the data
  2. Only the optimizer state
  3. The optimizer state, the gradients and the weights
  4. The activations