Module contents
Lesson 14 of 28Advanced 115 min

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

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.

InteractivePlan a configuration

Hypothetical cluster: 64 GPUs, eight per node, 80 GiB per GPU, 312 peak TFLOP/s; sequence 2048, global batch 512. The hypothetical MoE has 64 experts and top-2.

The estimate fits, before buffers and fragmentation. Microbatches per replica: 64.

  • States: 28.52 GiB; activations: 21.25 GiB.
  • Compute 49.01 s; bubble 2.30 s; communication 3.67 s.

The model excludes buffers, imbalance, quadratic attention and some collectives. Dense states follow ZeRO stage over DP; expert states use their DP/EP replicas.

2
Estimated memory (GiB)49.8
Estimated time (s)54.98
Estimated MFU40.1 %
Degrees, memory, and times use simplified assumptions described in the figure. Search enumerates configurations and chooses the lowest estimate among those that fit; it does not measure actual performance.

For the planner example, N=DP⋅TP⋅PP⋅CPN=DP\cdot TP\cdot PP\cdot CP. EP is a subgroup of DP: it must divide DP and shards experts across those ranks; each expert has DP/EPDP/EP 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 NN if its ranks are already counted within DP. Dense layers and experts may use different gradient-synchronization groups.

InteractiveThe mesh across two nodes

Two nodes, eight GPUs per node. Hypothetical bandwidth: 200 GB/s within and 25 GB/s between nodes; concurrent links are not modeled.

Node 0
GPU 0
TP0 · CP0 · PP0 · DP0
GPU 1
TP1 · CP0 · PP0 · DP0
GPU 2
TP2 · CP0 · PP0 · DP0
GPU 3
TP3 · CP0 · PP0 · DP0
GPU 4
TP0 · CP0 · PP1 · DP0
GPU 5
TP1 · CP0 · PP1 · DP0
GPU 6
TP2 · CP0 · PP1 · DP0
GPU 7
TP3 · CP0 · PP1 · DP0
Node 1
GPU 8
TP0 · CP0 · PP0 · DP1
GPU 9
TP1 · CP0 · PP0 · DP1
GPU 10
TP2 · CP0 · PP0 · DP1
GPU 11
TP3 · CP0 · PP0 · DP1
GPU 12
TP0 · CP0 · PP1 · DP1
GPU 13
TP1 · CP0 · PP1 · DP1
GPU 14
TP2 · CP0 · PP1 · DP1
GPU 15
TP3 · CP0 · PP1 · DP1

Readouts count groups crossing the boundary, not messages or measured time. Changing order changes placement, not cluster size.

TP × 4
CP × 1
PP × 2
DP × 2
Cross-node TP groups0
Cross-node PP groups0
Cross-node DP groups8
Move dimensions from fastest to slowest and observe which groups touch both nodes. The grid assigns coordinates to 16 GPUs in a hypothetical cluster.

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 PP parameters and balanced TP×PP partition, there are P/(TP⋅PP)P/(TP\cdot PP) 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

PTP⋅PP(4+12DP)bytes por GPU.\frac{P}{TP\cdot PP}\left(4+\frac{12}{DP}\right)\quad\text{bytes por GPU}.

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 DP/EPDP/EP 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 6PactivoBs6P_{activo}Bs 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 m=B/(DP⋅b)m=B/(DP\cdot b) and actual multiplication efficiency. In balanced GPipe, overhead versus ideal is (PP−1)/m(PP-1)/m; 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 CC, saving every τ\tau work units wastes approximately C/τC/\tau. With mean time between failures MM and a uniform failure within the interval, average lost work is τ/2\tau/2 per failure, or τ/(2M)\tau/(2M) per unit time. Young’s approximation minimizes

W(τ)=Cτ+τ2M,τ∗=2CM.W(\tau)=\frac{C}{\tau}+\frac{\tau}{2M},\qquad \tau^*=\sqrt{2CM}.

The derivative is −C/τ2+1/(2M)-C/\tau^2+1/(2M) and the second derivative 2C/τ32C/\tau^3 is positive for τ>0\tau>0. With M=180M=180 min and C=5C=5 min, τ∗=1800≈42.43\tau^*=\sqrt{1800}\approx42.43 min of work and the 1−W1-W 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.

InteractiveFailures and saves
  • Committed work
  • Ideal without failures

Horizon 1000 h; 14 failures in this trajectory. Young suggests 216.5 min of work between saves. Goodput approximation: 91.0 %; the finite trajectory may differ. Restart and correlated failures are excluded.

  • First-order approximation
  • Young optimum

The orange point marks the optimum; regions where the approximation is negative are omitted.

GPU
5000
60
5
Cluster MTBF (h)78.1
Young (min)216.5
Observed goodput91.6 %
A reproducible trajectory with independent per-GPU failures and instant restart. Young is an approximation; observed goodput depends on the finite trajectory and its last confirmed checkpoint.

If each GPU has independent exponential failures with mean MgM_g, cluster rate is the sum of rates and mean time to first failure is Mg/NM_g/N. 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.

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.

[ ]Search configurationsBrowser
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.

[ ]Resharded checkpointLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Proof
Prove: Derive Young's interval for W(τ)=C/τ+τ/(2M).
The proof will appear here as you work.

Step 1 of 2. What is the derivative?

Numeric
With M=180 min and C=5 min, how many minutes of work does Young suggest?
Numeric
With those values, what goodput percentage does 1−C/τ−τ/(2M) approximate at the optimum?
Numeric
With P=70 billion, TP=8, PP=4, DP=32 and ZeRO-1, how many decimal GB per GPU do weight, gradient and FP32 states occupy under this lesson's accounting?
Code
Implement valid_configs(world, model): return a list of positive integer tuples (dp,tp,pp,cp) whose product is world, with tp ≤ model['node'], node divisible by tp, heads divisible by tp, layers by pp, and seq by cp.
def valid_configs(world,model):
  ...
Shift+Enter to run
Quiz
Three ranks await a collective and the fourth logged a memory error before it. What first clue should you investigate?
Key idea
Choose the mesh for memory and communication on a specific topology; a cost model guides decisions but is calibrated with measurements. A consistent, verifiable checkpoint enables recovery, with explicit limits on exact reproduction.