Repository navigation
AutoTP: sequence sharding for training - #8860
pengdurice wants to merge 7 commits into
Conversation
…rding`) Signed-off-by: pengdurice <pengduhit@gmail.com>
Two problems when decoder layers are recomputed in backward (transformers 5 gradient_checkpointing_enable() uses non-reentrant checkpointing): - A block switched from separate collectives to the fused column path on its second call. Under checkpointing the second call is the backward recomputation of the first micro-step, which then saves different tensors than the forward pass: CheckpointError at ZeRO-1/2 in the first backward. Blocks now switch from the model's second forward pass on, counted by a pre-hook on the model. - ZeRO-3 replaces torch.nn.functional.linear with a custom autograd function that saves the weight, and inside a non-reentrant checkpoint PyTorch then does not call the weight's tensor hooks (torch 2.8). A linear weight left replicated in the decoder layers kept its partial gradient. At ZeRO-3 the gradient is now summed in a post-accumulate hook, registered before ZeRO-3's. Tests: every sequence-sharding mode with and without checkpointing at ZeRO 1 and 3, and a model with only attention sharded (replicated MLP linears) under checkpointing at ZeRO 1 and 3. Signed-off-by: pengdurice <pengduhit@gmail.com>
… of the block In its first forward pass a sequence-sharded block hands the gathered block input to every column-parallel linear of the block, so that a linear reading it records itself. A linear that never reads it (it reads another tensor of the block, or the block uses its weight without calling it, as an absorbed MLA attention does with kv_b_proj) kept that reference until the next first pass, which never comes: one copy of the whole sequence's hidden states per decoder layer stayed allocated. A forward hook at the end of each block now drops it. Signed-off-by: pengdurice <pengduhit@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: pengdurice <pengduhit@gmail.com>
…ient sum - Reject AutoEP MoE layers inside the decoder layers. - At ZeRO 0-2, raise in backward when a replicated parameter's gradient sum did not run (PyTorch skips the tensor hooks of a parameter a custom autograd function saves under non-reentrant checkpointing). - Keep column weights that have tensor hooks on the plain path; skip the weight-gradient GEMM of frozen weights. - Add frozen replicated parameters to AutoTP's frozen list, so unfreezing them raises. - Pass the layer's own training mode to add_bias (deepspeedai#8851). - Tests: ZeRO-2 cases, the weight-hook test and three rejection tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: pengdurice <pengduhit@gmail.com>
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3708d0511b
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| for name in row_layers: | ||
| if "." not in name: | ||
| raise ValueError(f"AutoTP sequence sharding: row-parallel linear {name!r} has no parent module") | ||
| parent = name.rsplit(".", 1)[0] |
There was a problem hiding this comment.
Reject nested block parents before adding hooks
In a layout where a row-parallel projection is a direct child of the decoder layer (HF OPT's fc2), this makes the entire decoder layer a block while its self_attn is another nested block. Both pre-hooks then all-gather the same activation (the outer pre-hook also runs before the entry scatter registered below), and fc2 reduce-scatters before the decoder layer's residual add, so enabling this option on an otherwise valid AutoTP OPT plan produces sequence/mask or residual shape failures. Validate that inferred blocks are disjoint terminal attention/MLP modules, or reject this layout.
Useful? React with 👍 / 👎.
| def gather(x): | ||
| # Fused only from the pass after the one that recorded the readers: activation checkpointing recomputes | ||
| # the block in backward within the same pass, and the recomputation must save what the forward saved. | ||
| if overlap and state.learned_in is not None and state.passes[0] > state.learned_in and state.can_fuse(): |
There was a problem hiding this comment.
Preserve per-forward mode during checkpoint recomputation
With non-reentrant activation checkpointing and two model forwards before one backward (for example, a contrastive/DPO loss), the first forward records the plain path at pass 1, the second increments passes, and recomputation of the first forward now satisfies this condition and takes ColumnGroupFromSequenceShards. That recomputation saves a different tensor set from the original plain matmuls, so checkpoint backward raises a metadata/count error or reconstructs the wrong graph. Track the mode per outstanding forward or delay fusion until the learning forward has completed backward.
Useful? React with 👍 / 👎.
|
|
||
| def hook(grad): | ||
| grad = grad.contiguous() | ||
| dist.all_reduce(grad, group=group) |
There was a problem hiding this comment.
Run replicated-gradient collectives on every rank
When an accepted layout leaves a replicated token-conditional module outside the TP blocks (for example, an attention-only partition with a sparse MLP that skips empty experts), sequence sharding gives ranks different tokens, so a parameter can be used on one rank but unused on another. A parameter hook runs only where its gradient is produced, making this all_reduce—and the ZeRO-3 variant in make_accumulated_grad_hook—rank-asymmetric; the run hangs or reduces unrelated gradients if branches differ. Drive these reductions from a schedule reached by every rank with zero gradients for locally unused parameters, or reject such modules.
Useful? React with 👍 / 👎.
- Reject a block that is a whole decoder layer or contains another block (a row-parallel linear directly in the decoder layer, as OPT's fc2). - Reject routed MoE layers in the decoder layers: the TP ranks hold different tokens, so they could use different experts and a gradient sum or block gather on some ranks only would hang. Document that replicated modules outside the blocks must use all their parameters on every rank. - Switch a block to the one-autograd-node path only when a forward pass starts after a backward, so a checkpoint recomputation takes the path its forward took, also with several forward passes before one backward. - Tests: an OPT layout, a routed MoE layer, and two forward passes before each backward with checkpointing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: pengdurice <pengduhit@gmail.com>
AutoTP: sequence sharding for training (
tensor_parallel.sequence_sharding)Part of: #8672 (Q4 2026 roadmap), "Enable training of large scale models".
Summary
AutoTP training today runs the norms, residual adds and other token-wise ops of every decoder layer on the whole
sequence on every tensor-parallel rank, keeps their activations at full size, and makes one all-reduce per
column-parallel linear in backward plus one per row-parallel linear in forward (7 per Qwen3 layer), all on the compute
stream. This PR adds
tensor_parallel.sequence_sharding(defaultfalse): the hidden states between the attentionand MLP blocks are split along the sequence over the TP ranks, as in Megatron-LM's sequence parallelism.
sequence_sharding_overlap(defaulttrue): the column-parallel linears that read a block input run in oneautograd node; backward reduce-scatters their summed input gradient while the weight-gradient GEMMs run; only this
rank's part of the input is saved for backward and gathered again there.
The name avoids "sequence parallel", which in DeepSpeed means Ulysses (
sequence_parallel_size), a differentscheme; the two are not combined.
Motivation
Today AutoTP training makes 7 all-reduces per Qwen3 layer on the compute stream (5 column-parallel input gradients in
backward, 2 row-parallel outputs in forward). On Qwen3-32B with activation recompute on 2 nodes, AutoTP got 62% slower
from TP 2 to TP 8 (Megatron-LM: 19%), and its best TP layout was 1.42x slower than Megatron-LM's best.
This PR is one of four. The others add copy-engine collectives for sequence sharding,
vocab_parallel_embedding(#8859), and ZeRO-1/2
overlap_param_gather. The table shows where DeepSpeed ends up with them: the Qwen2.5-72B andQwen3-32B runs use all four options, the Qwen3-8B run uses only
overlap_param_gather. Each framework ran at its bestmeasured setting, all three in one allocation per model, 8 x H200 per node, random weights, 8,192-token sequences,
bf16 compute, fp32 master weights and Adam states, bf16 gradient reduction, no recompute; seconds per step, mean of
steps 4-13; MFU at 989 TFLOPS per GPU. DeepSpeed runs the Hugging Face model with Liger kernels for RMSNorm, rotary
embedding and SwiGLU (applied by our benchmark script, not part of these PRs; without them DeepSpeed was 4.02 against
Megatron-LM's 3.32 s per step on Qwen3-8B without TP). Megatron-LM uses Transformer Engine's fused kernels, TorchTitan
its compile regions.
AutoTP before these options: Qwen2.5-72B 25.22 s (micro-batch 1; micro-batch 2 did not fit), Qwen3-32B 20.54 s
(TP 8, micro-batch 1).
Results
Measured with the first commit of this PR on master cc7b512 (2026-10-19), 8 x H200 per node, bf16 compute (torch
autocast), fp32 master weights and Adam states, 8,192-token sequences, no activation recompute,
vocab_parallel_lm_headwith the Liger vocabulary-parallel loss, and Liger kernels for RMSNorm, rotary embedding andSwiGLU (applied by our benchmark script, not part of this PR). Master and this branch ran in one allocation for each
model. Step time is the mean of steps 4-13 of 13.
The loss the benchmark script prints after the last step (
global_loss) is within 2.5e-4 of master's in all threesetups.
The later commits change the activation-checkpointing path, free a gathered block input that a block never reads, and
add checks. In runs without activation checkpointing they add only one Python hook call per replicated parameter per
backward at ZeRO stages 0-2. These step times were not measured again after merging master 4a9efc1.
Design
apply_autotp_sequence_shardingruns infinalize_autotpafter AutoTP has replaced thelinears. A block is the parent module of a row-parallel linear (
self_attn,mlp). Forward pre-hooks on the blocksgather their inputs; a pre-hook on the first decoder layer splits the hidden states and a forward hook on the last
gathers them again, so the final norm, output layer and loss see the whole sequence (combine with
vocab_parallel_lm_headto keep those sharded too).deepspeed.initialize(): every TP linear in the decoder layers belongs to a block; the blocks are inone numbered layer list and every layer has one; no column-parallel layer gathers its output; no DeepCompile
autotppass; no AutoTP layer class with its ownforward(LinearAllreduceWithReplicatedInput,LmHeadLinearAllreduce,SubParamLinearAllreduce,SubParamLinearLayer), which would keep its all-reduce; noAutoEP MoE layer in the decoder layers (AutoEP + AutoTP folding expects every TP rank to hold the whole sequence).
The sequence length must be divisible by the TP size (checked in the forward pass).
each token alone. An MLP left unsharded is fine; an attention module left unsharded would attend over the wrong
tokens. The tutorial says to shard every attention module.
work on contiguous buffers and need no reordering copy at batch > 1. The ops between blocks act on each token
alone, so any split is valid.
this rank's tokens, so their gradients are summed over the TP group (skipped where AutoTP already registered a sum).
checked) stops calling a parameter's tensor hooks once a custom autograd function saves that parameter inside
non-reentrant activation checkpointing, as fused norm kernels do. A post-accumulate hook therefore checks that
the sum ran and raises otherwise, instead of training on a partial gradient.
torch.nn.functional.linearby a custom autograd function, so the tensor hook would be skipped undercheckpointing for every replicated linear weight; ZeRO-3 reduces and frees each micro-step's gradient in its own
post-accumulate hook, so this hook sees exactly one micro-step.
frozen replicated parameters, so unfreezing one after
deepspeed.initialize()raises at the next backward.weights with tensor hooks, such as the sum of GPTBigCode's shared key/value rows that Sum GPTBigCode's shared key/value gradient across tensor-parallel ranks #8928 added to
fused_LinearLayer: the one-autograd-node path saves the weights, and PyTorch would then skip those hooks undernon-reentrant activation checkpointing.
uses the one-autograd-node path only from the next pass, so the backward recomputation of a layer saves the same
tensors as its forward pass.
layers.pygets one branch inLinearLayer.forward, one inLinearAllreduce.forwardandtwo class attributes;
engine.py11 lines infinalize_autotp; the rest is a new module.Duplicate check
Searched open issues and pull requests on 2026-10-18, 2026-10-19 and again on 2026-11-18 for "AutoTP sequence
parallel", "tensor parallel reduce-scatter sequence" and
sequence_sharding: none adds sequence sharding to AutoTP.DeepSpeed's sequence-parallel work (Ulysses, ALST, AutoSP) splits attention over ranks of its own and is a different
scheme.
Related pull requests:
add_biasin itsLinearLayer.forwardbranch, as the other branches do.vocab_parallel_embedding) adds lines next to this PR's infinalize_autotp,tensor_parallel/config.pyand both docs pages. Whichever of the two merges second needs a small rebase.
Sibling paths checked: ZeRO stages 1, 2 and 3 (all three in the unit tests). AutoTP's own gradient sum for replicated
parameters marked
grad_allreduce(register_replicated_grad_hooks, for example Qwen3'sq_norm/k_norm) uses thesame tensor hooks on master, so it has the same exposure to fused kernels under non-reentrant checkpointing. This PR
does not change it.
The change
deepspeed/module_inject/autotp_sequence_sharding.py(new, 459 lines)ScatterToSequenceShards,GatherFromSequenceShards,GatherToTensorParallelBlock,ReduceScatterFromTensorParallelBlock,ColumnGroupFromSequenceShards), the block hooks, the gradient hooks andapply_autotp_sequence_shardingdeepspeed/module_inject/layers.py(+19, -2)LinearLayer.forwardandLinearAllreduce.forward; two class attributes onTensorParallel_Layerdeepspeed/runtime/engine.py(+11)finalize_autotp; frozen replicated parameters join AutoTP's listdeepspeed/runtime/tensor_parallel/config.py(+15)sequence_sharding,sequence_sharding_overlapdocs/_pages/config-json.md,docs/_tutorials/autotp-training.mdtests/unit/v1/autotp/test_autotp_sequence_sharding.py(new)Tests
tests/unit/v1/autotp/test_autotp_sequence_sharding.py, 21 tests, 2 ranks with AutoTP 2 on a 2-layer Qwen3 (or aGLM-4.5-style MoE model) built from a config:
TestAutoTPSequenceShardingplain/overlapx activation checkpointing off / on = 12TestAutoTPSequenceShardingReplicatedMLPTestAutoTPSequenceShardingUnreadColumnTestAutoTPSequenceShardingWeightHooksTestAutoTPSequenceShardingRejectsdeepspeed.initialize(); a decoder norm that applies its weight through a custom autograd function under checkpointing at ZeRO-1 makes backward raise; a decoder norm weight frozen atdeepspeed.initialize()and unfrozen afterwards makes backward raiseThe last four rejection and hook tests fail on this branch before the review fixes (same hardware, see the control
row below), so they catch the problems those fixes address.
Every test file that uses a function this PR changes was run (found by searching
tests/forLinearLayer,LinearAllreduce,TensorParallel_Layer,autotp_size,TPTrainingConfig,tp_model_initand the other changednames). Three files that only matched an unrelated
add_biasof the inference kernels, andtests/unit/hybrid_engine/test_he_lora.py, which only matched its ownLinearLayer_LoRAclass, were not run.All runs are on this branch with master 4a9efc1 merged. GPU: 1 node of 8 NVIDIA H200 (driver 595.112.07), pytest
8.3.5, transformers 5.15.1. CPU: the CPU accelerator with the gloo backend and
LOCAL_SIZE=4, as in thecpu-torch-latest-v1-multirankworkflow, torch 2.8.0+cu126.test_autotp_sequence_sharding.pytest_autotp_sequence_sharding.pytest_autotp_sequence_sharding.py, the rejection, weight-hook and ZeRO-2 cases, on this branch merged with master but without the review fixes (control)test_autotp_training.py,-m sequential-m sequentialDEEPSPEED_RUN_H100_TESTS=1; 4 needliger_kernel, which is not installed here or in CI; 1 needsDEEPSPEED_PRETRAINED_ROLLOUT_MODEL)test_autoep_expert_activation.pytorch._grouped_mmcan stall with an empty expert, also on master)test_autoep_autotp_grad_parity.pywithDEEPSPEED_RUN_H100_TESTS=1test_autoep_autotp_sharded_attention.py, then-m sequentialtest_autotp_sequence_sharding.pytest_autotp_training.py(multi-rank tests only) +test_tp_plan_e2e.pytest_autotp_training.py,-m sequential-m sequentialtest_autoep_expert_activation.py)In the study, with this code under another name: losses equal TP 1 within 1.9e-6 in fp32 over 5 AdamW steps at batch 1
and 2 (within 1.1e-3 in bf16, 9.0e-4 with autocast and the vocabulary-parallel loss); every parameter gradient equals
the unsharded model's within a relative 4.3e-7 to 1.1e-6 (fp32, one backward, ZeRO-0).
pre-commit run --filespasses on every changed file.Compatibility
gradient_checkpointing_enable()), ZeRO 1, 2 and 3partition_activations)zero.Init, CPU or NVMe offloadvocab_parallel_lm_headfused_linearloss backend (#8945) not rundeepspeed.initialize()(unit test)autotppassdeepspeed.commcollectives onlyAI assistance
This change, its tests and this description were prepared with AI assistance (Claude).
TODO(user): read every changed line, then replace this line with a statement that you reviewed the change and ran the
tests.
🤖 Generated with Claude Code