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

0/11

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

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.

  1. 1Build the paired column-to-row MLP in parallel/ with explicit Gloo communication, and reconstruct outputs plus input and weight gradients against the model/ oracle, keeping collective records. Anchor the linear path with the TensorTonic column-parallel problem and the ported Picotron linear tests.
  2. 2Extend the layout to grouped-query attention and SwiGLU in parallel/, preserving query-to-value mapping and matching gate and up shards, checked against the model/ oracle for outputs and gradients. Run the TorchFeather attention and SwiGLU examples, then cover the grouped-query ownership variation the examples omit.
  3. 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.
  4. 4Express the layouts as DTensor placements on a named mesh in comm/, 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.
  5. 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.
  6. 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 plus reports/ separating CPU from GPU evidence.
How to check it
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.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.

  • TorchFeather - TP and Ring Attention Minimal ExamplesTorchFeather

    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.

  • PyTorch Tensor Parallel TutorialPyTorch

    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.

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

    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 Context Parallel TutorialPyTorch

    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

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