Skip to content

Training SDPA: bucket sequence lengths where torch picks cuDNN, so padded batches stop rebuilding plans - #15134

Merged
danielhanchen merged 3 commits into
mainfrom
sdpa-cudnn-length-buckets
Oct 24, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
sdpa-cudnn-length-buckets

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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. #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 Attention: keep training SDPA off cuDNN attention on SM100 #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 Attention: keep training SDPA off cuDNN attention on SM100 #15019 pin for now.
  • Coverage: 16-bit LoRA end to end and other models were not run.

cuDNN attention builds a new plan for every new sequence length (~170 ms
forward plus backward on H100). torch 2.14 picks cuDNN for training SDPA on
H100, and padded batches change length every step, so nearly every step paid
for a plan build. Causal calls with no mask now pad Q / K / V along the
sequence to a multiple of UNSLOTH_SDPA_CUDNN_BUCKET (128; 0 disables) and
slice the output, so the plan count is bounded by max_len / 128. Padded keys
follow every real query, so causal masking hides them.

Only applies where SDPA would pick cuDNN for the call (probed per shape), so
A100 / L4 / RTX PRO 6000 (flash) and the SM100 no-cuDNN pin are unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 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-24T14:21:03.715209Z 6c83c4f 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 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: 84c1042ff1

ℹ️ 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 on lines +157 to +158
Q, K, V = (F.pad(x, (0, 0, 0, pad)) for x in (Q, K, V))
out = scaled_dot_product_attention(Q, K, V, is_causal = True, **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.

P1 Badge Disable local length bucketing during ring context parallelism

When ring context parallelism is active on a device where SDPA selects cuDNN (for example, H100 with torch 2.14), these tensors are local sequence shards, not complete sequences. ContextParallelManager.apply replaces F.scaled_dot_product_attention with the ring dispatcher, and _ring_sdpa_backends explicitly permits cuDNN on supported torch versions. Padding each shard here therefore inserts unmasked zero keys between real portions of the global sequence: later queries can attend to padding from earlier shards, changing softmax normalization and silently corrupting outputs and gradients. Slicing the local output does not remove those contributions. Exclude _ring_attention_active() calls from the bucketing gate, or implement globally aware padding and masking.

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 6c83c4f: the bucketing gate now returns False whenever a context parallel manager is active (ring or ulysses), since the tensors can be sequence shards there. Covered by test_not_applied_under_context_parallelism[ring|ulysses].

@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: 6c83c4fb40

ℹ️ 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 a224ff3 into main Oct 24, 2026
11 of 29 checks passed
@danielhanchen
danielhanchen deleted the sdpa-cudnn-length-buckets branch October 24, 2026 14:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant