Skip to content

cuDNN SDPA: keep known-bad decode and NaN-dQ shapes off cuDNN before torch 2.14 / 2.15 - #15934

Merged
danielhanchen merged 10 commits into
mainfrom
torch-backport-cudnn-sdpa
Nov 4, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
torch-backport-cudnn-sdpa

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

Keeps SDPA off cuDNN attention for the two call shapes that later torch releases refuse, on torch versions that still route them to cuDNN.

The two bugs

pytorch/pytorch#193893 pytorch/pytorch#196678
Symptom wrong attention output (silent) NaN query gradients
Devices SM 10.x / 11.x (B200, B300, Thor) SM 9.0 (H100 / H200)
cuDNN 9.19 - 9.25.0, except 9.24.1 < 9.26
Call one query row (decode) not causal, query requires grad, key length % 128 == 64 (no mask needed)
torch guard pytorch#194963, in 2.14.0 / 2.14.1 pytorch#196861, in 2.15.0 only
Affected here torch 2.11 - 2.13 (wheels ship cuDNN 9.19 / 9.20) torch 2.11 - 2.14, including the 2.14 pip install unsloth gets

Unsloth's own paths avoid most of these:

  • the llama decode path keeps cuDNN off on SM 9.x / 10.x;
  • the bucketed masked SDPA pads key lengths to a multiple of 128.

Still exposed:

  • SM 11.x decode;
  • UNSLOTH_SDPA_DECODE_CUDNN=1;
  • decode through transformers' SDPA (FastModel, vision models);
  • left-padded training through transformers' SDPA (DPO / KTO) with key length % 128 == 64.

Change

fix_cudnn_sdpa_known_bad_shapes in import_fixes.py, run from GPU init:

  • It installs only when a visible device matches one of the rules above, so other GPUs and torch versions keep SDPA untouched.
  • The wrapper checks the call against the same conditions as torch's later guards. On a match it turns off only the cuDNN backend flag around the call, when the caller also has flash / efficient / math enabled, and turns it back on afterwards only if it turned it off. A cuDNN-only policy is left alone.
  • Under torch.compile the decision is read through a module property that Dynamo guards on, so a compiled call recompiles when the caller's backend policy flips that decision (AOTAutograd and Inductor fix the SDPA kernel at trace time, so a runtime flag flip alone cannot change it). The caller's flags are restored exactly in eager and compiled calls.
  • Under compile the key-length rule is tested on the runtime value, so a dynamic sequence length adds no guard or recompile. While tracing a symbolic length the call is treated as matching, so on an affected stack (torch < 2.15 with cuDNN < 9.26) dynamic-shape compiled training keeps those calls off cuDNN.
  • It warns once per bug. UNSLOTH_ALLOW_BUGGY_CUDNN_SDPA=1 opts out.

Tests (CPU)

67 new tests, all passing:

  • version and capability gates, including 9.24.1 and the 2.14 / 2.15 cut-offs;
  • per-call matching;
  • compiled calls: one graph for a mark_dynamic key length (strict and default); under aot_eager and inductor a call compiled under one policy follows a later policy (both orders), and the flags are restored;
  • backend selection under different caller policies;
  • install only on affected devices;
  • the opt-out.

H100 results (Colab H100 80GB, sm90, torch 2.14.1+cu130, cuDNN 9.24.0)

base = the merge base, head = this branch. Each arm asserts it imported its own tree.

The SM90 dQ bug reproduces on base and is gone on head. The trigger is a non-causal masked call, bf16, B 2, H 8, D 64, key length 192 (192 % 128 == 64), q.requires_grad, with low-logsumexp rows. Results are the same for a bool and an additive mask, eager and torch.compile:

base head
dQ non-finite 196608 of 196608 (all) 0
out / dK / dV non-finite 0 0
out / dK / dV max error vs fp64 (relative to max) 0.0031 - 0.0034 0.0031 - 0.0039

On head, dQ's max error relative to its own max is 38 on this adversarial input. Every key there carries a -960 component, so dQ's first channel is a large cancellation. A fused bf16 kernel shows the same thing on CPU (flash backend: 24 on an input built the same way); the fp64-accumulating math backend does not. dQ for the regular rows (below) matches base.

Regular masked training calls, key length 192 / 256 / 320 (bool and additive, default and fullgraph=True):

  • out / dQ / dK / dV max error vs fp64 is 0.0034 - 0.0039 on both arms, with no non-finite values;
  • no graph breaks on either arm, and fullgraph=True compiles on both;
  • head compiles 3 graphs for the three lengths where base compiles 2. That is the key-length guard: 192 hits the gate and 256 / 320 do not, so one extra specialization. No recompiles beyond that.

Tests on the H100: tests/test_cudnn_sdpa_known_bad_shapes.py 59 passed on head. On base the file fails because the code it tests is absent.

Not proven yet

  • The SM 10.x / 11.x (B200 / B300 / Thor) decode bug (#193893): no Blackwell GPU on Colab.
  • Training step time on H100 with the detour (only correctness and compile counters were measured).
  • The H100 results above predate the call-time policy change; it was checked on CPU only (torch 2.6, 2.13, 2.15 for the compile mechanics, with a stand-in op for the kernel choice).

…h < 2.14 / 2.15

Two cuDNN SDPA bugs that later torch releases refuse at backend selection are still
reachable on the torch our users run:

- pytorch#193893: one-query-row decode on SM 10.x / 11.x (B200, GB200, B300, Thor) with
  cuDNN 9.19 - 9.25.0 except 9.24.1 gives wrong attention (silently corrupted greedy
  generation). torch 2.14.0 already refuses it (pytorch#194963); torch 2.11 - 2.13
  cu128 / cu129 / cu130 / cu132 wheels (cuDNN 9.19 / 9.20) do not.
- pytorch#196678: non-causal SDPA backward on SM 9.0 with cuDNN < 9.26 returns NaN dQ when
  the key length is 64 mod 128 and a row's logsumexp is below ln(FLT_MIN) (left-padded
  DPO / KTO batches). torch 2.15.0 refuses it (pytorch#196861); torch 2.11 - 2.14 do not.

fix_cudnn_sdpa_known_bad_shapes mirrors both torch guards exactly (same version, device and
shape rules) as an F.scaled_dot_product_attention wrapper, installed only when a visible
device is affected, running the caller's enabled flash / efficient / math backends instead
(a cuDNN-only policy is left alone). The backend index is read through
assume_constant_result so compiled callers trace it without a graph break.
UNSLOTH_ALLOW_BUGGY_CUDNN_SDPA=1 opts out.

Tests (CPU, mocked capability / cuDNN / torch version):
UNSLOTH_NO_LOCAL_GPU=1 CUDA_VISIBLE_DEVICES= python -m pytest -q -o addopts= \
  tests/test_cudnn_sdpa_known_bad_shapes.py  -> 59 passed
plus neighbouring SDPA suites (grad layout, d256, dtensor, import drift, length bucket,
masked bucket, rocm windows, compiled block, fully masked rows): 172 passed, 118 skipped.
GPU repros (not run here): b200_kv_heads_lt8.py, h100_nan_dq_mask.py.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-04T14:13:49.330557Z ec94432 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 5110ea1d30

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

danielhanchen added a commit that referenced this pull request Oct 29, 2026
…15946)

## Summary

`Repo tests (CPU, studio)` is red on main since #15919, and on every PR
based after it (seen on staging for #15928, #15931 and #15934). Three
tests in `tests/studio/test_desktop_reliability_frontend_contract.py`
fail:

- `test_audio_page_matches_the_image_rail_header_and_action_footer`
- `test_images_header_tracks_preview_and_preserves_titlebar_controls`
- `test_media_page_headers_out_stack_the_mac_drag_region`

#15919 rebuilt the Images, Video and Audio headers on purpose: Create /
Train is centred in a `minmax(0,1fr)_auto_minmax(max-content,1fr)` row,
and the API / Library / sibling links moved into the new
`MediaHeaderActions` component, which steps down (pill off centre,
compact, then hidden) as space runs short. The product is right and the
tests pinned the old class strings, so the tests are what changes here.

## What changed

- A shared `_assert_media_header_row` check for the Images and Audio
headers: the new row columns, the pill centred in column 2
(`data-media-header-centre ... col-start-2 justify-self-center`), and
the links rendered inside `<MediaHeaderActions>` (the Library and
sibling links are now asserted to sit inside it, not just somewhere in
the header).
- `MediaHeaderActions` itself is pinned to what the old inline markup
guaranteed: its slot stays `pointer-events-none col-start-3 row-start-1`
(so gaps in the band still drag the macOS window) and only the links'
group is `pointer-events-auto`.
- The macOS drag-region test counts the clickable group drawn by
`MediaHeaderActions` when a page renders it, since that group no longer
appears in the page source.

## Verification

- Base (main at `862098ed4a`): 3 failed, 41 passed. Bisected to #15919:
its parent passes all 44.
- Head: 44 passed.
- Each guard still fails when the property it protects breaks (source
edited, test run, reverted):
  - slot made `pointer-events-auto`: Images and Audio header tests fail
  - links group no longer `pointer-events-auto`: all three fail
- Images sibling link moved out of `MediaHeaderActions`: Images header
test fails
  - Audio pill set to `justify-self-end`: Audio header test fails

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Oct 29, 2026
#15992)

## Summary


`studio/backend/tests/test_sharegpt_image_parallel_fetch.py::test_local_only_dataset_starts_no_threads`
(added in #15786) fails whenever it is the first test in its process to
create a `tqdm` bar, and passes otherwise. Seen on the `(Python 3.13,
rest)` backend shard for #15934, which does not touch this code:

```
tests/test_sharegpt_image_parallel_fetch.py:173: in test_local_only_dataset_starts_no_threads
E   assert [1] == []
```

Run on its own it fails every time on main (`pytest
tests/test_sharegpt_image_parallel_fetch.py::test_local_only_dataset_starts_no_threads`).
The one thread is tqdm's `TMonitor`: `tqdm.__new__` starts it for the
first bar in a process (unless `monitor_interval` is 0), and the
conversion's progress bar is that first bar when nothing earlier in the
xdist worker made one. The product does what the test means to check (a
local-only dataset takes the serial path and starts no fetch workers);
the test counted a process-global helper as a worker.

## What changed

The test sets `tqdm.std.tqdm.monitor_interval = 0` through `monkeypatch`
before counting, so the process-wide `Thread.__init__` count and the
`active_count()` check stay as strict as before and only the monitor is
out of the picture.

## Verification

- Base (main): the test alone fails with `assert [1] == []`.
- Head: alone 1 passed; whole file 9 passed.
- With the serial branch in `convert_sharegpt_with_images_to_vlm_format`
forced onto the thread pool (`if num_workers <= 1:` changed to `if
False:`), the test fails again with `assert [1] == []`, so it still
catches a local-only dataset starting fetch workers.
danielhanchen added a commit that referenced this pull request Oct 29, 2026
…follow the hoisted audio_base64 in the turn-scope check (#16023)

Two checks went red on main with #15889 (LFM3-Audio / LFM3-Omni on MLX).
They fail every PR's Backend CI `(Python 3.13, g-r)` shard and `Repo
tests (CPU, studio)` job, for example on #15988 and #15934.

## 1. The audio-input route's heal gate did not get the request's
contract


`test_passthrough_healing.py::test_every_post_decode_reinterpreter_is_handed_the_request_s_own_contract`
requires every `heal_gate` / `nudge_enabled` call to be handed the
request's `response_format`, so a constraining format withdraws
tool-call healing. #15889 added a new call in the audio-input branch of
`routes/inference.py` without that argument:

```
AssertionError: heal_gate/nudge_enabled not handed the contract at [30849]
```

The product side is where this belongs, not the test. Today the omission
is harmless: that branch only runs when the request carries
`audio_base64` and the model has audio input, and earlier in the handler
that same case refuses a constraining `response_format`. Forwarding
`_extract_response_format(payload)` keeps the site under the same rule
as the other nine. If that refusal is ever relaxed, the gate then does
the right thing without anyone remembering this site.

## 2. The turn-scope check read `audio_base64` as a literal


`test_multi_chat_prompt_queue_contract.py::test_a_media_turn_stays_legacy_and_its_attachments_stay_turn_scoped`
checks that `image_base64`, `audio_base64` and `video_base64` are
scanned from `currentTurnMessages`, never from thread history. #15889
hoisted the audio scan into `const turnAudioBase64 =
findLatestUserAudioBase64(currentTurnMessages, ...)` so it can also gate
`modalities`. The behaviour is unchanged, but the test matched the old
inline text.

Here the test was wrong. It now reads every request body site for each
field and follows a hoisted `const` to its definition. It then requires
the value to be a `findLatestUser*Base64(currentTurnMessages, ...)`
scan. A new test pins that reader on a hoisted value and on a history
scan.

## Verification

- Both tests fail on main and pass here. `test_passthrough_healing.py`
has 111 passed, `test_multi_chat_prompt_queue_contract.py` 17 passed.
- Sabotage, frontend: pointing `turnAudioBase64` at `messages` instead
of `currentTurnMessages` fails the media turn test and names the sent
expression.
- Sabotage, backend: restoring main's `routes/inference.py` fails the
contract test.
- The 15 backend test files that touch `audio_base64` or the heal gate:
2872 passed, 7 skipped.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
… key-length guard

Compiled calls captured the SDPA backend flags once at trace time (assume_constant_result) and
baked an sdpa_kernel restore to that snapshot, so a later call under a different policy ran a
backend the caller excluded and left it enabled. The cuDNN switch and its restore are now graph
calls (allow_in_graph) that read the flags when they run and turn back on only the cuDNN flag they
turned off.

The dQ-NaN rule tested s_kv % 128 == 64 in Python, which guarded on a dynamic key length: an
extra graph under dynamic compiles and a ConstraintViolationError under a strict mark_dynamic.
While compiling, the length is now tested on its value by the switch itself.

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Under AOTAutograd (aot_eager, inductor) the switch and restore helpers run
only while tracing, so the SDPA backend is fixed at compile time, and Dynamo
folds the backend flag reads without a guard. A call compiled under a
cuDNN-only policy kept the cuDNN kernel after a fallback was enabled, and
the reverse.

Read the decision through a module attribute (_SDPA_CUDNN_POLICY.cudnn_off):
Dynamo guards module attribute reads by value, re-read on every call, as it
does torch.backends.cudnn.enabled, so a policy change recompiles. Tests
compile with aot_eager and inductor through a probe op that picks its kernel
from the cuDNN flag when decomposed, as aten SDPA does.

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

An executable FX graph (torch.compile backend=eager) ran the switch, SDPA and
restore as separate nodes, so an SDPA exception (e.g. CUDA OOM) skipped the
restore and left cuDNN disabled. _sdpa_without_cudnn now does all three under
its own try/finally and is the single allow_in_graph call.

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: c36c6f7056

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 5392730605

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 1, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: a1fa7c5448

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: ec944325d8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 4, 2026
@danielhanchen
danielhanchen merged commit 8161e81 into main Nov 4, 2026
@danielhanchen
danielhanchen deleted the torch-backport-cudnn-sdpa branch November 4, 2026 14:54
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.

1 participant