Skip to content

Attention: keep training SDPA off cuDNN attention on SM100 - #15019

Merged
danielhanchen merged 7 commits into
mainfrom
dh/s4-sdpa-train-pin
Oct 24, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
dh/s4-sdpa-train-pin

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Stacked on #15009 (base branch dh/s4-padded-block-sdpa); merge that first.

On SM100 GPUs with torch 2.13 and later, SDPA picks cuDNN attention. cuDNN builds a new execution plan for every new sequence length, about 150 ms forward plus backward. Padded training batches change length every step, so without xformers the stock training path paid that in nearly every step.

Training calls now run SDPA on the flash, memory-efficient and math kernels on SM100:

  • The attention forwards pass their module's .training in AttentionContext, and run_attention hands it down as an argument (no global state). The flag also covers the no-grad forward of a checkpointed layer.
  • Eval and generation keep the default choice. UNSLOTH_SDPA_TRAIN_CUDNN=1 restores cuDNN.
  • Under block compile and gradient checkpointing this adds no graph break and no recompile.

Exclusive B200, no xformers, interleaved runs, useful tokens per second:

model, batches before after
Qwen3-0.6B LoRA, padded 2777 / 3060 5164 / 5333
Llama-3.2-1B LoRA, padded 3210 5192 (median step 291 to 138 ms)
Llama-3.2-1B LoRA, padding-free 7335 / 7442 7362 / 6978 (unchanged; this path already avoids cuDNN)

Losses match within run-to-run noise.

Not covered

FastModel and transformers' own attention modules call torch SDPA directly, so padded FastModel training on SM100 is not changed here and was not measured. H100 and ROCm were not run.

danielhanchen and others added 3 commits October 23, 2026 10:39
Inside a compiled decoder block, plain causal xformers calls run as SDPA. On SM100 with torch
2.13+ SDPA then picks cuDNN attention, which builds a new plan for every new sequence length, so
padded batches of varying length paid it in every step (Llama-3.2-1B LoRA, B200: 439 ms median
step compiled vs 227 ms stock). Pin that call to flash / efficient / math, the kernels xformers
itself runs; the backend list is built at import so tracing it adds no graph break.
With torch 2.13+ on SM100, SDPA picks cuDNN attention, which builds a new execution plan for
every new sequence length (about 150 ms forward plus backward). Padded training batches change
length every step, so without xformers the stock path paid it in nearly every step.

Training calls (AttentionContext.training, the attention module's .training, so the no-grad
forward of a checkpointed layer counts too) now run SDPA on flash / efficient / math on SM100
devices. Eval and generation are unchanged; UNSLOTH_SDPA_TRAIN_CUDNN=1 keeps cuDNN.

Exclusive B200, no xformers, interleaved runs, useful tokens/s:
Qwen3-0.6B LoRA padded 2777 / 3060 -> 5164 / 5333, Llama-3.2-1B LoRA padded 3210 -> 5192
(median step 291 -> 138 ms). Padding-free batches already avoid cuDNN (torch varlen / flash)
and are unchanged (7335 / 7442 vs 7362 / 6978).
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a90488e678

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

Comment thread unsloth/utils/attention_dispatch.py Outdated
Comment on lines +106 to +108
if args and args[0].is_cuda and args[0].device.index in _NO_CUDNN_TRAINING:
with _sdpa_kernel(_XFORMERS_LIKE_BACKENDS):
return scaled_dot_product_attention(*args, **kwargs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply the training backend restriction before probing GQA

For SM100 training calls where cuDNN supports GQA but flash cannot handle the mask or shape, _sdpa_takes_gqa still probes with cuDNN enabled and therefore retains enable_gqa=True. This wrapper disables cuDNN only afterward. On torch versions whose memory-efficient kernel does not support GQA, that forces the actual call onto math instead of expanding K/V and using memory-efficient attention, materializing quadratic attention scores and potentially causing OOMs. Both the regular and packed-segment paths perform their GQA probes outside this context; apply the same backend restriction during those probes so their decisions match the kernels available at execution.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ebda178. The enable_gqa probe now runs under the same backend restriction as the call it decides for: when a training call on SM100 runs without cuDNN attention (and for the compiled block's xformers stand-in), the dense and packed-segment GQA probes are asked with flash, efficient and math only. The flag comes from the call's own inputs (no global state), and the probe cache is keyed on the enabled backends, so restricted and default answers are cached separately. A masked GQA call that only cuDNN takes as GQA now expands K/V for the efficient kernel instead of landing on math.

On B200, a masked GQA training call (32 / 8 heads, 2 x 512, right padding) ran on math at 360 MB peak before and on efficient attention (forward and backward) at 81 MB after. A CPU test with a mocked probe checks that the restricted and default probes see the right backend sets, and that the packed-segment path passes the flag only when training; both new tests fail on the previous head.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 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-23T20:35:46.557431Z 6fe57c4 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.

pre-commit-ci Bot and others added 2 commits October 23, 2026 19:07
_sdpa_takes_gqa probed with cuDNN enabled, so on SM100 training (and the compiled block's
xformers stand-in) it could keep enable_gqa for a masked call only cuDNN takes; with cuDNN then
disabled, the efficient kernel (no GQA before torch 2.14) is out and the call ran on math. The
dense and packed-segment probes now run under the same flash / efficient / math restriction as
the call (no_cudnn, derived from the call's inputs), so K/V are expanded for efficient instead.

B200, masked GQA training call (32 / 8 heads, 2 x 512, right padding): math, 360 MB peak, before;
efficient attention, 81 MB peak, after.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: ebda178d00

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

The (Python 3.13, a-k) failures here (test_releasing_an_offloaded_step_graph_frees_its_capture_stream_workspace and test_load_marker_precedes_hub_guard_which_precedes_the_gpu_handoff) are not from this PR. This PR's base is dh/s4-padded-block-sdpa, which predates #15015 and #15017. Those fixed both tests on main. Merging main into the base branch clears them.

Base automatically changed from dh/s4-padded-block-sdpa to main October 23, 2026 20:32
# Conflicts:
#	unsloth/utils/attention_dispatch.py
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 6fe57c4694

ℹ️ 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
danielhanchen merged commit 5b258ae into main Oct 24, 2026
41 checks passed
@danielhanchen
danielhanchen deleted the dh/s4-sdpa-train-pin branch October 24, 2026 01:36
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 24, 2026
…dded batches stop rebuilding plans (unslothai#15134)

On H100 with torch 2.14, SDPA picks cuDNN attention for training
(`_fused_sdp_choice` returns cuDNN; torch 2.10 picks flash). cuDNN
builds a new plan for every new sequence length, about 130 to 170 ms for
forward plus backward. Padded batches change length almost every step,
so that cost lands on nearly every step. unslothai#15019 handled the same issue
on SM100 by keeping training off cuDNN there; H100 was not covered.

### Change
`_training_sdpa` in `unsloth/utils/attention_dispatch.py` now buckets
the sequence length where the existing backend probe says SDPA would
pick cuDNN.
- **When it applies:** causal calls only, with no mask, no dropout,
equal query and key lengths, and fp16 / bf16 on CUDA.
- **What it does:** pads Q / K / V along the sequence to a multiple of
`UNSLOTH_SDPA_CUDNN_BUCKET` (default 128), runs the same SDPA call, and
slices the output. The number of distinct plans is then bounded by
max_len / 128.
- **Why the real rows are unchanged:** the padded keys come after every
real query, so the causal mask hides them. The output rows and the
gradients are what the unpadded call returns.
- **Always at least 1 row of padding:** a zero pad specialises under
dynamo and would recompile when a length becomes an exact multiple of
128.
- **Where it does nothing:** anywhere torch does not pick cuDNN. That
covers torch 2.10 on H100, A100, L4, T4, RTX PRO 6000, AMD, and SM100,
which stays pinned off cuDNN by unslothai#15019.
- **Opt-out:** `UNSLOTH_SDPA_CUDNN_BUCKET=0` disables it.

### Results
Colab H100, Qwen3-0.6B 4-bit LoRA, padded batches with lengths 256 to
2048, batch size 8, 30 steps. Arms were interleaved 3 times with fresh
caches per arm.

| torch | main, steady step (3 runs) | this PR | peak memory main / PR |
final loss main / PR |
|---|---|---|---|---|
| 2.14.1 | 310.9 / 321.4 / 329.9 ms | 239.1 / 239.4 / 234.8 ms | 1.845 /
1.854 GB | 11.2978 / 11.2978 |
| 2.10.0 | 248.6 ms | 249.2 ms (not engaged) | 1.851 / 1.851 GB |
11.2977 / 11.2977 |

- **Speed:** on torch 2.14.1 the median step goes from 321 ms to 239 ms,
25% faster (1.32x). main's own run-to-run spread is 19 ms.
- **Where the time went:** both arms run the same cuDNN kernels with
about the same GPU time per step (245 vs 256 ms). The saving is
host-side plan building.
- **Loss:** the curves match step for step. The largest gap between arm
means is 0.0008, within the 0.0017 spread between repeats of the same
arm.
- **A100 and RTX PRO 6000:** forcing cuDNN there was about 8% slower. So
this change keeps torch's own backend choice and only buckets where
cuDNN is already picked.

### Tests
- **New `tests/test_sdpa_cudnn_length_bucket.py` (16 tests):**
  - the gate;
- outputs and gradients against unpadded cuDNN, for lengths 2 to 1000,
with and without GQA;
  - the bucketed lengths;
- one graph under `torch.compile(dynamic = True, fullgraph = True)`
across 4 lengths.

  All pass on B200 with torch 2.14.1 and 2.10.0.
- **14 attention test files, main vs this PR:**
- torch 2.14.1: 542 passed on both sides. The 8
`test_hf_packed_attention.py::test_varlen_matches_sdpa_over_the_dense_mask`
failures also fail on main.
  - torch 2.10.0: 499 passed, 0 failed on both sides.

### Not covered
- **Other torch versions:** which backend torch 2.11 to 2.13 pick on
H100 was not checked. The gate follows torch's choice either way.
- **Masked calls:** GRPO / DPO left-padded attention may pay the same
per-step plan cost, but it is not handled here.
- **SM100:** a GPU-time profile suggests bucketing would help there too,
but it stays on the unslothai#15019 pin for now.
- **Coverage:** 16-bit LoRA end to end and other models were not run.

---------

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