Distributed LLM Training: ZeRO/FSDP2, TP, Pipeline & Context Parallelism
First-principles guide to 4D LLM training: mixed-precision 16Ψ memory math, ZeRO-1/2/3 vs PyTorch FSDP2 DTensor, TP/SP, 1F1B/DualPipe bubbles, and ZigZag Context Parallelism.
End-to-end model engineering from SFT to multi-node RL: prompting & multimodal baselines, enterprise RAG, LoRA/QLoRA fine-tuning, 4D distributed training (ZeRO/FSDP2, TP/SP, 1F1B/DualPipe, Context Parallelism), GRPO math, verl rollout-training colocation, rigorous Evals, and Nov 2026 frontier benchmarks.
Browse all 12 chapters in this series ▾
- 01 Prompt Engineering Practice Guide
- 02 Multimodal AI Models Starter Guide
- 03 Retrieval-Augmented Generation (RAG) in Practice: Strategies & Production Best Practices
- 04 LLM Fine-Tuning Guide: How It Works, Real-World Use Cases, and Workflows
- 05 Distributed LLM Training: ZeRO/FSDP2, TP, Pipeline & Context Parallelism Reading
- 06 GRPO and Test-Time Compute without a Critic
- 07 Distributed RL Post-Training with verl: Colocation, Weight Resharding & Async Rollouts
- 08 Reject Benchmark Hacking: How to Build an LLM Evaluation System for Your Business (LLM-as-a-Judge)
- 09 Nov 2026 Frontier Models: GPT-6.2 Astra, Claude Fable 5.2 & Gemini 4
- 10 November 2026 Chinese Frontier LLMs: Qwen4-Max, Kimi K3.1 Pro, DeepSeek-V4, MiniMax M3.1 & GLM-5.3
- 11 Deep Dive into 11 AI Foundation Model Trends in 2026
- 12 The Critical Crossroads in AI History: Why Was *That One* Chosen Every Time?
NOTE
Executive Summary (TL;DR)
- First-Principles Mixed-Precision & Activation Math: Under standard BF16 compute + FP32 AdamW master states, a model with trainable parameters consumes of static HBM ( with FP32 gradient accumulation)—meaning a 70B dense model requires (
~1,043 GiB) before allocating a single activation tensor; while GQA + FlashAttention eliminates the quadratic attention matrix, linear activations still shatter single-GPU HBM ceilings at sequence lengths. - Orthogonal State Sharding & Intra-Layer Partitioning: Moving from DDP and ZeRO-1/2 ( parameter elements communicated per step) to ZeRO-3 / PyTorch
FSDP2( elements),fully_shardreplacesFSDP1flat-parameter packing with per-parameterDTensorsharding onDeviceMesh,torch.compile-friendly zero-copy views, and deterministicrecordStream-free memory management; pairing intra-node Tensor Parallelism (TP) with Sequence Parallelism (SP) replacesAllReducewithAllGather+ReduceScatterat identical communication volume while slashing non-TP activation memory by . - Zero-Bubble Pipelines & Load-Balanced Million-Token Contexts: Pipeline Parallelism evolves from
1F1B(bubble fraction , capping peak stored activations at microbatches) to Zero-Bubble PP (splitting backward into critical-path and bubble-filling ) and DeepSeek-V3's bidirectionalDualPipe(overlapping cross-node MoEAll-to-Allinside forward/backward compute); for long-context training, ZigZag Ring Attention pairs symmetric sub-chunks to eliminate the causal-mask idle stall of naive Ring Attention while breaking DeepSpeed-Ulysses's head-count ceiling.
Introduction: Why Frontier LLM Training Is a 4D Optimization Game Across HBM Walls and Bandwidth Cliffs
Once you graduate from single-node 7B LoRA runs in our End-to-End LLM Fine-Tuning Guide to full-parameter 70B post-training, million-token context extension, or multi-node policy updates in Test-Time Compute and GRPO in Practice and Distributed RL Post-Training with verl, the physical limits of an 80GiB H100/H800 GPU bring naive scripts to an immediate halt.
Modern distributed training frameworks project a massive computational graph onto physical cluster interconnects across four orthogonal parallelism axes (4D Parallelism, extended to 5D by Expert Parallelism EP for sparse MoE models):
- Data Parallelism (
DP/ZeRO/FSDP2/HSDP): Partitions batches across replicas while sharding optimizer states, gradients, and weights viaReduceScatterandAllGather; - Tensor & Sequence Parallelism (
TP + SP): Splits intra-layer matrix multiplications along row/column axes and shards residual/normalization activations along tokens, relying on high-bandwidth intra-node Scale-Up links; - Pipeline Parallelism (
PP): Slices model depth across stages, exchanging compact boundary activations across nodes via lightweight point-to-point (P2P) transfers; - Context Parallelism (
CP): Shards every intermediate activation along ultra-long sequences (), communicating exclusively inside the Self-Attention operator viaAll-to-Allor P2P KV rings.
flowchart TD
subgraph Cluster["4D + EP Distributed Parallelism Mapped onto Cluster Interconnect Tiers"]
direction TB
ScaleUp["Intra-Node / Intra-Rack Scale-Up Domain (NVLink 4/5: 900-1800 GB/s bidir, sub-us latency)"]
ScaleOut["Inter-Node Scale-Out Domain (400G/800G InfiniBand or RoCE RDMA: 50-100 GB/s unidir)"]
TP["TP + SP (Intra-layer GEMM & sequence split: 4 blocking AllGather/ReduceScatter per layer)"]
CP["CP (128K-1M long-context split: Intra-node Ulysses All-to-All + Inter-node ZigZag Ring P2P)"]
PP["PP (Inter-layer depth split: 1F1B / ZB-H1 / DualPipe lightweight cross-node P2P)"]
DP["FSDP2 / HSDP (Intra-node dp_shard AllGather + Inter-node dp_replicate gradient AllReduce)"]
ScaleUp --> TP
ScaleUp --> CP
ScaleOut --> PP
ScaleOut --> DP
end
Every sound cluster sizing decision begins not with YAML trial-and-error, but with a byte-exact ledger of HBM capacity and collective communication volume.
1. Mixed-Precision Memory & Activation Ledger from First Principles
Per-GPU peak HBM consumption during training is the sum of static model states (parameters, gradients, and optimizer states) and dynamic residual memory (saved forward activations, transient collective buffers, and allocator fragmentation).
1.1 Deriving the Exact 16Ψ (and 18Ψ) Byte Static Memory Formula
Let denote the number of trainable parameters. Frontier LLM training universally pairs BF16 forward/backward compute with FP32 AdamW master states. Why not update BF16 parameters directly in BF16? Because BF16 allocates 1 sign bit, 8 exponent bits, and only 7 explicit mantissa bits, yielding a machine epsilon near of . At production learning rates , normalized AdamW step updates sit around . Applying directly in BF16 triggers catastrophic mantissa swamping (), freezing convergence altogether.
Consequently, standard mixed-precision training maintains four static state tensors in HBM:
- BF16 Compute Weights (): Consumed by Tensor Core GEMMs during forward and backward passes at , totaling ;
- BF16 Gradients (): Produced during backpropagation at , totaling (note: when accumulating or reducing gradients in FP32 across microbatches or large DP groups via
reduce_dtype=fp32to prevent low-bit underflow, this buffer doubles to ); - FP32 Master Weights (): High-precision primary copy absorbing small optimizer updates at , totaling ;
- FP32 AdamW First & Second Moments (): Exponential moving averages of gradients () and squared gradients (), totaling .
Summing all four components yields the canonical static mixed-precision memory equation:
Let us verify this on a 70B dense model ():
- Decimal footprint: ( at );
- Binary HBM capacity (): (
~1,043 GiB).
In stark physical terms: before feeding a single token or allocating a single activation tensor, the static training states of a 70B model already exceed an entire 8× H100-80GB server's aggregate HBM () by !
1.2 Per-Layer Activation Memory: Classic Megatron MHA vs. Modern GQA + FlashAttention
Once static states are sharded, forward activations saved for backward gradient computation become the dominant HBM bottleneck. Let be sequence length, micro-batch size, hidden dimension, query attention heads, GQA key-value heads, and the SwiGLU intermediate width.
1. Classic Megatron-LM Multi-Head Attention (MHA) Formula: In a pre-FlashAttention Transformer block (LayerNorm + GeLU MLP of width + BF16 activations + 1-byte dropout masks), Korthikanti et al. (MLSys '23) derived the exact byte count saved per layer:
- Attention sub-block: Input LayerNorm (), shared QKV input (), and saved for (), saved for score-value matmul (), output projection input (), and residual dropout mask () sum to ; meanwhile, explicitly materializing the attention matrix stores Softmax probabilities (), attention dropout mask (), and dropped-out probabilities (), adding ;
- MLP sub-block: Input LayerNorm (), Linear-1 input (), GeLU input (), Linear-2 input (), and dropout mask () sum to .
Combining both sub-blocks yields the classic Megatron-LM activation equation:
Notice how violently the quadratic term explodes: for at , the term alone demands per layer—over across 80 layers!
2. Modern Stack (GQA + SwiGLU + RMSNorm + FlashAttention-2/3) & Selective Checkpointing: Modern foundation models (Llama-3, Qwen2.5, DeepSeek) fundamentally reshape this curve:
- FlashAttention eliminates HBM materialization: By tiling in on-chip SRAM with online softmax rescaling, FlashAttention never writes the score matrix to HBM. It saves only the final output () and a tiny FP32 log-sum-exp vector (), collapsing per-layer activation complexity to strictly linear ;
- GQA shrinks projections: Key and value activations shrink to (for Llama-3-70B with , saved tensors drop from to );
- SwiGLU MLP dominates remaining memory: Without dropout, modern uncheckpointed activation memory per layer is . For Llama-3-70B (), this equals , of which SwiGLU (
gate_proj,up_proj, and ) accounts for ()! - Selective Activation Checkpointing (SAC): While Full Block Checkpointing reduces steady-state storage to just the layer-boundary input at the cost of extra training FLOPs (re-running every GEMM in backward), PyTorch's Op-Level Selective Activation Checkpointing (
SAC) caches compute-intensive GEMM outputs while discarding and recomputing FLOP-free, memory-heavyRMSNorm,RoPE, andSwiGLUelementwise intermediates (or checkpoints every -th layer), cutting activation HBM by for under FLOP overhead.
| Activation Ledger Metric | Classic MHA (No FlashAttn) | Modern GQA + FlashAttn (No Checkpointing) | Modern Stack + Full Block Checkpointing |
|---|---|---|---|
| Per-Layer Complexity | + 1 active layer peak | ||
| Llama-3-70B (, 80 Layers) | ( blowup) | (purely linear, SwiGLU-heavy) | boundary inputs + active |
| Backward Recompute FLOP Overhead | (local SRAM tile recompute only) | (re-executes all QKV/O/MLP GEMMs) |
2. Data Parallelism Evolution: DDP, ZeRO-1/2/3, and PyTorch FSDP2 (`DTensor` + HSDP)
To fit static states across data-parallel GPUs, Microsoft DeepSpeed ZeRO (Zero Redundancy Optimizer) and PyTorch FSDP systematically eliminate the redundant state replication of DistributedDataParallel (DDP).
2.1 Exact Static Memory & Collective Communication Volume Across DDP and ZeRO-1/2/3
Let be the DP degree and the parameter count, with BF16 () forward/backward collectives (taking the ring/tree scaling factor for large ). Below we report communication in both parameter elements (, Rajbhandari SC'20 convention) and BF16 bus bytes:
| Strategy | Sharded States | Per-GPU Static Footprint (Bytes, Base) | Per-Step Collectives Breakdown | Comm Volume per Step (Elements / BF16 Bytes) | 70B @ Static HBM |
|---|---|---|---|---|---|
| DDP | None (replicated) | Backward grad AllReduce ( elems) | elems () | (OOM) | |
| ZeRO-1 () | Optimizer () | Grad ReduceScatter () + Updated param AllGather () | elems () | (OOM) | |
| ZeRO-2 () | Optimizer + Grads () | Streaming grad ReduceScatter () + Step-end AllGather () | elems () | (>80GiB) | |
| ZeRO-3 / FSDP () | All states () | Fwd AllGather () + Bwd AllGather () + Grad ReduceScatter () | elems () | (Fits cleanly) |
Two foundational architectural insights jump straight out of this table:
- ZeRO-1 and ZeRO-2 Are Communication-Free Lunches: Because a ring
AllReduceis physically implemented as 1ReduceScatter( elements) + 1AllGather( elements), ZeRO-1 and ZeRO-2 transfer the exact same elements () as DDP while slashing static memory from toward ! Whenever a single GPU can comfortably hold BF16 weights (e.g., 7B–14B models on 80GiB GPUs), ZeRO-2 /FSDP2(reshard_after_forward=False)strictly dominates ZeRO-3. - ZeRO-3 / FSDP Trades Communication ( vs. ) for Unbounded Capacity Scaling: Sharding the weights requires materializing each layer via
AllGatherbefore forward () and freeing it right after, materializing it again viaAllGatherbefore backward (), and streamingReduceScatteron gradients (), totaling elements (). With double-buffered async prefetching, layer 'sAllGatheroverlaps cleanly behind layer 's Tensor Core GEMMs.
2.2 Why PyTorch `FSDP2` (`fully_shard`) Superseded `FSDP1`
While PyTorch's original FullyShardedDataParallel (FSDP1) popularized sharded training, its internal FlatParameter abstraction created severe production pain points. Stabilized across PyTorch 2.4–2.6+, FSDP2 (torch.distributed.fsdp.fully_shard) re-architected sharding from the ground up:
- Per-Parameter
DTensoronDeviceMeshvs.FlatParameterConcatenation:FSDP1flattened and concatenated every parameter inside a wrapped module into a single monolithic 1DFlatParameterbuffer. That destroyed clean parameter boundaries—complicating frozen-backbone + LoRA fine-tuning, mixed parameter dtypes (FP32 norms alongside BF16 linears), optimizer param-group weight-decay exclusions, and distributed checkpoint (DCP) resharding, while causing frequenttorch.compilegraph breaks.FSDP2represents eachnn.Parameterindividually as aDTensorsharded along dim-0 (Shard(0)) on aDeviceMesh. Module hierarchies, state-dict keys, heterogeneous dtypes, andDCPwork natively out of the box with zero un-flattening glue.
- Zero-Copy View Semantics & End-to-End
torch.compileTracing:FSDP2exposes functional collective primitives (all_gather_copy_in,reduce_scatter_tensor) directly to TorchInductor, enabling whole-graph compilation to fuse parameter copy-ins and reorder collectives around compute kernels.
- Deterministic Stream-Free Memory Management (
recordStreamElimination):FSDP1relied on CUDA'sTensor.record_stream()to stop the compute stream from overwriting buffers still in flight on the NCCL stream. Whenever CPU kernel launches ran ahead of GPU execution,record_streamartificially extended buffer lifetimes insideCUDACachingAllocator, causing multi-gigabyte fragmentation spikes, phantom OOMs at logical usage, and costlycudaDeviceSynchronizecache flushes.FSDP2completely eliminatesrecord_stream(): it coordinates explicit double-bufferedAllGather/ReduceScatterqueues using deterministictorch.cuda.Eventfences between communication and compute streams. Unsharded buffers are released the instant a layer finishes, delivering higher MFU and a rock-steady HBM watermark across thousands of steps.
- 2D Hybrid Sharded Data Parallelism (
HSDP):- Passing a 2D
DeviceMeshlabeled("dp_replicate", "dp_shard")tofully_shardconfines chattyAllGather/ReduceScattercollectives inside high-bandwidth intra-node NVLink (dp_shard=8), while running a single coalesced gradientAllReduceacross inter-node RDMA scale-out links (dp_replicate) at optimizer step boundaries.
- Passing a 2D
3. Tensor Parallelism (`TP`) + Sequence Parallelism (`SP`): Intra-Layer Partitioning & Bandwidth Equivalence
At 70B–405B scale or sequence lengths, pure FSDP2 hits two walls: transient unsharded layer activations still burst on single GPUs, and scaling pure DP across hundreds of GPUs starves per-GPU micro-batch arithmetic intensity. Megatron-LM's Tensor Parallelism (TP) and Sequence Parallelism (SP) solve both inside a high-speed Scale-Up domain.
3.1 Megatron-LM Column-Parallel + Row-Parallel Pairing
Splitting arbitrary linear layers in isolation would trigger a collective after every GEMM. Instead, Megatron-LM pairs Column-Parallel first projections with Row-Parallel second projections across TP ranks:
- SwiGLU MLP Block:
- Partition
gate_projandup_projweights column-wise into . Because and elementwise act independently per channel, each GPU computes its local intermediate slice with zero communication: - Partition
down_projrow-wise into . By block-matrix multiplication:Each rank computes partial result , followed by 1AllReducein forward (and 1 conjugateAllReduceon input gradients beforegate_upin backward).
- Partition
- GQA Self-Attention Block:
- Partition query heads and KV heads across ranks ( query and KV heads per rank, requiring ). QKV projections run Column-Parallel, local FlashAttention and RoPE run completely communication-free, and output projection runs Row-Parallel with 1
AllReduce.
- Partition query heads and KV heads across ranks ( query and KV heads per rank, requiring ). QKV projections run Column-Parallel, local FlashAttention and RoPE run completely communication-free, and output projection runs Row-Parallel with 1
Thus, standard TP executes 2 AllReduce collectives in forward and 2 AllReduce collectives in backward per Transformer layer.
3.2 Sequence Parallelism (`SP`): Slashing Non-TP Activations by 1/t at Zero Extra Bandwidth
Standard TP leaves an expensive blind spot: outside the TP blocks—across RMSNorm / LayerNorm, Dropout, and the residual stream—every [b, s, h] activation tensor is identically replicated across all TP ranks! Because those point-wise ops are independent along the token axis , Sequence Parallelism (SP) shards them into [b, s/t, h]:
flowchart LR
subgraph PureTP["Standard TP Sub-Block (RMSNorm & Residuals Replicated as [b, s, h])"]
direction LR
T1["RMSNorm [b, s, h]"] --> T2["f: Fwd Identity / Bwd AllReduce"]
T2 --> T3["Colwise GEMM [b, s, h_ffn/t]"] --> T4["Rowwise GEMM Partial [b, s, h]"]
T4 --> T5["g: Fwd AllReduce / Bwd Identity"] --> T6["Residual Add [b, s, h]"]
end
subgraph TPSP["Modern TP + SP Sub-Block (Zero Replication, Identical Comm Volume)"]
direction LR
S1["SP RMSNorm [b, s/t, h]"] --> S2["g_bar: Fwd AllGather / Bwd ReduceScatter"]
S2 --> S3["Colwise GEMM [b, s, h_ffn/t]"] --> S4["Rowwise GEMM Partial [b, s, h]"]
S4 --> S5["f_bar: Fwd ReduceScatter / Bwd AllGather"] --> S6["SP Residual Add [b, s/t, h]"]
end
Let us prove the exact communication equivalence for one sub-block (e.g., MLP) operating on a BF16 activation tensor of size ( elements):
- Standard
TPforward: Executes 1AllReduceat thedown_projoutput. Since ring/NVSwitchAllReducedecomposes into 1ReduceScatter() + 1AllGather(), it transfers elements ( total, or per collective phase). TP + SPforward:- Executes 1
AllGatheralong sequence dim beforegate_up(), transferring ( elements); - Executes 1
ReduceScatteralong sequence dim afterdown_proj(summing partial GEMMs and scattering back to ), transferring ( elements).
- In backward, the autograd duals mirror this identically: 1
AllGather() afterdown_projand 1ReduceScatter() beforegate_up.
- Executes 1
Because 1 AllReduce 1 AllGather + 1 ReduceScatter, TP + SP incurs zero extra communication bytes over pure TP while slashing non-TP RMSNorm, Dropout, and residual activation memory by —bringing every single activation tensor in the Transformer onto true scaling!
IMPORTANT
Why TP Must Remain Inside a Single NVLink Scale-Up Domain Unlike FSDP's layer-prefetchable AllGather, TP + SP collectives sit directly on the critical serial execution path ( blocking collectives per layer across forward + backward, or serial barriers per microbatch on an 80-layer 70B model). Stepping across an 8-GPU chassis boundary onto RDMA NICs—a unidirectional bandwidth drop from NVLink 5—stalls Tensor Cores for of step time. Consequently, keep on standard 8-GPU HGX nodes, and only scale up to inside unified rack-scale fabrics like NVIDIA GB200/GB300 NVL72 ( bidirectional NVLink 5), as analyzed in Rack-Scale SuperPODs & Collectives Deep Dive.
4. Pipeline Parallelism (`PP`): From `GPipe` & `1F1B` to Interleaved `1F1B`, Zero-Bubble & `DualPipe`
When scaling across dozens of nodes where intra-node TP=8 cannot hold the model alone and scale-out links cannot absorb ZeRO-3's traffic, Pipeline Parallelism (PP) partitions layers sequentially across stages, sending only compact [b, s/t, h] boundary tensors via P2P. Its central adversary is the pipeline bubble.
4.1 Pipeline Bubble Derivation & Why `1F1B` Caps In-Flight Memory at p Microbatches
Suppose a pipeline has stages and splits each optimizer step into microbatches (), with per-stage forward and backward latencies and :
- Ideal compute duration: ;
- Warm-up & drain bubble duration: Stage waits forward steps before starting microbatch 1 and leaves backward steps at step drain, giving ;
- Pipeline Bubble Fraction (relative to ideal compute):
Driving the bubble below requires , exposing the pivotal memory divide between GPipe and 1F1B:
GPipe( Memory Blowup): Executes all forwards () before , forcing every stage to cache activations for all microbatches simultaneously—making large impossible without OOM.1F1B(Peak Memory Capped at ): Achieves the exact same bubble ratio , but stage runs only warm-up forwards before alternating 1 backward (immediately freeing microbatch 's activations!) with 1 forward . Worst-case Stage 0 holds at most in-flight microbatches regardless of how large grows!
4.2 Interleaved `1F1B`, Zero-Bubble (`Bx` / `Bw` Split) & DeepSeek-V3 `DualPipe`
Modern training stacks crush the remaining bubble via three progressively sharper schedules:
Interleaved
1F1B( Virtual Stages): Assigning each GPU non-contiguous layer chunks (e.g., for , GPU 0 holds layers and ) shrinks each chunk's execution time by , reducing the bubble fraction to:at the cost of higher cross-stage P2P activation traffic.
Zero-Bubble Pipeline Parallelism (
ZB-H1/ZB-V, Qi et al. ICLR '24): Backpropagation through is not monolithic—it comprises two independent GEMMs:- (Input Activation Gradient, ): Strictly on the inter-stage critical path, because Stage is blocked until it receives ;
- (Weight Gradient, ): Zero inter-stage dependency! Once Stage holds and saved , only accumulates into local parameter gradients needed at
optimizer.step().ZB-H1executes eagerly to unblock upstream stages and delays to slot directly into warm-up/drain bubble gaps—slashing1F1B's bubble by at identical -microbatch memory, while V-foldedZB-Vapproaches near-zero compute bubbles.
DeepSeek-V3
DualPipe(Bidirectional Pipeline + Compute-Comm Overlap): When training 671B-parameter MoE models (PP=16, EP=64), cross-node Expert Parallelism (see MoE Expert Parallelism Inference Engine Design) injects two heavy RDMAAll-to-Allcollectives (DispatchandCombine) into every MoE block.DualPipelaunches two independent microbatch streams simultaneously from both ends of the pipeline (Stage and Stage , with mirrored model chunks on symmetric stages). On every GPU, forward compute () of Stream A is paired and overlapped with backward () of Stream B: while Stream A drives Tensor Cores across most SMs, Stream B concurrently executes cross-node InfiniBand MoEAll-to-Allusing just 20 dedicated communication SMs—hiding nearly of EP and PP communication while halving pipeline bubbles to scale!
flowchart TD
subgraph S1F1B["Standard 1F1B Schedule (Stage 0 View: Monolithic B = Bx + Bw Leaves Tail Bubbles)"]
direction LR
A1["Warm-up: F1 → F2 → F3 → F4"] --> A2["Steady State: B1 → F5 → B2 → F6"]
A2 --> A3["Drain Phase: B3 → [Idle Bubble] → B4 → [Idle Bubble]"]
end
subgraph ZBDual["Zero-Bubble (ZB-H1) & DualPipe Core Mechanics (Bx/Bw Split + Bidirectional Overlap)"]
direction LR
Z1["Critical Path First: Emit Bx immediately to unblock upstream stage"] --> Z2["Bubble Backfill: Defer local Bw GEMMs into idle pipeline slots"]
Z2 --> Z3["DualPipe Bidirectional: Overlap Stream-A Fwd GEMMs with Stream-B MoE All-to-All"]
end
5. Context Parallelism (`CP`) for 128K–1M Long-Context Training
At tokens, even TP=8 + SP with Full Activation Checkpointing breaks down: at (1M), storing 80 checkpointed [b, s/8, h] boundary tensors alone consumes , and TP + SP's AllGather still reconstructs the full 1M-token sequence before every linear projection.
Context Parallelism (CP, degree ) shards all activations permanently as without ever gathering the full sequence onto one GPU. Because RMSNorm, RoPE, Linear, and SwiGLU act token-wise independently, Self-Attention is the only operator requiring cross-GPU communication, spawning two paradigms: DeepSpeed-Ulysses and Ring Attention.
5.1 DeepSpeed-Ulysses vs. Ring Attention: Head Ceilings and P2P Overlap
DeepSpeed-Ulysses (
All-to-AllSequence-to-Head Transpose):- Before Attention, are sequence-sharded as . An
All-to-Allacross ranks transposes partitioning to attention heads: . Each rank runs standard local FlashAttention over the full sequence for heads, followed by an inverseAll-to-Allback to . - Hard Limitation: Strictly bounded by KV head count ! On Llama-3-70B or Qwen2.5-72B (), once intra-node
TP=8shards those 8 KV heads, Ulysses cannot scaleCPfurther without duplicating KV heads across ranks.
- Before Attention, are sequence-sharded as . An
Ring Attention (Overlapped P2P KV Ring + Blockwise Online Softmax):
- Each rank keeps stationary and circulates around a -GPU ring via async
isend/irecvover steps, merging partial outputs via FlashAttention's exact log-sum-exp rescaling . - Overlap Arithmetic Intensity: Per ring step, compute is while GQA KV P2P volume is , giving a ratio of . For Llama-3-70B () at , (H100 BF16 vs. 400G IB balance point)—hiding cross-node RDMA transfers 100% behind compute with zero head-count limit!
- Each rank keeps stationary and circulates around a -GPU ring via async
5.2 The Causal Mask Load-Imbalance Trap & Striped / ZigZag Ring Attention
If we naively slice a causal sequence contiguously into across Ring Attention ranks, MFU collapses by nearly half!
Why Naive Contiguous Slicing Wastes ~50% Compute: Under autoregressive causal masking ():
- Rank (tokens ) computes only its own lower-triangular diagonal ( block) on step 0; on steps , incoming lie strictly in the future () and are 100% masked out ( FLOPs)!
- Rank (final tokens ) computes dense past blocks plus its causal triangle = blocks—doing more work than Rank ! Synchronizing at the step barrier forces all ranks to wait for Rank , leaving of cluster Tensor Cores completely idle!
How ZigZag / Striped Ring Attention Restores 100% Balance: Adopted in Megatron-Core and frontier 128K–1M trainers, ZigZag Ring Attention splits the sequence into equal sub-chunks of length and assigns the symmetric front-back pair to Rank :
flowchart LR
subgraph Naive["Naive Contiguous Split (c=4, 4 Chunks: Severe Straggler Skew, ~43%-50% Idle)"]
direction TB
N0["Rank 0 holds [C0]: Computes 0.5 causal block only (3 steps completely idle!)"]
N3["Rank 3 holds [C3]: Computes 3 full blocks + 0.5 diagonal = 3.5 blocks (7x skew!)"]
end
subgraph ZigZag["ZigZag Symmetric Split (c=4, 2c=8 Sub-Chunks: Exact 2 Sub-Blocks per GPU Every Step)"]
direction TB
Z0["Rank 0 holds (S0, S7): S0 does 0.5 + S7 does 7.5 = 8.0 sub-blocks"]
Z1["Rank 1 holds (S1, S6): S1 does 1.5 + S6 does 6.5 = 8.0 sub-blocks"]
Z2["Rank 2 holds (S2, S5): S2 does 2.5 + S5 does 5.5 = 8.0 sub-blocks"]
Z3["Rank 3 holds (S3, S4): S3 does 3.5 + S4 does 4.5 = 8.0 sub-blocks"]
end
Let us verify the exact FLOP invariance on Rank :
- Identical Total Work: attends to sub-blocks, while attends to sub-blocks. Summing them cancels identically:
- Identical Work on Every Single Ring Step: When Rank processes KV pair from Rank :
- For : sub-blocks;
- For (): both and attend densely to () and skip () = sub-blocks;
- For (): skips both (), while attends densely to both and () = sub-blocks!
Every GPU executes exactly 2 dense sub-blocks on every tick of the ring, achieving load balance! In 1M-token production stacks, 2D Unified Sequence Parallelism (USP) pairs intra-node Ulysses=8 over NVLink with inter-node ZigZag Ring=8 over RDMA for effortless 64-way CP.
6. Production Implementation & Cluster Sizing Blueprint
Let us put all pieces together in clean, syntactically valid PyTorch 2.5+ (DeviceMesh + TP/SP + FSDP2) code following the TorchTitan production pattern.
6.1 PyTorch 2.5+ 3D DeviceMesh (`dp_replicate`, `dp_shard`, `tp`) + SP + FSDP2
This script composes intra-node ColwiseParallel / RowwiseParallel / SequenceParallel with 2D HSDP fully_shard without altering a single line of mathematical forward() code (launch via torchrun --nnodes=8 --nproc_per_node=8 train_3d.py):
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.tensor import Replicate, Shard
from torch.distributed.tensor.parallel import (
ColwiseParallel,
PrepareModuleInput,
RowwiseParallel,
SequenceParallel,
parallelize_module,
)
from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard
class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x: torch.Tensor) -> torch.Tensor:
norm_x = x.float() * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps)
return norm_x.type_as(x) * self.weight
class FeedForward(nn.Module):
def __init__(self, dim: int, hidden_dim: int):
super().__init__()
self.w1 = nn.Linear(dim, hidden_dim, bias=False) # gate_proj
self.w3 = nn.Linear(dim, hidden_dim, bias=False) # up_proj
self.w2 = nn.Linear(hidden_dim, dim, bias=False) # down_proj
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.w2(F.silu(self.w1(x)) * self.w3(x))
class GQAAttention(nn.Module):
def __init__(self, dim: int, n_heads: int, n_kv_heads: int):
super().__init__()
self.n_heads = n_heads
self.n_kv_heads = n_kv_heads
self.head_dim = dim // n_heads
self.wq = nn.Linear(dim, n_heads * self.head_dim, bias=False)
self.wk = nn.Linear(dim, n_kv_heads * self.head_dim, bias=False)
self.wv = nn.Linear(dim, n_kv_heads * self.head_dim, bias=False)
self.wo = nn.Linear(n_heads * self.head_dim, dim, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
bsz, seqlen, _ = x.shape
# Local head counts adjust automatically after column-wise TP sharding
q = self.wq(x).view(bsz, seqlen, -1, self.head_dim).transpose(1, 2)
k = self.wk(x).view(bsz, seqlen, -1, self.head_dim).transpose(1, 2)
v = self.wv(x).view(bsz, seqlen, -1, self.head_dim).transpose(1, 2)
out = F.scaled_dot_product_attention(q, k, v, is_causal=True, enable_gqa=True)
return self.wo(out.transpose(1, 2).contiguous().view(bsz, seqlen, -1))
class TransformerBlock(nn.Module):
def __init__(self, dim: int, hidden_dim: int, n_heads: int, n_kv_heads: int):
super().__init__()
self.attention_norm = RMSNorm(dim)
self.attention = GQAAttention(dim, n_heads, n_kv_heads)
self.ffn_norm = RMSNorm(dim)
self.feed_forward = FeedForward(dim, hidden_dim)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# Under TP + SP, residual x stays sequence-sharded as [batch, seq_len // tp_size, dim]
x = x + self.attention(self.attention_norm(x))
x = x + self.feed_forward(self.ffn_norm(x))
return x
class MiniLLM(nn.Module):
def __init__(self, vocab_size: int = 128256, dim: int = 4096, n_layers: int = 8):
super().__init__()
self.tok_embeddings = nn.Embedding(vocab_size, dim)
self.layers = nn.ModuleList([
TransformerBlock(dim=dim, hidden_dim=14336, n_heads=32, n_kv_heads=8)
for _ in range(n_layers)
])
self.norm = RMSNorm(dim)
self.output = nn.Linear(dim, vocab_size, bias=False)
def forward(self, tokens: torch.Tensor) -> torch.Tensor:
h = self.tok_embeddings(tokens)
for layer in self.layers:
h = layer(h)
return self.output(self.norm(h))
def apply_3d_parallel(
model: MiniLLM,
dp_replicate: int,
dp_shard: int,
tp_size: int,
) -> tuple[MiniLLM, dist.device_mesh.DeviceMesh]:
# 1. Initialize 3D hardware-aligned DeviceMesh: (inter-node replicate, intra-node shard, intra-node TP)
mesh_3d = init_device_mesh(
"cuda",
(dp_replicate, dp_shard, tp_size),
mesh_dim_names=("dp_replicate", "dp_shard", "tp"),
)
tp_mesh = mesh_3d["tp"]
dp_mesh = mesh_3d["dp_replicate", "dp_shard"] if dp_replicate > 1 else mesh_3d["dp_shard"]
# 2. Apply TP + SP first: embeddings emit Shard(1) directly into the SP residual stream
parallelize_module(
model,
tp_mesh,
{
"tok_embeddings": RowwiseParallel(
input_layouts=Replicate(),
output_layouts=Shard(1),
),
"norm": SequenceParallel(),
"output": ColwiseParallel(
input_layouts=Shard(1),
output_layouts=Replicate(),
),
},
)
for layer in model.layers:
parallelize_module(
layer,
tp_mesh,
{
"attention_norm": SequenceParallel(),
"attention": PrepareModuleInput(
input_layouts=(Shard(1),),
desired_input_layouts=(Replicate(),),
),
"attention.wq": ColwiseParallel(),
"attention.wk": ColwiseParallel(),
"attention.wv": ColwiseParallel(),
"attention.wo": RowwiseParallel(output_layouts=Shard(1)),
"ffn_norm": SequenceParallel(),
"feed_forward": PrepareModuleInput(
input_layouts=(Shard(1),),
desired_input_layouts=(Replicate(),),
),
"feed_forward.w1": ColwiseParallel(),
"feed_forward.w3": ColwiseParallel(),
"feed_forward.w2": RowwiseParallel(output_layouts=Shard(1)),
},
)
# 3. Apply FSDP2 (fully_shard) bottom-up, composing 2D/3D DTensors across (dp_shard, tp)
mp_policy = MixedPrecisionPolicy(
param_dtype=torch.bfloat16,
reduce_dtype=torch.float32, # FP32 gradient reduction prevents underflow at high DP degree
)
for layer in model.layers:
fully_shard(layer, mesh=dp_mesh, mp_policy=mp_policy, reshard_after_forward=True)
fully_shard(model, mesh=dp_mesh, mp_policy=mp_policy, reshard_after_forward=True)
return model, mesh_3d
if __name__ == "__main__":
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
dist.init_process_group(backend="nccl")
world_size = dist.get_world_size()
# Example: 64 GPUs (8x8) -> dp_replicate=2, dp_shard=8, tp=4; 8 GPUs -> 1x2x4
tp_degree = 4
dp_shard_degree = min(8, world_size // tp_degree)
dp_rep_degree = world_size // (dp_shard_degree * tp_degree)
with torch.device("meta"):
llm = MiniLLM()
llm, mesh = apply_3d_parallel(llm, dp_rep_degree, dp_shard_degree, tp_degree)
llm.to_empty(device="cuda") # Materialize only local 1/(dp_shard * tp) DTensor shards on HBM
dist.destroy_process_group() Note the with torch.device("meta") + to_empty(device="cuda") idiom: instantiating 8 copies of a 70B model in CPU RAM per node immediately triggers host OOM. Constructing the model on meta, applying TP + FSDP2 DTensor sharding metadata first, and materializing only local shards directly on CUDA before streaming weights via torch.distributed.checkpoint is mandatory at 70B+ scale.
6.2 Cluster Topology Decision Table (7B to 671B MoE Across 8–512 GPUs)
Never enable extra parallelism axes unnecessarily—every added dimension introduces new collective barriers. Use this production sizing matrix across 80GiB/141GiB H100/H800 or GB200 clusters:
| Workload & Model Scale | Cluster Size | Recommended Parallelism Recipe | Architectural Rationale |
|---|---|---|---|
| 7B–8B Dense (4K–32K SFT / GRPO) | 8 GPUs (1× HGX) | FSDP2 (dp_shard=8), TP=1, PP=1, CP=1 | Static state is just (); TP=1 avoids all 4 blocking intra-layer collectives, sustaining MFU. |
| 7B–8B Dense (128K–512K Long-Context) | 32 GPUs (4× HGX) | FSDP2 (dp_shard=8) × CP=4/8 (ZigZag Ring) | Weights are small, 512K activations are huge; ZigZag Ring CP shards sequence memory while hiding KV P2P inside FlashAttention. |
| 70B–72B Dense (8K–32K SFT / RL) | 64 GPUs (8× HGX) | HSDP (dp_rep=2, dp_shard=8) × TP=4 (+SP) | Static ; intra-node TP=4 + SP slashes layer & logit spikes while HSDP confines AllGather inside NVLink. |
| 70B–72B Dense (128K–256K Long-Context) | 128–256 GPUs (16–32× HGX) | TP=8 (+SP) × CP=4–8 (ZigZag) × PP=2 × ZeRO-1 | Intra-node TP=8 saturates 8 GQA KV heads; cross-node ZigZag Ring CP scales sequence orthogonally without head replication. |
| 671B MoE (37B Active) (DeepSeek-V3 Scale) | 256–512 GPUs (H800 or NVL72) | TP=1 × PP=8–16 (DualPipe) × EP=64 × ZeRO-1 | static state; DualPipe hides cross-node EP=64 MoE All-to-All behind forward/backward GEMMs (fits inside 1 rack on NVL72). |
Frequently Asked Questions (FAQ)
Q1: Since a 70B model's static state takes only 16.3 GiB/GPU under 64-GPU `FSDP2` (`TP=1`), why does it suddenly OOM at 32K sequence length unless we enable `TP=4/8 + SP`?
Because single-GPU HBM ceilings are broken by unsharded transient spikes, not persistent shards! Under TP=1, increasing cannot shrink two massive per-GPU buffers: first, the active layer's uncheckpointed SwiGLU intermediate tensors reconstructed during backward; second—and most lethal—the output vocabulary cross-entropy logit spike. On Qwen2.5-72B (vocabulary ), materializing an unsharded [1, 32768, 152064] FP32 logit tensor plus its gradient instantaneously demands ! Enabling TP=4/8 + SP alongside Vocab-Parallel Cross-Entropy (or Liger-Kernel's chunked FusedLinearCrossEntropy) slashes this transient spike by .
Q2: When combining Activation Checkpointing with `FSDP2` or `ZeRO-3`, does recomputing the forward pass during backward trigger an extra `AllGather` (`4Ψ` instead of `3Ψ`)?
Only if your checkpoint wrapper spans across multiple fully_shard units! If you wrap a multi-layer sequential stage inside one checkpoint call while applying fully_shard per inner TransformerBlock, backward recomputation must AllGather and free each block's weights once during recompute and again during gradient propagation—inflating communication from to . Always apply activation checkpointing inside (or 1-to-1 per) each TransformerBlock before calling fully_shard(layer): FSDP2 then executes just 1 backward AllGather per block, retaining the unsharded BF16 parameters across local forward recomputation and immediate backward gradient computation to preserve volume.
Q3: Why set `reduce_dtype=torch.float32` in `FSDP2` `MixedPrecisionPolicy` when it doubles `ReduceScatter` traffic compared to BF16?
At data-parallel scales of , FP32 gradient reduction is critical for numerical stability. When per-rank gradients are pre-divided by or accumulated across microbatches, deep residual and embedding gradients routinely dip to . Summing 64–256 BF16 tensors (7 mantissa bits) introduces severe non-associative rounding drift and underflow to zero. While reduce_dtype=torch.float32 raises ReduceScatter volume from to (increasing total step volume from to , ), suppressing cross-rank syncs on intermediate gradient-accumulation microsteps keeps wall-clock overhead below while matching single-node FP32 reference convergence.
Q4: On GQA models with only 8 KV heads (like Llama-3-70B, `n_kv_heads=8`), how can we combine intra-node `TP=8` with `CP=8` for 512K training without hitting Ulysses's head ceiling?
This is precisely where ZigZag Ring Attention shines over standalone DeepSpeed-Ulysses. Once intra-node TP=8 shards all 8 KV heads across 8 NVLink GPUs ( local KV head per rank), Ulysses has zero head divisibility left unless you wastefully replicate KV heads across nodes. ZigZag Ring Attention is completely orthogonal to head sharding: configure intra-node GPUs as TP=8 (+SP) (8 Q heads and 1 KV head per GPU), and group GPUs sharing the same local_rank across 8 nodes into a cross-node CP=8 ZigZag Ring. Each ring circulates only that rank's single local KV head ( the P2P bandwidth!), scaling cleanly to tokens with zero KV replication.