Skip to content

Attention: keep packed fp32 on one xformers call, read the fp32 downcast from Q's device - #14805

Merged
danielhanchen merged 4 commits into
mainfrom
dh/s3-packed-fp32-attention
Oct 23, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
dh/s3-packed-fp32-attention

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

On sm_80+ hosts without flash-attn, select_attention_backend(use_varlen=True) prefers torch's kernels for packed rows. Torch varlen only takes fp16 / bf16, so fp32 Q/K/V (DoRA) fell through to _sdpa_packed_segments and made one SDPA launch per run of equal-length segments.

With 64 segments (2144 tokens, H=8, KV=2, D=64) on B200 that is 64 SDPA calls per forward. Before the native preference landed it was one block-diagonal xformers call, and the audit measured 34.2 ms vs 1.67 ms fwd+bwd.

Changes

  • _run_attention reroutes a packed SDPA call back to xformers when the inputs are fp32 and SDPA was chosen only because torch varlen is preferred. This covers xformers present, native preference on, segment path on, no padding mask, CUDA, no dropout, and no ring attention. The per-device, padding-mask and int32 guards still run afterwards. fp16 / bf16 routing is unchanged.
  • The xformers fp32 downcast is now decided from Q's device (_xformers_rejects_fp32) instead of device 0. CPU tensors on a B200 host were being downcast to bf16, which made test_plain_causal_attention_traces_with_a_dynamic_length[xformers] fail on GPU hosts.

Tests

  • tests/utils/test_attention_packed_fp32_routing.py
    • CPU routing tests with mocks: fp32 pack -> 1 xformers call, bf16 -> torch varlen, no xformers / dropout -> SDPA.
    • A device-keyed downcast test.
    • A CUDA parity test: 64 segments, fp32, forward and dQ/dK/dV against an fp64 per-segment SDPA reference, asserting exactly one xformers launch.
  • On main, 5 of the 6 new tests fail on a GPU host, and so does the existing [xformers] dynamic-length test. All pass with this change.
  • Two existing tests that patched the module flag on CPU tensors now patch _xformers_rejects_fp32.

Verified on B200 (torch 2.13): 64 SDPA calls on main vs 1 xformers call here for fp32; bf16 makes 1 varlen call on both. The attention test files pass on CPU and GPU.

…ast from Q's device

select_attention_backend prefers torch's kernels for packed calls on sm_80+ hosts
without flash-attn, but torch varlen takes only fp16 / bf16. fp32 Q/K/V (DoRA) then
fell to one SDPA launch per segment run: 64 launches for a 64-segment pack, about
20x slower on B200 than the single block-diagonal xformers call used before. Route
those calls back to xformers; fp16 / bf16 dispatch is unchanged.

The xformers fp32 downcast flag was read once from device 0, so CPU tensors on a
B200 host were downcast to bf16. Decide it from Q's device instead.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-23T07:10:41.237008Z afed9a2 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 added a commit that referenced this pull request Oct 22, 2026
pre-commit.ci fails `ruff-format-with-kwargs` on every open PR (#14806,
#14805, #14803, #14790, #14785, #14781, #14780, #14777, #14776, #14775,
#14774, #14773, #14772, #14770, #14769, #14768, and others): "files were
modified by this hook". pre-commit.ci runs the hooks on all files, and
20 files on main (26 by the time this lands) are not in the formatter's
output, so every PR is reformatted outside its own diff. Where
pre-commit.ci can push, its autofix commit drags those unrelated files
into the PR (for example #14790's touches `tests/test_block_compile.py`,
`tests/test_bnb_integration_compile.py` and `unsloth/models/_utils.py`).

The drift came in with PRs merged today, among them #14702, #14751,
#14759, #14784, #14786, #14787, #14788, #14791 and the FP8 block decode,
GRPO routing replay, 4-bit decode, compiled blocks and MoE LoRA target
changes.

### Change

`python scripts/run_ruff_format.py` (the hook's own entry point,
`ruff==0.6.9` as pinned in `.pre-commit-config.yaml`) applied to those
20 files, plus 6 more from #14739, #14779 and #14806, which merged while
this was open. Formatting only.

### Verification

- Every changed file parses to an identical AST before and after.
- A second run of the hook over the same files changes nothing (fixed
point), and over all tracked Python files on this branch it changes
nothing.
- `ruff check` passes on the changed files;
`tests/test_formatter_fixed_point.py` passes (16).

Open PRs pick this up on their next pre-commit.ci run after merging
main.
@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: 5a1bc73cda

ℹ️ 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 +876 to +877
if backend == SDPA and _packed_fp32_prefers_xformers(config, context, Q, K, V):
backend = XFORMERS

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 Keep deterministic packed FP32 attention on SDPA

When torch.use_deterministic_algorithms(True) is active on an sm80+ host with xFormers but no FlashAttention, packed FP32 inputs still satisfy this condition and are switched from SDPA to xFormers. _torch_varlen_takes() deliberately rejects deterministic mode, and hf_packed_attention._sdpa_requested() likewise keeps such calls on SDPA because the varlen/efficient backward is nondeterministic; this new branch instead bypasses the deterministic per-segment SDPA path and can silently violate reproducibility or fail under strict deterministic enforcement. Exclude deterministic mode from this reroute.

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 afed9a2: packed fp32 now stays on per-segment SDPA under torch.use_deterministic_algorithms(True), matching _torch_varlen_takes and hf_packed_attention._sdpa_requested. xformers' flash backward is marked non-deterministic (xformers fmha/flash.py IS_DETERMINISTIC = False, rejected in common.py when deterministic mode is on). Test: test_packed_fp32_deterministic_stays_on_sdpa.

Comment on lines +769 to +770
if torch.float32 not in (Q.dtype, K.dtype, V.dtype):
return False

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 Keep unsupported head dimensions on SDPA

On sm100+ devices, where the file notes that xFormers can only use its fp16/bf16 FlashAttention op, packed FP32 inputs with a head dimension above 256 still pass this predicate, get downcast, and are sent to an xFormers kernel that cannot execute that shape. The previous per-segment SDPA path supports the fallback, and _torch_varlen_takes() already rejects Q.shape[-1] > 256; apply the same shape eligibility check before rerouting so large-head models do not fail with “no operator found.”

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 afed9a2: on cards where xformers needs the fp32 downcast (sm_100+), head_dim above 256 now stays on SDPA, since xformers' flash op caps K at 256. Below sm_100, cutlass runs fp32 at any head dim, so the single call is kept there. Test: test_packed_fp32_large_head_dim_stays_on_sdpa_on_sm100.

Deterministic mode keeps the per-segment SDPA path, as _torch_varlen_takes and
hf_packed_attention already do: xformers' flash backward is non-deterministic.
On sm_100+ fp32 is downcast for xformers' flash op, which has no kernel above
head_dim 256, so those calls also stay on SDPA.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: afed9a260a

ℹ️ 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 0947723 into main Oct 23, 2026
@danielhanchen
danielhanchen deleted the dh/s3-packed-fp32-attention branch October 23, 2026 08:47
danielhanchen added a commit that referenced this pull request Oct 27, 2026
…out autocast (#15410)

## Problem

#14805 sends packed fp32 rows back to one xformers call when torch
varlen is preferred and flash-attn is absent. On sm_100+ (B200, sm_120)
xformers only runs its fp16 / bf16 flash op, so `_run_attention`
downcasts Q/K/V to bf16 and returns the bf16 result. The per-segment
SDPA that the reroute replaced returned fp32 when autocast is off.

A model loaded with `dtype = torch.float32` and trained without autocast
(`bf16 = False`, `fp16 = False`) then hands a bf16 tensor to an fp32
`o_proj`:

```
RuntimeError: expected mat1 and mat2 to have the same dtype, but got: c10::BFloat16 != float
```

## Fix

When the packed fp32 reroute fires and autocast is off, the xformers
output is cast back to the input dtype. Under autocast the output stays
in the autocast dtype, which is what the per-segment SDPA returned too.
The routing (one xformers launch per packed call) is unchanged.

## Before / after

B200, torch 2.13, transformers 5.17, real xformers, no flash-attn. Tiny
Llama (head_dim 64, 2 layers) loaded through `FastLanguageModel` with
`dtype = torch.float32`, LoRA on q/k/v/o, packed forward
(`packed_seq_lengths = [40, 32, 24]`) plus backward, no autocast, block
compile off:

| arm | packed forward + backward | xformers calls |
|---|---|---|
| main with `_packed_fp32_prefers_xformers` forced off (pre-#14805
routing) | pass, loss 10.4728 | 0 |
| main | `expected mat1 and mat2 to have the same dtype` | 1 |
| this PR | pass, loss 10.4729 | 4 |

Tests in `tests/utils/test_attention_packed_fp32_routing.py`:

| test | main | this PR |
|---|---|---|
| `test_packed_fp32_reroute_keeps_fp32_output_on_sm100` (CPU, mocked
xformers) | fail (fp16 output) | pass |
| `test_packed_fp32_cuda_feeds_an_fp32_o_proj` (real CUDA + xformers) |
fail (bf16 output) | pass |
| the 8 existing tests in the file | pass | pass |

`tests/utils/test_attention_dispatch_dora_dtype.py`: 5 passed on B200.

## Not covered

- The dense (unpacked) xformers path on sm_100+ also downcasts fp32 and
returns bf16, so an fp32 model without autocast fails there on main and
before #14805 alike. That is pre-existing and left alone here, since a
DoRA model on a bf16 base without autocast may depend on the bf16 return
(not tested).
- Only B200 was run. Below sm_100 xformers runs fp32 natively, so no
downcast happens there.

---------

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