Skip to content

Add an opt-in attention-output stash for Hugging Face reentrant checkpointing - #8759

Open
yh0903 wants to merge 3 commits into
deepspeedai:masterfrom
yh0903:yh0903/autoep-attention-output-stash
Open

yh0903 wants to merge 3 commits into
deepspeedai:masterfrom
yh0903:yh0903/autoep-attention-output-stash

Conversation

@yh0903

@yh0903 yh0903 commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

With Hugging Face per-layer reentrant gradient checkpointing, backward recomputes every decoder layer, including its attention forward. On Qwen3-30B-A3B on 8 H100s (sequence 4096, micro-batch 4), that recomputed attention forward was about 0.79 s of an 18.7 s step.

This adds an opt-in installer, install_attention_stash(model, num_layers). For the last num_layers decoder layers, the first forward keeps its attention output, and the recompute uses it instead of running the attention forward again. It is a memory-for-compute trade: one attention output plus its log-sum-exp per stashed layer, held from the layer's forward to its recompute.

Change

  • New deepspeed/runtime/activation_checkpointing/attention_stash.py. Like the fused RoPE installer (Add an opt-in fused Triton RoPE for Hugging Face split-half models #8663), it belongs to the attention layers, so it is installed rather than configured under expert_parallel, and it works with or without AutoEP.
  • The installer wraps Hugging Face's "sdpa" entry in ALL_ATTENTION_FUNCTIONS. Attention modules without a stash call the original function.
  • First forward, inside the reentrant checkpoint (grad disabled, the decoder layer's input requires grad):
    • calls aten._scaled_dot_product_cudnn_attention, the op F.scaled_dot_product_attention dispatches to, with the log-sum-exp;
    • keeps the output.
  • Recompute (grad enabled inside a backward pass):
    • projections, norms and RoPE are still recomputed;
    • the attention node is an autograd function that returns the kept output;
    • its backward is aten._scaled_dot_product_cudnn_attention_backward, called with exactly the arguments of PyTorch's derivative for the forward op.
  • Each kept output is keyed by its decoder layer's input: data pointer, version and shape, recorded by a forward pre-hook. The reentrant recompute runs on a detached alias of that same tensor, so a backward can only use its own forward's output. An output whose forward's graph is freed without a backward is released with that input, through weakref.finalize.
  • Fails instead of falling back, for:
    • a model without attn_implementation="sdpa";
    • a training forward of a stashed layer outside a Hugging Face reentrant checkpoint, including non-reentrant checkpointing;
    • an attention mask (padding) or attention dropout;
    • a PyTorch SDPA backend choice other than cuDNN;
    • a recompute with no kept output;
    • a second install on the same layer, a non-integer or out-of-range num_layers, or missing PyTorch entry points.
  • Docs: a section in autoep.rst after the fused RoPE one.

Finalization

  • Rebased onto current master without changing cuDNN forward/backward arguments.
  • Failed decoder forwards clear pending inputs through an always-called hook; duplicate installation validates every selected layer before mutating any of them.
  • Evaluation never creates stash entries, even if an input tensor requires grad. Replayed attention explicitly rejects create_graph=True; saved outputs are consumed once, so repeated backward through a retained graph is outside the contract.
  • Direct CUDA tests use fresh DistributedTest workers, and the engine test restores its process-wide SDPA patch inside the worker.
  • Three new lifecycle/autograd regressions fail on the original runtime before the fixes. Local macOS/Torch 2.10.0/Transformers 5.12.0 validation: 15 passed, 3 CUDA cases skipped under ordinary pytest. Local forked pytest exits with status 3, including in an isolated-plugin check; those runs are not reported as passing. The Linux/device results below provide the actual forked acceptance.
  • Linux/H100 acceptance: 18 distinct cases passed, 0 skipped, under pytest --forked, on a 4x NVIDIA H100 80GB HBM3 allocation (CUDA cases use one worker), driver 580.159.04, torch 2.10.0.2/CUDA 13.0, Triton 3.6.0, transformers 5.12.0 and cuDNN 9.17. The first run passed all 15 CPU contracts and both direct cuDNN cases; the engine case was blocked by transport initialization. Only the engine case was retried with the accepted default NCCL transport setup and passed on unchanged source. This includes the actual AutoEP training-step comparison.
  • The test file is moved into tests/unit/v1/activation_checkpointing/test_attention_stash.py so the current diff selector includes it, rather than silently selecting no tests from the old out-of-scope location. Executable test ASTs are unchanged by this relocation; the relocated CPU file also passes 15 cases with 3 CUDA skips. The CI selector includes exactly this file; collection checks are separate from the actual Linux/H100 runs.

Numerics

  • In the tested configuration, the forward output, dK and dV are numerically equal to Hugging Face's SDPA call under torch.equal; this does not prove signed-zero bit-pattern equality.
  • cuDNN accumulates dQ non-deterministically: PyTorch does not select cuDNN SDPA under torch.use_deterministic_algorithms(True), and six autograd runs on the same inputs gave six different dQ results.
  • The replayed dQ stays within that spread, one replay run was numerically equal to an autograd run under torch.equal, and both have identical error against an FP32 reference in the recorded experiment.

Tests

tests/unit/v1/activation_checkpointing/test_attention_stash.py:

  • CPU, on a tiny Hugging Face Mixtral, with the cuDNN calls swapped for the CPU flash-attention kernels:
    • loss and gradients match the normal recompute for 1 and all 3 layers stashed, with nothing left kept;
    • two forwards, then their backwards in reverse order: each recompute takes its own forward's output;
    • no-grad, eval and dropped forwards retain nothing;
    • every fail-fast path above.
    • Three mutations are each caught by a test: a recompute takes any kept output instead of its own; dropped forwards are not released; training without a checkpoint does not fail.
  • GPU (cuDNN):
    • the replayed node against autograd's: numerical equality under torch.equal for output, dK and dV; dQ as accurate as autograd's against FP32;
    • a training step of an AutoEP engine on a two-layer Mixtral, with and without the stash: equal loss, attention gradients within 1e-2 relative L2.
  • H100 run of the new tests together with the existing activation-checkpointing and AutoEP unit suites: 240 passed, 1 skipped. Both cuDNN tests of the new file ran and passed. The skip is the MiniMax-M3 router-logit test, which needs Transformers >= 5.15.0; the image has 5.12.0.

Current device command, from tests/ on the documented H100/cuDNN setup:

PYTHONPATH=.. pytest --forked unit/v1/activation_checkpointing/test_attention_stash.py

End to end

Qwen3-30B-A3B on 8 H100s: expert parallel 8 with DeepEP, sequence 4096, micro-batch 4, 16 accumulation steps, per-layer reentrant checkpointing. Measured with an equivalent benchmark prototype on our benchmark stack, one allocation, order 0 / 30 / 48 stashed layers, then reverse:

Stashed layers Run medians Median Peak allocated
0 18,733.9 / 18,739.1 ms 18,736.5 ms 58.69 GB
30 18,202.0 / 18,215.5 ms 18,208.7 ms (-2.82%) 62.77 GB
48 17,911.1 / 17,910.0 ms 17,910.6 ms (-4.41%) 65.23 GB
  • The peak is in the micro-batch forward/backward, not the optimizer step, so every stashed layer adds its 136 MB to it.
  • Losses agree within same-arm repeat noise over 30 steps.
  • Before the timing, a one-H100 gate ran on the real attention shapes. It checked the op-level numerics above, and that a two-layer model is as far from the baseline as the baseline is from its own rerun. It measured 0.93 ms saved per stashed layer and micro-batch.

AI assistance was used for final review, integration and regression tests. The submitting human authorized this existing PR update; maintainer review is still required. This is not a new duplicate feature, and the historical performance evidence is not a retiming of the current branch.

AI review follow-up

  • The installer accepts only the canonical Hugging Face SDPA entry, or its own wrapper around that entry. An existing Ulysses/custom SDPA wrapper is rejected before any mutation, so no sequence-gather/output-partition communication can be bypassed by installing this stash. This does not add support for composing stash with sequence parallelism.
  • Consuming a saved output detaches its input finalizer. A later forward using a detached alias of the same storage retains its own cache entry even if the older input is freed. The regression checks two backwards and accumulated parameter/input gradients; the reviewed runtime fails with the missing-output error.
  • CPU stand-ins are now placed at torch.ops.aten and the Torch SDPA selector, with the real ATen signatures and supported argument contract. Production _cudnn_forward, _cudnn_backward and _sdp_backend helpers all remain in the tested path; the fixture no longer replaces stash-module internals.
  • The final forked CPU file passes 18 tests, with 4 device cases skipped, on macOS/Torch 2.10.0/Transformers 5.12.0. The two new CPU regressions reproduce missing wrapper rejection and stale-finalizer failure on the reviewed runtime. Changed-files pre-commit passed.
  • The exact final test file then passed 22/22 cases, 0 skipped, with pytest exit code 0, on a 4x NVIDIA H100 80GB HBM3 allocation, driver 580.159.04, using the documented Torch 2.10.0.2/CUDA 13.0, Transformers 5.12.0 and cuDNN 9.17 setup. This includes all CPU contracts, real cuDNN replay and higher-order-gradient rejection, the new same-storage-alias lifecycle regression, and the AutoEP training-step comparison. The final command is the pytest --forked file selector above. The runtime and every retained test body are unchanged from the first follow-up device run; the complete consolidated file was rerun to verify a clean process exit, not retimed.

An additional two-rank installation-only probe reached the expected Ulysses-wrapper rejection, but its pytest process did not exit before the timeout. That probe is not counted as passing and is not included in the consolidated CI file: rejecting any noncanonical registry function is an unconditional installer contract, covered by the CPU no-mutation regression without introducing sequence-group setup/teardown dependencies. No stash/Ulysses composition or sequence-parallel numerical validation is claimed.

The cuDNN arithmetic/call arguments and existing E2E memory-for-compute evidence are unchanged; no fresh performance or convergence experiment was run.

@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
yh0903 and others added 2 commits November 16, 2026 15:24
…pointing

With Hugging Face per-layer reentrant gradient checkpointing, backward
recomputes every decoder layer, including its attention forward.
install_attention_stash(model, num_layers) keeps the cuDNN SDPA output and
log-sum-exp of the last num_layers decoder layers from the first forward,
and the recompute builds the attention node from the kept output instead
of running the attention forward again. Projections, norms and RoPE are
still recomputed; the replayed backward is the call PyTorch's derivative
for _scaled_dot_product_cudnn_attention makes.

Kept outputs are keyed by the decoder layer's input (data pointer, version
and shape); the reentrant recompute runs on a detached alias of that tensor,
so each backward can only use its own forward's output, and outputs of
forwards dropped without a backward are released with their input.
Unsupported use fails instead of falling back: non-SDPA models, training
outside a reentrant checkpoint, attention masks or dropout, and SDPA
backends other than cuDNN.

Like the fused RoPE installer, it belongs to the attention layers and is
installed rather than configured under expert_parallel.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: yh0903 <helloyu0903@gmail.com>
Release pending inputs even after failed decoder forwards, preflight every layer before duplicate-install rejection, and bypass stashing in evaluation. Explicitly reject higher-order gradients without changing the cuDNN forward/backward arguments.

Run CUDA tests in fresh workers, restore the SDPA wrapper within the engine worker, and move the consolidated regression file into the current v1 CI scope. Preserve the documented first-order, single-backward and cuDNN-only contract.

Signed-off-by: yh0903 <helloyu0903@gmail.com>
@yh0903
yh0903 force-pushed the yh0903/autoep-attention-output-stash branch from f0de17d to 8cac4da Compare November 17, 2026 04:27
@yh0903
yh0903 marked this pull request as ready for review November 17, 2026 04:27
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 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-17T04:38:21.801119Z 8cac4da 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: 8cac4da02e

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

Reject noncanonical SDPA registry entries before patching any layer, while allowing reuse of the installer's own canonical wrapper. Detach consumed inputs' finalizers so an older same-storage alias cannot delete a later forward's saved output.

Move CPU stand-ins to the documented ATen and backend-selector collaborator boundaries. Add no-mutation, wrapper-reuse and CPU/cuDNN alias-lifecycle regressions; preserve the cuDNN arithmetic and opt-in support limits.

Signed-off-by: yh0903 <helloyu0903@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