GPU Collective Operations and Large Matrix Multiplication
(Understanding distributed computing with 2 nodes × 8 H100 GPUs)
1. What “operations” are we talking about?
When working with deep learning models, especially large language models (LLMs), you’ll quickly outgrow what a single GPU can handle. But scaling to multiple GPUs introduces a new challenge that might surprise you: it’s not the math that becomes the bottleneck—it’s the communication.
On a single GPU, the main operations are math kernels (GEMM for matrix multiplications, convolutions, etc.). Your GPU is incredibly good at these—NVIDIA’s H100 can perform up to 2000 TFLOPS for certain operations!
On many GPUs, however, the bottleneck shifts dramatically to communication: how quickly can you move tensors between GPUs? This is where collective operations become critical.
These communication operations are typically implemented by libraries like NCCL (NVIDIA Collective Communication Library). NCCL is the backbone of distributed GPU computing—it provides a small set of highly optimized collective operations that run across many GPUs (called “ranks”) simultaneously.(NVIDIA Docs)
What you’ll learn in this guide:
-
The fundamental collective operations — We’ll define each one mathematically and show concrete examples with small GPU counts (typically 4 GPUs) to build intuition.
-
Real-world application — We’ll demonstrate how to orchestrate these operations to perform large matrix multiplication on 2 nodes × 8 H100 GPUs (16 GPUs total), showing multiple parallel strategies.
Notation we’ll use throughout:
-
P GPUs total in our system, indexed by ranks .
-
Each rank holds some tensor like , , etc. The superscript denotes which GPU owns that data.
2. Core multi‑GPU operations (NCCL-style)
Think of collective operations as the verbs of distributed computing. Just like you have basic operations in sequential programming (read, write, add), distributed GPU computing has its own primitive operations that form the building blocks of any parallel algorithm.
NCCL provides these fundamental collectives:(NVIDIA Docs)
Data Distribution:
- Point‑to‑point:
Send,Recv— One GPU talks to another - Broadcast — One GPU sends to all
- Scatter — One GPU distributes different chunks to each GPU
- Gather — One GPU collects from all
- AllGather — Every GPU gets everything from everyone
Data Aggregation:
- Reduce — Combine data from all GPUs, deliver to one
- AllReduce — Combine data from all GPUs, deliver to all
- ReduceScatter — Combine and distribute different chunks to each GPU
Advanced Patterns:
- AlltoAll — Full data shuffle across all GPUs
- Barrier — Synchronization point
We’ll explore each one with both mathematical definitions and intuitive examples.
Note: To keep things concrete, most examples use P = 4 GPUs. This is small enough to visualize but large enough to show the patterns that scale to hundreds or thousands of GPUs.
2.1 Notation
-
: number of GPUs (ranks)
-
Rank indices:
-
Scalars:
-
Vectors:
-
Matrices:
When we say “operation = SUM”, we mean elementwise sum:
Other reduction ops are possible: MIN, MAX, PROD, etc.
2.2 Point‑to‑point: Send / Recv
These are the most basic building blocks. One rank explicitly sends data to another.
-
Math view:
Rank has tensor .
Rank receives a copy: . -
Example (P = 4):
Rank 0 sends vector to Rank 3.-
Before:
-
Rank 0:
-
Rank 3:
-
-
After:
- Rank 3:
-
-
Use:
Flexible patterns (pipelines, custom graphs). NCCL also offersncclSend/ncclRecvin addition to collectives.(arXiv)
2.3 Broadcast
Definition: One rank (the root) sends the same tensor to all ranks.
Think of Broadcast like a professor handing out identical copies of an exam to all students in a class. Everyone gets the exact same thing.
-
Math:
Let root be rank , with tensor .
After broadcast, every rank has: -
Example (P = 4, root = 0)
Root rank 0 has . Others have garbage.
Rank Before 0 1 2 3 -
Illustration
Rank 0 ---> Rank 1 \--> Rank 2 \--> Rank 3 -
Use in matmul:
Broadcast the full matrix (or a panel of ) from one rank to all ranks that need it.
2.4 Scatter
Definition: One root rank distributes different slices of a tensor to each rank.
Unlike Broadcast where everyone gets the same data, Scatter is like dealing cards: each GPU gets a different piece of the data. This is perfect for splitting up a large dataset for parallel processing.
-
Math:
Root has tensor where each is a “chunk”.
After scatter: -
Example (P = 4)
Root rank 0 has vector of length 8, split into 4 chunks of length 2:
After scatter (chunks of 2):
Rank 0 1 2 3 -
Use:
Initial distribution of rows/columns of a large matrix across GPUs.
2.5 Gather
Definition: Opposite of Scatter—the root rank collects slices from all ranks and concatenates them.
Think of this as collecting homework from all students and stapling them together into one stack.
-
Math:
Each rank has a chunk . Root collects: -
Example (P = 4)
Each rank has length-2 vector:
Rank 0 1 2 3 After gather at root 0:
-
Use:
If you want the full result on a single GPU (for checkpointing, validation, etc.).
2.6 AllGather
Definition: AllGather = Gather + Broadcast combined. Every rank ends up with the concatenation of all chunks.
This is incredibly useful: each GPU starts with their own piece of data, and after AllGather, every GPU has the complete picture—everyone’s pieces concatenated together.
-
Math:
Each rank has chunk .
After AllGather, each rank stores concatenated tensor: -
Example (P = 4, N = 1)
Each rank has a single scalar:
Rank 0 1 2 3 After AllGather:
- Every rank has .
-
Illustration
Before: After (on every rank): [0] [0,1,2,3] [1] ---> [0,1,2,3] [2] [0,1,2,3] [3] [0,1,2,3] -
Use in matmul:
Common in tensor parallelism: each GPU computes part of the output (e.g. some columns), then an AllGather combines them so every GPU has the full output.(DEV Community)
2.7 Reduce
Definition: Reduce aggregates values across ranks using an operation (like SUM, MAX, MIN) and delivers the result only to a root rank.
This is your classic “reduce” operation from functional programming, but distributed across GPUs. Common use case: summing gradients from all GPUs during distributed training.
-
Math:
Each rank has vector . With operation SUM and root , root receives: -
Example (P = 4, N = 2, root = 0)
Each rank has vector .
-
Rank 0:
-
Rank 1:
-
Rank 2:
-
Rank 3:
Sum:
Only root 0 receives .
-
-
Use:
Aggregate statistics (loss sums, norms, etc.) on a single GPU.
2.8 AllReduce
Definition: AllReduce is Reduce + Broadcast fused—everyone gets the reduced result.
This is probably the most important collective operation in deep learning. In data-parallel training, after each GPU computes gradients on its batch, you need to average those gradients across all GPUs. AllReduce does exactly this: combines everyone’s data (via reduction) and gives the result back to everyone.
-
Math (SUM):
Each rank has vector .
DefineAfter AllReduce, every rank has .
-
Example (same as Reduce but every rank gets result)
Inputs:
-
Rank 0:
-
Rank 1:
-
Rank 2:
-
Rank 3:
Sum = . After AllReduce:
Rank 0 1 2 3 -
-
Important identity:
In many libraries, the fastest way to implement AllReduce is actually:
(NCCL and similar libs do this using ring or tree algorithms.)(DEV Community)
-
Use in matmul:
If each GPU computes a partial such thatthen an AllReduce(SUM) gives the full to all GPUs.
2.9 ReduceScatter
Definition: “Reduce, then Scatter” in one shot.
ReduceScatter is a clever optimization: instead of reducing all the data and giving the complete result to everyone (AllReduce), we reduce it and then immediately scatter different pieces to different GPUs. This is more communication-efficient when you don’t need the full result everywhere.
-
Math (SUM):
Each rank has vector conceptually split into chunks:where each .
For each chunk index , define reduced chunk:
After ReduceScatter, rank holds . So each rank gets a different piece of the reduced result.
-
Example (P = 4, N = 1)
Let’s say each rank has a vector of length 4:
-
Rank 0:
-
Rank 1:
-
Rank 2:
-
Rank 3:
Conceptually, column-wise sums:
After ReduceScatter, rank gets :
-
Rank 0:
-
Rank 1:
-
Rank 2:
-
Rank 3:
-
-
Relation to AllReduce:
-
Use in matmul:
When each GPU holds a full-size partial but we want to shard the final result across GPUs instead of replicating: do ReduceScatter and keep sharded chunks.
2.10 AlltoAll
Definition: Every rank sends a different chunk to every other rank—a complete data shuffle.
This is the most general (and communication-intensive) collective. Think of it as a generalized transpose operation across GPUs. It’s essential for changing data layouts in complex parallel algorithms.
-
Math:
Each rank has inputwhere is the chunk destined to rank .
After AlltoAll, rank receives
-
Example (P = 3):
Each rank holds 3 scalars:
-
Rank 0: → wants to send to rank
-
Rank 1:
-
Rank 2:
After AlltoAll:
-
Rank 0:
-
Rank 1:
-
Rank 2:
-
-
Use:
Shuffle tokens, perform certain parallel FFTs, change data layout (e.g. from sequence-parallel to tensor-parallel layouts).
2.11 Barrier
Definition: Barrier is purely synchronization—all ranks wait until everyone reaches the barrier.
No data is transferred; this is just a coordination point. It ensures all GPUs have finished their previous work before moving to the next phase. Use sparingly, as synchronization can hurt performance.
-
Math:
No data transformation. It enforces: -
Use:
Coordinating phases of an algorithm; ensure all GPUs have finished a previous step before starting next.
3. How these operations relate
Understanding how collective operations compose is key to designing efficient distributed algorithms. Here are some crucial identities:
Composition identities:
- AllReduce ≡ Reduce + Broadcast
- AllReduce ≡ ReduceScatter + AllGather (often more efficient!)
- Gather ≡ AllGather (but only one rank keeps the result)
- Scatter ≡ “reverse” of Gather
Why do these matter? Libraries like NCCL don’t implement every operation from scratch. Instead, they compose primitives and choose the optimal algorithm based on:
- Message size (small messages favor different algorithms than large ones)
- Network topology (tree, ring, or hierarchical patterns)
- Minimizing latency (startup cost)
- Maximizing bandwidth usage (throughput)
For example, the ring-allreduce algorithm implements AllReduce as ReduceScatter + AllGather, which turns out to be more bandwidth-efficient than the naive Reduce + Broadcast approach.(DEV Community)
4. Hardware context: 2 nodes × 8 H100 GPUs
Before we dive into distributed matrix multiplication, let’s understand the hardware we’re working with. The performance of collective operations depends critically on your network topology.
Typical H100 cluster configuration:
Within each node:
- 8 × NVIDIA H100 GPUs in an HGX/DGX-style baseboard
- All GPUs fully connected via NVLink 4.0 and NVSwitch 3
- Bandwidth: up to 900 GB/s bidirectional per GPU inside the node(NVIDIA)
- This is incredibly fast—comparable to GPU memory bandwidth!
Between nodes:
- High-speed interconnect: typically NVIDIA Quantum‑2 InfiniBand (400 Gb/s) or high-end Ethernet(NVIDIA Developer)
- This is fast by networking standards, but it’s ~20x slower than NVLink
Why this matters: The hierarchy of communication
Communication within your cluster is hierarchical with two distinct tiers:
- Intra-node (within a node): Fast & fat—NVLink/NVSwitch provides massive bandwidth
- Inter-node (across nodes): Slower & narrower—limited by NICs and network fabric
Smart libraries like NCCL exploit this hierarchy. When performing a collective like AllReduce across 16 GPUs (2 nodes × 8), NCCL typically:
- Does local reduction within each node (fast NVLink)
- Exchanges data between nodes (slower InfiniBand)
- Completes local operations within each node (fast NVLink again)
This three-stage approach minimizes expensive cross-node traffic.(NVIDIA Docs)
Key takeaway: Design your parallel algorithms to maximize intra-node communication and minimize inter-node traffic!
5. Large matrix multiplication on 16 GPUs
Now for the main event: how do we actually use these collective operations to multiply massive matrices that don’t fit on a single GPU?
The problem
We want to compute:
where:
The challenge: These matrices are so large that:
- ❌ They don’t fit on a single GPU (memory constraint)
- ✓ They do fit across 16 GPUs when distributed
Think training a giant language model where a single weight matrix might be 20,000 × 20,000 in FP16 (1.6 GB just for that one matrix!).
Multiple strategies
There’s no single “best” way to distribute matrix multiplication. The optimal strategy depends on:
- Matrix dimensions (, , )
- Network topology
- Memory constraints
- Whether you need the full result everywhere
We’ll explore three fundamental approaches, building from simple to sophisticated:
- Data parallelism — Split the data (rows of ), replicate the model
- Tensor parallelism — Split the model (columns/rows of ), replicate the data
- 2D parallelism (SUMMA) — Split both data AND model for maximum scalability
For clarity, I’ll treat the 16 GPUs as a 4 × 4 logical grid:
Column j
0 1 2 3
R +----+----+----+----+
o0 |G0 |G1 |G2 |G3 |
w1 +----+----+----+----+
2 |G4 |G5 |G6 |G7 |
3 +----+----+----+----+
|G8 |G9 |G10 |G11 |
+----+----+----+----+
|G12 |G13 |G14 |G15 |
+----+----+----+----+You can imagine:
- Node 0 contains GPUs G0–G7
- Node 1 contains GPUs G8–G15
But algorithmically we just see a 4×4 grid.
5.1 Strategy 1: Data Parallelism
Data parallelism is the simplest and most widely used distributed training strategy. The core idea: replicate the model on each GPU, but give each GPU different data.
Key idea: Split matrix (input data) by rows across GPUs. Each GPU holds the full matrix (model weights) and processes its own subset of the data.
How it works
For our matrix multiplication :
Partitioning:
-
Split by rows into blocks:
-
Each GPU holds:
- Its data shard: (just rows)
- Full model: (complete weight matrix, replicated on all GPUs)
Forward pass: ✅ No communication needed!
Each GPU independently computes:
After computation, the result is naturally distributed:
Each GPU holds its portion .
If we need the full result: Use Gather or AllGather
Gatherto one root GPU:AllGatherto all GPUs: every GPU gets the complete
In neural network training context
Think of as a forward pass through a linear layer:
- : batch of input activations (size: batch × features)
- : weight matrix (size: features × hidden)
- : batch of output activations (size: batch × hidden)
Forward:
- Each GPU processes samples
- No communication (each GPU has full )
- Output naturally sharded by samples
Backward:
When computing gradients:
- Gradient w.r.t. weights: Each GPU computes
- These are partial gradients that need to be averaged across all GPUs
- AllReduce(SUM) to aggregate:
- Every GPU updates its copy of identically
Communication: Only in backward pass (AllReduce of gradients)
Trade-offs
Pros:
- ✓ Simplest to implement — minimal code changes from single-GPU training
- ✓ No communication in forward pass — compute-bound, not communication-bound
- ✓ Scales perfectly with batch size — 16 GPUs = 16× effective batch size
- ✓ Works with any model architecture — no model changes needed
Cons:
- ✗ Memory bottleneck: Every GPU stores the full model
- For a 175B parameter model, each GPU needs ~350GB just for weights!
- ✗ Doesn’t help with large models — can’t train models bigger than single-GPU memory
- ✗ Gradient AllReduce cost — communication volume = model size
- For GPT-3 scale, that’s 175B parameters to AllReduce every iteration!
When to use: When your model fits on a single GPU but you want to:
- Increase throughput (process more data)
- Use larger batch sizes for better convergence
- Reduce training time via data parallelism
Example: Training ResNet-50 (25M parameters) on ImageNet across 8 GPUs. Each GPU stores the full 25M parameter model and processes 32 images/batch (256 total batch size).
5.2 Strategy 2: Tensor Parallelism
Tensor parallelism solves the opposite problem from data parallelism: what if the model is too large to fit on a single GPU?
Key idea: Split the model weights (matrix ) across GPUs. Each GPU holds only a portion of the parameters and processes the same input data.
The setting
Suppose you have a massive linear layer: where:
- (batch size , input dimension )
- (weight matrix)
- (output)
In a GPT-3 scale model, might be 12,288 and might be 12,288—that’s a 1.8GB weight matrix just for this one layer!
There are two natural ways to split this:
Column-parallel weights (AllGather pattern)
Idea: Split by columns across GPUs:
where .
Each GPU holds:
- Full input: (replicated across all GPUs)
- Weight shard: (only 1/16 of the weights!)
Forward pass:
-
Each GPU computes its partial output:
-
AllGather to combine all partial outputs:
After AllGather, every GPU has the complete output .
Communication: AllGather of size (the output activations)
Row-parallel weights (AllReduce pattern)
Idea: Split by rows (equivalently, split the input dimension):
Each GPU holds:
- Input shard: (only 1/16 of the input features)
- Weight shard: (only 1/16 of the weights)
Forward pass:
-
Each GPU computes a partial result:
-
AllReduce(SUM) to sum all partial results:
After AllReduce, every GPU has the complete output .
Communication: AllReduce of size (the output activations)
Trade-offs
Pros:
- ✓ Reduces memory per GPU by factor of (16× reduction!)
- ✓ Enables training huge models that don’t fit on single GPU
- ✓ Scales with model size — bigger models benefit more
Cons:
- ✗ Communication in forward pass — AllGather or AllReduce required
- ✗ Requires model parallelism-aware code — must split layers appropriately
- ✗ Load balancing challenges — layers must be split evenly
When to use: When your model is too large to fit on a single GPU:
- Large language models (GPT-3, PaLM)
- Massive vision models
- Any model where weights > GPU memory
Example: GPT-3 175B with tensor parallelism across 8 GPUs means each GPU stores ~22B parameters instead of 175B.
Comparison with data parallelism
| Aspect | Data Parallelism | Tensor Parallelism |
|---|---|---|
| What’s split? | Input data (rows of ) | Model weights (columns/rows of ) |
| What’s replicated? | Full model on each GPU | Input data on each GPU |
| Forward communication | None | AllGather or AllReduce |
| Backward communication | AllReduce (gradients) | AllGather or AllReduce |
| Memory per GPU | Full model | Model / |
| Scales with | Batch size | Model size |
| Use when | Model fits on 1 GPU | Model too large for 1 GPU |
5.3 Strategy 3: 2D Parallelism (SUMMA algorithm)
Now that we’ve seen data parallelism (split data, replicate model) and tensor parallelism (split model, replicate data) separately, what if we could combine both?
SUMMA (Scalable Universal Matrix Multiplication Algorithm) does exactly this: it’s a 2D algorithm that splits BOTH the data (rows of ) AND the model (columns of ) simultaneously.
Key idea: Arrange GPUs in a 2D grid. Use row parallelism for data and column parallelism for model weights, getting the benefits of both strategies at once.
Why this is powerful:
- Better memory efficiency than pure data parallelism (model is split)
- Better communication efficiency than pure tensor parallelism (less data to broadcast)
- Scales in two dimensions: both batch size AND model size
Setup: 2D GPU grid
We arrange our 16 GPUs in a 4×4 grid:
- Process grid: rows, columns, total GPUs
- Row dimension: Data parallelism (split input by rows)
- Column dimension: Tensor parallelism (split weights by columns)
Matrix partitioning:
Result matrix : partitioned into 4×4 blocks
GPU computes block .
Input matrix : split by rows AND inner dimension
- Rows: 4 blocks () for data parallelism
- Inner dim: 4 panels along for the algorithm
Weight matrix : split by columns AND inner dimension
- Columns: 4 blocks () for tensor parallelism
- Inner dim: 4 panels along (matching )
Algorithm: SUMMA in action
Here’s the beautiful part: we compute the matrix multiplication panel by panel, which naturally factors as:
Let’s walk through this with detailed visualizations to make the algorithm concrete.
The GPU grid layout
First, recall our 4×4 grid of 16 GPUs:
Column j
0 1 2 3
┌──────┬──────┬──────┬──────┐
i=0 │ G0 │ G1 │ G2 │ G3 │ Row 0
├──────┼──────┼──────┼──────┤
Row i=1 │ G4 │ G5 │ G6 │ G7 │ Row 1
├──────┼──────┼──────┼──────┤
i=2 │ G8 │ G9 │ G10 │ G11 │ Row 2
├──────┼──────┼──────┼──────┤
i=3 │ G12 │ G13 │ G14 │ G15 │ Row 3
└──────┴──────┴──────┴──────┘
Col 0 Col 1 Col 2 Col 3Each GPU will compute block of the result.
Initial data distribution (for panel t)
At the start of processing panel , each row/column needs certain blocks of and :
Matrix A blocks (by row):
- Row 0 GPUs: One GPU in row 0 owns
- Row 1 GPUs: One GPU in row 1 owns
- Row 2 GPUs: One GPU in row 2 owns
- Row 3 GPUs: One GPU in row 3 owns
Matrix B blocks (by column):
- Col 0 GPUs: One GPU in col 0 owns
- Col 1 GPUs: One GPU in col 1 owns
- Col 2 GPUs: One GPU in col 2 owns
- Col 3 GPUs: One GPU in col 3 owns
Ownership pattern (example):
For our visualization, assume the following initial distribution. The specific ownership doesn’t affect the algorithm—only which GPU broadcasts first in each row/column.
For panel t=0:
- A blocks: GPU (0,0) owns , GPU (1,1) owns , GPU (2,2) owns , GPU (3,3) owns
- B blocks: GPU (0,0) owns , GPU (0,1) owns , GPU (0,2) owns , GPU (0,3) owns
For panel t=1:
- A blocks: GPU (0,1) owns , GPU (1,1) owns , GPU (2,2) owns , GPU (3,3) owns
- B blocks: GPU (1,0) owns , GPU (1,1) owns , GPU (1,2) owns , GPU (1,3) owns
(Similar patterns for panels t=2 and t=3)
Step 1: Broadcast A panel across rows
Goal: Every GPU in row needs
Concrete example: Let’s trace through panel t=1
According to our ownership pattern, for panel t=1:
- GPU (0,1) = G1 owns
- GPU (1,1) = G5 owns
- GPU (2,2) = G10 owns
- GPU (3,3) = G15 owns
Let’s visualize what happens for Row 1:
BEFORE Broadcast (Row 1, panel t=1):
┌──────┬──────┬──────┬──────┐
│ G4 │ G5 │ G6 │ G7 │ Row 1
│ - │A1(1) │ - │ - │ (GPU (1,1) = G5 initially has A1 for panel 1)
└──────┴──────┴──────┴──────┘
Broadcast A1(1) across Row 1 (from G5):
←──── G5 ────→
↓ ↓ ↓
G4 G5 G6 G7
AFTER Broadcast (Row 1, panel t=1):
┌──────┬──────┬──────┬──────┐
│ G4 │ G5 │ G6 │ G7 │ Row 1
│A1(1) │A1(1) │A1(1) │A1(1) │ (All GPUs in Row 1 now have A1 for panel 1)
└──────┴──────┴──────┴──────┘This happens simultaneously for all 4 rows (for panel t=1):
Row 0: G1 broadcasts A0(1) to → G0, G1, G2, G3
Row 1: G5 broadcasts A1(1) to → G4, G5, G6, G7
Row 2: G10 broadcasts A2(1) to → G8, G9, G10, G11
Row 3: G15 broadcasts A3(1) to → G12, G13, G14, G15Communication pattern: 4 independent row-wise broadcasts (one per row)
Step 2: Broadcast B panel across columns
Goal: Every GPU in column needs
Continuing with panel t=1:
For panel t=1, assume B blocks are also owned diagonally:
- GPU (1,0) = G4 owns
- GPU (1,1) = G5 owns
- GPU (1,2) = G6 owns
- GPU (1,3) = G7 owns
Let’s visualize what happens for Column 2:
BEFORE Broadcast (Column 2, panel t=1):
Col 2
┌──────┐
│ G2 │ Row 0
│ - │
├──────┤
│ G6 │ Row 1
│B2(1) │ (GPU (1,2) = G6 initially has B2 for panel 1)
├──────┤
│ G10 │ Row 2
│ - │
├──────┤
│ G14 │ Row 3
│ - │
└──────┘
Broadcast B2(1) down Column 2 (from G6):
↑
│
G6 (owner)
│
↓
G2, G10, G14
AFTER Broadcast (Column 2, panel t=1):
Col 2
┌──────┐
│ G2 │ Row 0
│B2(1) │
├──────┤
│ G6 │ Row 1
│B2(1) │
├──────┤
│ G10 │ Row 2
│B2(1) │
├──────┤
│ G14 │ Row 3
│B2(1) │
└──────┘This happens simultaneously for all 4 columns (for panel t=1):
Col 0: G4 broadcasts B0(1) to → G0, G4, G8, G12
Col 1: G5 broadcasts B1(1) to → G1, G5, G9, G13
Col 2: G6 broadcasts B2(1) to → G2, G6, G10, G14
Col 3: G7 broadcasts B3(1) to → G3, G7, G11, G15Communication pattern: 4 independent column-wise broadcasts (one per column)
Step 3: What each GPU has after both broadcasts
After both broadcasts for panel t=1, each GPU has exactly what it needs:
Column j
0 1 2 3
┌────────────┬────────────┬────────────┬────────────┐
i=0 │ G0 │ G1 │ G2 │ G3 │
│ A0(1),B0(1)│ A0(1),B1(1)│ A0(1),B2(1)│ A0(1),B3(1)│
├────────────┼────────────┼────────────┼────────────┤
i=1 │ G4 │ G5 │ G6 │ G7 │
│ A1(1),B0(1)│ A1(1),B1(1)│ A1(1),B2(1)│ A1(1),B3(1)│
├────────────┼────────────┼────────────┼────────────┤
i=2 │ G8 │ G9 │ G10 │ G11 │
│ A2(1),B0(1)│ A2(1),B1(1)│ A2(1),B2(1)│ A2(1),B3(1)│
├────────────┼────────────┼────────────┼────────────┤
i=3 │ G12 │ G13 │ G14 │ G15 │
│ A3(1),B0(1)│ A3(1),B1(1)│ A3(1),B2(1)│ A3(1),B3(1)│
└────────────┴────────────┴────────────┴────────────┘Key observation: GPU has and — exactly the blocks needed to compute its contribution to from panel 1!
Step 4: Local GEMM computation
For panel t=1, each GPU independently computes (no communication needed!):
GPU (i,j) computes:
C_ij += A_i(1) × B_j(1)
┌─────────┐
│ A_i(1) │ (M/4) × K_1
└─────────┘
×
┌──────────┐
│ B_j(1) │ K_1 × (N/4)
└──────────┘
║
▼
┌──────────┐
│ C_ij │ (M/4) × (N/4)
└──────────┘Concrete examples for panel t=1:
- GPU 5 (position (1,1)): computes
- GPU 6 (position (1,2)): computes
- GPU 10 (position (2,2)): computes
- All 16 GPUs compute their respective block contributions from panel 1
Step 5: Repeat for all panels
We just walked through panel t=1 in detail. The same process happens for all 4 panels:
Panel t=0:
- Broadcast blocks across rows, Broadcast blocks down columns
- Each GPU computes:
Panel t=1: (shown in detail above)
- Broadcast blocks across rows, Broadcast blocks down columns
- Each GPU computes:
Panel t=2:
- Broadcast blocks across rows, Broadcast blocks down columns
- Each GPU computes:
Panel t=3:
- Broadcast blocks across rows, Broadcast blocks down columns
- Each GPU computes:
After all 4 panels: Each GPU has computed:
which is exactly the -th block of the full matrix product .
Final result distribution:
Column j
0 1 2 3
┌──────┬──────┬──────┬──────┐
i=0 │ C00 │ C01 │ C02 │ C03 │
├──────┼──────┼──────┼──────┤
i=1 │ C10 │ C11 │ C12 │ C13 │
├──────┼──────┼──────┼──────┤
i=2 │ C20 │ C21 │ C22 │ C23 │
├──────┼──────┼──────┼──────┤
i=3 │ C30 │ C31 │ C32 │ C33 │
└──────┴──────┴──────┴──────┘Each GPU holds its unique block of the result!
Collectives used:
- Broadcast along rows and columns (8 independent broadcasts per panel).
- Implementation detail: row/column Broadcasts are often implemented internally as
AllGatheron a sub-communicator. E.g., an NCCL communicator for all ranks in a row/column.(NVIDIA Docs)
Hierarchy with 2×8 H100s:
- Each row/column communicator spans both nodes.
- NCCL likely does:
- Intra-node phase: use NVLink/NVSwitch to move data among 8 GPUs in each node (fast).(NVIDIA)
- Inter-node phase: send one copy across nodes over InfiniBand.
- Final intra-node distribution.
You as the user just call ncclBroadcast or torch.distributed.broadcast with appropriate process groups; the library does the topology-aware scheduling.
Discussion: SUMMA as 2D hybrid parallelism
Now that we’ve seen the full algorithm, let’s explicitly connect SUMMA to the parallelism strategies used in modern LLM training.
SUMMA = Data Parallelism (rows) + Tensor Parallelism (columns)
Consider the computation where:
- represents input activations (e.g., batch of tokens)
- represents weight matrix (e.g., MLP layer)
- represents output activations
Row dimension (data parallelism):
- We split into 4 row-blocks:
- Each row block contains samples
- GPU row processes samples corresponding to
- This is data parallelism: different GPUs process different data
Column dimension (tensor parallelism):
- We split into 4 column-blocks:
- Each column block contains output features
- GPU column computes features corresponding to
- This is tensor parallelism: different GPUs hold different parts of the model weights
Communication patterns match:
In SUMMA:
- Row-wise broadcasts distribute blocks → analogous to broadcasting input activations in data parallelism
- Column-wise broadcasts distribute blocks → analogous to having each GPU hold a shard of weights in tensor parallelism
- Each GPU computes its block → processes data with weight shard
Why 2D is powerful:
| Strategy | Scales with | Memory per GPU | Communication |
|---|---|---|---|
| Pure data parallel (1D rows) | Batch size | Full model | AllReduce of gradients |
| Pure tensor parallel (1D cols) | Model size | Model/ | AllGather + AllReduce |
| SUMMA (2D hybrid) | Both batch AND model | Model/ (approx) | Broadcasts only |
For a 16-GPU setup:
- 1D data parallel: Each GPU stores full model, handles batch/16
- 1D tensor parallel: Each GPU stores model/16, handles full batch
- 2D SUMMA (4×4): Each GPU stores ~model/4, handles batch/4
The 2D approach gives better memory efficiency than pure data parallelism and better communication efficiency than pure tensor parallelism for large-scale problems!
Real-world usage:
While pure SUMMA is less common in LLM training (because neural network layers require specific patterns), the principle of 2D parallelism is crucial:
- Some frameworks use 2D parameter sharding (e.g., ZeRO-3 with tensor parallelism)
- Understanding SUMMA helps reason about hybrid parallelism strategies
- The communication patterns (row/column broadcasts) appear in various forms in modern distributed training
5.4 Implementation: Hierarchy on 2 nodes × 8 H100s
Take any of the above collectives (Broadcast, AllGather, AllReduce): NCCL will typically implement them hierarchically:
-
Intra‑node phase (within each 8‑GPU H100 node)
- Use NVLink/NVSwitch; bandwidth up to ~900 GB/s per GPU.(NVIDIA)
- For example, do a ReduceScatter inside node 0 and node 1 separately.
-
Inter‑node phase (between the two nodes)
- Use NICs / InfiniBand; e.g. 400 Gb/s between nodes.(NVIDIA Developer)
- Exchange the reduced shards between nodes.
-
Final intra‑node phase
- AllGather within each node to reconstruct the complete result on the GPUs that need it.
For you, this is abstracted away. You just specify:
dist.all_reduce(tensor, op=dist.ReduceOp.SUM, group=world_group)and the library builds the optimal combination of:
- ReduceScatter
- AllGather
- Broadcast
- Send/Recv
depending on topology and collective type.
6. Deep dive: Why implement AllReduce as ReduceScatter + AllGather?
You might wonder: if AllReduce = Reduce + Broadcast, why do libraries like NCCL prefer to implement it as ReduceScatter + AllGather instead? The answer lies in communication efficiency and bandwidth utilization.
6.1 The two implementations compared
Let’s compare both approaches for GPUs, each holding a vector of size .
Method 1: Reduce + Broadcast
-
Reduce phase: All GPUs send their data to the root
- Root receives and combines elements
- Communication: elements flow TO the root
-
Broadcast phase: Root sends result to all GPUs
- Root sends elements to each of GPUs
- Communication: elements flow FROM the root
Problem: The root becomes a bottleneck! It must handle elements flowing through its network interface, while other GPUs handle much less.
Method 2: ReduceScatter + AllGather
-
ReduceScatter phase:
- Divide each GPU’s elements into chunks of size
- Reduce across GPUs and scatter results
- Each GPU ends up with a different chunk of the final sum
-
AllGather phase:
- Each GPU shares its chunk with all others
- Everyone reconstructs the full -element result
Advantage: Communication is balanced across all GPUs! No single bottleneck.
6.2 Concrete example: P = 4 GPUs
Let’s use GPUs, each with a vector of 4 elements (so ).
Initial state:
GPU 0: [a₀, a₁, a₂, a₃]
GPU 1: [b₀, b₁, b₂, b₃]
GPU 2: [c₀, c₁, c₂, c₃]
GPU 3: [d₀, d₁, d₂, d₃]
Goal: Every GPU should have:
[a₀+b₀+c₀+d₀, a₁+b₁+c₁+d₁, a₂+b₂+c₂+d₂, a₃+b₃+c₃+d₃]
Method 1: Reduce + Broadcast (root = GPU 0)
Reduce phase (3 data transfers TO GPU 0):
GPU 1 → GPU 0: [b₀, b₁, b₂, b₃]
GPU 2 → GPU 0: [c₀, c₁, c₂, c₃]
GPU 3 → GPU 0: [d₀, d₁, d₂, d₃]
GPU 0 computes: [a₀+b₀+c₀+d₀, a₁+b₁+c₁+d₁, a₂+b₂+c₂+d₂, a₃+b₃+c₃+d₃]
Broadcast phase (3 data transfers FROM GPU 0):
GPU 0 → GPU 1: [sum₀, sum₁, sum₂, sum₃]
GPU 0 → GPU 2: [sum₀, sum₁, sum₂, sum₃]
GPU 0 → GPU 3: [sum₀, sum₁, sum₂, sum₃]
Total communication:
- GPU 0: receives 12 elements, sends 12 elements = 24 elements
- GPUs 1,2,3: send 4 elements, receive 4 elements = 8 elements each
- Bottleneck at GPU 0!
Method 2: ReduceScatter + AllGather
ReduceScatter phase (using ring algorithm):
Step 1: Each GPU sends one chunk clockwise, receives one chunk counter-clockwise
GPU 0 sends [a₃] to GPU 1, receives [d₀] from GPU 3 → computes [a₀+d₀]
GPU 1 sends [b₀] to GPU 2, receives [a₁] from GPU 0 → computes [a₁+b₁]
GPU 2 sends [c₁] to GPU 3, receives [b₂] from GPU 1 → computes [b₂+c₂]
GPU 3 sends [d₂] to GPU 0, receives [c₃] from GPU 2 → computes [c₃+d₃]
Step 2: Continue for 2 more rounds…
After ReduceScatter:
GPU 0 has: [a₀+b₀+c₀+d₀] (chunk 0 of final result)
GPU 1 has: [a₁+b₁+c₁+d₁] (chunk 1 of final result)
GPU 2 has: [a₂+b₂+c₂+d₂] (chunk 2 of final result)
GPU 3 has: [a₃+b₃+c₃+d₃] (chunk 3 of final result)
AllGather phase (using ring algorithm):
Each GPU shares its chunk with others through rounds of ring communication.
After AllGather, every GPU has: [sum₀, sum₁, sum₂, sum₃]
Total communication:
- Every GPU: sends and receives equal amounts
- Each GPU sends elements in ReduceScatter
- Each GPU sends elements in AllGather
- Total per GPU: elements
- No bottleneck! Perfectly balanced.
6.3 Communication cost analysis
Let’s formalize the comparison. Assume:
- GPUs, each with elements
- = latency (startup cost per message)
- = transfer time per element
| Method | Total Data Moved | Steps (Latency) | Bottleneck? |
|---|---|---|---|
| Reduce + Broadcast | (tree) or (naive) | ✗ Root is bottleneck | |
| ReduceScatter + AllGather (Ring) | ✓ Fully balanced |
Key insight: Both methods move the same total amount of data! But the ring-based approach:
- Balances the load — every GPU sends/receives equal amounts
- Maximizes bandwidth utilization — all network links active simultaneously
- Avoids bottlenecks — no single GPU is overwhelmed
6.4 Why this matters for large P
For small (2-8 GPUs), the difference is minor. But for large (hundreds to thousands of GPUs):
Reduce + Broadcast:
- Root’s NIC becomes saturated
- Other GPUs sit idle waiting for root
- Cannot utilize full bisection bandwidth of the network
ReduceScatter + AllGather (Ring/Tree algorithms):
- All GPUs participate equally
- All network links utilized simultaneously
- Scales efficiently to thousands of GPUs
- This is why it’s used in training runs with 1000+ GPUs!
6.5 Modern NCCL optimizations
In practice, NCCL doesn’t use a pure ring algorithm. It combines multiple techniques:
- Ring algorithm for large messages (bandwidth-bound)
- Tree algorithm for small messages (latency-bound)
- Hierarchical algorithms for multi-node setups:
- ReduceScatter within each node (fast NVLink)
- Exchange between nodes (slower InfiniBand)
- AllGather within each node (fast NVLink)
Bottom line: When you call torch.distributed.all_reduce(), you’re getting a sophisticated implementation that’s far more efficient than naive Reduce + Broadcast!
7. Parallelism strategies in distributed training
Now let’s see how these collective operations enable the three main parallelism paradigms used in modern LLM training. We’ll use MLP layers as concrete examples, showing exactly which GPU operations are needed for forward and backward passes.
7.1 Data Parallelism
Key idea: Each GPU holds a complete copy of the model but processes a different batch of data.
This is the simplest and most common form of parallelism. If you’ve ever used DistributedDataParallel in PyTorch, you’ve used data parallelism!
How it works
Setup (P = 4 GPUs):
- All GPUs have identical model copies: weights
- Training data is split into different batches:
- GPU 0 processes batch
- GPU 1 processes batch
- GPU 2 processes batch
- GPU 3 processes batch
Forward pass: ✅ No communication needed!
Each GPU independently computes:
Each GPU computes its own loss:
Backward pass: 🔄 AllReduce required!
Each GPU computes gradients on its local batch:
But we want to update using the average gradient across all batches:
Collective operation needed:
# Each GPU has computed its local gradient
grad_W_local = compute_gradient(loss, W) # shape: [K, H]
# AllReduce with SUM operation
dist.all_reduce(grad_W_local, op=dist.ReduceOp.SUM)
# Average the result
grad_W = grad_W_local / world_size
# Update weights (identical on all GPUs)
W -= learning_rate * grad_WWhy AllReduce? Because every GPU needs the averaged gradient to update its local copy of identically!
Example: Single-layer MLP with data parallelism
class MLPLayerDataParallel:
def __init__(self, K, H):
# Every GPU has the full weight matrix
self.W = torch.randn(K, H, device='cuda') # K × H
def forward(self, X_local):
# X_local: [B, K] - different batch on each GPU
# No communication needed!
Y = torch.matmul(X_local, self.W) # [B, H]
return Y
def backward(self, X_local, grad_Y):
# grad_Y: [B, H] - gradient from loss
# Compute local gradient
grad_W = torch.matmul(X_local.T, grad_Y) # [K, H]
# AllReduce to average across all GPUs
dist.all_reduce(grad_W, op=dist.ReduceOp.SUM)
grad_W /= dist.get_world_size()
# Update weights
self.W -= learning_rate * grad_W
# Compute gradient w.r.t. input (for previous layer)
grad_X = torch.matmul(grad_Y, self.W.T) # [B, K]
return grad_XCommunication cost
- Forward: 0 communication ✓
- Backward: 1 AllReduce of size (the weight gradient)
- Memory per GPU: Full model ( weights)
Pros:
- ✓ Simple to implement
- ✓ No communication in forward pass
- ✓ Scales well with batch size
Cons:
- ✗ Every GPU must store the full model (doesn’t help with huge models)
- ✗ Communication cost grows with model size
Used for: Most standard distributed training (e.g., ResNet, BERT on moderate scales)
7.2 Tensor Parallelism (Single-layer MLP)
Key idea: Split the model weights across GPUs, not the data. Each GPU processes the same batch but computes only part of the result.
This allows training models that don’t fit on a single GPU!
Forward pass: Column-parallel weights
Let’s split weight matrix by columns:
where .
Setup (P = 4 GPUs):
- All GPUs have the same input: (replicated)
- GPU owns weight shard
Forward computation:
Each GPU computes:
To get the full output, we need:
Collective operation: AllGather
# Local computation
Y_local = torch.matmul(X, W_shard) # [B, H/4]
# AllGather to collect all column chunks
Y_gathered = [torch.empty_like(Y_local) for _ in range(4)]
dist.all_gather(Y_gathered, Y_local)
# Concatenate along feature dimension
Y = torch.cat(Y_gathered, dim=-1) # [B, H]After forward: Every GPU has the complete output .
Backward pass: Column-parallel weights
Given gradient from the next layer: (replicated on all GPUs)
Step 1: Split gradient to match forward sharding
Since , we split the gradient:
Each GPU takes its corresponding chunk:
Step 2: Compute gradient w.r.t. weights
GPU computes:
No communication needed! Each GPU has its weight gradient shard.
Step 3: Compute gradient w.r.t. input
Each GPU computes a partial gradient:
But the full gradient is:
Collective operation: AllReduce
# Compute partial input gradient
grad_X_partial = torch.matmul(grad_Y_local, W_shard.T) # [B, K]
# AllReduce to sum all partial gradients
dist.all_reduce(grad_X_partial, op=dist.ReduceOp.SUM)
# Now grad_X_partial contains the full gradient
grad_X = grad_X_partialComplete implementation: Column-parallel layer
class ColumnParallelMLP:
def __init__(self, K, H, process_group):
self.pg = process_group
self.world_size = dist.get_world_size(process_group)
self.rank = dist.get_rank(process_group)
# Each GPU owns H/world_size columns
self.H_local = H // self.world_size
self.W_shard = torch.randn(K, self.H_local, device='cuda')
def forward(self, X):
# X: [B, K] - replicated on all GPUs
# Local matmul
Y_local = torch.matmul(X, self.W_shard) # [B, H_local]
# AllGather to get full output
Y_list = [torch.zeros_like(Y_local) for _ in range(self.world_size)]
dist.all_gather(Y_list, Y_local, group=self.pg)
Y = torch.cat(Y_list, dim=-1) # [B, H]
# Save for backward
self.X = X
return Y
def backward(self, grad_Y):
# grad_Y: [B, H] - full gradient, replicated on all GPUs
# Split grad_Y into chunks
grad_Y_chunks = torch.chunk(grad_Y, self.world_size, dim=-1)
grad_Y_local = grad_Y_chunks[self.rank] # [B, H_local]
# Compute weight gradient (local, no communication)
grad_W = torch.matmul(self.X.T, grad_Y_local) # [K, H_local]
self.W_shard -= learning_rate * grad_W
# Compute input gradient (partial)
grad_X_partial = torch.matmul(grad_Y_local, self.W_shard.T) # [B, K]
# AllReduce to get full input gradient
dist.all_reduce(grad_X_partial, op=dist.ReduceOp.SUM, group=self.pg)
return grad_X_partialCommunication cost
- Forward: 1 AllGather of size per GPU → total
- Backward: 1 AllReduce of size
- Memory per GPU: weights (4× reduction!)
Pros:
- ✓ Reduces memory per GPU by factor of
- ✓ Enables training models that don’t fit on one GPU
Cons:
- ✗ Communication required in both forward and backward
- ✗ More complex to implement
Used for: Large transformer models (Megatron-LM, GPT-3)
7.3 Tensor Parallelism (Two-layer MLP)
Now let’s see how tensor parallelism works across multiple layers. This is where the fusion optimization becomes important!
Setup: Two-layer MLP
Standard MLP with two layers:
Megatron-LM strategy:
- Layer 1: Column-parallel (split by columns)
- Layer 2: Row-parallel (split by rows)
This combination minimizes communication!
Forward pass
Layer 1 (column-parallel):
GPU owns
Each GPU computes:
Key optimization: We do NOT do AllGather here! Instead, keep sharded.
Layer 2 (row-parallel):
GPU owns
Each GPU computes partial output:
Full output is:
Collective operation: AllReduce
# Forward through layer 1 (column-parallel)
H1_local = F.gelu(torch.matmul(X, W1_shard)) # [B, H/4]
# No AllGather! Keep sharded
# Forward through layer 2 (row-parallel)
Y_partial = torch.matmul(H1_local, W2_shard) # [B, K]
# AllReduce to sum partial outputs
dist.all_reduce(Y_partial, op=dist.ReduceOp.SUM)
Y = Y_partial # [B, K]Total forward communication: Just 1 AllReduce! (Instead of 1 AllGather + 1 AllReduce if we didn’t fuse)
Backward pass
Given: (replicated)
Layer 2 backward (row-parallel):
Gradient w.r.t. :
Gradient w.r.t. (partial):
Since , the full gradient is already sharded correctly:
No communication needed! The gradient naturally matches the sharding.
Layer 1 backward (column-parallel):
Gradient w.r.t. :
where we need to backprop through GeLU first.
Gradient w.r.t. input (partial):
Full gradient:
Collective operation: AllReduce
# Backward through layer 2
grad_W2 = torch.matmul(H1_local.T, grad_Y) # [H/4, K]
grad_H1_local = torch.matmul(grad_Y, W2_shard.T) # [B, H/4]
# No communication! Gradients match sharding
# Backward through GeLU
grad_H1_local = grad_H1_local * gelu_derivative(...)
# Backward through layer 1
grad_W1 = torch.matmul(X.T, grad_H1_local) # [K, H/4]
grad_X_partial = torch.matmul(grad_H1_local, W1_shard.T) # [B, K]
# AllReduce for input gradient
dist.all_reduce(grad_X_partial, op=dist.ReduceOp.SUM)
grad_X = grad_X_partialTotal backward communication: Just 1 AllReduce!
The fusion win
Without fusion (if we did AllGather after layer 1):
- Forward: 1 AllGather + 1 AllReduce = 2 collectives
- Backward: 1 AllReduce + 1 AllReduce = 2 collectives
- Total: 4 collective operations
With fusion (column-parallel → row-parallel):
- Forward: 1 AllReduce
- Backward: 1 AllReduce
- Total: 2 collective operations
Communication reduction: 50%! This is why Megatron-LM alternates column and row parallelism.
7.4 Pipeline Parallelism (Two-layer MLP)
Key idea: Split the model vertically (by layers) instead of horizontally (by tensors). Different layers live on different GPUs.
This is essential when models are so deep that even a few layers don’t fit on one GPU!
Setup: Two-layer MLP on 4 GPUs
Let’s split our two-layer MLP differently:
- GPU 0-1: First layer ()
- GPU 2-3: Second layer ()
Wait, but we only have 2 layers and 4 GPUs? We’ll use microbatching to keep all GPUs busy!
Simpler version (2 GPUs):
- GPU 0: Holds (first layer)
- GPU 1: Holds (second layer)
Forward pass without microbatching (naive)
Timeline:
Time 1: GPU 0 computes H₁ = GeLU(X W₁)
GPU 1 idle ❌
Time 2: GPU 0 sends H₁ to GPU 1
GPU 1 receives H₁
Time 3: GPU 0 idle ❌
GPU 1 computes Y = H₁ W₂
Problem: GPUs spend 50% of time idle! This is called the pipeline bubble.
Collective operations:
- Send/Recv (point-to-point): GPU 0 sends to GPU 1
Forward pass with microbatching (efficient)
Split the batch into microbatches:
Timeline (M = 4 microbatches):
Time: 1 2 3 4 5 6 7
GPU 0: F₁ F₂ F₃ F₄ B₁ B₂ B₃ B₄
GPU 1: F₁ F₂ F₃ F₄ B₁ B₂ B₃ B₄
F₁ = forward pass of microbatch 1
B₁ = backward pass of microbatch 1
Detailed timeline:
| Time | GPU 0 | GPU 1 | Communication |
|---|---|---|---|
| 1 | Fwd: | Idle | - |
| 2 | Fwd: | Fwd: | Send : GPU 0→1 |
| 3 | Fwd: | Fwd: | Send : GPU 0→1 |
| 4 | Fwd: | Fwd: | Send : GPU 0→1 |
| 5 | Bwd: gradients for (batch 1) | Fwd: | Send : GPU 0→1 |
| 6 | Bwd: gradients for (batch 2) | Bwd: gradients for (batch 1) | Recv : GPU 1→0 |
| … | … | … | … |
Bubble time: Only at the beginning and end! With microbatches and pipeline stages (GPUs):
With microbatches and GPUs: bubble =
With more microbatches (e.g., ): bubble =
Backward pass with microbatching
Key: Backward must happen in reverse order of forward (LIFO).
Timeline:
Forward: GPU 0 (F₁ F₂ F₃ F₄) → GPU 1 (F₁ F₂ F₃ F₄)
Backward: GPU 1 (B₄ B₃ B₂ B₁) → GPU 0 (B₄ B₃ B₂ B₁)
For each microbatch backward:
-
GPU 1 computes:
-
GPU 1 sends to GPU 0
-
GPU 0 receives and computes:
Collective operations:
- Forward: Send from GPU 0 to GPU 1 (for each microbatch)
- Backward: Send from GPU 1 to GPU 0 (for each microbatch)
- These are point-to-point (Send/Recv), not collectives!
Complete implementation outline
# GPU 0 (first layer)
if rank == 0:
for microbatch_id in range(num_microbatches):
# Forward
X_micro = get_microbatch(X, microbatch_id)
H1 = F.gelu(torch.matmul(X_micro, W1)) # [B/M, H]
# Send to GPU 1
dist.send(H1, dst=1)
# Save for backward
activations[microbatch_id] = (X_micro, H1)
# Backward (reverse order!)
for microbatch_id in reversed(range(num_microbatches)):
# Receive gradient from GPU 1
grad_H1 = torch.empty_like(H1)
dist.recv(grad_H1, src=1)
# Backward through layer 1
X_micro, H1 = activations[microbatch_id]
grad_H1 = grad_H1 * gelu_derivative(...)
grad_W1 += torch.matmul(X_micro.T, grad_H1) # Accumulate
grad_X_micro = torch.matmul(grad_H1, W1.T)
# GPU 1 (second layer)
elif rank == 1:
for microbatch_id in range(num_microbatches):
# Receive from GPU 0
H1 = torch.empty([batch_size_micro, H])
dist.recv(H1, src=0)
# Forward
Y = torch.matmul(H1, W2) # [B/M, K]
loss = compute_loss(Y, labels_micro)
# Save for backward
activations[microbatch_id] = H1
# Backward
for microbatch_id in reversed(range(num_microbatches)):
H1 = activations[microbatch_id]
# Backward through layer 2
grad_Y = compute_grad_from_loss(...)
grad_W2 += torch.matmul(H1.T, grad_Y) # Accumulate
grad_H1 = torch.matmul(grad_Y, W2.T)
# Send gradient to GPU 0
dist.send(grad_H1, dst=0)Communication cost
For microbatches:
- Forward: Send/Recv operations (each sending tensor of size )
- Backward: Send/Recv operations (same size)
- Total: point-to-point transfers
Memory consideration: Must store activations for all microbatches! This is the trade-off:
- More microbatches → less bubble time → better GPU utilization
- More microbatches → more memory for activation storage
Pros and cons
Pros:
- ✓ Can train models that don’t fit on any single GPU
- ✓ Simple conceptually (just split layers)
- ✓ No need to modify model architecture
Cons:
- ✗ Pipeline bubble reduces efficiency
- ✗ Requires careful microbatch tuning
- ✗ More complex gradient accumulation
- ✗ Load balancing issues if layers have different computational costs
Used for: Very large models (GPT-3 uses 3D parallelism: data + tensor + pipeline)
7.5 Comparing the three strategies
| Strategy | What’s split? | Communication | Memory/GPU | Best for |
|---|---|---|---|---|
| Data Parallel | Data batches | AllReduce (backward) | Full model | Standard training, moderate models |
| Tensor Parallel | Weight matrices | AllGather/AllReduce (fwd+bwd) | of weights | Wide layers, large hidden dims |
| Pipeline Parallel | Layers | Send/Recv (fwd+bwd) | of layers | Deep models, many layers |
Real-world LLM training uses all three!
Example: GPT-3 (175B parameters)
- Data parallelism across 64 batches
- Tensor parallelism within 8-GPU nodes (for wide layers)
- Pipeline parallelism across 8 stages (for depth)
- Total: 64 × 8 × 8 = 4096 GPUs!
8. Practical code examples
Let’s make the three parallelism strategies from Section 5 concrete with PyTorch code.
8.1 Data Parallelism (from section 5.1)
import torch
import torch.distributed as dist
# Initialize distributed environment
# Assumes you've already called dist.init_process_group()
rank = dist.get_rank()
world_size = dist.get_world_size()
# Problem: compute C = A @ B
# A: input data (batch of samples) - SPLIT across GPUs
# B: weight matrix - REPLICATED on all GPUs
M, K, N = 10000, 5000, 5000
# Split A by rows (data parallelism)
M_local = M // world_size
M_start = rank * M_local
M_end = (rank + 1) * M_local
# Each GPU loads its data slice and full model
A_local = load_matrix_slice(A, rows=slice(M_start, M_end), cols=slice(None)) # (M/P) × K
B = load_full_matrix(B) # K × N (replicated on all GPUs!)
# Forward pass: no communication needed!
C_local = torch.matmul(A_local, B) # (M/P) × N
# Each GPU has its portion of the output
# If we want the full result on all GPUs:
C_gathered = [torch.zeros_like(C_local) for _ in range(world_size)]
dist.all_gather(C_gathered, C_local)
C = torch.cat(C_gathered, dim=0) # M × N
# For training: gradient computation
# Each GPU computes gradient on its data slice
grad_B_local = torch.matmul(A_local.T, grad_C_local) # K × N
# AllReduce to average gradients across all GPUs
dist.all_reduce(grad_B_local, op=dist.ReduceOp.SUM)
grad_B = grad_B_local / world_size
# All GPUs update their identical copy of B
B -= learning_rate * grad_B8.2 Tensor Parallelism: Column-parallel (from section 5.2)
class ColumnParallelLinear(torch.nn.Module):
def __init__(self, in_features, out_features, process_group):
super().__init__()
self.process_group = process_group
world_size = dist.get_world_size(process_group)
# Each GPU owns only part of the columns
self.out_features_per_partition = out_features // world_size
self.weight = torch.nn.Parameter(
torch.randn(in_features, self.out_features_per_partition)
)
def forward(self, x):
# x shape: [batch, in_features]
# Each GPU computes its partition
output_partial = torch.matmul(x, self.weight) # [batch, out_features_per_partition]
# AllGather to collect all partitions
output_list = [torch.zeros_like(output_partial) for _ in range(dist.get_world_size(self.process_group))]
dist.all_gather(output_list, output_partial, group=self.process_group)
# Concatenate along feature dimension
output = torch.cat(output_list, dim=-1) # [batch, out_features]
return output8.3 Tensor Parallelism: Row-parallel (from section 5.2)
class RowParallelLinear(torch.nn.Module):
def __init__(self, in_features, out_features, process_group):
super().__init__()
self.process_group = process_group
world_size = dist.get_world_size(process_group)
# Each GPU owns only part of the rows
self.in_features_per_partition = in_features // world_size
self.weight = torch.nn.Parameter(
torch.randn(self.in_features_per_partition, out_features)
)
def forward(self, x_partial):
# x_partial shape: [batch, in_features_per_partition]
# Input is already partitioned across GPUs
# Each GPU computes its partial result
output_partial = torch.matmul(x_partial, self.weight) # [batch, out_features]
# AllReduce to sum all partials
dist.all_reduce(output_partial, op=dist.ReduceOp.SUM, group=self.process_group)
return output_partial # [batch, out_features]9. Summary and key takeaways
The fundamental primitives
In multi-GPU computing, collective communication operations are the building blocks:
Data Distribution:
- Broadcast — One-to-all replication
- Scatter — One-to-all distribution (different data)
- Gather — All-to-one collection
- AllGather — All-to-all collection (everyone gets everything)
Data Aggregation:
- Reduce — Combine data, deliver to one
- AllReduce — Combine data, deliver to all ⭐ Most important for ML
- ReduceScatter — Combine and distribute chunks
Advanced:
- AlltoAll — Complete shuffle
- Send/Recv — Point-to-point communication
- Barrier — Synchronization
Three parallelism strategies for distributed training
| Strategy | What’s split? | Communication | Memory/GPU | Best for |
|---|---|---|---|---|
| Data Parallelism (5.1) | Input data (rows of ) | AllReduce (backward only) | Full model | Model fits on 1 GPU, want larger batches |
| Tensor Parallelism (5.2) | Model weights (cols/rows of ) | AllGather or AllReduce (forward & backward) | Model / | Model too large for 1 GPU |
| 2D Parallelism (SUMMA) (5.3) | Both data AND model | Row/column Broadcasts | ~Model / | Maximum scalability, very large |
Hardware-aware optimization
Modern GPU clusters have hierarchical communication:
- Intra-node: NVLink/NVSwitch (~900 GB/s per H100) ⚡
- Inter-node: InfiniBand (~400 Gb/s) — 20× slower
Design principle: Maximize intra-node traffic, minimize inter-node traffic. NCCL automatically optimizes collectives for your topology.
Real-world impact
These techniques enable training models that wouldn’t fit on any single machine:
- GPT-3 (175B parameters): Trained using 3D parallelism (data + tensor + pipeline)
- Megatron-LM: Production framework built on AllReduce and AllGather patterns
- FSDP (Fully Sharded Data Parallel): Uses ReduceScatter + AllGather to shard optimizer states
Understanding collective operations isn’t just academic—it’s essential for anyone working with large-scale ML systems!
Further reading
- NCCL Documentation — Official NVIDIA guide
- Megatron-LM Paper — Tensor parallelism for transformers
- PyTorch Distributed Tutorial — Hands-on examples
- The Annotated Transformer — Understanding what you’re parallelizing