Simulate ring all-reduce step by step

This is a NumPy simulation of NCCL's ring all-reduce; no network is involved.

p workers each hold a vector split into p chunks. Ring all-reduce has two phases of p - 1 steps each:
1. Reduce-scatter: at step k, worker i sends chunk (i - k) mod p to worker (i + 1) mod p, which adds it into its own copy of that chunk. All sends in a step happen at the same time.
2. All-gather: at step k, worker i sends chunk (i + 1 - k) mod p (now fully reduced) to worker (i + 1) mod p, which overwrites its copy.

Write ring_allreduce(vectors) where vectors is a list of p equal-length arrays whose length is divisible by p. Return (result_per_worker, elements_sent_per_worker), where the first is a list of arrays (all equal to the sum) and the second is how many elements one worker sent in total.

Signaturedef ring_allreduce(vectors)

Understand the idea

Ring all-reduce sums a vector across p workers arranged in a circle, without any central server. Each vector is cut into p chunks. Phase 1 (reduce-scatter, p - 1 steps): each worker passes one chunk to its right neighbour, who adds it in; after this, worker i holds the full sum of chunk (i + 1) mod p. Phase 2 (all-gather, p - 1 steps): the finished chunks travel around the ring and overwrite stale copies. All sends in a step use the values from before that step. Worked example: p = 3, w0 = [1, 2, 3], w1 = [10, 20, 30], w2 = [100, 200, 300], one element per chunk. Step 0: w1 chunk 0 becomes 11, w2 chunk 1 becomes 220, w0 chunk 2 becomes 303. Step 1: w1 chunk 2 = 30 + 303 = 333, w2 chunk 0 = 100 + 11 = 111, w0 chunk 1 = 2 + 220 = 222. Now each worker owns one full sum. Each worker sends 2 (p - 1) chunks of size n / p, here 4 elements. NCCL uses rings for multi-GPU gradient sync.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: 3 workers sumring_allreduce(_v)[0]
  • Sample 2: bytes sent per workerring_allreduce(_v)[1]