Simulate a two-level hierarchical all-reduce
Why it matters Multi-node training uses hierarchical collectives so that slower inter-node links carry only a fraction of the gradient traffic.
Clusters have fast links inside a node and slower links between nodes. A hierarchical all-reduce reduce-scatters inside each node, all-reduces each shard across nodes, then all-gathers inside the node, so only 1 / G of the data crosses the slow network per GPU.
Write hier_allreduce(grads, bytes_per_elem=4). grads has shape (nodes, G, L) with L divisible by G (raise ValueError otherwise). Step 1: inside each node, GPU g ends with shard g (elements g * L / G to (g + 1) * L / G - 1) of that node's sum. Step 2: GPU g of every node all-reduces its shard across nodes (sum). Step 3: inside each node, all-gather the shards so every GPU has the full sum. Return a dict {"result": array (nodes, G, L) after step 3, "shards": array (nodes, G, L / G) after step 2, "inter_bytes": bytes each GPU sends between nodes in step 2 with a ring, 2 * (nodes - 1) / nodes * (L / G) * bytes_per_elem}.
def hier_allreduce(grads, bytes_per_elem=4)Example
grads [[[1, 2], [3, 4]], [[10, 20], [30, 40]]] (2 nodes, 2 GPUs, L 2) gives shards [[[44], [66]], [[44], [66]]], every result row [44, 66] and inter_bytes 4.0.
Understand the idea
Imagine every office in a company first totals its own expense reports, splits the total into pages, and then only one person per page phones the matching person in every other office. Each office phone line carries just one page per person instead of the whole report. Inside the office, papers move quickly by hand. Worked example: two nodes with two GPUs each and vectors of length 2. Node sums are [4, 6] and [40, 60]. GPU 0 of each node takes element 0, GPU 1 takes element 1. Across nodes, shard 0 is 4 + 40 = 44 and shard 1 is 66. After the all-gather every GPU has [44, 66]. Each GPU sent 2 x 1/2 x 1 element x 4 bytes = 4 bytes between nodes. Rule: inter-node bytes per GPU = 2 (n - 1) / n x L / G x bytes. With 8 GPUs per node, the slow network carries an eighth of the flat-ring traffic per GPU.
Shapes and data flow
grads (nodes, G, L) -> node sum (nodes, L) -> shards (nodes, G, L/G) -> summed across nodes -> result (nodes, G, L)