Unit 10 of 11 · about 4 hours · implement
Divisibility failures and single-process reconstruction oracles
A divisible shape does not prove correct ownership, and an uneven shape is not automatically illegal. Explicit policies and independent oracles separate implementation limits from mathematical limits.
You'll be able to
- Validate sequence, feature and head ownership under an explicit equal-shard, uneven-shard or padding policy.
- Implement independent single-process forward, loss and gradient oracles for TP and CP layouts.
- Catch wrong shard order, repeated bias, invalid targets and missing gradient sums with negative tests.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Uneven DTensor shards and metadata checksPyTorch Tensor Parallel Tutorial
Shard:torch.chunksemantics and experimental uneven-sharding note;DTensor.from_local:run_check,shapeandstrideRead these entries only. Uneven placement support does not imply every module or collective accepts ragged inputs.
- Equal-shard assertions and a linear oracle suitePicotron - Tensor and Context Parallelism
Reference weight transfer; forward comparisons; backward weight, bias and input-gradient checks
Also inspect constructor divisibility assertions in https://github.com/huggingface/picotron/blob/59714b1bf25541dbeb6f5a721ed15f6d0768e786/picotron/tensor_parallel/tensor_parallel.py . Port the CUDA/NCCL harness to CPU/Gloo as described in Practice.
- Dense CP reconstruction and its missing checksTorchFeather - TP and Ring Attention Minimal Examples
main: sequence partition, dense causal SDPA reference and output comparisonReuse the dense reference, not the ring implementation, as the oracle. Add gradients and uneven-token cases in your deterministic simulation; the shipped suite checks neither.
Focus on
- Record the ownership policy before launching. Picotron requires equal linear/vocabulary shards. Whole-head GQA without KV replication requires TP degree to divide query and KV head counts; retain the mapping checks from the attention unit.
- DTensor uneven sharding follows
torch.chunk, not a balanced remainder policy. On four ranks, ten elements have lengths[3, 3, 3, 1]. A custom CP simulation may use different boundaries if it preserves every logical token exactly once. - Reconstruct by logical indices and compare against ordinary PyTorch with the same global weights, inputs, masks, positions and loss denominator. Reusing the sharded mask builder in both paths can hide the same bug.
- Compare input and reconstructed parameter gradients, not only output. Start with zero dropout and
torch.float64; then add indexed RNG replay and justify lower-precision tolerances separately.
Common mistakes · 3
- Assuming
torch.chunkassigns the remainder one element at a time. Its shard boundaries can differ from a balanced split. - Padding tokens without excluding padded keys and padded loss entries. The padded execution then changes the objective.
- Testing only all-ones upstream gradients. Add a nonuniform or nonlinear scalar loss to expose indexing errors.
Try it yourself
Closed-book, before checking anything
[0, 3, 6, 9, 10]. Compare outputs and query/key/value gradients against dense attention under squared-output sum loss. Separately reconstruct torch.arange(10.) from four Gloo DTensor shards and check lengths [3, 3, 3, 1]. Reject four-way equal KV-head sharding for eight query heads and two KV heads. Swap two output shards and remove one gradient contribution; each mutation must fail a specific oracle assertion rather than hang in a collective.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Must a ten-token sequence be rejected on four CP ranks?Answer
Only if the implementation requires equal shards and has no padding policy. An uneven implementation can be correct with explicit boundaries, valid masks and compatible communication.
2.Why can a correct output hide an incorrect backward pass?Answer
Missing input-gradient sums or remote KV-gradient returns do not change forward values. Compare each derivative under the same logical loss.
3.What makes the dense path an independent oracle?Answer
It uses ordinary full tensors and independently declared global visibility and positions. It does not reproduce the partitioned algorithm's ownership logic.
Practice
- Picotron: tensor-parallel linear forward/backward tests
At commit 59714b1, port
tests/test_tensor_parallel.pyand run it with four CPU processesUse CPU tensors, Gloo and
torch.manual_seed(42)instead of the utility import; replace the column test's exacttorch.eqwithtorch.testing.assert_close. Keep identical reference weights and inputs across TP partners. Run the port withtorchrun --nproc-per-node 4and your file path. The section mini-project covers uneven CP, invalid targets, padding and ownership mutations intrainlab.
You're done when
The CPU linear suite and uneven attention output/gradient oracle pass, and each declared illegal layout or injected ownership error fails before performance measurement.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 10 more in the section
- Picotron - Tensor and Context ParallelismHugging Face · required
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 · required
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 · required
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.
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.
- 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.
- 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_parallelwith 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-parallelas a practitioner second view. Its script needs one GPU per rank. - PyTorch Context Parallel TutorialPyTorch · support
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 · 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_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.