# Collective Communication: Why All-Reduce Has So Many Algorithms

> Collective communication is the plumbing of multi-GPU training. This page simulates five all-reduce algorithms and checks them element by element, compares rounds and traffic with the alpha-beta model, then shows how topology, summation order and MoE all-to-all change the choice.

- URL: https://dmxsf.com/en/wiki/systems/collective-communication/
- [DMXSF](https://dmxsf.com/en/about/)
- Advanced
- Updated: 2026-11-18
- Tags: Systems & hardware, Distributed training, Mixture of Experts

## After this page you will be able to

- State what broadcast, reduce, all-reduce, reduce-scatter, all-gather and all-to-all do, and derive that all-reduce equals reduce-scatter followed by all-gather.
- Write the time of a collective as rounds times alpha plus traffic times S/B, and derive the rounds and traffic of the star, binary tree, recursive doubling, ring and recursive halving-doubling algorithms.
- Tell whether an all-reduce is latency-bound or bandwidth-bound, compute the crossover between two algorithms, and explain why gradient sync uses rings while small activation all-reduces use recursive doubling.
- Explain how the bandwidth gap between NVLink inside a node and InfiniBand between nodes changes the choice (staggered rings, 2D ring, halving-doubling), and compare busbw with link bandwidth.
- Explain how the non-associativity of floating-point addition makes different reduction algorithms give bitwise different results, and why low-precision reduction error grows with chain length.
- Explain why MoE all-to-all is limited by inter-node bandwidth and how node-limited routing cuts the number of copies sent over IB.

**Collective communication** is a family of operations in which several GPUs cooperate: every participant (a **rank**) calls the same operation at the same time, and together they broadcast, sum, gather or transpose data. Every synchronization in multi-GPU training is a collective. Data parallelism uses all-reduce to add up gradients; ZeRO and FSDP use reduce-scatter and all-gather to shard gradients and parameters; tensor parallelism does an all-reduce in every layer, forward and backward; expert parallelism in MoE uses all-to-all to ship tokens to the GPUs that hold their experts. One operation has many implementations, and the best one depends on three things: how large the message is (latency-bound or bandwidth-bound), what the network looks like (NVLink inside a node and InfiniBand between nodes differ by a few times), and whether you care about bit-for-bit reproducible results.

The previous two pages did the accounting for compute and bandwidth ([GPU and Roofline](https://dmxsf.com/en/wiki/systems/gpu-and-roofline/)) and for numerical precision ([Numerical Precision](https://dmxsf.com/en/wiki/systems/numerical-precision/)). This page does the accounting for **communication**, in the same way: write five all-reduce algorithms as a **synchronous network simulator** (a few dozen lines of NumPy each, recording how much data every rank sends and receives in every round), check element by element that the result equals `x.sum(0)`, and feed the rounds and the traffic into the alpha-beta model to get times. Everything runs on a CPU, with no GPU or NIC. The times come from the model, not from measurement: the bandwidths are the H800-cluster numbers reported in the DeepSeek-V3 paper ([walkthrough](https://dmxsf.com/en/blog/deepseek-v3-technical-report/)), and the start-up latency of 5 µs is an illustrative value; on another cluster, measure with nccl-tests. This page expands the ring all-reduce section of [Distributed Training](https://dmxsf.com/en/wiki/pretraining/distributed-training/) and answers the question that page leaves open: if the ring is already bandwidth-optimal, why do communication libraries ship trees, 2D rings and so many other algorithms?

## The six primitives

Collectives have a fixed vocabulary. Take $p$ ranks, each holding a vector of size $S$. These six primitives cover almost every synchronization in LLM training and inference (definitions as in the NCCL documentation):

*Figure: Four ranks, each with four data blocks (a block can be large). Color shows which rank the data came from (a to d), S is the sum of that block over all ranks, and a dashed box is empty. After all-reduce every rank holds the full sum; after reduce-scatter each rank holds one block of it, and an all-gather on top restores the all-reduce result.*

| Primitive | What it does | What each rank holds afterwards | Typical use |
| --- | --- | --- | --- |
| broadcast | copies the vector of one rank (the root) to everyone | the root's vector | distributing the initial weights |
| reduce | sums all vectors element-wise, the result goes to the root only | the root holds the sum, the others are unchanged | collecting a metric on rank 0 |
| all-reduce | sums element-wise, the result goes to everyone | the full sum (an identical copy on every rank) | gradient sync in data parallelism, activation sums in tensor parallelism |
| reduce-scatter | sums element-wise, then splits the sum into $p$ blocks, one per rank | block $r$ of the sum (size $S/p$) | gradient sharding in ZeRO and FSDP |
| all-gather | every rank contributes one block, the concatenation goes to everyone | the full concatenated vector (size $S$) | gathering parameters in ZeRO-3 and FSDP |
| all-to-all | rank $i$ sends its block $j$ to rank $j$ (a block "transpose") | block $r$ from every rank | dispatch and combine in MoE |

In the first five, data is either summed or copied to everyone; all-to-all alone is a "transpose": every rank sends different content to every other rank, and nothing is summed. That difference matters in the last section.

## One identity: all-reduce is reduce-scatter plus all-gather

Take an all-reduce apart and it does two things: compute the sum, then deliver the sum to everyone. Reduce-scatter does the first (the sum is split into blocks and each rank holds only its own block), all-gather does the second (each rank hands its block of the sum to everyone). The NCCL documentation states two equivalences: a reduce followed by a broadcast, and a reduce-scatter followed by an all-gather, are both the same as an all-reduce.

The two forms differ in **who moves the data**. Reduce plus broadcast is a tree: the root's link carries the whole vector while most other links sit idle. In reduce-scatter plus all-gather each rank handles only a $1/p$ block at a time, all links work simultaneously, and each rank sends

$$
\underbrace{\frac{p-1}{p}S}_{\text{reduce-scatter}}+\underbrace{\frac{p-1}{p}S}_{\text{all-gather}}=2\,\frac{p-1}{p}\,S
$$

which only approaches $2S$ as $p$ grows: it is **almost independent of the GPU count**, and that is one of the basic reasons gradient sync still scales. The nccl-tests documentation argues by counting that this is the ideal: every element needs $p-1$ additions and $p$ assignments, each step lands on a different rank, so there are $2(p-1)$ point-to-point transfers per element, shared by $p$ links, and when bandwidth is the limit the best possible time is $t=\frac{2(p-1)\,S}{p\,B}$. ZeRO and FSDP pull exactly these two steps apart: after the reduce-scatter each rank updates only its own share of the parameters, and an all-gather restores the full parameters (see [Distributed Training](https://dmxsf.com/en/wiki/pretraining/distributed-training/)).

## Five implementations of all-reduce

[Read the ring all-reduce simulator](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/systems/collectives.py)

The simulator below is the basis of the whole page. It does one thing: it records the point-to-point transfers that happen together in one round, and at the end of the round it counts how many elements each rank sent and received. The algorithms are written as operations on NumPy arrays; nothing runs in parallel, but the data flow matches real implementations, so we can check results element by element and count rounds and traffic exactly.

Environment: Apple M2 Max (CPU), Python 3.14.3, NumPy 2.4.2, PyTorch 2.10.0 (used only in the BF16 section, 1 thread); the whole code runs in about 20 seconds, and the script printed identical output in two independent runs.

```python
import numpy as np

class Net:
    """Synchronous network model: a round is a batch of simultaneous sends.

    If node is set, a transfer inside one node (node consecutive ranks) is
    tagged nv (NVLink) and one across nodes ib (InfiniBand); otherwise all.
    Each round records, per link class, the largest amount any single rank
    sends or receives, in elements.
    """

    def __init__(self, p, node=None):
        self.p, self.node, self.rounds, self.cur = p, node, [], []

    def send(self, src, dst, x):
        self.cur.append((src, dst, x.size))
        return x.copy()

    def end_round(self):
        vol = {}
        for s, d, k in self.cur:
            c = "all"
            if self.node:
                c = "nv" if s // self.node == d // self.node else "ib"
            v = vol.setdefault(c, np.zeros((2, self.p), dtype=np.int64))
            v[0, s] += k
            v[1, d] += k
        self.rounds.append({c: int(v.max()) for c, v in vol.items()})
        self.cur = []
```

`Net.send` copies the data and does the bookkeeping; `end_round` records the maximum, over ranks, of the elements sent or received in that round, which is the bottleneck of the round. The `node` argument is for the topology section. First, the three simplest algorithms:

```python
def star(net, x):
    """Everyone sends to rank 0, which sums and sends the result back."""
    got = [net.send(r, 0, x[r]) for r in range(1, net.p)]
    net.end_round()
    total = x[0] + sum(got)
    out = [total] + [net.send(0, r, total) for r in range(1, net.p)]
    net.end_round()
    return out

def tree(net, x):
    """Binomial tree: reduce to rank 0, then broadcast back."""
    buf, d = [v.copy() for v in x], 1
    while d < net.p:
        for r in range(d, net.p, 2 * d):
            buf[r - d] += net.send(r, r - d, buf[r])
        net.end_round()
        d *= 2
    while d > 1:
        d //= 2
        for r in range(d, net.p, 2 * d):
            buf[r] = net.send(r - d, r, buf[r - d])
        net.end_round()
    return buf

def rec_double(net, x):
    """Recursive doubling: swap the whole vector with the partner at d."""
    buf, d = [v.copy() for v in x], 1
    while d < net.p:
        got = [net.send(r ^ d, r, buf[r ^ d]) for r in range(net.p)]
        buf = [b + g for b, g in zip(buf, got)]
        net.end_round()
        d *= 2
    return buf
```

- **Star**: every rank sends its vector to rank 0, which sums and sends the result back. Only 2 rounds, but rank 0's link must receive $p-1$ vectors in one round: the worst baseline.
- **Binary tree**: in round $k$, ranks at distance $2^{k-1}$ add their vector into their partner (reduce), then the result is broadcast back in reverse order: $2\lg p$ rounds, and the bottleneck rank moves a whole vector in every round.
- **Recursive doubling**: in every round each rank exchanges its whole vector with the partner at distance $d=1,2,4,\dots$ and adds; after $\lg p$ rounds every rank holds the full sum. The fewest rounds, but every round moves a whole vector.

The **ring** connects the $p$ ranks in a circle and cuts the vector into $p$ blocks. The reduce-scatter phase takes $p-1$ steps: in step $s$, rank $i$ sends block $(i-s)\bmod p$ to the next rank, and the receiver adds it into its own copy of that block; after $p-1$ steps every block has gone once around the ring and each rank holds the complete sum of one block. The all-gather phase takes another $p-1$ steps to hand those blocks to everyone. Every step, every rank sends only $S/p$. `ring_phase` also supports several rings running concurrently, which the topology section uses.

```python
def ring_phase(net, buf, groups, spans, reduce):
    """One ring phase: every group walks m-1 steps on its own span.

    reduce=True is reduce-scatter (add while passing), False is all-gather.
    """
    m = len(groups[0])
    for s in range(m - 1):
        moves = []
        for g, (lo, hi) in zip(groups, spans):
            w = (hi - lo) // m
            for i, r in enumerate(g):
                c = (i - s) % m if reduce else (i + 1 - s) % m
                moves.append((r, g[(i + 1) % m], lo + c * w, lo + c * w + w))
        sent = [(d, a, b, net.send(r, d, buf[r][a:b])) for r, d, a, b in moves]
        for d, a, b, v in sent:
            if reduce:
                buf[d][a:b] += v
            else:
                buf[d][a:b] = v
        net.end_round()

def ring(net, x):
    """Ring all-reduce: reduce-scatter plus all-gather, 2(p-1) rounds."""
    buf, g, n = [v.copy() for v in x], [list(range(net.p))], x.shape[1]
    ring_phase(net, buf, g, [(0, n)], True)
    ring_phase(net, buf, g, [(0, n)], False)
    return buf
```

**Recursive halving-doubling** (Rabenseifner's algorithm) does the reduce-scatter with "vector halving, distance doubling": in the first round a rank exchanges with its partner at distance 1, sends the half it is not responsible for and adds the half it receives; the next round repeats on the remaining half with the partner at distance 2, and so on for $\lg p$ rounds, leaving each rank with a complete sum of size $S/p$. The all-gather runs in reverse: the vector doubles and the distance halves. It has both the low latency of $2\lg p$ rounds and the optimal bandwidth of $2\frac{p-1}{p}S$; the price is that $p$ must be a power of two (the general case is handled in the paper by Thakur et al.).

```python
def halve_double(net, x):
    """Rabenseifner (p a power of two): vector-halving reduce-scatter and
    vector-doubling all-gather."""
    p, n = net.p, x.shape[1]
    buf, span = [v.copy() for v in x], [(0, n)] * p
    ds = [1 << k for k in range(p.bit_length() - 1)]  # 1, 2, 4, ...
    for d in ds:
        sent = []
        for r in range(p):
            lo, hi = span[r]
            mid = (lo + hi) // 2
            a, b = (lo, mid) if r & d else (mid, hi)  # the half to send
            sent.append((r ^ d, a, b, net.send(r, r ^ d, buf[r][a:b])))
        for q, a, b, v in sent:
            buf[q][a:b] += v  # q keeps exactly this half
            span[q] = (a, b)
        net.end_round()
    for d in reversed(ds):
        sent = [(r ^ d, span[r], net.send(r, r ^ d, buf[r][slice(*span[r])]))
                for r in range(p)]
        old = list(span)
        for q, (a, b), v in sent:
            buf[q][a:b] = v
            span[q] = (min(old[q][0], a), max(old[q][1], b))
        net.end_round()
    return buf
```

Now check each algorithm for $p=8$ and $p=64$, with 4096 random integers per rank (integer addition is exact, so `==` can decide right from wrong):

```python
ALGOS = {"star": star, "tree": tree, "rec-double": rec_double,
         "ring": ring, "halve-double": halve_double}
rng = np.random.default_rng(0)
n, nets = 4096, {}
print(f"{'p':>3} {'algorithm':<13}{'rounds':>7}{'volume/n':>10}"
      f"{'formula':>9}  correct")
for p in (8, 64):
    x = rng.integers(-1000, 1000, size=(p, n))  # integers: == is exact
    lg = p.bit_length() - 1
    formula = {"star": (2, 2 * (p - 1)), "tree": (2 * lg, 2 * lg),
               "rec-double": (lg, lg), "ring": (2 * (p - 1), 2 * (p - 1) / p),
               "halve-double": (2 * lg, 2 * (p - 1) / p)}
    for name, f in ALGOS.items():
        net = nets[(p, name)] = Net(p)
        ok = all(np.array_equal(o, x.sum(0)) for o in f(net, x))
        rounds, vol = len(net.rounds), sum(r["all"] for r in net.rounds) / n
        ok = ok and (rounds, vol) == formula[name]
        print(f"{p:>3} {name:<13}{rounds:>7}{vol:>10.3f}"
              f"{formula[name][1]:>9.3f}  {ok}")
```

All five algorithms give every rank a result equal to `x.sum(0)` element by element (`correct` is True throughout). `rounds` is the number of rounds, and `volume/n` is the number of elements the bottleneck rank moves over all rounds divided by the vector length, that is, the traffic in units of $S$; it matches the closed-form `formula` column exactly:

| Algorithm | Rounds $R$ | Traffic $c$ of the bottleneck rank (units of $S$) | At $p=64$ |
| --- | --- | --- | --- |
| star | 2 | $2(p-1)$ | 2 rounds, 126 |
| binary tree | $2\lg p$ | $2\lg p$ | 12 rounds, 12 |
| recursive doubling | $\lg p$ | $\lg p$ | 6 rounds, 6 |
| ring | $2(p-1)$ | $2(p-1)/p$ | 126 rounds, 1.969 |
| recursive halving-doubling | $2\lg p$ | $2(p-1)/p$ | 12 rounds, 1.969 |

Ring and halving-doubling both reach the ideal traffic $2(p-1)/p$; they differ in rounds: the ring needs $2(p-1)$, which grows linearly with the GPU count, halving-doubling only $2\lg p$.

## The alpha-beta model: latency and bandwidth

The time of one point-to-point transfer can be written $T=\alpha+S/B$: $\alpha$ is a start-up latency independent of the data size (software scheduling, kernel launch, network round trip), $B$ is the link bandwidth and $S$ the number of bytes. For a synchronous collective algorithm, add up the time of every round and get

$$
T=R\,\alpha+c\,\frac{S}{B}
$$

where $R$ is the number of rounds and $c$ the traffic of the bottleneck rank (units of $S$), exactly the two columns the simulator prints. In this formula every algorithm is just a pair $(R,c)$, so comparing algorithms means comparing two numbers: for small messages $R\alpha$ dominates and fewer rounds win; for large messages $cS/B$ dominates and less traffic wins. The model ignores the arithmetic of the summation itself (an H100's memory bandwidth of 3.35 TB/s is 67 times a 50 GB/s network, so summing is much cheaper than moving), congestion and protocol overhead, so it is good for orderings and orders of magnitude only.

The times below use $\alpha=5$ µs (an illustrative value) and the bandwidths reported in the DeepSeek-V3 paper. $p=8$ assumes the 8 GPUs sit in one node, so the link is NVLink at 160 GB/s; $p=64$ assumes 8 nodes and charges every link at the inter-node IB rate of 50 GB/s (inside and outside the node are not distinguished yet; the next section does that). The star makes rank 0 send and receive $p-1$ messages in one round while the model charges one $\alpha$ per round, which is unfair to it, so the timing tables leave it out. The largest message, 13.5 GB, is the BF16 gradient of a 7B model (6.738B parameters).

```python
ALPHA = 5e-6  # start-up latency per round: an illustrative value
BW = {8: 160e9, 64: 50e9}  # bytes/s per link: H800 numbers, DeepSeek-V3
SIZES = [("16 KiB", 16 * 2**10), ("512 KiB", 512 * 2**10),
         ("16 MiB", 16 * 2**20), ("512 MiB", 512 * 2**20),
         ("13.5 GB", 13.476e9)]

def seconds(net, size, n, alpha, bw):
    """Per round: alpha + bytes of the busiest rank / bandwidth (max over
    link classes); then sum over rounds."""
    return sum(alpha + max(v / n * size / bw[c] for c, v in r.items())
               for r in net.rounds)

TIMED = [a for a in ALGOS if a != "star"]  # star: p-1 msgs/round, unfair
for p in (8, 64):
    print(f"p={p}, bandwidth {BW[p] / 1e9:.0f} GB/s, "
          f"alpha={ALPHA * 1e6:.0f} µs, times in ms")
    print(f"{'size':<9}" + "".join(f"{a:>13}" for a in TIMED) + "   best")
    for label, size in SIZES:
        t = {a: seconds(nets[(p, a)], size, n, ALPHA, {"all": BW[p]})
             for a in TIMED}
        print(f"{label:<9}" + "".join(f"{t[a] * 1e3:>13.3f}" for a in TIMED)
              + f"   {min(t, key=t.get)}")
    ra, rb = nets[(p, "rec-double")], nets[(p, "halve-double")]
    lat = (len(rb.rounds) - len(ra.rounds)) * ALPHA
    gap = (sum(r["all"] for r in ra.rounds)
           - sum(r["all"] for r in rb.rounds)) / n / BW[p]
    print(f"rec-double / halve-double crossover: {lat / gap / 2**10:.0f} KiB")
    tr = seconds(nets[(p, "ring")], SIZES[-1][1], n, ALPHA, {"all": BW[p]})
    alg = SIZES[-1][1] / tr / 1e9
    print(f"ring, {SIZES[-1][0]}: algbw {alg:.1f} GB/s, "
          f"busbw {alg * 2 * (p - 1) / p:.1f} GB/s")
```

```text
p=8, bandwidth 160 GB/s, alpha=5 µs, times in ms
size              tree   rec-double         ring halve-double   best
16 KiB           0.031        0.015        0.070        0.030   rec-double
512 KiB          0.050        0.025        0.076        0.036   rec-double
16 MiB           0.659        0.330        0.254        0.214   halve-double
512 MiB         20.163       10.081        5.942        5.902   halve-double
13.5 GB        505.380      252.690      147.464      147.424   halve-double
rec-double / halve-double crossover: 1875 KiB
ring, 13.5 GB: algbw 91.4 GB/s, busbw 159.9 GB/s
p=64, bandwidth 50 GB/s, alpha=5 µs, times in ms
size              tree   rec-double         ring halve-double   best
16 KiB           0.064        0.032        0.631        0.061   rec-double
512 KiB          0.186        0.093        0.651        0.081   halve-double
16 MiB           4.087        2.043        1.291        0.721   halve-double
512 MiB        128.909       64.455       21.769       21.199   halve-double
13.5 GB       3234.300     1617.150      531.247      530.678   halve-double
rec-double / halve-double crossover: 363 KiB
ring, 13.5 GB: algbw 25.4 GB/s, busbw 49.9 GB/s
```

How to read the two tables:

- **Small messages: count rounds.** At 16 KiB recursive doubling is fastest at both scales (0.015 ms and 0.032 ms). At 64 ranks the ring takes 126 rounds, and the start-up latency alone is 126 × 5 µs = 0.63 ms, 0.631 ms in total, about 20 times recursive doubling.
- **Large messages: count traffic.** At 13.5 GB ring and halving-doubling are almost equally fast (64 ranks: 531.247 and 530.678 ms), recursive doubling is about 3 times slower and the binary tree about 6 times: their traffic is 6 and 12 vectors against the ring's 1.969.
- **In between there is a crossover.** Recursive doubling ($R_a,c_a$) and halving-doubling ($R_b,c_b$) take equally long at the data size
  $S^{*}=\frac{(R_b-R_a)\,\alpha B}{c_a-c_b}$, which is 363 KiB for 64 ranks and 1875 KiB for 8 ranks (the second-to-last line of each block of output). Below it the rounds decide, above it the traffic does. $S^{*}$ is proportional to $\alpha B$, the number of bytes a link moves during one start-up time, so higher bandwidth pushes the crossover to the right.
- **busbw approaches the link bandwidth.** The last line of each block is `algbw` (data size over time) and `busbw` (the "bus bandwidth" after multiplying by $2(p-1)/p$) for a ring all-reduce of 13.5 GB. `algbw` falls with the GPU count (91.4 GB/s to 25.4 GB/s) while `busbw` steadily approaches the link bandwidth (159.9 and 49.9 GB/s against 160 and 50 GB/s). That is why nccl-tests introduced `busbw`: it can be compared directly with the hardware peak and does not change with the GPU count.

*Figure: Time of one all-reduce versus data size at p=64, 50 GB/s and alpha=5 µs (log-log). The curves are T = R alpha + c S/B, with the number of rounds R and the volume c (in units of S) taken from the simulator output above. The dashed line is the crossover between rec-double and halve-double; to its left the number of rounds decides, to its right the volume does, and ring almost coincides with halve-double there.*

Each curve in the figure is $T=R\alpha+cS/B$: the flat part on the left is $R\alpha$ (latency), the slope-1 part on the right is $cS/B$ (bandwidth). The ring has the highest plateau (126 rounds), recursive doubling the lowest (6 rounds); on the right, the two algorithms with the least traffic, ring and halving-doubling, hug the bottom. The two typical situations sit at the two ends of the figure: **gradient sync** (13.5 GB) is far to the right, bandwidth-bound, and should use a ring or halving-doubling; the **activation all-reduce of tensor parallelism** at batch size 1 in decoding is only 8192 × 2 bytes = 16 KiB (hidden size 8192, BF16), near the left end, latency-bound, and the algorithm with fewer rounds wins. Both situations exist in the same cluster, which is why communication libraries pick the algorithm by message size instead of fixing one. NCCL's environment variable `NCCL_ALGO` can restrict the algorithms; it is unset by default, in which case NCCL chooses automatically from the node topology and architecture.

The calculator below hands you the same model: change the ranks, the message size, the bandwidth and the latency, and watch the four curves and the crossover move. The defaults are 64 ranks, 50 GB/s and $\alpha=5$ µs; click "16 KiB" and then "13.5 GB" to see the fastest algorithm change from recursive doubling to halving-doubling; drop the ranks to 2 and the crossover disappears, because with two ranks recursive doubling needs one round and moves no more data than the others.

**Tree variants.** The binary tree in the table is the worst because the root's link moves $2\lg p$ times the data; in this model it is dominated by recursive doubling on both counts (twice the rounds and twice the traffic). NCCL 2.4 introduced the **double binary tree**: two complementary trees in which every rank is an interior node in one and a leaf in the other, each tree handling half of the data, so every rank sends and receives as little as in a ring while the latency grows with $\lg p$. NVIDIA reported up to 180 times lower latency than the ring on 24,576 GPUs of the Summit supercomputer, and NCCL switches back to rings automatically when a ring would give more bandwidth.

## Multi-node topology: two kinds of link

A real cluster is not a uniform network. In DeepSeek-V3's H800 cluster the 8 GPUs of a node are connected by NVLink (160 GB/s) while nodes are connected by InfiniBand (50 GB/s), a factor of 3.2. The model above treats all links as equally fast, which is unfair to a 64-rank ring: some hops of the ring always cross nodes over IB, and every round waits for the slowest hop.

`Net(p, node=8)` books the transfers of every round by link class (`nv` and `ib`). The time of a round is the slower of the two classes (they can run concurrently), and the time of the whole all-reduce is the sum over rounds. Below, four approaches are compared on a 13.5 GB gradient, assuming every GPU has its own 50 GB/s inter-node link (one NIC per GPU):

| Approach | Idea |
| --- | --- |
| flat ring | one big ring over all $p$ ranks, in rank order |
| 8 rings | the data is split into 8 parts and 8 concurrent rings handle one part each, every ring entering and leaving the node through a different GPU |
| 2D ring | reduce-scatter inside the node, then an all-reduce of each 1/8 across nodes, then an all-gather inside the node (called the hierarchical ring in the NCCL 2.4 blog) |
| halve-double | recursive halving-doubling with ranks numbered contiguously per node |

```python
K = 8  # GPUs per node
BWX = {"nv": 160e9, "ib": 50e9}  # NVLink and IB, again from DeepSeek-V3
GRAD = 6.738e9 * 2  # BF16 gradients of a 7B model: 13.5 GB

def multi_ring(net, x):
    """8 concurrent rings, 1/8 of the data each, entering nodes at
    different GPUs."""
    p, n = net.p, x.shape[1]
    buf = [v.copy() for v in x]
    gs = [[nd * K + (j + t) % K for nd in range(p // K) for j in range(K)]
          for t in range(K)]
    spans = [(t * n // K, (t + 1) * n // K) for t in range(K)]
    ring_phase(net, buf, gs, spans, True)
    ring_phase(net, buf, gs, spans, False)
    return buf

def two_d_ring(net, x):
    """2D ring: reduce-scatter in node, all-reduce across, all-gather."""
    p, n = net.p, x.shape[1]
    buf, nodes = [v.copy() for v in x], p // K
    intra = [list(range(i * K, i * K + K)) for i in range(nodes)]
    inter = [list(range(j, p, K)) for j in range(K)]
    own = [((j + 1) % K * n // K, ((j + 1) % K + 1) * n // K) for j in range(K)]
    ring_phase(net, buf, intra, [(0, n)] * nodes, True)
    ring_phase(net, buf, inter, own, True)
    ring_phase(net, buf, inter, own, False)
    ring_phase(net, buf, intra, [(0, n)] * nodes, False)
    return buf

TOPO = {"flat ring": ring, "8 rings": multi_ring, "2D ring": two_d_ring,
        "halve-double": halve_double}
print(f"{'p':>4} {'algorithm':<13}{'rounds':>7}{'nv/n':>7}{'ib/n':>7}"
      f"{'nv ms':>8}{'ib ms':>8}{'time ms':>9}{'speedup':>9}  correct")
for p in (64, 512):
    x = rng.integers(-1000, 1000, size=(p, n))
    for name, f in TOPO.items():
        net = Net(p, node=K)
        ok = all(np.array_equal(o, x.sum(0)) for o in f(net, x))
        nv = sum(r.get("nv", 0) for r in net.rounds) / n
        ib = sum(r.get("ib", 0) for r in net.rounds) / n
        t = seconds(net, GRAD, n, ALPHA, BWX) * 1e3
        base = t if name == "flat ring" else base
        print(f"{p:>4} {name:<13}{len(net.rounds):>7}{nv:>7.3f}{ib:>7.3f}"
              f"{nv * GRAD / BWX['nv'] * 1e3:>8.1f}"
              f"{ib * GRAD / BWX['ib'] * 1e3:>8.1f}"
              f"{t:>9.1f}{base / t:>8.1f}x  {ok}")
```

```text
   p algorithm     rounds   nv/n   ib/n   nv ms   ib ms  time ms  speedup  correct
  64 flat ring        126  1.969  1.969   165.8   530.6    531.2     1.0x  True
  64 8 rings          126  1.723  0.246   145.1    66.3    145.7     3.6x  True
  64 2D ring           28  1.750  0.219   147.4    59.0    206.5     2.6x  True
  64 halve-double      12  1.750  0.219   147.4    59.0    206.4     2.6x  True
 512 flat ring       1022  1.996  1.996   168.1   538.0    543.1     1.0x  True
 512 8 rings         1022  1.747  0.250   147.1    67.2    152.2     3.6x  True
 512 2D ring          140  1.750  0.246   147.4    66.3    214.4     2.5x  True
 512 halve-double      18  1.750  0.246   147.4    66.3    213.8     2.5x  True
```

`nv/n` and `ib/n` are the sums over rounds of the elements the bottleneck rank sends or receives on NVLink and IB (units of $S$), `nv ms` and `ib ms` are those divided by the respective bandwidth, and `time ms` is the time with the slower link taken round by round and then summed.

- **The flat ring is stuck on IB.** In every round some rank (the GPU on the node boundary) has to use IB and the whole ring waits for it: 531.2 ms is almost exactly the 530.6 of `ib ms`, while NVLink would have needed only 165.8 ms.
- **8 rings spread the IB traffic over 8 GPUs.** Every ring enters and leaves the node through a different GPU, so `ib/n` falls from 1.969 to 0.246 and `ib ms` to 66.3; the bottleneck moves to NVLink (145.1 ms), both link classes work at the same time, and the total of 145.7 ms is 3.6 times as fast as the flat ring.
- **The 2D ring has less IB traffic and is still slower.** `ib/n` is only 0.219, but the phases run one after another, so NVLink's 147.4 ms and IB's 59.0 ms add up to 206.5 ms: the two link classes never work at the same time.
- **Halve-double is hierarchical by construction.** Its first three rounds have partners at distance 1, 2 and 4, all inside the node, and only then does it cross nodes. The data flow is that of the 2D ring (same `nv/n` and `ib/n`, 206.4 ms) in 12 rounds instead of 28; at 512 ranks it is 18 rounds against 140.
- **The bandwidth term does not grow with the GPU count, the latency term does.** From 64 to 512 ranks the flat ring goes only from 531.2 ms to 543.1 ms, while its rounds grow from 126 to 1022. For a 13.5 GB message that latency is irrelevant; for small messages it is a disaster.

Topology awareness comes down to two rules: put as few bytes as possible on the slow link (IB traffic falls from 1.969 to 0.219 and 0.246), and keep both link classes busy at the same time (8 rings do, the sequential 2D ring does not). Note that the model assumes every GPU has its own NIC; with a single NIC per node the advantage of 8 rings disappears, so on a real cluster measure with nccl-tests on the target machines instead of trusting the model.

## Floating-point addition is not associative: the order is the result

The **mathematical** result of an all-reduce does not depend on the algorithm; the **numerical** result does: floating-point addition is commutative but not associative, and $(a+b)+c$ and $a+(b+c)$ can differ in the last bits. The five algorithms above add the same numbers in different orders (as the nccl-tests documentation puts it, a ring adds in ring order and a tree adds hierarchically).

```python
def rel_rms(y, ref):
    return float(np.sqrt(np.mean((y - ref) ** 2) / np.mean(ref**2)))

p, n = 8, 4096
x = rng.standard_normal((p, n)).astype(np.float32)  # FP32 grads per rank
ref, res = x.astype(np.float64).sum(0), {}
for name, f in ALGOS.items():
    outs = f(Net(p), x)
    same = all(np.array_equal(outs[0], o) for o in outs)
    res[name] = outs[0]
    err = rel_rms(outs[0].astype(np.float64), ref)
    print(f"{name:<13} ranks bit-identical: {same!s:<5} rel. error {err:.2e}")
print("share of elements that differ bitwise between two algorithms:")
print(f"{'':<13}" + "".join(f"{b:>13}" for b in res))
for a in res:
    print(f"{a:<13}" + "".join(f"{np.mean(res[a] != res[b]):>13.1%}"
                               for b in res))
bad = [np.zeros(n, np.float32) for _ in range(p)]
for r in range(p):  # anti-pattern: every rank starts from its own data
    for k in range(p):
        bad[r] = bad[r] + x[(r + k) % p]
print(f"each rank sums from itself: rank 0 and rank 1 differ on "
      f"{np.mean(bad[0] != bad[1]):.1%} of elements")
```

```text
star          ranks bit-identical: True  rel. error 5.69e-08
tree          ranks bit-identical: True  rel. error 4.80e-08
rec-double    ranks bit-identical: True  rel. error 4.80e-08
ring          ranks bit-identical: True  rel. error 5.54e-08
halve-double  ranks bit-identical: True  rel. error 4.80e-08
share of elements that differ bitwise between two algorithms:
                      star         tree   rec-double         ring halve-double
star                  0.0%        57.5%        57.5%        51.5%        57.5%
tree                 57.5%         0.0%         0.0%        56.1%         0.0%
rec-double           57.5%         0.0%         0.0%        56.1%         0.0%
ring                 51.5%        56.1%        56.1%         0.0%        56.1%
halve-double         57.5%         0.0%         0.0%        56.1%         0.0%
each rank sums from itself: rank 0 and rank 1 differ on 55.9% of elements
```

Four observations:

1. **Within one algorithm, all ranks get bit-identical results** (`ranks bit-identical: True` on every row). This is mandatory: the replicas of data parallelism must update with the same gradient, and a single differing bit makes them drift apart slowly.
2. **Between algorithms, the results differ bitwise.** The percentages in the matrix are the share of elements that differ bitwise between two algorithms (FP32, 8 ranks, 4096 elements): between star, tree and ring, 51.5% to 57.5% of the elements differ. Tree, recursive doubling and halving-doubling are at 0.0% against each other, because for a power-of-two $p$ they add along the same balanced binary tree ($x_0+x_1$, $x_2+x_3$, ... then pairs of those).
3. **But the errors are the same size.** The relative error against a float64 reference is about $5\times10^{-8}$ for all of them (4.80e-08 to 5.69e-08), the size of an FP32 rounding. The difference is not who is more accurate but **reproducibility**: change the GPU count, the algorithm or the topology and the low bits of the gradient change, so the loss curve cannot be reproduced bit for bit.
4. **A counter-example.** The last line makes every rank start summing from its own data (rank $r$ adds $x_r$, then $x_{r+1}$, ...), and the results of rank 0 and rank 1 differ in 55.9% of the elements. What a collective library has to guarantee is not "the best summation order" but "everyone gets the same answer".

> [!NOTE] Reproducing a multi-GPU run bit for bit
> The reduction order is set jointly by the GPU count, the parallel configuration and the communication algorithm. To reproduce a run bit for bit, fix all three (and the gradient bucket size), and compare only against runs with the same configuration. Low-bit differences after a configuration change are not a bug in the communication library; they are a property of floating-point numbers.

If gradients are communicated and reduced in BF16, every addition rounds, and the effect of the order is amplified. Below, the same BF16 gradients are summed three ways, and the error is the relative root-mean-square error against the exact float64 sum:

```python
import torch

torch.set_num_threads(1)

def bf16_errors(p, n=20000):
    g = torch.Generator().manual_seed(0)
    x = torch.randn(p, n, generator=g).bfloat16().float()  # BF16 gradients
    exact = x.double().sum(0)

    def rel(y):
        return float(((y.double() - exact) ** 2).mean().sqrt()
                     / (exact**2).mean().sqrt())

    fp32 = x.sum(0).bfloat16().float()  # FP32 sum, round once
    acc = x[0].clone()
    for k in range(1, p):  # ring: round to BF16 at every hop
        acc = (acc + x[k]).bfloat16().float()
    lvl = x
    while len(lvl) > 1:  # tree: round once per level
        lvl = (lvl[0::2] + lvl[1::2]).bfloat16().float()
    return rel(fp32), rel(acc), rel(lvl[0])

print(f"{'p':>4} {'FP32':>8} {'BF16 ring':>10} {'BF16 tree':>10} "
      f"{'ring/FP32':>10}")
rows = [(p, *bf16_errors(p)) for p in (8, 64, 512)]
for p, a, b, c in rows:
    print(f"{p:>4} {a:>8.4f} {b:>10.4f} {c:>10.4f} {b / a:>10.1f}")
for i, name in ((2, "ring"), (3, "tree")):
    g = [rows[k + 1][i] / rows[k][i] for k in range(2)]
    print(f"each 8x in p multiplies the BF16 {name} error by "
          f"{g[0]:.1f} and {g[1]:.1f}")
```

```text
   p     FP32  BF16 ring  BF16 tree  ring/FP32
   8   0.0017     0.0037     0.0031        2.2
  64   0.0016     0.0096     0.0044        5.8
 512   0.0017     0.0265     0.0054       15.9
each 8x in p multiplies the BF16 ring error by 2.6 and 2.8
each 8x in p multiplies the BF16 tree error by 1.4 and 1.2
```

- **FP32 accumulation, rounded once at the end**: error 0.0017, independent of $p$; this is BF16's own rounding error.
- **Ring: round to BF16 at every hop.** The chain rounds $p-1$ times and the error grows from 0.0037 at $p=8$ to 0.0265 at $p=512$, 15.9 times the FP32 accumulation; each time $p$ is multiplied by 8 the error is multiplied by 2.6 and 2.8, close to $\sqrt{8}$, that is, the error grows with the square root of the number of roundings.
- **Tree: round once per level.** Only $\lg p$ roundings: the error goes from 0.0031 to 0.0054, multiplied by only 1.4 and 1.2 for each factor of 8 in $p$.

The conclusion agrees with the accumulator conclusion in [Numerical Precision](https://dmxsf.com/en/wiki/systems/numerical-precision/): a low-precision reduction should either use short chains (trees) or accumulate in higher precision. Llama 3 uses FP32 for the cross-GPU reduce-scatter in FSDP ([walkthrough](https://dmxsf.com/en/blog/the-llama-3-herd-of-models/)), for exactly this reason.

## MoE all-to-all and node-limited routing

Expert parallelism puts different experts on different GPUs, and every MoE layer does two all-to-alls: after routing, the activations of the tokens are sent to the GPUs that hold their experts (dispatch), and after the experts have run, the results are sent back (combine). The difference from all-reduce is that nothing can be summed, so there is no "every rank sends only $2S$": where each token goes is decided by the routing, the total traffic is the sum of the activation bytes of all (token, expert) pairs, and the cross-node part goes over IB. On a 2D TPU network GShard measured that the time of an all-reduce is essentially independent of the number of devices while an all-to-all grows roughly as $\sqrt{D}$ ($D$ is the device count), so all-to-all is harder to scale.

In DeepSeek-V3's cluster NVLink is 160 GB/s and IB is 50 GB/s. The paper's answer is **node-limited routing**: each token is sent to at most $M=4$ nodes, chosen by the sum of the highest $K_r/M$ affinity scores of the experts on each node ($K_r=8$ is the number of experts a token selects); the token first goes over IB to the GPU with the same in-node index on each target node (one copy per target node), and inside the node NVLink forwards it to the specific experts. The paper also does a small calculation: a token can select about 3.2 experts per target node without adding NVLink overhead, so 4 nodes could hold up to about 13 experts (4 × 3.2) at the same communication cost, while only 8 are selected in practice.

Below, a simulation shows how the node limit cuts the number of copies sent over IB. The setup follows DeepSeek-V3's training configuration: 256 routed experts, 8 selected per token, experts spread evenly over 8 nodes (32 per node), and each token sits on a random one of the 8 nodes. The affinities are i.i.d. uniform random numbers, to show the mechanism only: real router affinities are far from uniform, and training runs with the node limit in place, so the `swapped` and `kept` columns must not be read as an estimate of quality loss.

```python
from math import comb

E, TOPK, G = 256, 8, 8  # routed experts, experts per token, nodes
PER, T = E // G, 200_000  # 32 experts per node; simulated tokens
gen = np.random.default_rng(0)
score = gen.random((T, E))  # affinities: i.i.d. uniform, a mechanism demo only
origin = gen.integers(G, size=T)[:, None]  # the node each token starts on
rows = np.arange(T)[:, None]

def pick(score, topk):
    return np.argpartition(-score, topk - 1, axis=1)[:, :topk]

def route(score, m):
    """Node-limited routing: keep the m nodes with the largest sum of
    their top TOPK/m affinities."""
    best = np.sort(score.reshape(T, G, PER), axis=2)[:, :, -(TOPK // m):]
    keep = np.zeros((T, G), dtype=bool)
    keep[rows, pick(best.sum(2), m)] = True
    return pick(np.where(np.repeat(keep, PER, axis=1), score, -1.0), TOPK)

base = pick(score, TOPK)  # top-8 with no node limit
chosen = np.zeros((T, E), dtype=bool)
chosen[rows, base] = True
mass = np.take_along_axis(score, base, 1).sum(1).mean()
print(f"per-expert sends, no dedup: each token sends "
      f"{(base // PER != origin).sum(1).mean():.2f} copies over IB")
print(f"{'M':>2} {'nodes':>6} {'IB copies':>10} {'experts/node':>13} "
      f"{'swapped':>8} {'kept':>7}")
for m in (8, 4, 2, 1):
    sel = route(score, m)
    node = np.sort(sel // PER, axis=1)
    distinct = 1 + (np.diff(node, axis=1) != 0).sum(1)
    ib = distinct - (node == origin).any(1)  # 1 copy per other node
    kept = np.take_along_axis(score, sel, 1).sum(1).mean() / mass
    swapped = TOPK - chosen[rows, sel].sum(1).mean()
    print(f"{m:>2} {distinct.mean():>6.2f} {ib.mean():>10.2f} "
          f"{TOPK / distinct.mean():>13.2f} {swapped:>8.2f} {kept:>7.1%}")
exp = G * (1 - comb(E - PER, TOPK) / comb(E, TOPK))
print(f"expected nodes per token at M=8, from theory: {exp:.2f}")
```

```text
per-expert sends, no dedup: each token sends 7.00 copies over IB
 M  nodes  IB copies  experts/node  swapped    kept
 8   5.29       4.63          1.51     0.00  100.0%
 4   3.95       3.46          2.02     1.46   99.7%
 2   2.00       1.75          4.00     4.02   98.1%
 1   1.00       0.88          8.00     6.00   94.0%
expected nodes per token at M=8, from theory: 5.29
```

- **Per-expert sends, no deduplication.** On average $8\times7/8=7$ of the 8 selected experts are on other nodes, so each token sends 7.00 copies over IB.
- **Deduplicate by node.** One copy per target node: with $M=8$ (no limit) a token reaches 5.29 nodes on average, matching the theoretical expectation $8\bigl(1-\binom{224}{8}/\binom{256}{8}\bigr)$ of 5.29 (which validates the simulator), and sends 4.63 copies over IB (nothing to send for its own node).
- **Limit the number of nodes.** With $M=4$ a token reaches 3.95 nodes on average and sends 3.46 copies over IB; $M=2$ gives 1.75; $M=1$ gives 0.88, that is $7/8$: a copy is needed only when the token is not on the chosen node.
- **The price is a changed routing.** `swapped` is the average number of the 8 experts that are replaced: 1.46 at $M=4$, 6.00 at $M=1$. The paper's reason for the limit is less IB traffic, so that IB and NVLink communication overlap completely, together with DualPipe hiding the all-to-all behind computation.

## In practice: reading the numbers

| Symptom | Likely cause | What to check first |
| --- | --- | --- |
| all-reduce of a small tensor is slow, busbw far below the link bandwidth | latency-bound: time is about rounds times alpha | merge into larger messages (gradient bucketing), do fewer communications; make sure small messages are not handled by an algorithm meant for large ones |
| busbw of a large tensor does not reach the link bandwidth | a single ring is stuck on a slow link, or not all NICs are used | measure busbw on the target machines with nccl-tests; check the topology and the number of NICs |
| cross-node busbw far below intra-node | IB is the bottleneck | reduce cross-node traffic: keep tensor parallelism inside the node, hierarchical communication, node-limited routing |
| loss disagrees in the low bits after changing the parallel configuration | the reduction order changed | fix the parallel configuration and the communication algorithm before comparing; this is not a bug |

PyTorch's DDP organizes gradients into buckets (25 MiB by default, parameter `bucket_cap_mb`) and starts the all-reduce of a bucket as soon as its gradients are ready, overlapping with the backward computation of the layers still to come. Buckets cannot be too small: in this page's model $\alpha B$ is 5 µs × 50 GB/s = 250 KB, a message has to be much larger than that to amortize the start-up latency, and 25 MiB is about 100 times it.

## Common misconceptions

1. **"A ring all-reduce's traffic grows linearly with the GPU count."** Each rank sends about $2S$, almost independent of $p$: 1.969 at 64 ranks and 1.996 at 512 (the flat ring in the `topo` output, `ib/n` column). What grows linearly with the GPU count is the number of **rounds**, that is, the latency.
2. **"A tree has latency $\lg p$, so trees beat rings."** The bottleneck rank of a single binary tree moves $2\lg p$ times the data: 3234.300 ms on 13.5 GB against 531.247 ms for the ring. Trees only win on small messages; NCCL's double binary tree is what achieves full bandwidth and logarithmic latency together.
3. **"Double the bandwidth and all-reduce takes half the time."** True only in the bandwidth-bound regime; small messages are latency-bound and barely notice.
4. **"The result of an all-reduce does not depend on the algorithm."** Mathematically it does not, bitwise it does: different reduction orders make 51.5% to 57.5% of the elements differ bitwise.
5. **"Use algbw to judge the hardware."** algbw falls with the GPU count (91.4 GB/s on 8 ranks, 25.4 GB/s on 64); to compare with the link, use busbw (159.9 and 49.9 GB/s).
6. **"MoE communication is just total bytes."** Inside and outside a node differ by 3.2 times in bandwidth, so book the links separately: 7.00 copies per-expert, 4.63 deduplicated by node, 3.46 limited to 4 nodes.

## Summary and exercises

- Among the six primitives, all-reduce equals reduce-scatter plus all-gather (and also reduce plus broadcast); in the ring implementation each rank sends about $2S$, almost independent of the GPU count.
- The time is $T=R\alpha+cS/B$: ring has $(R,c)$ of $(2(p-1),\,2(p-1)/p)$, halving-doubling $(2\lg p,\,2(p-1)/p)$, recursive doubling $(\lg p,\,\lg p)$ and binary tree $(2\lg p,\,2\lg p)$. Small messages compare rounds, large messages compare traffic; at 64 ranks and 50 GB/s the crossover is 363 KiB.
- Inside and outside a node are two kinds of link: on 64 ranks the flat ring takes 531.2 ms, 8 staggered rings 145.7 ms, and the 2D ring and halving-doubling about 206 ms; put the fewest bytes on the slow link and keep both kinds of link busy.
- Floating-point addition is not associative: different reduction orders make 51.5% to 57.5% of the elements differ bitwise at the same error level; BF16 chain reduction error grows with $p$ (15.9 times the FP32 accumulation at $p=512$), a tree grows only slowly.
- MoE all-to-all is limited by inter-node bandwidth; node-limited routing cuts the copies each token sends over IB from 4.63 to 3.46 ($M=4$).

### Quick self-test

**1. Which combinations are equivalent to one all-reduce?**

- [x] reduce, then broadcast
- [x] reduce-scatter, then all-gather
- [ ] all-gather, then reduce-scatter
- [ ] all-to-all, then broadcast

> The NCCL documentation gives the first two equivalences. After an all-gather every rank holds the full vector, and a reduce-scatter on top sums $p$ identical vectors, so every rank gets $p$ times its own original block, which has nothing to do with the sum over ranks.

**2. A ring all-reduce on 64 ranks: how many rounds, and how much traffic (in units of $S$) for the bottleneck rank?**

- [ ] 6 rounds, 6
- [ ] 12 rounds, 1.969
- [x] 126 rounds, 1.969
- [ ] 2 rounds, 126

> Reduce-scatter and all-gather take $p-1=63$ steps each, 126 rounds in all, each step sends $S/p$, for a total of $2\times63/64=1.969$. 12 rounds with 1.969 is halving-doubling, 6 rounds with 6 is recursive doubling, 2 rounds with 126 is the star (the $p=64$ part of the `check` output).

**3. At 64 ranks, 50 GB/s and $\alpha=5$ µs, which all-reduce is fastest for 16 KiB, and why is the ring slowest?**

- [x] Recursive doubling is fastest (0.032 ms); the ring needs 126 rounds, the start-up latency alone is 0.63 ms, 0.631 ms in total
- [ ] The ring is fastest because its traffic is the smallest
- [ ] The binary tree is fastest because its number of rounds is $\lg p$
- [ ] All four are equally fast because 16 KiB is tiny

> For small messages the time is about $R\alpha$: recursive doubling has 6 rounds, the binary tree and halving-doubling 12 each (0.064 and 0.061 ms), the ring 126. Traffic hardly matters at 16 KiB.

**4. 8 nodes with 8 GPUs each, all-reduce of a 13.5 GB gradient: which approach is fastest?**

- [ ] One big ring over 64 ranks (531.2 ms)
- [x] 8 concurrent rings, each entering and leaving the node through a different GPU (145.7 ms)
- [ ] The 2D ring (206.5 ms)
- [ ] Recursive halving-doubling (206.4 ms)

> In the big ring the bottleneck of every round is IB (`ib ms` 530.6). 8 rings let the 8 GPUs use their own IB links at the same time, the IB traffic falls to about 1/8 (`ib/n` 0.246), the bottleneck moves to NVLink (145.1 ms) and both link classes work at once. The 2D ring and halving-doubling have even less IB traffic (0.219), but their phases run one after another, so NVLink's 147.4 ms and IB's 59.0 ms add up. The conclusion depends on the assumption that every GPU has its own 50 GB/s link.

**5. On 8 ranks of FP32 data, star, tree and ring all-reduce differ bitwise in 51.5% to 57.5% of the elements, yet all have a relative error of about $5\times10^{-8}$. How should this be understood?**

- [ ] Two of the algorithms are wrong
- [x] Floating-point addition is not associative, the three algorithms add in different orders and differ only in the last bits; the errors are the same size, none is more accurate
- [ ] The network dropped some bits
- [ ] The input data of the ranks differ

> Within each algorithm all ranks still get bit-identical results (`ranks bit-identical: True`), so the replicas do not drift. Tree, recursive doubling and halving-doubling are at 0.0% against each other because they add along the same balanced binary tree.

**6. Why does DeepSeek-V3 limit each token to at most 4 nodes?**

- [ ] To reduce the number of experts
- [x] Inter-node IB has only about $1/3.2$ of the intra-node NVLink bandwidth, and limiting the nodes reduces the copies sent over IB; in this page's simulation, deduplicating by node with no limit makes each token send 4.63 copies over IB, and limiting to 4 nodes brings it to 3.46
- [ ] Because NCCL supports at most 4 nodes
- [ ] To turn all-to-all into an exact sum

> The paper's numbers: NVLink 160 GB/s, IB 50 GB/s. With the limit, IB and NVLink communication can overlap completely, and a token can select about 3.2 experts per target node without adding NVLink overhead.

**Exercises:**

1. (Derivation) Show that in a ring all-reduce each rank sends $2\frac{p-1}{p}S$, and explain why nccl-tests multiplies algbw by $2(p-1)/p$ to get busbw. Then check with the ring time of 531.247 ms for $p=64$ and 13.5 GB in the `times` output: does busbw approach 50 GB/s?
2. (Calculation) Use $S^{*}=\frac{(R_b-R_a)\,\alpha B}{c_a-c_b}$ to compute the crossover of recursive doubling and halving-doubling for $p=8$, $B=160$ GB/s and $\alpha=5$ µs, and compare it with the 1875 KiB in the output.
3. (Estimate) DeepSeek-V3 has a hidden size of 7168. Estimate in BF16 how many bytes a token sends over IB in the dispatch step with per-expert sends (7.00 copies), with deduplication by node and no limit (4.63 copies), and with $M=4$ (3.46 copies).

<details>
<summary>Reference answers</summary>

1. Reduce-scatter takes $p-1$ steps, each rank sending one block of $S/p$ per step, $\frac{p-1}{p}S$ in all; the all-gather is the same, so $2\frac{p-1}{p}S$ in total. The ideal time is $t=\frac{2(p-1)S}{pB}$, hence $B=\frac{S}{t}\cdot\frac{2(p-1)}{p}=\text{algbw}\times\frac{2(p-1)}{p}$: multiplying by this factor converts "data size over time" into the bandwidth the links actually carried, which can be compared with the hardware peak and does not change with $p$. Check: algbw $=13.476\,\text{GB}/0.531247\,\text{s}$ is the 25.4 GB/s in the output, times $2\times63/64$ gives the 49.9 GB/s in the output, close to 50 GB/s; what is missing is the start-up latency of the 126 rounds.
2. $\Delta R=6-3=3$ and $\Delta c=3-1.75=1.25$ (recursive doubling has $c=\lg 8=3$, halving-doubling $c=2\times7/8=1.75$). $S^{*}=3\times5\,\mu\text{s}\times160\,\text{GB/s}/1.25=1.92\times10^{6}$ bytes, and dividing by 1024 gives exactly 1875 KiB.
3. One activation is $7168\times2=14336$ bytes. Per-expert sends: $7.00\times14336$ is about 100 KB; deduplicated by node with no limit: $4.63\times14336$ is about 66 KB; $M=4$: $3.46\times14336$ is about 50 KB, about a quarter less than with no limit. A real system may transmit activations in lower precision; this only compares the effect of the number of copies.

</details>

## Further reading

- NVIDIA, [NCCL User Guide: Collective Operations](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/collectives.html): the definition of each primitive and the statement that reduce plus broadcast and reduce-scatter plus all-gather are equivalent to all-reduce; `NCCL_ALGO` is in the [environment variables](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/env.html) documentation.
- NVIDIA, [nccl-tests: Performance](https://github.com/NVIDIA/nccl-tests/blob/master/doc/PERFORMANCE.md): the definitions of algbw and busbw and the conversion factor of each primitive.
- Thakur, Rabenseifner and Gropp, [Optimization of Collective Communication Operations in MPICH](https://www.mcs.anl.gov/~thakur/papers/ijhpca-coll.pdf) (2005): the alpha-beta cost and the range of use of recursive doubling, recursive halving-doubling, rings and other algorithms, including the handling of $p$ that is not a power of two.
- Jeaugey, [Massively Scale Your Deep Learning Training with NCCL 2.4](https://developer.nvidia.com/blog/massively-scale-deep-learning-training-nccl-2-4/) (NVIDIA Technical Blog, 2019): double binary trees and the hierarchical (2D) ring.
- Sergeev and Del Balso, [Horovod: fast and easy distributed deep learning in TensorFlow](https://arxiv.org/abs/1802.05799) (2018): an early use of ring all-reduce in deep learning training.
- DeepSeek-AI, [DeepSeek-V3 Technical Report](https://arxiv.org/abs/2412.19437) (2024): node-limited routing and the cross-node all-to-all kernels; [walkthrough](https://dmxsf.com/en/blog/deepseek-v3-technical-report/).
- Lepikhin et al., [GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding](https://arxiv.org/abs/2006.16668) (2020): scalability of all-reduce versus all-to-all on TPUs.
- PyTorch, [DistributedDataParallel](https://docs.pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html): gradient bucketing and overlap with the backward computation.

## Companion code

[Collective communication: simulate a ring all-reduce](https://github.com/dmxsf/dmxsf/tree/main/labs/systems/collective-communication): Track each chunk through reduce-scatter and all-gather, then compare the observed per-rank bytes with the alpha-beta model.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run systems/collective-communication`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/systems/collective-communication/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/systems/collective-communication/README.en.md)
- [`collectives.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/systems/collectives.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#collective-communication)

## FAQ

### What is all-reduce, and how does it relate to reduce-scatter and all-gather?

All-reduce gives every GPU the element-wise sum of the same vector held by all GPUs; data-parallel training uses it to add up gradients. It is equivalent to a reduce-scatter followed by an all-gather: first the sum is split into blocks and each GPU keeps only its own block, then every GPU collects all the blocks. The NCCL documentation also lists reduce followed by broadcast as an equivalent form. In the ring implementation each step makes every GPU send (p-1)/p of the vector, so the two together are about 2 vectors, almost independent of the GPU count p. ZeRO and FSDP simply pull the two steps apart and insert 'update only my share of the parameters' in between.

### How do ring, tree and recursive-doubling all-reduce differ, and when should each be used?

They trade rounds (latency) against traffic (bandwidth). The simulator on this page measures, on 64 GPUs: ring 126 rounds and 1.969 vectors of traffic per GPU; recursive halving-doubling 12 rounds and the same 1.969; recursive doubling 6 rounds but 6 vectors; binary tree 12 rounds and 12 vectors. For small messages the rounds decide and recursive doubling is fastest; for large messages the traffic decides and ring and halving-doubling win, while on a 13.5 GB gradient recursive doubling is about 3 times slower and the binary tree about 6 times. With the illustrative parameters (alpha 5 µs, 50 GB/s) recursive doubling and halving-doubling cross at 363 KiB. NCCL picks the algorithm automatically from message size and node topology; NCCL_ALGO is only for troubleshooting.

### What is the difference between algbw and busbw in NCCL tests, and how do I tell whether communication runs at full speed?

algbw is data size divided by time; busbw is algbw times a factor that depends on the primitive (2(n-1)/n for all-reduce, (n-1)/n for all-gather, reduce-scatter and all-to-all, 1 for broadcast and reduce), so that it can be compared directly with the peak link bandwidth and does not change with the GPU count (nccl-tests documentation). In this page's model, a ring all-reduce of a 13.5 GB gradient has an algbw of 91.4 GB/s on 8 GPUs but only 25.4 GB/s on 64, so algorithm bandwidth falls with the GPU count; the busbw is 159.9 and 49.9 GB/s, both close to the link bandwidth (160 and 50 GB/s). If a measured busbw is far below the link bandwidth, check whether the message is too small and whether the topology and the number of NICs are sensible.

### Why can't multi-GPU training runs be reproduced bit for bit across different GPU counts?

Floating-point addition is not associative: (a+b)+c and a+(b+c) can differ in the last bits, so the order of the reduction decides the low bits of the result. On 8 ranks of FP32 data this page measures that star, binary-tree and ring orders give results that differ bitwise in 51.5% to 57.5% of the elements, while the relative error of all three is about 5e-8: none is more accurate, the order is just different (binary tree, recursive doubling and halving-doubling add along the same binary tree and are bit-identical to each other). A different GPU count, algorithm or network topology changes the order, so reproducing a run bit for bit requires fixing the parallel configuration and the communication algorithm. Within one all-reduce all ranks receive bit-identical results, which is what keeps the replicas from drifting apart.

### Why is MoE all-to-all expensive, and what is DeepSeek-V3's node-limited routing?

Expert parallelism sends tokens to the GPUs that hold their experts (dispatch) and sends the results back (combine); both are all-to-all. There is nothing to sum, the traffic is set by the routing, and the cross-node part goes over IB. In DeepSeek-V3's cluster NVLink is 160 GB/s and IB is 50 GB/s, so each token is sent to at most 4 nodes, one copy per target node, and inside the node NVLink forwards it to the experts. In this page's simulation (256 experts, top 8, 8 nodes, uniformly random affinities) each token sends 7.00 copies over IB when every expert gets its own copy, 4.63 after deduplicating by node, and 3.46 when limited to 4 nodes.
