Skip to content

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

Merged
atalman merged 1 commit into
release/2.13from
cherry-pick-187225-by-pytorch_bot_bot_
Jun 22, 2026
Merged

atalman merged 1 commit into
release/2.13from
cherry-pick-187225-by-pytorch_bot_bot_

Conversation

@pytorchbot

Copy link
Copy Markdown
Collaborator

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.

…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

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
(cherry picked from commit 77abe15)
@pytorch-bot

pytorch-bot Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 99c5135 with merge base 636bc91 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot

pytorch-bot Bot commented Jun 18, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@atalman
atalman merged commit a6ab33a into release/2.13 Jun 22, 2026
129 checks passed
he-yufeng added a commit to he-yufeng/pytorch that referenced this pull request Jun 24, 2026
The per-(batch, head) dropout RNG offset in the mem-efficient attention
kernels is

    (batch_id * num_heads + head_id) * num_queries * num_keys

and is evaluated in 32-bit, so it wraps once num_queries * num_keys passes
2^32 (seq_len > 65536, or smaller with several heads/batches). Two problems
follow once it wraps:

- The forward pass does the whole multiply in 32-bit, while the backward
  pass already has an int64_t batch_id but still forms the
  num_heads * num_queries * num_keys product in 32-bit. They disagree at
  large sizes, so the dropout mask applied in the backward pass no longer
  matches the one from the forward pass and the gradients are wrong.
- Different (batch, head) slots collapse onto the same wrapped offset and
  stop being masked independently.

This is the same class of overflow as pytorch#187684 (which widened the attn_bias
and dropout skipahead offsets); widen the remaining dropout offset on both
sides so it always carries the true 64-bit value.

Added test_mem_eff_attention_dropout_rng_offset_no_overflow, which uses
seq_len == 65536 (num_queries * num_keys == 2^32 exactly) so every offset
wraps to 0, feeds two heads identical q/k/v, and checks the heads are still
masked independently.

Signed-off-by: Yufeng He <[email protected]>
@github-actions
github-actions Bot deleted the cherry-pick-187225-by-pytorch_bot_bot_ branch July 23, 2026 02:24
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.

4 participants