AI State of the Art
SOTA/Training: Modern Training Techniques/31 min
Section 88

Tensor Parallelism: Splitting Matrices

Listen as a podcast →

What this method splits, and what it must communicate

As with any parallelism strategy, two questions are enough, and they should be answered before any detail.

What TP splits: the weight tensor. TP, or Tensor Parallelism, splits neither the batch of examples, as data parallelism does, nor the layers, as pipeline parallelism does. It cuts one single weight matrix into pieces and hands one piece to each device. A tensor is simply the general name for an array of numbers with any number of dimensions: a vector has one, a matrix two, and the activations inside a transformer three.

What it must communicate: the partial result of every matrix product, in the middle of the computation, at every layer. If each device holds only a piece of the matrix, none of them can produce the complete product. So the pieces have to be glued back together before anything can proceed, with an all-reduce, which adds up every device's contribution and hands the total back to all of them.

That difference in timing is the whole subject of this page. Data parallelism communicates once, at the end, on data nothing else depends on. Tensor parallelism communicates inside the computation, on data the next step depends on immediately. The first exchange hides underneath the computation; the second one stops it.

Where the reference implementation lives

This page stays at the level of principle: what is split, what is communicated, at what price. The reference implementation (the exact placement of the all-reduce operations inside a transformer block, the paper's conjugate operators, the large-scale measurements) is covered in Megatron-LM and is not repeated here.

Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism (Shoeybi et al., 2019)

Why you end up cutting a matrix

Data parallelism does not reduce memory, and ZeRO or FSDP split the model states but still gather one complete layer before using it. Two ceilings therefore remain, and TP is the only tool that attacks them.

Take an order of magnitude, with deliberately round illustrative numbers. A hidden dimension d=8192d = 8192 (the width of the vector representing each token) and a feed-forward network that widens it to 4d=327684d = 32768 before bringing it back to dd.

  • One weight matrix of that block holds 8192×32768=2688192 \times 32768 = 268 million parameters, i.e. 537537 megabytes in BF16 at 2 bytes per parameter. There are two per layer, and several dozen layers.
  • The intermediate activation is the array of numbers the first matrix produces. For a batch of 4 sequences of 4096 tokens, it holds 4×4096×32768=5374 \times 4096 \times 32768 = 537 million values, again 1.071.07 gigabytes, for a single tensor, in a single layer. Across 80 layers, that one item alone approaches 86 GB.

TP divides both by the number of devices in the group: each device holds only part of the matrix, and therefore produces only part of the intermediate activation. That second saving, the one on activations, is what really sets TP apart from ZeRO, ZeRO does not partition activations at all.

The two ways to cut a matrix

The whole mechanism of TP lives inside one matrix product:

Y=XWY = X W

where XX is the input activation, that is, a result computed on the text currently being processed, and WW is a matrix of learned weights, frozen after training. This distinction matters for what follows: splitting WW is an engineering decision made once and for all, whereas splitting XX changes what travels for every token.

There are exactly two ways to cut WW, and they do not cost the same.

By columns: no communication for the product

Cut WW vertically, into blocks of columns, one per device:

W=[ W1∣W2∣…∣WP ]W = [\,W_1 \mid W_2 \mid \ldots \mid W_P\,]

Y=XW=[ XW1∣XW2∣…∣XWP ]Y = X W = [\,X W_1 \mid X W_2 \mid \ldots \mid X W_P\,]

where PP is the number of devices in the group, WiW_i the block of columns held by device ii, and XWiX W_i the matching block of columns of the result.

In one sentence: from the complete input and its own block of columns, each device produces finished columns of the result directly. Nothing to add up, hence nothing to exchange for this product. On the other hand, every device needs the whole of XX, and nobody holds the whole of YY.

By rows: an all-reduce is unavoidable

Cut WW horizontally, into blocks of rows. A matrix product pairs the columns on the left with the rows on the right, so if WW is cut by rows, XX must be cut by columns at the very same place.

\qquad X = [\,X_1 \mid X_2 \mid \ldots \mid X_P\,]$$ $$Y = X W = X_1 W_1 + X_2 W_2 + \ldots + X_P W_P$$ where $X_i$ is the block of input columns held by device $i$ and $W_i$ its block of weight rows. In one sentence: *each device produces a result of the right shape but incomplete (a partial contribution to the whole result) and the $P$ contributions must be added to obtain $Y$.* That is exactly what an all-reduce does, and here it is **mandatory**. <Callout type="tip" title="The pairing that makes TP viable"> Look at the two inputs and the two outputs. The column split needs a complete input and yields an output split by columns; the row split needs precisely an input split by columns. The two dovetail. Hence the trick: cut the **first** matrix of a block by columns and the **second** by rows, and the output of the first feeds the second **without a single exchange in between**. One all-reduce at the exit of the block instead of two. That is the engineering contribution of the Megatron-LM paper, spelled out [over there](/state-of-the-art/megatron-lm). </Callout> <ImageWithSource src="/images/admin/img-1785229537076.png" alt="Two stacked diagrams. On top, Tensor Parallelism (2 GPUs): a 1x4 input flows through a Linear 4x4 layer then a Linear 4x2 layer before the 1x2 output; each layer rectangle is cut down the middle by a dashed vertical line, the left half labelled GPU 0 and the right half GPU 1. At the bottom, Pipeline Parallelism (2 GPUs): the same layers are grouped inside two large coloured frames, GPU 0 holding the input and the Linear 4x4 layer, GPU 1 holding the Linear 4x2 layer and the output, the two frames joined by a horizontal arrow." source="Hugging Face blog, Tensor Parallelism (huseinzol05)" sourceUrl="https://huggingface.co/blog/huseinzol05/tensor-parallelism" caption="The difference is the direction of the cut. On top, each layer is split vertically and both GPUs work on the same layer at the same time: that is tensor parallelism. At the bottom, whole layers are handed out and the GPUs take turns one after the other: that is pipeline parallelism." size="full" /> ## Inside a transformer: two places, two natural cuts ### Attention: split by heads Multi-head attention is an ideal case, because the heads are **independent**: each computes its own weighting over the whole sequence, and their results only mix at the very end. With 32 heads and 4 devices, you give 8 whole heads to each device. What is being split are the learned weight matrices $W_Q$, $W_K$ and $W_V$, cut **by columns**, head by head. Each device therefore computes its own $Q$, $K$ and $V$, which are **activations** obtained by multiplying the current text by those matrices, and its own softmax, without asking anyone for anything. Splitting the weight matrix by heads and splitting the result by heads are two descriptions of the same split. Only at the output projection (cut **by rows**) does an all-reduce recombine the contributions. <ImageWithSource src="/images/admin/img-1785229536216.webp" alt="Diagram of tensor parallelism inside an attention layer, annotated 32 attention heads and 4 GPUs. Input X fans out to four boxes in parallel: GPU-0 handles heads 0 to 7, GPU-1 heads 8 to 15, GPU-2 heads 16 to 23, GPU-3 heads 24 to 31, each computing its own QKV attention. This first block is boxed and labelled GEMM1 column parallel. Each GPU then produces its slice of the output Z by multiplying its result with its share of the projection matrix W, in a second block labelled GEMM2 row parallel. The four arrows finally converge on a blue box that sums the contributions of all heads." source="Jarvislabs blog, Scaling LLM Inference (DP, PP, TP)" sourceUrl="https://jarvislabs.ai/blog/scaling-llm-inference-dp-pp-tp" caption="Splitting by heads. With 32 heads and 4 GPUs, each GPU gets 8 whole heads and computes its attention without exchanging a single byte with the others. Only at the output projection, on the right, do the four pieces come back together as one simple sum, the all-reduce described in the text." size="full" /> Two annotations on that diagram deserve unpacking. **GEMM** stands for *GEneral Matrix Multiply*: in high-performance computing vocabulary, that is the name of the elementary operation everything else is made of. *Column parallel* and *row parallel* are the two cuts from the previous section. ### The feed-forward network: columns then rows The second block of every layer chains two matrix products separated by a non-linear function (historically **GeLU**, *Gaussian Error Linear Unit*) applied value by value: $$Y = \text{GeLU}(X W_1)\, W_2$$ where $X$ is the input activation and $W_1$, $W_2$ two matrices of learned weights. Apply the pairing: $W_1$ by columns, $W_2$ by rows. Why that order and not the reverse? Because GeLU works **value by value**. The column split gives each device finished values of the intermediate result, on which GeLU can be applied immediately. The row split would only give partial sums, and $\text{GeLU}(a+b) \neq \text{GeLU}(a) + \text{GeLU}(b)$: you would have to add first, hence communicate one extra time. <Callout type="info" title="What TP does not apply to"> TP splits the **large matrix products**: attention and the feed-forward network. The lightweight operations (layer normalizations, dropout, residual additions, the embedding table) stay replicated identically on every device in the group. The computation they represent is negligible, but their **activations** take up the same room on every device: that is pure redundancy, and it is [sequence parallelism](/state-of-the-art/sequence-parallelism)'s job. </Callout> ## The cost: an exchange you cannot hide Every TP all-reduce carries an activation tensor of shape $B \times L \times d$: batch size times sequence length times hidden dimension. As with the data-parallel ring, each device then sends: $$V = 2 \cdot \frac{P-1}{P} \cdot B \cdot L \cdot d \cdot (\text{bytes per value})$$ The Megatron-LM paper establishes that the column-then-row pairing gets you through with **two all-reduce operations on the forward pass and two on the backward pass**, i.e. four per layer per training step. One per block (attention and feed-forward network) in each direction. <Callout type="warning" title="Why TP needs a very fast link and data parallelism does not"> It is not a question of volume, it is a question of **where the exchange sits inside the computation**. The data-parallel all-reduce carries gradients and happens **once, at the end of the backward pass**, on data nothing else depends on. You launch it as soon as the first gradients are ready and it runs **underneath** the computation that continues: it becomes almost free in wall-clock time. The TP all-reduce is **in the middle** of the computation. The device needs the complete result of the block to start the next one: nothing can proceed until the exchange finishes. It sits on the critical path, it cannot be hidden, and it happens four times per layer. On an 80-layer model that is 320 synchronized stops per training step. A second aggravation: what travels are **activations**, whose size grows with batch size and sequence length, whereas the gradients of data parallelism are always the size of the model, whatever the text. The full argument, with the detail of the two communication operators, is in [Megatron-LM](/state-of-the-art/megatron-lm); the hiding mechanism is explained in [FSDP](/state-of-the-art/fsdp). </Callout> ### Where the "TP stays inside one machine" rule comes from You have to compare links in the **same unit**, and this is where readers most often go wrong: network links are advertised in **gigabits** per second, internal buses in **gigabytes** per second, and a byte is eight bits. | Link | Advertised rate | In gigabytes per second | |---|---|---| | NVLink 4, between cards in one machine | 900 GB/s | **900** | | InfiniBand NDR, between machines | 400 Gbit/s | **50** | The ratio is roughly **18x**, not 2x as a comparison of 900 and 400 would suggest. An exchange that cannot be hidden, repeated 320 times per step, over a link eighteen times slower: that is fatal. Hence the engineering rule, without exception in practice, **a TP group never crosses a machine boundary**. These interconnects are detailed in [Scaling infrastructure](/state-of-the-art/scaling-infra). ## How many devices in TP? In practice 2, 4 or 8: the number of cards wired together by NVLink inside one machine. An 8-card machine therefore caps the TP degree at 8. Two reasons not to push beyond, even if the hardware allowed it. The first is the previous one: crossing the machine boundary would place a link eighteen times slower on the critical path. The second is that the more you split, the **smaller** the matrix pieces each device gets, and a graphics card only reaches full efficiency on large matrix products. Below a certain size, the start-up time of each operation weighs more than the computation itself, and efficiency collapses. <Callout type="tip" title="The strategy that works"> Take the **smallest** TP degree that makes the model fit, and not one more. Then complete it: [pipeline parallelism](/state-of-the-art/pipeline-parallelism) to spread the layers across machines, [data parallelism](/state-of-the-art/data-parallelism) to occupy the rest of the cluster. The classic combination is a TP degree of 8 inside each machine, pipeline between machines, data parallelism on top. </Callout> ## What TP leaves behind: sequence parallelism The lightweight operations set aside above (normalization, dropout, residual addition) are replicated across every device in the TP group. Their compute cost is negligible, but each device stores an **identical copy** of their activations: at a TP degree of 8, the same information takes up eight times its room. **SP**, or *Sequence Parallelism*, splits precisely those operations along the **sequence length**: each device in the group handles only a slice of tokens. - **TP**: splits the hidden dimension, for the large matrix products. - **SP**: splits the sequence length, for the operations TP does not touch. - **Transitions**: at the boundary between the two modes, an all-gather one way and a reduce-scatter the other. The remarkable point is that those transitions cost **nothing extra**. An all-reduce is exactly a reduce-scatter followed by an all-gather (that identity is demonstrated in [FSDP](/state-of-the-art/fsdp)) so replacing the TP all-reduce operations by that pair carries the same volume. You remove a memory redundancy without paying a single byte of network. <ImageWithSource src="/images/admin/img-1785229536297.png" alt="Diagram of a Transformer layer split into five successive zones, drawn on two rows for two GPUs. At both ends and in the middle, three blue zones labelled Sequence Parallel contain the LayerNorm and then the Dropout, applied separately to two sequence slices noted X1 and X2. Between them, two grey zones labelled Tensor Parallel contain the matrix multiplications: matrix A is split by columns, a GeLU is applied, then matrix B is split by rows. Two green vertical bars noted g and g-bar mark the transitions between the two partitioning modes." source="NVIDIA Technical Blog, Mastering LLM Techniques: Inference Optimization" sourceUrl="https://developer.nvidia.com/blog/mastering-llm-techniques-inference-optimization/" caption="Both splits coexist inside a single layer. The blue zones handle LayerNorm and dropout by cutting the sequence in two; the grey zones handle the big matrix multiplications by cutting the hidden dimension. The green g bars are the conversion operations between the two modes: all-gather one way, reduce-scatter the other." size="full" /> The details are in [Sequence parallelism](/state-of-the-art/sequence-parallelism). ## Composing with the other splits TP is never used on its own, because it is confined to one machine. - **TP with [data parallelism](/state-of-the-art/data-parallelism)**: each TP group forms one complete model and receives its share of the batch. - **TP with [pipeline parallelism](/state-of-the-art/pipeline-parallelism)**: layers are distributed across machines, and inside each machine TP splits the matrices. - **TP with [ZeRO](/state-of-the-art/zero) or [FSDP](/state-of-the-art/fsdp)**: the optimizer states are partitioned across replicas, on top of the TP split. The first three form **three-dimensional parallelism**, TP × PP × DP, whose grid is described in [Megatron-LM](/state-of-the-art/megatron-lm). The order of the three dimensions is not arbitrary: it follows the ranking of the links from fastest to slowest, and that is what puts TP inside the machine. ## Summary Tensor parallelism splits **one single weight matrix** across several devices. There are two ways to cut it: by columns, which requires no exchange for the product, and by rows, which requires one in order to add up the partial contributions. You chain them (columns then rows) so that you pay for only one per block. What to remember is not the volume exchanged but its **timing**: the TP all-reduce lands **in the middle** of the computation, the device waits for it, and that happens four times per layer in both directions. There is no way to tuck it underneath computation, unlike data parallelism's single end-of-backward exchange. For that reason alone, TP stays locked inside one machine, on the fast link between neighbouring cards, and going multi-machine calls for other splits. <Quiz lang="en" questions={[ { q: "What exactly does tensor parallelism split?", options: [ "The batch of examples, spread across the cards, each processing its own share", "The model's layers, handed out one after another to different cards, each hosting its own stage", "One single weight matrix, cut into pieces spread across the cards", "Only the optimizer states, with weights and gradients replicated everywhere", ], answer: 2, explain: "That is what sets it apart: DP splits the batch, pipeline splits the layers, TP slices through one and the same matrix, so each card holds only a piece, which forces it to reassemble partial results in the middle of the computation.", }, { q: "Why does tensor parallelism demand a very fast link between cards, when data parallelism makes do with the network between machines?", options: [ "Because TP exchanges a much larger volume of data than DP, by several orders of magnitude, more than any inter-machine network could absorb", "Because its all-reduce lands in the middle of the computation: the card needs the complete result to start the next block, the exchange cannot be hidden, and it repeats four times per layer", "Because NCCL only works inside a single machine and falls back to the CPU whenever the network has to be crossed", "Because activations are more sensitive to transmission errors than gradients: the slightest corruption on the inter-machine network would distort the forward pass, whereas an error on a gradient averages out and disappears", ], answer: 1, explain: "It is not a question of volume but of where the exchange sits in the computation. DP's exchange comes at the end, on data nothing depends on anymore, and runs underneath the computation; TP's sits on the critical path, 320 synchronized stalls per step on an 80-layer model.", }, { q: "In the feed-forward network, the first matrix is cut by columns and the second by rows. Why that order and not the reverse?", options: [ "Because the first matrix is larger than the second: you cut the heavier one in the direction that yields the smallest pieces", "Pure convention inherited from Megatron: the reverse order would work just as well and cost exactly the same number of exchanges", "Because the row split runs faster when it comes second, memory then being accessed in the right order", "Because GeLU applies value by value: the column split yields finished values it can be applied to right away, whereas the row split would yield only partial sums, and GeLU(a+b) is not GeLU(a) + GeLU(b)", ], answer: 3, explain: "As a bonus, the column-split output of the first matrix is exactly the input the row-split second matrix expects: the two interlock with no exchange in between, and a single all-reduce per block suffices.", }, { q: "What truly distinguishes TP from ZeRO or FSDP, which also split the weights across cards?", options: [ "TP also splits the intermediate activations: each card produces only its share of the intermediate tensor, whereas ZeRO always gathers a full layer before using it and never partitions activations", "TP is cheaper in communication than ZeRO: by moving only pieces of matrices rather than whole parameters, it would divide the exchanged volume by the number of cards, where ZeRO must rebroadcast every complete layer before using it", "ZeRO only works at inference and TP only at training, so the two techniques would never compete for the same job", "TP splits the batch on top of the weights, stacking the benefits of data parallelism and memory sharding", ], answer: 0, explain: "That second saving is the one that matters: a single intermediate activation of the feed-forward network can exceed a gigabyte, and there are dozens of layers. Only TP lightens that item, because each card computes only its slice of the result.", }, { q: "On a cluster of 64 cards spread over 8 machines, why not push the TP degree to 64?", options: [ "Because NCCL is limited to 8 participants per communication group, a size beyond which the library refuses to build the ring", "Because a matrix mathematically cannot be cut into more than 8 pieces: beyond that, the dimensions no longer divide into whole shares and some cards would receive empty blocks, breaking the distributed multiplication algorithm outright", "Because the TP group must never cross a machine boundary (the unhideable exchange would land on a link roughly 18 times slower) and because beyond that, the matrix pieces become too small for each card to reach full efficiency", "Because the learning rate would have to be multiplied by 64 to compensate, making training unstable", ], answer: 2, explain: "The engineering rule: take the smallest TP degree that makes the model fit, capped by the machine (2, 4 or 8 cards under NVLink), then complete with pipeline parallelism between machines and data parallelism on top.", }, ]} />