Tensor, Sequence and Context Parallelism
Model parallelism splits one layer or sequence across ranks. Correct layouts, partial reductions, RNG and loss ownership matter more than memorizing wrapper APIs.
Section 5 of 10 · 11 units · about 47 hours
By the end you can Implement and gradient-test column and row parallel linear layers plus a small context-parallel attention path, reconstruct the single-process result, and defend the collective and memory cost of each layout.
Units
- Column- and row-parallel linear layers and communication cancellation5h
- Vocabulary-parallel embeddings, output projection and cross-entropy5h
- Tensor-parallel attention heads, GQA divisibility and MLP partitioning5h
- Sequence-parallel normalization and residual layouts3h
- DTensor placements and redistribution as collectives4h
- DeviceMesh, tensor-parallel groups and input, output and gradient layouts4h
- Tensor-parallel memory and communication volume by layer4h
- Context-parallel sequence ownership and ring attention5h
- Causal masks, document boundaries, positions and RNG across shards4h
- Divisibility failures and single-process reconstruction oracles4h
- Choosing TP and CP degrees, and asynchronous tensor parallelism4h
Build it
Mini project · about 12 to 16 hours
Tensor, sequence and context parallelism with owned layouts
Extend trainlab with tensor, sequence and context parallel mechanisms over the tiny transformer, each checked against a single-process oracle on CPU. Sharded layouts, collective records and timing models make degree choices testable instead of inherited.
- 1Build the paired column-to-row MLP in
parallel/with explicit Gloo communication, and reconstruct outputs plus input and weight gradients against themodel/oracle, keeping collective records. Anchor the linear path with the TensorTonic column-parallel problem and the ported Picotron linear tests. - 2Extend the layout to grouped-query attention and SwiGLU in
parallel/, preserving query-to-value mapping and matching gate and up shards, checked against themodel/oracle for outputs and gradients. Run the TorchFeather attention and SwiGLU examples, then cover the grouped-query ownership variation the examples omit. - 3Add vocabulary-parallel embedding and sharded cross-entropy in
parallel/with per-token reductions, tied-weight accumulation and range checks against ordinary cross-entropy. Add sequence-sharded norms and residuals with per-rank gain-gradient sums, layout assertions and saved-versus-temporary accounting. - 4Express the layouts as
DTensorplacements on a named mesh incomm/, with group manifests, boundary assertions and forward and backward oracle comparisons. Keep a transition suite that reconstructs each layout and records the backend-aware collective behind every communicating move. - 5Build the ring-attention path in
parallel/with streamed key-value visits, online softmax state and remote-gradient returns, removing the redundant rotation and rechecking outputs and gradients. Cover packed-document masks, rotary alignment and indexed dropout replay with negative cases plus uneven-shard, padding, invalid-target and ownership-mutation oracles. - 6Derive the per-rank ledger in
plan/after working the JAX matmul-strategies question. Tabulate feasible degree candidates with a bandwidth-sensitive timing model and matched correctness and timing records for the sync and async paths, with GPU overlap traces only with two or more GPUs.
What you hand in
- The
parallel/tensor, sequence and context mechanisms with oracles, manifests and collective records. - The
plan/ledger, candidate table and timing model with synchronous and asynchronous records. tests/replaying every oracle and negative case plusreports/separating CPU from GPU evidence.
How to check it
- Self-grade with the rubric below
- TensorTonic: Reconstruct a Column-Parallel MLP Layer
Pass the public cases in your harness; keep rank-ordered outputs without claiming collectives.
- TorchFeather tensor-parallel attention example
Run the CPU comparison; extend to grouped-query ownership in trainlab.
- TorchFeather tensor-parallel SwiGLU example
Run the CPU comparison; keep gate and up shards aligned.
- TorchFeather ring-attention minimal example
Recheck outputs after removing the redundant rotation; add gradient ownership.
- Picotron tensor-parallel linear tests
Port to CPU processes with modern assertions; keep shared reference weights.
- How to Scale Your Model matmul strategies question
Derive both strategies on paper before opening the printed solution.
How it's graded
Paired MLP correctness
Pass: Outputs plus input and weight gradients match the oracle, and collective records name each communicating move.
Great: A second sharding or activation choice replays cleanly, and one seeded defect shows which check catches it.
Vocabulary and sequence layouts
Pass: Sharded loss, tied weights, norms and residuals match oracles, with gain sums and accounting kept.
Great: Reset-position and repeated-mask mutations fail named assertions, and padding policy is exercised.
Ring and oracle discipline
Pass: Ring outputs and gradients match dense attention, uneven and empty cases pass, and illegal layouts are rejected.
Great: Ownership mutations fail specific assertions, and the redundant rotation removal keeps the match.
Ledger and degree choice
Pass: The ledger covers parameters, activations and collectives, separating payload, traffic, saved and peak memory.
Great: Synchronous and asynchronous paths match oracles, candidates name their limiting constraint, and GPU traces report exposed communication honestly.
Resources
- Ultra-Scale Playbook - Tensor, Sequence and Context ParallelismHugging Face
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)
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
Read
tensor_parallel/tensor_parallel.py,tp_communications.py,context_parallel/context_parallel.pyandcp_communications.py.tests/test_tensor_parallel.pyhardcodes NCCL and CUDA; port it to Gloo on CPU and compare withtorch.testing.assert_close, because its exact equality check fails when sharded and full matmuls round differently. - TorchFeather - TP and Ring Attention Minimal ExamplesTorchFeather
Run
minimal_examples/block_matrix_multiply.py, thentp_swiglu.pyandtp_attention.pywith 2 processes andring_attention.pywith 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. - PyTorch Tensor Parallel TutorialPyTorch
Use the tutorial to map
ColwiseParallel,RowwiseParallel,SequenceParallel,PrepareModuleInputand loss parallelism to the ownership model you derived, with the DTensor reference at https://docs.pytorch.org/docs/2.14/distributed.tensor.html forShard,Replicate,Partialandredistribute. Add assertions around every layout transition. - Reducing Activation Recomputation in Large Transformer ModelsKorthikanti et al. (MLSys 2023)
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)
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
Follow
step4_tensor_parallelwith its diff and the Part 2 video. Write your own column and row layers first. - Distributed Training Guide - Chapter 6 Tensor ParallelismLambda Labs
Read colwise and rowwise linear layers, embeddings, norms, loss parallelism and throughput accounting in
06-tensor-parallelas a practitioner second view. Its script needs one GPU per rank. - PyTorch Context Parallel TutorialPyTorch
Read the
context_parallelAPI, 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
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
Solve Reconstruct a Column-Parallel MLP Layer, including its uneven-shard cases.
- PyTorch 2.14 SDPA - explicit masks and dropoutPyTorch
Use the equivalent attention implementation and
attn_mask/dropout_pcontract 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.