Unit 9 of 11 · about 4 hours · implement

Causal masks, document boundaries, positions and RNG across shards

A shard-local index is not a token's logical position. Correct shapes and collectives can still compute a different objective if masking, rotation or randomness changes with partitioning.

You'll be able to

  • Preserve causal visibility, document isolation and position IDs when tokens cross CP shard boundaries.
  • Implement initialization and dropout checks that distinguish replicas from disjoint shards.
  • Diagnose mask-offset, rotary-table and RNG mismatches with a partition-independent CPU oracle.

Covers

Causal masks, document boundaries and position offsets under CPDropout and initialization RNG consistency across shards
1

Read

In this order, only the parts listed

0 of 4 done

  1. Sequence buffers and the rotary-frequency trapPyTorch Context Parallel Tutorial

    Introduction: buffers, buffer_seq_dims and missing freq_cis warning; Enable Context Parallel: sharding/restoration and output comparison (page read 2026-10-14)

    Read on any machine. With two or more GPUs, run the example with one NCCL rank per GPU and a matching process count. On CPU, use the ring simulation instead. The tutorial compares outputs only, not gradients or dropout replay.

  2. Explicit packed-document visibilityPyTorch 2.14 SDPA - explicit masks and dropout

    Equivalent implementation; boolean mask note; parameters attn_mask, is_causal and dropout_p

    Build the CPU oracle with an explicit allowed-entry mask and zero SDPA dropout. Apply the document-boundary policy from From documents to training examples: packing and loss masks. Do not pass a custom mask to the CP wrapper without separately verifying its support.

  3. Replicated versus model-parallel random streamsMegatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism

    arXiv:1909.08053v4, Appendix B.2, Model Parallel Random Number Generation

  4. Initialize globally, then select the intended shardPicotron - Tensor and Context Parallelism

    ColumnParallelLinear.reset_parameters, RowParallelLinear.reset_parameters and VocabParallelEmbedding.reset_parameters

    Inspect the master-weight generation and shard selection. This depends on matching RNG state across ranks; it is not a broadcast or a guarantee for independently initialized ranks.

2

Focus on

  • Build on RoPE and From documents to training examples: packing and loss masks. Carry global token indices, document IDs, declared position IDs and validity with each shard. For isolated causal documents, allow only valid keys from the same document no later than the query.
  • Slice masks by query and KV ownership, not local triangular indices alone. Slice rotary frequencies using the same position IDs as the unsharded path; zig-zag placement needs index selection rather than one contiguous offset.
  • Replicated values must use identical initialization and replicated dropout masks. Disjoint head/token shards need their own logical random entries, not repeated same-seed local masks. A global mask sliced by logical indices is a small partition-independent oracle, not a scalable implementation.
  • Attention-probability dropout acts on the normalized weights, not on the softmax denominator. For exact replay, key mask entries by logical query/key/head identity or slice one global mask. Same seed alone does not align different draw shapes and orders.
Common mistakes · 3
  • Using is_causal=True on a rectangular local-query/global-key block. SDPA's upper-left alignment does not supply the shard's position offset.
  • Assuming EOS isolates documents or that a loss mask changes attention visibility. The two masks preserve different semantics.
  • Restarting the same seed for each disjoint shard. This can repeat dropout patterns and cannot establish equality with a global random stream.
3

Try it yourself

Closed-book, before checking anything

On CPU, use seed-0 torch.float64 inputs shaped , document IDs [0, 0, 0, 1, 1, 1, 1, 1] and position IDs 0 through 7. Split the sequence into four shards; compare explicit masked attention and gradients against the dense isolated-document oracle. Apply your existing RoPE with the same position IDs and verify sharded reconstruction, then reset each shard's positions to zero and catch the mismatch. For output dropout probability 0.25, generate one global keep mask and scale by ; slicing and reconstructing it must reproduce the dense masked output. Changing a value in the first document must not change the second document's output.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.A query in the second document follows a key from the first. Is the key allowed under the isolated policy?Answer

    No. Causal order is necessary but not sufficient; document identity must also match.

  2. 2.Why is rank-local arange insufficient for rotary positions?Answer

    It loses logical offsets or reordered indices. Each token must receive the same rotation as in the declared unsharded position policy.

  3. 3.Do distinct rank seeds guarantee partition-independent dropout?Answer

    No. They can provide distinct streams for a fixed layout, but changing ownership changes which random entry reaches a logical element. Exact oracle replay needs explicit logical indexing.

You're done when

Your dense/sharded mask, position and dropout checks pass, and reset-position, repeated-mask and cross-document-visibility mutations each fail the intended invariant.

Only when you can do this without notes.

Leads to

Notes

Resources · 4 for this unit, 9 more in the section
  • 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.

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

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

Also in this 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.

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

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