Repository navigation
[SDPA] Fix 32-bit offset overflow in mem-efficient attention forward with attn_bias - #187684
Merged
Merged
Conversation
…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)
This was referenced Jun 18, 2026
🔗 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 FailuresAs of commit 99c5135 with merge base 636bc91 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This PR needs a
|
drisspg
approved these changes
Jun 22, 2026
atalman
approved these changes
Jun 22, 2026
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]>
20 of 27 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
F.scaled_dot_product_attentionwith the EFFICIENT_ATTENTION backend and anexplicit
attn_masksilently returns garbage for every query row past2^32 / seq_lenoncenum_queries * num_keys > 2^32(i.e. S > 65536 for squareself-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_startisuint32_t:pytorch/aten/src/ATen/native/transformers/cuda/mem_eff_attention/kernel_forward.h
Line 635 in 545c55c
and the per-row offset into the bias tensor is computed as
query_start * p.bias_strideMwherebias_strideMisint32_t, so the multiplyhappens in 32-bit unsigned arithmetic and wraps modulo 2^32:
pytorch/aten/src/ATen/native/transformers/cuda/mem_eff_attention/kernel_forward.h
Line 811 in 545c55c
Past
row = 2^32 / seq_lenthe 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(not2^31 / S) matches theunsigned arithmetic.
The dropout RNG
skipaheadoffset in the same kernel has the same 32-bitmultiply (
(query_start + thread_i) * p.num_keys_absolute). The backward kernelcomputes the equivalent offset with an
int64_tquery_start(
kernel_backward.h), so with dropout + large seq_len the forward and backwarddropout masks diverge past the same boundary, corrupting gradients.
The batch/head-level strides (
bias_strideB/bias_strideH) were alreadywidened to
int64_tpreviously; the per-row offset was missed. Note thesekernels 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-linecasts; in-bounds behavior is bit-identical.
Reproduction (any sm80+ GPU, bf16)
Observed on
2.14.0.dev20260612+cu130(H200, sm90) — corruption onset isexactly
2^32 // Sfor 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
test_mem_eff_attention_large_seq_len_attn_mask_index_overflow(gated by
@largeTensorTest("12GB", "cuda")): explicit additive causal maskvs
is_causal=Trueon the same backend at seq_len=70000. Fails before thisfix (max abs diff 0.54 past row 61356, exact 0 before it), passes after.
kernel_forward.h(pristine vs patched, same CUTLASS pin) into a standalone extension driving
AttentionKernel<bf16, Sm80, true, 64, 64, 64>with identical S=73728inputs. 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.