Split an MLP across GPUs with tensor parallelism

This is a NumPy simulation of Megatron-style tensor parallelism.

A transformer MLP is y = relu(x @ W1) @ W2. Megatron splits W1 by COLUMNS and W2 by ROWS across p GPUs. Each GPU computes its slice of the hidden layer with no communication, multiplies by its rows of W2, and one all-reduce (a sum) at the end gives y.

Write tp_mlp(x, W1, W2, p) that simulates this: split W1 into p column blocks and W2 into p matching row blocks (np.array_split), compute each GPU's partial output, and return (y, partials) where partials is the list of per-GPU outputs and y is their sum.

Signaturedef tp_mlp(x, W1, W2, p)

Understand the idea

Tensor parallelism splits one layer's weights across GPUs. For an MLP y = relu(x W1) W2, cut W1 by columns so each GPU owns whole hidden units, and cut W2 by the matching rows. Each GPU computes its part of the hidden layer, applies ReLU locally, multiplies by its rows of W2, and a single sum at the end gives y. Splitting W1 by rows would give partial pre-activations, and ReLU of a partial sum is not the sum of ReLUs: relu(1) + relu(-2) = 1 but relu(1 - 2) = 0. Worked example: x = [[1, 1]], W1 = [[1, -1], [1, -2]], W2 = [[3], [4]], p = 2. GPU 0 takes column 0 of W1: hidden 1 + 1 = 2, relu 2, times row 0 of W2 (3) = 6. GPU 1 takes column 1: hidden -1 - 2 = -3, relu 0, times 4 = 0. Sum = 6, matching the single-GPU answer. Rule: split W1 columns and W2 rows with np.array_split, partial_k = relu(x W1_k) W2_k, y = sum of partials. Megatron-LM trains large LLMs this way.

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

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

  • Sample 1: matches the single-GPU MLPtp_mlp(_x, _W1, _W2, 2)[0]
  • Sample 2: partials of 3 GPUstp_mlp(_x, _W1, _W2, 3)[1][0]