Skip to content

[SDPA] Fix 32-bit offset overflow in mem-efficient attention forward with attn_bias - #187225

Closed
bin123apple wants to merge 2 commits into
pytorch:mainfrom
bin123apple:fix-memeff-bias-32bit-overflow
Closed

bin123apple wants to merge 2 commits into
pytorch:mainfrom
bin123apple:fix-memeff-bias-32bit-overflow

Conversation

@bin123apple

Copy link
Copy Markdown
Contributor

Summary

F.scaled_dot_product_attention with the EFFICIENT_ATTENTION backend and an
explicit attn_mask silently returns garbage for every query row past
2^32 / seq_len once num_queries * num_keys > 2^32 (i.e. S > 65536 for square
self-attention). No error, no warning, no NaN — the corrupted values look
plausible, which makes this extremely hard to attribute downstream (we found it
as silently diverging RL training metrics).

Root cause

In kernel_forward.h, query_start is uint32_t:

const uint32_t query_start = blockIdx.x * kQueriesPerBlock;

and the per-row offset into the bias tensor is computed as
query_start * p.bias_strideM where bias_strideM is int32_t, so the multiply
happens in 32-bit unsigned arithmetic and wraps modulo 2^32:

const_cast<scalar_t*>(p.attn_bias_ptr + query_start * p.bias_strideM + iter_key_start),

Past row = 2^32 / seq_len the kernel reads the mask from wrapped addresses
(typically an earlier row of the same tensor), producing wrong attention for
those rows. Corruption onset at exactly 2^32 / S (not 2^31 / S) matches the
unsigned arithmetic.

The dropout RNG skipahead offset in the same kernel has the same 32-bit
multiply ((query_start + thread_i) * p.num_keys_absolute). The backward kernel
computes the equivalent offset with an int64_t query_start
(kernel_backward.h), so with dropout + large seq_len the forward and backward
dropout masks diverge past the same boundary, corrupting gradients.

The batch/head-level strides (bias_strideB/bias_strideH) were already
widened to int64_t previously; the per-row offset was missed. Note these
kernels were vendored from xformers, which has since removed its in-tree CUTLASS
FMHA sources, so the fix needs to land here.

Fix

Compute both offsets in 64-bit, matching kernel_backward.h. Two one-line
casts; in-bounds behavior is bit-identical.

Reproduction (any sm80+ GPU, bf16)

import torch
import torch.nn.functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel

S, HD = 73728, 64                        # S^2 = 1.27 * 2^32
torch.manual_seed(0)
q = torch.randn(1, 1, S, HD, device="cuda", dtype=torch.bfloat16) * 0.1
k = torch.randn(1, 1, S, HD, device="cuda", dtype=torch.bfloat16) * 0.1
v = torch.randn(1, 1, S, HD, device="cuda", dtype=torch.bfloat16)
idx = torch.arange(S, device="cuda")
causal = (idx[:, None] >= idx[None, :])[None, None]

ref = F.scaled_dot_product_attention(q, k, v, is_causal=True)   # ground truth
with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION):
    out = F.scaled_dot_product_attention(q, k, v, attn_mask=causal)

B = 2**32 // S   # predicted corruption onset = row 58254
print((out - ref)[0, 0, :B].abs().max())   # ~6e-5  (bf16 noise)
print((out - ref)[0, 0, B:].abs().max())   # ~0.39  (garbage)

Observed on 2.14.0.dev20260612+cu130 (H200, sm90) — corruption onset is
exactly 2^32 // S for every S tested (73728→58254, 81920→52428, 98304→43690,
90000→47721). The MATH backend with the same mask tensor is correct everywhere,
confirming the mask contents are fine and the bug is in the kernel's indexing.
is_causal=True (no mask tensor) is unaffected.

Test plan

  • Added test_mem_eff_attention_large_seq_len_attn_mask_index_overflow
    (gated by @largeTensorTest("12GB", "cuda")): explicit additive causal mask
    vs is_causal=True on the same backend at seq_len=70000. Fails before this
    fix (max abs diff 0.54 past row 61356, exact 0 before it), passes after.
  • Verified the kernel change directly on H200: compiled kernel_forward.h
    (pristine vs patched, same CUTLASS pin) into a standalone extension driving
    AttentionKernel<bf16, Sm80, true, 64, 64, 64> with identical S=73728
    inputs. Pristine reproduces the corruption bit-for-bit with the stock binary
    (max diff 0.39 past row 58254); patched returns bf16-noise-level diff
    (6.1e-5) everywhere, and is bit-identical to pristine for all in-bounds rows.

AI assistance (Claude) was used to locate the overflow and prepare this PR; the
change and verification were reviewed end-to-end by the submitter.

…tn_bias

When an attn_bias is present and num_queries * num_keys > 2^32, the
per-row bias offset `query_start * p.bias_strideM` in the forward
kernel was computed in 32-bit arithmetic (query_start is uint32_t) and
wrapped around, so the kernel silently read the mask from wrong
addresses: the output of every query row past 2^32 / seq_len is garbage,
with no error or warning.

The dropout RNG skipahead offset in the same kernel had the same 32-bit
wraparound; the backward pass computes that offset in 64-bit, so with
dropout enabled the forward and backward dropout masks diverged past the
same boundary.

Compute both offsets in 64-bit, matching what kernel_backward.h already
does. Add a regression test gated by largeTensorTest(12GB).

Co-Authored-By: Claude Fable 5 <[email protected]>
@pytorch-bot

pytorch-bot Bot commented Jun 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 3 New Failures, 1 Unrelated Failure

As of commit 0616c0c with merge base 096c3b3 (image):

NEW FAILURES - The following jobs have failed:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

@linux-foundation-easycla

linux-foundation-easycla Bot commented Jun 13, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

One or more co-authors of this pull request were not found. You must specify co-authors in commit message trailer via:

Co-authored-by: name <email>

Supported Co-authored-by: formats include:

  1. Anything <[email protected]> - it will locate your GitHub user by id part.
  2. Anything <[email protected]> - it will locate your GitHub user by login part.
  3. Anything <public-email> - it will locate your GitHub user by public-email part. Note that this email must be made public on Github.
  4. Anything <other-email> - it will locate your GitHub user by other-email part but only if that email was used before for any other CLA as a main commit author.
  5. login <any-valid-email> - it will locate your GitHub user by login part, note that login part must be at least 3 characters long.

Alternatively, if the co-author should not be included, remove the Co-authored-by: line from the commit message.

Please update your commit message(s) by doing git commit --amend and then git push [--force] and then request re-running CLA check via commenting on this pull request:

/easycla

@bin123apple

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "release notes: cuda"

@pytorch-bot pytorch-bot Bot added the release notes: cuda release notes category label Jun 13, 2026
@bin123apple

Copy link
Copy Markdown
Contributor Author

/easycla

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.

Pull request overview

Fixes a silent correctness bug in CUDA mem-efficient SDPA (EFFICIENT_ATTENTION) where 32-bit offset arithmetic could wrap when num_queries * num_keys > 2^32, causing wrong reads from attn_bias (and potentially incorrect dropout RNG offsets), and adds a regression test to cover large-sequence masked attention.

Changes:

  • Widen per-row attn_bias pointer offset computation in kernel_forward.h to 64-bit to prevent wraparound for large QK sizes.
  • Widen the forward-pass dropout skipahead offset computation to 64-bit to match backward’s 64-bit indexing behavior.
  • Add a large-tensor CUDA test that compares explicit additive causal masks vs is_causal=True for large seq_len to catch the overflow regression.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
test/test_transformers.py Adds a large-sequence regression test for masked mem-efficient attention correctness past the 32-bit wrap boundary.
aten/src/ATen/native/transformers/cuda/mem_eff_attention/kernel_forward.h Uses 64-bit math for bias pointer and dropout RNG skipahead offsets to avoid 32-bit overflow.

Comment thread test/test_transformers.py Resolved
Comment thread test/test_transformers.py Outdated
out = torch.nn.functional.scaled_dot_product_attention(
query, key, value, attn_mask=attn_mask
)
# before the fix, all rows past 2**32 // seq_len (= 61356) were garbage
@Skylion007

Copy link
Copy Markdown
Collaborator

If you can reduce the test case slightly per copilot's suggestion looks good.

@Skylion007

Copy link
Copy Markdown
Collaborator

This isn't also an issue in the backward pass, right?

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
@bin123apple
bin123apple force-pushed the fix-memeff-bias-32bit-overflow branch from b948cd5 to 0616c0c Compare June 13, 2026 19:50
@bin123apple

Copy link
Copy Markdown
Contributor Author

This isn't also an issue in the backward pass, right?

I think the backward pass is not affected. In kernel_backward.h the equivalent
per-row bias offset is already computed with an int64_t query_start, so it
doesn't overflow; this PR just brings the forward kernel in line with that.

@Skylion007
Skylion007 requested review from eqy and ngimel June 13, 2026 20:38
@Skylion007 Skylion007 added this to the 2.14.0 milestone Jun 15, 2026
@Skylion007 Skylion007 added the module: correctness (silent) issue that returns an incorrect result silently label Jun 16, 2026
@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jun 16, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@bin123apple

Copy link
Copy Markdown
Contributor Author

@Skylion007 The merge attempts have each been blocked by different unrelated ROCm flaky failures. Anything needed from my side? Thanks!

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot cherry-pick --help

@pytorch-bot

pytorch-bot Bot commented Jun 18, 2026

Copy link
Copy Markdown

❌ 🤖 pytorchbot command failed:

@pytorchbot cherry-pick: error: the following arguments are required: --onto/--into, -c/--classification

usage: @pytorchbot cherry-pick --onto ONTO [--fixes FIXES] -c
                               {regression,critical,fixnewfeature,docs,release}

Try @pytorchbot --help for more info.

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot cherry-pick --onto release/2.13 -c critical

@pytorchbot

Copy link
Copy Markdown
Collaborator

Cherry picking #187225

The cherry pick PR is at #187684 and it is recommended to link a critical cherry pick PR with an issue. The following tracker issues are updated:

Details for Dev Infra team Raised by workflow job

atalman pushed a commit that referenced this pull request Jun 22, 2026
…with attn_bias (#187684)

[SDPA] Fix 32-bit offset overflow in mem-efficient attention forward with attn_bias (#187225)

## Summary

`F.scaled_dot_product_attention` with the **EFFICIENT_ATTENTION** backend and an
explicit `attn_mask` **silently returns garbage** for every query row past
`2^32 / seq_len` once `num_queries * num_keys > 2^32` (i.e. S > 65536 for square
self-attention). No error, no warning, no NaN — the corrupted values look
plausible, which makes this extremely hard to attribute downstream (we found it
as silently diverging RL training metrics).

## Root cause

In `kernel_forward.h`, `query_start` is `uint32_t`:

https://github.com/pytorch/pytorch/blob/545c55c1724bafed6772a0b85fecfd09f9aa0dbb/aten/src/ATen/native/transformers/cuda/mem_eff_attention/kernel_forward.h#L635

and the per-row offset into the bias tensor is computed as
`query_start * p.bias_strideM` where `bias_strideM` is `int32_t`, so the multiply
happens in 32-bit unsigned arithmetic and wraps modulo 2^32:

https://github.com/pytorch/pytorch/blob/545c55c1724bafed6772a0b85fecfd09f9aa0dbb/aten/src/ATen/native/transformers/cuda/mem_eff_attention/kernel_forward.h#L811

Past `row = 2^32 / seq_len` the kernel reads the mask from wrapped addresses
(typically an earlier row of the same tensor), producing wrong attention for
those rows. Corruption onset at exactly `2^32 / S` (not `2^31 / S`) matches the
unsigned arithmetic.

The dropout RNG `skipahead` offset in the same kernel has the same 32-bit
multiply (`(query_start + thread_i) * p.num_keys_absolute`). The backward kernel
computes the equivalent offset with an `int64_t` `query_start`
(`kernel_backward.h`), so with dropout + large seq_len the forward and backward
dropout masks diverge past the same boundary, corrupting gradients.

The batch/head-level strides (`bias_strideB`/`bias_strideH`) were already
widened to `int64_t` previously; the per-row offset was missed. Note these
kernels were vendored from xformers, which has since removed its in-tree CUTLASS
FMHA sources, so the fix needs to land here.

## Fix

Compute both offsets in 64-bit, matching `kernel_backward.h`. Two one-line
casts; in-bounds behavior is bit-identical.

## Reproduction (any sm80+ GPU, bf16)

```python
import torch
import torch.nn.functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel

S, HD = 73728, 64                        # S^2 = 1.27 * 2^32
torch.manual_seed(0)
q = torch.randn(1, 1, S, HD, device="cuda", dtype=torch.bfloat16) * 0.1
k = torch.randn(1, 1, S, HD, device="cuda", dtype=torch.bfloat16) * 0.1
v = torch.randn(1, 1, S, HD, device="cuda", dtype=torch.bfloat16)
idx = torch.arange(S, device="cuda")
causal = (idx[:, None] >= idx[None, :])[None, None]

ref = F.scaled_dot_product_attention(q, k, v, is_causal=True)   # ground truth
with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION):
    out = F.scaled_dot_product_attention(q, k, v, attn_mask=causal)

B = 2**32 // S   # predicted corruption onset = row 58254
print((out - ref)[0, 0, :B].abs().max())   # ~6e-5  (bf16 noise)
print((out - ref)[0, 0, B:].abs().max())   # ~0.39  (garbage)
```

Observed on `2.14.0.dev20260612+cu130` (H200, sm90) — corruption onset is
exactly `2^32 // S` for every S tested (73728→58254, 81920→52428, 98304→43690,
90000→47721). The MATH backend with the same mask tensor is correct everywhere,
confirming the mask contents are fine and the bug is in the kernel's indexing.
`is_causal=True` (no mask tensor) is unaffected.

## Test plan

- Added `test_mem_eff_attention_large_seq_len_attn_mask_index_overflow`
  (gated by `@largeTensorTest("12GB", "cuda")`): explicit additive causal mask
  vs `is_causal=True` on the same backend at seq_len=70000. Fails before this
  fix (max abs diff 0.54 past row 61356, exact 0 before it), passes after.
- Verified the kernel change directly on H200: compiled `kernel_forward.h`
  (pristine vs patched, same CUTLASS pin) into a standalone extension driving
  `AttentionKernel<bf16, Sm80, true, 64, 64, 64>` with identical S=73728
  inputs. Pristine reproduces the corruption bit-for-bit with the stock binary
  (max diff 0.39 past row 58254); patched returns bf16-noise-level diff
  (6.1e-5) everywhere, and is bit-identical to pristine for all in-bounds rows.

AI assistance (Claude) was used to locate the overflow and prepare this PR; the
change and verification were reviewed end-to-end by the submitter.
Pull Request resolved: #187225
Approved by: https://github.com/Skylion007



(cherry picked from commit 77abe15)

Co-authored-by: Bin Lei <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…with attn_bias (pytorch#187225)

## Summary

`F.scaled_dot_product_attention` with the **EFFICIENT_ATTENTION** backend and an
explicit `attn_mask` **silently returns garbage** for every query row past
`2^32 / seq_len` once `num_queries * num_keys > 2^32` (i.e. S > 65536 for square
self-attention). No error, no warning, no NaN — the corrupted values look
plausible, which makes this extremely hard to attribute downstream (we found it
as silently diverging RL training metrics).

## Root cause

In `kernel_forward.h`, `query_start` is `uint32_t`:

https://github.com/pytorch/pytorch/blob/545c55c1724bafed6772a0b85fecfd09f9aa0dbb/aten/src/ATen/native/transformers/cuda/mem_eff_attention/kernel_forward.h#L635

and the per-row offset into the bias tensor is computed as
`query_start * p.bias_strideM` where `bias_strideM` is `int32_t`, so the multiply
happens in 32-bit unsigned arithmetic and wraps modulo 2^32:

https://github.com/pytorch/pytorch/blob/545c55c1724bafed6772a0b85fecfd09f9aa0dbb/aten/src/ATen/native/transformers/cuda/mem_eff_attention/kernel_forward.h#L811

Past `row = 2^32 / seq_len` the kernel reads the mask from wrapped addresses
(typically an earlier row of the same tensor), producing wrong attention for
those rows. Corruption onset at exactly `2^32 / S` (not `2^31 / S`) matches the
unsigned arithmetic.

The dropout RNG `skipahead` offset in the same kernel has the same 32-bit
multiply (`(query_start + thread_i) * p.num_keys_absolute`). The backward kernel
computes the equivalent offset with an `int64_t` `query_start`
(`kernel_backward.h`), so with dropout + large seq_len the forward and backward
dropout masks diverge past the same boundary, corrupting gradients.

The batch/head-level strides (`bias_strideB`/`bias_strideH`) were already
widened to `int64_t` previously; the per-row offset was missed. Note these
kernels were vendored from xformers, which has since removed its in-tree CUTLASS
FMHA sources, so the fix needs to land here.

## Fix

Compute both offsets in 64-bit, matching `kernel_backward.h`. Two one-line
casts; in-bounds behavior is bit-identical.

## Reproduction (any sm80+ GPU, bf16)

```python
import torch
import torch.nn.functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel

S, HD = 73728, 64                        # S^2 = 1.27 * 2^32
torch.manual_seed(0)
q = torch.randn(1, 1, S, HD, device="cuda", dtype=torch.bfloat16) * 0.1
k = torch.randn(1, 1, S, HD, device="cuda", dtype=torch.bfloat16) * 0.1
v = torch.randn(1, 1, S, HD, device="cuda", dtype=torch.bfloat16)
idx = torch.arange(S, device="cuda")
causal = (idx[:, None] >= idx[None, :])[None, None]

ref = F.scaled_dot_product_attention(q, k, v, is_causal=True)   # ground truth
with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION):
    out = F.scaled_dot_product_attention(q, k, v, attn_mask=causal)

B = 2**32 // S   # predicted corruption onset = row 58254
print((out - ref)[0, 0, :B].abs().max())   # ~6e-5  (bf16 noise)
print((out - ref)[0, 0, B:].abs().max())   # ~0.39  (garbage)
```

Observed on `2.14.0.dev20260612+cu130` (H200, sm90) — corruption onset is
exactly `2^32 // S` for every S tested (73728→58254, 81920→52428, 98304→43690,
90000→47721). The MATH backend with the same mask tensor is correct everywhere,
confirming the mask contents are fine and the bug is in the kernel's indexing.
`is_causal=True` (no mask tensor) is unaffected.

## Test plan

- Added `test_mem_eff_attention_large_seq_len_attn_mask_index_overflow`
  (gated by `@largeTensorTest("12GB", "cuda")`): explicit additive causal mask
  vs `is_causal=True` on the same backend at seq_len=70000. Fails before this
  fix (max abs diff 0.54 past row 61356, exact 0 before it), passes after.
- Verified the kernel change directly on H200: compiled `kernel_forward.h`
  (pristine vs patched, same CUTLASS pin) into a standalone extension driving
  `AttentionKernel<bf16, Sm80, true, 64, 64, 64>` with identical S=73728
  inputs. Pristine reproduces the corruption bit-for-bit with the stock binary
  (max diff 0.39 past row 58254); patched returns bf16-noise-level diff
  (6.1e-5) everywhere, and is bit-identical to pristine for all in-bounds rows.

AI assistance (Claude) was used to locate the overflow and prepare this PR; the
change and verification were reviewed end-to-end by the submitter.
Pull Request resolved: pytorch#187225
Approved by: https://github.com/Skylion007

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…with attn_bias (pytorch#187225)

## Summary

`F.scaled_dot_product_attention` with the **EFFICIENT_ATTENTION** backend and an
explicit `attn_mask` **silently returns garbage** for every query row past
`2^32 / seq_len` once `num_queries * num_keys > 2^32` (i.e. S > 65536 for square
self-attention). No error, no warning, no NaN — the corrupted values look
plausible, which makes this extremely hard to attribute downstream (we found it
as silently diverging RL training metrics).

## Root cause

In `kernel_forward.h`, `query_start` is `uint32_t`:

https://github.com/pytorch/pytorch/blob/545c55c1724bafed6772a0b85fecfd09f9aa0dbb/aten/src/ATen/native/transformers/cuda/mem_eff_attention/kernel_forward.h#L635

and the per-row offset into the bias tensor is computed as
`query_start * p.bias_strideM` where `bias_strideM` is `int32_t`, so the multiply
happens in 32-bit unsigned arithmetic and wraps modulo 2^32:

https://github.com/pytorch/pytorch/blob/545c55c1724bafed6772a0b85fecfd09f9aa0dbb/aten/src/ATen/native/transformers/cuda/mem_eff_attention/kernel_forward.h#L811

Past `row = 2^32 / seq_len` the kernel reads the mask from wrapped addresses
(typically an earlier row of the same tensor), producing wrong attention for
those rows. Corruption onset at exactly `2^32 / S` (not `2^31 / S`) matches the
unsigned arithmetic.

The dropout RNG `skipahead` offset in the same kernel has the same 32-bit
multiply (`(query_start + thread_i) * p.num_keys_absolute`). The backward kernel
computes the equivalent offset with an `int64_t` `query_start`
(`kernel_backward.h`), so with dropout + large seq_len the forward and backward
dropout masks diverge past the same boundary, corrupting gradients.

The batch/head-level strides (`bias_strideB`/`bias_strideH`) were already
widened to `int64_t` previously; the per-row offset was missed. Note these
kernels were vendored from xformers, which has since removed its in-tree CUTLASS
FMHA sources, so the fix needs to land here.

## Fix

Compute both offsets in 64-bit, matching `kernel_backward.h`. Two one-line
casts; in-bounds behavior is bit-identical.

## Reproduction (any sm80+ GPU, bf16)

```python
import torch
import torch.nn.functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel

S, HD = 73728, 64                        # S^2 = 1.27 * 2^32
torch.manual_seed(0)
q = torch.randn(1, 1, S, HD, device="cuda", dtype=torch.bfloat16) * 0.1
k = torch.randn(1, 1, S, HD, device="cuda", dtype=torch.bfloat16) * 0.1
v = torch.randn(1, 1, S, HD, device="cuda", dtype=torch.bfloat16)
idx = torch.arange(S, device="cuda")
causal = (idx[:, None] >= idx[None, :])[None, None]

ref = F.scaled_dot_product_attention(q, k, v, is_causal=True)   # ground truth
with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION):
    out = F.scaled_dot_product_attention(q, k, v, attn_mask=causal)

B = 2**32 // S   # predicted corruption onset = row 58254
print((out - ref)[0, 0, :B].abs().max())   # ~6e-5  (bf16 noise)
print((out - ref)[0, 0, B:].abs().max())   # ~0.39  (garbage)
```

Observed on `2.14.0.dev20260612+cu130` (H200, sm90) — corruption onset is
exactly `2^32 // S` for every S tested (73728→58254, 81920→52428, 98304→43690,
90000→47721). The MATH backend with the same mask tensor is correct everywhere,
confirming the mask contents are fine and the bug is in the kernel's indexing.
`is_causal=True` (no mask tensor) is unaffected.

## Test plan

- Added `test_mem_eff_attention_large_seq_len_attn_mask_index_overflow`
  (gated by `@largeTensorTest("12GB", "cuda")`): explicit additive causal mask
  vs `is_causal=True` on the same backend at seq_len=70000. Fails before this
  fix (max abs diff 0.54 past row 61356, exact 0 before it), passes after.
- Verified the kernel change directly on H200: compiled `kernel_forward.h`
  (pristine vs patched, same CUTLASS pin) into a standalone extension driving
  `AttentionKernel<bf16, Sm80, true, 64, 64, 64>` with identical S=73728
  inputs. Pristine reproduces the corruption bit-for-bit with the stock binary
  (max diff 0.39 past row 58254); patched returns bf16-noise-level diff
  (6.1e-5) everywhere, and is bit-identical to pristine for all in-bounds rows.

AI assistance (Claude) was used to locate the overflow and prepare this PR; the
change and verification were reviewed end-to-end by the submitter.
Pull Request resolved: pytorch#187225
Approved by: https://github.com/Skylion007

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 ciflow/trunk Trigger trunk jobs on your pull request Merged module: correctness (silent) issue that returns an incorrect result silently open source release notes: cuda release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants