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

Column- and row-parallel linear layers and communication cancellation

TP changes which rank computes each part of one layer. A plausible forward output can hide a missing input-gradient reduction or a repeated bias.

You'll be able to

  • Derive local outputs, weight gradients and input-gradient reductions for column- and row-parallel linear layers.
  • Implement a paired sharded MLP and reconstruct its forward and backward results against an unsharded oracle.
  • Explain why keeping the intermediate features sharded removes communication between the two projections.

Covers

Column-parallel linear layers and output ownershipRow-parallel linear layers and partial-result reductionColwise-to-rowwise communication cancellation
1

Read

In this order, only the parts listed

0 of 3 done

  1. Two matrix partitions and their compositionUltra-Scale Playbook - Tensor, Sequence and Context Parallelism

    Tensor Parallelism; Tensor parallelism in a transformer block, opening feedforward example

    Stop before the attention discussion. Do not gather column outputs when the next row-parallel layer consumes the same feature shards.

  2. Megatron-LM: forward and backward communicationMegatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism

    arXiv:1909.08053v4, Section 3, equations 1 to 3, Figure 3a and Code 1

    Read through the MLP derivation. Leave self-attention and vocabulary sharding to the next units.

  3. Weight storage and conjugate autograd operatorsPicotron - Tensor and Context Parallelism

    ColumnParallelLinear and RowParallelLinear, including initialization and forward

    Also open https://github.com/huggingface/picotron/blob/59714b1bf25541dbeb6f5a721ed15f6d0768e786/picotron/tensor_parallel/tp_communications.py and read CopyToModelParallelRegion, ReduceFromModelParallelRegion and GatherFromModelParallelRegion. Defer the asynchronous operator.

2

Focus on

  • Use the paper's convention , then translate to PyTorch's stored of shape . Column parallelism shards stored rows; row parallelism shards stored columns.
  • Column outputs own distinct features. Their input gradients are partial contributions that must be summed. Row outputs are full-shaped partial sums; their forward reduction must happen before adding a replicated bias.
  • An elementwise activation preserves feature ownership. Pair matching column output shards with row input shards instead of gathering and splitting again.
  • Megatron's identity-backward reduction assumes replicated outputs represent one logical loss, not separate independent losses on every TP rank. Reconstruct gradients under that contract.
Common mistakes · 3
  • Applying GELU to each row-parallel partial sum before reduction. Nonlinearity does not commute with summation.
  • Adding a full output bias on every rank before a sum. The result contains one bias per rank.
  • Comparing bitwise equality after changing GEMM partitioning. Floating-point reduction order changes; use a justified tolerance.
3

Try it yourself

Closed-book, before checking anything

Closed-book, derive and simulate a bias-free column-GELU-row MLP on CPU with two shards, shaped , first stored weight and second . Generate all tensors once with seed 0 in torch.float64, slice the same weights, and use squared-output mean loss. Match output, input gradient and both reconstructed weight gradients with torch.testing.assert_close. Then add one shared output bias after summation.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Why does the first projection need a backward sum even though its forward pass is local?Answer

    Each feature shard contributes to the same input. The full input gradient is the sum of those contributions.

  2. 2.For stored weights shaped and on two ranks, what shapes stay local?Answer

    The first weight is , the intermediate is , and the second weight is . Each second-projection partial output is and must be summed.

  3. 3.Does column-to-row pairing eliminate all communication?Answer

    No. It eliminates the intermediate gather. With replicated block boundaries, the row output still needs a forward sum and the column input gradient a backward sum.

5

Practice

  • TensorTonic: Reconstruct a Column-Parallel MLP Layer

    Implement column_parallel_mlp(x, weight_shards, bias_shards); public cases: Two single-column shards, Uneven biased shards and One shard

    This free problem reconstructs a linear projection only, despite its title. Its weights use input-by-output storage. It checks rank-ordered outputs, not collectives or gradients. The section mini-project covers the paired TP MLP, explicit communication and gradient oracle in trainlab.

You're done when

The three public cases and your paired MLP output and gradient checks pass, and you draw both passes with no intermediate gather and exactly one output bias.

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.

  • 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.

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 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.

  • 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.

  • 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.