Composing parallelisms: planning, checkpointing and surviving failures
Real training combines five parallelisms across thousands of GPUs and experiences failures every few hours. We compose DP, TP, PP, CP and EP over topology, choose configurations with rules and a cost model compared with published designs, and keep training alive using distributed reshardable checkpoints, checkpoint interval optimization, slow-node detection and deadlock debugging.
After this lesson you can
- Compose DP, TP, PP, CP and EP on a mesh and place each dimension at the appropriate network level.
- Build a memory, compute, communication and bubble cost model and use it to choose a configuration.
- Explain published Megatron, Llama 3 and DeepSeek-V3 configurations from their constraints.
- Save a sharded state and reload with a different process count while verifying exact continuity.
- Derive the optimal checkpoint interval and diagnose deadlocks and desynchronization.
Before you start
- 21ZeRO stage 3 and FSDP: parameter shardingHybrid sharded data parallelismMegatron transformer block partitioningDevice meshes and DTensor placementsPipeline bubbleInterleaved pipeline scheduleContext parallelismExpert parallelismModel FLOPs utilization
- 04Exponential, gamma and chi-squared distributionsMemoryless property
- 03Derivative as best linear approximationClassification of critical points
- 00Atomic writes and checkpoint rotationExact resumption
A configuration is a layout and a schedule
A large model may need to distribute parameters, activations, and work simultaneously. Parallelism composition combines data (DP), tensor (TP), pipeline stages (PP), context (CP), and experts (EP). Each axis creates groups with different collectives and each group occupies specific physical links. A configuration that fits in memory can still be slow if frequent communication crosses a shared network.
For the planner example, . EP is a subgroup of DP: it must divide DP and shards experts across those ranks; each expert has replicas. This is a convention of this mesh, not a universal identity: other implementations organize EP with differently overlapping groups. Do not multiply EP again into if its ranks are already counted within DP. Dense layers and experts may use different gradient-synchronization groups.
TP communicates within each layer and often prefers high-speed intranode links. PP sends activations and gradients between stages, CP moves attention information, and DP synchronizes replicas. Megatron-LM observes in its experiments that TP within a node and PP across nodes can be useful; this is not a law for every topology. An inner dimension whose size divides GPUs per node forms local groups in the figure’s linear placement. Changing order can make those same groups cross nodes.
Coordinate assignment must be part of the plan. With two eight-GPU nodes, if TP=4 is the fastest index, each group of four occupies contiguous GPUs within one node. Changing axis order can distribute the same four TP coordinates across nodes. Total GPU count and degrees do not change, but collective paths do. On a real network, network-card affinity, shared links, and process placement also matter; linear enumeration is only an approximation.
DP does not always mean each GPU stores a full state copy. FSDP can shard parameters, gradients, and optimizer across data replicas and gather what each layer needs. CP shards positions, but layer parameters can remain replicated along that axis and their gradient contributions must be combined. The mesh describes who collaborates on each operation; it does not replace a specification of which tensor is replicated or sharded.
Search using an explicit model
Configuration search enumerates valid factors and discards those that do not fit. Constraints include divisibility of heads by TP, layers by PP, sequence by CP, and local batch by microbatch. Divisibility rules describe simple partitioning; padding, replication, or uneven layers can allow other configurations at additional cost. Keeping TP inside a node can also be relaxed, but requires modeling its slower network.
For a dense model with parameters and balanced TP×PP partition, there are logical parameters per rank before ZeRO. With BF16 parameters and gradients, FP32 master and two moments, ZeRO-1 retains four bytes per parameter for weight and gradient and shards twelve optimizer-state bytes across DP. Its estimate is
For 70 billion parameters, TP=8, PP=4 and DP=32, this gives 9.5703125 decimal GB per GPU before activations and buffers. In MoE, the tool separately counts dense and expert parameters: it divides the latter by EP and shards their optimizer states across replicas. It does not assume a different expert is a replica of the first.
The figure’s model estimates activations from microbatch, sequence, width, layer count, and in-flight activations. It approximates TP and sequence memory terms without the quadratic attention term or buffers. It estimates compute as useful FLOPs, adds recomputation if enabled, and separates compute, bubble, and communication. TP uses ideal ring all-reduce; CP moves K/V, PP sends activations, and EP performs illustrative dispatch and return. An alpha-beta term adds per-round latency and size over bandwidth. Communication is not overlapped and congestion, kernel variation, embedding imbalance, and fragmentation-related memory failures are not modeled.
When comparing candidates, check feasibility first and time second. If a candidate estimates 79 GiB on an 80 GiB GPU, the model still does not guarantee the job starts: uncounted activations, communication buffers, and fragmentation can exhaust the margin. A comfortable estimate can also fail if the final stage has a head much larger than average. Search selects the minimum of its candidates; it does not prove a global optimum exists or that the winner is fastest on hardware.
The alpha-beta term distinguishes small and large messages. A collective with many small messages repeatedly pays latency; one with large tensors may be bandwidth-limited. Reducing bytes does not necessarily reduce time if round count increases. Adding times also assumes everything is exposed: if communication and compute overlap, that sum can overestimate the step. Conversely, congestion and queues can make it longer than the model.
Estimated MFU divides useful FLOPs by total time and aggregate peak. It is not instantaneous utilization and its numerator excludes extra recomputation work. Reducing microbatch size can lower memory but changes microbatch count and actual multiplication efficiency. In balanced GPipe, overhead versus ideal is ; a deep pipeline with few microbatches can therefore pay substantial waiting.
The lab explores a 64-GPU mesh and compares a TP8/PP8 case with the 91B experiment of Narayanan et al., who studied that degree and several microbatches. The example’s other internal sizes and bandwidths are declared substitutes; its seconds are not presented as a measurement from the paper. In the Llama 3 report, dimension order accounts for network and FSDP; DeepSeek-V3 reports PP16 and EP64 with ZeRO-1, avoiding TP in training through other optimizations. These designs have different assumptions. Alpa automates partition decisions with a broader cost model than this grid search.
Save and change the mesh
A distributed checkpoint stores shards of a logical state and metadata to reconstruct them. When resuming with another mesh, each rank can read the parts needed for its new partition. PyTorch Distributed Checkpoint supports this pattern for compatible structures. Asynchronous saving can hide some write time but must isolate a consistent snapshot from updates and await confirmation before treating it as recoverable.
Exact continuity requires more than weights: optimizer state, step, learning-rate scheduler, randomness, data position and order, and any model-specific state. Changing process count can change reduction order and random-number consumption; resharding therefore does not guarantee bitwise agreement for every training run. The lab verifies a deterministic elementwise CPU update: it saves weight, moment, and step with four ranks, simulates a failure after saving, and reloads with two. Its data signal depends on global step, not mutable RNG; it does not demonstrate general stochastic continuity.
A resumer must know whether the latest save completed. A robust sequence writes shards and metadata to a temporary location, checks completion, and only then publishes a commit marker. The exact mechanism depends on storage guarantees; local atomic rename does not imply identical remote-store semantics. If the process fails during writing, retain the prior checkpoint and discard the incomplete one. Testing reads matters as much as observing a successful write.
How often to save
Checkpoint interval optimization balances two losses. If saving costs , saving every work units wastes approximately . With mean time between failures and a uniform failure within the interval, average lost work is per failure, or per unit time. Young’s approximation minimizes
The derivative is and the second derivative is positive for . With min and min, min of work and the approximation gives 76.43% goodput. The model is first-order: here loss is not very small and finite saving and restart deserve consideration. Daly studies a higher-order correction including failures during saving and recovery time; formulas vary depending on whether the interval counts useful work only or writing too.
If each GPU has independent exponential failures with mean , cluster rate is the sum of rates and mean time to first failure is . The assumption fails if a network interruption affects many nodes at once. The figure counts work only upon checkpoint confirmation, even if useful work is still in flight at the horizon. Instant restart is a simplification; slow reads, repair, and queues increase failure cost.
The optimal interval grows with the square root of save cost and the square root of time between failures. Quadrupling write cost doubles the interval, not quadruples it. Quadrupling the number of independent GPUs quarters cluster MTBF and halves the suggested interval. This alone does not predict a reliable service: correlated failure, checkpoint loss, or long repair changes effective rates and costs.
Failures, slow nodes, and deadlocks
Fault tolerance at scale combines detection, an intact checkpoint, restart, and resumption. A half-written checkpoint must not replace the last confirmed one; a manifest or atomic rename can mark completion depending on storage. An inconsistent snapshot of weights and moment can load without a format error yet change training.
Distributed debugging starts by finding the first rank that stopped progressing. If ranks run collectives in different orders, they wait for incompatible operations; if one runs out of memory, others can wait for a collective that never starts. A rank-dependent conditional branch can cause the same symptom. A slow node may arrive late without diverging. Compare per-rank traces with collective names and sequences, earlier errors, memory, and timings; a timeout is a signal, not proof the network library caused it.
The lab injects a different replicated step on one rank and compares hashes; it detects that specific divergence, but not every deadlock or corruption of sharded parameters. Checksums are comparable only for data that should be equal. Hashes of different shards need not match; reconstruct or verify each shard against its reference.
Lab: grid search
The next dense planner counts ZeRO, activations, four communication terms, and bubble. Candidate set, link speed, efficiency, and shapes are explicit assumptions; it is not calibrated against a real run and does not search every possible mesh.
from itertools import product
# Modelo deliberadamente sencillo; todos los tiempos son estimaciones, no mediciones.
model=dict(params=91e9, active=91e9, layers=72, heads=80, hidden=10240, seq=2048, batch=512)
cluster=dict(world=64, node=8, memory=80*2**30, peak=312e12, efficiency=0.45,
local_bw=200e9, network_bw=25e9, latency=10e-6)
def valid(world,model,node,micro=2):
for tp,pp,cp in product((1,2,4,8,16,32,64),repeat=3):
denom=tp*pp*cp
if world%denom: continue
dp=world//denom
if tp>node or node%tp or model['heads']%tp or model['layers']%pp or model['seq']%cp: continue
if model['batch']%(dp*micro): continue
yield dict(dp=dp,tp=tp,pp=pp,cp=cp,micro=micro)
def estimate(c, model, cluster, zero=1, sp=True, recompute=False):
dp,tp,pp,cp,micro=(c[k] for k in ('dp','tp','pp','cp','micro'))
m=model['batch']//(dp*micro); P=model['params']/(tp*pp)
# Parámetros y gradientes BF16; maestro + dos momentos FP32.
coefficients=[16,4+12/dp,2+14/dp,16/dp]
states=P*coefficients[zero]
activation=micro*model['seq']/cp*model['hidden']*(34/tp if sp else 10+24/tp)*model['layers']/pp*min(m,pp)
if recompute: activation*=0.5
memory=states+activation
ideal=6*model['active']*model['batch']*model['seq']/(cluster['world']*cluster['peak'])
compute=ideal/cluster['efficiency']*(4/3 if recompute else 1)
bubble=compute*(pp-1)/m
# Un modelo alpha-beta explícito, sin solapamiento: cuatro all-reduce TP
# por capa y micro-lote; DP reduce gradientes una vez; CP mueve K/V y PP
# activaciones en ambos sentidos. No incluye EP ni todos los buffers.
alpha=cluster['latency']; local=cluster['local_bw']; net=cluster['network_bw']
tensor=micro*model['seq']/cp*model['hidden']*2
tp_time=4*(model['layers']/pp)*m*(2*(tp-1)*alpha+2*(tp-1)/tp*tensor/local)
dp_time=2*(dp-1)*alpha+2*(dp-1)/dp*(2*P)/net
cp_time=(model['layers']/pp)*m*((cp-1)*alpha+2*tensor*(cp-1)/net)
pp_time=2*m*(pp-1)/pp*(alpha+tensor/net)
communication=tp_time+dp_time+cp_time+pp_time
total=compute+bubble+communication
return dict(memory=memory,states=states,activation=activation,compute=compute,bubble=bubble,comm=communication,total=total,mfu=ideal/total)
candidates=[]
for c in valid(cluster['world'],model,cluster['node']):
result=estimate(c,model,cluster)
if result['memory']<=cluster['memory']: candidates.append((result['total'],c,result))
candidates.sort(key=lambda item:item[0])
print('Configuraciones válidas que caben:',len(candidates))
for _,c,r in candidates[:3]: print(c,'memoria GiB',round(r['memory']/2**30,2),'segundos',round(r['total'],3),'MFU',round(r['mfu'],3))
published=dict(dp=1,tp=8,pp=8,cp=1,micro=2)
r=estimate(published,model,cluster)
print('Caso TP8 PP8 de Narayanan, dimensiones sustitutas explícitas:',round(r['memory']/2**30,2),'GiB;',round(r['total'],3),'s; MFU',round(r['mfu'],3))
assert published in list(valid(64,model,8))
assert abs((4+12/32)*70e9/32/1e9-9.5703125)<1e-9
Lab: checkpoint and resharding
A vector, its moment, and step are saved using DTensor and torch.distributed.checkpoint. Four processes write and rank zero exits with an error code after the save barrier; two processes resume, reshard, and compare the next step bitwise with a deterministic reference. An artificial step divergence is detected with exchanged hashes. The example does not attempt to reproduce RNG, data loaders, GPU kernels, or every state of real training.
import os, subprocess, sys, tempfile
from pathlib import Path
script = r'''
import os, socket, subprocess, sys, tempfile, hashlib
from pathlib import Path
import torch
import torch.distributed as dist
import torch.distributed.checkpoint as dcp
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.tensor import distribute_tensor, Shard
SIZE=32
def initial():
return torch.linspace(-1,1,SIZE),torch.zeros(SIZE)
def step(w,m,step_number):
# Ejemplo determinista elemento a elemento; la señal de entrenamiento
# depende del paso global y no del número de rangos.
target=torch.arange(SIZE,dtype=torch.float32)/SIZE + step_number/16
grad=w-target
m=0.9*m+grad
return w-0.05*m,m
def rank_job(mode,rank,world,port,directory):
os.environ['MASTER_ADDR'],os.environ['MASTER_PORT']='127.0.0.1',str(port)
torch.set_num_threads(1)
dist.init_process_group('gloo',rank=rank,world_size=world)
mesh=init_device_mesh('cpu',(world,))
def sharded(t): return distribute_tensor(t,mesh,[Shard(0)])
w,m=initial()
if mode=='save':
w,m=step(w,m,0)
state={'weight':sharded(w),'momentum':sharded(m),'step':torch.tensor(1,dtype=torch.int64)}
dcp.save(state,checkpoint_id=directory)
dist.barrier()
print('Guardado rango',rank,'fragmento',state['weight'].to_local().numel(),flush=True)
dist.destroy_process_group()
# Una caída después de confirmar el checkpoint no invalida su contenido.
if rank==0: os._exit(17)
else:
state={'weight':sharded(torch.zeros(SIZE)),'momentum':sharded(torch.zeros(SIZE)),'step':torch.tensor(0,dtype=torch.int64)}
dcp.load(state,checkpoint_id=directory)
assert int(state['step'])==1
start=rank*(SIZE//world); end=(rank+1)*(SIZE//world)
w1,m1=step(*initial(),0); refw,refm=step(w1,m1,1)
localw=state['weight'].to_local(); localm=state['momentum'].to_local()
target=torch.arange(SIZE,dtype=torch.float32)[start:end]/SIZE+1/16
grad=localw-target; localm=0.9*localm+grad; localw=localw-0.05*localm
assert torch.equal(localw,refw[start:end]) and torch.equal(localm,refm[start:end])
# Inyecta una divergencia en el paso replicado; todos contrastan hashes.
probe=state['step'].clone();
if rank==1: probe+=1
digest=hashlib.sha256(probe.numpy().tobytes()).digest()[:8]
checksum=torch.tensor(int.from_bytes(digest,'little',signed=True),dtype=torch.int64)
checks=[torch.empty_like(checksum) for _ in range(world)]
dist.all_gather(checks,checksum)
assert len({int(x) for x in checks})==2
print('Rango',rank,'fragmento',len(localw),'continuación bit a bit: sí; divergencia detectada',flush=True)
dist.destroy_process_group()
def run(mode,world,directory):
with socket.socket() as sock:
sock.bind(('127.0.0.1',0)); port=str(sock.getsockname()[1])
env=os.environ.copy();env['PYTHONIOENCODING']='utf-8'
procs=[subprocess.Popen([sys.executable,__file__,mode,str(rank),str(world),port,directory],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,encoding='utf-8',errors='replace',env=env) for rank in range(world)]
for rank,proc in enumerate(procs):
out,err=proc.communicate(timeout=600)
wanted=17 if mode=='save' and rank==0 else 0
if proc.returncode!=wanted: raise RuntimeError(f'{mode} rango {rank}: {proc.returncode}\n{err}')
print(out,end='')
if __name__=='__main__':
if len(sys.argv)>1:
rank_job(sys.argv[1],int(sys.argv[2]),int(sys.argv[3]),sys.argv[4],sys.argv[5])
else:
with tempfile.TemporaryDirectory() as directory:
run('save',4,directory)
print('Caída simulada tras el guardado; reinicio con dos rangos')
run('load',2,directory)
'''
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "checkpoint.py"
path.write_text(script, encoding="utf-8")
env = os.environ.copy(); env["PYTHONIOENCODING"] = "utf-8"
result = subprocess.run([sys.executable, str(path)], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=600, env=env)
print(result.stdout)
if result.returncode: raise RuntimeError(result.stderr)npm run lab and open the connection link.Exercises
Step 1 of 2. What is the derivative?
def valid_configs(world,model):
...