Unit 2 of 11 · about 5 hours · derive, implement
Vocabulary-parallel embeddings, output projection and cross-entropy
Vocabulary logits can be much larger than the residual stream. Reducing per-token statistics avoids gathering them, but only if target ownership and the loss denominator remain correct.
You'll be able to
- Derive stable vocabulary-parallel cross-entropy and its local logit gradients without gathering full logits.
- Implement vocabulary-range embedding ownership and preserve tied embedding/output weights.
- Compare a CPU sharded loss with ordinary cross-entropy, then map it to PyTorch 2.14 loss parallelism.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Sharded input and output embeddingsMegatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism
arXiv:1909.08053v4, Section 3, paragraphs beginning 'The transformer language model has an output embedding' through the fused cross-entropy discussion
- Vocabulary ranges and masked lookupPicotron - Tensor and Context Parallelism
VocabParallelEmbedding, especially_vocab_range_from_global_vocab_sizeandforward;apply_tensor_parallelfinal-projection replacementUse default dense lookup without padding or renormalization. Picotron gathers the final logits; use the loss-parallel route below to avoid that gather.
- Loss-parallel layouts and current contractPyTorch Tensor Parallel Tutorial
Apply Loss Parallel, Figure 2 and final-projection plan (page read 2026-10-14)
Open https://docs.pytorch.org/docs/2.14/distributed.tensor.parallel.html#torch.distributed.tensor.parallel.loss_parallel for the 2.14 contract. Keep the first implementation on a one-dimensional CPU mesh with class-index targets and no label smoothing.
Focus on
- Build on Stable softmax, cross-entropy and loss reductions. For a token, reduce local maxima to , then sum local exponentials into . Reduce the target logit from its unique owner; loss is .
- Each vocabulary shard computes its part of . Only the target owner subtracts one. Apply the same valid-token denominator as the unsharded loss.
- Embedding ranks own disjoint vocabulary ranges. Nonowners contribute zero; summation reconstructs each lookup. Tied embeddings and output projections must share the same trainable shard, accumulating both gradient contributions once.
loss_parallel()requires class-sharded DTensor logits and backward inside the context. PyTorch 2.14 supports mean reduction only on a one-dimensional mesh; multi-dimensional token sharding needs sums or unreduced losses and an explicit global denominator.
Common mistakes · 3
- Normalizing each vocabulary shard separately. That produces multiple distributions rather than one distribution over the full vocabulary.
- Treating every nonlocal token as an invalid global token. Validate the global ID first, then mask nonownership before lookup.
- Padding the vocabulary and leaving padded logits in the softmax. Those classes change the denominator unless explicitly excluded.
Try it yourself
Closed-book, before checking anything
torch.tensor([[1000., 1001., -1000., 999.], [2., -1., 0., 3.]], dtype=torch.float64) into two class shards and use targets [1, 3]. Compute the max, exponential-sum and target-owner reductions, then the mean loss and analytic logit gradients. Match ordinary torch.nn.functional.cross_entropy. Repeat with class-sharded DTensors on two CPU processes using Gloo and loss_parallel(), comparing loss and reconstructed gradients.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why must the maximum be global before summing exponentials?Answer
All shard sums must use the same exponential scale. Independent local maxima require additional rescaling before their sums can be combined.
2.Does averaging local vocabulary losses recover cross-entropy?Answer
No. Vocabulary shards partition classes for the same tokens. Combine their normalization statistics first; average only over the declared valid tokens.
3.What gradient reaches a tied vocabulary shard?Answer
The sum of its input-embedding and output-projection contributions. Two independently updated copies are not weight tying.
You're done when
Your sharded loss and logit gradients match the ordinary oracle, lookup ownership passes at both ends of each range, and a tied-weight test accumulates both uses into one shard.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 10 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.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. - 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.
- 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. - 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. - 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.