Skip to content

[sdpa] Add grad_logsumexp input to _flash_attention_backward - #206398

Closed
drisspg wants to merge 1 commit into
mainfrom
drisspg/stack/2
Closed

drisspg wants to merge 1 commit into
mainfrom
drisspg/stack/2

Conversation

@drisspg

@drisspg drisspg commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PRs:


Human Note

Flex-attention used to be th eonly way to actually propgate grads backwards for logsumexp; This came up int he context of a
pytorch/torchtitan#6329 where these grads were being dropped vy arlen attention. This adds the argument
to the backward op so that we can propogate for backends that support FA4

Agent Notes

This commit was authored with an AI assistant.

Problem. Losses that use the logsumexp (LSE) returned by flash attention need its gradient
in the backward. The GPT-OSS attention-sink rescale out * sigmoid(lse - sink) is one
(pytorch/torchtitan#6329). aten::_flash_attention_backward had no way to receive that
gradient.

Fix. Add an optional grad_logsumexp keyword input next to grad_out. With it, the
backward's per-row term becomes rowsum(dO * O) - dLSE; nothing else in the kernel changes.

Backend Behavior with grad_logsumexp
FA4 Passed to the kernel as dlse; about 1% extra backward time
FA4, head dim 256 on SM100 Raises (that kernel has no dlse)
FA2, FA3 Raise, pointing at activate_flash_attention_impl("FA4")
ROCm, XPU Raise

Behavior to know. The check rejects any passed gradient without reading its values, so it
never syncs and is safe under CUDA graph capture. The cost: torch.compile passes an all-zero
gradient for an lse that is returned from a compiled region but never used, and that is rejected
too. The error message says to detach such an lse inside the region.

Implementation details
  • attention_backward.cu (FA2/ROCm) and xpu/attention_backward.cpp: TORCH_CHECK_NOT_IMPLEMENTED
    when grad_logsumexp is defined.
  • _fa4.py: _fa4_backward_support_error checks shape (must match logsumexp) and fp32; the
    SM100 head-dim-256 limit raises NotImplementedError like the other rejections. dlse is
    passed only when set, so older FA4 releases without that argument keep working. FA4 makes
    dlse contiguous itself.
  • _fa3.py raises when grad_logsumexp is set.
  • register_flash_attention_impl's docstring tells providers that overrides of
    _flash_attention_backward receive grad_logsumexp and must raise if they cannot use it.
  • AOTI fallback bumped to v2 for the new argument; C shims and shim_function_versions.txt
    regenerated. Meta registration accepts the new kwarg.
  • Rejected alternatives:
    • Folding dLSE into an extra head-dim column (zero in q/k/v, one in dO, -dLSE in O) lets
      FA2/FA3/cuDNN compute the right gradient with no kernel change. Dropped: 1.6x to 1.9x
      backward time, fails for head dims the padded kernel cannot run, and hard to follow.
    • Having varlen call FA4 directly: no schema change, but couples varlen to the FA4 module.
  • Native FA2 support needs a dLSE input in the upstream flash-attention preprocess kernel plus a
    submodule bump; it would plug into this argument.

The next commit makes varlen_attn pass the gradient.

Validation

  • Tested on GB300 (cuDNN 9.24.1, FA4 installed from the pinned submodule). FA3 (needs SM90),
    ROCm, and XPU were not run.
  • With grad_logsumexp=None, the new FA4 test fails (dq relative L2 error 0.11 to 0.41 against
    fp32); with it, it passes.
  • test/test_varlen_attention.py and test/nn/attention/test_fa4.py pass with only this commit
    applied.

@pytorch-bot

pytorch-bot Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - Ready for human review:

The PR adds an optional keyword-only `grad_logsumexp` input to
`aten::_flash_attention_backward`. FA4 passes it to the kernel as `dlse`, and
FA2, FA3, ROCm and XPU reject it with `NotImplementedError`. Recommendation:
Approve. Both earlier findings are fixed, and the only remaining point is a
non-blocking docstring correction.

Findings (1):

[minor] test/test_varlen_attention.py:361
Non-blocking: the docstring of `_assert_sink_rescale_grads_match_reference` says
"dq, dk, and dv are the gradients that exercise the lse gradient." dv does not
depend on `grad_logsumexp`. `lse` depends only on Q and K, so dV = PdO whatever
dLSE is. In the kernel, dLSE enters only through D = rowsum(dOO)  dLSE, which
feeds dS, so only dq and dk depend on it. If the gradient were dropped, the dv
check would still pass and only the dq and dk checks would catch it. This
matches the PR body, which cites only dq errors without `grad_logsumexp`.
Suggested wording: "dq and dk are the gradients that exercise the lse gradient;
dv (PdO) and dsink do not depend on it."

Reviewed commit: 347437f

Review run

🐛 Report a bad review

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/206398

Note: Links to docs will display an error until the docs builds have been completed.

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

❌ 1 New Failure

As of commit 347437f with merge base 1a2fb1c (image):

🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:

  • New test fails on ROCm
    • test_flash_attention_backward_grad_logsumexp_requires_fa4 runs fa2 wherever PLATFORM_SUPPORTS_FLASH_ATTENTION holds, ROCm included
    • It asserts requires the FA4, but under USE_ROCM attention_backward.cu raises grad_logsumexp is not supported on ROCm instead
    • TestVarlenAttentionCUDA already branches on TEST_WITH_ROCM, so the class runs there; the description says ROCm was not run
  • Not a trivial change
    • Adds grad_logsumexp to the _flash_attention_backward schema and changes FA4 backward gradient math by passing dlse
    • Adds exported AOTI C shims aoti_torch_{cuda,xpu}__flash_attention_backward_v2 and bumps the fallback to v2 in torchgen/aoti/fallback_ops.py
    • A new feature across native, AOTI, and Python FA3/FA4 overrides fits no trivial class

reason: build_or_ci_risk
Reviewed commit: a0fe42b (NOT the current head 347437f)

Inference job

🐛 Report a wrong verdict

NEW FAILURE - The following job has failed:

  • pull / linux-jammy-py3.11-clang21-asan / test (default, 9, 18, lf-l-x86iavx512-16-128) (gh)
    test_linalg

    AI verdict: AI verdict: probably not related

    Every test_linalg test passes (1837 passed). The failure is an intermittent crash during Python interpreter shutdown: an immortal interned string is freed, or ASAN reports a SEGV or a huge allocation. The same crash already happens on the merge base without the suspect, where it was hidden because retries passed. The suspect only touches the CUDA/FA4 flash-attention backward, which a CPU ASAN test_linalg run never executes.

    Full reasoning on HUD →

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot

pytorch-bot Bot commented Nov 24, 2026

Copy link
Copy Markdown

Attention! native_functions.yaml was changed

If you are adding a new function or defaulted argument to native_functions.yaml, you cannot use it from pre-existing Python frontend code until our FC window passes (two weeks). Split your PR into two PRs, one which adds the new C++ functionality, and one that makes use of it from Python, and land them two weeks apart. See https://github.com/pytorch/pytorch/wiki/PyTorch's-Python-Frontend-Backward-and-Forward-Compatibility-Policy#forwards-compatibility-fc for more info.


Attention! PyTorch one of the C-stable API file was changed

You MUST NOT change existing function declarations in this, as this header defines a stable C ABI. If you need to change the signature for a function, introduce a new v2 version of the function and modify code generation to target the new version of the function.

@drisspg

drisspg commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot review

@pytorch-bot

pytorch-bot Bot commented Nov 24, 2026

Copy link
Copy Markdown

The automated review only re-runs on PRs labeled in progress and neither ready for review nor no automated review.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 24, 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-24T04:06:32.647321Z 8cb6dfe 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.

@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Nov 24, 2026
@drisspg drisspg removed the topic: not user facing topic category label Nov 24, 2026
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 24, 2026
@drisspg

drisspg commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot review

@pytorch-bot pytorch-bot Bot added in progress PR is being worked on by the author, until the automated review accepts it and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 24, 2026
github-actions[bot]

This comment was marked as outdated.

@drisspg

drisspg commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Automated review follow-up (a0fe42b): moved the SM100 head-dim-256 check into _fa4_backward_support_error, gave ROCm its own error message, inlined the FA3 rejection, noted in the test helper that dsink does not exercise the kernel, documented the grad_logsumexp override contract in register_flash_attention_impl, and added ciflow/b200 so the FA4 tests run. Not changed: dlse contiguity, because FA4 already applies maybe_contiguous(dlse) (flash_attn/cute/interface.py:2511); and an old-FA4 signature probe, because the pinned FA4 accepts dlse and an older install only fails, with a TypeError naming dlse, when an lse gradient is actually passed.

github-actions[bot]

This comment was marked as outdated.

@drisspg

drisspg commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Automated review follow-up (c427986): the ROCm test now expects the ROCm message (assertion branches on TEST_WITH_ROCM); the SM100 head-dim-256 rejection raises NotImplementedError again (checked only when grad_logsumexp is set), and register_flash_attention_impl names NotImplementedError; the ROCm/CUDA message prefix is chosen in a constexpr before the check instead of #if inside the macro; the detach hint mentions torch.compile regions again.

@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Nov 24, 2026
github-actions[bot]

This comment was marked as outdated.

@github-actions
github-actions Bot dismissed their stale review November 24, 2026 05:31

Withdrawn: the automated review of c427986 found nothing blocking.

## Human Note

Flex-attention used to be th eonly way to actually propgate grads backwards for logsumexp; This came up int he context of a
pytorch/torchtitan#6329 where these grads were being dropped vy arlen attention. This adds the argument
to the backward op so that we can propogate for backends that support FA4

## Agent Notes

This commit was authored with an AI assistant.

**Problem.** Losses that use the logsumexp (LSE) returned by flash attention need its gradient
in the backward. The GPT-OSS attention-sink rescale `out * sigmoid(lse - sink)` is one
(pytorch/torchtitan#6329). `aten::_flash_attention_backward` had no way to receive that
gradient.

**Fix.** Add an optional `grad_logsumexp` keyword input next to `grad_out`. With it, the
backward's per-row term becomes `rowsum(dO * O) - dLSE`; nothing else in the kernel changes.

| Backend | Behavior with `grad_logsumexp` |
| --- | --- |
| FA4 | Passed to the kernel as `dlse`; about 1% extra backward time |
| FA4, head dim 256 on SM100 | Raises (that kernel has no `dlse`) |
| FA2, FA3 | Raise, pointing at `activate_flash_attention_impl("FA4")` |
| ROCm, XPU | Raise |

**Behavior to know.** The check rejects any passed gradient without reading its values, so it
never syncs and is safe under CUDA graph capture. The cost: `torch.compile` passes an all-zero
gradient for an lse that is returned from a compiled region but never used, and that is rejected
too. The error message says to detach such an lse inside the region.

<details>
<summary>Implementation details</summary>

- `attention_backward.cu` (FA2/ROCm) and `xpu/attention_backward.cpp`: `TORCH_CHECK_NOT_IMPLEMENTED`
  when `grad_logsumexp` is defined.
- `_fa4.py`: `_fa4_backward_support_error` checks shape (must match `logsumexp`) and fp32; the
  SM100 head-dim-256 limit raises `NotImplementedError` like the other rejections. `dlse` is
  passed only when set, so older FA4 releases without that argument keep working. FA4 makes
  `dlse` contiguous itself.
- `_fa3.py` raises when `grad_logsumexp` is set.
- `register_flash_attention_impl`'s docstring tells providers that overrides of
  `_flash_attention_backward` receive `grad_logsumexp` and must raise if they cannot use it.
- AOTI fallback bumped to v2 for the new argument; C shims and `shim_function_versions.txt`
  regenerated. Meta registration accepts the new kwarg.
- Rejected alternatives:
  - Folding dLSE into an extra head-dim column (zero in q/k/v, one in dO, -dLSE in O) lets
    FA2/FA3/cuDNN compute the right gradient with no kernel change. Dropped: 1.6x to 1.9x
    backward time, fails for head dims the padded kernel cannot run, and hard to follow.
  - Having varlen call FA4 directly: no schema change, but couples varlen to the FA4 module.
- Native FA2 support needs a dLSE input in the upstream flash-attention preprocess kernel plus a
  submodule bump; it would plug into this argument.

</details>

The next commit makes `varlen_attn` pass the gradient.

## Validation

- Tested on GB300 (cuDNN 9.24.1, FA4 installed from the pinned submodule). FA3 (needs SM90),
  ROCm, and XPU were not run.
- With `grad_logsumexp=None`, the new FA4 test fails (dq relative L2 error 0.11 to 0.41 against
  fp32); with it, it passes.
- `test/test_varlen_attention.py` and `test/nn/attention/test_fa4.py` pass with only this commit
  applied.

stack-info: PR: #206398, branch: drisspg/stack/2

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated review of 347437f: nothing blocking; ready for human review.

The PR adds an optional keyword-only grad_logsumexp input to aten::_flash_attention_backward. FA4 passes it to the kernel as dlse, and FA2, FA3, ROCm and XPU reject it with NotImplementedError. Recommendation: Approve. Both earlier findings are fixed, and the only remaining point is a non-blocking docstring correction.

⚪ 1 non-blocking finding

dsink comes from autograd outside the attention backward; dq, dk, and dv are the

Non-blocking: the docstring of _assert_sink_rescale_grads_match_reference says "dq, dk, and dv are the gradients that exercise the lse gradient." dv does not depend on grad_logsumexp. lse depends only on Q and K, so dV = PdO whatever dLSE is. In the kernel, dLSE enters only through D = rowsum(dOO) dLSE, which feeds dS, so only dq and dk depend on it. If the gradient were dropped, the dv check would still pass and only the dq and dk checks would catch it. This matches the PR body, which cites only dq errors without grad_logsumexp. Suggested wording: "dq and dk are the gradients that exercise the lse gradient; dv (PdO) and dsink do not depend on it."

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #206399

pytorchmergebot pushed a commit that referenced this pull request Nov 24, 2026
Stacked PRs:
 * __->__#206399
 * #206398

--- --- ---

## Human Note

Wire up the last one for FA4; its annoying that only fa4 acutaly supports this; fa2 and cudnn dont; provides nice erroing. This
does chagnge teh behavior in compile but it makes it way more correct so im game.

## Agent Notes

This commit was authored with an AI assistant.

**Problem.** `varlen_attn(..., return_aux=AuxRequest(lse=True))` marked the returned lse as
non-differentiable, and its backward ignored the lse gradient. Losses that use lse silently got
wrong dQ/dK. TorchTitan's GPT-OSS sink rescale hit this (pytorch/torchtitan#6329): the issue's
repro shows 0.32 / 0.28 max relative error in dQ / dK against eager, versus 3e-3 for
flex_attention.

**Fix.** When the caller asks for lse, it is differentiable, and its gradient goes to
`aten::_flash_attention_backward` as `grad_logsumexp` (previous commit).

| Situation | Result |
| --- | --- |
| FA4 active, loss uses lse | Correct gradients |
| FA2 or cuDNN, loss uses lse | Raises with the fix for that backend: activate FA4, or with FA4 already active, put Flash first |
| lse returned but not used (eager, or dropped inside a compiled region) | No gradient sent; works on every backend |
| lse returned unused from a `torch.compile` region, or under reentrant checkpointing | A zero gradient arrives; FA2/cuDNN raise. Detach the lse |
| lse not requested | Unchanged |

**Backend selection.** When FA4 is active and lse is returned while grad is enabled, Flash is now
preferred over cuDNN by default, since only FA4 uses the lse gradient. An explicit
`sdpa_kernel(..., set_priority=True)` order still wins. Inputs FA4 does not support then fail in
FA4 instead of falling back to cuDNN.

**BC-breaking note.** The lse returned with `return_aux=AuxRequest(lse=True)` now requires grad
when the inputs do. Code that backpropagates through it on FA2 or cuDNN, which previously got
silently wrong gradients, now raises `NotImplementedError`: activate FA4
(`torch.nn.attention.activate_flash_attention_impl("FA4")`) and enable
`SDPBackend.FLASH_ATTENTION`, or use flex_attention. Code that keeps the lse only for logging or
inspection should call `lse.detach()`; this is required when a zero gradient reaches it
(returning it from a `torch.compile` region, reentrant activation checkpointing).

<details>
<summary>Implementation details</summary>

- The private op `torch_attn::_varlen_attn` gains `return_lse`; lse stays non-differentiable when
  it is False, so direct callers of the op are unaffected.
- The autograd function sets `set_materialize_grads(False)`, so an unused lse arrives as `None`
  rather than zeros; a `None` `grad_out` (out unused) becomes zeros before the kernel call.
- `_varlen_attn_backward` rejects an lse gradient unless the backend is Flash with FA4 active,
  without reading its values, so the check never syncs.

</details>

## Validation

- The issue's repro script with FA4 active: varlen vs eager is now 3.4e-3 (dQ) / 4.5e-3 (dK),
  the same as flex. Without FA4 it raises the FA4-required error instead of returning wrong
  gradients.
- `test_varlen_lse_gradient` fails all 4 cases on the unpatched `varlen.py` (dq relative L2 error
  0.11 to 0.41) and passes with this commit.
- Full `test/test_varlen_attention.py`, `test/nn/attention/test_fa4.py`, and the varlen flop
  counter test pass on GB300.
Pull Request resolved: #206399
Approved by: https://github.com/tianyu-l
Stack dependencies: #206398
tianyu-l added a commit to pytorch/torchtitan that referenced this pull request Nov 26, 2026
… deterministic mode (#6398)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
Since torch `2.16.0.dev20261125`, "1 GPU Integration (Fake PG)" fails on
every PR and "8 GPU Integration (Real PG - full suite - models)" fails
on main. The A10G golden losses drift in the low digits. Torch
`dev20261124` passed (last green: 11:04 UTC run 45601059954), and every
run after the nightly switch fails the same tests with the same values.

The cause is pytorch/pytorch#204322, "[inductor] Deterministic mode:
turn off Triton FMA contraction, emit explicit FMAs". In
`config.deterministic` mode, Inductor now compiles its generated Triton
kernels with `enable_fp_fusion=False`, so the result no longer depends
on which block size or `num_warps` autotuning picks. The golden runs set
`debug.deterministic=True`, so their rounding changes. This is an
intentional upstream numerics change, not a torchtitan bug, so the fix
is to regenerate the goldens.

**Example** (`llama3_fsdp+tp+cp`, Fake PG, A10G):

```
step  golden (dev20261124)          dev20261125
4     3.6361570  gn 0.76279575      3.6361570  gn 0.76279598
5     3.6227007                     3.6228001
10    3.4226971                     3.4225903
```

## How the cause was isolated
The two nightlies are 70 PyTorch commits apart
(283f59dd27...122eafd311), and the new torch also pins cuDNN 9.28.1 (was
9.26.0). I bisected locally on GB300 with `deepseek_v3_fsdp+ep` (Fake
PG), which reproduces the drift there. Each row below gives
bitwise-identical results on repeat runs.

| torch binary | cuDNN | Python change | step 1 loss |
| --- | --- | --- | --- |
| dev20261124 | 9.26.0 | -- | 7.990665912628174 |
| dev20261124 | 9.28.1 | -- | 7.990665912628174 |
| dev20261125 | 9.28.1 | -- | 7.990651607513428 |
| dev20261125 | 9.28.1 | dev20261124's `_inductor`/`_dynamo`/`fx`/... |
7.990665912628174 |
| dev20261125 | 9.28.1 | only #204322 reverted | **7.990665912628174** |
| dev20261125 | 9.28.1 | only #204320 reverted | 7.990651607513428 |
| dev20261125 | 9.28.1 | #184946, #206365, #203784, #203888 reverted |
7.990651607513428 |

So the cuDNN bump has no effect, and reverting #204322 alone restores
the old numerics bit for bit.

## What changed
Mechanical: the numeric rows of 11 golden files are replaced. Headers
and step counts are unchanged and were checked against the source
blocks.

| Golden file | Tests | max rel. loss diff | final loss old -> new |
| --- | --- | --- | --- |
| `fake_pg/a10g/llama3.txt` | `llama3_fsdp+tp+cp`, `+region_ac` |
3.1e-05 | 3.42270 -> 3.42259 |
| `fake_pg/a10g/deepseek_v3.txt` | `deepseek_v3_fsdp+ep` | 4.0e-05 |
6.32932 -> 6.32955 |
| `fake_pg/a10g/qwen3.txt` | `qwen3_moe_fsdp+tp+cp+ep_param_groups` |
5.5e-03 | 2.96522 -> 2.98026 |
| `fake_pg/a10g/muse_glimmer.txt` | `muse_glimmer_text_fsdp` | 3.4e-04 |
6.71710 -> 6.71748 |
| `real_pg/a10g/llama3.txt` | `llama3_fsdp+tp+cp`, `+region_ac` |
7.1e-05 | 4.05240 -> 4.05239 |
| `real_pg/a10g/llama3_pp.txt` | `llama3_fsdp+tp+pp` | 6.3e-05 | 4.19607
-> 4.19609 |
| `real_pg/a10g/deepseek_v3.txt` | `deepseek_v3_fsdp+ep` | 1.1e-04 |
3.81001 -> 3.81031 |
| `real_pg/a10g/deepseek_v3_cp_pp.txt` | `deepseek_v3_fsdp+cp+pp+ep` |
2.5e-04 | 3.83078 -> 3.83064 |
| `real_pg/a10g/gpt_oss_pp.txt` | `gpt_oss_pp+fsdp+cp+ep+sacop` |
1.7e-03 | 3.90803 -> 3.90858 |
| `real_pg/a10g/qwen3.txt` | `qwen3_moe_fsdp+tp+cp+ep_param_groups` |
6.8e-05 | 5.34935 -> 5.34934 |
| `real_pg/a10g/muse_glimmer.txt` | `muse_glimmer_text_fsdp` | 8.0e-03 |
3.71158 -> 3.70928 |

Over 10 steps, last-bit differences grow more in some runs than others
(`real_pg` `muse_glimmer` 8.0e-3, `gpt_oss_pp` 1.7e-3, `fake_pg` `qwen3`
5.5e-3). Final losses move in both directions. Fake PG grad norms are
already meaningless (up to ~1e17) and change by more.

`{fake_pg,real_pg}/a10g/sft.txt` are unchanged and still pass.
`gpt_oss_fsdp+tp+ep` (`gpt_oss.txt`), and `gpt_oss_pp+fsdp+ep+sacop` in
Real PG, crash under `dev20261125` for a separate reason.
pytorch/pytorch#206398 made varlen's lse differentiable, and only FA4
can backpropagate through it. That is fixed in a separate PR, so this
PR's Fake PG and Real PG jobs still fail on those two tests.

## Numerics
The new values are the "Baseline metrics in import file format" blocks
that `loss_compare` printed in the A10G CI logs under `dev20261125`.
A10G numerics can't be reproduced off that hardware, so they come
straight from CI. The values agree across runs:
- Fake PG: #6395 (main HEAD deb3e43) == #6245 == #5678 == #6389. #5629
differs only in tests its own changes touch.
- Real PG: main 7ccb1bb == d2a8af2 == 7a60bbb == 8919259 (the
scheduled run).

## Testing
- This PR's CI is the test. `ciflow/fake-pg` checks the 4 fake-PG files.
`ciflow/real-pg` is added so the full Real PG suite checks all 7 real-PG
files. The `real_pg_required` subset only covers `llama3_pp`,
`deepseek_v3_cp_pp` and `gpt_oss_pp`.
- The local bisection above used `python -m
tests.integration_tests.run_tests --execution_mode fake_pg --ngpu 1
--test_name deepseek_v3_fsdp+ep` on GB300, with each torch/cuDNN
combination as a `PYTHONPATH` overlay.
- `pre-commit run` on the changed files passes.

## Known issues / follow-ups
- `real_pg/mi350x/*` is not updated. The ROCm workflow
(`integration_test_rocm.yaml`) still passes on main because the ROCm
nightly index serves torch `dev20261119`, which predates #204322 (run
45670678052). Expect the same drift on MI350X once the ROCm nightly
advances. Those goldens need a refresh from that run's logs then.
- `real_pg/kimi_k3_b200.txt` (B200 workflow) and `rl_grpo_cuda.txt` (RL
loss guard) are unaffected for now. Those jobs end up on pinned older
torch (`dev20261102` and `dev20261107` in today's runs). Expect the same
drift when their torch pins move past `dev20261125`.
- The goldens track whatever nightly CI installs, so a later nightly can
shift them again.
tianyu-l added a commit to pytorch/torchtitan that referenced this pull request Nov 26, 2026
torch dev20261125 (pytorch/pytorch#206398) makes the lse that varlen_attn
returns differentiable. Before, it was non-differentiable, so GPT-OSS's
sink rescale out * sigmoid(lse - sinks) silently dropped part of the q/k
gradient (#6329). Now only Flash with FA4 supports that backward; cuDNN
and FA2/FA3 raise.

- VarlenInnerAttention drops cuDNN from its backend priority when an
  out_transform consumes the lse under grad, as deterministic mode already
  does. Our explicit priority otherwise picks cuDNN and the default GPT-OSS
  recipe fails on SM100.
- A10G and MI350X have no FA4: gpt_oss_fsdp+tp+ep switches to flex, and the
  varlen gpt_oss_pp+fsdp+ep+sacop moves to the B200 suite.
tianyu-l added a commit to pytorch/torchtitan that referenced this pull request Nov 26, 2026
Torch before pytorch/pytorch#206398 (RL's pinned nightly) marks the lse
non-differentiable, so FA4 passed the old check while q/k still missed the
gradient through out_transform. Check lse.requires_grad after the call, and
take the RL GPT-OSS varlen test out of CI until RL's torch includes the fix.
tianyu-l added a commit to pytorch/torchtitan that referenced this pull request Nov 26, 2026
#6400)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
GPT-OSS rescales attention output by its sinks using the attention lse:
`y = out * sigmoid(lse - sinks)`. The lse depends on q and k, so their
gradients need the lse's gradient.

- **torch <= dev20261124:** `varlen_attn` marked the returned lse
non-differentiable (`ctx.mark_non_differentiable(lse, rng_state)`).
GPT-OSS on the default `varlen` backend therefore trained with part of
its q/k gradient silently missing (#6329).
- **torch dev20261125 (pytorch/pytorch#206398):** the lse is
differentiable. Only Flash with FA4 implements its backward; cuDNN and
FA2/FA3 raise `NotImplementedError` in backward.

Since that nightly, on `main`:

| Hardware | GPT-OSS + `varlen` training on `main` |
| --- | --- |
| SM100 (FA4), deterministic | works, correct gradients (cuDNN is
already skipped in deterministic mode) |
| SM100 (FA4), default | **raises**: `VarlenInnerAttention` sets
priority `[CUDNN, FLASH]`, which overrides torch's "prefer Flash when
the lse needs a gradient", so cuDNN gets picked |
| A10G (FA2), H100 (FA3), MI350X | **raises** in backward: no FA4 (this
PR raises in forward instead, pointing to flex) |

CI: `gpt_oss_fsdp+tp+ep` (Fake PG and Real PG) and
`gpt_oss_pp+fsdp+ep+sacop` (Real PG) crash on A10G on every run since
the nightly switch.

**Example** (gradient of `y = out * sigmoid(lse - sinks)`, one causal
sequence, T=256, H=4, D=64, bf16 vs fp64 reference, GB300):

```
                     dev20261124            dev20261125
varlen cuDNN         dq err 9.6e-02         NotImplementedError
varlen FA2           dq err 9.6e-02         NotImplementedError
varlen FA4           dq err 9.6e-02         dq err 4.4e-03
flex                 dq err 4.4e-03         dq err 4.4e-03
```

## What changed
- `torchtitan/models/common/attention/attention.py`:
`VarlenInnerAttention` drops cuDNN from the backend priority when an
`out_transform` consumes the lse under grad. That's the same filter
deterministic mode already applies. On SM100, the default GPT-OSS recipe
now trains with FA4 and the full gradient. Only GPT-OSS passes an
`out_transform`, so other models are unaffected.
- Same file: without FA4, that case raises a `ValueError` in forward
that points to `attn_backend='flex'`. Torch's backward error suggests
detaching the lse, which would silently bring back the dropped gradient.
No-grad passes (RL generator, reference model) are unaffected and keep
cuDNN.
- Same file: on torch before pytorch/pytorch#206398, `varlen_attn`
returns an lse with `requires_grad=False` even when q requires grad, so
the FA4 check alone would pass while q/k still miss the gradient.
Forward now raises when `q.requires_grad and not lse.requires_grad`.
This catches exactly that case without parsing versions:

  | torch (GB300, FA4) | `out.requires_grad` | `lse.requires_grad` |
  | --- | --- | --- |
| dev20261030 (same behavior as RL's dev20261107) | True | False ->
raises |
  | dev20261125 | True | True |
- `torchtitan/models/gpt_oss/README.md`: training with the default
varlen backend needs FA4. Other hardware should use the flex recipes.
- `tests/integration_tests/models.py`: A10G and MI350X have no FA4, so
`gpt_oss_fsdp+tp+ep` uses the existing `gpt_oss_debugmodel_flex` recipe.
The config is renamed to `gpt_oss_debugmodel_flex_fsdp4_tp2_ep4`,
matching `gpt_oss_debugmodel_flex_fsdp2_cp2_pp2_ep4_sac`.
- `tests/integration_tests/b200.py`: the varlen test
`gpt_oss_pp+fsdp+ep+sacop` moves here from the A10G/MI350X models suite
(mechanical move). It is the CI coverage of GPT-OSS's default varlen +
sinks path, and only B200 has FA4.
- `tests/integration_tests/rl.py`: `rl_grpo_moe_debug_tp4_ep4`, RL CI's
only GPT-OSS test, leaves CI, with a TODO in the B200 RL list to add it
back. It trained with part of the q/k gradient missing on every GPU,
because RL pins torch dev20261107 through PyTorch's nightly vLLM wheel.
With the check above it raises, and the vLLM generator only supports
varlen, so it can't switch to flex. The recipe stays in
`torchtitan_recipes/tests/rl/alphabet_sort.py`. A10G RL CI keeps
TP=4/EP=4 MoE coverage through
`rl_grpo_moe_debug_tp4_ep4_batch_invariant` (Qwen3 MoE).
- `scripts/install_rl_env.sh`: the existing torch-pin TODO now says RL
can't train GPT-OSS with varlen until RL's torch includes the fix.
- `tests/unit_tests/cpu/.../test_varlen_attention.py`:
`test_out_transform_receives_th_lse` checks the lse shape passed to
`out_transform`, so it now runs under `torch.no_grad()` (CPU has no
FA4).

## Alternatives considered
- **Detach the lse:** keeps the wrong gradients from before.
- **Hardware-skip the varlen tests:** skip keys are `cuda` / `rocm`, not
per GPU, and skipping on A10G and ROCm would leave the default GPT-OSS
path with no coverage.
- **Config-time error instead of forward-time:** the FA implementation
is chosen from the device when the attention config builds, and a config
can be built on a different host than the one it trains on. Forward is
the first point where the device is known, and it raises before any
compute.

## Numerics
- **SM100, deterministic:** unchanged. The `gpt_oss_debugmodel` loss and
grad_norm are bitwise identical before and after on GB300 with torch
dev20261125 (8.02175 / 45.5388, 5.88992 / 16.0247, 5.73024 / 6.5475).
- **SM100, non-deterministic:** used to raise, now trains.
- **Goldens:** `gpt_oss.txt` for `fake_pg/a10g`, `real_pg/a10g` and
`real_pg/mi350x` are regenerated, because `gpt_oss_fsdp+tp+ep` now runs
flex. The old values came from varlen with the lse gradient dropped. The
new values come from this PR's CI (torch dev20261125). The header
becomes `# config: gpt_oss_debugmodel_flex_fsdp4_tp2_ep4`.

| Golden | Step 10 loss / grad_norm, old (varlen) | New (flex) |
| --- | --- | --- |
| `fake_pg/a10g` | 5.02574 / 4.95290 | 5.05224 / 5.40115 |
| `real_pg/a10g` | 3.86363 / 1.83918 | 3.83998 / 1.64099 |
| `real_pg/mi350x` | 3.84717 / 1.70434 | 3.86655 / 1.87447 |

## Testing
- GB300, torch dev20261125, `gpt_oss_debugmodel` 3 steps:
  - non-deterministic: raises on `main`, trains with this PR.
  - deterministic: bitwise identical.
- GB300, torch dev20261125: `run_tests --execution_mode fake_pg
--test_name gpt_oss_fsdp+tp+ep` runs to completion with flex. It only
mismatches the A10G golden, as expected on GB300.
- GB300, `gpt_oss_debugmodel` 3 steps at HEAD: torch dev20261125 trains,
and the deterministic run is still bitwise identical (8.02175 / 45.5388
at step 1). Torch dev20261030 raises the non-differentiable-lse
`ValueError`.
- The lse check isn't verified under a whole-model `torch.compile`. In
`gpt_oss_debugmodel`, attention is outside the compiled regions.
- The B200 suite will run the moved varlen test (8 GPUs). Not run
locally (needs 8 GPUs).

## Known issues / follow-ups
- Closes #6329 once merged.
- RL GPT-OSS training with varlen raises until RL's torch includes
pytorch/pytorch#206398. RL's torch is pinned through PyTorch's
2026-11-07 nightly vLLM wheel, and moving it is blocked on the vLLM 0.33
stack (#5498, #5967). Then `rl_grpo_moe_debug_tp4_ep4` goes back into
the B200 RL suite.
wwwjn added a commit to pytorch/torchtitan that referenced this pull request Dec 1, 2026
… GPT-OSS B200 TODO; note the torch escape hatch

RL now installs the newest torch nightly, which includes pytorch/pytorch#206398. The varlen lse guard stays: torch 2.15, which the release validation installs, does not include it (release/2.15 diverged from the fix).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 ciflow/inductor GL/superseded GreenLight review is superseded by changes in progress PR is being worked on by the author, until the automated review accepts it Merged release notes: inductor (aoti)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants