Module contents
Lesson 8 of 28Core 110 min

Communication between GPUs: collectives, NCCL and the alpha-beta model

Parallel strategies depend on which collectives run, how many bytes they move, and over which links. We define collective primitives and their identities, build the alpha-beta cost model, and prove ring all-reduce bandwidth optimality against tree algorithms that win for small messages. We review hardware (PCIe, NVLink, InfiniBand) and the NCCL and torch.distributed stack, and practice with CPU Gloo processes because NCCL requires a separate GPU per rank.

After this lesson you can

  • Define each collective primitive and use identities such as all-reduce = reduce-scatter + all-gather.
  • Derive alpha-beta cost for ring all-reduce and prove its bandwidth optimality.
  • Choose between ring, tree and recursive doubling by message size and rank count.
  • Implement ring all-reduce using point-to-point send and receive in torch.distributed and fit α and β to real measurements.
  • Interpret algbw and busbw in nccl-tests results.

Before you start

Data crossing boundaries

On a shared-memory computer, threads can read the same address. With multiple devices, each rank has its own memory and must explicitly communicate needed data. A model can use hundreds of gigabytes of traffic per step when summing gradients, gathering parameters, and redistributing activations; the amount depends on the model and its parallelism. Without counting bytes and latency it is impossible to interpret efficiency loss when scaling.

A collective defines the result each rank receives, not one unique algorithm to obtain it. Let xrx_r be rank rr‘s vector: broadcast copies a root input to all; reduce combines all inputs at one root; all-reduce delivers that reduction to all. all-gather concatenates one fragment from each rank on every rank. reduce-scatter reduces full vectors and distributes a distinct result fragment to each rank. all-to-all exchanges distinct fragments among every pair. Dimensions and rank order are part of the contract.

The identity all-reduce = reduce-scatter + all-gather describes results when both operations use the same reduction, partition, and order. In differentiation, the adjoint of all-gather is reduce-scatter with sum: contributions to a fragment from all copies are summed for its owner. Conversely, the adjoint of sum reduce-scatter is all-gather. This duality assumes every copy contributes to the loss and does not replace gradient scaling analysis.

InteractiveA ring, fragment by fragment
R.T0T1T2T3
0
0
0
0
0
1
1
1
1
1
2
2
2
2
2
3
3
3
3
3

R. means rank, T means chunk, and D is the source in all-to-all. The ring reads the previous state each round. Reduce and broadcast use a star centered on rank 0. All-to-all leaves the values unchanged. A dot marks a fragment that has yet to arrive.

4
Collective
Round 0
PhaseInitial
Rounds0 / 6
Each cell lists the contributions it contains. In the first p-1 rounds one fragment per rank is reduced; in the next rounds all are gathered.

The cost model and the ring

The alpha-beta model approximates an nn-byte message as α+n/β\alpha+n/\beta seconds: α\alpha is latency per message and β\beta is bandwidth in bytes per second. It assumes a dedicated link, uniform transmission, and no contention. Reduction compute, topology, queues, and launch may matter; the model is a measurable hypothesis, not a guarantee.

In ring all-reduce, divide each nn-byte vector into pp equal fragments. Each round sends a fragment to the next neighbor and receives from the previous one. In reduce-scatter, the receiver adds the received fragment to its own; after p−1p-1 rounds it holds one complete sum. In all-gather it forwards that sum without adding it again for another p−1p-1 rounds. If send and receive overlap and each step costs α+n/(pβ)\alpha+n/(p\beta),

Tring=2(p−1)(α+npβ),Vrank=2(p−1)pn.T_{\rm ring}=2(p-1)\left(\alpha+\frac{n}{p\beta}\right),\qquad V_{\rm rank}=\frac{2(p-1)}{p}n.

For an example, number ranks 0 through 3 and have each send to the next modulo 4. Rank 0 successively receives fragments 3, 2, and 1 from rank 3. On each receive it adds its contribution; at the end it has complete fragment 1. During gathering it receives already reduced fragments 0, 3, and 2 and copies them. Crucially, every send in a round is prepared from the state before that round; updating all ranks sequentially using newly written values would simulate different communication.

For example, for p=8p=8, n=2⋅109n=2\cdot10^9 bytes, α=10 μs\alpha=10\,\mu s, and β=100⋅109\beta=100\cdot10^9 bytes/s, the model predicts 14(10−5+0.0025)=0.0351414(10^{-5}+0.0025)=0.03514 s. Size is decimal; 2 GiB would produce another result. The formula assumes the vector is evenly divided and each link’s bandwidth allows the assumed directions.

The traffic bound requires care. In the point-to-point sums and copies model, each element needs at least p−1p-1 transfers to collect its pp contributions and p−1p-1 to distribute the result. That is at least 2(p−1)n2(p-1)n aggregate bytes if each element has the same size and data are neither compressed nor encoded. The average sent per rank is at least 2(p−1)n/p2(p-1)n/p; therefore at least one rank sends that much or more. The ring matches it on every rank, balancing traffic, and reaches that bandwidth bound under the model’s assumptions. The claim that every rank of any algorithm must send that much is false: in star reduction and broadcast, a leaf sends only nn bytes and receives the result, while the root bears much more traffic. The nccl-tests documentation derives the same factor from aggregate transfers.

Small messages and hierarchy

A binary tree reduces toward the root and broadcasts toward leaves. With depth log⁡2p\log_2 p, a power-of-two rank count, and a full vector per message, the simple model is 2log⁡2p(α+n/β)2\log_2 p(\alpha+n/\beta). Recursive doubling exchanges and reduces the full vector with the partner differing in one bit for log⁡2p\log_2p rounds; it costs log⁡2p(α+n/β)\log_2p(\alpha+n/\beta). Recursive reduce-scatter followed by recursive all-gather reduces volume for large messages. Their power-of-two restrictions and detailed cost require handling leftover ranks when pp is not a power of two. A segmented double-tree implementation differs from this simple tree and can overlap work; see Thakur, Rabenseifner and Gropp.

In NCCL complementary double trees, a rank acting as an internal node in one tree is a leaf in the other and each tree processes part of the data. The figure uses the optimistic approximation 2log⁡2(p)α+2(p−1)n/(pβ)2\log_2(p)\alpha+2(p-1)n/(p\beta): it combines logarithmic depth with minimum balanced traffic. This is an illustrative model, not an exact NCCL formula or a guarantee that both terms overlap this way on a particular network.

In recursive halving, each pair exchanges and reduces half the vector it retains; in the next round it exchanges half of what remains. For p=8p=8 the sizes sent per rank are n/2,n/4,n/8n/2,n/4,n/8. The geometric sum is 7n/87n/8: each rank retains one reduced eighth. Recursive all-gather reverses the sequence and sends another n/8+n/4+n/2n/8+n/4+n/2. If exchanges occur separately on ideal links, cost is 2log⁡2(p)α+2(p−1)n/(pβ)2\log_2(p)\alpha+2(p-1)n/(p\beta). This explains how logarithmic latency and balanced volume can coexist without proving a particular implementation or arbitrary topology simultaneously achieves those terms.

Recursive doubling instead sends the entire vector each round. For eight ranks it sends 3n3n per rank, versus the ring’s 7n/47n/4. Fewer rounds favor short messages; greater volume can hurt long ones. Partner order also determines which links are shared: a logical butterfly can map poorly onto a physical network if many pairs cross the same link. Therefore an NCCL selector may prefer another strategy or protocols even when the simple model suggests a winner.

InteractiveLatency or bandwidth
  • Ring
  • Ideal double tree
  • Recursive doubling
  • Single tree

The double tree uses an optimistic approximation: latency from two logarithmic traversals plus minimum balanced traffic. The single tree sends the full vector at each level. To overlay measurements, enter numeric pairs with sizes between 256 and 2²⁸ bytes. Use the parameters from your run. Segmentation, topology, and software can shift the crossover.

8
1.0
2.0
64
Latency / bandwidth10.0 µs / 100 GB/s
Ring1.314 ms
Ideal double tree1.234 ms
Recursive doubling2.043 ms
Compare ideal models for power-of-two rank counts. The log₂ and log₁₀ transformed axes show several orders of magnitude.

For small messages rounds dominate: the ring pays 2(p−1)α2(p-1)\alpha. For large messages volume per rank matters more and the ring can win. The crossover depends on the network and actual algorithm, not just nn. Floating-point addition is also nonassociative: changing reduction order can change the last bits even when both collectives are mathematically correct.

Links can be PCIe or NVLink within a node, NVSwitch to interconnect multiple GPUs, and networks such as InfiniBand or RoCE between nodes. GPUDirect RDMA allows, in compatible configurations, transfers between GPU memory and the network without an intermediate CPU copy; availability depends on platform and configuration. A hierarchical collective can reduce within each node, communicate between nodes, and broadcast locally, but performance depends on link assignment and whether phases overlap.

Topology contains more information than a single bandwidth number. Two GPUs may share a PCIe switch, have to cross the CPU, or have a direct link; multiple network cards may share a bottleneck. One-direction bandwidth, bidirectional aggregate, and nominal link speed are not interchangeable. A real test should record process placement, CPU affinity, device path, driver version, and concurrent jobs. A published NVLink value does not turn a PCIe machine into one with that link.

For hierarchical reduction one can choose a representative per node: first combine local vectors, then reduce and distribute among representatives, and finally broadcast within each node. This is easy to reason about, but the representative can become a bottleneck. Another organization distributes fragments among multiple GPUs or cards to use more links in parallel. Both have the same final semantics if partition and operation agree; they need not have the same time or numerical summation order.

InteractiveTwo connection levels
Node 1
GPU 0GPU 1GPU 2GPU 3
Node 2
GPU 0GPU 1GPU 2GPU 3
Node 3
GPU 0GPU 1GPU 2GPU 3
Node 4
GPU 0GPU 1GPU 2GPU 3

The flat model uses network bandwidth for every hop across multiple nodes, or local bandwidth for a single node. The hierarchical model adds a local reduction, a ring among representatives, and a local broadcast. Each local stage is approximated by half a ring pass. The model omits overlap and contention.

4
4
100
25
256
Flat ring20.43 ms
Simplified hierarchy20.25 ms
Slowest stageNetwork
Build a topology and compare two deliberately simple sequential models. No figure value is a physical measurement.

Simulate rounds and count traffic

Each matrix a[r,c] contains fragment cc held by rank rr. Rounds read a copy of the prior state, as if all sends occurred simultaneously. The counter is aggregate sent traffic, without also counting receives. The second function implements recursive doubling for powers of two.

[ ]Ring and recursive doubling in NumPyBrowser
import numpy as np
def ring(inputs):
    p,n=inputs.shape
    assert n%p==0
    a=np.stack([np.stack(np.split(row,p)) for row in inputs])
    sent=0
    for s in range(p-1):
        old=a.copy()
        for r in range(p):
            c=(r-s-1)%p
            a[r,c]+=old[(r-1)%p,c]
            sent+=old[(r-1)%p,c].nbytes
    reduced=a.copy()
    for s in range(p-1):
        old=a.copy()
        for r in range(p):
            c=(r-s)%p
            a[r,c]=old[(r-1)%p,c]
            sent+=old[(r-1)%p,c].nbytes
    return a.reshape(p,n),reduced,sent
def doubling(inputs):
    p,n=inputs.shape
    assert p>0 and p&(p-1)==0
    a=inputs.copy();sent=0;step=1
    while step<p:
        old=a.copy()
        for r in range(p): a[r]+=old[r^step];sent+=old[r].nbytes
        step*=2
    return a,sent
for p in (3,4,5,8):
    x=np.arange(p*p*3,dtype=np.float64).reshape(p,p*3)
    y,rs,traffic=ring(x)
    np.testing.assert_array_equal(y,np.broadcast_to(x.sum(axis=0),x.shape))
    for r in range(p):
        np.testing.assert_array_equal(rs[r,(r+1)%p],np.split(x.sum(axis=0),p)[(r+1)%p])
    assert traffic==2*(p-1)*x[0].nbytes
    print('p:',p,'rondas anillo:',2*(p-1),'bytes agregados:',traffic)
    if p&(p-1)==0:
        d,dt=doubling(x);np.testing.assert_array_equal(d,y)
        print('  doubling: rondas',int(np.log2(p)),'bytes',dt)

The ring works for three and five ranks, not just powers of two. In the preceding model fragments have equal length; a nondivisible vector requires padding or variable-sized partitions. The rs data let you check which fragment is complete before the second phase, not merely the final result.

NCCL, processes, and measurements

A process group assigns a unique rank and world size. torchrun can start processes, and torch.distributed offers collectives and point-to-point sends. All ranks must execute compatible collectives in the same order; a mismatch can deadlock them. An asynchronous call returns a work object: wait before consuming output or reusing its memory. CUDA stream dependencies must also be respected. See the PyTorch APIs and NCCL guide.

In data parallelism, each replica computes a local gradient and a global reduction lets all apply a consistent update. If batches have different numbers of valid tokens, weight sums by token count rather than blindly averaging local means. In tensor parallelism, a projection can produce partial outputs summed with all-reduce; when parameters are sharded, all-gather can temporarily reconstruct needed fragments. In an expert layer, all-to-all distributes tokens to destinations and a second redistribution returns results. These are common choices, not identities fixing every implementation.

Point-to-point operation order matters too. If everyone performs a blocking send and nobody posts a receive, the program can wait for resources or a neighbor. The lab posts nonblocking send and receive each round and waits for both before modifying or reusing buffers. A barrier before each sample approximately aligns the start but does not eliminate operating-system cost or guarantee all start in the same cycle. Measuring the maximum local rank time reflects the slowest participant; the median of repetitions reduces the influence of an isolated interruption.

A linear fit of time against bytes returns a slope and intercept. Only if the data behave like the ideal ring does interpreting them as 2(p−1)/(pβ)2(p-1)/(p\beta) and 2(p−1)α2(p-1)\alpha make sense. A negative intercept, nonpositive slope, or systematic residuals show that the model or size range does not describe the sample. The fitted rate includes library, copies, scheduling, and transport used in that run: CPU Gloo cannot be directly converted into NVLink or production-network bandwidth.

NCCL uses an exclusive GPU per process in this case; sharing it across ranks can cause invalid use or deadlock. This machine has one RTX 3060, so the next lab uses four CPU processes with Gloo. It checks semantics and measures local software and transport, not NCCL, NVLink, or four GPUs. A real NCCL test requires four distinct GPUs and an environment configured for them.

In nccl-tests, algbw=n/T measures original vector bytes per time. For all-reduce, busbw=algbw\,2(p-1)/p is a normalization based on minimum aggregate traffic, not a direct link-counter reading. With eight ranks and algbw=40 GB/s, busbw=70 GB/s. Comparing with a nominal 100 GB/s link gives 70%, provided topology and units are comparable. Warm-up, repetitions, synchronization, different sizes, and the maximum across ranks matter when measuring.

Local lab: four Gloo processes

The next program runs four real CPU processes on one computer. The FileStore rendezvous file avoids dependence on a TCP rendezvous server; each process uses loopback to communicate. The loopback interface uses the Windows or Linux default name here and can be replaced with GLOO_SOCKET_IFNAME before launching. It writes a temporary program because the Windows process-start method needs to import a real file with an if __name__ == '__main__' clause.

Each round posts send and receive, waits for both to finish, and only then modifies the received fragment. The test verifies the expected sum and the library collective, warms up, performs five repetitions per size, and fits a line. The code prints pairs you can paste into the figure. The fit is descriptive: inspect R² and residuals before interpreting α and β.

[ ]A real ring with four CPU processesLocal GPU
import os, sys, subprocess, tempfile
from pathlib import Path
source = r'''
"""All-reduce en anillo con cuatro procesos CPU y Gloo; ninguna GPU virtual."""
import os, sys, tempfile, time
from pathlib import Path
import numpy as np
import torch
import torch.distributed as dist
import torch.multiprocessing as mp

def ring_allreduce(x):
    rank=dist.get_rank();p=dist.get_world_size()
    if x.numel()%p: raise ValueError('longitud divisible por número de rangos')
    chunks=list(x.chunk(p)); prev=(rank-1)%p; nxt=(rank+1)%p
    for step in range(p-1):
        send=(rank-step)%p; recv=(rank-step-1)%p
        buf=torch.empty_like(chunks[recv])
        tx=dist.isend(chunks[send],dst=nxt);rx=dist.irecv(buf,src=prev)
        tx.wait();rx.wait();chunks[recv].add_(buf)
    for step in range(p-1):
        send=(rank+1-step)%p;recv=(rank-step)%p
        buf=torch.empty_like(chunks[recv])
        tx=dist.isend(chunks[send],dst=nxt);rx=dist.irecv(buf,src=prev)
        tx.wait();rx.wait();chunks[recv].copy_(buf)
    return x

def worker(rank,p,store_uri):
    os.environ.setdefault('GLOO_SOCKET_IFNAME','Loopback Pseudo-Interface 1' if sys.platform=='win32' else 'lo')
    torch.set_num_threads(1)
    dist.init_process_group('gloo',init_method=store_uri,rank=rank,world_size=p)
    try:
        sizes=[256,1024,4096,16384,65536,262144,1048576]
        times=[]
        for nbytes in sizes:
            n=nbytes//4;base=torch.arange(n,dtype=torch.float32)
            expected=p*base+p*(p-1)/2
            for _ in range(2):
                x=base+rank;ring_allreduce(x)
                assert torch.equal(x,expected)
            x=base+rank; dist.all_reduce(x)
            assert torch.equal(x,expected)
            samples=[]
            for _ in range(5):
                x=base+rank; dist.barrier()
                start=time.perf_counter();ring_allreduce(x); elapsed=time.perf_counter()-start
                worst=torch.tensor(elapsed,dtype=torch.float64);dist.all_reduce(worst,op=dist.ReduceOp.MAX)
                samples.append(worst.item())
                assert torch.equal(x,expected)
            med=float(np.median(samples));times.append(med)
            if rank==0: print('bytes',nbytes,'mediana del máximo por rango ms',med*1e3,flush=True)
        if rank==0:
            slope,intercept=np.polyfit(np.asarray(sizes,dtype=float),times,1)
            alpha=intercept/(2*(p-1));beta=2*(p-1)/(p*slope) if slope>0 else float('nan')
            print('ajuste descriptivo alpha segundos',alpha,'beta bytes/s',beta,flush=True)
            predicted=slope*np.asarray(sizes)+intercept
            residual=np.sum((np.asarray(times)-predicted)**2);total=np.sum((np.asarray(times)-np.mean(times))**2)
            print('R2 del ajuste lineal:',1-residual/total if total else float('nan'),flush=True)
            print('para pegar en el gráfico: bytes milisegundos',flush=True)
            for size,elapsed in zip(sizes,times): print(size,elapsed*1000,flush=True)
            if alpha<0 or slope<=0:print('ajuste no físico: no interpretar como parámetros de red',flush=True)
    finally:
        dist.destroy_process_group()

if __name__=='__main__':
    with tempfile.TemporaryDirectory(prefix='oryon-gloo-') as d:
        uri=(Path(d)/'rendezvous').as_uri()
        print('PyTorch',torch.__version__,'procesos CPU Gloo 4, FileStore',flush=True)
        mp.spawn(worker,args=(4,uri),nprocs=4,join=True)
'''
with tempfile.TemporaryDirectory(prefix='oryon-gloo-lab-') as directory:
    script=Path(directory)/'gloo_anillo.py'
    script.write_text(source,encoding='utf-8')
    env=os.environ.copy();env['PYTHONUTF8']='1'
    result=subprocess.run([sys.executable,str(script)],env=env,text=True,encoding='utf-8',capture_output=True)
    print(result.stdout,end='')
    if result.returncode:
        print(result.stderr)
        raise RuntimeError(f'El proceso Gloo terminó con código {result.returncode}')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In a Windows run with PyTorch 2.11.0 and Gloo, maximum median times for 256, 1024, 4096, 16384, 65536, 262144, and 1048576 bytes were 3.7042, 1.5228, 5.2972, 3.5102, 2.5431, 2.7332, and 4.2255 ms respectively. The line gave R² = 0.0596: in this shared-load campaign, scatter is too high to treat its parameters as reliable network properties. Another campaign gave R² = 0.9133 and fitted bandwidth 0.920 GB/s, illustrating sensitivity to conditions. Both are local CPU-process communications, not NCCL or GPU measurements.

Exercises

Numeric
In milliseconds, what does the ring predict for 2 decimal GB, 8 ranks, 10 µs latency and 100 GB per second per link?
Numeric
For eight ranks, what is busbw in GB/s when algbw is 40 GB/s?
Proof
Prove: In the point-to-point sums and copies model, prove the aggregate bound and explain what it guarantees about the most loaded rank.
0
There are p independent inputs per element and the result must reach all ranks.

Step 1 of 3. How many transfers at minimum gather p contributions into one sum?

Quiz
Which associations are correct for these common operations?

More than one answer may be correct.

Code
Implement ring_allreduce(x) for a NumPy matrix with p rows and n columns, where n is divisible by p. Simulate p-1 reduce-scatter rounds and p-1 all-gather rounds, reading a copy per round. Return a new matrix with the sum on each rank; do not implement it using a global sum.
import numpy as np
def ring_allreduce(x):
  pass
Shift+Enter to run
Key idea
Count rounds, bytes, and links with explicit assumptions. A rank simulation, CPU Gloo measurement, and multi-GPU NCCL benchmark answer different questions.