Skip to content

fix(attention): stop handing FlashAttention 4 the -1 window sentinel - #3532

Closed
nvegesna-netizen wants to merge 10 commits into
NVIDIA:mainfrom
nvegesna-netizen:nvegesna/fa4-window-sentinel
Closed

nvegesna-netizen wants to merge 10 commits into
NVIDIA:mainfrom
nvegesna-netizen:nvegesna/fa4-window-sentinel

Conversation

@nvegesna-netizen

Copy link
Copy Markdown
Contributor

Problem

FlashAttention 4 returns an all-zero output for causal attention on SM100, silently — no
exception, no warning, finite values, every element zero. Fixes #3528.

No context parallelism is needed to reproduce it:

import torch, transformer_engine.pytorch as te
b, s, h, d = 2, 1024, 8, 128
q, k, v = (torch.randn(b, s, h, d, device="cuda", dtype=torch.bfloat16) for _ in range(3))
dpa = te.DotProductAttention(h, d, qkv_format="bshd", attn_mask_type="causal",
                             attention_dropout=0.0).to(dtype=torch.bfloat16, device="cuda")
print(dpa(q, k, v).abs().max())   # tensor(0., device='cuda:0')

Run it with NVTE_FUSED_ATTN=0 NVTE_UNFUSED_ATTN=0, or cuDNN FusedAttention wins backend
selection for this shape and hides the defect entirely.

Cause

TE normalises an unbounded window side to -1 (check_set_window_size); FA4's sentinel is None.
Until Dao-AILab/flash-attention#2490 a shim widened any pair summing below zero to full attention,
so TE's causal encoding (-1, 0) was always erased and causal=True alone set the mask. #2490
narrowed that to pairs where both bounds are negative, so (-1, 0) now survives as a literal
band of [row + 1, row] — empty. flash_attn/cute/mask.py guards on is not None and uses the
value arithmetically, so the kernel returns zeros and an all -inf LSE.

Measured directly, with TransformerEngine out of the picture:

flash_attn_func(q, k, v, causal=True, window_size=(-1, 0))      # out.abs().max() = 0.0
flash_attn_func(q, k, v, causal=True, window_size=(None, None)) # out.abs().max() = 3.453125

Change

Normalise negative window bounds to None at the FA4 entry points, where the symbols are bound.

Why there rather than at the call sites. The ~20 sites that build these kwargs are shared with
FA2 >= 2.7 and FA3, for which -1 is the correct spelling; rewriting them in place would mean
forking every one on use_flash_attn_4.

Why all four entry points. The non-CP path calls flash_attn_func / flash_attn_varlen_func;
context parallelism calls _flash_attn_fwd / _flash_attn_bwd. Covering only one pair is worse
than covering neither, because run_attention_with_cp.py grades a CP run against a non-CP run of
the same backend: with both sides returning zeros the comparison agrees and passes, so correcting
one side alone makes the fix present as a regression. That is not hypothetical — an earlier partial
attempt did exactly that, turning two passing arms red.

Genuine sliding windows already carry non-negative bounds and pass through untouched.

Verification (B200, SM100)

check result
non-CP causal through DotProductAttention 3.453125e+00, was 0.000000e+00; relerr vs float64 2.046e-03
sliding windows (256,0), (128,0), (0,0) relerr 2.046e-03, 2.046e-03, 0.000e+00
CP with FA4 on: p2p bshd/sbhd/thd 3/3 pass — p2p failed before this change
CP with FA4 on: all_gather, a2a bshd/sbhd 4/4 pass — were passing before, and still are
CP with FA4 off (control) 3/3 pass
test_fa4_window_sentinel.py 12 passed
test_attention.py sweep (regression) 487 passed, 138 skipped, 0 failed

Numerics are graded against a float64 reference, never against another backend. That matters
here: the defect survived because the CP suite compares against a run of the same backend, so an
error present on both sides cancels. float64 rather than float32 because torch computes fp32
matmuls in TF32 on Ampere and newer, whose significand is 11 bits — the same as fp16 — so an fp32
reference cannot judge a bf16 kernel.

Tests

tests/pytorch/attention/test_fa4_window_sentinel.py, registered in qa/L0_pytorch_unittest:

  • eleven parametrized cases for the normalizer, which run on any machine, including that a genuine
    sliding window such as (511, 0) is passed through unchanged
  • one end-to-end case, skipped unless FA4 is installed on SM100, pinned to FlashAttention and
    anchored to a float64 reference. It asserts a non-zero output separately from the tolerance
    check, so the specific failure is named rather than reported as a large error.

Note on CI

Three independent reasons this was invisible, each worth addressing on its own and none of them
fixed here:

  1. NVTE_FLASH_ATTN_V4=0 is exported in qa/L1_pytorch_distributed_unittest/test.sh and the L0
    suites, so FA4 is never exercised under context parallelism.
  2. CI pins flash-attn-4==4.0.0b11, which predates cute: don't widen intentionally-empty offset windows to full attention Dao-AILab/flash-attention#2490.
  3. run_attention_with_cp.py grades a CP run against a non-CP run of the same backend, so it
    cannot detect any error affecting both equally. Two of the three comm types reported PASS on a
    backend that was returning zeros.

nvegesna-netizen and others added 2 commits September 17, 2026 00:15
FA4 returns an all-zero output for causal attention on SM100, silently. No
exception, no warning, finite values, every element zero. Measured against a
float64 reference on B200, with no context parallelism involved:

    flash_attn_func(q, k, v, causal=True, window_size=(-1, 0))
        out.abs().max() = 0.0            relerr = 1.000e+00
    flash_attn_func(q, k, v, causal=True, window_size=(None, None))
        out.abs().max() = 3.453125       relerr = 2.046e-03

TE normalizes an unbounded window side to -1; FA4 spells it None. Until
flash-attention NVIDIA#2490 a shim widened any pair summing below zero to full
attention, so TE's (-1, 0) was always erased and causal= alone set the mask.
NVIDIA#2490 narrowed that to pairs where both bounds are negative, so (-1, 0) now
survives as a literal band of [row + 1, row] -- empty. The kernel returns zeros
and an all -inf LSE.

Normalizing negative bounds to None at the four FA4 entry points, rather than at
the ~20 sites that build these kwargs: those sites are shared with FA2 >= 2.7 and
FA3, where -1 is the correct spelling, so fixing them in place would mean forking
every one on use_flash_attn_4.

All four entry points, not just the two used by context parallelism. The non-CP
path calls flash_attn_func/flash_attn_varlen_func; CP calls
_flash_attn_fwd/_flash_attn_bwd. Covering one pair is worse than covering
neither, because run_attention_with_cp.py grades a CP run against a non-CP run of
the same backend: with both sides zero the comparison agrees, and correcting one
side alone makes the fix present as a regression. That is not hypothetical --
it is what an earlier partial attempt did.

Three reasons CI could not see this, all still worth addressing separately:
NVTE_FLASH_ATTN_V4=0 in the distributed suite, a flash-attn-4 pin predating
NVIDIA#2490, and the self-referential comparison above, which cannot detect any error
affecting CP and non-CP equally.

The new test anchors to a float64 reference rather than to another backend, and
pins FlashAttention -- cuDNN FusedAttention wins selection for the shape under
test and would mask the defect entirely.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com>
It lives in dot_product_attention.py, not utils.py, so the GPU arm of the new
test failed at import on B200 while the eleven parametrized cases passed. The
behaviour it checks was separately confirmed in the same run -- a non-CP forward
through DotProductAttention returned 3.453125e+00 against 0.000000e+00 before the
fix, relerr 2.046e-03 -- so this is the test reaching the assertion, not a change
in what is being asserted.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com>
@github-actions github-actions Bot added the community-contribution PRs from external contributor outside the core maintainers, representing community-driven work. label Sep 17, 2026
@greptile-apps

greptile-apps Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[High risk] Changes how attention window parameters reach FlashAttention 4.

The PR appears safe to merge, with both previous findings resolved and no new actionable issues introduced since the previous review.

Summary

This PR prevents FlashAttention 4 from receiving Transformer Engine’s -1 unbounded-window sentinel, which FA4 can interpret as an empty causal window and silently return all-zero attention output.

  • Adds an FA4-specific wrapper that converts -1 window bounds to None across dense, variable-length, context-parallel forward, and context-parallel backward entry points.
  • Leaves non-negative sliding-window bounds unchanged.
  • Adds normalization coverage and an SM100 end-to-end numerical regression test that pins and verifies FA4 backend selection.
  • Changes since the previous review only shorten explanatory comments and docstrings; runtime behavior is unchanged.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Transformer Engine window bounds] --> B[FA4 entry-point wrapper]
  B -->|bound equals -1| C[Convert bound to None]
  B -->|non-negative bound| D[Preserve bound]
  C --> E[FlashAttention 4]
  D --> E
  E --> F[Dense or variable-length attention]
  E --> G[Context-parallel forward or backward]
Loading

Reviews (9) · Last reviewed commit: "refactor(attention): condense the FA4 se..." · Reviewed by Greptile

Comment thread qa/L0_pytorch_unittest/test.sh Resolved
qa/L0_pytorch_unittest exports NVTE_FLASH_ATTN_V4=0, and the skip condition
checked flash_attn_func_v4 is None -- an import binding that env var does not
affect. So on an SM100 L0 job the test would not skip: it would run, TE would
decline FA4, fall through to FA2 (the same lane sets NVTE_FLASH_ATTN_V2=1), and
pass while measuring a backend the test is not written for.

A green test that exercises the wrong backend is the failure mode this fix exists
to close, so relying on the lane to have FA4 enabled is the wrong dependency. The
test now pins NVTE_FLASH_ATTN_V4=1 alongside the fused and unfused disables, and
asserts the selected backend reports version 4 before grading any numbers. That
makes it correct in any lane and stops a future lane quietly opting it out.

Reported by greptile-apps on NVIDIA#3532, which flagged that the L0 runner disables FA4;
the fall-through to FA2 is the part that makes it a false green rather than a skip.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com>
nvegesna-netizen added a commit to nvegesna-netizen/TransformerEngine that referenced this pull request Sep 17, 2026
qa/L0_pytorch_unittest exports NVTE_FLASH_ATTN_V4=0, and the skip condition
checked flash_attn_func_v4 is None -- an import binding that env var does not
affect. So on an SM100 L0 job the test would not skip: it would run, TE would
decline FA4, fall through to FA2 (the same lane sets NVTE_FLASH_ATTN_V2=1), and
pass while measuring a backend the test is not written for.

A green test that exercises the wrong backend is the failure mode this fix exists
to close, so relying on the lane to have FA4 enabled is the wrong dependency. The
test now pins NVTE_FLASH_ATTN_V4=1 alongside the fused and unfused disables, and
asserts the selected backend reports version 4 before grading any numbers. That
makes it correct in any lane and stops a future lane quietly opting it out.

Reported by greptile-apps on NVIDIA#3532, which flagged that the L0 runner disables FA4;
the fall-through to FA2 is the part that makes it a false green rather than a skip.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
nvegesna-netizen added a commit to nvegesna-netizen/TransformerEngine that referenced this pull request Sep 17, 2026
It read as the only backend serving symmetric head_dim in (256, 512] with
context parallelism. That was true when written and is now imprecise:
Dao-AILab/flash-attention#2877 adds symmetric D512 kernels to FA4, and with the
window-sentinel fix in NVIDIA#3532 that path works too.

Qualified to released components, which is the claim that actually holds -- NVIDIA#2877
is unmerged and unreviewed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
nvegesna-netizen and others added 2 commits September 22, 2026 06:04
Review asked whether the -1 to None translation should sit behind a version
gate keyed on the FA4 release that changed the sentinel. It does not need one,
and the reason is worth recording where the next reader will look.

Transcribing flash-attention's _resolve_causal_local_window from before NVIDIA#2490
(interface.py @ 59cf537812) and after it, and running every (causal, window)
pair TE emits through both:

  mask type              b11 as-is       b11 normalized   post-2490 as-is
  causal                 CAUSAL          CAUSAL           LOCAL left=-1 right=0
  causal_bottom_right    CAUSAL          CAUSAL           LOCAL left=-1 right=0
  no_mask                FULL            FULL             FULL
  sliding window         LOCAL 511/0     LOCAL 511/0      LOCAL 511/0

Normalizing changes nothing on the older release, because the old code reaches
the same resolved state from (-1, 0) by widening that the new code reaches from
(None, 0) directly. So the translation is inert before the change and corrective
after it, with no version boundary to get wrong. All four entry points funnel
through that one resolver, on both releases, so the trace covers them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com>
Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com>
nvegesna-netizen added a commit to nvegesna-netizen/TransformerEngine that referenced this pull request Sep 26, 2026
It read as the only backend serving symmetric head_dim in (256, 512] with
context parallelism. That was true when written and is now imprecise:
Dao-AILab/flash-attention#2877 adds symmetric D512 kernels to FA4, and with the
window-sentinel fix in NVIDIA#3532 that path works too.

Qualified to released components, which is the claim that actually holds -- NVIDIA#2877
is unmerged and unreviewed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com>
nvegesna-netizen added a commit to nvegesna-netizen/TransformerEngine that referenced this pull request Sep 26, 2026
It read as the only backend serving symmetric head_dim in (256, 512] with
context parallelism. That was true when written and is now imprecise:
Dao-AILab/flash-attention#2877 adds symmetric D512 kernels to FA4, and with the
window-sentinel fix in NVIDIA#3532 that path works too.

Qualified to released components, which is the claim that actually holds -- NVIDIA#2877
is unmerged and unreviewed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com>
@cyanguwa cyanguwa added the 2.21 label Sep 28, 2026
@sudhakarsingh27

Copy link
Copy Markdown
Member

Pls also fix the DCO

@ptrendx

ptrendx commented Sep 29, 2026

Copy link
Copy Markdown
Member

Following up on the DCO request above: @nvegesna-netizen Please sign every commit in this PR. See https://github.com/NVIDIA/TransformerEngine/blob/main/CONTRIBUTING.rst#sign-your-work

FA4 widens a window to full attention only when both bounds are negative, so a lone negative
bound is a valid request for an empty window. Matching on `bound < 0` would silently turn one of
those into full attention; `== -1` translates exactly TE's sentinel and leaves every other value
with its FA4 meaning. It also matches how TE spells this sentinel elsewhere, including
utils.py:1435, which already treats a non-(-1) negative as a genuine sliding window.

Folds the normalizer and the decorator into one function, and drops the kwargs-passthrough test,
which checked nothing about windows.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com>
@nvegesna-netizen
nvegesna-netizen force-pushed the nvegesna/fa4-window-sentinel branch from ec5a7de to e718fc8 Compare October 1, 2026 07:17
…on.py

A file and an L0 entry for two tests on a one-line fix is not worth it. The directory already
carries 14 test files, and the rest each cover a backend or subsystem rather than a bug fix.

Nothing is dropped: the module docstring's reasoning moves into a section comment above the
tests, since it explains why the numerical test is anchored to a float64 reference rather than to
another backend, which is the thing that made the bug detectable at all.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com>
Consequence of moving this test into test_attention.py: it now shares a process with tests that
set NVTE_FLASH_ATTN=0, and several of those do not restore it. utils.py derives
use_flash_attention_4 as (NVTE_FLASH_ATTN and NVTE_FLASH_ATTN_V4), so an inherited 0 disables FA4
whatever the v4 switch says, and the backend assertion then fails rather than grading the fix.

The save and restore iterate the pinned dict, so the new key is covered by both.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com>
@sudhakarsingh27

Copy link
Copy Markdown
Member

/te-ci pytorch L0 L1

sudhakarsingh27 added a commit to sudhakarsingh27/TransformerEngine that referenced this pull request Oct 6, 2026
FA4 b33 treats TE's -1 unbounded window sentinel as a literal offset, so
the D=256 coverage in this PR needs the adapter from NVIDIA#3532 at all four FA4
entry points. Bring that final adapter change into this branch instead of
leaving the new FA4 path dependent on another open PR.

Keep the regression tests in test_attention_backend_selection.py alongside
the focused FA4 tests. Cover both window argument forms and preserved
negative offsets, compare every batch and head with a float64 reference,
and run these cases under the FA4 b33 L3 lane.

Signed-off-by: Sudhakar Singh <sudhakars@nvidia.com>
The new prose ran long for its surroundings. backends.py has a median docstring
of 1 line and only one of 28 reaches 10; this helper's was 16, the second
longest in the file. test_attention.py has a median of 1 and a max of 9, and
carried a 15-line banner.

Kept the facts a reader cannot derive: that FA4 widens a window only when both
bounds are negative, which turns TE's causal (-1, 0) into an empty band and an
all-zero output with nothing raised; that only -1 is rewritten because a lone
negative is a valid empty-window request; and why all four backend switches are
pinned in the end-to-end test. Cut the rationale the PR description already
carries.

Helper docstring 16 lines to 6, test banner 15 to 3, end-to-end docstring 8 to
5. No code changed: verified by comparing ASTs with docstrings stripped.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com>
sudhakarsingh27 added a commit that referenced this pull request Oct 12, 2026
* Update FA4 D=256 capability gates

FA4 b31 added seqused_q/k forward support for the SM100 D=256 kernel, while b33 added backward support. Select FA4 by the installed release and actual backward eligibility, retain the deterministic backward guard, and exercise the released b33 dependency stack in L3.

Signed-off-by: Sudhakar Singh <sudhakars@nvidia.com>

* Cover FA4 D=256 seqused paths

Protect the release boundary with focused selector cases and extend the existing no-load-balance CP test to run D=256. This verifies the existing all-gather metadata path without adding strategy-specific production plumbing.

Signed-off-by: Sudhakar Singh <sudhakars@nvidia.com>

* Integrate FA4 window sentinel handling into D=256 coverage

FA4 b33 treats TE's -1 unbounded window sentinel as a literal offset, so
the D=256 coverage in this PR needs the adapter from #3532 at all four FA4
entry points. Bring that final adapter change into this branch instead of
leaving the new FA4 path dependent on another open PR.

Keep the regression tests in test_attention_backend_selection.py alongside
the focused FA4 tests. Cover both window argument forms and preserved
negative offsets, compare every batch and head with a float64 reference,
and run these cases under the FA4 b33 L3 lane.

Signed-off-by: Sudhakar Singh <sudhakars@nvidia.com>

* Shorten FA4 sentinel regression explanations

Keep the adapter comment focused on the sentinel contract and the FA4-only boundary. Name the numerical test for its independent reference and remove the redundant all-zero assertion, which singled out one symptom already caught by the full-output comparison.

Signed-off-by: Sudhakar Singh <sudhakars@nvidia.com>

* Remove redundant FA4 float64 reference test

The standalone D=128 BSHD comparison does not exercise the D=256 THD path added by this PR. Keep the direct window-sentinel regression in L3; existing attention tests provide numerical comparisons.

Signed-off-by: Sudhakar Singh <sudhakars@nvidia.com>

* Restore FA4 numerical sentinel regression

The argument-only sentinel test cannot prove the adapted FA4 call produces correct attention; generic cross-backend comparisons may skip. Restore the independent reference check and keep only representative left, right, and non-sentinel cases for both window argument forms.

Signed-off-by: Sudhakar Singh <sudhakars@nvidia.com>

* Update FA4 L3 dependency and backend coverage

CUTLASS DSL 4.8.0 recognizes SM107 while the previous pin does not, so keep the FA4 L3 dependency and installation guidance aligned. Running the small backend-selection module directly covers its eligibility and window-sentinel cases without a bespoke node list. Clarify that non-all-gather THD metadata depends on pad_between_seqs.

Signed-off-by: Sudhakar Singh <sudhakars@nvidia.com>

* Keep FA4 regression tests focused on model configs

A dedicated D=256 model preserves separate QK and V dimensions without a one-off runner override. Exclude it from the broad CP matrix because the no-load-balance test already exercises the intended path. The L3 causal cross-backend cases cover numerical behavior, so retain the sentinel unit test and remove the redundant standalone reference test.

Signed-off-by: Sudhakar Singh <sudhakars@nvidia.com>

* Keep FA4 expectation explicit in CP test

Query backend availability before deciding whether to skip the D=256 case. Supported FA4 b33 configurations should fail when FA4 is unexpectedly unavailable, while unsupported configurations still skip. Keep the general no-Flash skip separate from the D=256 assertion.

Signed-off-by: Sudhakar Singh <sudhakars@nvidia.com>

* Keep full CP model catalogs for focused tests

The earlier D=256 broad-matrix exclusion kept cp_2_4 in the essential FlashAttention catalog solely for the focused no-load-balance case. That mixes model availability with test selection. Keep the full FlashAttention and FusedAttention catalogs available to the runner and focused tests, and narrow only the essential broad CP parametrizations. Non-essential broad runs continue to use the full catalog.

Signed-off-by: Sudhakar Singh <sudhakars@nvidia.com>

---------

Signed-off-by: Sudhakar Singh <sudhakars@nvidia.com>
@sudhakarsingh27

Copy link
Copy Markdown
Member

Closing since #3540 went that addresses this FA4 sentinel issue as well

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

Labels

2.21 attention community-contribution PRs from external contributor outside the core maintainers, representing community-driven work.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FA4 returns an all-zero output for causal attention on SM100 after flash-attention #2490

5 participants