CS 336: Language Modeling from Scratch Lecture 7 — Multi-GPU Parallelism

Collectives, Blackwell Interconnects, CUDA Streams, and Distributed Training
Stanford University

From Single-GPU to Multi-GPU Parallelism

Unifying theme: compute (Tensor Cores & ALUs) is far from data. Orchestrate computation to avoid data-transfer bottlenecks.

Hardware keeps getting faster, yet frontier models keep growing—so multi-level parallelism is permanent.

The Generalized Memory & Interconnect Hierarchy

L1 Cache / Shared Mem Single GPU · On-chip SRAM HBM (B200: 8 TB/s) Single GPU · Off-chip DRAM NVLink 5.0 / NVSwitch (0.9 TB/s per direction) 8-GPU Node · 72-GPU NVL72 Rack InfiniBand (~0.05 TB/s) / Ethernet Multi-Node Pod · Multi-Pod Cluster Capacity ↑ Bandwidth ↓
  • Every tier trades bandwidth for capacity and reach
  • Crossing a boundary drops bandwidth sharply:
    • B200 HBM: 8 TB/s
    • B200 NVLink 5.0: 0.9 TB/s per direction
    • InfiniBand pod link: ~0.05 TB/s
  • Parallelism strategies must match communication frequency to tier speed

Keep frequent, fine-grained transfers inside NVLink; push infrequent transfers across InfiniBand or Ethernet.

CUDA Fundamentals: SMs, HBM, and Async Streams

Host CPU Python / PyTorch Launch GEMM Launch NCCL op async async Blackwell GPU (CUDA Device) Compute Stream FIFO queue: matmul, GeLU, attn Comm Stream (NCCL) FIFO queue: send/recv/reduce CUDA Event SMs Tensor Cores L1 / SMEM Shared by math & NCCL kernels! HBM 8 TB/s (B200) ↔ NVLink 5.0 ↔ PCIe / RDMA torch.cuda.synchronize() blocks the Host CPU until queued GPU kernels finish.

Without torch.cuda.synchronize(), a host timer only measures Python launch overhead, not GPU execution.

Multi-GPU Execution: Processes, Ranks, and Barriers

Proc 0 rank = 0 master Proc 1 rank = 1 Proc 2 rank = 2 Proc 3 rank = 3 GPU 0 cuda:0 GPU 1 cuda:1 GPU 2 cuda:2 GPU 3 cuda:3 NCCL Communicator (NVLink / NVSwitch / RDMA) SPMD: every process runs the same script, branching on rank
  • One OS process per GPU avoids Python GIL contention and isolates CUDA device contexts
  • SPMD (Single Program, Multiple Data): all $W$ ranks run the same code on different shards of data or weights
  • Two distinct synchronizations:
    • torch.cuda.synchronize(): wait for this GPU's stream
    • dist.barrier(): wait for all ranks to reach the same point

Ranks run asynchronously—without barriers or collective dependencies, one rank can race far ahead of another.

What Fills a GPU's HBM During Training?

Single-GPU Training HBM Footprint (Dynamic + Static State) Parameters model weights Gradients same shape as params Optimizer States (AdamW) momentum, variance, master copies Saved Activations scales with batch × seq × layers ← Model State (scales with parameter count) → ← Dynamic State →

Next: build the distributed communication primitives and hardware model that make sharding fast.

Part 1: Collective Communication Primitives

Naming rules: Reduce applies an associative/commutative op (sum, min, max) · Scatter is the inverse of Gather · All- means every rank receives the result.

Rooted Collectives: Broadcast and Scatter

Broadcast (rank 0 → all ranks)

Before After R0[0, 1, 2, 3] R1 R2 R3 [0, 1, 2, 3] [0, 1, 2, 3] [0, 1, 2, 3] [0, 1, 2, 3]
  • Use case: rank 0 loads initial weights or checkpoint and broadcasts to all ranks

Scatter (split from rank 0 → all ranks)

Before After R0 0 1 2 3 R1 R2 R3 [0] [1] [2] [3]
  • Conceptual stepping stone to Reduce-Scatter

Rooted collectives have a single source or destination rank; training hot loops mostly use symmetric "All-" variants.

Rooted Collectives: Gather and Reduce

Gather (inverse of Scatter → rank 0)

Before After R0[0] R1[1] R2[2] R3[3] 0 1 2 3
  • Stepping stone to All-Gather

Reduce (combine with op, e.g. SUM → rank 0)

Before After (SUM) R0[0] R1[1] R2[2] R3[3] + [6]
  • Stepping stone to All-Reduce ($0+1+2+3=6$)

Reduction operators must be associative and commutative (e.g., sum, min, max) so NCCL can reorder partial reductions freely.

Workhorse Collective: All-Gather

Input (1 shard / rank) Output (full tensor / rank) R0[0] R1[1] R2[2] R3[3] All- Gather 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3
  • Performs a Gather whose destination is every rank, not just rank 0
  • FSDP / ZeRO use case: each GPU permanently stores only $1/W$ of a layer's weights, then runs All-Gather just before forward or backward compute
  • Tensor Parallelism use case: reassemble sharded activation columns across ranks

Every rank receives $W - 1$ shards from peers, so total data moved per rank is $\frac{W-1}{W} S$ for output size $S$.

Workhorse Collective: Reduce-Scatter

Input (full tensor / rank) Output (summed shard) R0 0 1 2 3 R1 1 2 3 4 R2 2 3 4 5 R3 3 4 5 6 Reduce- Scatter [6] [10] [14] [18]
  • Reduces each slice across all ranks (column-wise sum here), then scatters one reduced slice to each rank
  • Rank $r$ receives the reduced value of slice $r$:
    • R0: $0+1+2+3 = 6$
    • R1: $1+2+3+4 = 10$
    • R2: $2+3+4+5 = 14$, R3: $18$
  • Use case: sum backward gradients across data shards while keeping storage distributed

Reduce-Scatter is the exact communication dual of All-Gather: each rank ends up with $1/W$ of the reduced tensor.

All-Reduce = Reduce-Scatter + All-Gather

Inputs (4 ranks) After Reduce-Scatter After All-Gather (= All-Reduce) R0[0, 1, 2, 3] R1[1, 2, 3, 4] R2[2, 3, 4, 5] R3[3, 4, 5, 6] Reduce-Scatter ((W − 1) / W) · S bytes [6] [10] [14] [18] All-Gather ((W − 1) / W) · S bytes [6, 10, 14, 18] [6, 10, 14, 18] [6, 10, 14, 18] [6, 10, 14, 18] Total All-Reduce volume = 2 × Reduce-Scatter volume

All-to-All: The Sparse MoE Routing Primitive

Before (row = sender rank) After (transpose!) R0 0 1 2 3 R1 4 5 6 7 R2 8 9 10 11 R3 12 13 14 15 All-to-All col j → rank j 0 4 8 12 1 5 9 13 2 6 10 14 3 7 11 15 Color = destination rank; balanced All-to-All is a distributed matrix transpose
  • Most general collective: each rank sends a distinct tensor slice to every other rank
  • Essential for sparse Mixture-of-Experts (MoE): each rank holds a batch slice and a subset of experts; All-to-All routes tokens to their assigned experts
  • Supports unbalanced splits, though routing skew slows down the overloaded rank

All-to-All stresses every GPU's per-direction link bandwidth because every rank talks to every peer simultaneously.

Part 2: GPU Interconnects — Classic vs. Datacenter

ScopeClassic Workstation / BaselineBlackwell Datacenter Fabric
Inside a GPU On-chip SRAM ↔ HBM B200 on-chip SRAM ↔ HBM at 8 TB/s
Intra-node / Rack Shared PCIe bus (v7.0, 16 lanes = 242 GB/s) NVLink 5.0 + NVSwitch (0.9 TB/s per direction per B200; up to 72 GPUs in GB200/GB300 NVL72)
Inter-node (Pod) Standard Ethernet (~200 MB/s home baseline, via CPU) InfiniBand (~0.05 TB/s, via HCA + RDMA) or RoCE across 256 nodes/pod
Inter-pod (Cluster) N/A Ethernet connecting $N$ pods

Notice the orders-of-magnitude gap between NVLink 5.0 (0.9 TB/s per direction) and inter-node InfiniBand (~0.05 TB/s): 18×.

Blackwell Intra-Domain: 8-GPU Node to 72-GPU NVL72

Classic 8-GPU Node (Ampere/Hopper era & B200 server)

GPU 0 GPU 1 GPU 2 GPU 3 GPU 4 GPU 5 GPU 6 GPU 7 NVSwitch Fabric Non-blocking NVLink (B200: 0.9 TB/s per direction)

Blackwell GB200 / GB300 NVL72 Rack

Tray 1 · 4 Blackwell GPUs Tray 2 · 4 Blackwell GPUs Tray 3 · 4 Blackwell GPUs Tray 4 · 4 Blackwell GPUs ⋮ (18 compute trays) Tray 16 · 4 Blackwell GPUs Tray 17 · 4 Blackwell GPUs Tray 18 · 4 Blackwell GPUs Rack-Scale NVSwitch 72 GPUs 1 NVLink 5.0 domain 4 GPUs/tray × 18 trays/rack = 72 GPUs

Scaling Out: Pods and Cluster Networks

Pod 1 (256 Nodes) Node 0 8 GPUs + NVLink Node 1 8 GPUs + NVLink … Node 255 8 GPUs + NVLink InfiniBand Fabric (~0.05 TB/s) GPU → PCIe → HCA (InfiniBand NIC) → IB Cable Pod N (256 Nodes) 256 Blackwell Nodes NVLink 5.0 / NVL72 domains InfiniBand / RoCE Ethernet Cluster link

Bypassing the CPU: Standard Ethernet vs. RDMA

Standard Ethernet Path (CPU in the loop) GPU 0 HBM CPU Kernel Bufferbuild TCP packets NIC 0ring buffer NIC 1ring buffer CPU 1 Kernelunpack TCP GPU 1 HBM GPUDirect RDMA Path (InfiniBand or RoCE — CPU bypassed) GPU 0 HBM HCA / RDMA NICdirect PCIe DMA HCA / RDMA NICdirect PCIe DMA GPU 1 HBM CPU 0 idle CPU 1 idle IB / RoCE Fabric

NCCL: Translating Collectives to Blackwell Kernels

PyTorch (torch.distributed) all_reduce, reduce_scatter, all_to_all NCCL 1. Detects topology (NVLink, NVSwitch, PCIe, NICs) 2. Selects optimal algorithm (Ring / Tree / Switch) 3. Launches CUDA kernels on GPU SMs streams packets across links Blackwell Hardware Fabric NVLink 5.0 · NVSwitch · GPUDirect RDMA
  • NVIDIA Collective Communication Library (NCCL) bridges high-level collectives and low-level GPU packets
  • Automatically discovers intra-node NVLink/NVSwitch topology and inter-node InfiniBand/RoCE NICs
  • Picks ring or tree schedules depending on message size and world size
  • CUDA detail: NCCL executes inside CUDA kernels on GPU SMs, enqueued on a CUDA stream

Because NCCL adapts to the physical topology at runtime, the same PyTorch collective code runs from 4 GPUs to full pods.

Part 3: Programming Collectives in torch.distributed

import os, torch, torch.distributed as dist

def setup(rank: int, world_size: int):
    os.environ["MASTER_ADDR"] = "localhost"
    os.environ["MASTER_PORT"] = "15623"
    backend = "nccl" if torch.cuda.is_available() else "gloo"
    dist.init_process_group(backend, rank=rank, world_size=world_size)

# Example: in-place All-Reduce across 4 CUDA GPUs
data = torch.tensor([0., 1, 2, 3], device=f"cuda:{rank}") + rank
dist.all_reduce(tensor=data, op=dist.ReduceOp.SUM, async_op=False)
# Every rank now holds tensor([6., 10., 14., 18.])

Always call dist.destroy_process_group() on exit to release NCCL communicators cleanly.

Verifying All-Reduce = Reduce-Scatter + All-Gather

# Input on each rank r: [r, r+1, r+2, r+3]
inp = torch.arange(world_size, dtype=torch.float32,
                   device=f"cuda:{rank}") + rank
shard = torch.empty(1, device=f"cuda:{rank}")

# Step 1: Reduce-Scatter (each rank keeps 1/world_size of the sum)
dist.reduce_scatter_tensor(output=shard, input=inp, op=dist.ReduceOp.SUM)

# Step 2: All-Gather (every rank collects all reduced shards)
full = torch.empty(world_size, device=f"cuda:{rank}")
dist.all_gather_into_tensor(output_tensor=full, input_tensor=shard)
Rankinpshard (after Reduce-Scatter)full (after All-Gather)
Rank 0[0, 1, 2, 3][6.][6., 10., 14., 18.]
Rank 1[1, 2, 3, 4][10.][6., 10., 14., 18.]
Rank 2[2, 3, 4, 5][14.][6., 10., 14., 18.]
Rank 3[3, 4, 5, 6][18.][6., 10., 14., 18.]

Use reduce_scatter_tensor and all_gather_into_tensor (contiguous tensors) to avoid extra copies.

Benchmarking Collectives Correctly on CUDA

data = torch.randn(100 * 1024**2, device=f"cuda:{rank}")

# 1. Warmup: initialize NCCL rings/buffers and JIT/CUDA state
dist.all_reduce(tensor=data, op=dist.ReduceOp.SUM, async_op=False)
torch.cuda.synchronize()    # Wait for local GPU kernels to finish
dist.barrier()              # Align all ranks before starting clock

# 2. Timed collective
t0 = time.time()
dist.all_reduce(tensor=data, op=dist.ReduceOp.SUM, async_op=False)
torch.cuda.synchronize()    # Ensure collective actually finished on GPU!
dist.barrier()              # Wait for the slowest rank
duration = time.time() - t0

Reasoning About Collective Bus Bandwidth

Ring Schedule (W = 4) R0 R1 R2 R3 (W − 1) steps RS + (W − 1) steps AG

For tensor size $S$ bytes across $W$ ranks in time $t$:

$$\text{BW}_{\text{All-Reduce}} = \frac{2(W - 1)}{W} \cdot \frac{S}{t} \approx \frac{2S}{t}$$

$$\text{BW}_{\text{Reduce-Scatter}} = \frac{W - 1}{W} \cdot \frac{S}{t} \approx \frac{S}{t}$$

  • Bus bandwidth normalizes out $W$ so you can compare directly against link speed (e.g., NVLink 5.0)
  • Independent of world size $W$ and topology (ring or tree) in the large-message regime
  • All-Reduce moves $2\times$ the data of Reduce-Scatter in $2\times$ the time → same bus bandwidth

Each step sends one $S/W$-byte shard; $W-1$ steps for Reduce-Scatter plus $W-1$ steps for All-Gather give factor $2(W-1)/W$.

Part 4: Distributed Training — Axes of Parallelism

We implement each strategy from primitives on a deep MLP (batch_size=128, num_dim=1024, num_layers=4)—representative because MLPs are the compute bottleneck in Transformers.

StrategyDimension ShardedPrimary CommunicationInterconnect Fit
Data (DDP)Batch ($B \to B/W$)All-Reduce gradientsModerate (IB / NVLink)
Sharded Data (FSDP / ZeRO)Batch + model state ($1/W$)All-Gather params + Reduce-Scatter gradsModerate (overlapped)
Tensor (TP)Hidden width ($D \to D/W$)All-Gather / All-Reduce activations per layerFast only (NVLink / NVL72)
Expert (EP)MoE experts (width)All-to-All token dispatch & combineFast (NVLink / NVL72)
Pipeline (PP)Depth ($L \to L/W$ layers)Point-to-point send / recvTolerates slow IB / RoCE
Sequence / ContextSequence length ($T \to T/W$)Ring / All-to-All attention statesNVLink / fast IB

Data Parallelism (DDP): Split the Batch

Global Batch B B₀ (32) B₁ (32) B₂ (32) B₃ (32) Full Model + Optimizer Copy on Every GPU GPU 0: W, AdamWFwd(B₀) → Loss L₀ → Bwd → g₀ GPU 1: W, AdamWFwd(B₁) → Loss L₁ → Bwd → g₁ GPU 2: W, AdamWFwd(B₂) → Loss L₂ → Bwd → g₂ GPU 3: W, AdamWFwd(B₃) → Loss L₃ → Bwd → g₃ All-Reduce (AVG grads) Identical AdamW step on all

Mathematically equivalent to single-GPU training on the full global batch $B$.

Data Parallelism (DDP): Bare-Bones PyTorch

local_bs = batch_size // world_size
x_local = data[rank * local_bs : (rank + 1) * local_bs].to(f"cuda:{rank}")

# Every rank holds all parameters and its own AdamW optimizer state
params = [get_init_params(num_dim, num_dim, rank)
          for _ in range(num_layers)]
optimizer = torch.optim.AdamW(params, lr=1e-3)

for step in range(num_steps):
    x = x_local
    for param in params:
        x = F.gelu(x @ param)
    loss = x.square().mean()
    loss.backward()

    # ONLY difference from single-GPU training: average gradients
    for param in params:
        dist.all_reduce(param.grad, op=dist.ReduceOp.AVG)

    optimizer.step()
    optimizer.zero_grad()

Every rank initializes with the same seed (or receives a rank-0 broadcast) so parameters start identical.

DDP: Exact Semantics and the Memory Wall

Memory ComponentSingle GPUDDP ($W$ GPUs)Bottleneck?
ActivationsFull batch $B$$B / W$ (sharded)Reduced by $W$
ParametersFull modelFull model (replicated)Redundant $W\times$
GradientsFull modelFull model (replicated)Redundant $W\times$
AdamW Optimizer StatesFull modelFull model (replicated)Redundant $W\times$

DDP speeds up training (more FLOPs), but cannot train a model whose parameters + optimizer states exceed one GPU's HBM.

From DDP to FSDP / ZeRO: Splitting All-Reduce

DDP (Replicated State — full model state per GPU) Full W, g, Optstored on every GPU Forward + Backward All-Reduce(g)= RS + AG Full AdamW Stepduplicated W× FSDP / ZeRO (Sharded State — 1/W model state per GPU) Shard 1/Wof W, Opt All-Gatherlayer weights Wℓ Layer Computefree Wℓ after! Reduce-Scattersum & shard gℓ Sharded AdamWupdate own 1/W Same communication building blocks (All-Gather + Reduce-Scatter), 1/W persistent model-state HBM!

Tensor Parallelism (TP): Shard Along Width

Input X (replicated) B × D 128 × 1024 × Weight W sharded by columns W₀GPU 0 W₁GPU 1 W₂GPU 2 W₃GPU 3 Each shard: D × (D/W) = 1024 × 256 Local GeLU(X·Wr) Y₀ Y₁ Y₂ Y₃ All-Gather + concat Full Y on all [Y₀, Y₁, Y₂, Y₃] B × D

Tensor Parallelism (TP): Bare-Bones PyTorch

data = data.to(f"cuda:{rank}")         # All ranks hold full batch (128x1024)
local_dim = num_dim // world_size      # Shard hidden dim: 1024 // 4 = 256

# Each rank holds only 1/world_size of every layer's columns
params = [get_init_params(num_dim, local_dim, rank)
          for _ in range(num_layers)]

x = data
for layer in range(num_layers):
    # Local matmul + GeLU -> shape (batch_size, local_dim)
    x = F.gelu(x @ params[layer])

    # Gather activation shards from every rank
    shards = [torch.empty(batch_size, local_dim, device=f"cuda:{rank}")
              for _ in range(world_size)]
    dist.all_gather(tensor_list=shards, tensor=x, async_op=False)

    # Concatenate along feature dim -> shape (batch_size, num_dim)
    x = torch.cat(shards, dim=1)

Every layer runs a blocking collective over full activations before the next layer can start.

Tensor Parallelism: Why NVLink Is Mandatory

TP also shines in serving (decoding), where batch size is small and latency—not just throughput—dominates.

Pipeline Parallelism (PP): Shard Along Depth

Rank 0 (Stage 0) Layer 0 MatMul + GeLU Layer 1 MatMul + GeLU Holds params for layers 0–1 only send / recv activations (micro-batch) Rank 1 (Stage 1) Layer 2 MatMul + GeLU Layer 3 MatMul + GeLU Holds params for layers 2–3 only

Pipeline Parallelism (PP): Micro-Batched PyTorch

local_layers = num_layers // world_size
local_params = [get_init_params(num_dim, num_dim, rank)
                for _ in range(local_layers)]

# Split batch into micro-batches to shrink pipeline bubbles
micro_bs = batch_size // num_micro_batches
if rank == 0:
    micro_batches = data.to("cuda:0").chunk(num_micro_batches, dim=0)
else:
    micro_batches = [torch.empty(micro_bs, num_dim, device=f"cuda:{rank}")
                     for _ in range(num_micro_batches)]

for x in micro_batches:
    if rank - 1 >= 0:
        dist.recv(tensor=x, src=rank - 1)   # Receive from previous stage
    for param in local_params:
        x = F.gelu(x @ param)               # Run local layers
    if rank + 1 < world_size:
        dist.send(tensor=x, dst=rank + 1)   # Forward to next stage

Backward reverses the flow: each stage receives output gradients from rank + 1 and sends input gradients to rank - 1.

Pipeline Bubbles and Micro-Batching

Naive (1 batch, $P=2$ stages): half of GPU time is idle (bubble)

Staget1t2t3t4
Rank 0 (L0–1)FwdidleidleBwd
Rank 1 (L2–3)idleFwdBwdidle

Micro-batched ($M=4$ micro-batches, $P=2$ stages): stages stay busy in steady state

Staget1t2t3t4t5t6t7t8t9t10
Rank 0 (L0–1)F0F1F2F3idleidleB3B2B1B0
Rank 1 (L2–3)idleF0F1F2F3B3B2B1B0idle

Micro-batching trades activation memory (storing in-flight micro-batches) for higher GPU utilization.

Part 5: Hiding Communication via CUDA Stream Overlap

Synchronous (async_op=False): Tensor Cores stall on every collective Compute NCCL Bwd L3 stall Bwd L2 stall Bwd L1 stall RS grad L3 RS grad L2 RS grad L1 Overlapped (async_op=True on dedicated NCCL stream): hide latency behind math Compute NCCL Bwd L3 Bwd L2 Bwd L1 Bwd L0 RS grad L3 RS grad L2 RS grad L1 RS grad L0 Faster step!

Sparse MoE & Expert Parallelism (Current Practice)

Local Tokens Rank 0 batch Rank 1 batch Rank 2..W−1 Router top-k experts All-to-All Dispatch route tokens Local Experts GPU 0: Exp A GPU 1: Exp B GPU r: Exp … All-to-All Combine return tokens Out tokens

Beyond MLPs: Attention and Sequence Parallelism

Long-context training combines sequence/context parallelism with TP/EP inside NVLink domains and DP/FSDP across nodes.

Composing Multi-Dimensional Parallelism on Blackwell

Across Pods / Nodes (InfiniBand ~0.05 TB/s · RoCE) Data Parallelism (FSDP / ZeRO) · Pipeline Parallelism Blackwell NVLink 5.0 Domain (0.9 TB/s/dir · up to 72 GPUs) Tensor Parallelism · Expert Parallelism (All-to-All) · Context Single Blackwell GPU (HBM 8 TB/s · SRAM) Kernel Fusion · Tiling · Activation Checkpointing Recompute ⇄ Store (HBM) ⇄ Communicate
  • Match traffic to bandwidth: put TP, EP, and context parallelism inside NVLink 5.0 / NVL72; put PP and FSDP/DP across InfiniBand
  • Fundamental systems trade-off: for every intermediate tensor, you can recompute it, store it in HBM, or shard & communicate it across GPUs
  • Frameworks: we build from explicit PyTorch/NCCL primitives to see the mechanics; compiler-driven stacks (e.g., JAX/TPUs) infer collectives from sharding annotations

Recap: Multi-GPU Parallelism

Every distributed training system balances three currencies: compute (recompute), HBM (store), and interconnect bandwidth (communicate).