Repository navigation
[SDPA] Fix 32-bit offset overflow in mem-efficient attention forward with attn_bias - #187225
bin123apple wants to merge 2 commits into
Conversation
…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]>
🔗 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 FailureAs of commit 0616c0c with merge base 096c3b3 ( 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. |
|
One or more co-authors of this pull request were not found. You must specify co-authors in commit message trailer via: Supported
Alternatively, if the co-author should not be included, remove the Please update your commit message(s) by doing |
|
@pytorchbot label "release notes: cuda" |
|
/easycla |
There was a problem hiding this comment.
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_biaspointer offset computation inkernel_forward.hto 64-bit to prevent wraparound for largeQKsizes. - Widen the forward-pass dropout
skipaheadoffset 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=Truefor largeseq_lento 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. |
| 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 |
|
If you can reduce the test case slightly per copilot's suggestion looks good. |
|
This isn't also an issue in the backward pass, right? |
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
b948cd5 to
0616c0c
Compare
I think the backward pass is not affected. In |
|
@pytorchbot merge |
Merge startedYour 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 |
Merge failedReason: 2 jobs have failed, first few of them are: trunk / linux-jammy-rocm-py3.10-mi350 / test (default, 4, 8, amd-do-linux.rocm.gpu.gfx950.1), trunk / linux-jammy-rocm-py3.10-mi350 / test (default, 1, 8, amd-do-linux.rocm.gpu.gfx950.1) Details for Dev Infra teamRaised by workflow job |
|
@Skylion007 The merge attempts have each been blocked by different unrelated ROCm flaky failures. Anything needed from my side? Thanks! |
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 4 checks: B200 Smoke Tests / linux-jammy-cuda13.0-py3.10-gcc11-sm100 / test (smoke_b200, 1, 1, linux.dgx.b200), trunk / linux-jammy-rocm-py3.10-mi350 / test (default, 1, 8, amd-do-linux.rocm.gpu.gfx950.1), trunk / linux-jammy-rocm-py3.10-mi350 / test (default, 4, 8, amd-do-linux.rocm.gpu.gfx950.1), trunk / linux-jammy-rocm-py3.10-mi350 / test (default, 6, 8, amd-do-linux.rocm.gpu.gfx950.1) Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
|
@pytorchbot cherry-pick --help |
|
❌ 🤖 pytorchbot command failed: Try |
|
@pytorchbot cherry-pick --onto release/2.13 -c critical |
Cherry picking #187225The 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 teamRaised by workflow job |
…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]>
…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]>
…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]>
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.