Skip to content

AutoTP: sequence sharding for training - #8860

Open
pengdurice wants to merge 7 commits into
deepspeedai:masterfrom
pengdurice:peng-add-autotp-sequence-sharding-v1
Open

pengdurice wants to merge 7 commits into
deepspeedai:masterfrom
pengdurice:peng-add-autotp-sequence-sharding-v1

Conversation

@pengdurice

@pengdurice pengdurice commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

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 (default false): the hidden states between the attention
and MLP blocks are split along the sequence over the TP ranks, as in Megatron-LM's sequence parallelism.

"tensor_parallel": {
    "autotp_size": 4,
    "sequence_sharding": true
}
  • Each block all-gathers its input; its row-parallel linear reduce-scatters its output instead of all-reducing it.
  • In backward, one reduce-scatter per block sums the input gradients of all its column-parallel linears.
  • Norms and residual adds run on 1/tp of the tokens, and their activations are 1/tp the size.
  • sequence_sharding_overlap (default true): the column-parallel linears that read a block input run in one
    autograd 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 different
scheme; 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 and
Qwen3-32B runs use all four options, the Qwen3-8B run uses only overlap_param_gather. Each framework ran at its best
measured 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.

Model, GPUs DeepSpeed (AutoTP + these options) Megatron-LM (main, Transformer Engine 2.19) TorchTitan (main)
Qwen2.5-72B, 32 15.18 s, 50.3% (TP 8, micro-batch 2) 15.02 s, 50.9% 15.39 s, 49.6%
Qwen3-32B, 16 13.71 s, 52.6% (TP 4, micro-batch 2) 14.11 s, 51.1% 13.66 s, 52.8%
Qwen3-8B, 8 3.21 s, 54.3% (ZeRO-1 without TP) 3.22 s, 54.1% 3.18 s, 54.9%

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_head with the Liger vocabulary-parallel loss, and Liger kernels for RMSNorm, rotary embedding and
SwiGLU (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.

Setup Master This PR Peak memory (rank 0), master -> this PR
Qwen3-8B, 1 node, AutoTP 2 x ZeRO-1 over 4, micro-batch 2, 32 sequences per step 3.701 s 3.524 s (4.8% less) 87.0 -> 78.0 GiB
Qwen3-8B, 1 node, AutoTP 8, micro-batch 4, 32 sequences per step 5.814 s 5.030 s (13.5% less) 80.8 -> 49.5 GiB
Qwen2.5-72B, 4 nodes (EFA), AutoTP 8 x ZeRO-1 over 4, 64 sequences per step 27.00 s at micro-batch 1; micro-batch 2 runs out of GPU memory 17.43 s at micro-batch 2 (35.4% less, 1.55x) 126.1 -> 114.1 GiB

The loss the benchmark script prints after the last step (global_loss) is within 2.5e-4 of master's in all three
setups.

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

  • Where it applies: apply_autotp_sequence_sharding runs in finalize_autotp after AutoTP has replaced the
    linears. A block is the parent module of a row-parallel linear (self_attn, mlp). Forward pre-hooks on the blocks
    gather 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_head to keep those sharded too).
  • Checks at deepspeed.initialize(): every TP linear in the decoder layers belongs to a block; the blocks are in
    one numbered layer list and every layer has one; no column-parallel layer gathers its output; no DeepCompile
    autotp pass; no AutoTP layer class with its own forward (LinearAllreduceWithReplicatedInput,
    LmHeadLinearAllreduce, SubParamLinearAllreduce, SubParamLinearLayer), which would keep its all-reduce; no
    AutoEP 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).
  • Not checked: the modules of a decoder layer outside its blocks run on this rank's tokens, so they must act on
    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.
  • Token layout: each rank holds one contiguous chunk of the flattened batch x sequence tokens, so the collectives
    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.
  • Replicated parameters inside the decoder layers (norm weights, row-parallel biases, an unsharded MLP) see only
    this rank's tokens, so their gradients are summed over the TP group (skipped where AutoTP already registered a sum).
    • ZeRO stages 0-2: a tensor hook sums each micro-step's gradient before accumulation. PyTorch (2.8.0 and 2.9.1
      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.
    • ZeRO-3: a post-accumulate hook, registered before ZeRO-3's own, sums the gradient. ZeRO-3 replaces
      torch.nn.functional.linear by a custom autograd function, so the tensor hook would be skipped under
      checkpointing 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 get no hook. They are added to the list that [AutoTP] Support frozen AutoTP models and manage AutoTP mode per model #8851 introduced for AutoTP's own
      frozen replicated parameters, so unfreezing one after deepspeed.initialize() raises at the next backward.
  • ZeRO-3 partitioned weights use the plain path (separate collectives), not the one-autograd-node overlap. So do
    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 under
    non-reentrant activation checkpointing.
  • Activation checkpointing: a block learns which linears read its input in the model's first forward pass and
    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.
  • Frozen weights in the one-autograd-node path get no weight-gradient GEMM.
  • Core-file footprint: layers.py gets one branch in LinearLayer.forward, one in LinearAllreduce.forward and
    two class attributes; engine.py 11 lines in finalize_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:

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's q_norm/k_norm) uses the
same 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

File Change
deepspeed/module_inject/autotp_sequence_sharding.py (new, 459 lines) the autograd functions (ScatterToSequenceShards, GatherFromSequenceShards, GatherToTensorParallelBlock, ReduceScatterFromTensorParallelBlock, ColumnGroupFromSequenceShards), the block hooks, the gradient hooks and apply_autotp_sequence_sharding
deepspeed/module_inject/layers.py (+19, -2) the branches in LinearLayer.forward and LinearAllreduce.forward; two class attributes on TensorParallel_Layer
deepspeed/runtime/engine.py (+11) the call in finalize_autotp; frozen replicated parameters join AutoTP's list
deepspeed/runtime/tensor_parallel/config.py (+15) sequence_sharding, sequence_sharding_overlap
docs/_pages/config-json.md, docs/_tutorials/autotp-training.md the options and a "Sequence Sharding" section
tests/unit/v1/autotp/test_autotp_sequence_sharding.py (new) the tests below

Tests

tests/unit/v1/autotp/test_autotp_sequence_sharding.py, 21 tests, 2 ranks with AutoTP 2 on a 2-layer Qwen3 (or a
GLM-4.5-style MoE model) built from a config:

Class Cases What it checks, against what
TestAutoTPSequenceSharding ZeRO 1, 2, 3 x modes plain / overlap x activation checkpointing off / on = 12 3 SGD steps match the losses of the unsharded model trained with plain PyTorch (within 1e-5); the decoder norms see half of the sequence on each rank; at ZeRO 1 and 2 a decoder norm weight matches the unsharded model after the steps (its summed gradient)
TestAutoTPSequenceShardingReplicatedMLP ZeRO 1, 3, checkpointing on only attention is sharded, so the MLP linears stay replicated inside the sequence-sharded layers and their gradients must be summed over TP; 3 steps match the unsharded model
TestAutoTPSequenceShardingUnreadColumn ZeRO 1, 3 a column-parallel linear that the block never calls does not keep the gathered block input alive after the step
TestAutoTPSequenceShardingWeightHooks ZeRO 1, overlap, checkpointing on a tensor hook on a column-parallel weight runs once per layer and step on all 3 steps
TestAutoTPSequenceShardingRejects 4 a sequence length not divisible by TP raises; AutoEP MoE layers in the decoder layers raise at deepspeed.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 at deepspeed.initialize() and unfrozen afterwards makes backward raise

The 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/ for LinearLayer,
LinearAllreduce, TensorParallel_Layer, autotp_size, TPTrainingConfig, tp_model_init and the other changed
names). Three files that only matched an unrelated add_bias of the inference kernels, and
tests/unit/hybrid_engine/test_he_lora.py, which only matched its own LinearLayer_LoRA class, were not run.

cd tests
pytest unit/v1/autotp/test_autotp_sequence_sharding.py
pytest unit/v1/autotp/test_autotp_training.py unit/v1/autotp/test_tp_plan_e2e.py \
    unit/v1/autotp/test_tp_plan_real_models.py unit/v1/autotp/test_autotp_custom_patterns.py \
    unit/module_inject/test_tp_partition_config_path.py unit/module_inject/test_tp_autograd_reduce.py \
    unit/module_inject/test_fused_repartition.py unit/hybrid_engine/test_he_policy.py
pytest -m sequential unit/v1/autotp/test_autotp_training.py
pytest unit/checkpoint/test_autotp_uc_checkpoint.py unit/runtime/tensor_parallel/test_autotp_universal_checkpoint.py \
    unit/checkpoint/test_affine_shard_map.py unit/checkpoint/test_zero_affine.py unit/compile/test_tp_compile.py
pytest -m sequential <the same five files>
pytest unit/v1/moe/test_autoep_autotp_checkpoint.py unit/v1/moe/test_autoep_autotp_deepcompile_reject.py \
    unit/v1/moe/test_autoep_autotp_folding_config.py unit/v1/moe/test_autoep_autotp_runtime.py \
    unit/v1/moe/test_autoep_checkpoint.py unit/v1/moe/test_autoep_unit.py \
    unit/v1/ops/muon/test_per_head_muon_accelerator.py \
    unit/v1/sequence_parallelism/test_liger_vocab_parallel_cross_entropy.py unit/v1/test_hybrid_engine_rollout_v1.py \
    unit/v1/moe/test_autoep_expert_activation.py unit/v1/moe/test_autoep_autotp_grad_parity.py \
    unit/v1/moe/test_autoep_autotp_sharded_attention.py
pytest -m sequential unit/v1/moe/test_autoep_autotp_sharded_attention.py

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 the
cpu-torch-latest-v1-multirank workflow, torch 2.8.0+cu126.

Test files Where, torch Result
test_autotp_sequence_sharding.py GPU, torch 2.8.0 21 passed
test_autotp_sequence_sharding.py GPU, torch 2.9.1+cu128 21 passed
test_autotp_sequence_sharding.py, the rejection, weight-hook and ZeRO-2 cases, on this branch merged with master but without the review fixes (control) GPU, torch 2.8.0 4 failed (the weight-hook test and the 3 new rejection tests), 5 passed
the files of the second command GPU, torch 2.8.0 159 passed, 3 skipped (2 existing BF16-optimizer overflow skips; 1 needs an environment without transformers)
test_autotp_training.py, -m sequential GPU, torch 2.8.0 66 passed
the checkpoint group, then -m sequential GPU, torch 2.8.0 412 passed; 9 passed
the AutoEP group (the files of the fifth command except the last three) GPU, torch 2.8.0 364 passed, 12 skipped (7 run only with DEEPSPEED_RUN_H100_TESTS=1; 4 need liger_kernel, which is not installed here or in CI; 1 needs DEEPSPEED_PRETRAINED_ROLLOUT_MODEL)
test_autoep_expert_activation.py GPU, torch 2.9.1+cu128 (on torch 2.8 the backward of torch._grouped_mm can stall with an empty expert, also on master) 96 passed, 12 skipped (the file's own skip: "with Triton installed, this form's grouped path needs CUDA tensors")
test_autoep_autotp_grad_parity.py with DEEPSPEED_RUN_H100_TESTS=1 GPU, torch 2.8.0 20 passed
test_autoep_autotp_sharded_attention.py, then -m sequential GPU, torch 2.8.0 69 passed; 2 passed
test_autotp_sequence_sharding.py CPU, torch 2.8.0 20 passed, 1 skipped (the AutoEP test needs an accelerator) in 6:52
test_autotp_training.py (multi-rank tests only) + test_tp_plan_e2e.py CPU, torch 2.8.0 50 passed, 2 skipped (the existing BF16-optimizer overflow skips) in 11:17
test_autotp_training.py, -m sequential CPU, torch 2.8.0 66 passed in 12:16
the other AutoTP files of the second command CPU, torch 2.8.0 105 passed, 1 skipped (it needs an environment without transformers) in 6:36
the checkpoint group, then -m sequential CPU, torch 2.8.0 412 passed in 7:46; 3 passed, 6 skipped ("CPU does not support this test yet")
the AutoEP group (11 files, without test_autoep_expert_activation.py) CPU, torch 2.8.0 342 passed, 123 skipped (accelerator-only tests) in 33:28

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 --files passes on every changed file.

Compatibility

Cell Validated
AutoTP 2, ZeRO 1, 2 and 3, fp32 (unit tests, GPU and CPU) yes
AutoTP 2-8, ZeRO-1, bf16 + torch autocast, Qwen3-8B / 32B, Qwen2.5-72B, 1-4 nodes yes, with the first commit of this PR: Qwen3-8B (AutoTP 2 and 8, 1 node) and Qwen2.5-72B (AutoTP 8, 4 nodes); Qwen3-32B in the study code only; not run again after the merge
Activation checkpointing (non-reentrant, gradient_checkpointing_enable()), ZeRO 1, 2 and 3 yes (unit tests)
A fused kernel that saves a replicated decoder-layer weight (such as Liger's RMSNorm) with non-reentrant checkpointing ZeRO 0-2: rejected in backward (unit test at ZeRO-1); ZeRO-3: sums after accumulation, covered by the replicated-MLP test, whose linear weights ZeRO-3 saves in a custom autograd function, not with a fused norm
Reentrant checkpointing, DeepSpeed's own activation checkpointing (partition_activations) not run
Gradient accumulation over several micro-steps not run in the unit tests (they use 1); this PR's benchmark runs above used 4 to 8 micro-steps per step, without checkpointing
fp16 with loss scaling not run
zero.Init, CPU or NVMe offload not run
Checkpoint save / load not run; the option changes no parameter or optimizer state
vocab_parallel_lm_head yes in the benchmark runs (Liger backend); the fused_linear loss backend (#8945) not run
AutoEP + AutoTP folding rejected at deepspeed.initialize() (unit test)
Ulysses / ALST / AutoSP sequence parallelism together with it not supported, not checked at initialization
Pipeline parallel, torch.compile, the DeepCompile autotp pass not run; the DeepCompile pass is rejected
Models other than Qwen3 / Llama-style decoders (GPTBigCode's fused QKV is accepted but not run) not run; the checks above reject unsupported layouts
Accelerators other than CUDA GPU runs on CUDA only; the CPU accelerator with gloo passes the unit tests; uses deepspeed.comm collectives only

AI 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

…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>
@tohtana tohtana added needs-gpu-test GPU testing is recommended to validate the changes in this PR. and removed needs-gpu-test GPU testing is recommended to validate the changes in this PR. labels Nov 10, 2026
pengdurice and others added 3 commits November 18, 2026 16:29
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>
@pengdurice
pengdurice marked this pull request as ready for review November 18, 2026 16:52
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T17:03:34.482066Z 3708d05 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants