Pidoku

Collectives and NCCL

Module 9 Lesson 9.f 1h 15m Difficulty 4/5

Prerequisites 9.c, 14.c


Before you start: words you need#

WordPlain meaning
RankOne participant in a distributed job, usually one GPU and the process that drives it.
CollectiveA communication operation that every rank in a group takes part in at the same time, such as summing a tensor across all GPUs.
CommunicatorNCCL’s object for a fixed group of ranks that do collectives together.
All-reduceEvery rank contributes a tensor; afterwards every rank holds the sum. Tensor parallelism does two per layer (14.c).
All-to-allEvery rank sends a different piece of data to every other rank. Expert parallelism does this every MoE layer (14.e).
α (alpha) and β (beta)The two costs of a message: a fixed start-up time α, and the time per byte β = 1 ÷ bandwidth.
Protocol (Simple / LL / LL128)How NCCL packs data and signals that it has arrived. LL (“low latency”) variants trade bandwidth for latency.

1. What is it?#

Collectives are communication operations involving every rank in a group. NCCL (NVIDIA Collective Communications Library, said “nickel”) is the implementation almost everything uses on NVIDIA GPUs; AMD’s RCCL plays the same role on Instinct GPUs (7.h).

BROADCAST       one rank's data → all ranks
REDUCE          all ranks' data → summed on one rank
ALL-REDUCE      all ranks' data → summed, result on ALL ranks    ← tensor parallelism
ALL-GATHER      each rank's slice → the whole tensor on all ranks
REDUCE-SCATTER  sum across ranks, then each rank keeps one slice
ALL-TO-ALL      each rank sends distinct data to every other rank ← expert parallelism
SEND / RECV     point-to-point                                    ← pipeline parallelism

The current release line is NCCL 2.32 (2.32.6 on 9 November 2026); 2.32.3 added initial Rubin support.

Facts checked on 12 November 2026.


2. Why does it exist?#

Because naive implementations are very slow. NCCL:

  • detects the topology (NVLink, NVSwitch, PCIe, NICs, NUMA) and builds rings and trees through it;
  • implements algorithms that reach near-peak bandwidth;
  • runs on the GPU as kernels, with no CPU on the data path;
  • overlaps with compute on separate streams;
  • uses GPUDirect P2P and RDMA where available (9.c), and NVLink SHARP on NVSwitch systems.

A hand-rolled all-reduce using cudaMemcpy and host coordination is typically 5–20x slower.


3. Simple analogy#

Eight people each have a column of numbers and all need the grand total.

  • Ring: everyone passes a running subtotal to the person on their left, round and round. Each person only ever talks to one neighbour, and the work is shared evenly, but it takes many rounds.
  • Tree: people pair up, then pairs pair up, and so on, then the answer flows back down. Fewer rounds, more uneven work.
  • One-shot: everyone shouts their numbers to everyone at once and adds them up themselves. One round, but everyone hears everything: fine for a short list, terrible for a long one.

4. Tiny example: measuring it#

Shell
git clone https://github.com/NVIDIA/nccl-tests && cd nccl-tests && make

# all-reduce across 8 GPUs, message sizes from 1 KB to 1 GB
./build/all_reduce_perf -b 1K -e 1G -f 2 -g 8

# all-to-all (for MoE)
./build/alltoall_perf -b 1K -e 1G -f 2 -g 8

Illustrative output on an 8×H100 NVSwitch node (yours will differ):

    size    count    type   time(us)  algbw(GB/s)  busbw(GB/s)
      1K      256   float      8.9      0.11        0.20
     16K     4096   float      9.4      1.74        3.05
    256K    65536   float     14.2     18.5        32.3
      4M  1048576   float     78.3     53.5        93.6
     64M 16777216   float    881.0     76.2       133.3
      1G 268435456  float  13120.0     81.8       143.2

Read the time(us) column for small sizes: 8.9 µs for 1 KB and 9.4 µs for 16 KB. The time is almost constant: it is pure latency. That flat region is where LLM decode lives.

  • algbw is message size ÷ time.
  • busbw multiplies by 2(N−1)/N for all-reduce, so it can be compared with the hardware’s link bandwidth. Here 143 GB/s against a 450 GB/s NVLink 4 link per direction.

Run this on your hardware and record the results. You will use them in every communication cost estimate (9.g).


5. Technical explanation#

The ring all-reduce#

The ring explains the 2(N−1)/N factor that appears in every communication cost calculation.

N ranks, each with a buffer of S bytes, cut into N chunks.

PHASE 1: REDUCE-SCATTER (N−1 steps)
  Step k: rank i sends chunk (i−k) mod N to rank (i+1) mod N and adds the chunk it receives.
  After N−1 steps: rank i holds the fully reduced chunk i+1.

PHASE 2: ALL-GATHER (N−1 steps)
  Step k: rank i sends a complete chunk to rank (i+1) mod N.
  After N−1 steps: every rank has every reduced chunk.

Data sent per rank: 2 × (N−1)/N × S
Time:               2(N−1) × α  +  2(N−1)/N × S × β
                    └ latency ┘    └── bandwidth ──┘

Two observations:

  1. The bandwidth term tends to 2S/bandwidth as N grows: it does not grow with N. The ring is bandwidth-optimal.
  2. The latency term 2(N−1) × α does grow with N: 14 steps at N = 8.

LLM decode sends small messages: batch × hidden size × 2 bytes, a few hundred KB (14.c). So decode collectives are latency-bound. That is why:

  • NCCL uses trees and the LL protocols for small messages;
  • engines ship custom one-shot and two-shot all-reduce kernels;
  • tensor-parallel scaling degrades past 8: the latency term grows while each GPU’s compute shrinks (9.g).

How NCCL picks an algorithm#

  1. At initialisation it probes NVLink, PCIe, NUMA and the network, and builds graphs of possible rings and trees.
  2. For each call it picks an algorithm (Ring, Tree, NVLS on NVSwitch systems, PAT and others), a protocol (Simple, LL, LL128) and a number of channels (parallel rings), from a cost model of message size and topology.

The LL protocol sends small units with an inline flag, so the receiver knows data has arrived without a separate synchronisation: lower latency, half the bandwidth. LL128 does the same with 128-byte units and loses less bandwidth. If NCCL_DEBUG=INFO shows Simple for small decode all-reduces, something is misconfigured.

Newer NCCL features worth knowing#

  • NVLink SHARP (NVLS): NVSwitch chips perform part of the reduction, so less data crosses each link (9.c).
  • Symmetric memory and the device API: buffers registered at the same address on every rank, and kernels that issue communication from inside the GPU; recent releases extend this to the network (GPU-initiated networking). This is what lets compute and communication be fused into one kernel.
  • Fault handling: ncclCommAbort tears down a stuck communicator; ncclCommShrink builds a new communicator without failed ranks; ncclCommRevoke stops outstanding work. Frameworks are starting to use them; most serving stacks still restart the whole group on failure (23.e).
  • RAS: a built-in diagnostic service that reports which ranks are stuck and why (NCCL_RAS_ENABLE).

Custom all-reduce in inference engines#

vLLM, SGLang and TensorRT-LLM ship their own all-reduce kernels for small messages inside one NVLink domain:

  • One-shot: every GPU writes its buffer directly into every other GPU’s memory over NVLink, then each sums locally. One step, but N−1 times the data.
  • Two-shot: a direct reduce-scatter then a direct all-gather. Two steps, ring-like volume.

They only work when all GPUs can address each other’s memory (NVLink P2P), and engines fall back to NCCL otherwise. vLLM also has a PyTorch symmetric-memory path and FlashInfer-based fused all-reduce + RMSNorm kernels (14.c). The startup log says which is in use; --disable-custom-all-reduce turns vLLM’s own kernel off for comparison.

The environment variables that matter#

Shell
# DEBUGGING: start here
NCCL_DEBUG=INFO               # topology detection, transports, algorithm choice
NCCL_DEBUG_SUBSYS=INIT,GRAPH  # more detail on setup

# NETWORK SELECTION (multi-node)
NCCL_SOCKET_IFNAME=eth0       # interface for bootstrap traffic
NCCL_IB_HCA=mlx5_0,mlx5_1     # which RDMA adapters to use
NCCL_IB_DISABLE=1             # force TCP: debugging only, slow
NCCL_NET_GDR_LEVEL=PHB        # how far apart a GPU and NIC may be for GPUDirect RDMA

# ALGORITHM AND PROTOCOL (for experiments; defaults are usually right)
NCCL_ALGO=Ring,Tree
NCCL_PROTO=Simple,LL,LL128
NCCL_MIN_NCHANNELS=4
NCCL_MAX_NCHANNELS=32

# NVLINK
NCCL_P2P_DISABLE=1            # disable NVLink/PCIe peer-to-peer (debugging)
NCCL_NVLS_ENABLE=0            # disable NVLink SHARP (debugging)
NCCL_MNNVL_ENABLE=1           # multi-node NVLink on NVL72-class racks

There is no NCCL_TIMEOUT variable. Hang protection comes from the framework. In PyTorch, the timeout argument of init_process_group (default 10 minutes for NCCL) bounds how long a collective may wait; TORCH_NCCL_ASYNC_ERROR_HANDLING (on by default in recent PyTorch) tears the process down when a collective fails or times out, and TORCH_NCCL_BLOCKING_WAIT=1 makes the host thread wait and raise instead. Set a timeout deliberately; it converts a hang into a crash that a supervisor can restart (9.h, 23.e).


6. Under the hood: four algorithms, one model#

The program costs four all-reduce algorithms on 8 GPUs with α = 2 µs per step and 450 GB/s per GPU (NVLink 4), using the formulas above.

Go
// allreduce_algos.go — four all-reduce algorithms under the alpha-beta model.
package main

import (
	"fmt"
	"math"
)

const (
	n     = 8.0   // GPUs
	alpha = 2e-6  // seconds per step (launch, sync, link latency)
	beta  = 450e9 // bytes/s per GPU, one direction (NVLink 4)
)

// ring: 2(n-1) steps, each GPU moves 2(n-1)/n of the data.
func ring(s float64) float64 { return 2*(n-1)*alpha + 2*(n-1)/n*s/beta }

// tree: about 2 log2(n) steps; bandwidth term roughly 2s/beta.
func tree(s float64) float64 { return 2*math.Log2(n)*alpha + 2*s/beta }

// one-shot: every GPU writes its whole buffer to every peer, then sums locally.
func oneShot(s float64) float64 { return alpha + (n-1)*s/beta }

// two-shot: direct reduce-scatter, then direct all-gather: 2 steps, ring-like volume.
func twoShot(s float64) float64 { return 2*alpha + 2*(n-1)/n*s/beta }

func size(s float64) string {
	switch {
	case s >= 1<<30:
		return fmt.Sprintf("%.0f GB", s/(1<<30))
	case s >= 1<<20:
		return fmt.Sprintf("%.0f MB", s/(1<<20))
	}
	return fmt.Sprintf("%.0f KB", s/(1<<10))
}

func main() {
	fmt.Println("message       ring µs   tree µs  one-shot µs  two-shot µs   fastest")
	for _, s := range []float64{1 << 10, 64 << 10, 512 << 10, 4 << 20, 64 << 20, 1 << 30} {
		t := map[string]float64{"ring": ring(s), "tree": tree(s), "one-shot": oneShot(s), "two-shot": twoShot(s)}
		best := "ring"
		for k, v := range t {
			if v < t[best] {
				best = k
			}
		}
		fmt.Printf("%8s %12.1f %9.1f %12.1f %12.1f   %s\n",
			size(s), t["ring"]*1e6, t["tree"]*1e6, t["one-shot"]*1e6, t["two-shot"]*1e6, best)
	}
}

Output:

message       ring µs   tree µs  one-shot µs  two-shot µs   fastest
    1 KB         28.0      12.0          2.0          4.0   one-shot
   64 KB         28.3      12.3          3.0          4.3   one-shot
  512 KB         30.0      14.3         10.2          6.0   two-shot
    4 MB         44.3      30.6         67.2         20.3   two-shot
   64 MB        289.0     310.3       1045.9        265.0   two-shot
    1 GB       4203.7    4784.2      16704.7       4179.7   two-shot

How to read it:

  • Up to tens of KB, one-shot wins by a wide margin: one step instead of 14. Decode messages at small batch are in this range.
  • Around hundreds of KB to MB, two-shot wins: two steps, without one-shot’s N-fold traffic.
  • For large messages, ring and two-shot converge: both move 2(N−1)/N × S, so bandwidth sets the time. The model gives two-shot a small edge because it assumes every GPU can send to all peers at full speed at once, which only an NVSwitch provides; real NCCL rings and NVLS do as well or better at these sizes.
  • The model ignores NCCL’s protocol choices, which is why real small-message times (about 9 µs above) sit between the tree and one-shot rows.

7. Performance implications#

  • Decode collectives are latency-bound. More bandwidth does not help; fewer steps does.
  • Prefill collectives are bandwidth-bound. Thousands of tokens make each message tens of MB (9.g).
  • Custom kernels matter most at small batch. At 160 all-reduces per token, saving 10–20 µs each is several milliseconds per token.
  • Fusion hides the rest. Fusing the all-reduce with the following residual add and RMSNorm, or overlapping it with the next GEMM, removes kernel boundaries (13.j).

8. Production implications#

  • Measure collectives with nccl-tests on every new node type. Record the latency and busbw curves; they are inputs to every capacity estimate.
  • Run NCCL_DEBUG=INFO once per node type to confirm the transports: P2P/NVL inside a node, NET/IB/.../GDRDMA across nodes.
  • Set a framework timeout and supervise the whole group; one dead rank stalls the rest.
  • Watch the logs for unhandled system error and remote process exited, which usually mean a rank died, and for RAS reports of stuck ranks.
  • Pin NCCL versions with the engine and driver you tested. New releases change algorithm choices and occasionally performance.

9. Common mistakes#

  1. Setting NCCL_TIMEOUT and believing it does something. It does not exist; use the framework’s timeout.
  2. Assuming NVLink is being used. A misconfigured container can silently fall back to PCIe or shared memory. Check NCCL_DEBUG=INFO.
  3. Optimising bandwidth when you are latency-bound. Decode messages are small.
  4. Turning off the engine’s custom all-reduce. Measurable inter-token latency at small batch.
  5. Wrong NCCL_SOCKET_IFNAME. NCCL bootstraps over the wrong interface and fails or runs slowly.
  6. Expecting NCCL to recover by itself. It provides tools (abort, shrink); your framework must use them, or restart the group.

10. Hands-on exercise#

  1. Run allreduce_algos.go. Change α to 5 µs and then N to 72 (an NVL72). Where does the one-shot/two-shot crossover move?
  2. Benchmark your collectives. Run all_reduce_perf from 1 KB to 1 GB. Plot time against size on log-log axes. Find the crossover between the latency-bound and bandwidth-bound regions.
  3. Protocol effect. Run all_reduce_perf with NCCL_PROTO=Simple and with the default. How much does LL buy at 16 KB?
  4. Custom all-reduce. Measure decode inter-token latency in vLLM with and without --disable-custom-all-reduce at batch 1 and batch 64.
  5. Break it. Set NCCL_P2P_DISABLE=1 and re-measure. This simulates a server without NVLink.

11. Interview questions#

  1. Explain the ring all-reduce and derive its 2(N−1)/N data volume.
  2. Why is LLM decode latency-bound rather than bandwidth-bound in its collectives?
  3. What is the LL protocol, and when does NCCL use it?
  4. What are one-shot and two-shot all-reduce, and when does each win?
  5. How do you protect a serving job from a hung collective?
  6. How would you verify that NVLink and GPUDirect RDMA are actually being used?
  7. What happens when one rank in an NCCL group dies, and what can you do about it?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in