Unit 6 of 11 · about 4 hours · implement

DeviceMesh, tensor-parallel groups and input, output and gradient layouts

A mesh names who participates; placements name what they own. Both must agree with the module's local computation and backward contract.

You'll be able to

  • Construct named CPU device meshes and verify the membership and order of tensor-parallel subgroups.
  • Implement explicit module input/output layout contracts and inspect parameter and gradient placements.
  • Diagnose wrong input ownership, group membership and local-versus-global shape assumptions before they become numerical mismatches.

Covers

DeviceMesh and tensor-parallel process groupsInput, output and gradient layout contracts
1

Read

In this order, only the parts listed

0 of 3 done

  1. Mesh construction and SPMD agreementPyTorch Tensor Parallel Tutorial

    init_device_mesh: SPMD notes and parameters; DeviceMesh methods get_coordinate, get_local_rank and get_group

    Use CPU meshes and Gloo first. Read only these mesh entries, not the full communication reference. For named-axis slicing, use the DP/TP mesh example in the input-ownership guide below.

  2. Parallel styles are boundary contractsPyTorch Tensor Parallel Tutorial

    parallelize_module, ColwiseParallel, RowwiseParallel and PrepareModuleInput: input/output layouts, use_local_output and source-rank semantics

  3. Same inputs within a tensor groupDistributed Training Guide - Chapter 6 Tensor Parallelism

    Ensure all GPUs on a node get the same input: named DP/TP mesh, four-rank table and sampler arguments; Computing throughput with our new world size

    Read the ownership example, not the GPU training script. TP is not inherently node-local: the example chooses that placement.

2

Focus on

  • A named mesh axis identifies ordered process groups, not a tensor dimension. Shard(1) refers to a tensor axis; mesh['tp'] chooses a communicator axis.
  • parallelize_module accepts a one-dimensional mesh. Slice a composed mesh before passing the TP submesh. All ranks must agree on mesh construction and module plans.
  • The default column style interprets ordinary inputs as replicated and returns local feature shards. The default row style interprets ordinary inputs as feature shards and returns replicated outputs. Use use_local_output=False while inspecting logical shapes and placements.
  • TP partners process the same logical examples. Their distinct weight shards contribute to one model result; do not count them as separate data replicas or multiply token throughput by TP degree.
Common mistakes · 3
  • Using global rank as the sampler's data-replica rank. TP partners then consume different inputs while trying to compute one layer.
  • Treating a plain local output shape as the global shape in a head reshape. Keep DTensor metadata or adjust the local reshape explicitly.
  • Passing a two-dimensional mesh directly to parallelize_module. The TP API requires its one-dimensional submesh.
3

Try it yourself

Closed-book, before checking anything

Launch four CPU processes with Gloo and construct init_device_mesh('cpu', (2, 2), mesh_dim_names=('dp', 'tp')). Verify TP groups [0, 1] and [2, 3], and DP groups [0, 2] and [1, 3]. On each TP submesh, parallelize an MLP containing Linear(4, 8), GELU and Linear(8, 4) with column then row styles and DTensor outputs. Transfer identical seed-0 weights and inputs to an ordinary MLP; compare output, input gradient and reconstructed parameter gradients for squared-output mean loss.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.On the reproduced mesh, which ranks share rank 2's TP computation?Answer

    Ranks 2 and 3. Rank 0 is rank 2's DP partner for the same TP-coordinate weight shard, not its TP partner.

  2. 2.Can a local tensor prove that its claimed replica is identical elsewhere?Answer

    No. Validate or synchronize the data across its group. Declaring a replicated layout is a contract, not evidence.

  3. 3.Why keep input-gradient placement in the boundary table?Answer

    The caller must receive the derivative of the intended logical input. A correct forward shard can still return a partial or duplicated gradient incorrectly.

You're done when

Every rank's group manifest matches the hand table, the MLP oracle passes, and each boundary records logical shape, local shape, placement and expected gradient ownership.

Only when you can do this without notes.

Leads to

Notes

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

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

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

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

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