Repository navigation
Conversation
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". ✅ AUTOMATED REVIEW - Ready for human review:
Findings (1): Reviewed commit: 🔗 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 SEVsThere are 1 currently active SEVs. If your PR is affected, please view them below: ❌ 1 New FailureAs of commit 347437f with merge base 1a2fb1c ( 🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:
reason: NEW FAILURE - The following job has failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
Attention! native_functions.yaml was changedIf 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 changedYou 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. |
8d83bcb to
cbd283b
Compare
9e512d3 to
8cb6dfe
Compare
|
@pytorchbot review |
|
The automated review only re-runs on PRs labeled |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@pytorchbot review |
8cb6dfe to
a0fe42b
Compare
|
Automated review follow-up (a0fe42b): moved the SM100 head-dim-256 check into |
a0fe42b to
c427986
Compare
|
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. |
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
c427986 to
347437f
Compare
There was a problem hiding this comment.
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
pytorch/test/test_varlen_attention.py
Line 361 in 347437f
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
|
Starting merge as part of PR stack under #206399 |
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
… 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.
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.
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.
#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.
… 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).
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_backwardhad no way to receive thatgradient.
Fix. Add an optional
grad_logsumexpkeyword input next tograd_out. With it, thebackward's per-row term becomes
rowsum(dO * O) - dLSE; nothing else in the kernel changes.grad_logsumexpdlse; about 1% extra backward timedlse)activate_flash_attention_impl("FA4")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.compilepasses an all-zerogradient 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) andxpu/attention_backward.cpp:TORCH_CHECK_NOT_IMPLEMENTEDwhen
grad_logsumexpis defined._fa4.py:_fa4_backward_support_errorchecks shape (must matchlogsumexp) and fp32; theSM100 head-dim-256 limit raises
NotImplementedErrorlike the other rejections.dlseispassed only when set, so older FA4 releases without that argument keep working. FA4 makes
dlsecontiguous itself._fa3.pyraises whengrad_logsumexpis set.register_flash_attention_impl's docstring tells providers that overrides of_flash_attention_backwardreceivegrad_logsumexpand must raise if they cannot use it.shim_function_versions.txtregenerated. Meta registration accepts the new kwarg.
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.
submodule bump; it would plug into this argument.
The next commit makes
varlen_attnpass the gradient.Validation
ROCm, and XPU were not run.
grad_logsumexp=None, the new FA4 test fails (dq relative L2 error 0.11 to 0.41 againstfp32); with it, it passes.
test/test_varlen_attention.pyandtest/nn/attention/test_fa4.pypass with only this commitapplied.