ZeRO and FSDP: sharding optimizer states, gradients and parameters
With DDP every GPU stores 16 bytes per parameter even when updating only a portion. ZeRO removes redundancy in stages: optimizer states, gradients, then parameters gathered just in time. We derive memory and communication volume, implement the stages from scratch with Gloo processes, study PyTorch FSDP and FSDP2 and CPU/NVMe offloading, and use ZeRO-Offload to fine-tune on an RTX 4060 a model that would not fit with GPU AdamW.
After this lesson you can
- Derive per-GPU memory and communication volume for DDP and ZeRO-1, 2 and 3.
- Implement ZeRO-1, ZeRO-2 and minimal FSDP with hooks gathering and releasing parameters per unit.
- Configure units, prefetch and resharding in FSDP2 and explain their effects on peak memory and overlap.
- Train an approximately 1B-parameter model on the local GPU with the optimizer on CPU and measure cost.
- Choose between ZeRO-2, ZeRO-3 and HSDP according to model and network.
Before you start
A replica need not store everything
With data parallelism, every GPU contains the same weights, gradients, and optimizer states. For 7 billion parameters, conventional mixed-precision AdamW accounting totals 112 decimal GB per GPU before activations and temporaries: more than fits on many cards. If each rank updates only a portion, why keep every state there?
The diagram counts resident amount, not each shard’s physical location. In sharded stages, each GPU owns a different quarter of the corresponding component. To illustrate communication it assumes equal-sized, equal-dtype weight and gradient transfers, an ideal ring, and no padding. Offloading adds traffic to and from CPU that the network readout excludes.
Do the accounting before choosing
Let be parameter count and rank count. In the conventional recipe from the ZeRO paper, compute weights and gradients take two bytes each; FP32 master weights and two FP32 Adam moments total twelve bytes. Not all implementations retain exactly these copies: check the specific policy. Activations, buffers, and reserved memory are added separately.
| Stage | Parameters | Gradients | AdamW state | Total per rank |
|---|---|---|---|---|
| DDP | ||||
| ZeRO-1 | ||||
| ZeRO-2 | ||||
| ZeRO-3 |
Each entry is in bytes; the equations are ideal accounting with equal shards. During ZeRO-3 forward and backward, parameters of the active unit are materialized, and prefetch can keep more than one. Gradients may temporarily exist in full before reduction. ZeRO alone does not reduce activations: checkpointing changes that term at the cost of recomputation.
In ZeRO-2 gradients are also sharded: reduce-scatter sums gradients from all ranks and delivers each owner its segment. The local optimizer operates on that segment and all-gather reconstructs weights for the next forward. Reducing each bucket when ready allows earlier gradient release; in the small lab below a hook reduces each gradient as it becomes ready during backward, but the example does not claim to demonstrate peak-memory savings.
How many bytes move
Count bytes sent per rank, not aggregate cluster traffic. For an -byte matrix and balanced ring, reduce-scatter and all-gather each send bytes per rank. Their sum is the cost of ring all-reduce. ZeRO-1 and ZeRO-2 use gradient reduction and gathering of updated parameters. If weights and gradients have equal size , both stages send , like DDP. If their dtypes differ, count each operation’s bytes separately.
With resharding after forward, ZeRO-3 uses weight all-gather in forward, another in backward, and gradient reduce-scatter: under the same assumption. The ratio to DDP is , not three times: the sometimes-used and notation counts elements in the many-rank limit, not bytes independently of dtype. Keeping full weights between forward and backward avoids one gather but increases memory. Latency, overlap, topology, and padding are excluded from this count.
FSDP unit size and prefetch determine the tradeoff. One unit for the entire model gathers everything at once: peak may still be too high. Many small units increase the number and latency of collectives. With prefetch, an upcoming unit can coexist with the current one, increasing peak in exchange for overlap. The figure assumes a limit of two full units during forward, plus persistent shards and other memory not shown.
In FSDP2, apply fully_shard bottom-up to submodules and then the root. Sharded parameters are DTensor; construct the optimizer after sharding. reshard_after_forward=True releases full parameters and requires another gather in backward; False retains them. MixedPrecisionPolicy distinguishes compute dtype from reduction dtype. To measure actual peak, record allocated and reserved memory, not only the ideal model.
Move states off the GPU
ZeRO-Offload and ZeRO-Infinity use CPU and, in Infinity, NVMe as well to expand effective storage. Offloaded weights, gradients, and states must travel over bandwidth-limited links. Pinned memory enables asynchronous copies but occupies physical RAM; do not reuse the buffer before a copy completes. The CPU optimizer needs master weights and moments and competes for memory bandwidth and cores.
For example, moving a BF16 gradient for billion parameters to CPU and returning BF16 weights is 2 GB in each direction. At 20 GB/s effective per direction, if both transfers are serialized and do not overlap compute, the model minimum is s per step. This is an estimate, not a PCIe measurement. The ZeRO-Offload paper reports results for other models and hardware, not times for this computer.
The “fits” readout is necessary under the model, not sufficient in practice: CUDA context, fragmentation, activations differing from the estimate, communication, and each unit’s peak are missing. With offloading, also sum all shards hosted in the same RAM and leave room for the system and data. For a machine with 32 GB RAM and an 8 GB RTX 4060 you can enter those values; they are not the machine used to validate this lesson.
Hybrid sharding and checkpoints
Hybrid sharded data parallelism (HSDP) shards states within local groups and replicates across groups. Large gathers can therefore use fast intranode links while gradients synchronize among equivalent replicas over the internode network. The advantage depends on topology, model, and available collectives. FSDP2’s two-dimensional mesh uses one replica dimension and one sharding dimension.
To clip gradients, calculate the global sum of squares of unique shards, reduced over the sharding dimension without counting replicated copies more than once; then use the same clipping factor everywhere. A full checkpoint requires correctly gathering states; a sharded one retains distribution metadata and needs resharding if the mesh changes. See training checkpoints and also save optimizer, scheduler, and random states.
Lab: three stages with four processes
The next program uses CPU Gloo, two matrices, AdamW, and two steps. In stage 1 it reduces full gradients and updates shards; in stage 2 a hook reduces each gradient when ready and releases its full copy. In stage 3 each unit uses hooks to gather before forward and backward and release afterward; an autograd function computes the gradient and reduce-scatter. All ranks reconstruct the result and compare it with monolithic and DDP references. The example is educational: it assumes identical hook order on all ranks and does not implement shared parameters, missing gradients, failures, real prefetch, padding, or a production optimizer.
import os, subprocess, sys, tempfile
from pathlib import Path
program = r'''
import os, socket, subprocess, sys
import torch
import torch.distributed as dist
WORLD = 4
def worker(rank, port):
torch.set_num_threads(1)
dist.init_process_group('gloo', init_method='tcp://127.0.0.1:'+port, rank=rank, world_size=WORLD)
traffic = [0]
def gather(shard):
parts = [torch.empty_like(shard) for _ in range(WORLD)]
traffic[0] += shard.numel() * shard.element_size()
dist.all_gather(parts, shard.contiguous())
return torch.cat(parts)
class ShardedMatmul(torch.autograd.Function):
@staticmethod
def forward(ctx, x, shard, unit):
weight = unit.full
ctx.save_for_backward(x, shard)
ctx.unit = unit
return x @ weight
@staticmethod
def backward(ctx, grad_out):
x, shard = ctx.saved_tensors
weight = ctx.unit.full
grad_x = grad_out @ weight.T
grad_full = (x.T @ grad_out).reshape(-1).contiguous()
grad_shard = torch.empty_like(shard)
traffic[0] += grad_full.numel() * grad_full.element_size()
dist.reduce_scatter_tensor(grad_shard, grad_full)
return grad_x, grad_shard / WORLD, None
class Unit(torch.nn.Module):
def __init__(self, shard):
super().__init__()
self.shard = torch.nn.Parameter(shard.clone())
self.full = None
self.register_forward_pre_hook(lambda mod, args: mod.unshard())
self.register_forward_hook(lambda mod, args, output: mod.release())
self.register_full_backward_pre_hook(lambda mod, grad: mod.unshard())
self.register_full_backward_hook(lambda mod, grad_in, grad_out: mod.release())
def unshard(self):
self.full = gather(self.shard.detach()).view(4,4)
def release(self):
self.full = None
def forward(self, x):
return ShardedMatmul.apply(x, self.shard, self)
x = torch.arange(32, dtype=torch.float32).view(8,4)/32
y = torch.arange(8, dtype=torch.float32).view(8,1).expand(-1,4)/8
initial = [torch.linspace(-.2,.2,16), torch.linspace(.15,-.15,16)]
ref = [torch.nn.Parameter(v.clone().view(4,4)) for v in initial]
ref_opt = torch.optim.AdamW(ref, lr=.01)
for _ in range(2):
ref_opt.zero_grad(set_to_none=True)
((torch.tanh(x @ ref[0]) @ ref[1]-y)**2).mean().backward()
ref_opt.step()
reference = [p.detach().reshape(-1) for p in ref]
class Net(torch.nn.Module):
def __init__(self):
super().__init__()
self.a = torch.nn.Parameter(initial[0].clone())
self.b = torch.nn.Parameter(initial[1].clone())
def forward(self, x):
return torch.tanh(x @ self.a.view(4,4)) @ self.b.view(4,4)
net = Net()
ddp = torch.nn.parallel.DistributedDataParallel(net)
ddp_opt = torch.optim.AdamW(ddp.parameters(), lr=.01)
for _ in range(2):
ddp_opt.zero_grad(set_to_none=True)
xb, yb = x[rank*2:(rank+1)*2], y[rank*2:(rank+1)*2]
((ddp(xb)-yb)**2).mean().backward()
ddp_opt.step()
ddp_error = max((a-b).abs().max().item() for a,b in zip(net.parameters(),reference))
assert ddp_error < 1e-6, (rank, ddp_error)
if rank == 0: print('DDP: dos pasos coinciden con referencia:', ddp_error < 1e-6, flush=True)
for stage in (1,2,3):
traffic[0] = 0
if stage == 3:
units = [Unit(v[rank*4:(rank+1)*4]) for v in initial]
params = [u.shard for u in units]
else:
params = [torch.nn.Parameter(v.clone()) for v in initial]
local = [torch.nn.Parameter(v.detach()[rank*4:(rank+1)*4].clone()) if stage < 3 else v for v in params]
optim = torch.optim.AdamW(local, lr=.01)
hooks = []
if stage == 2:
def make_hook(part):
def reduce_ready(full):
grad = torch.empty(4)
traffic[0] += full.grad.numel() * full.grad.element_size()
dist.reduce_scatter_tensor(grad, full.grad.contiguous())
part.grad = grad / WORLD
full.grad = None
return reduce_ready
hooks = [full.register_post_accumulate_grad_hook(make_hook(part)) for full,part in zip(params,local)]
for step in range(2):
optim.zero_grad(set_to_none=True)
for p in params: p.grad = None
xb, yb = x[rank*2:(rank+1)*2], y[rank*2:(rank+1)*2]
if stage == 3:
xb = xb.requires_grad_()
z = units[1](torch.tanh(units[0](xb)))
else:
z = torch.tanh(xb @ params[0].view(4,4)) @ params[1].view(4,4)
((z-yb)**2).mean().backward()
if stage == 3: assert all(u.full is None for u in units)
if stage == 1:
for full, part in zip(params,local):
traffic[0] += full.grad.numel() * full.grad.element_size()
dist.all_reduce(full.grad)
part.grad = full.grad[rank*4:(rank+1)*4].clone() / WORLD
optim.step()
if stage < 3:
with torch.no_grad():
for full,part in zip(params,local): full.copy_(gather(part.detach()))
for hook in hooks: hook.remove()
payload = traffic[0] # antes de la reunión para verificar
tensors = list(params) + list(local) + [p.grad for p in params if p.grad is not None]
tensors += [p.grad for p in local if p.grad is not None]
tensors += [value for state in optim.state.values() for value in state.values() if torch.is_tensor(value)]
storages = {t.untyped_storage().data_ptr(): t.untyped_storage().nbytes() for t in tensors}
resident = sum(storages.values())
full_results = [gather(v.detach()) for v in local]
error = max((a-b).abs().max().item() for a,b in zip(full_results,reference))
assert error < 1e-6, (rank,stage,error)
print('rango', rank, 'etapa', stage, 'equivalente:', error < 1e-6,
'bytes estados observados:', resident, 'bytes de entrada a colectivas:', payload, flush=True)
dist.destroy_process_group()
if len(sys.argv) == 3:
worker(int(sys.argv[1]),sys.argv[2])
else:
with socket.socket() as sock:
sock.bind(('127.0.0.1',0)); port=str(sock.getsockname()[1])
env=dict(os.environ,PYTHONUTF8='1',OMP_NUM_THREADS='1')
ps=[subprocess.Popen([sys.executable,__file__,str(r),port], stdout=subprocess.PIPE,stderr=subprocess.PIPE,
text=True,encoding='utf-8',errors='replace',env=env) for r in range(WORLD)]
try:
for proc in ps:
out,err=proc.communicate(timeout=120)
if proc.returncode: raise RuntimeError(err or out)
if out.strip(): print(out.strip())
finally:
for proc in ps:
if proc.poll() is None: proc.kill()
for proc in ps: proc.wait()
'''
with tempfile.TemporaryDirectory() as directory:
script = Path(directory) / 'laboratorio.py'
script.write_text(program, encoding='utf-8')
env = dict(os.environ, PYTHONUTF8='1', OMP_NUM_THREADS='1')
result = subprocess.run([sys.executable, str(script)], capture_output=True,
text=True, encoding='utf-8', errors='replace',
env=env, timeout=180)
if result.returncode:
raise RuntimeError(result.stderr or result.stdout)
print(result.stdout.strip())npm run lab and open the connection link.The program counts storage bytes for parameters, gradients, and optimizer state still alive at the end of each stage, deduplicating shared storage. It also sums tensor bytes presented as collective inputs, excluding the final verification gather. That second figure measures the API, not bytes measured on the link: it excludes outputs and does not determine Gloo’s algorithm. Memory is not process peak either and excludes activations and temporary buffers. Stage 1 communicates a full all-reduce plus all-gather, a naive implementation that does not achieve the derivation’s ideal reduce-scatter plus all-gather volume.
Lab: FSDP2 and offloading on one GPU
The first program tests bottom-up fully_shard with four CPU/Gloo processes and compares two steps against a monolithic reference. It uses the same data and initial weights as the previous lab, transposed because nn.Linear stores the matrix in the opposite convention. API and compatibility depend on version; the test completed on the local PyTorch 2.11 installation. Next you will check manual AdamW updates against PyTorch and run two fine-tuning steps of pretrained TinyLlama-1.1B on the WikiText-2 training set. These are two short steps to verify flow, not convergence or quality evaluation.
import os, subprocess, sys, tempfile
from pathlib import Path
program = r'''
import os
import socket
import subprocess
import sys
import torch
import torch.distributed as dist
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.fsdp import fully_shard
if len(sys.argv) == 3:
rank, port = int(sys.argv[1]), sys.argv[2]
torch.set_num_threads(1)
dist.init_process_group('gloo', init_method='tcp://127.0.0.1:' + port, rank=rank, world_size=4)
torch.manual_seed(1)
model = torch.nn.Sequential(torch.nn.Linear(4, 4, bias=False), torch.nn.Tanh(), torch.nn.Linear(4, 4, bias=False))
# Los pesos coinciden con los del laboratorio anterior, traspuestos por la convención de Linear.
with torch.no_grad():
model[0].weight.copy_(torch.linspace(-.2,.2,16).view(4,4).T)
model[2].weight.copy_(torch.linspace(.15,-.15,16).view(4,4).T)
reference = torch.nn.Sequential(torch.nn.Linear(4, 4, bias=False), torch.nn.Tanh(), torch.nn.Linear(4, 4, bias=False))
reference.load_state_dict(model.state_dict())
x = torch.arange(32, dtype=torch.float32).view(8,4)/32
y = torch.arange(8, dtype=torch.float32).view(8,1).expand(-1,4)/8
ref_opt = torch.optim.AdamW(reference.parameters(),lr=.01)
for _ in range(2):
ref_opt.zero_grad(set_to_none=True)
((reference(x)-y)**2).mean().backward()
ref_opt.step()
mesh = init_device_mesh('cpu', (4,))
fully_shard(model[0], mesh=mesh)
fully_shard(model[2], mesh=mesh)
fully_shard(model, mesh=mesh)
opt = torch.optim.AdamW(model.parameters(),lr=.01)
for _ in range(2):
opt.zero_grad(set_to_none=True)
((model(x[rank*2:(rank+1)*2])-y[rank*2:(rank+1)*2])**2).mean().backward()
opt.step()
full = [p.full_tensor() for p in model.parameters()]
error = max((a-b).abs().max().item() for a,b in zip(full, reference.parameters()))
assert error < 1e-6, (rank, error)
if rank == 0: print('FSDP2 CPU: dos pasos coinciden con referencia:', error < 1e-6, flush=True)
dist.destroy_process_group()
else:
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
port = str(sock.getsockname()[1])
env = dict(os.environ, PYTHONUTF8='1', OMP_NUM_THREADS='1')
procs = [subprocess.Popen([sys.executable, __file__, str(r), port], stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, encoding='utf-8', errors='replace', env=env) for r in range(4)]
try:
for proc in procs:
out, err = proc.communicate(timeout=90)
if proc.returncode: raise RuntimeError(err or out)
if out.strip(): print(out.strip())
finally:
for proc in procs:
if proc.poll() is None: proc.kill()
for proc in procs: proc.wait()
'''
with tempfile.TemporaryDirectory() as directory:
script = Path(directory) / 'laboratorio.py'
script.write_text(program, encoding='utf-8')
env = dict(os.environ, PYTHONUTF8='1', OMP_NUM_THREADS='1')
result = subprocess.run([sys.executable, str(script)], capture_output=True,
text=True, encoding='utf-8', errors='replace',
env=env, timeout=180)
if result.returncode:
raise RuntimeError(result.stderr or result.stdout)
print(result.stdout.strip())npm run lab and open the connection link.The large program is excluded from the automatic checker because of its memory requirements. You need PyTorch with CUDA and BF16, transformers, datasets, accelerate, sufficient RAM, and the cached model. To download it beforehand run from huggingface_hub import snapshot_download and snapshot_download("TinyLlama/TinyLlama-1.1B-Chat-v1.0"); datasets obtains WikiText-2 if not cached. BF16 weights live on GPU; master weights and both FP32 moments live in pinned CPU memory. A pinned buffer receives gradients in blocks and copies are synchronized before it is reused or weights modified. The first step creates states, so its time includes initialization. Measure throughput in input tokens per second and peak PyTorch-allocated memory.
The validation run used PyTorch 2.11, a 12 GiB RTX 3060, and 1,100,048,384 trainable parameters. It completed both steps with finite losses and 4.36 GiB allocated peak. These are two different training-set fragments: their losses do not measure improvement. Times vary with shared load and are printed in your run. An RTX 4060 was not available for this check. Conventional -byte accounting for that model exceeds this GPU’s total capacity even before activations, but actual peak depends on implementation.
import math
import torch
ref = torch.nn.Parameter(torch.tensor([.2, -.4, .7]))
mine = ref.detach().clone()
moment, variance = torch.zeros_like(mine), torch.zeros_like(mine)
opt = torch.optim.AdamW([ref],lr=1e-5,betas=(.9,.999),eps=1e-8,weight_decay=.01)
for step,grad in enumerate([torch.tensor([.1,-.3,0.]),torch.tensor([-.2,.4,.7])],1):
ref.grad=grad.clone(); opt.step()
moment.mul_(.9).add_(grad,alpha=.1)
variance.mul_(.999).addcmul_(grad,grad,value=.001)
bias1,bias2=1-.9**step,1-.999**step
denominator=variance.sqrt().add_(1e-8*math.sqrt(bias2))
mine.mul_(1-1e-5*.01).addcdiv_(moment,denominator,value=-1e-5*math.sqrt(bias2)/bias1)
assert torch.allclose(mine,ref.detach(),atol=1e-7,rtol=1e-6)
print('AdamW por bloques: dos pasos coinciden con torch.optim.AdamW')npm run lab and open the connection link.import math
import os
import time
import torch
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
torch.manual_seed(7)
torch.set_num_threads(4)
assert torch.cuda.is_available() and torch.cuda.is_bf16_supported()
name = os.environ.get('ORYON_MODEL', 'TinyLlama/TinyLlama-1.1B-Chat-v1.0')
tokenizer = AutoTokenizer.from_pretrained(name, local_files_only=True)
dataset = load_dataset('Salesforce/wikitext', 'wikitext-2-raw-v1', split='train')
text = '\n'.join(s for s in dataset['text'][:300] if s.strip())
ids = tokenizer(text, return_tensors='pt', truncation=True, max_length=256)['input_ids'][0]
assert len(ids) >= 256
batches = [ids[i:i+128].unsqueeze(0).to('cuda') for i in (0,128)]
model = AutoModelForCausalLM.from_pretrained(name, dtype=torch.bfloat16,
device_map='cuda', local_files_only=True)
model.train()
model.config.use_cache = False
model.gradient_checkpointing_enable()
params = [p for p in model.parameters() if p.requires_grad]
print('parámetros:', sum(p.numel() for p in params), flush=True)
torch.cuda.reset_peak_memory_stats()
# Optimizer state stays on CPU. Small pinned buffers are reused only after synchronization.
states = {}
block = 2*1024*1024
g_buffer = torch.empty(block, dtype=torch.bfloat16, pin_memory=True)
b1,b2,eps,lr,wd = .9,.999,1e-8,1e-5,.01
for step, batch in enumerate(batches, 1):
model.zero_grad(set_to_none=True)
torch.cuda.synchronize()
start = time.perf_counter()
loss = model(input_ids=batch, labels=batch).loss
assert torch.isfinite(loss)
loss.backward()
torch.cuda.synchronize()
with torch.no_grad():
for p in params:
if p.grad is None: continue
key = id(p)
if key not in states:
master = torch.empty(p.numel(), dtype=torch.float32, pin_memory=True)
master.copy_(p.detach().reshape(-1), non_blocking=True)
torch.cuda.synchronize()
states[key] = (master, torch.zeros(p.numel(), dtype=torch.float32, pin_memory=True),
torch.zeros(p.numel(), dtype=torch.float32, pin_memory=True))
master,m,v = states[key]
flat_g,flat_p = p.grad.reshape(-1),p.data.reshape(-1)
for begin in range(0,p.numel(),block):
end=min(begin+block,p.numel()); count=end-begin
gb=g_buffer[:count]
gb.copy_(flat_g[begin:end], non_blocking=True)
torch.cuda.synchronize()
g=gb.float()
mm,vv,ww=m[begin:end],v[begin:end],master[begin:end]
mm.mul_(b1).add_(g,alpha=1-b1)
vv.mul_(b2).addcmul_(g,g,value=1-b2)
bias1,bias2=1-b1**step,1-b2**step
denom=vv.sqrt().add_(eps*math.sqrt(bias2))
ww.mul_(1-lr*wd).addcdiv_(mm,denom,value=-lr*math.sqrt(bias2)/bias1)
flat_p[begin:end].copy_(ww,non_blocking=True)
torch.cuda.synchronize()
p.grad = None
elapsed=time.perf_counter()-start
print('paso',step,'pérdida',float(loss.detach()),'tokens/s',round(128/elapsed,2),flush=True)
print('GPU:',torch.cuda.get_device_name(),flush=True)
print('pico asignado GiB:',round(torch.cuda.max_memory_allocated()/2**30,3),flush=True)npm run lab and open the connection link.Exercises
Step 1 of 3. How much does reduce-scatter followed by all-gather send?
def shard_flat_params(values, rank, world):
...
def gather_flat_params(shards, length):
...psi, p = 7.5, 64
print('GB por GPU:', [psi*k for k in (16, 4+12/p, 2+14/p, 16/p)])
print('segundos PCIe:', 2*2/20)