Activation memory: checkpointing, gradient accumulation and offloading
Activations rather than weights are often what does not fit in GPU memory. We examine what autograd saves for backward and three ways to reduce it: recomputation (full, √n, binomial and selective checkpointing), dividing the batch into microbatches with correctly normalized gradient accumulation, and moving tensors to CPU with overlapping transfers. All are applied to a GPT that does not fit in 8 GB until these methods are used.
After this lesson you can
- Prove the O(√n) activation-memory bound for segmented checkpointing and its recomputation cost.
- Calculate an optimal checkpoint schedule with dynamic programming for heterogeneous costs.
- Implement token-normalized gradient accumulation that exactly reproduces a large batch.
- Apply full and selective checkpointing, accumulation and offloading to a GPT on the available GPU, record hardware and experimental budget, and measure memory and throughput.
- Identify dangerous interactions: dropout with recomputation and batch normalization with accumulation.
Before you start
Store less without changing the function
Activation memory grows with microbatch size and sequence length. Autograd saves what backward needs: for example, multiplication needs operands and a nonlinear function may need its input or output. Reducing these allocations does not change parameters or automatically divide work between GPUs. Recomputation, accumulation, and CPU offloading change where and when the bytes are paid for.
Whether activations dominate depends on architecture, length, optimizer, and kernel. Some models have states larger than their activations. Measure the peak and actual allocations before choosing a solution. The memory anatomy from the first lesson helps distinguish states, activations, and temporaries.
A chain and its boundaries
Activation checkpointing retains segment inputs, discards their intermediates, and reruns each segment during backward. It is not a training checkpoint on disk. The recomputed function must be equivalent to the first evaluation, including random state and side effects.
For homogeneous layers, divide the chain into segments of approximately length. Retain boundaries during forward and reconstruct one segment at a time in backward. If each activation occupies one unit, there are boundaries and temporary activations, giving a peak of . The continuous minimum of occurs at , by differentiation or the arithmetic-geometric mean inequality. For integer sizes use segments as balanced as possible. Each layer runs at most once more under this strategy, so recomputation costs at most one full forward pass. This bound counts only activations of a homogeneous chain, not weights, gradients, buffers, or kernel temporaries. It is the tradeoff of Chen et al..
With even tighter memory, prefixes can be reconstructed multiple times. The checkpoint schedule decides what to retain and reevaluate under a budget. The binomial Revolve algorithm handles a chain under specific assumptions about steps and memory: it is not necessarily optimal on a graph with branches, heterogeneous sizes, or asynchronous transfers. A dynamic-programming scheduler must define its cost and memory model before claiming optimality.
With very few boundaries, a strategy can return to the beginning and run a prefix before each backward step: it saves states but repeats early layers many times. A binomial schedule distributes saved points and reconstruction cycles to use available space. The tradeoff need not be just one additional forward pass. Adding memory never worsens the best cost within the same model, since any schedule feasible under a small budget remains feasible under a larger one.
Lab: manual backward and recomputation
In this 64-layer chain, each state has the same shape. The count measures activation units, not the peak of a real allocator. We keep all boundaries until the end for a conservative bound, and also count the full local stack although its first state already appears among the boundaries. Derivatives of the same objective are compared layer by layer. The seed and matrices are the same across strategies.
import numpy as np
def normal(x, weights):
states = [x]
for w in weights:
states.append(np.tanh(states[-1] @ w))
g = 2*states[-1]/states[-1].size
grad = [None]*len(weights)
for i in range(len(weights)-1, -1, -1):
dz = g*(1-states[i+1]**2)
grad[i] = states[i].T @ dz
g = dz @ weights[i].T
return states[-1], grad, len(states)
def checkpointed(x, weights, cuts):
if cuts[-1] != len(weights) or sorted(set(cuts)) != list(cuts):
raise ValueError('cortes crecientes que terminen en n')
saved = {0: x}
y = x
for i, w in enumerate(weights, 1):
y = np.tanh(y @ w)
if i in cuts:
saved[i] = y
g = 2*y/y.size
grad = [None]*len(weights)
peak, replay = len(saved), 0
starts = (0,) + tuple(cuts[:-1])
for begin, end in reversed(list(zip(starts, cuts))):
local = [saved[begin]]
for i in range(begin, end):
local.append(np.tanh(local[-1] @ weights[i]))
replay += 1
peak = max(peak, len(saved)+len(local))
for i in range(end-1, begin-1, -1):
dz = g*(1-local[i-begin+1]**2)
grad[i] = local[i-begin].T @ dz
g = dz @ weights[i].T
return y, grad, peak, replay
rng = np.random.default_rng(4)
n, width, batch = 64, 16, 8
weights = [np.eye(width)+rng.normal(scale=.01, size=(width,width)) for _ in range(n)]
x = rng.normal(scale=.3, size=(batch,width))
y0, grad0, base_peak = normal(x, weights)
for segment in (1, 4, 8, 16, 64):
cuts = list(range(segment, n, segment))+[n]
y, grad, peak, replay = checkpointed(x, weights, cuts)
error = max(float(np.max(np.abs(a-b))) for a,b in zip(grad,grad0))
assert np.allclose(y,y0) and error < 1e-12
print('segmento',segment,'cota de activaciones',peak,
'capas rehechas',replay,'error máximo de gradiente',error)
print('referencia: activaciones guardadas',base_peak)In this run the conservative bound is 18 for segments of eight, compared with 65 stored states in the reference. The algorithm reconstructs 64 layers, one additional forward pass. The bound for unit-length segments is 67 because this code still recomputes there and counts duplicates; a real system could avoid that. The size of each unit depends on tensor shape and dtype.
To study heterogeneous layers, now use a different model, explicitly distinct from the earlier counter. A partition into segments pays the sum of boundary mem plus the largest segment sum of mem as temporary space. A unit segment keeps its context and is not recomputed; another segment pays the sum of its cost values. These simplifications define a precise problem, not an exact PyTorch prediction. At the optimum, the temporary maximum is some segment’s sum. We enumerate that maximum and solve by dynamic programming for the best prefix at each boundary-memory amount. Exhaustive traversal of partitions validates the small result.
For fixed temporary maximum , the dynamic-programming state contains the last processed index and boundary-memory sum . For each previous cut , the transition adds the boundary at , checks that segment memory does not exceed , and adds its reconstruction cost. Of two schedules reaching the same , only the lower cost is needed: future decisions depend on , , and , not on how the state was reached. Enumerating all possible temporary maxima and requiring within budget also examines the optimum’s maximum. This proves optimality for this finite model, not for a general autograd graph.
from itertools import product
from math import inf
def evaluate(mem, cost, ends):
start = boundary = peak = replay = 0
for end in ends:
boundary += mem[end-1]
peak = max(peak, sum(mem[start:end]))
if end-start > 1:
replay += sum(cost[start:end])
start = end
return boundary+peak, replay
def plan_checkpoints(mem, cost, budget):
n = len(mem)
if not n or len(cost) != n or any(m <= 0 for m in mem) or any(c < 0 for c in cost):
raise ValueError('listas válidas de igual longitud')
best = (inf, None)
for peak in {sum(mem[i:j]) for i in range(n) for j in range(i+1,n+1)}:
cap = budget-peak
if cap < 0:
continue
dp = {(0,0): (0,())}
for end in range(1,n+1):
for start in range(end):
if sum(mem[start:end]) > peak:
continue
extra = 0 if end-start == 1 else sum(cost[start:end])
for (idx, used), (value, path) in list(dp.items()):
if idx != start:
continue
new = used+mem[end-1]
if new > cap:
continue
key = (end,new)
candidate = (value+extra,path+(end,))
if key not in dp or candidate < dp[key]:
dp[key] = candidate
for (idx,_), value in dp.items():
if idx == n and value < best:
best = value
return best[1]
mem, cost = [2,4,1,3,2,5], [5,1,8,2,7,3]
for budget in (14,15,18,22):
plan = plan_checkpoints(mem,cost,budget)
candidates = []
for flags in product((0,1),repeat=len(mem)-1):
ends = tuple(i+1 for i,flag in enumerate(flags) if flag)+(len(mem),)
memory, replay = evaluate(mem,cost,ends)
if memory <= budget:
candidates.append((replay,ends))
brute = min(candidates,default=None)
assert (plan is None) == (brute is None)
if plan is not None:
assert evaluate(mem,cost,plan)[1] == brute[0]
print('presupuesto',budget,'plan',plan,'memoria y coste',
None if plan is None else evaluate(mem,cost,plan))Accumulation: sum before dividing
Gradient accumulation divides a batch into microbatches and accumulates their contributions before updating. If the batch contains valid tokens with losses , the objective is . By gradient linearity, each microbatch can backpropagate its sum divided by the same ; the final gradient sum mathematically equals that of the full batch. In floating point, summation order can produce small differences.
Do not average the means of differently sized microbatches: that gives each microbatch the same weight, not each token. Determine before backward, or accumulate sums and divide gradients before clipping and updating. Equivalence requires every example to see the same function: batch normalization computes different statistics per microbatch, and dropout masks must match if pointwise equality is required. Do not run the optimizer or its scheduler once per microbatch if you want to imitate a single large-batch step.
For example, if the first microbatch has two tokens and mean gradient 1, while the second has eight and mean gradient 3, the mean of means is 2. The mean of all ten tokens is . The mismatch is not numerical noise: the first rule weights each token in the short group four times as heavily as each token in the long group. With FP16 loss scaling, unscale before clipping; with multiple processes also account for whether the collective sums or averages their gradients.
import numpy as np
rng = np.random.default_rng(3)
x = rng.normal(size=(10, 4))
y = rng.normal(size=10)
w = rng.normal(size=4)
grad_full = 2*x.T @ (x @ w-y)/len(y)
parts = (slice(0,2), slice(2,10))
grad_sum = sum(2*x[p].T @ (x[p] @ w-y[p]) for p in parts)/len(y)
grad_means = sum(2*x[p].T @ (x[p] @ w-y[p])/len(y[p]) for p in parts)/2
print('error suma por token:',np.max(np.abs(grad_full-grad_sum)))
print('error media de medias:',np.max(np.abs(grad_full-grad_means)))
assert np.allclose(grad_full, grad_sum)What to recompute and what to offload
Selective recomputation discards only intermediates whose memory savings justify reconstruction cost. Korthikanti et al. study attention in their transformer and parallel configuration, not a universal constant for all architectures. FlashAttention already avoids materializing the full matrix and internally recomputes parts; wrapping it in checkpointing can repeat additional work. Measure the specific kernel and model before calling recomputation free.
Activation offloading stores tensors in CPU RAM and returns them before backward uses them. torch.autograd.graph.save_on_cpu applies this idea to autograd-saved tensors; offloading optimizer states is a separate decision. Pinned memory can allow asynchronous copies, but overlap requires suitable dependencies and timing: if the link lies on the critical path, transfer cost is paid. Measure CPU and device memory, time, and throughput, not just GPU peak.
The next figure uses real snapshots on an RTX 3060 with PyTorch 2.11.0+cu128, from the lesson 12 GPT initialized with 12 blocks, width 512, eight heads, context 1024, batch eight, BF16 autocast and SDPA math attention. Each point synchronizes CUDA and records allocated memory at the end of a block’s forward or start of its backward. Forward plus backward is measured without an optimizer. Accumulation uses four microbatches of two and therefore has more samples. Synchronization alters timing; points can miss peaks between samples and are not a throughput benchmark. The figure is neither a continuous trace nor a model-quality comparison.
Below you can record these snapshots again with the local lab’s class and functions. Each record call synchronizes for clarity: do not use those times to compare performance. A curve joins sparse samples; it does not reveal transient peaks between them. The figure’s data come from an earlier run and a new capture will have its own figures.
Local lab: a GPT under an 8 GiB budget
Save the “GPT PyTorch y cargadores” cell from m18 lesson 12 as gpt_pytorch.py. This test initializes a new GPT with that class and synthetic inputs: it requires no trained checkpoint and does not aim to evaluate language. The 8 GiB limit affects only this lab process’s allocator. The documented run’s GPU has 12 GiB, so failure under that limit does not prove the model exhausts its physical 12 GiB. The limit is set before tensor allocation and persists in this session: restart the kernel to remove it. Math attention is forced, dropout disabled, and BF16 used with autocast; another implementation, especially Flash, can have a different peak.
The step uses 12 sequences of length 1024 and discards 128 labels from the first example. Each microbatch backpropagates the sum of its losses divided by the total number of valid tokens. The seed, model, and data are reset for each mode. After warm-up, one step is measured with synchronization and includes AdamW; peak is allocated, not reserved, memory. An expected memory failure is reported as failure of that mode, not as a completed measurement. The function also compares full-block and MLP checkpointing, microbatch accumulation, and save_on_cpu.
import os, time
from pathlib import Path
from contextlib import nullcontext
import torch
from torch.nn import functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel
from torch.utils.checkpoint import checkpoint
assert torch.cuda.is_available()
scope = {}
exec(compile(Path(os.environ.get('ORYON_GPT_TORCH_CODE','gpt_pytorch.py')).read_text(encoding='utf-8'),
'gpt_pytorch.py','exec'),scope)
total_memory = torch.cuda.get_device_properties(0).total_memory
torch.cuda.set_per_process_memory_fraction(min(1., 8*1024**3/total_memory))
print('GPU:',torch.cuda.get_device_name(),'PyTorch:',torch.__version__,'límite del ensayo: 8 GiB')
def forward_gpt(net, ids, mode):
b,t = ids.shape
pos = torch.arange(t,device=ids.device)
x = net.embedding_dropout(net.token(ids)+net.position(pos)[None,:,:])
for block in net.blocks:
if mode == 'checkpoint':
x = checkpoint(lambda value, layer=block: layer(value)[0],x,use_reentrant=False)
elif mode == 'selectivo':
a,_ = block.attn(block.n1(x)); x = x+a
x = x+checkpoint(block.mlp,block.n2(x),use_reentrant=False)
else:
x,_ = block(x)
return F.linear(net.final(x),net.token.weight)
def trial(mode, batch=12):
torch.manual_seed(41)
net = scope['TorchGPT'](vocab=256,context=1024,width=512,layers=12,heads=8,dropout=0).cuda().train()
opt = torch.optim.AdamW(net.parameters(),lr=1e-4)
gen = torch.Generator(device='cuda').manual_seed(42)
ids = torch.randint(256,(batch,1024),generator=gen,device='cuda')
targets = torch.randint(256,(batch,1024),generator=gen,device='cuda')
targets[0,:128] = -100
valid = int((targets != -100).sum())
micro = 1 if mode == 'acumulacion' else batch
try:
for iteration in range(2):
opt.zero_grad(set_to_none=True)
if iteration == 1:
torch.cuda.synchronize(); torch.cuda.reset_peak_memory_stats(); start = time.perf_counter()
total_loss = 0.
context = torch.autograd.graph.save_on_cpu(pin_memory=True) if mode == 'offload' else nullcontext()
with context, sdpa_kernel(SDPBackend.MATH), torch.autocast('cuda',dtype=torch.bfloat16):
for begin in range(0,batch,micro):
logits = forward_gpt(net,ids[begin:begin+micro],mode)
loss = F.cross_entropy(logits.reshape(-1,256),targets[begin:begin+micro].reshape(-1),
ignore_index=-100,reduction='sum')/valid
total_loss += float(loss.detach())
loss.backward()
opt.step(); torch.cuda.synchronize()
elapsed = time.perf_counter()-start
print(mode,'lote:',batch,'pérdida:',total_loss,'pico asignado GiB:',round(torch.cuda.max_memory_allocated()/2**30,3),
'tokens/s:',round(valid/elapsed))
except torch.OutOfMemoryError as exc:
print(mode,'no cabe bajo el límite de 8 GiB:',str(exc).splitlines()[0])
finally:
del net,opt,ids,targets
torch.cuda.empty_cache()
for mode in ('base','checkpoint','selectivo','acumulacion','offload'):
trial(mode)
trial('selectivo',batch=8)npm run lab and open the connection link.import json
def memory_trace(mode, micro):
torch.manual_seed(41)
net = scope['TorchGPT'](vocab=256,context=1024,width=512,layers=12,heads=8,dropout=0).cuda().train()
gen = torch.Generator(device='cuda').manual_seed(42)
ids = torch.randint(256,(8,1024),generator=gen,device='cuda')
targets = torch.randint(256,(8,1024),generator=gen,device='cuda')
samples = []
torch.cuda.synchronize(); start = time.perf_counter()
def record(label):
torch.cuda.synchronize()
samples.append(dict(label=label,seconds=time.perf_counter()-start,
gib=torch.cuda.memory_allocated()/2**30))
record('inicio')
context = torch.autograd.graph.save_on_cpu(pin_memory=True) if mode == 'offload' else nullcontext()
with context, sdpa_kernel(SDPBackend.MATH), torch.autocast('cuda',dtype=torch.bfloat16):
for begin in range(0,8,micro):
cur = ids[begin:begin+micro]
x = net.embedding_dropout(net.token(cur)+net.position(torch.arange(1024,device='cuda'))[None,:,:])
for i,block in enumerate(net.blocks):
if mode == 'checkpoint':
x = checkpoint(lambda value,layer=block: layer(value)[0],x,use_reentrant=False)
elif mode == 'selectivo':
a,_ = block.attn(block.n1(x)); x = x+a
x = x+checkpoint(block.mlp,block.n2(x),use_reentrant=False)
else:
x,_ = block(x)
record(f'forward {begin}:{i}')
def hook(grad,label=f'backward {begin}:{i}'):
record(label)
return grad
x.register_hook(hook)
logits = F.linear(net.final(x),net.token.weight)
loss = F.cross_entropy(logits.reshape(-1,256),targets[begin:begin+micro].reshape(-1),reduction='sum')/targets.numel()
loss.backward()
record('final')
del net,ids,targets,x,logits,loss
torch.cuda.empty_cache()
return samples
traces = {mode:memory_trace(mode,micro) for mode,micro in
[('base',8),('checkpoint',8),('selectivo',8),('acumulacion',2),('offload',8)]}
Path('instantaneas-gpt.json').write_text(json.dumps(traces,indent=2,ensure_ascii=False),encoding='utf-8')
for name, points in traces.items():
print(name,'muestras:',len(points),'mayor instantánea GiB:',round(max(p['gib'] for p in points),3))npm run lab and open the connection link.In one local run under shared load, baseline and MLP-only checkpointing exhausted the limit at batch 12; full checkpointing, accumulation, and offloading finished with allocated peaks of 2.375, 1.396, and 2.210 GiB respectively. The last test reduces batch size to 8 to measure the selective case when it fits. These are separate strategies, not additive savings, and measurements at different batch sizes are not directly comparable. Printed rates from one short step vary with load and warm-up; they do not prove one strategy is generally faster. Compare gradients with dropout disabled and dtype-appropriate tolerance before using a variant for real training.
This small control uses FP32 and the same parameter state for each strategy. The hook records every tensor autograd asks to save: the sum of their sizes counts logical allocations, not necessarily exclusive physical memory, because two views can share storage. Losses and all gradients are checked with math attention; the larger BF16 test can differ more due to operation order.
import copy
torch.manual_seed(12)
reference = scope['TorchGPT'](vocab=32,context=16,width=32,layers=2,heads=4,dropout=0).cuda().train()
ids = torch.randint(32,(2,16),device='cuda')
targets = torch.randint(32,(2,16),device='cuda')
targets[0,:5] = -100
valid = int((targets != -100).sum())
state = copy.deepcopy(reference.state_dict())
saved = []
def pack(t):
saved.append((tuple(t.shape),str(t.dtype),t.numel()*t.element_size()))
return t
def unpack(t):
return t
baseline = None
for mode in ('base','checkpoint','selectivo','offload','acumulacion'):
reference.load_state_dict(state); reference.zero_grad(set_to_none=True)
context = (torch.autograd.graph.saved_tensors_hooks(pack,unpack) if mode == 'base' else
torch.autograd.graph.save_on_cpu(pin_memory=True) if mode == 'offload' else nullcontext())
with context, sdpa_kernel(SDPBackend.MATH):
micro = 1 if mode == 'acumulacion' else 2
total_loss = 0.
for begin in range(0,2,micro):
logits = forward_gpt(reference,ids[begin:begin+micro],mode)
loss = F.cross_entropy(logits.reshape(-1,32),targets[begin:begin+micro].reshape(-1),
ignore_index=-100,reduction='sum')/valid
total_loss += float(loss.detach())
loss.backward()
grads = [p.grad.detach().clone() for p in reference.parameters()]
if baseline is None:
baseline = (total_loss,grads)
print('tensores guardados:',len(saved),'bytes lógicos:',sum(s[2] for s in saved),
'primeras formas:',saved[:4])
else:
err = max(float((g-h).abs().max()) for g,h in zip(grads,baseline[1]))
print(mode,'error máximo de gradiente:',err)
assert abs(total_loss-baseline[0]) < 1e-6 and err < 1e-5npm run lab and open the connection link.Exercises
Step 1 of 4. How many activations are saved as boundaries?
More than one answer may be correct.
accumulated_gradient(parts, w) for squared regression without a factor of 1/2. Each element of parts is a pair (X, y), with one token per row. Return the gradient of the mean of all losses, not the mean of means.import numpy as np
def accumulated_gradient(parts, w):
passplan_checkpoints(mem, cost, budget) using the lab model. Return a tuple of segment-end indices ending in n that minimizes recomputation without exceeding the budget, or None if no feasible plan exists. mem contains positive integers and cost nonnegative values.def plan_checkpoints(mem, cost, budget):
pass