Tensor-Parallel Linear Layer: Forward, Backward, and Collectives
Machine LearningModel answerLast updated
Work out the forward and backward passes of a linear layer whose weight columns are split across devices, pinpoint the required collective, and design tests for sharding bugs.
A bias-free linear layer computes Y = X @ W, where X is (B, D) and W is (D, H). The layer is trained with tensor parallelism on P devices. H is divisible by P, and the weight matrix is split along its output columns: device p holds W_p of shape (D, H/P). Every device starts with the complete X, and during the backward pass device p receives only its own slice dY_p of the upstream gradient, with shape (B, H/P).
Your task
- Derive the forward computation. State the local tensor shape for every expression, and say how (or whether) the full
Yis assembled. - Derive the backward formulas for
dWanddXfrom the differential of the loss. - Name each collective needed so that the full
dXends up replicated on all devices whiledWstays column-sharded. Explain why each is required and what it costs in communication volume. - Write NumPy-style pseudocode for one device's forward and backward step, treating collectives as abstract calls such as
all_gatherandall_reduce. - Describe a debugging plan covering shape errors, numerical errors, and collective mistakes.
- Briefly discuss, without implementing it, how things change if
Xor the contraction dimensionDis sharded instead.
Assumptions
- Plain dense matmul, no bias.
- Devices run synchronously with identical floating-point dtype.
- Local matmul is available, and collectives are treated as black-box primitives.
- The scalar loss provides
dYwith the same logical shape asY.
Points worth clarifying up front
- Which tensors must be replicated and which sharded after each phase?
- Are you optimizing for communication volume, peak memory, or latency?
- Are gradients also averaged across data-parallel replicas?
- What reference implementation and tolerances exist for testing?
Hints
Hint 1
Annotate every expression with its local shape. For example, `X @ W_p` is `(B, D) @ (D, H/P) = (B, H/P)`.
Hint 2
Start from `dL = <dY, dX_in @ W + X @ dW_in>` and read off the gradients. Then ask which of them involves a sum over the sharded dimension `H`.
Hint 3
`dX = dY @ W^T = sum_p dY_p @ W_p^T`. Each device can only compute one term of that sum, so think about which collective combines them.
Hint 4
Check the implementation by simulating `P` devices in one process on tiny shapes and comparing against the unsharded computation.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Setup
Partition W by columns: W = [W_0 | W_1 | ... | W_{P-1}], with W_p of shape (D, H/P). Partition Y and dY the same way along the column axis, so Y_p and dY_p are (B, H/P).
Forward
Each device computes
Y_p = X @ W_p, shapes (B, D) @ (D, H/P) -> (B, H/P).
Column blocks of Y depend only on the matching column blocks of W, so the forward pass needs no communication. The full Y = concat_p(Y_p, axis=1) is only needed if the next op requires it. In that case use an all-gather along the column axis (each device receives (P-1) * B * H/P elements). In practice, the next layer is often a row-sharded matmul that consumes Y_p directly, which avoids the gather.
Backward
From Y = X W, the differential is dY = dX_in W + X dW_in. For a scalar loss L, with upstream gradient G = dL/dY:
dW = X^T @ GdX = G @ W^T
Weight gradient. Column block p is dW_p = X^T @ dY_p, shapes (D, B) @ (B, H/P) -> (D, H/P). This uses only local data (full X, local dY_p), so no communication is needed, and dW_p has exactly the shape and sharding of W_p.
Input gradient. dX = dY @ W^T. Splitting the contraction over H into shards gives
dX = sum_{p} dY_p @ W_p^T, where each term is (B, H/P) @ (H/P, D) -> (B, D).
Each device computes only its partial dX_p of full shape (B, D). The true gradient is the sum over devices, so we need an all-reduce (sum) over the tensor-parallel group. This is the single required collective in the backward pass, and it leaves dX replicated everywhere, which is what the upstream layer expects.
Communication cost
- Forward: zero (or one all-gather of
B*Helements total if the fullYis needed). - Backward: one all-reduce of
B*Delements. A ring all-reduce moves about2 * (P-1)/P * B * Delements per device. This is independent ofH, which makes the scheme attractive whenH >> D's partner dimension is large butB*Dis modest. - Compute per device:
3 * B*D*H/Pmultiply-adds across forward,dW, anddX, which is a perfect 1/P split. - Memory:
W_panddW_pshrink byP;XanddXstay replicated.
The all-reduce can be overlapped with the dW_p computation, since dW_p does not depend on it. Compute dX_p first, launch the all-reduce asynchronously, then compute dW_p.
Pseudocode (device p)
def forward(X, W_p):
Y_p = X @ W_p # (B, H/P)
ctx = (X, W_p)
return Y_p # optionally all_gather(Y_p, axis=1)
def backward(ctx, dY_p):
X, W_p = ctx
dX_partial = dY_p @ W_p.T # (B, H/P) @ (H/P, D) -> (B, D)
handle = all_reduce_async(dX_partial, op="sum")
dW_p = X.T @ dY_p # (D, B) @ (B, H/P) -> (D, H/P)
dX = handle.wait() # (B, D), identical on all devices
return dX, dW_p
Alternative shardings (discussion only)
- Contraction dimension
Dsharded (X_pis(B, D/P),W_pis(D/P, H)): forward gives partial sumsX_p @ W_pof shape(B, H), so the forward needs an all-reduce (or reduce-scatter). BackwarddX_p = dY @ W_p^Tis local and already sharded, anddW_p = X_p^T @ dYis local. The collective moves from backward to forward, and its size scales withB*H. Xsharded along batch (data parallel): forward is local;dWbecomes a partial sum over batch shards and needs an all-reduce ofD*Helements.dXstays local.
The choice depends on which of B*D, B*H, D*H is smallest and on what the neighbouring layers expect.
Debugging plan
- Single-process simulation. Emulate
Pdevices with a list of arrays and implement collectives as plainsum/concatenate. Compare to unshardedX @ W,G @ W.T,X.T @ Gusing small random shapes (e.g.B=3, D=4, H=8, P=2). - Shard ordering. Use a distinctive
W(e.g.W[i,j] = 100*i + j) and check that gatheredYequals the reference column order. Wrong rank ordering in all-gather is a classic silent bug. - Transposes and shapes. Assert shapes at each step. A square case (
D == H/P) hides transpose bugs, so test with all dimensions distinct. - Gradient scaling. Verify loss scaling is applied once. Common errors are averaging instead of summing in the all-reduce (dividing
dXbyP) or summing when a data-parallel mean is intended. - Numerical check. Finite differences in float64 on a tiny problem validate the formulas. In float32 or bf16, compare to the unsharded result with tolerances like
rtol ~1e-5(fp32) and looser for bf16. Differences come from changed summation order in the all-reduce, so do not expect bitwise equality. Accumulate in fp32 if inputs are low precision. - Collective semantics. Check that all devices call collectives in the same order, with the same group and tensor size (mismatches cause hangs). After the all-reduce, assert that
dXis identical across devices. TestP=1(should reduce to the unsharded code) and uneven-but-divisible edge cases.
Common mistakes
- Forgetting the all-reduce on
dXand using only the local partial, which silently produces wrong gradients for upstream layers. - Adding a collective for
dW_p, which is unnecessary here and wastes bandwidth. - Using all-gather where a sum is needed, or mixing up reduce-scatter and all-reduce output layouts.
- Assuming results match bitwise across different
P.