Skip to content

[gpt_oss] Varlen sinks: keep cuDNN out of the backward through the lse - #6400

Merged
tianyu-l merged 7 commits into
mainfrom
gpt-oss-varlen-sinks-flash
Nov 26, 2026
Merged

tianyu-l merged 7 commits into
mainfrom
gpt-oss-varlen-sinks-flash

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

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.

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 [sdpa] Add grad_logsumexp input to _flash_attention_backward 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

@pytorch-bot pytorch-bot Bot added ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 25, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 25, 2026
@github-actions
github-actions Bot requested a review from drisspg November 25, 2026 23:19
@tianyu-l tianyu-l added ciflow/real-pg Run the full 8-GPU Real PG integration suite ciflow/rocm labels Nov 25, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 9s —— View job


Approve -- please address the items before merging (empty human summary, regenerate goldens, TODO link for the lse case, keep use_real_pg=True): review

@claude claude 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.

Verdict: Approve -- please address the items below before merging. The fix is in the right place. Since the lse became differentiable, the explicit [CUDNN, FLASH] priority overrides torch's own "prefer Flash when the lse needs a gradient", and this PR stops that. The remaining items are mechanical. A maintainer still needs to review, because this touches models/common/.

What this PR does. VarlenInnerAttention drops cuDNN from its backend priority when an out_transform consumes the lse under grad. That is the same filter deterministic mode already applies. On GPUs without FA4, the GPT-OSS FSDP+TP+EP integration test moves to flex. The varlen PP+FSDP+EP test moves to the B200 suite.

Example. GPT-OSS gpt_oss_debugmodel, torch dev20261125, non-deterministic:

                       main                          this PR
GB300 (FA4)            cuDNN picked -> backward      FA4 picked -> full q/k grad
                       NotImplementedError
H100 / A10G / MI350X   cuDNN -> backward raises      FA2/FA3 -> backward raises
                                                     (unchanged; see inline)
no_grad (RL generator) cuDNN                         cuDNN (unchanged)
deterministic          Flash                         Flash (bitwise identical)

Must fix

  1. The "Summary (human-written)" section is empty. The author needs to fill it in.
  2. Goldens: tests/assets/losses/{fake_pg/a10g,real_pg/a10g,real_pg/mi350x}/gpt_oss.txt still hold varlen values for gpt_oss_debugmodel_fsdp4_tp2_ep4, which were computed with the lse gradient dropped. Regenerate them from this PR's CI, as the description's TODO says. The # config: header is updated when you regenerate.
  3. torchtitan/models/common/attention/attention.py:514 -- the TODO doesn't cover the lse case, and it has no upstream link (inline).
  4. tests/integration_tests/b200.py:334 -- the "mechanical" move drops use_real_pg=True (inline).

Should consider

  • torchtitan/models/common/attention/attention.py:519 -- without FA4, raise in forward and point users at flex. Today, torch's backward error suggests detaching, which brings #6329 back (inline).
  • torchtitan/models/gpt_oss/README.md -- "Supported Features" doesn't mention that training with the default varlen backend now needs FA4 (SM100), and that other hardware should use the flex recipe. Line 37 still lists gpt_oss_pp+fsdp+ep+sacop as if it runs in the main CI; it now runs only on B200.
Details
  • Layer: out_transform is a generic VarlenInnerAttention contract, and the lse-backward limitation belongs to the kernel, not to GPT-OSS. A filter in common code is therefore fine, even though GPT-OSS (torchtitan/models/gpt_oss/model.py:140) is the only consumer today. Putting sdpa_backends=["FLASH_ATTENTION"] in the GPT-OSS flavors would also drop cuDNN from no-grad inference.
  • torch.is_grad_enabled(): forward and remat recompute both run with grad enabled (activation_remat.py has no no_grad or reentrant path), so forward and recompute pick the same backend. RL generator and reference-model passes run under no_grad and keep cuDNN.
  • Coverage: the B200 test sets no deterministic mode, so it exercises the new filter on SM100. That only happens once the B200 workflow's torch pin passes dev20261125. Until then, no CI job runs varlen with the lse gradient. The description says this.

Not verified: GPU behavior (FA4 selection on SM100, the backward error text on FA2/FA3/ROCm).

Comment on lines +514 to +518
# TODO: Remove the deterministic case once the cuDNN varlen backward
# honors use_deterministic_algorithms (upstream issue not filed yet). It
# neither raises nor runs deterministically, so repeated runs differ.
# cuDNN also has no backward for the lse that out_transform consumes;
# only Flash with FA4 does, and other implementations raise in backward.

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.

The TODO covers only the deterministic case. The lse case also works around an upstream gap (cuDNN, FA2 and FA3 have no lse backward), but it has no removal condition and no issue link. If torch adds an lse backward to cuDNN later, nothing here tells a reader this filter can go. Add a TODO for the lse case too, linking pytorch/pytorch#206398 or a follow-up issue for the cuDNN lse backward:

Suggested change
# TODO: Remove the deterministic case once the cuDNN varlen backward
# honors use_deterministic_algorithms (upstream issue not filed yet). It
# neither raises nor runs deterministically, so repeated runs differ.
# cuDNN also has no backward for the lse that out_transform consumes;
# only Flash with FA4 does, and other implementations raise in backward.
# TODO: Remove the deterministic case once the cuDNN varlen backward
# honors use_deterministic_algorithms (upstream issue not filed yet). It
# neither raises nor runs deterministically, so repeated runs differ.
# TODO(<upstream issue>): Remove the lse case once cuDNN implements the
# backward for the lse that out_transform consumes. Since
# pytorch/pytorch#206398 only Flash with FA4 does; others raise in backward.

Comment on lines +519 to +520
lse_needs_grad = out_transform is not None and torch.is_grad_enabled()
if torch.are_deterministic_algorithms_enabled() or lse_needs_grad:

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.

Should consider: on A10G, H100 and ROCm, this filter picks Flash (FA2/FA3), which then raises NotImplementedError in the first backward. According to the PR description, torch's message suggests detaching the lse, and detaching brings back the silently dropped q/k gradient from #6329. You already compute fa_impl at line 499, so a forward-time check costs about 4 lines. It fails before any compute and points users at the right fix:

if lse_needs_grad and fa_impl != "FA4":
    raise ValueError(
        "Backpropagating through out_transform's lse needs FA4 (SM100). "
        "Use FlexInnerAttention (e.g. gpt_oss_debugmodel_flex) on this hardware."
    )

The check would need a TODO next to it, so it gets removed once torch adds an lse backward for FA2/FA3. Unverified: I couldn't confirm what current_flash_attention_impl() returns on ROCm.

configs=[gpt_oss_debugmodel_fsdp4_pp2_ep4_sac],
test_descr="GPT-OSS PP+FSDP+EP+selective AC with VarlenInnerAttention",
test_name="gpt_oss_pp+fsdp+ep+sacop",
ngpu=8,

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.

The description calls this a mechanical move, but the entry drops use_real_pg=True. The config uses PP=2. If someone runs the b200 suite with --execution_mode fake_pg, validate_fake_pg_compatibility (tests/integration_tests/__init__.py:98) raises, and --test_scope real_pg_required would skip this test. CI isn't affected today, because the B200 workflow runs real_pg with scope all. Keep the flag:

Suggested change
ngpu=8,
ngpu=8,
use_real_pg=True,

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.
Values from this PR's CI under torch 2.16.0.dev20261125: Fake PG and Real PG
on A10G, Real PG on MI350X.
@tianyu-l
tianyu-l force-pushed the gpt-oss-varlen-sinks-flash branch from 36a6b5d to 2c1f7b2 Compare November 26, 2026 04:59
Its trainer backpropagates through the varlen lse, which needs FA4 (SM100).
Note in install_rl_env.sh that RL's pinned torch still drops that gradient.
@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 1s —— View job


Approve -- please address the items before merging (the empty human-written summary, plus a README paragraph to reorder): review

@claude claude 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.

Verdict: Approve -- please address the items below before merging. HEAD resolves every code item from the previous review. The only thing still missing is the human-written summary. A maintainer still needs to review, because this touches models/common/.

What this PR does. In VarlenInnerAttention, when an out_transform consumes the lse under grad, cuDNN is dropped from the backend priority. If FA4 isn't active, it raises a ValueError in forward that points to flex. On hardware without FA4, the GPT-OSS integration and RL tests move to flex or to the B200 suites.

Example. GPT-OSS gpt_oss_debugmodel on varlen, torch dev20261125:

                        main                               this PR
GB300, default          cuDNN -> backward raises           FA4, full q/k grad
GB300, deterministic    FA4                                FA4 (bitwise identical)
H100 / A10G / MI350X    FA2/FA3/cuDNN -> backward raises   ValueError in forward -> use flex
no_grad (RL gen, ref)   cuDNN                              cuDNN (unchanged)

Earlier items

  • Goldens regenerated, with the header gpt_oss_debugmodel_flex_fsdp4_tp2_ep4: resolved.
  • TODO for the lse case, now referencing pytorch/pytorch#206398: resolved.
  • use_real_pg=True on the moved B200 test: resolved.
  • Raise in forward without FA4: resolved (attention.py:522).
  • README note on FA4 and B200: resolved.

Must fix

  1. The "Summary (human-written)" section of the description is still empty. The author has to fill it in.

Should consider

  • torchtitan/models/gpt_oss/README.md:39 -- the new paragraph separates "Those jobs use Interleaved1F1B" from the CI list it refers to (inline).
Details
  • fa_impl comes from current_flash_attention_impl(), which VarlenInnerAttention.__init__ (attention.py:428) activates through activate_cuda_flash_attention_impl(). On ROCm and SM<9.0 it is None, so the new check raises there. That matches moving the A10G/MI350X tests to flex.
  • CP varlen (cp_attention.py:387) goes through _forward_varlen as well, so the check covers CP too.
  • Remaining varlen GPT-OSS training callers in CI: only the moved B200 test and the B200 RL test. The graph_trainer GPT-OSS numerics configs already use flex. graph_trainer_gpt_oss_debugmodel (varlen) has no test consumer.
  • Remat recompute runs with grad enabled, so forward and recompute pick the same backend.

Not verified: FA4 selection and the lse backward on SM100 (needs a GPU run); B200 CI results for the moved tests.

Comment on lines +39 to +42
The attention sinks rescale the output by `sigmoid(lse - sinks)`, so training
backpropagates through the attention lse. With the default `varlen` backend
only FA4 (SM100) supports that backward, and other hardware raises a
`ValueError`; use the flex recipes (`attn_backend="flex"`) there.

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.

Should consider: this paragraph sits between the CI job list and "Those jobs use Interleaved1F1B..." (line 44), so "Those jobs" now follows the sinks paragraph and its referent is unclear. Move this paragraph below the PP paragraph that ends at "Full-backward schedules ... are unaffected.", so the CI list and its follow-up stay together.

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

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 1s —— View job


Approve -- please address the items before merging (the empty human-written summary, plus torchtitan/rl/README.md still lists GPT-OSS RL as supported): review

@claude claude 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.

Verdict: Approve -- please address the items below before merging. The new commit (fb658e3) closes a real gap: on RL's pinned torch, FA4 passed the old check while q/k still silently missed the lse gradient. What's left is description and docs. A maintainer still needs to review, because this touches models/common/.

What changed since the last review. _forward_varlen now raises after the kernel call when q.requires_grad and not lse.requires_grad, which is exactly the case of a torch from before pytorch/pytorch#206398. rl_grpo_moe_debug_tp4_ep4 leaves CI, and a TODO in the B200 RL list says when to add it back.

Example. GPT-OSS on varlen, GB300 (FA4):

torch                    before fb658e3                     at HEAD
dev20261107 (RL pin)     trains, q/k miss the lse gradient  ValueError -> newer torch or flex
dev20261125 (core CI)    FA4, full gradient                 FA4, full gradient (unchanged)
no_grad (RL gen, ref,    cuDNN                              cuDNN (q.requires_grad is False,
 validator)                                                  so the check doesn't fire)

Must fix

  1. The "Summary (human-written)" section of the description is still empty. The author has to fill it in.
  2. torchtitan/rl/README.md:45 still lists GPT-OSS as "Supported". With this PR, anyone who sets up RL with scripts/install_rl_env.sh (pinned to the dev20261107 nightly) and runs rl_grpo_gpt_oss_20b_varlen gets the new ValueError on the first trainer forward. On non-SM100 hardware it raises even with a newer torch, and the vLLM generator only supports varlen. Change the row to say that GPT-OSS RL training needs SM100 plus a torch that includes pytorch/pytorch#206398, and that it is blocked until RL's torch pin moves. Link the TODO in install_rl_env.sh.

Should consider

  • torchtitan/models/gpt_oss/README.md:39 -- still open from the last review. The sinks paragraph sits between the CI list and "Those jobs use Interleaved1F1B", which refers to that list.
Details
  • Placement of the new check: it runs only when out_transform is not None, after the kernel. Torch's backend choice can't be checked before the call, so this placement is the earliest possible. It costs one kernel call before raising on the first forward.
  • No false positives in the CI paths I checked. The RL bitwise-parity GPT-OSS test (tests/rl/unit_tests/gpu/test_bitwise_parity.py) runs trainer forwards under torch.no_grad(). The validator (components/validator.py:281) and the RL logprob/reference passes also use no_grad. Remat recompute runs with grad enabled, and q.requires_grad is True there, so forward and recompute behave the same.
  • The two grad signals differ: the FA4 check uses torch.is_grad_enabled() and the lse check uses q.requires_grad. They only disagree for a grad-enabled forward on inputs that don't require grad. No in-repo caller does that, so I'm not asking for a change.
  • rl_grpo_moe_debug_tp4_ep4 keeps config-level coverage in tests/rl/unit_tests/cpu/test_alphabet_sort.py. The TODO in rl.py names the condition for re-adding it.

Not verified: the dev20261107 and dev20261125 behavior of the check on GPU (I relied on the author's GB300 runs); behavior under a whole-model torch.compile.

@tianyu-l
tianyu-l merged commit 0dd145d into main Nov 26, 2026
38 of 39 checks passed
IvanKobzarev added a commit to IvanKobzarev/torchtitan that referenced this pull request Dec 1, 2026
Port the Cuspy configuration and golden-loss updates from pytorch#6390 and pytorch#6398. Use the GPT-OSS attention backend split from pytorch#6400 so varlen LSE backward runs on FA4 hardware. Select both Gloo and NCCL for the Muon CPU-offload test mesh.
acisseJZhong added a commit that referenced this pull request Dec 1, 2026
Per review: GPT-OSS varlen training needs FA4, and #6400 already covers it
on B200. Remove the GraphTrainer GPT-OSS bitwise tests (varlen and flex),
the H100 GPT-OSS loss-compare test and its recipes, and the two skipped
GPT-OSS trace tests.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/real-pg Run the full 8-GPU Real PG integration suite ciflow/rl ciflow/rocm CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[GPT-OSS] Incorrect gradients produced by varlen attention backend

3 participants