Skip to content

[Triton/Gluon] Fix NaN dq in Triton MHA backward when every logit of a row is very n… - #6428

Merged
azaidy merged 4 commits into
ROCm:mainfrom
Abdennacer-Badaoui:fa-bwd-dq-nan-fix
Oct 21, 2026
Merged

azaidy merged 4 commits into
ROCm:mainfrom
Abdennacer-Badaoui:fa-bwd-dq-nan-fix

Conversation

@Abdennacer-Badaoui

Copy link
Copy Markdown
Contributor

Fix NaNs in Triton MHA backward

The Triton MHA backward can produce NaNs in dq when attention logits are extremely negative (logsumexp < -88). Reproduced on Qwen2.5-1.5B (layer 15, head 7, logits around -100) while running TRL's Async GRPO on MI300X. These NaNs propagate through subsequent gradients and break training.

Root cause: The dq loop recomputes p = exp(qk * scale - lse) without masking out-of-range keys in the unmasked branch. Since these keys are loaded as zero, exp(-lse) can overflow to inf, and inf * 0 produces NaNs. This occurs in the last row block when the sequence length is not block-aligned.

Fix: Apply the key-range mask to p in mha_onekernel_bwd.py and both dq loops in flash_attn_triton_amd/bwd.py.

Tests (MI300X):

  • Added test_mha_backward_varlen_very_negative_logits for both implementations. Fails on main, passes with the fix.
  • test_mha.py -k backward: 238 passed, no new failures.
  • test_mha_dao_ai.py: 37 passed, unchanged from main.
  • On captured Qwen2.5 tensors, dq goes from 384 NaNs to 0 and matches an FP32 reference.

Performance: No measurable regression. Forward + backward on 16 sequences of ~2k tokens (BF16, causal, 32 Q / 8 KV heads, head dim 128):

  • Block-aligned: 9.80 ms vs. 9.74–9.83 ms.
  • Ragged: 10.09 ms vs. 10.05–10.08 ms.

The same fix is proposed for the vendored aiter-flash-attn copy in huggingface/kernels-community.

…egative

In the backward pass, the dq loop recomputes p = exp(qk * scale - lse). In the
unmasked part of the loop, keys past end_n are loaded as 0 but p was not masked
for them, so p = exp(-lse) there. When every logit of a query row is very
negative (lse < -88), exp(-lse) overflows to inf and inf * k(=0) writes NaN
into dq. This happens on real activations (Qwen2.5-1.5B, layer 15, head 7) and
turns every gradient below that layer into NaN.

Mask p with the key-range mask in the unmasked branch, in the one-kernel
backward and in both dq loops of the dao_ai backward. Add a regression test
with logits around -100 and sequence lengths that are not block multiples.
@Abdennacer-Badaoui
Abdennacer-Badaoui requested a review from a team October 12, 2026 09:42
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 6428 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

@github-actions github-actions Bot changed the title Fix NaN dq in Triton MHA backward when every logit of a row is very n… [Triton/Gluon] Fix NaN dq in Triton MHA backward when every logit of a row is very n… Oct 12, 2026
@Boss2002n
Boss2002n requested a balanced review from Copilot October 12, 2026 17:33

Copilot AI 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.

🟡 Changes recommended

The modified split-mode backward branch lacks regression coverage.

1 open finding
What changed in this PR

Fixes NaN dq gradients in Triton MHA backward for ragged sequences with extremely negative logits.

Changes:

  • Masks out-of-range key probabilities in three backward loops.
  • Adds regression coverage for default and DAO AI implementations.
File Description
aiter/​ops/​triton/​_triton_kernels/​attention/​mha_onekernel_bwd.py Masks invalid keys in one-kernel backward.
aiter/​ops/​triton/​_triton_kernels/​flash_attn_triton_amd/​bwd.py Masks invalid keys in fused and split backward paths.
op_tests/​triton_tests/​attention/​test_mha.py Adds a ragged, negative-logit regression test.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

The dao_ai varlen backward defaults to the fused mode, so the dq loop of the
split mode (_bwd_dq_inner_split) was not exercised. Add a case that runs it
with the same input.
@zufayu

zufayu commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

@aiter-bot review

@aiter-bot

Copy link
Copy Markdown

aiter-bot — queued behind 1 review(s); expect to start in about 50 min. The box reviews one PR at a time.

vgokhale
vgokhale previously approved these changes Oct 14, 2026
@aiter-bot

Copy link
Copy Markdown

ROCm/aiter PR #6428 — [Triton/Gluon] Fix NaN dq in Triton MHA backward when every logit of a row is very negative

Masks out-of-range keys in the recomputed attention probabilities of the three non-causal dq loops of the Triton MHA backward, so that exp(-m) overflowing to inf on zero-loaded padding keys can no longer put inf*0 = NaN into dq when a row's logsumexp drops below ~-88.

Review (advisory): ⚠️ NEEDS WORK
Validation (deterministic): NOT RUN — REVIEW_AUTO_VALIDATE=0 disabled the auto-run (the required target op_tests/triton_tests/attention/test_mha.py existed; no idle GPU here either) — environment gap, not a PR defect
Perf (advisory): NOT RUN — triaged target op_tests/triton_tests/attention/test_mha.py ships no benchmark entry point, and no idle GPU here (8/8 at 99% util) to hand-run one; the PR's own hand timing (fwd+bwd, 16 seqs of ~2k tokens, bf16, causal: block-aligned 9.80 vs 9.74–9.83 ms base, ragged 10.09 vs 10.05–10.08 ms base) is unverified

⚠️ [verified] The fix covers the three dq loops that store dq behind a row mask, but the two backward modes that accumulate dq with atomic adds still recompute p unmasked in their MASK=False branch — flash_attn_triton_amd/bwd.py:1209-1214 leaves pT unmasked and its dq atomic_add at bwd.py:1260-1265 is masked only by query-row validity, and the same structure sits in the sibling mha_fused_bwd.py:254-259 with a row-only-masked atomic add at mha_fused_bwd.py:324-330 — so on this PR's own repro shape (causal, seqlens 300/250, logits ≈ -102) the padding keys of a partial key block still yield pT = exp(-m) = inf and inf*0 = NaN would land in dq for in-range rows via dao_ai BWD_MODE="fused_atomic" or mha_set_use_fused_bwd_kernel(True), neither of which the new test's default/fused/split parametrization exercises. Author must apply the same key-range mask to pT in both atomic loops (or state why they are immune) and extend the test's parametrization to those two modes.

📝 [verified] op_tests/triton_tests/attention/test_mha.py ships no benchmark entry point, so the deterministic perf stage can never time MHA backward and this PR's no-regression claim rests solely on the author's hand run. Reviewer should ask for a @benchmark/run_perftest entry (the harness test_mla_v4_triton.py:164 already uses) so future MHA backward changes get base-vs-head timing in CI.

@zufayu

zufayu commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

Where that review came from — I ran the bot on your PR to show what it does. It is not an automatic hook; nothing reviews your PR unless somebody asks.

Any reviewer on the aiter allowlist can ask for one, on any PR including their own. The trigger is a comment containing the words below — shown quoted here, because quoted lines deliberately do not trigger it:

@aiter-bot review

  • Reviews the PR at its current head. Comment again after pushing fixes for a fresh pass; a repeat on the same commit is deduped.
  • One review runs at a time on one box, roughly 20 minutes. If work is ahead of you the bot replies with your place in the queue, and if the runner is down it says so rather than leaving you waiting for a review that will never start.
  • The card is advisory. It never blocks a merge, 🔴 included — it is there to be argued with.

Feedback on the review itself is welcome; it is how the rules get better.

@azaidy azaidy assigned vgokhale and unassigned brunomazzottiamd Oct 14, 2026

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

LGTM!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants