Skip to content

Keep attention in fp32 for fp32 models instead of downcasting to bf16 - #18099

Merged
danielhanchen merged 3 commits into
mainfrom
fp32-attention-keeps-fp32
Nov 17, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
fp32-attention-keeps-fp32

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

A model loaded with dtype = torch.float32 gets bf16 attention on some GPUs, without any warning. _run_attention downcasts fp32 Q / K / V to bf16 whenever the chosen backend cannot take fp32: FlashAttention (dense or varlen), and xformers on sm_100+. That downcast exists for DoRA (#1013), whose q / k / v projections come out in fp32 inside a 16-bit model, but it also fires for a genuine fp32 model with no autocast.

On a B200 (xformers 0.0.35, no FA2), unsloth/Qwen3-0.6B in fp32, 1,024 tokens, per-token log-probs against HF fp32 eager:

arm attention attention output logp error mean max tokens > 1e-2 hidden rel err, layer 0 / 27
main xformers, fp32 in bf16 5.6e-3 0.304 187 / 1023 2.1e-3 / 4.0e-3
this PR SDPA fp32 2.9e-6 1.7e-4 0 / 1023 8.9e-7 / 2.0e-6

Every parameter and buffer is fp32 in both arms, TF32 is off, and the RMSNorm / RoPE kernels match HF to about 3e-6 once attention stays fp32. Any host with flash-attn installed takes the same branch.

Change

unsloth/utils/attention_dispatch.py

  • When Q, K and V are all fp32 and autocast is off, and SDPA can reproduce the call (no softcap, no xformers-only kwargs, flash kwargs limited to causal / zero dropout / matching scale, a plain causal mask or packing info), the call runs on SDPA in fp32 instead of being downcast.
  • _packed_fp32_prefers_xformers no longer sends such packed calls to xformers on sm_100+, so they stay on per-segment fp32 SDPA.
  • DoRA under autocast (how the Trainer runs it) still downcasts to the autocast dtype, unchanged. Mixed precision training is unaffected, since its Q / K / V are 16-bit.

An fp32 model on a flash-attn or sm_100+ host now pays for fp32 SDPA attention, which is what it asked for.

Tests

  • tests/utils/test_attention_dispatch_dora_dtype.py: an fp32 model stays fp32 through flash dense, flash varlen and sm_100 xformers, and matches an fp32 SDPA reference. tests/utils/test_attention_packed_fp32_routing.py: a packed fp32 model stays fp32 on sm_100. These 5 fail on main and pass here.
  • The existing DoRA downcast tests now run under bf16 autocast, which is how DoRA reaches this code in training.
  • pytest tests/utils -k attention: 212 passed on main (5 new fail), 217 passed, 16 skipped here.

Not covered on a GPU: a flash-attn host (unit tested with a stub kernel), sm_120, and the compiled packed path _prepared_packed_attention, which still downcasts CUDA fp32 input (keeping it fp32 needs a dense mask; left as is).

… bf16

A dtype=torch.float32 model ran attention in bf16 whenever the chosen kernel
was FlashAttention or xformers on sm_100+ (B200, sm_120), because the DoRA
fp32 q/k/v downcast (#1013) also fired when Q/K/V were all fp32 with no
autocast. That cost ~5e-3 nats mean, 0.3 max per token versus an HF fp32
reference. Route such calls to SDPA, which computes fp32 natively; DoRA under
autocast still downcasts to the autocast dtype.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T07:42:12.993817Z 60740b4 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.

[skip ci]

@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: 3c5f788957

ℹ️ 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 +1806 to +1809
and _keeps_fp32_attention(Q, K, V)
and _sdpa_replaces_half_kernel(config, context)
):
backend = SDPA

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 Preserve causal masking when rerouting cached multi-token queries

For fp32 calls with a KV cache, multiple new query tokens (1 < q_len < kv_seq_len), and no explicit attention mask, this switch changes causal FlashAttention into unmasked SDPA. This input is accepted by LlamaAttention_fast_forward, which concatenates past_key_value before calling the dispatcher. The SDPA branch only sets is_causal=True when query and key lengths match, so the rerouted call receives attn_mask=None, is_causal=False, allowing earlier query tokens to attend to later new tokens and changing their outputs. Build an offset causal mask for this case, or exclude it from the replacement predicate until SDPA can reproduce the original 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.

Valid, fixed in 60740b4. The reroute now skips causal calls with no mask and no packing info when 1 < q_len != kv_seq_len, so cached multi-token queries keep the original causal kernel. New test test_fp32_cached_multi_token_query_keeps_causal_flash fails without the change.

…unmasked SDPA is not causal there)

[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. Nice work!

Reviewed commit: 60740b4e11

ℹ️ 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 917904e into main Nov 17, 2026
@danielhanchen
danielhanchen deleted the fp32-attention-keeps-fp32 branch November 17, 2026 08:16
danielhanchen added a commit that referenced this pull request Nov 17, 2026
…ys fp32 (red since #18099) (#18118)

`tests/test_attention_dispatch_compiled_block.py::test_rerouted_xformers_keeps_the_fp32_downcast`
fails on main in the CPU `rest` shard since #18099 (seen on the staging
runs of #18075 and #18076):

```
E   assert torch.float32 == torch.bfloat16
```

## Cause

#18099 made fp32 Q/K/V with autocast off stay fp32 (rerouted to SDPA)
instead of being downcast to bf16 for xformers / flash, because that is
a genuine fp32 model. The DoRA downcast still applies under autocast,
which is how DoRA reaches this code in training. #18099 moved its own
DoRA tests under autocast, but this compiled-path test in another file
still called the reroute with plain fp32 inputs and no autocast, so it
now sees the intended fp32 result.

The behaviour change is correct; the test predates it.

## Fix

- `test_rerouted_xformers_keeps_the_fp32_downcast` now takes the
autocast decision (`_keeps_fp32_attention` returns False), so it still
checks the DoRA downcast through the compiled reroute. CPU CI cannot
enter CUDA autocast, and faking `torch.is_autocast_enabled` trips
dynamo's global autocast guard ("Global autocast state changed while
dynamo tracing"), so the decision is patched directly.
- New `test_rerouted_xformers_keeps_an_fp32_model_in_fp32` covers the
other half under `fullgraph` compile: without autocast the reroute
returns fp32 and matches the fp32 SDPA reference.

## Verification

- main: `test_rerouted_xformers_keeps_the_fp32_downcast` fails.
- this branch: `tests/test_attention_dispatch_compiled_block.py` and
`tests/utils/test_attention_dispatch_dora_dtype.py` 19 passed, 2
skipped.
- Sabotage: with `_keeps_fp32_attention` forced to False (the pre-#18099
behaviour), the new fp32 test fails.
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