Unit 8 of 11 · about 5 hours · derive, implement
Context-parallel sequence ownership and ring attention
CP keeps tokens partitioned through the block instead of gathering the full sequence for TP. Attention must still combine every allowed remote key with each local query.
You'll be able to
- Derive query ownership, KV visits and per-rank forward communication for a context-parallel ring.
- Implement a deterministic ring-attention simulation with dense output and gradient oracles.
- Explain causal load imbalance and distinguish streamed KV storage from gathering all KV.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Context ownership, ring exchange and causal imbalanceUltra-Scale Playbook - Tensor, Sequence and Context Parallelism
Context Parallelism; Ring Attention; Zig-Zag Ring Attention - A balanced compute implementation
Read the ownership and KV-exchange diagrams, not the benchmark plots. The rendered zig-zag heading uses a long dash; locate it by title.
- Incremental attention across a ringRing Attention with Blockwise Transformers for Near-Infinite Context
arXiv:2310.01889v4, Section 3, Ring-Based Blockwise Attention; Algorithm 1; Appendix A,
scan_kv_blockand the forwardlax.scanAlgorithm 1 prints only compute iterations before feedforward and omits the final received block's attention evaluation. Use Appendix A's visits as the coverage contract; an optimized forward ring needs transfers. Leave fused kernels to depth work.
- Four-rank causal ring on CPUTorchFeather - TP and Ring Attention Minimal Examples
rotate_tensors,apply_local_causal_mask,ring_attention,format_ring_scheduleandmainoutput comparisonThis example checks forward output only and waits for communication before the next compute. It is not gradient or overlap evidence. Its final rotation is redundant for forward output.
Focus on
- Keep queries and outputs local; stream KV shards past each query shard. With contiguous sequence ownership, a rank skips wholly future KV blocks and masks its own diagonal block. Reordered ownership requires actual global token indices.
- Reuse Online softmax state, query and key-value tiling and output tolerance. Carry the running maximum, exponential denominator and weighted numerator across KV visits; never softmax each block independently and sum normalized outputs.
- For CP degree , batch , sequence , KV heads , head width and element bytes , one equal KV shard is bytes. A forward ring without the redundant return sends shards per rank, excluding metadata. Backward requires its own communication ledger.
- Remote keys accumulate gradient contributions from multiple query owners. A differentiable simulation can retain that graph; a real P2P implementation must explicitly return and sum remote KV gradients. CP parameter replicas also need globally weighted gradient sums.
Common mistakes · 3
- Summing per-block normalized attention. Each block used a different denominator; merge unnormalized statistics instead.
- Assuming a correct P2P forward pass gives remote KV gradients automatically. Ordinary send/receive calls do not create that distributed autograd path.
- Calling contiguous causal partitioning balanced. Early query shards have fewer allowed KV blocks than late shards; zig-zag placement changes this work distribution.
Try it yourself
Closed-book, before checking anything
torch.float64 query, key and value tensors shaped . Compare outputs and all three input gradients under squared-output sum loss with dense causal attention, at a stated tolerance. Skip wholly masked blocks safely. For the named torch.float32 example, count 128 bytes per KV shard: four rotations send 512 bytes per rank, while three sufficient rotations send 384 bytes. Removing only the final rotation must preserve output.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.How many KV visits and transfers are needed for a noncausal forward ring on four ranks?Answer
Four visits, including the local shard, and three transfers per rank. Returning the last shard to its original owner is unnecessary for the forward output.
2.Under contiguous causal ownership, which rank has more useful work: the first or last?Answer
The last. Its queries can use all earlier blocks; the first rank can use only its own causally masked block.
3.Does CP alone divide parameter memory by its degree?Answer
No. It partitions sequence activations and work while parameters remain replicated over the CP group unless another sharding dimension is added.
Practice
- TorchFeather: ring-attention minimal example
At commit c416ab1, run
torchrun --nproc-per-node 4 --master-port 29653 minimal_examples/ring_attention.pyfrom the repository rootIt uses Gloo on CPU, prints KV-owner schedules and checks output against ordinary causal SDPA. Remove the redundant final rotation and recheck. The section mini-project covers remote-gradient ownership and mask variations in
trainlab; the public example does not test them.
You're done when
The CPU example and your dense forward/gradient simulation agree, every allowed KV block is visited once, and your byte count distinguishes four shipped rotations from three necessary transfers.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 10 more in the 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.
- 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.
- 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.
Also in this 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.
- 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.
- 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 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. - 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.