Repository navigation
Keep attention in fp32 for fp32 models instead of downcasting to bf16 - #18099
Conversation
… 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.
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
There was a problem hiding this comment.
💡 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".
| and _keeps_fp32_attention(Q, K, V) | ||
| and _sdpa_replaces_half_kernel(config, context) | ||
| ): | ||
| backend = SDPA |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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]
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…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.
Problem
A model loaded with
dtype = torch.float32gets bf16 attention on some GPUs, without any warning._run_attentiondowncasts 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.6Bin fp32, 1,024 tokens, per-token log-probs against HF fp32 eager: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_packed_fp32_prefers_xformersno longer sends such packed calls to xformers on sm_100+, so they stay on per-segment fp32 SDPA.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.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).