Unit 5 of 11 · about 4 hours · explain, implement
DTensor placements and redistribution as collectives
DTensor automates communication from layout metadata. Incorrect metadata can silently turn a valid local tensor into the wrong logical tensor.
You'll be able to
- Explain Replicate, Shard and Partial as ownership states of one logical tensor.
- Implement redistribution checks and predict which transitions require communication.
- Distinguish a logical layout transition from the backend algorithm used to execute it.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Sharded contractions and unreduced resultsHow to Scale Your Model - Chapters 3 and 5
Chapter 3, Computation With Sharded Arrays: Cases 1, 2 and 3
Stop before Case 4. Translate unreduced outputs to
Partial()rather than copying JAX syntax into PyTorch. - PyTorch 2.14 placement and redistribution referencePyTorch Tensor Parallel Tutorial
DTensor Placement Types:
Shard,Replicate,Partial;DTensor.redistributetransition list;DTensor.from_local,to_local,full_tensoranddistribute_tensorStay on one DeviceMesh. Skip private placement types and tensor factory functions.
- A real Partial result before reductionTorchFeather - TP and Ring Attention Minimal Examples
main:down_partialplacement assertion,partial_to_sequenceredistribution anddescribeoutput
Focus on
Replicate()means identical complete values;Shard(dim)means distinct indexed pieces;Partial()means full-shaped contributions awaiting a sum by default. Equal local shapes do not imply equal ownership.- On one mesh axis, shard-to-replicate is an all-gather, partial-to-replicate an all-reduce, and partial-to-shard a reduce-scatter. Replicate-to-shard needs local slicing only.
- Changing the sharded tensor dimension requires a logical all-to-all. In PyTorch 2.14.1 CPU DTensor execution can fall back to all-gather plus chunking; do not assign the ideal all-to-all byte count to that fallback.
distribute_tensorstarts from a global leaf tensor.DTensor.from_localdeclares ownership of existing local values and is differentiable; withrun_check=False, correctness is your responsibility.full_tensor()can communicate.
Common mistakes · 3
- Wrapping different complete values as replicas without synchronizing them. Metadata does not make unequal data identical.
- Gathering Partial values as if they were distinct output features. Partial values must be reduced, not concatenated.
- Calling
full_tensor()only on rank zero. Every participating rank must execute the required collective in the same order.
Try it yourself
Closed-book, before checking anything
torch.arange(16, dtype=torch.float64).reshape(4, 4) with Shard(0). Reconstruct it, redistribute to Shard(1), and reconstruct again. Separately wrap full-shaped local matrices filled with rank plus one using DTensor.from_local and Partial(): reduction must give 10 in every entry. Obtain both replicated and row-sharded reduced layouts and verify the same logical value. Predict each collective before executing it.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.A local row-parallel matmul has the full output shape. Is it replicated?Answer
Not before reduction. Each rank used only part of the contracting dimension, so its result is a Partial contribution.
2.Which placement change can avoid communication in forward?Answer
Replicate-to-Shard: every rank already has all values and can keep its own slice. Backward still follows the chosen gradient-layout contract.
3.Does
to_local()return the global tensor?AnswerOnly when the placement is already replicated. For Shard it returns a shard; for Partial it returns an unreduced contribution.
You're done when
Every reconstruction agrees, your transition table predicts local versus communicating operations, and your logs distinguish logical all-to-all from the CPU fallback.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 10 more in the section
- 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. - 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.
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 - 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. - 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. - 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.