Skip to content

Replay AutoEP's DeepEP dispatch layout in non-reentrant checkpoint recompute - #8731

Merged
tohtana merged 4 commits into
deepspeedai:masterfrom
yh0903:yh0903/autoep-deepep-checkpoint-replay
Oct 12, 2026
Merged

tohtana merged 4 commits into
deepspeedai:masterfrom
yh0903:yh0903/autoep-deepep-checkpoint-replay

Conversation

@yh0903

@yh0903 yh0903 commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

With comm_backend="deepep", a non-reentrant checkpoint that recomputes a fresh dispatch can silently corrupt AutoEP gradients. Pure reentrant checkpointing (without a nested non-reentrant region) and the collective backend are unaffected by the original layout defect.

DeepEP's received row order depends on arrival timing (unless its deterministic receive order is enabled). A non-reentrant checkpoint keeps the forward pass's autograd nodes, and with them the forward's dispatch handle, while replacing the activations they saved with recomputed ones. The recompute dispatched afresh, so the experts' recomputed activations came back in a new arrival order, while combine's backward still scattered gradient rows in the forward's order. A reentrant recompute builds a new graph whose nodes use the recomputed handle, so it stays consistent. This is the failure noted at the end of #8636.

Change

  • Each AutoEPMoELayer keeps a DeepEPCheckpointReplay record of its forward dispatch handles. Every fresh grad-enabled dispatch records its handle, including graph-building forwards of inner non-reentrant checkpoints during an outer reentrant checkpoint's backward. Only an actual cached-handle replay skips recording.
  • Dispatches inside backward reuse the sole live forward graph's handle through DeepEP's cached path (ElasticBuffer.dispatch(..., handle=..., topk_weights=..., do_expand=handle.do_expand)). If no live handle exists, the dispatch is fresh. A device-side assertion checks that the recomputed routing equals the handle's.
  • Lifetime and matching:
    • A record is owned by the autograd node of the combine that used its handle. It lives exactly as long as the graph that needs it, and is never part of a reference cycle, so it is still freed when Python GC is disabled.
    • A recompute is matched to its forward by requiring exactly one live forward graph. An earlier replay does not exclude a retained graph, which may run backward again. This holds when each micro-batch runs backward and releases its graph before the layer's next forward, as sequential gradient accumulation does.
    • If a recompute could belong to more than one live forward, it raises an error naming reentrant checkpointing as the alternative, rather than guessing.
  • A reentrant checkpoint's first pass records nothing because it runs without grad. Its graph-building recompute records fresh dispatches when needed by a nested non-reentrant region; the standalone reentrant path still dispatches afresh and remains self-consistent.
  • Docs: autoep.rst describes the checkpointing behavior and its constraint.

With PyTorch's default early stop, a non-reentrant recompute now also ends once the expert activations are restored, so it no longer repeats the combine, unless something after the combine in the checkpointed region saves activations (such as shared experts).

Tests

  • CPU, TestCheckpointRecomputeLayout in tests/unit/module_inject/test_auto_ep_comm.py.
    • Uses a buffer that follows DeepEP's dispatch/combine contract but gives every fresh dispatch a new arrival order.
    • Integer-valued data makes every sum exact, so reordering alone cannot change a result, while mismatched rows do.
    • Expert, gate and input gradients over three micro-batches match no-checkpoint exactly under both checkpoint modes (rtol=atol=0, not a signed-zero bit-pattern assertion).
    • Non-reentrant replays on the cached handle and stops before the combine.
    • Also covered: retain_graph backward twice on one graph; rejection after interleaving a retained graph with a new forward of identical routing; nested non-reentrant/reentrant checkpoints with trainable or frozen inputs; a discarded plain forward with GC disabled; and no-grad/discarded checkpoint forwards followed by a successful checkpoint backward. Tests assert observable gradients and errors, not private weak-reference containers. Changed routing remains rejected.
    • The current comm file passes all 62 tests; three configuration-helper cases also pass. The preceding runtime reproduces both nested gradient failures and the missing retained-graph rejection.
  • H100, test_autoep_deepep_parity.py, uniform and skewed routing, 256 rows per rank.
    • Compares ordinary and nested non-reentrant checkpoints with reentrant, retaining relative L2 error below 1e-2 for the input gradient and every parameter gradient.
    • Checks that ordinary non-reentrant early stop runs one combine per layer; nested non-reentrant/reentrant runs two forward combines and three layer forwards.
    • Real DeepEP also checks retained-graph interleaving is rejected on every rank.
    • The existing comparison's absolute tolerances (gradient atol=5e-2, parameter delta atol=5e-4 at lr=1e-4) exceed this model's gradients and first Adam updates, so they cannot detect the defect. On current master, test_cleanup_matches_legacy_preparation[True-False] passes even though the gradients are wrong.
  • Earlier validation on 4 H100s with DeepEP: the full parity file plus the CPU file gave 78 passed, 0 skipped. With the original replay fix removed, the then-new test failed for both routings, with input-gradient relative L2 error of 0.96 (uniform) and 0.99 (skewed).
  • Current AI-review follow-up on 4 NVIDIA H100 80GB HBM3 GPUs, torch 2.10/CUDA 13.0, Triton 3.6.0, transformers 5.12.0 and DeepEP v2: 6 passed, 0 skipped. This includes uniform/skewed ordinary and nested checkpoint gradient parity, plus retained-graph interleaving rejection on every rank.
  • With the preceding replay runtime and the same corrected integration tests, both nested cases fail: input-gradient relative L2 error is 0.956 / 0.973, versus the unchanged 1e-2 threshold. The missing retained-graph rejection is independently reproduced by the deterministic CPU oracle; its unsafe real-DeepEP negative control stalled and was stopped rather than used as successful validation.
  • Final CPU validation under pytest --forked: 65 passed (62 comm/replay cases plus 3 configuration-helper cases). The original AI-review runtime fails the frozen/trainable nested gradient subcases and incorrectly accepts retained-graph interleaving. The current implementation passes the discarded/no-grad and GC-disabled lifetime cases without inspecting private storage.
  • End to end, Qwen3-30B-A3B on 8 H100s (EP8, MB4/GA16, S4096):
    • Step losses with non-reentrant plus this change matched reentrant to within 5.3e-4 over 30 steps.
    • Non-reentrant was 0.7% slower than reentrant there. It skips the recomputed combines, but the remaining DeepEP calls spent longer waiting for peer ranks.
    • This PR is a correctness fix and makes no performance claim.

The review follow-up changes replay recording/matching and the associated tests only. Existing end-to-end evidence is retained; no benchmark was restarted. All PR commits carry Signed-off-by; the automated sign-off finding cited a SHA outside the actual PR commit list.

yh0903 added 2 commits October 2, 2026 16:19
…compute

DeepEP's received row order depends on arrival timing. A non-reentrant
activation checkpoint keeps the forward pass's autograd nodes, and the
dispatch handle they hold, while replacing their saved activations with
recomputed ones. A recompute that dispatched afresh fed the experts rows in
another order than combine's backward scatters gradients into, corrupting
expert, input and router gradients. Reentrant checkpointing was unaffected
because its recompute rebuilds the graph.

Each layer now records its forward dispatch handles. A recompute, recognized
by running inside backward, repeats its forward's dispatch on the recorded
handle. Entries live exactly as long as the graph that needs them and are
matched by elimination; a recompute that could belong to several live
forward passes raises instead of guessing.

With PyTorch's default early stop, a non-reentrant recompute also ends once
the expert activations are restored, skipping the recomputed combine.

Signed-off-by: yh0903 <[email protected]>
The shared parity tolerances are absolute and larger than the mock model's
gradients and first Adam updates, so they accepted gradients scattered onto
another arrival order. Compare relative L2 error instead, on enough rows per
rank for the arrival order to vary.

Signed-off-by: yh0903 <[email protected]>
@yh0903
yh0903 marked this pull request as ready for review October 9, 2026 23:19
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-09T23:26:27.943252Z 6c1d76d 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: 6c1d76df4d

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread deepspeed/module_inject/auto_ep_comm.py Resolved
Comment thread deepspeed/module_inject/auto_ep_comm.py Resolved
Comment thread deepspeed/module_inject/auto_ep_comm.py Resolved
yh0903 added 2 commits October 9, 2026 17:08
…guity

A graph-building inner non-reentrant checkpoint can run during an outer
reentrant checkpoint's backward. Record its fresh grad-enabled dispatch;
only an actual cached-handle replay should skip recording.

A previously replayed graph can remain live under retain_graph. Reject
multiple live forward graphs before choosing a handle rather than letting
a newer waiting entry hide the retained one. Single retained graphs can
still replay repeatedly. Remove the now-unused replayed-entry flag.

Test nested gradients with changing arrival permutations, including frozen
inputs, and rejection of interleaved retained graphs. Replace private
weakref-container assertions with no-grad/discarded-forward gradient and
GC-disabled lifetime behavior. Add actual DeepEP nested and retained-graph
integration cases, preserving existing numerical tolerances.

Signed-off-by: yh0903 <[email protected]>
Nested reentrant/non-reentrant checkpointing executes the router three
times per layer rather than twice. Compare every observed route against
that layer's reference routing while requiring exactly one extra call.
Preserve the numerical gradient and parameter-update tolerances and the
existing strict route ordering check for ordinary checkpoint controls.

Signed-off-by: yh0903 <[email protected]>
@yh0903
yh0903 force-pushed the yh0903/autoep-deepep-checkpoint-replay branch from 6c1d76d to d71ba0a Compare October 10, 2026 01:02
@yh0903

yh0903 commented Oct 10, 2026

Copy link
Copy Markdown
Contributor Author

Codex's comments are addressed in the latest commit:

Fresh grad-enabled dispatches are now recorded even during an outer checkpoint’s backward; only actual handle replays skip recording. Handle selection checks all live graphs, including previously replayed retained graphs, and rejects ambiguous interleaving.
The lifetime tests now verify gradients and replay behavior after no-grad/discarded forwards, including with GC disabled, rather than inspecting private storage.
All 65 CPU cases and 6 real-DeepEP cases on four H100 GPUs pass. The previous runtime fails both nested cases with input-gradient relative L2 errors of 0.956 and 0.973, against the unchanged 1e-2 threshold.

@tohtana tohtana left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Looks good to me, let's merge!

@tohtana
tohtana enabled auto-merge October 12, 2026 05:38
@tohtana
tohtana added this pull request to the merge queue Oct 12, 2026
Merged via the queue into deepspeedai:master with commit 9ec1353 Oct 12, 2026
15 checks passed
@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
@auto-pr-labeler-with-jev auto-pr-labeler-with-jev Bot added the skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. label Nov 14, 2026
tohtana pushed a commit to yh0903/DeepSpeed that referenced this pull request Nov 14, 2026
## Summary

Add opt-in `expert_parallel.skip_recompute_combine` for AutoEP's DeepEP
route. In supported Hugging Face per-decoder-layer **reentrant**
checkpointing, the recomputed MoE output is used only by the residual
add and is discarded by the checkpoint. The route records post-expert
row weighting and combine backward without executing those forward
operations; dispatch, expert compute and all required backward transfers
still run. Default behavior is unchanged.

This is the existing skip-combine PR, not a duplicate implementation. It
remains distinct from the non-reentrant layout replay merged in
deepspeedai#8731. The branch preserves that replay, the fused
gate+up defaults from deepspeedai#8733, and the independent
exact-size buffer checks from deepspeedai#8747. AI assistance
was used for finalization, with author review before submission.

## Supported contract

- `comm_backend="deepep"`, `autoep_size > 1`, BF16 dispatch; eager and
fused row weighting, at their unchanged `score_apply` boundary.
- Supported decoder presets: `deepseek_v2`, `deepseek_v3`, `minimax_m3`,
`mixtral`, `qwen3_5_moe`, `qwen3_moe`, checked against Transformers
5.12.0 modeling code.
- The recompute guard checks the attached decoder layer's current state
and checkpoint configuration: `training=True`,
`gradient_checkpointing=True` and the standard Torch checkpoint partial
with `use_reentrant=True`. An eval-mode decoder does not run its own
Hugging Face checkpoint, so an outer reentrant recompute is rejected
rather than recording a NaN output. Ordinary eval forwards are
unchanged. Transformers 5 defaults to non-reentrant, so explicitly use
`gradient_checkpointing_kwargs={"use_reentrant": True}`.
- Any non-null `moe_layer_pattern` is rejected during configuration
validation when the skip is enabled, even with an explicit or
automatically selected supported preset, a pattern matching the preset,
or an empty string. Leave the pattern unset or disable the skip;
custom-pattern support is unchanged with the option off.
- Other checkpoint APIs, non-reentrant checkpointing with this flag and
unsupported presets are outside the supported contract. Without
recomputation, the ordinary path runs.
- The skip requires that the MoE output has no value-dependent consumer
in the recompute. The combined sentinel is NaN; an invalid consumer can
produce non-finite values or gradients, but the sentinel is **not** a
general runtime proof that arbitrary wrappers, hooks or patched decoder
graphs are safe.

## Finalization

Resolved the upstream conflicts without dropping replay or buffer
behavior. Both normal and recorded combines now share their
backward-context setup, including transferring the pending dispatch
entry from the exchange to the consuming autograd node. Otherwise the
recorded path could retain a stale entry and attempt to replay the
previous step's routing in a later reentrant backward.

The CPU reproducer fails before the context fix with `activation
checkpointing recomputed a different routing`. The new regression
performs three successive steps with changing routes and compares
outputs, input/router/expert gradients and required transfers for both
pre/post score application.

The single CUDA weighting test now runs in a fresh `DistributedTest`
worker, retaining its actual fused/recorded-backward comparison rather
than allocating CUDA from an ordinary forked unittest. The existing
real-DeepEP skip parity cases run two steps per model. The one-step test
helper's defaults and original tolerances remain unchanged.

### Review follow-up

Following the review, reject pattern overrides before model conversion.
Applying an override preserves the supported preset name but can select
a different decoder parent, so a preset-name whitelist cannot establish
the residual-only output-consumer contract. The fix is a four-line
configuration guard, not a decoder-graph validator or a runtime
fallback.

Six parametrized cases cover automatic and explicit preset selection, a
custom parent, the preset's own pattern and an empty pattern. Each also
checks that disabling the skip or leaving the pattern unset remains
accepted. Both configuration references document the restriction. The
kernels, recorded backward, supported execution paths and numerical
thresholds are unchanged.

### Training-state guard follow-up

The decoder must actually be checkpointing, not merely configured to
checkpoint. Hugging Face enables the per-layer checkpoint only when
`gradient_checkpointing` and `training` are both true. Without the
training-state check, an eval decoder under an outer reentrant
checkpoint can feed the recorded NaN into a value-dependent consumer
such as `y * y`. The original guard was reproduced on CPU with finite
forward output but non-finite input, router and expert gradients, for
both pre and post score application.

The guard now fails closed in that invalid recompute. A faithful decoder
harness uses actual Torch nested reentrant checkpoints: training-mode
output and every input/router/expert gradient match the unskipped CPU
reference, eval-mode outer recomputes raise, and ordinary train/eval
forwards retain the full route unchanged. The kernel, backward and
numerical thresholds are unchanged.

The latest master merge preserves the maintainers' existing merge
commits and resolves only the import conflict by retaining `math`,
`weakref` and `partial`. The lightweight `__new__` test layer explicitly
initializes the optional overlap flag to its disabled default for
eventual merge compatibility; the independent overlap feature from
deepspeedai#8739 is not imported into this PR.

## Testing

Latest training-state guard validation: **145 passed, 1 CUDA test
skipped, 58 subtests passed**, on **1x Apple M4 Pro CPU**, macOS 26.7,
Python 3.11.15, Torch **2.14.1**, pytest 9.1.1; CUDA and accelerator
driver are not applicable. This covers the complete comm/replay suite,
configuration tests and supported decoder attachment. The same selector
previously reported **139 passed, 1 skipped, 52 subtests passed** for
the earlier pattern-guard follow-up:

```bash
DS_ACCELERATOR=cpu PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONDONTWRITEBYTECODE=1 \
  python -m pytest -q -p no:cacheprovider \
  tests/unit/module_inject/test_auto_ep_comm.py \
  tests/unit/v1/moe/test_autoep_unit.py::TestAutoEPConfig \
  tests/unit/v1/moe/test_autoep_unit.py::TestModelDetectionAndReplacement::test_skip_recompute_combine_attaches_each_layer_to_its_decoder_layer
```

The skipped case requires CUDA and Triton for recorded fused weighting;
its existing device evidence is listed below. The newly affected
nested-checkpoint and ordinary-forward train/eval tests also pass under
isolated forked workers (**2 passed, 0 skipped**):

```bash
DS_ACCELERATOR=cpu PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONDONTWRITEBYTECODE=1 \
  python -m pytest -q -p no:cacheprovider -p pytest_forked --forked \
  tests/unit/module_inject/test_auto_ep_comm.py::TestSkipRecomputeCombine::test_outer_recompute_respects_the_decoder_training_state \
  tests/unit/module_inject/test_auto_ep_comm.py::TestSkipRecomputeCombine::test_nothing_is_skipped_without_a_recompute
```

The new regression produces exactly two missing-error failures with the
original guard (eval mode, pre/post), while its two training controls
pass. The earlier six pattern regressions passed under isolated forked
workers (**6 passed, 0 skipped**) on the same CPU setup:

```bash
DS_ACCELERATOR=cpu PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONDONTWRITEBYTECODE=1 \
  python -m pytest -q -p no:cacheprovider -p pytest_forked --forked \
  tests/unit/v1/moe/test_autoep_unit.py::TestAutoEPConfig::test_skip_recompute_combine_rejects_pattern_overrides_even_with_supported_presets
```

Existing product validation is bound to the original PR commit
`29303c378`: **275 passed, 1 skipped** on four H100s. All four
eager/fused and uniform/skewed skip-parity cases ran, as did the
recorded fused-weighting backward test. The skipped case is a MiniMax-M3
router-logit test requiring Transformers >=5.15.0; the validation
environment has 5.12.0. This is reused evidence for the original
implementation, not a claim that the entire suite was rerun after
rebase.

Pre-review focused CPU validation: **75 passed, 1 CUDA test skipped**,
under both ordinary pytest and `pytest --forked`, on macOS with Torch
2.10.0 and Transformers 5.12.0. This covers the comm/replay suite, three
skip config/conversion cases and the one-step helper defaults. Ordinary
pytest also reports **52 subtests passed**.

Earlier focused device validation, before the pattern and training-state
guard follow-ups: **9 passed, 0 skipped** with `pytest --forked`, on
**4x NVIDIA H100 80GB HBM3**, driver **580.159.04**, Torch
**2.10.0.2+cu130 / CUDA 13.0**, Triton **3.6.0**, Transformers
**5.12.0**, using the previously validated DeepEP runtime:

- All four eager/fused and uniform/skewed skip-parity cases run two
training steps on each model. They retain the original numerical bounds,
check last-step output/input/router/parameter gradients and accumulated
parameter deltas, and verify one forward combine per layer per step
rather than two.
- The four upstream non-reentrant/nested-reentrant replay cases still
pass, confirming that the shared context preserves normal replay
behavior.
- The recorded fused-weighting backward comparison runs in a fresh
worker. The original ordinary unittest reproduces `Cannot re-initialize
CUDA in forked subprocess` on the same setup; the new worker-based case
passes.

GPU reproduction selector, from `tests/`:

```bash
PYTHONPATH=.. DEEPSPEED_RUN_H100_TESTS=1 pytest --forked \
  unit/module_inject/test_auto_ep_comm.py unit/v1/moe/test_autoep_deepep_parity.py \
  -k 'skipping_the_recomputed_combine or recorded_fused_row_weighting or non_reentrant_checkpointing_replays'
```

Changed-files pre-commit passed for all 11 files in the final PR delta.
Existing device evidence is reused for unchanged kernels/backward and
supported training paths; GPU tests, full E2E and the existing
performance matrix were not restarted for these guard follow-ups. The
new state predicate is exercised through actual Torch
checkpoint/autograd on CPU, not presented as a fresh H100 execution or a
real Transformers-model run. The focused tests do not establish every
ZeRO/offload/TP/PP combination, other hardware, arbitrary checkpoint
composition or long-run convergence.

The static CI selector includes the v1 AutoEP unit and parity files.
Real DeepEP cases remain gated on the opt-in H100 test flag, four GPUs
and a GIN-capable DeepEP build, so test collection alone does not prove
they ran. The standalone recorded-weighting CUDA comparison is outside
Modal's v1 test scope and was explicitly included in the focused
hardware command above; its recorded path is also exercised by the v1
model-parity cases. Full GPU CI follows the repository's merge-queue
workflow.

## Existing performance evidence

Qwen3-30B-A3B, **8 H100s**, EP8, micro-batch **4**, gradient
accumulation **16**, sequence **4096**, DeepEP **28 SMs**, reentrant
activation checkpointing; **30 steps with 10 warmup**. The equivalent
benchmark prototype records the same weighting/combine backward but
returns uninitialized output where the product fills NaN. Both arms
inherit concatenated gate+up and backward weight-gradient overlap; this
is the **incremental skip effect**, not their combined benefit.

One allocation, order normal / skip / skip / normal:

| Recompute | Run medians | Mean |
|---|---|---:|
| Normal | 20,575.1 / 20,574.2 ms | 20,574.7 ms |
| Combine + post-weighting forward skipped | 19,945.7 / 19,928.2 ms |
**19,936.9 ms (-3.10%)** |

Peak allocated memory stayed at **58.69 GB**; peak reserved memory was
**0.25 GB lower**. Loss differences over these 30 steps were within
same-arm repeat noise (maximum **9.4e-4**). The 8-GPU residual-block
gate had numerical equality under `torch.equal` for output/input/router
gradients and expert-gradient differences around **5e-5 relative L2**,
within two normal recomputes' variation. `torch.equal` is not a claim
about signed-zero bit patterns.

The measurements are historical prototype evidence, **not** a retiming
of the rebased product or a universal benefit across models/hardware.
Skipping the forward combine removes that recompute transfer; it does
not add overlap or remove the cached dispatch and weight-gradient
communication required by backward.

---------

Signed-off-by: yh0903 <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: pengdurice <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants