Fitting More in Memory: Mixed Precision and Gradient Accumulation
Where training memory goes, how fp16 and bf16 trade range for precision, what autocast keeps in 32-bit and what it halves (measured), why fp16 needs a gradient scaler and in what order to scale, unscale, clip and step, and how gradient accumulation gives a large effective batch when only a small one fits.
Contentsand lesson path
On this page
- Why it matters
- Range and precision of 16-bit formats
- Mixed precision with autocast
- fp16 and the gradient scaler
- Gradient accumulation and clipping
- Check your understanding
- Apply it
- Review prompt
Lessons of Efficient PyTorch Training
- Lab: Feeding the GPU with Custom Datasets and DataLoaders Lab · 25 min
- Fitting More in Memory: Mixed Precision and Gradient Accumulation Concept · 20 min
- Worked Example: Checkpoint, Crash, Resume Worked example · 20 min
- Lab: Profile a Slow Training Loop and Fix It Lab · 30 min
- Lab: From One GPU to Several with DistributedDataParallel Lab · 25 min
- Check: Speed, Memory and Repeatability Knowledge check · 10 questions
What you will learn
- Use mixed precision, gradient accumulation and gradient clipping to train larger models or batches within a fixed GPU memory budget.
Prerequisites: Deep Learning Fundamentals
01. Why it matters
Training runs out of GPU memory long before it runs out of ideas. Four things share that memory. The weights and their gradients take one number each per parameter. The optimizer state adds more: AdamW keeps two running averages per parameter. The activations are the intermediate results of the forward pass that autograd saves because the backward pass needs them; they grow with batch size and input size, and for large batches they are often the biggest item.
This lesson covers three tools for a fixed budget: mixed precision, which stores and computes many tensors with 16-bit numbers; gradient accumulation, which builds the gradient of a large batch from small ones; and gradient clipping, which stops a rare huge gradient from wrecking the weights. The examples run on a CPU; on a GPU only the device string changes. Memory figures are measured by the scripts.
02. Range and precision of 16-bit formats
A floating-point number has an exponent, which sets its range (how large or small it can be), and a mantissa, which sets its precision (how many significant digits it keeps). The standard 32-bit format, fp32, has 8 exponent bits and 23 mantissa bits. The two 16-bit formats split their bits differently: fp16 has 5 exponent bits and 10 mantissa bits, bf16 (brain float) has 8 exponent bits and only 7 mantissa bits. torch.finfo shows what that means.
import torch
print(f"{'dtype':9} {'bytes':>5} {'largest':>10} {'smallest normal':>16} {'eps':>10}")
for dtype in (torch.float32, torch.float16, torch.bfloat16):
f = torch.finfo(dtype)
name = str(dtype).replace("torch.", "")
print(f"{name:9} {f.bits // 8:5d} {f.max:10.3g} {f.tiny:16.3g} {f.eps:10.3g}")
values = torch.tensor([1e-8, 70000.0, 1.001])
for dtype in (torch.float16, torch.bfloat16):
shown = ", ".join(f"{v:.6g}" for v in values.to(dtype).float().tolist())
print(f"1e-8, 70000 and 1.001 stored as {str(dtype)[6:]}: {shown}")python formats.pydtype bytes largest smallest normal eps
float32 4 3.4e+38 1.18e-38 1.19e-07
float16 2 6.55e+04 6.1e-05 0.000977
bfloat16 2 3.39e+38 1.18e-38 0.00781
1e-8, 70000 and 1.001 stored as float16: 0, inf, 1.00098
1e-8, 70000 and 1.001 stored as bfloat16: 1.00117e-08, 70144, 1fp16 keeps more digits (eps, the gap after 1.0, is about 0.001) but covers a narrow range: the largest value is 65,504 and normal numbers stop at about 6e-5, with less precise subnormal numbers down to about 6e-8, so 70,000 becomes inf and 1e-8 becomes 0. bf16 has the same range as fp32, so both values survive, but with only about two to three significant digits: 70,000 is stored as 70,144 and 1.001 rounds to 1. Neither format is safe for everything. Adding a small update to a large weight, or summing thousands of values, needs more precision than either keeps, which is why mixed precision keeps those operations in fp32.
03. Mixed precision with autocast
torch.autocast is a context manager that picks a precision per operation. Inside it, matrix multiplications and convolutions run in the 16-bit type you choose, because they tolerate it and, on GPUs with tensor cores, run much faster in it. Operations that need range or precision, such as reductions, softmax and most losses, run in fp32. The weights themselves stay in fp32: autocast casts a 16-bit copy on the fly for each operation, and the optimizer updates the fp32 master weights, so small updates are not rounded away.
The script measures what that saves. A saved-tensors hook is a function that autograd calls for every tensor it stores for the backward pass, so summing their sizes gives the activation memory of one forward pass.
"""Bytes that autograd saves for the backward pass: fp32 versus autocast."""
import torch
from torch import nn
def saved_bytes(model, x, autocast):
total = 0
def pack(t): # called for every tensor that autograd keeps for backward
nonlocal total
total += t.numel() * t.element_size()
return t
with torch.autograd.graph.saved_tensors_hooks(pack, lambda t: t):
with torch.autocast("cpu", dtype=torch.bfloat16, enabled=autocast):
out = model(x)
return total, out
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(512, 2048), nn.GELU(), nn.Linear(2048, 512))
x = torch.randn(2048, 512)
for autocast in (False, True):
total, out = saved_bytes(model, x, autocast)
label = "autocast bf16" if autocast else "plain fp32 "
print(f"{label}: saved {total / 2**20:5.2f} MiB, "
f"output {out.dtype}, weights {model[0].weight.dtype}")
params = sum(p.numel() for p in model.parameters())
print(f"parameters: {params:,} -> weights + grads + AdamW state in fp32: "
f"{params * 16 / 2**20:.1f} MiB")python saved_memory.pyplain fp32 : saved 40.00 MiB, output torch.float32, weights torch.float32
autocast bf16: saved 20.00 MiB, output torch.bfloat16, weights torch.float32
parameters: 2,099,712 -> weights + grads + AdamW state in fp32: 32.0 MiBUnder autocast the tensors saved for backward shrink from 40 MiB to 20 MiB, because the layer inputs and hidden activations are now stored with 2 bytes per number. The output is bf16, but the weights are still fp32, and so are their gradients and the AdamW state: for this model the 16 bytes per parameter (4 for the weight, 4 for its gradient, 8 for the two AdamW averages) stay at 32 MiB. Mixed precision therefore mainly buys room for larger batches and longer inputs; to shrink the per-parameter memory you need other tools, such as sharding the optimizer state across GPUs, covered in the DistributedDataParallel lab.
On a GPU you write torch.autocast("cuda", dtype=torch.bfloat16). bf16 needs fairly recent hardware (NVIDIA Ampere or later; torch.cuda.is_bf16_supported() tells you), while fp16 runs on older GPUs too, at the price of the extra step in the next section.
04. fp16 and the gradient scaler
Gradients can be tiny: in a detection network from the mixed-precision training paper, many activation-gradient values fell below the range of fp16. In fp16 such values lose digits or become exactly zero, and a weight whose gradient is zero stops learning. Loss scaling multiplies the loss by a large factor before backward(), so every gradient is multiplied by the same factor (the chain rule is linear in the loss) and moves into the range fp16 can hold. The gradients are divided by the factor again, in fp32, before the optimizer uses them.
"""Why fp16 needs loss scaling: a tiny gradient, with and without a scale factor."""
import torch
w = torch.ones(3, dtype=torch.float16, requires_grad=True)
x = torch.tensor([1e-3, 1e-4, 1e-5], dtype=torch.float16)
for scale in (1.0, 1024.0):
w.grad = None
loss = (w * x).sum() * 1e-3 # a loss whose gradient is x * 1e-3
(loss * scale).backward()
unscaled = w.grad.float() / scale # unscale in fp32, as GradScaler does
stored = [f"{g:.3g}" for g in w.grad.float().tolist()]
print(f"scale {scale:4.0f}: stored in fp16 {stored}")
print(f" unscaled in fp32 {[f'{g:.3g}' for g in unscaled.tolist()]}")
print("true gradient: ", [f"{g:.3g}" for g in (x.float() * 1e-3).tolist()])python scaler.pyscale 1: stored in fp16 ['1.01e-06', '1.19e-07', '0']
unscaled in fp32 ['1.01e-06', '1.19e-07', '0']
scale 1024: stored in fp16 ['0.00103', '0.000102', '1.03e-05']
unscaled in fp32 ['1e-06', '1e-07', '1e-08']
true gradient: ['1e-06', '1e-07', '1e-08']Without scaling, the third gradient is 0 and the second keeps barely one digit. With a factor of 1,024, all three come back to their true values after unscaling. A fixed factor is fragile, though: too small and gradients still underflow, too large and they overflow to inf. torch.amp.GradScaler adapts it. It starts high, and whenever it finds an inf or NaN gradient it skips that optimizer step and halves the factor; after a long run of good steps (2,000 by default) it doubles it again. The order of calls matters: scale the loss and call backward(), then unscale_ so that the gradients are true values, then clip, then scaler.step, then scaler.update.
"""The GradScaler recipe, run with fp16 autocast on the CPU."""
import torch
from torch import nn
torch.manual_seed(0)
model = nn.Linear(8, 1)
opt = torch.optim.SGD(model.parameters(), lr=0.1)
scaler = torch.amp.GradScaler("cpu", init_scale=2.0**18)
x, y = torch.randn(32, 8), torch.randn(32, 1)
for step in range(1, 6):
opt.zero_grad()
with torch.autocast("cpu", dtype=torch.float16):
loss = nn.functional.mse_loss(model(x), y)
scaler.scale(loss).backward() # gradients are now multiplied by the scale
scaler.unscale_(opt) # divide by the scale; also checks for inf and NaN
norm = nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
before = model.weight.detach().clone()
scaler.step(opt) # skips the update if any gradient is inf or NaN
scaler.update() # halves the scale after an overflow
moved = not torch.equal(before, model.weight)
print(f"step {step}: loss {loss.item():.4f}, grad norm {norm.item():7.3f}, "
f"weights updated {moved}, next scale {scaler.get_scale():.0f}")python scaler_loop.pystep 1: loss 1.2498, grad norm inf, weights updated False, next scale 131072
step 2: loss 1.2498, grad norm inf, weights updated False, next scale 65536
step 3: loss 1.2498, grad norm inf, weights updated False, next scale 32768
step 4: loss 1.2498, grad norm 1.607, weights updated True, next scale 32768
step 5: loss 1.1056, grad norm 1.280, weights updated True, next scale 32768The starting factor of 262,144 is too large for this model: the fp16 gradients overflow, the norm is inf, and the scaler skips the update and halves the factor, three times in a row. At 32,768 the gradients fit and training proceeds, with the loss unchanged until then because no update happened. A few skipped steps at the start of an fp16 run are normal. A scale that keeps falling for hundreds of steps points to a real problem, such as a learning rate that is too high. With bf16 the range problem does not arise, which is why bf16 training usually runs without a scaler.
05. Gradient accumulation and clipping
Sometimes the batch size you want does not fit in memory at all. Gradient accumulation uses the fact that backward() adds to .grad instead of replacing it. You run several small micro-batches, call backward() on each, and step the optimizer only after the last one, so the update uses the sum of their gradients. With a loss that averages over its batch, as most do, the sum is too large by the number of micro-batches, so each loss is divided by that number first. The script checks the arithmetic against one batch of 64.
"""Gradient accumulation: four micro-batches of 16 versus one batch of 64."""
import torch
from torch import nn
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(10, 32), nn.ReLU(), nn.Linear(32, 1))
x, y = torch.randn(64, 10), torch.randn(64, 1)
loss_fn = nn.MSELoss() # mean over the batch
def grads():
return torch.cat([p.grad.flatten() for p in model.parameters()])
model.zero_grad()
loss_fn(model(x), y).backward()
full = grads()
for divide in (False, True):
model.zero_grad()
for xb, yb in zip(x.split(16), y.split(16)): # 4 micro-batches
loss = loss_fn(model(xb), yb)
(loss / 4 if divide else loss).backward() # .grad adds up across calls
acc = grads()
print(f"divide by 4: {divide!s:5} ratio to full batch {(acc / full).mean():.3f}, "
f"max difference {(acc - full).abs().max():.1e}")
# An uneven split: 64 rows as micro-batches of 24, 24 and 16
model.zero_grad()
for xb, yb in zip(x.split(24), y.split(24)):
(loss_fn(model(xb), yb) / 3).backward()
print(f"sizes 24/24/16, divide by 3: max diff {(grads() - full).abs().max():.1e}")
model.zero_grad()
for xb, yb in zip(x.split(24), y.split(24)):
(loss_fn(model(xb), yb) * len(xb) / len(x)).backward() # weight by size
print(f"sizes 24/24/16, weight by size: max diff {(grads() - full).abs().max():.1e}")python accum.pydivide by 4: False ratio to full batch 4.000, max difference 2.0e+00
divide by 4: True ratio to full batch 1.000, max difference 6.0e-08
sizes 24/24/16, divide by 3: max diff 8.2e-02
sizes 24/24/16, weight by size: max diff 6.0e-08Without the division, the accumulated gradient is exactly four times the full-batch one, as if the learning rate had been multiplied by four. With it, the two agree to rounding error (about 1e-7). The uneven split shows a trap: when micro-batches have different sizes, dividing each mean by the number of micro-batches gives the small one too much weight. Weighting each loss by its share of the rows restores the full-batch gradient. Layers that compute statistics over the batch, such as batch normalisation, still see only one micro-batch at a time, so accumulation is not identical to a large batch for them.
Gradient clipping with clip_grad_norm_ measures the norm (overall length) of all gradients together and, if it exceeds max_norm, scales them all down by the same factor, so the direction of the update is kept. It returns the norm before clipping, which is worth logging. The next script combines everything for a typical step: bf16 autocast, four micro-batches per update, and clipping before each optimizer step.
"""One optimizer step per 4 micro-batches, with bf16 autocast and clipping."""
import torch
from torch import nn
torch.manual_seed(0)
X = torch.randn(1024, 20)
Y = (X[:, :5].sum(1, keepdim=True) > 0).float()
model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Linear(64, 1))
opt = torch.optim.AdamW(model.parameters(), lr=1e-2)
accum_steps, micro = 4, 32 # effective batch: 4 x 32 = 128 rows per update
step = 0
opt.zero_grad()
for i, (xb, yb) in enumerate(zip(X.split(micro), Y.split(micro)), start=1):
with torch.autocast("cpu", dtype=torch.bfloat16): # use "cuda" on a GPU
logits = model(xb)
loss = nn.functional.binary_cross_entropy_with_logits(logits.float(), yb)
(loss / accum_steps).backward()
if i % accum_steps == 0:
norm = nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
opt.step()
opt.zero_grad()
step += 1
if step in (1, 2, 4, 8):
print(f"update {step}: last micro-batch loss {loss.item():.3f}, "
f"grad norm before clipping {norm.item():.3f}")
print(f"{i} micro-batches -> {step} optimizer updates")python recipe.pyupdate 1: last micro-batch loss 0.703, grad norm before clipping 0.285
update 2: last micro-batch loss 0.680, grad norm before clipping 0.274
update 4: last micro-batch loss 0.600, grad norm before clipping 0.300
update 8: last micro-batch loss 0.555, grad norm before clipping 0.285
32 micro-batches -> 8 optimizer updatesThirty-two micro-batches become eight optimizer updates, each over an effective batch of 128 rows, while only 32 rows are in memory at a time. The gradient norms stay near 0.3, below the limit of 1.0, so clipping never changes an update here; it is insurance against the rare spike that would otherwise throw the weights far off. Two details to carry into your own loops: a learning-rate scheduler should step once per optimizer update, not per micro-batch, and the logged loss is the last micro-batch, not the mean of the effective batch.
06. Check your understanding
07. Apply it
In your practice package:
- Add a
precisionsetting (fp32,bf16,fp16) and anaccum_stepssetting to the config, and implement the step order fromscaler_loop.pyandrecipe.py, using a scaler only for fp16. - Log the gradient norm before clipping and, for fp16, the current scale.
- On a GPU, record samples per second and
torch.cuda.max_memory_allocated()for fp32 and bf16 at the same effective batch; on a CPU, record the saved-tensor memory as insaved_memory.py. Check that the validation metric stays within a small tolerance.
08. Review prompt
Without looking back, list the four things that use memory during training and which of them autocast shrinks; explain range and precision for fp16 and bf16 with one example value each; describe how loss scaling rescues small gradients and what GradScaler does after an overflow; give the order of scale, backward, unscale, clip, step and update; and explain how to scale micro-batch losses, including the case of uneven micro-batches.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.