Split attention heads across GPUs with tensor parallelism
Why it matters Large model inference and training split attention heads across GPUs in exactly this column-then-row pattern so each layer needs only one all-reduce.
Tensor parallel attention gives each GPU a subset of heads. The query, key and value projections are split by columns (each rank owns its heads' columns) and the output projection is split by rows, so each rank produces a partial output and one all-reduce sum finishes the layer.
Write tp_attention(X, Wq, Wk, Wv, Wo, n_heads, tp). X is (T, d); all weights are (d, d); head h uses columns h * hd to (h + 1) * hd with hd = d // n_heads. Raise ValueError if n_heads is not divisible by tp. Rank r owns heads r * (n_heads // tp) to (r + 1) * (n_heads // tp) - 1, i.e. one contiguous column block of Wq, Wk, Wv and the same row block of Wo. Each rank runs causal softmax attention for its heads (scores scaled by 1 / sqrt(hd)), concatenates its head outputs to (T, d / tp), and multiplies by its row block of Wo. Return (Y, partials) where partials has shape (tp, T, d) and Y is their sum.
def tp_attention(X, Wq, Wk, Wv, Wo, n_heads, tp)Example
with d 4, 2 heads, tp 2 the sum of the two partials equals the single-GPU attention output; for X = I (4 x 4) and every weight the identity, Y rounded to 4 places is [[1, 0, 0, 0], [0.3302, 0.6698, 0, 0], [0.3333, 0.3333, 0.5035, 0], [0.25, 0.25, 0.1989, 0.4034]].
Understand the idea
Tensor parallel attention is like several teams each answering a subset of the exam questions and then adding their marks. Heads do not talk to each other inside attention, so each GPU can take whole heads. The trick is to slice the weights so no data moves until the very end. Q, K, V projections are cut by columns: rank r computes only its heads' Q, K, V. The output projection is cut by rows matching those columns, because Y = concat(heads) Wo = sum over ranks of heads_r Wo_r. Worked example: d = 4, two heads of size 2, tp = 2. Rank 0 uses columns 0 to 1 and rows 0 to 1 of Wo; rank 1 uses columns and rows 2 to 3. Each returns a full-size (T, 4) partial; adding them gives the exact layer output. Rule: Y = sum_r Attn_r(X Wq_r, X Wk_r, X Wv_r) Wo_r, one all-reduce per layer.
Shapes and data flow
X (T, d) @ Wq[:, c0:c1] (d, d/tp) -> Q_r (T, d/tp); heads (T, hd); concat (T, d/tp) @ Wo[c0:c1, :] (d/tp, d) -> partial (T, d)