Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

cuDNN SDPA backward: give grad_output the output's layout on torch 2.6 - 2.13 (#15445)

Daniel Han2df2860783ec
diff --git a/tests/test_cudnn_sdpa_backward_grad_layout.py b/tests/test_cudnn_sdpa_backward_grad_layout.py
new file mode 100644
index 00000000000..bb5c2412b9c
--- /dev/null
+++ b/tests/test_cudnn_sdpa_backward_grad_layout.py
@@ -0,0 +1,334 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""torch 2.6 - 2.13 cuDNN SDPA backward plans ignore grad_output strides, so same-shape backwards
+with different grad layouts give wrong grads. The GPU test's opt-out arm proves the bug exists."""
+
+import importlib
+import json
+import os
+import subprocess
+import sys
+import textwrap
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+
+def _affected(*args):
+ # Per test, so the GPU test still runs (and fails) on a tree without the fix.
+ from unsloth.import_fixes import _cudnn_sdpa_backward_cache_ignores_grad_layout
+ return _cudnn_sdpa_backward_cache_ignores_grad_layout(*args)
+
+
+class TestAffectedRange:
+ @pytest.mark.parametrize(
+ "torch_version, cudnn_version",
+ [
+ ("2.13.0+cu130", 92000),
+ ("2.13.0+cu129", 92400),
+ ("2.10.0+cu128", 91002),
+ ("2.6.0+cu126", 90501),
+ ("2.12.1", 91900),
+ ],
+ )
+ def test_affected(self, torch_version, cudnn_version):
+ assert _affected(torch_version, cudnn_version)
+
+ @pytest.mark.parametrize(
+ "torch_version, cudnn_version",
+ [
+ ("2.14.0+cu130", 92400), # pytorch/pytorch#191576 keys the plan on grad_output strides
+ ("2.14.1+cu130", 92400),
+ ("2.15.0", 92500),
+ ("2.5.1+cu124", 90501), # always copied grad_output into the output layout
+ ("2.6.0+cu124", 90100), # cuDNN < 9.5.1
+ ("2.13.0+cpu", None),
+ ("not a version", 92000),
+ ],
+ )
+ def test_not_affected(self, torch_version, cudnn_version):
+ assert not _affected(torch_version, cudnn_version)
+
+
+class TestGradInOutputLayout:
+ def _fn(self):
+ from unsloth.import_fixes import _sdpa_grad_layout_function
+ return _sdpa_grad_layout_function()
+
+ def test_gradient_takes_the_output_layout(self):
+ # Output laid out (B, T, H, D) seen as (B, H, T, D), the layout SDPA gives a HF-style query.
+ x = torch.randn(2, 5, 3, 4).transpose(1, 2).requires_grad_()
+ y = self._fn().apply(x)
+ grad = torch.randn(2, 3, 5, 4) # contiguous (B, H, T, D): a different layout
+ (got,) = torch.autograd.grad(y, x, grad)
+ assert got.stride() == x.stride()
+ assert torch.equal(got, grad)
+
+ def test_matching_gradient_is_not_copied(self):
+ x = torch.randn(2, 3, 5, 4, requires_grad = True)
+ y = self._fn().apply(x)
+ grad = torch.randn(2, 3, 5, 4)
+ captured = []
+ x.register_hook(lambda g: captured.append(g.data_ptr()))
+ y.backward(grad)
+ assert captured == [grad.data_ptr()]
+
+ def test_forward_is_identity(self):
+ x = torch.randn(2, 3, 5, 4, requires_grad = True)
+ y = self._fn().apply(x)
+ assert torch.equal(y, x) and y.stride() == x.stride() and y.data_ptr() == x.data_ptr()
+
+
+def _install_wrapper(monkeypatch):
+ """Installs the real wrapper on a CPU box made to look like CUDA torch 2.13 / cuDNN 9.20."""
+ import torch.nn.functional as F
+
+ import_fixes = importlib.import_module("unsloth.import_fixes")
+
+ monkeypatch.delenv("UNSLOTH_SKIP_CUDNN_SDPA_GRAD_LAYOUT_FIX", raising = False)
+ monkeypatch.setattr(
+ F, "scaled_dot_product_attention", torch._C._nn.scaled_dot_product_attention
+ )
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.version, "hip", None, raising = False)
+ monkeypatch.setattr(torch, "__version__", "2.13.0+cu130")
+ monkeypatch.setattr(torch.backends.cudnn, "version", lambda: 92000)
+ import_fixes.fix_cudnn_sdpa_backward_grad_layout()
+ sdpa = F.scaled_dot_product_attention
+ assert getattr(sdpa, import_fixes._SDPA_GRAD_LAYOUT_FLAG, False)
+ # CPU outputs stand in for CUDA ones from here on.
+ monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))
+ return sdpa
+
+
+def _math():
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+ return sdpa_kernel([SDPBackend.MATH])
+
+
+def _hf_query():
+ # (B, T, H, D) seen as (B, H, T, D); math returns a contiguous output, so a gradient read back
+ # through transpose(1, 2) arrives in a different layout.
+ g = torch.Generator().manual_seed(0)
+ return torch.randn(1, 6, 2, 8, dtype = torch.float64, generator = g).transpose(1, 2)
+
+
+def _loss(
+ sdpa,
+ x,
+ inplace = False,
+):
+ out = sdpa(x, x, x)
+ if inplace:
+ out.mul_(2.0)
+ return (out.transpose(1, 2).contiguous() * 3.0).sum()
+
+
+class TestNonCudnnBackendsKeepNativeBehaviour:
+ def test_func_grad_through_the_wrapper(self, monkeypatch):
+ sdpa = _install_wrapper(monkeypatch)
+ x = _hf_query()
+ with _math():
+ got = torch.func.grad(lambda t: _loss(sdpa, t))(x)
+ ref = torch.func.grad(lambda t: _loss(torch._C._nn.scaled_dot_product_attention, t))(x)
+ assert torch.equal(got, ref)
+
+ def test_inplace_on_the_output_then_backward(self, monkeypatch):
+ sdpa = _install_wrapper(monkeypatch)
+ grads = []
+ for fn in (sdpa, torch._C._nn.scaled_dot_product_attention):
+ x = _hf_query().requires_grad_()
+ with _math():
+ _loss(fn, x, inplace = True).backward()
+ grads.append(x.grad)
+ assert torch.equal(*grads)
+
+ def test_math_output_is_returned_untouched(self, monkeypatch):
+ sdpa = _install_wrapper(monkeypatch)
+ x = _hf_query().requires_grad_()
+ with _math():
+ out = sdpa(x, x, x)
+ assert not out._is_view() and not out._backward_hooks
+ assert type(out.grad_fn).__name__ == "UnsafeViewBackward0"
+
+
+class TestCudnnHookPath:
+ """The eager path a cuDNN output takes, driven on CPU by treating the math node as cuDNN's."""
+
+ @pytest.fixture
+ def sdpa(self, monkeypatch):
+ import_fixes = importlib.import_module("unsloth.import_fixes")
+
+ sdpa = _install_wrapper(monkeypatch)
+ monkeypatch.setattr(
+ import_fixes,
+ "_SDPA_GRAD_LAYOUT_NODES",
+ frozenset(("UnsafeViewBackward0",)),
+ raising = False,
+ )
+ return sdpa
+
+ def _grad_at_sdpa_node(self, sdpa, inplace):
+ x = _hf_query().requires_grad_()
+ seen = []
+ with _math():
+ out = sdpa(x, x, x)
+ assert not out._is_view() and out._backward_hooks # the hook engaged
+ out.grad_fn.register_prehook(lambda grads: seen.append(grads[0].stride()))
+ stride = out.stride()
+ if inplace:
+ out.mul_(2.0)
+ (out.transpose(1, 2).contiguous() * 3.0).sum().backward()
+ return seen, stride, x.grad
+
+ @pytest.mark.parametrize("inplace", [False, True])
+ def test_grad_reaches_backward_in_the_output_layout(self, sdpa, inplace):
+ seen, stride, grad = self._grad_at_sdpa_node(sdpa, inplace)
+ assert seen == [stride]
+ x = _hf_query().requires_grad_()
+ with _math():
+ _loss(torch._C._nn.scaled_dot_product_attention, x, inplace).backward()
+ assert torch.equal(grad, x.grad)
+
+ def test_func_grad(self, sdpa):
+ x = _hf_query()
+ with _math():
+ got = torch.func.grad(lambda t: _loss(sdpa, t))(x)
+ ref = torch.func.grad(lambda t: _loss(torch._C._nn.scaled_dot_product_attention, t))(x)
+ assert torch.equal(got, ref)
+
+
+class TestCompiledPathFunction:
+ """torch.compile takes the autograd.Function (a hook on an intermediate graph-breaks)."""
+
+ def _fn(self):
+ from unsloth.import_fixes import _sdpa_grad_layout_function
+ return _sdpa_grad_layout_function()
+
+ def _f(self, wrap):
+ def f(x):
+ return (
+ wrap(torch._C._nn.scaled_dot_product_attention(x, x, x)).transpose(1, 2) * 3.0
+ ).sum()
+
+ return f
+
+ @pytest.mark.parametrize("transform", ["grad", "vmap_grad", "jacrev"])
+ def test_func_transforms(self, transform):
+ fn = self._fn()
+ x = _hf_query()
+
+ def run(wrap):
+ f = self._f(wrap)
+ if transform == "grad":
+ return torch.func.grad(f)(x)
+ if transform == "vmap_grad":
+ return torch.func.vmap(torch.func.grad(f))(x[None].expand(3, *x.shape))
+ return torch.func.jacrev(
+ lambda t: wrap(torch._C._nn.scaled_dot_product_attention(t, t, t))
+ )(x)
+
+ with _math():
+ assert torch.equal(run(fn.apply), run(lambda o: o))
+
+ def test_fullgraph_compile_has_no_graph_break(self):
+ from torch._dynamo.utils import counters
+
+ fn = self._fn()
+ torch._dynamo.reset()
+ counters.clear()
+ compiled = torch.compile(self._f(fn.apply), fullgraph = True, backend = "aot_eager")
+ x = _hf_query().requires_grad_()
+ ref_x = x.detach().clone().requires_grad_()
+ with _math():
+ compiled(x).backward()
+ self._f(lambda o: o)(ref_x).backward()
+ assert not counters["graph_break"]
+ assert torch.equal(x.grad, ref_x.grad)
+ torch._dynamo.reset()
+
+
+def _stack_is_affected():
+ """Checked without unsloth, so a tree without the fix still runs the GPU test."""
+ if not torch.cuda.is_available() or getattr(torch.version, "hip", None):
+ return False
+ from packaging.version import Version
+
+ v = Version(Version(torch.__version__).base_version)
+ cudnn = torch.backends.cudnn.version()
+ if not (Version("2.6") <= v < Version("2.14")) or cudnn is None or cudnn < 90501:
+ return False
+ return torch.cuda.get_device_capability()[0] >= 8
+
+
+_PROBE = textwrap.dedent(
+ """
+ import json
+ import unsloth # noqa: F401 (applies the import-time fixes)
+ import torch
+ import torch.nn.functional as F
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+
+ B, H, T, D = 1, 8, 374, 64
+ out = {}
+
+ def loss(q, k, v, w, kw, backend):
+ with sdpa_kernel([backend]):
+ o = F.scaled_dot_product_attention(q, k, v, scale = 0.11, **kw)
+ # "hf": output read through transpose(1, 2) like HF modeling code, grad laid out (B, T, H, D);
+ # "plain": output read directly, contiguous (B, H, T, D) grad.
+ return ((o.transpose(1, 2) if w.shape[1] == T else o) * w).sum()
+
+ def hf_like(q, k, v, w, kw):
+ return loss(q, k, v, w, kw, SDPBackend.CUDNN_ATTENTION)
+
+ def err(fn, seed, kw, layout):
+ g = torch.Generator(device = "cuda").manual_seed(seed)
+ q, k, v = (torch.randn(B, H, T, D, device = "cuda", dtype = torch.bfloat16, generator = g).requires_grad_() for _ in range(3))
+ shape = (B, T, H, D) if layout == "hf" else (B, H, T, D)
+ w = torch.randn(*shape, device = "cuda", dtype = torch.bfloat16, generator = g)
+ got = torch.autograd.grad(fn(q, k, v, w, kw), (q, k, v))
+ qf, kf, vf = (t.detach().float().requires_grad_() for t in (q, k, v))
+ ref = torch.autograd.grad(loss(qf, kf, vf, w.float(), kw, SDPBackend.MATH), (qf, kf, vf))
+ return max(float((a.float() - r).abs().max()) for a, r in zip(got, ref))
+
+ mask = torch.ones(T, T, dtype = torch.bool, device = "cuda").tril()[None, None]
+ # Every case: a backward with one grad layout, then a same-shape one with the other layout.
+ for name, kw in (("mask", {"attn_mask": mask}), ("causal", {"is_causal": True}), ("nomask", {})):
+ out[f"eager-{name}"] = [err(hf_like, 1, kw, "hf"), err(hf_like, 0, kw, "plain")]
+ out[f"eager-{name}-reverse"] = [err(hf_like, 3, kw, "plain"), err(hf_like, 2, kw, "hf")]
+ torch._dynamo.reset()
+ compiled = torch.compile(hf_like, fullgraph = True)
+ kw = {"attn_mask": mask}
+ out["compiled-mask"] = [err(compiled, 5, kw, "hf"), err(compiled, 4, kw, "plain")]
+ print("PROBE_RESULT " + json.dumps(out))
+ """
+)
+
+
+def _run_probe(extra_env = None):
+ env = dict(os.environ)
+ env.pop("UNSLOTH_SKIP_CUDNN_SDPA_GRAD_LAYOUT_FIX", None)
+ env.update(extra_env or {})
+ r = subprocess.run(
+ [sys.executable, "-c", _PROBE], capture_output = True, text = True, env = env, timeout = 900
+ )
+ line = [x for x in r.stdout.splitlines() if x.startswith("PROBE_RESULT ")]
+ assert line, f"probe crashed (rc {r.returncode}):\n{r.stdout[-3000:]}\n{r.stderr[-3000:]}"
+ return json.loads(line[-1][len("PROBE_RESULT ") :])
+
+
+ not _stack_is_affected(), reason = "needs CUDA torch 2.6 - 2.13 with cuDNN >= 9.5.1"
+)
+def test_cudnn_sdpa_backward_is_right_across_grad_layouts_after_import():
+ # bf16 vs fp32 math max abs error is ~0.03 here; the stale plan gives 0.7 - 7.
+ res = _run_probe()
+ bad = {k: v for k, v in res.items() if max(v) > 0.1}
+ assert not bad, f"wrong cuDNN SDPA gradients (max abs err vs fp32 math, first, second): {bad}"
+ # Kill switch: without the fix the second backward of a pair is wrong, so the probe can fail.
+ off = _run_probe({"UNSLOTH_SKIP_CUDNN_SDPA_GRAD_LAYOUT_FIX": "1"})
+ assert max(off["eager-mask"][1], off["eager-causal"][1]) > 0.5, off
diff --git a/tests/test_cudnn_sdpa_grad_layout_dtensor.py b/tests/test_cudnn_sdpa_grad_layout_dtensor.py
new file mode 100644
index 00000000000..b02705a9ff6
--- /dev/null
+++ b/tests/test_cudnn_sdpa_grad_layout_dtensor.py
@@ -0,0 +1,96 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""The grad-layout wrapper must skip DTensor outputs (context_parallel), else the backward copy
+raises "aten.copy_.default got mixed torch.Tensor and DTensor"."""
+
+import json
+import os
+import socket
+import subprocess
+import sys
+import textwrap
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+_PROBE = textwrap.dedent(
+ """
+ import json, os
+ import unsloth # noqa: F401 (installs the import-time SDPA wrappers)
+ import torch, torch.distributed as dist, torch.nn.functional as F
+ from torch.distributed.device_mesh import init_device_mesh
+ from torch.distributed.tensor.experimental import context_parallel
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+
+ dist.init_process_group("nccl", rank = 0, world_size = 1)
+ mesh = init_device_mesh("cuda", (1,))
+ B, H, T, D = 1, 4, 256, 64
+ out = {}
+ # Contiguous (B, H, T, D) query, output read through transpose(1, 2): the gradient's layout
+ # differs from the output's, so the wrapper's backward re-lays it out.
+ for name, backend in (("flash", SDPBackend.FLASH_ATTENTION), ("efficient", SDPBackend.EFFICIENT_ATTENTION)):
+ g = torch.Generator(device = "cuda").manual_seed(0)
+ q, k, v = (torch.randn(B, H, T, D, device = "cuda", dtype = torch.bfloat16, generator = g) for _ in range(3))
+ w = torch.randn(B, T, H, D, device = "cuda", dtype = torch.bfloat16, generator = g)
+ ref_in = [t.clone().requires_grad_() for t in (q, k, v)]
+ with sdpa_kernel([backend]):
+ o = F.scaled_dot_product_attention(*ref_in, is_causal = True)
+ ref = torch.autograd.grad((o.transpose(1, 2) * w).sum(), ref_in)
+ bufs = [t.clone() for t in (q, k, v)]
+ try:
+ with sdpa_kernel([backend]), context_parallel(
+ mesh, buffers = bufs, buffer_seq_dims = [2, 2, 2], no_restore_buffers = set(bufs)
+ ):
+ cp_in = [t.requires_grad_() for t in bufs]
+ o = F.scaled_dot_product_attention(*cp_in, is_causal = True)
+ got = torch.autograd.grad((o.transpose(1, 2) * w).sum(), cp_in)
+ out[name] = max(float((a.float() - r.float()).abs().max()) for a, r in zip(got, ref))
+ except Exception as e:
+ out[name] = f"{type(e).__name__}: {str(e).splitlines()[0]}"
+ print("PROBE_RESULT " + json.dumps(out))
+ dist.destroy_process_group()
+ """
+)
+
+
+def _context_parallel_available():
+ try:
+ from torch.distributed.tensor.experimental import context_parallel # noqa: F401
+ except Exception:
+ return False
+ return True
+
+
+def _free_port():
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
[email protected](not torch.cuda.is_available(), reason = "needs CUDA")
+ not (torch.distributed.is_available() and torch.distributed.is_nccl_available()),
+ reason = "needs NCCL",
+)
[email protected](not _context_parallel_available(), reason = "torch without context_parallel")
+def test_context_parallel_sdpa_backward_with_the_grad_layout_wrapper():
+ env = dict(
+ os.environ,
+ MASTER_ADDR = "127.0.0.1",
+ MASTER_PORT = str(_free_port()),
+ RANK = "0",
+ WORLD_SIZE = "1",
+ LOCAL_RANK = "0",
+ )
+ env.pop("UNSLOTH_SKIP_CUDNN_SDPA_GRAD_LAYOUT_FIX", None)
+ r = subprocess.run(
+ [sys.executable, "-c", _PROBE], capture_output = True, text = True, env = env, timeout = 900
+ )
+ line = [x for x in r.stdout.splitlines() if x.startswith("PROBE_RESULT ")]
+ assert line, f"probe crashed (rc {r.returncode}):\n{r.stdout[-3000:]}\n{r.stderr[-3000:]}"
+ res = json.loads(line[-1][len("PROBE_RESULT ") :])
+ # One rank: context parallel attention is the plain attention, gradients equal.
+ assert all(isinstance(v, float) and v == 0.0 for v in res.values()), res
diff --git a/tests/test_flex_head_dim_version_gate.py b/tests/test_flex_head_dim_version_gate.py
index bcf0e5d010a..4d200ea51dc 100644
--- a/tests/test_flex_head_dim_version_gate.py
+++ b/tests/test_flex_head_dim_version_gate.py
@@ -2,6 +2,8 @@
"""head_dim 256 routes to flex only until SDPA reaches cuDNN with a mask (torch 2.14, sm100).
Above 256 no cuDNN build helps, so it routes on every version."""
+import inspect
+
import pytest
import unsloth # noqa: F401 (must precede transformers)
@@ -102,11 +104,10 @@ def test_gate_is_off_below_blackwell(monkeypatch):
def _plain_sdpa(monkeypatch):
- # The SM100 cuDNN head_dim 256 detour wraps SDPA at import on a B200; these test plain SDPA.
+ # Import-time wrappers (the SM100 cuDNN head_dim 256 detour, the torch 2.6 - 2.13 cuDNN grad
+ # layout fix on top of it) can stack on a B200; these test plain SDPA, so unwrap them all.
sdpa = u.torch.nn.functional.scaled_dot_product_attention
- monkeypatch.setattr(
- u.torch.nn.functional, "scaled_dot_product_attention", getattr(sdpa, "__wrapped__", sdpa)
- )
+ monkeypatch.setattr(u.torch.nn.functional, "scaled_dot_product_attention", inspect.unwrap(sdpa))
def _blackwell_torch_2_14(monkeypatch):
@@ -123,6 +124,29 @@ def test_gate_is_on_for_blackwell_on_torch_2_14(monkeypatch):
assert u._sdpa_reaches_cudnn_at_head_dim_256() is True
+def test_plain_sdpa_strips_both_stacked_sdpa_wrappers(monkeypatch):
+ # A B200 on torch 2.13 installs the d256 detour, then the grad-layout wrapper over it.
+ from unsloth import import_fixes
+
+ F = u.torch.nn.functional
+ monkeypatch.setattr(
+ F, "scaled_dot_product_attention", u.torch._C._nn.scaled_dot_product_attention
+ )
+ monkeypatch.delenv("UNSLOTH_ALLOW_CUDNN_SDPA_D256", raising = False)
+ monkeypatch.delenv("UNSLOTH_SKIP_CUDNN_SDPA_GRAD_LAYOUT_FIX", raising = False)
+ monkeypatch.setattr(import_fixes, "_sdpa_cudnn_d256_sm100_devices", lambda: {0})
+ monkeypatch.setattr(u.torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(u.torch.version, "hip", None, raising = False)
+ monkeypatch.setattr(u.torch, "__version__", "2.13.0+cu130")
+ monkeypatch.setattr(u.torch.backends.cudnn, "version", lambda: 92000)
+ import_fixes.fix_cudnn_sdpa_d256_masked_backward()
+ import_fixes.fix_cudnn_sdpa_backward_grad_layout()
+ sdpa = F.scaled_dot_product_attention
+ assert getattr(sdpa, import_fixes._SDPA_GRAD_LAYOUT_FLAG, False)
+ assert getattr(sdpa.__wrapped__, "_unsloth_avoids_cudnn_d256_masked_backward", False)
+ test_gate_is_on_for_blackwell_on_torch_2_14(monkeypatch)
+
+
def test_gate_is_off_while_the_cudnn_d256_detour_is_installed(monkeypatch):
# Masked head_dim 256 training then runs the efficient kernel, not cuDNN, so flex is faster.
_blackwell_torch_2_14(monkeypatch)
diff --git a/tests/test_hf_packed_attention.py b/tests/test_hf_packed_attention.py
index 5b67875decd..d0e1c1bd4a5 100644
--- a/tests/test_hf_packed_attention.py
+++ b/tests/test_hf_packed_attention.py
@@ -1541,7 +1541,9 @@ def test_block_varlen_runs_inside_the_graph_and_matches_dense_sdpa(monkeypatch,
out = fn(q, k, v, mask, torch.tensor(lengths, dtype = torch.int32), (cu, max(lengths)))
grad = torch.randn_like(out)
got = torch.autograd.grad(out, (q, k, v), grad)
- ref_out, _ = sdpa_attention_forward(module, q, k, v, mask, scaling = 0.11)
+ # Math reference: cuDNN on torch 2.6 - 2.13 can reuse a stale backward plan (wrong grads).
+ with torch.nn.attention.sdpa_kernel(torch.nn.attention.SDPBackend.MATH):
+ ref_out, _ = sdpa_attention_forward(module, q, k, v, mask, scaling = 0.11)
ref = torch.autograd.grad(ref_out, (q, k, v), grad)
torch.testing.assert_close(out.float(), ref_out.float(), atol = 2e-2, rtol = 2e-2)
for g, r in zip(got, ref):
diff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.py
index bb7c52afe15..845767ea4cc 100644
--- a/unsloth/_gpu_init.py
+++ b/unsloth/_gpu_init.py
@@ -361,6 +361,7 @@ from .import_fixes import (
fix_vllm_guided_decoding_params,
fix_vllm_pdl_blackwell,
fix_cudnn_sdpa_d256_masked_backward,
+ fix_cudnn_sdpa_backward_grad_layout,
fix_rocm_windows_fused_sdpa,
fix_triton_compiled_kernel_missing_attrs,
fix_dynamo_config_thread_visibility,
@@ -450,6 +451,7 @@ fix_vllm_guided_decoding_params()
fix_trl_vllm_ascend()
fix_vllm_pdl_blackwell()
fix_cudnn_sdpa_d256_masked_backward()
+fix_cudnn_sdpa_backward_grad_layout()
# Windows ROCm only, probe-gated: fused attention fails on every call there (gfx1151, torch 2.11).
fix_rocm_windows_fused_sdpa()
fix_triton_compiled_kernel_missing_attrs()
@@ -517,6 +519,7 @@ del fix_vllm_guided_decoding_params
del fix_trl_vllm_ascend
del fix_vllm_pdl_blackwell
del fix_cudnn_sdpa_d256_masked_backward
+del fix_cudnn_sdpa_backward_grad_layout
del fix_rocm_windows_fused_sdpa
del fix_triton_compiled_kernel_missing_attrs
del fix_dynamo_config_thread_visibility
diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.py
index a688a9373b0..f4e8fab5df0 100644
--- a/unsloth/import_fixes.py
+++ b/unsloth/import_fixes.py
@@ -7657,6 +7657,112 @@ def fix_cudnn_sdpa_d256_masked_backward():
)
+_SDPA_GRAD_LAYOUT_FLAG = "_unsloth_gives_sdpa_backward_the_output_layout"
+_SDPA_GRAD_LAYOUT_FUNCTION = []
+# Eager outputs whose backward is cuDNN's; flash / efficient / math outputs stay untouched.
+_SDPA_GRAD_LAYOUT_NODES = frozenset(("ScaledDotProductCudnnAttentionBackward0",))
+
+
+def _cudnn_sdpa_backward_cache_ignores_grad_layout(torch_version, cudnn_version):
+ """torch 2.6 - 2.13 key the cuDNN backward plan without grad_output strides (fixed in
+ pytorch/pytorch#191576); cuDNN < 9.5.1 always copies grad_output to the output layout."""
+ try:
+ torch_version = TrueVersion(TrueVersion(str(torch_version)).base_version)
+ except Exception:
+ return False
+ if not (TrueVersion("2.6") <= torch_version < TrueVersion("2.14")):
+ return False
+ return cudnn_version is not None and int(cudnn_version) >= 90501
+
+
+def _sdpa_grad_to_layout(stride, grad):
+ if grad.stride() == stride:
+ return grad
+ return grad.new_empty_strided(grad.size(), stride).copy_(grad)
+
+
+def _sdpa_grad_layout_function():
+ if _SDPA_GRAD_LAYOUT_FUNCTION:
+ return _SDPA_GRAD_LAYOUT_FUNCTION[0]
+ import torch
+
+ try:
+ import torch._dynamo.config as dynamo_config
+
+ # torch 2.6 Dynamo bans grad.stride() in a traced backward: a graph break per SDPA call.
+ stride_banned = "stride" in dynamo_config._autograd_backward_strict_mode_banned_ops
+ except Exception:
+ stride_banned = False
+
+ class _GradInOutputLayout(torch.autograd.Function):
+ # setup_context + generate_vmap_rule: torch.func.grad / vmap / jacrev keep working.
+ generate_vmap_rule = True
+
+ @staticmethod
+ def forward(out):
+ return out.view_as(out)
+
+ @staticmethod
+ def setup_context(ctx, inputs, output):
+ ctx.out_stride = inputs[0].stride()
+
+ @staticmethod
+ def backward(ctx, grad):
+ if stride_banned and torch.compiler.is_compiling():
+ return grad.new_empty_strided(grad.size(), ctx.out_stride).copy_(grad)
+ return _sdpa_grad_to_layout(ctx.out_stride, grad)
+
+ _SDPA_GRAD_LAYOUT_FUNCTION.append(_GradInOutputLayout)
+ return _GradInOutputLayout
+
+
+def fix_cudnn_sdpa_backward_grad_layout():
+ """Force SDPA grad_output into the output's layout, which the plan key does cover, so two
+ same-shape backwards with different grad layouts cannot share a stale plan (wrong grads)."""
+ if os.environ.get("UNSLOTH_SKIP_CUDNN_SDPA_GRAD_LAYOUT_FIX", "0") == "1":
+ return
+ try:
+ import torch
+ import torch.nn.functional as F
+
+ if not torch.cuda.is_available() or getattr(torch.version, "hip", None):
+ return
+ if not _cudnn_sdpa_backward_cache_ignores_grad_layout(
+ torch.__version__, torch.backends.cudnn.version()
+ ):
+ return
+ grad_in_output_layout = _sdpa_grad_layout_function()
+ except Exception as e:
+ logger.info(f"Unsloth: Skipping the cuDNN SDPA backward layout fix ({e})")
+ return
+ if getattr(F.scaled_dot_product_attention, _SDPA_GRAD_LAYOUT_FLAG, False):
+ return
+
+ original = F.scaled_dot_product_attention
+
+ @functools.wraps(original)
+ def scaled_dot_product_attention(*args, **kwargs):
+ out = original(*args, **kwargs)
+ # Plain tensors only: a DTensor gradient cannot be copied into a plain empty_strided buffer.
+ if type(out) is torch.Tensor and out.requires_grad and out.is_cuda and not out.is_nested:
+ if torch.compiler.is_compiling():
+ # Dynamo graph-breaks on a hook on an intermediate; the Function traces inline.
+ return grad_in_output_layout.apply(out)
+ if type(out.grad_fn).__name__ in _SDPA_GRAD_LAYOUT_NODES:
+ # A hook keeps out a plain tensor: a Function output is a view, so in-place
+ # ops on it would raise.
+ out.register_hook(functools.partial(_sdpa_grad_to_layout, out.stride()))
+ return out
+
+ scaled_dot_product_attention.__wrapped__ = original
+ setattr(scaled_dot_product_attention, _SDPA_GRAD_LAYOUT_FLAG, True)
+ F.scaled_dot_product_attention = scaled_dot_product_attention
+ logger.info(
+ f"Unsloth: torch {torch.__version__} reuses cuDNN SDPA backward plans across gradient "
+ "layouts; SDPA gradients are given the output's layout"
+ )
+
+
def _rocm_windows_broken_sdpa_backends():
"""Fused SDPA backends ("flash", "mem_efficient") failing on this process's Windows ROCm GPU.