pytorch - ✅(Solved) Fix `_scaled_dot_product_efficient_attention_backward` meta kernel predicts wrong output strides at batch >= 65536 [2 pull requests, 2 comments, 2 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
pytorch/pytorch#180445Fetched 2026-04-17 08:22:33
View on GitHub
Comments
2
Participants
2
Timeline
50
Reactions
1
Participants
Assignees
Timeline (top)
subscribed ×19mentioned ×18labeled ×5commented ×2

torch.compile crashes on the backward pass of nn.MultiheadAttention when batch >= 65536.

The CUDA kernel has two code paths (aten/src/ATen/native/transformers/cuda/attention_backward.cu:1047):

  • batch <= 65535: calls the backward kernel directly, which allocates its own output
  • batch >= 65536: chunks the batch, pre-allocates output via at::empty_strided(..., input.strides()). This clones the input's strides.

The meta kernel (torch/_meta_registrations.py:6057) always predicts strides via torch.empty_permuted((B,H,S,D), (0,2,1,3)), which is matching only the first path. When inductor passes non-contiguous inputs, the strides diverge and assert_size_stride fails.

Error Message

import torch

attn = torch.nn.MultiheadAttention(embed_dim=512, num_heads=1, batch_first=True, device="cuda") compiled = torch.compile(attn)

q = torch.rand(65536, 1, 512, device="cuda") kv = torch.rand(65536, 10, 512, device="cuda") mask = torch.randint(0, 2, (65536, 10), dtype=torch.bool, device="cuda")

out = compiled(query=q, key=kv, value=kv, key_padding_mask=mask, attn_mask=None, need_weights=False)[0] out.sum().backward()

AssertionError: expected size 65536==65536, stride 512==5120 at dim=0;

expected size 10==10, stride 33554432==512 at dim=2

Error in op: torch.ops.aten._scaled_dot_product_efficient_attention_backward.default

Root Cause

torch.compile crashes on the backward pass of nn.MultiheadAttention when batch >= 65536.

The CUDA kernel has two code paths (aten/src/ATen/native/transformers/cuda/attention_backward.cu:1047):

  • batch <= 65535: calls the backward kernel directly, which allocates its own output
  • batch >= 65536: chunks the batch, pre-allocates output via at::empty_strided(..., input.strides()). This clones the input's strides.

The meta kernel (torch/_meta_registrations.py:6057) always predicts strides via torch.empty_permuted((B,H,S,D), (0,2,1,3)), which is matching only the first path. When inductor passes non-contiguous inputs, the strides diverge and assert_size_stride fails.

Fix Action

Fix / Workaround

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 48 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 8 On-line CPU(s) list: 0-7 Vendor ID: AuthenticAMD Model name: AMD EPYC 7R13 Processor CPU family: 25 Model: 1 Thread(s) per core: 2 Core(s) per socket: 4 Socket(s): 1 Stepping: 1 BogoMIPS: 5300.00 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid extd_apicid aperfmperf tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm cmp_legacy cr8_legacy abm sse4a misalignsse 3dnowprefetch topoext ssbd ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 invpcid rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 clzero xsaveerptr rdpru wbnoinvd arat npt nrip_save vaes vpclmulqdq rdpid Hypervisor vendor: KVM Virtualization type: full L1d cache: 128 KiB (4 instances) L1i cache: 128 KiB (4 instances) L2 cache: 2 MiB (4 instances) L3 cache: 16 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-7 Vulnerability Gather data sampling: Not affected Vulnerability Ghostwrite: Not affected Vulnerability Indirect target selection: Not affected Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Old microcode: Not affected Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Mitigation; Safe RET Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Retpolines; IBPB conditional; IBRS_FW; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected Vulnerability Srbds: Not affected Vulnerability Tsa: Mitigation; Clear CPU buffers Vulnerability Tsx async abort: Not affected Vulnerability Vmscape: Not affected

PR fix notes

PR #597: Skip patch_sdpa_bool_causal_mask below 65536 seq_len to fix Gemma4 VRAM regression

Description (problem / solution / changelog)

Summary

  • Early exit from patch_sdpa_bool_causal_mask's wrapper when both query seq_len and mask key length are below 2**16, so short / medium context training bypasses the workaround entirely
  • Keeps the Qwen3.5 long context fix (unslothai/unsloth#4906, PR #587) in place for seq_len >= 65536
  • Recovers 2.55 GB of reserved VRAM on Gemma4-31B LoRA SFT, restoring pre 2026.4.7 memory with no loss or grad norm changes

Root cause

PR #587 installed a wrapper around transformers.integrations.sdpa_attention.sdpa_attention_forward that:

  1. For pure causal bool masks, drops the mask and calls SDPA with is_causal=True
  2. For non pure causal bool masks (packed sequences, label masking like train_on_responses_only), converts the bool mask to a [B, H, S, S] float additive bias via torch.where

Both transformations are necessary at seq_len >= 2**16 to avoid the Cutlass SDPA int16 sequence index overflow (pytorch/pytorch#162588, still open). At smaller seq_len they are not needed:

  • The bool mask path through SDPA is correct
  • Rewriting pure causal to attention_mask=None, is_causal=True can pick a different SDPA backend than the bool mask path and, on recent torch builds, actually increases reserved VRAM
  • The torch.where float conversion allocates an [B, H, S, S] tensor per attention layer per forward that autograd holds live through backward

Across a Gemma4-31B LoRA SFT run these effects combine to add roughly 2.5 GB of reserved VRAM.

Measurements

Hardware: 1x NVIDIA B200 (180 GB), torch 2.9.1+cu128, transformers 5.5.0, Gemma4-31B LoRA SFT, FineTome-100k 3000 rows, per_device_train_batch_size=1, gradient_accumulation_steps=4, max_seq_length=8192, max_steps=60, seed=3407, adamw_8bit, train_on_responses_only.

Phase 8 (trainer.train 60 steps):

Configpeak_alloc GBpeak_reserved GBtotal wall s
unsloth 2026.4.4 + zoo 2026.4.6 (prev pypi)19.5325.01533.6
unsloth 2026.4.5 + zoo 2026.4.7 (current pypi)19.8327.56566.8
unsloth 2026.4.5 + zoo 2026.4.7 + this PR19.5325.01527.5

Training trajectory (this PR):

  • Losses first 5: [2.128, 0.626, 0.914, 1.588, 1.240]
  • Losses last 5: [0.925, 0.448, 0.759, 0.852, 0.749]
  • final train_loss = 0.8154 (prev pypi: 0.8255; current pypi: 0.8205)
  • Grad norms first 5: [0.872, 0.399, 0.625, 1.176, 1.109]
  • Grad norms last 5: [0.420, 0.555, 0.417, 0.310, 0.506]
  • LoRA adapter_model.safetensors: 233.63 MB (identical across all three runs)

Test plan

  • Bisected the regression to unsloth_zoo pypi 2026.4.6 -> 2026.4.7 (unsloth 2026.4.4 vs 2026.4.5 with the same zoo is a no op, zoo alone changes Phase 8 reserved from 25.01 GB to 27.56 GB)
  • Confirmed the source is patch_sdpa_bool_causal_mask via an env var gated early return: disabling the patch entirely recovered 25.01 GB exactly
  • Confirmed Gemma4-31B LoRA SFT 60 steps with this fix matches prev pypi peak / reserved / loss / grad norms
  • Qwen3.5-4B / 9B at seq_len = 69632 regression check (still expected to apply the fallback because query seq_len >= 65536 bypasses the early exit)
  • Sliding window model regression check (Gemma2 / Mistral / Qwen2, 3)

Upstream

The underlying pytorch bug that this patch works around is still open: pytorch/pytorch#162588. Related: pytorch/pytorch#142228, pytorch/pytorch#180445. Until pytorch fixes the kernel, the wrapper is load bearing for long context Qwen3.5 training, but should not fire for everyone else.

Changed files

  • unsloth_zoo/temporary_patches/misc.py (modified, +18/-4)

PR #180617: Make strides consistent for _scaled_dot_product_efficient_attention_backward

Description (problem / solution / changelog)

Stack from ghstack (oldest at bottom):

  • -> #180617

Fixes #180445

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

Changed files

  • aten/src/ATen/native/transformers/cuda/attention_backward.cu (modified, +10/-12)
  • test/inductor/test_cuda_repro.py (modified, +51/-0)

Code Example

import torch

attn = torch.nn.MultiheadAttention(embed_dim=512, num_heads=1, batch_first=True, device="cuda")
compiled = torch.compile(attn)

q = torch.rand(65536, 1, 512, device="cuda")
kv = torch.rand(65536, 10, 512, device="cuda")
mask = torch.randint(0, 2, (65536, 10), dtype=torch.bool, device="cuda")

out = compiled(query=q, key=kv, value=kv, key_padding_mask=mask, attn_mask=None, need_weights=False)[0]
out.sum().backward()
# AssertionError: expected size 65536==65536, stride 512==5120 at dim=0;
#   expected size 10==10, stride 33554432==512 at dim=2
# Error in op: torch.ops.aten._scaled_dot_product_efficient_attention_backward.default
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

Summary

torch.compile crashes on the backward pass of nn.MultiheadAttention when batch >= 65536.

The CUDA kernel has two code paths (aten/src/ATen/native/transformers/cuda/attention_backward.cu:1047):

  • batch <= 65535: calls the backward kernel directly, which allocates its own output
  • batch >= 65536: chunks the batch, pre-allocates output via at::empty_strided(..., input.strides()). This clones the input's strides.

The meta kernel (torch/_meta_registrations.py:6057) always predicts strides via torch.empty_permuted((B,H,S,D), (0,2,1,3)), which is matching only the first path. When inductor passes non-contiguous inputs, the strides diverge and assert_size_stride fails.

Reproducer

import torch

attn = torch.nn.MultiheadAttention(embed_dim=512, num_heads=1, batch_first=True, device="cuda")
compiled = torch.compile(attn)

q = torch.rand(65536, 1, 512, device="cuda")
kv = torch.rand(65536, 10, 512, device="cuda")
mask = torch.randint(0, 2, (65536, 10), dtype=torch.bool, device="cuda")

out = compiled(query=q, key=kv, value=kv, key_padding_mask=mask, attn_mask=None, need_weights=False)[0]
out.sum().backward()
# AssertionError: expected size 65536==65536, stride 512==5120 at dim=0;
#   expected size 10==10, stride 33554432==512 at dim=2
# Error in op: torch.ops.aten._scaled_dot_product_efficient_attention_backward.default

Error logs

No response

Versions

PyTorch version: 2.12.0.dev20260408+cu128 Is debug build: False CUDA used to build PyTorch: 12.8 ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.4 LTS (x86_64) GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0 Clang version: Could not collect CMake version: version 3.28.3 Libc version: glibc-2.39

Python version: 3.11.14 (main, Feb 3 2026, 22:51:56) [Clang 21.1.4 ] (64-bit runtime) Python platform: Linux-6.17.0-1007-aws-x86_64-with-glibc2.39 Is CUDA available: True CUDA runtime version: Could not collect CUDA_MODULE_LOADING set to: GPU models and configuration: GPU 0: NVIDIA L40S Nvidia driver version: 580.126.20 cuDNN version: Could not collect Is XPU available: False HIP runtime version: N/A MIOpen runtime version: N/A Is XNNPACK available: True Caching allocator config: N/A

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 48 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 8 On-line CPU(s) list: 0-7 Vendor ID: AuthenticAMD Model name: AMD EPYC 7R13 Processor CPU family: 25 Model: 1 Thread(s) per core: 2 Core(s) per socket: 4 Socket(s): 1 Stepping: 1 BogoMIPS: 5300.00 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid extd_apicid aperfmperf tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm cmp_legacy cr8_legacy abm sse4a misalignsse 3dnowprefetch topoext ssbd ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 invpcid rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 clzero xsaveerptr rdpru wbnoinvd arat npt nrip_save vaes vpclmulqdq rdpid Hypervisor vendor: KVM Virtualization type: full L1d cache: 128 KiB (4 instances) L1i cache: 128 KiB (4 instances) L2 cache: 2 MiB (4 instances) L3 cache: 16 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-7 Vulnerability Gather data sampling: Not affected Vulnerability Ghostwrite: Not affected Vulnerability Indirect target selection: Not affected Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Old microcode: Not affected Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Mitigation; Safe RET Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Retpolines; IBPB conditional; IBRS_FW; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected Vulnerability Srbds: Not affected Vulnerability Tsa: Mitigation; Clear CPU buffers Vulnerability Tsx async abort: Not affected Vulnerability Vmscape: Not affected

Versions of relevant libraries: [pip3] nvidia-cublas-cu12==12.8.4.1 [pip3] nvidia-cuda-cupti-cu12==12.8.90 [pip3] nvidia-cuda-nvrtc-cu12==12.8.93 [pip3] nvidia-cuda-runtime-cu12==12.8.90 [pip3] nvidia-cudnn-cu12==9.20.0.48 [pip3] nvidia-cufft-cu12==11.3.3.83 [pip3] nvidia-curand-cu12==10.3.9.90 [pip3] nvidia-cusolver-cu12==11.7.3.90 [pip3] nvidia-cusparse-cu12==12.5.8.93 [pip3] nvidia-cusparselt-cu12==0.7.1 [pip3] nvidia-nccl-cu12==2.29.7 [pip3] nvidia-nvjitlink-cu12==12.8.93 [pip3] nvidia-nvtx-cu12==12.8.90 [pip3] torch==2.12.0.dev20260408+cu128 [pip3] triton==3.7.0+git282c8251 [conda] Could not collect

cc @ezyang @eellison @bdhirsh @bobrenjc93 @aorenste @chauhang @penguinwu @drisspg @liangel-02 @howardzhang-cv

extent analysis

TL;DR

The issue can be worked around by ensuring that the input tensors to torch.nn.MultiheadAttention are contiguous in memory when the batch size is greater than or equal to 65536.

Guidance

  • Verify that the input tensors q, kv, and mask are contiguous in memory using the is_contiguous() method.
  • If the tensors are not contiguous, consider using the contiguous() method to make them contiguous before passing them to torch.nn.MultiheadAttention.
  • Alternatively, try to avoid using batch sizes greater than or equal to 65536, as this seems to trigger the problematic code path in the CUDA kernel.
  • Investigate whether updating to a newer version of PyTorch or CUDA might resolve the issue, as the problem may have been fixed in a later version.

Example

q = torch.rand(65536, 1, 512, device="cuda").contiguous()
kv = torch.rand(65536, 10, 512, device="cuda").contiguous()
mask = torch.randint(0, 2, (65536, 10), dtype=torch.bool, device="cuda").contiguous()

Notes

The issue seems to be related to the way PyTorch handles non-contiguous inputs to torch.nn.MultiheadAttention when the batch size is large. The contiguous() method can be used to ensure that the input tensors are contiguous in memory, which may help to avoid the issue.

Recommendation

Apply the workaround of making the input tensors contiguous in memory using the contiguous() method, as this is a relatively simple and safe change that can help to avoid the issue.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING