Skip to content

Packed attention: run the in-graph varlen probe with grad enabled, so a checkpoint's no_grad first trace keeps the varlen path - #15414

Merged
danielhanchen merged 4 commits into
mainfrom
dh/s7-rc-packed_probe_grad
Oct 27, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
dh/s7-rc-packed_probe_grad

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Problem

_varlen_in_graph_probe (unsloth/utils/hf_packed_attention.py) decides once per (device, dtype, head_dim, heads, kv_heads, window) whether a compiled decoder block may call aten's flash varlen kernel. It runs a real forward and backward, catches any exception as "no", and caches the answer for every grad mode.

The probe is evaluated while Dynamo traces the block. If that first trace runs without grad, the probe's .backward() raises, the probe returns False, and the cached False then also serves every later grad-enabled call. Two real ways to get there: a packed torch.inference_mode() (or no_grad) forward before training, for example a quick generation or evaluation pass, and a reentrant torch.utils.checkpoint(..., use_reentrant=True) around a compiled block, whose first forward runs under no_grad. Unsloth's own block compile already runs a grad-enabled trial first, so the default offloaded checkpointing path is not affected. When it happens, the packed row falls back to SDPA over the dense T x T mask for the whole run while the metadata preparation still runs every step. Outputs stay correct; the speedup from #15325 is lost.

Fix

The probe body runs under torch.inference_mode(False), torch.enable_grad(), so its verdict is the same whichever grad mode the first trace has. The cheap hardware/build checks now run before the two probe tensors are allocated. Nothing else changes: the cache key, the traced branch and the kernel call are untouched.

Before / after

B200, torch 2.13.0, transformers 5.17.0. Base = origin/main 0ea0473, head = this branch.

Test Base Head
test_varlen_in_graph_probe_runs_its_backward_with_grad_enabled[no_grad] FAIL (probe saw grad off) PASS
test_varlen_in_graph_probe_runs_its_backward_with_grad_enabled[inference_mode] FAIL (probe saw inference mode) PASS
test_varlen_in_graph_verdict_does_not_depend_on_the_first_grad_mode[no_grad] FAIL (False cached, grad answer True) PASS
test_varlen_in_graph_verdict_does_not_depend_on_the_first_grad_mode[inference_mode] FAIL (False cached) PASS
test_reentrant_checkpoint_first_trace_keeps_the_block_varlen_path FAIL (packed row fell back to dense SDPA) PASS, forward and dQ / dK / dV match SDPA
tests/test_hf_packed_attention.py + tests/test_block_compile.py, whole files 175 passed, 15 failed 180 passed, 10 failed

The 10 failures left on head are the same test IDs on base (test_varlen_matches_sdpa_over_the_dense_mask[*-dispatch-*] and test_block_varlen_runs_inside_the_graph_and_matches_dense_sdpa[*], which pass when run alone). The two CPU-only tests also pass on CPU hosts, and the first one passes on torch 2.14.1.

Not covered

  • An end-to-end packed training throughput A/B with Unsloth gradient checkpointing (exclusive GPU) was not run. The engagement test shows the varlen kernel now runs in both the checkpoint forward and its recompute.
  • _leaves_block_probe (used only on torch < 2.13) also reads grad state through _fused_sdp_choice and is not changed here.
  • torch 2.10 / 2.11 / 2.12 and ROCm were not run.

… a checkpoint's no_grad first trace keeps the varlen path
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-10-27T10:34:53.749829Z 03d5867 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 93388d3b18

ℹ️ 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. You're on a roll.

Reviewed commit: 03d58674e6

ℹ️ 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".

[skip ci]
@danielhanchen
danielhanchen merged commit 707f023 into main Oct 27, 2026
@danielhanchen
danielhanchen deleted the dh/s7-rc-packed_probe_grad branch October 27, 2026 12:53
danielhanchen added a commit that referenced this pull request Oct 27, 2026
…6 - 2.13 (#15445)

## Problem

On torch 2.6 through 2.13, the cuDNN SDPA backward caches its execution
plan under a key that leaves out the strides of `grad_output`. Suppose
one process runs two same-shape cuDNN SDPA backwards, and the second
`grad_output` has a different layout from the first. The second backward
then reuses the first plan and returns wrong dQ / dK / dV. There is no
error and there are no NaNs.

A common way to hit it is a HF style call, which reads the output
through `transpose(1, 2)` and so hands back a `(B, T, H, D)` gradient,
followed by a call that reads the output directly and hands back a
contiguous `(B, H, T, D)` gradient. Errors against an fp32 math
reference (bf16, B=1, H=8, T=374, D=64, B200):

| Case | torch 2.13.0 / cuDNN 9.20 | torch 2.14.1 / cuDNN 9.24 |
| --- | --- | --- |
| second backward, block-causal mask | 6.31 | 0.016 |
| second backward, `is_causal=True` | 6.31 | 0.016 |
| second backward, no mask | 0.68 | 0.002 |
| second backward, B=4 H=16 T=1024 D=128 causal | 10.69 | 0.031 |
| same layout both times | 0.016 | 0.016 |

This is a torch bug, not a cuDNN one:

- torch 2.13.0 still fails with the cuDNN 9.24 library swapped in.
- torch 2.10.0 / cuDNN 9.10 fails the same way.

`aten/src/ATen/native/cudnn/MHA.cpp` in 2.13 builds `MHAParams` from the
q / k / v / bias dims and strides only. With cuDNN >= 9.5.1 it hands
`grad_output` to cuDNN with its own strides; older cuDNN builds copied
it to the output layout first. pytorch/pytorch#191576 (commit
eaf9ee9780, first released in 2.14.0) adds the `o`, `dO` and
softmax-stats dims and strides to the key. pytorch/pytorch#144913 and
#202035 are related cuDNN SDPA backward layout reports, but neither is
this bug.

On torch 2.13 with CUDA 13 wheels and cuDNN > 9.15, SDPA picks cuDNN
first by default on SM90 and SM100. Unsloth's own training SDPA avoids
cuDNN on SM100, but HF modeling code (`attn_implementation="sdpa"`) and
the H100 path still run the cuDNN backward. In this repo,
`test_block_varlen_runs_inside_the_graph_and_matches_dense_sdpa` fails
when it runs inside the full `tests/test_hf_packed_attention.py` file on
torch 2.13 / B200. Its cuDNN dense reference reuses a plan that an
earlier test left behind, and gets max abs error 3.3 to 4.9.

## Fix

On torch 2.6 - 2.13 with CUDA and cuDNN >= 9.5.1 (not ROCm),
`fix_cudnn_sdpa_backward_grad_layout` wraps
`torch.nn.functional.scaled_dot_product_attention`. When the output
requires grad, it passes through a small identity `autograd.Function`,
and the backward of that function gives the incoming gradient the
output's own strides. If the gradient already has them, nothing is
copied.

The output layout follows the query layout, and the query layout is part
of the key. With `grad_output` pinned to the output layout, the key
fully describes the plan. This is the same condition torch 2.14
enforces. cuDNN attention stays enabled, so its speed is kept. Every
other backend just sees a gradient in its own output's layout.

`UNSLOTH_SKIP_CUDNN_SDPA_GRAD_LAYOUT_FIX=1` opts out. On torch >= 2.14
nothing is installed.

Alternatives considered:

- Forcing `grad_output.contiguous()` is also correct, as long as every
call goes through it. But it copies on every HF call, because HF
gradients come in `(B, T, H, D)` layout.
- Disabling cuDNN SDPA for training is correct but slow. Flash attention
cannot take a mask, so masked training falls back to the efficient
kernel (numbers below).

The block varlen test now takes a math-backend reference, as #15414's
test does, so its result no longer depends on test order.

## Before / after

Tests on B200 (base = main 8abe47a):

| Test | 2.13.0 base | 2.13.0 head | 2.14.1 base | 2.14.1 head |
| --- | --- | --- | --- | --- |
| `test_cudnn_sdpa_backward_is_right_across_grad_layouts_after_import`
(eager mask / causal / no mask, both orders, compiled) | FAIL (6.31) |
PASS | skip | skip |
| same test with the opt-out env (kill switch) | n/a | bug reproduces (>
0.5) | n/a | n/a |
| `TestAffectedRange`, `TestGradInOutputLayout` (CPU) | FAIL (no symbol)
| PASS | FAIL (no symbol) | PASS |
| `test_block_varlen_runs_inside_the_graph_and_matches_dense_sdpa[None,
4]` in the full file | FAIL | PASS | not run | not run |
| `test_cudnn_sdpa_d256_masked_backward.py` | PASS | PASS | PASS | PASS
|

Speed: attention forward + backward, Qwen3-0.6B shape (B=4, 16 heads,
head_dim 128, bf16, HF layout), torch 2.13.0, B200. Each value is the
median ms over 3 repeats of 20 steps.

| T, kind | cuDNN | cuDNN + this fix | cuDNN + fix, contiguous grad
(copy) | flash | efficient |
| --- | --- | --- | --- | --- | --- |
| 1024 causal | 0.178 | 0.208 | 0.227 | 0.363 | 0.675 |
| 2048 causal | 0.420 | 0.406 | 0.407 | 1.101 | 2.130 |
| 4096 causal | 0.988 | 1.100 | 1.187 | 3.383 | 7.467 |
| 1024 masked | 0.355 | 0.303 | 0.495 | no kernel | 1.129 |
| 2048 masked | 0.880 | 0.884 | 0.934 | no kernel | 3.866 |
| 4096 masked | 3.146 | 3.144 | 3.236 | no kernel | 15.070 |

With HF layout gradients, a profiler run of the fix arm shows the same 7
CUDA kernels and the same device time as plain cuDNN (T=4096 causal).
The remaining differences are eager host overhead from one extra
autograd node, and they sit within the run-to-run spread seen on 2.14.1.
A copy runs only when a caller hands a gradient in another layout, and
it costs about 3% at T=4096. Turning cuDNN off instead would cost 2.6x
to 3.4x on causal calls (flash) and 4.4x to 4.8x on masked calls
(efficient).

## Not covered

- Code that calls `torch.ops.aten._scaled_dot_product_cudnn_attention`
directly, or that bound `scaled_dot_product_attention` before Unsloth is
imported, bypasses the wrapper.
- torch 2.14.0 nightlies from before 2026-08-05 still carry the bug but
report version 2.14.0, so they are left alone.
- Only torch 2.10.0 and 2.13.0 were run on the affected side. 2.6 - 2.9,
2.11 and 2.12 are covered from the `MHA.cpp` source at each tag.
- SM90 (H100) was not run: Colab had no H100 for this account. The fault
is in the arch-neutral torch cache key, and SM90 is a default cuDNN arch
on 2.13, so H100 is expected to be affected, but that has not been
measured.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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