Unit 3 of 11 · about 5 hours · derive, implement

Tensor-parallel attention heads, GQA divisibility and MLP partitioning

Attention heads and MLP features supply independent work, but shared KV heads and paired gates constrain which shards may be kept local.

You'll be able to

  • Partition complete attention heads and matching output-projection columns, preserving forward and backward semantics.
  • Derive legal GQA head layouts and distinguish KV sharding from KV replication.
  • Implement matching gate/up feature shards for a tensor-parallel SwiGLU block.

Covers

Tensor-parallel attention head partitioningGrouped-query attention divisibility constraintsTensor-parallel MLP partitioning
1

Read

In this order, only the parts listed

0 of 4 done

  1. Transformer TP and the GQA qualificationUltra-Scale Playbook - Tensor, Sequence and Context Parallelism

    Tensor parallelism in a transformer block: feedforward and multi-head attention diagrams, MQA/GQA paragraph and KV-head synchronization example

    Stop before the throughput plots. The stated head limit describes whole-head partitioning, not every possible tensor-parallel algorithm.

  2. Whole-head attention partitioningMegatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism

    arXiv:1909.08053v4, Section 3, Figure 3b and Figure 4

  3. Tensor-parallel attention oracleTorchFeather - TP and Ring Attention Minimal Examples

    split_heads, merge_heads, local_attention and main: projection placements through output and all gradient comparisons

  4. Aligned SwiGLU shardsTorchFeather - TP and Ring Attention Minimal Examples

    swiglu; main from gate/up/down distribution through reconstruction and gradient assertions

2

Focus on

  • Build on Multi-head attention: split, merge and gradients, MQA and GQA: sharing keys and values, and The modern decoder block. The new task is ownership and communication, not another attention implementation.
  • For whole-head sharding without KV replication, TP degree divides both and , and divides . Preserve each query's KV mapping when slicing projection rows and output-projection columns.
  • When , a different plan may replicate KV heads among ranks. Their shared projection gradients must then be summed across the replica subgroup; the simple equally sharded plan is not legal.
  • SwiGLU gate and up projections use identical intermediate-feature boundaries. Their product remains sharded; the down projection produces partial residual-width outputs.
Common mistakes · 3
  • Splitting channels through the middle of a head and using the original softmax as if each shard had a complete query/key dot product.
  • Dividing query heads but forgetting KV-head constraints. Shapes may be divisible while query-to-KV ownership is wrong.
  • Pairing differently ordered gate and up shards. Their elementwise product then changes the MLP.
3

Try it yourself

Closed-book, before checking anything

Run the two named CPU examples below, then redraw their local projection and head shapes without notes. Extend a deterministic simulation to , , head width 4 and TP degree 2: each rank owns four contiguous query heads and their one KV head. With identical seed-0 torch.float64 inputs and zero dropout, concatenated local attention must match the full GQA oracle. Reject degree 4 under the no-KV-replication policy.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Can eight query heads and two KV heads use four equally KV-sharded ranks?Answer

    Not with complete KV heads and no replication. Two KV heads cannot give every rank one shard. A replicated-KV implementation is a separate plan with shared-gradient reduction.

  2. 2.Why is an output-projection reduction still needed after local head attention?Answer

    Each head subset contributes through a different set of output-projection input columns to the same residual-width output. Those partial contributions must be summed.

  3. 3.Which intermediate dimension must both SwiGLU branches shard identically?Answer

    The expanded feedforward feature dimension. Each gate value must multiply the up value for the same feature before the row-parallel down projection.

5

Practice

  • TorchFeather: tensor-parallel SwiGLU and attention minimal examples

    Run torchrun --nproc-per-node 2 --master-port 29652 minimal_examples/tp_attention.py and torchrun --nproc-per-node 2 --master-port 29651 minimal_examples/tp_swiglu.py from the repository root at commit c416ab1

    Both use Gloo on CPU and compare outputs, loss, input gradients, norm gradients and projection gradients with ordinary tensors. They cover MHA, not GQA. The section mini-project covers the GQA ownership variation in trainlab.

You're done when

Both named examples pass, your GQA reconstruction passes, and you identify illegal head plans before launching collectives.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 10 more in the section
  • Ultra-Scale Playbook - Tensor, Sequence and Context ParallelismHugging Face · primary

    Read Tensor Parallelism, Tensor parallelism in a transformer block, Sequence parallelism, Context Parallelism, Ring Attention and Zig-Zag Ring Attention in order. Redraw every tensor shape and collective for a concrete batch, sequence, hidden and head configuration; the context-parallel section gives no byte formula, so derive one yourself.

  • Megatron-LM: Training Multi-Billion Parameter Language Models Using Model ParallelismShoeybi et al. (2019) · required

    Read the model-parallel section: the and operators, MLP and self-attention partitioning, and the parallel embedding and cross-entropy. Derive each forward and backward collective before reading the code.

  • TorchFeather - TP and Ring Attention Minimal ExamplesTorchFeather · required

    Run minimal_examples/block_matrix_multiply.py, then tp_swiglu.py and tp_attention.py with 2 processes and ring_attention.py with 4, all on Gloo on CPU; each checks its output and gradients against ordinary tensors. Change one placement or mask and watch the check fail.

Also in this section

  • Reducing Activation Recomputation in Large Transformer ModelsKorthikanti et al. (MLSys 2023) · support

    Read the sequence-parallelism and selective-recomputation sections and the activation-memory equations. Check them against your own per-layer memory derivation.

  • Ring Attention with Blockwise Transformers for Near-Infinite ContextLiu et al. (ICLR 2024) · support

    Read the ring algorithm and its overlap condition, then compare it with all-gather context parallelism and DeepSpeed-Ulysses (arXiv 2309.14509) when choosing a context-parallel scheme.

  • Picotron - Tensor and Context ParallelismHugging Face · required

    Read tensor_parallel/tensor_parallel.py, tp_communications.py, context_parallel/context_parallel.py and cp_communications.py. tests/test_tensor_parallel.py hardcodes NCCL and CUDA; port it to Gloo on CPU and compare with torch.testing.assert_close, because its exact equality check fails when sharded and full matmuls round differently.

  • Picotron Tutorial - Step 4 and Part 2 VideoHugging Face · support

    Follow step4_tensor_parallel with its diff and the Part 2 video. Write your own column and row layers first.

  • Distributed Training Guide - Chapter 6 Tensor ParallelismLambda Labs · support

    Read colwise and rowwise linear layers, embeddings, norms, loss parallelism and throughput accounting in 06-tensor-parallel as a practitioner second view. Its script needs one GPU per rank.

  • PyTorch Tensor Parallel TutorialPyTorch · required

    Use the tutorial to map ColwiseParallel, RowwiseParallel, SequenceParallel, PrepareModuleInput and loss parallelism to the ownership model you derived, with the DTensor reference at https://docs.pytorch.org/docs/2.14/distributed.tensor.html for Shard, Replicate, Partial and redistribute. Add assertions around every layout transition.

  • PyTorch Context Parallel TutorialPyTorch · support

    Read the context_parallel API, buffer sequence dimensions, rotation methods and the rotary-frequency trap. It needs CUDA GPUs and NCCL; on CPU, keep to the TorchFeather ring-attention example.

  • How to Scale Your Model - Chapters 3 and 5Google DeepMind · support

    Solve the sharded-matrix multiplication layouts in Chapter 3 and the Megatron sharding section of Chapter 5. Translate the results into PyTorch DTensor placements and collective counts.

  • TensorTonic - Reconstruct a Column-Parallel MLP LayerTensorTonic · support

    Solve Reconstruct a Column-Parallel MLP Layer, including its uneven-shard cases.

  • PyTorch 2.14 SDPA - explicit masks and dropoutPyTorch · reference

    Use the equivalent attention implementation and attn_mask/dropout_p contract to build a CPU packed-document oracle before translating masks to context-parallel blocks. Do not assume the experimental CP wrapper supports every SDPA mask.