Chapter 40
Tensor, Sequence, and Context Parallelism
On this page
- Column-parallel linear layers
- Row-parallel linear layers
- Tensor layouts are types
- Vocabulary-parallel embedding and loss
- Differentiate vocabulary-parallel cross-entropy
- Local GEMM efficiency
- Sequence parallelism
- Context parallelism
- Causal and ragged context
- Choosing TP versus CP
- Topology and communicator concurrency
- Design Exercises
- Worked Solutions
- Carry one tensor through tensor-parallel ownership
Intra-layer parallelism partitions the tensor dimensions of one model replica. It makes large layers or long activations fit, but puts communication inside every transformer block and can shrink local kernels below efficient shapes.
Column-parallel linear layers¶
For a linear operation Y = X A, column parallelism partitions output columns of A across p ranks. Each rank computes a shard Y_i = X A_i. The input X is replicated across the tensor-parallel group, while the output feature dimension is sharded.
This maps naturally to Q, K, V, or the first MLP projection when attention heads or intermediate features divide evenly. A following operation that can consume the sharded features avoids an immediate all-gather.
Bias, activation, and gating should be applied locally when their partition matches. If the API materializes full Y unnecessarily, an all-gather erases the benefit and adds memory.
Row-parallel linear layers¶
Row parallelism partitions the input rows of A and the corresponding feature dimension of X. Rank i computes a partial output X_i A_i; partials must be summed across ranks. The result is usually produced by all-reduce, or reduce-scatter when the next region can consume a sharded output.
A common transformer plan pairs a column-parallel expansion with a row-parallel contraction. In the forward pass, the intermediate activation remains sharded and the contraction's partial outputs require reduction. Backward has a corresponding boundary: a column-parallel layer produces partial input gradients that must be summed across tensor-parallel ranks, commonly by all-reduce or by a reduce-scatter/all-gather sequence when sequence parallelism is active. The same principle applies to attention projections: choose adjacent layouts so communication occurs at a small number of deliberate boundaries.
Tensor layouts are types¶
Treat each tensor as carrying a distribution type such as:
- replicated;
- sharded on hidden, head, vocabulary, sequence, or batch dimension;
- partial, meaning local values require reduction;
- uneven or padded shard with a validity mask.
Operators transform these types. A compiler or framework can insert collectives, but a robust design should state them. Many accidental all-gathers come from an interface that forgets a tensor is already sharded.
Residual connections require compatible layouts. Dropout masks, bias, and normalization statistics must have a defined logical mapping so changing tensor-parallel degree does not silently change model semantics beyond the reproducibility contract.
Vocabulary-parallel embedding and loss¶
Large vocabularies can shard embedding rows or output logits. For embedding lookup, each rank identifies token IDs it owns, produces local vectors for those IDs, and reduces or routes results. For vocabulary-parallel cross-entropy, compute a distributed log-sum-exp:
- reduce the maximum logit across vocabulary shards;
- compute local shifted exponentials and reduce their sums;
- locate the target token's owning shard and reduce its logit contribution;
- form loss and local gradient without gathering all logits.
Numerical stability and padding vocabulary entries matter. Sampling from sharded logits similarly needs exact global top candidates or distributed normalization, depending on the decoding policy.
Differentiate vocabulary-parallel cross-entropy¶
Let rank r own vocabulary set V_r, with logits z_rj for one target token y. Compute global m=max_r max_j z_rj, local s_r=sum_j exp(z_rj-m), and global s=sum_r s_r. Exactly one owner contributes the target logit to z_y=sum_r 1[y in V_r]*z_ry. Then loss=m+log(s)-z_y.
The local derivative is dz_rj=exp(z_rj-m)/s-1[j=y]. For an ignored token, multiply the whole row by zero and exclude it from the supervised denominator. Every vocabulary rank must agree on that mask. Do not divide by vocabulary-parallel degree: the shards partition classes, not independent training examples.
A custom backward can save the normalized local probabilities and avoid differentiating the max collective. Algebraically, the terms involving the stabilizing maximum cancel in the exact log-sum-exp derivative. Label smoothing adds a global class-sum term and must use global vocabulary size, including a stated policy for padded classes. Gathering all logits is unnecessary, but global normalization and target ownership are not optional.
Local GEMM efficiency¶
Increasing tensor-parallel degree divides matrix dimensions. Communication grows as a fraction of step time, and local GEMMs may lose tile efficiency or tensor-core alignment. The useful degree is bounded by:
- hidden, head, and intermediate dimensions;
- batch-token dimension at the target workload;
- link latency and bandwidth;
- memory required for one shard;
- collective overlap opportunity.
Strong scaling eventually stops when smaller local work no longer amortizes collectives. Quantization or faster kernels can move that crossover to a lower degree because compute shrinks while communication may not.
Sequence parallelism¶
Within a tensor-parallel region, LayerNorm and dropout can operate on separate sets of tokens. Sequence parallelism assigns each rank a sequence shard with the full hidden vector for every locally owned token, reducing replicated activation memory. LayerNorm still needs that token's full hidden dimension for its statistics; splitting the hidden dimension would require an additional distributed reduction.
Transitions often use reduce-scatter to produce sequence shards and all-gather before operations that require another layout. It complements tensor parallelism; it does not by itself partition attention's all-token dependency.
Random operations need a logical mask policy. If dropout is intended to be invariant to partition degree, map randomness by global token and feature coordinate, not local rank index. If exact cross-degree identity is not promised, at least preserve distribution and rank consistency.
Context parallelism¶
Context parallelism partitions the entire sequence and its activations across a group. Tokenwise linear and normalization operations run locally. Attention is different: local queries require keys and values from the full logical context.
In training, many query positions are processed together and the backward pass must return attention-gradient contributions to the owning sequence shards. Serving adds a different distinction: prefill and autoregressive decode have different query-to-history ratios and therefore need different context-parallel layouts. The distributed-inference chapter distinguishes prefill context parallelism (PCP) from decode context parallelism (DCP); the two should not be treated as interchangeable settings.
Do not confuse these with phase-specific tensor parallelism: a disaggregated service can run ordinary TP at one degree in its prefill pool and another degree in its decode pool. That changes model-group ownership across a KV handoff, whereas PCP and DCP partition sequence work or history. Part III's “Different TP sizes for prefill and decode” gives a concrete TP=4 to TP=2 handoff.
Implementations may:
- all-gather K/V for attention, paying memory;
- circulate K/V blocks in a ring while updating online attention state;
- exchange queries and accumulate partial results;
- use hierarchical variants aligned with topology.
Ring-style attention keeps only a K/V block at a time and overlaps transfer with attention compute. It needs an online softmax merge so partial score ranges combine exactly. Backward must route gradient contributions to the owners of Q, K, and V.
Causal and ragged context¶
Causal attention has triangular work. A naive contiguous sequence partition gives early query blocks little valid K/V work and late blocks much more, creating imbalance. Zigzag or interleaved partitions can distribute early and late positions across ranks. The mapping must preserve output order and mask semantics.
Packed ragged sequences add boundaries and different lengths. Do not let an attention block cross sequence identity. Cost models should use valid query-key pairs, not padded maximum length alone. Load balance may require bucketing, packing, or a nonuniform block assignment.
Choosing TP versus CP¶
Both can reduce activation memory, but they affect different work. Raising TP shrinks hidden-dimension GEMMs and adds collectives throughout the block. Raising CP shrinks sequence-local activations and attention queries while replicating weights across the CP group and communicating attention context. Because CP ranks process different fragments of one logical sequence rather than independent examples, their parameter-gradient contributions must also be combined before the optimizer step. In a dense layout this reduction commonly spans DP×CP ranks at fixed PP and TP coordinates, or the equivalent sharded group. Its normalization must preserve the intended logical-token objective rather than treating CP as another independent-example dimension.
For very long sequence and already efficient hidden-dimension kernels, CP may preserve better local GEMM shapes than another TP step. For huge hidden layers that do not fit, TP remains necessary. Compose them only after measuring the communication paths and divisibility constraints.
Topology and communicator concurrency¶
TP collectives are frequent and latency-sensitive, so keep TP groups on the fastest local fabric. CP transfers can be large and may span a broader domain if attention compute hides them. When TP and CP overlap, their communicator traffic can contend for the same links.
Schedule group operations in a consistent order across ranks and reserve streams/buffers deliberately. A theoretically independent CP ring and TP all-reduce can deadlock or serialize if communicator creation or launch order differs.
Design Exercises¶
- Derive the collectives in paired column- and row-parallel linear layers.
- How would you implement vocabulary-parallel cross-entropy without gathering logits?
- Why can a larger tensor-parallel degree make both compute and communication efficiency worse?
- Compare sequence parallelism with context parallelism.
- Design causal context partitioning that avoids severe load imbalance.
- How do you choose TP and CP degrees for a long-context transformer?
Worked Solutions¶
1. Paired linear layers¶
Column sharding replicates input X, partitions output columns of A, and produces a sharded feature activation with no forward reduction. A compatible activation and next linear consume that shard. Row sharding of the contraction computes partial full outputs from each input-feature shard, then all-reduces them, or reduce-scatters if the next region accepts a shard. The efficient forward pair avoids gathering the expanded intermediate and communicates at the contraction boundary; during backward, the column-parallel layer also sums its partial input gradients across the tensor-parallel group.
2. Vocabulary-parallel loss¶
Reduce the maximum across vocabulary shards for stable logits, subtract it locally, reduce the local exponential sums into a global denominator, and reduce the target logit from the one owning rank. Each rank can then compute loss and its local gradient shard. Mask padded vocabulary entries and use consistent reduction precision. This avoids materializing batch-by-full-vocabulary logits on every rank.
3. Excess TP¶
Each extra shard reduces local matrix dimensions and may break tile alignment, lower arithmetic intensity, and expose launch overhead. Collectives remain inside every layer; smaller messages can become latency-bound and a higher rank count adds steps or contention. The group also spans slower links once it exceeds a fabric domain. Profile local GEMM efficiency, collective exposure, and memory; stop strong scaling when step time or cost per token worsens.
4. Sequence versus context¶
Sequence parallelism typically shards tokenwise activation regions associated with tensor parallelism, reducing duplicated normalization/dropout activations and using layout transitions around tensor-parallel blocks. Context parallelism partitions full network inputs and activations by sequence. Attention then communicates K/V or Q across context ranks because tokens interact. CP targets long-context activation/attention scaling; SP is a lighter complement to TP.
5. Causal balance¶
Estimate valid query-key work per sequence block. Assign each rank a mixture of early and late query blocks, such as a zigzag mapping, so triangular work sums are similar. Circulate K/V blocks and skip masked interactions, preserve global position and output order, and handle ragged sequence boundaries explicitly. Validate both per-rank attention FLOPs and communication, because equal tokens do not imply equal causal work.
6. TP and CP selection¶
Use enough TP to fit large hidden layers while keeping local GEMMs efficient and groups within fast links. Use CP when sequence-driven activation memory or attention work remains the constraint and another TP step would make hidden-dimension kernels too small. Sweep feasible factor pairs with actual batch/sequence, measure peak memory, TP and CP exposed communication, attention balance, and end-to-end tokens per second, then map groups to noncontending topology paths.
Carry one tensor through tensor-parallel ownership¶
For two ranks and row-vector notation, let X be [B,S,D], W1 be [D,4D], and W2 be [4D,D]. Column-shard W1 so rank r produces U_r of shape [B,S,2D]. Its local nonlinear activation feeds the matching row shard of W2, producing a partial [B,S,D] output. Sum those partial outputs to recover the unsharded result; concatenation would have the wrong semantics.
| Boundary | Rank-local value | Communication obligation |
|---|---|---|
| First projection input | Replicated X | Backward partial dX contributions must be summed |
| Hidden activation | Half of the 4D channels | No gather for a pointwise nonlinearity |
| Second projection output | Partial sum over hidden channels | Forward sum, or reduce-scatter if downstream expects a sequence shard |
| Sequence-sharded residual | A declared slice of B/S with full D | Gather before an operation requiring all input positions, unless its kernel supports the distributed layout |
Context parallel attention has a different dependency: each query needs eligible global K/V contributions. Combining local normalized outputs by ordinary averaging is wrong; combine their normalization statistics as in the online attention derivation. Backward must return remote contributions to the owners of K/V. Shape compatibility alone cannot establish either reduction.