Repository navigation
Fix FlashAttention fp32 crash with DoRA (use_dora=True) - #6526
Conversation
DoRA upcasts lora_magnitude_vector to fp32 for the optimizer, which promotes the q/k/v_proj output to fp32. FlashAttention only accepts fp16/bf16, so the fp32 q/k/v raised 'FlashAttention only support fp16 and bf16 data type'. Downcast q/k/v to the compute dtype before the flash kernels. Fixes #1013
There was a problem hiding this comment.
Code Review
This pull request addresses an issue where DoRA upcasts projection outputs to fp32, causing FlashAttention to fail since it only supports 16-bit floating-point formats. The changes introduce downcasting logic for fp32 Q/K/V tensors in run_attention along with regression tests. The review feedback suggests making the autocast dtype lookup more robust by handling potential exceptions more gracefully and ensuring the resolved dtype is strictly restricted to fp16 or bf16.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| if backend in (FLASH_DENSE, FLASH_VARLEN) and Q.dtype == torch.float32: | ||
| flash_dtype = torch.bfloat16 if SUPPORTS_BFLOAT16 else torch.float16 | ||
| if torch.is_autocast_enabled(): | ||
| try: | ||
| flash_dtype = torch.get_autocast_dtype("cuda") | ||
| except (AttributeError, TypeError): | ||
| flash_dtype = torch.get_autocast_gpu_dtype() | ||
| Q, K, V = Q.to(flash_dtype), K.to(flash_dtype), V.to(flash_dtype) |
There was a problem hiding this comment.
The current exception handling only catches (AttributeError, TypeError). However, torch.get_autocast_dtype("cuda") can raise other exceptions such as ValueError or RuntimeError on environments where CUDA is not supported or compiled, which would cause a crash.
Additionally, if autocast is enabled but configured to use torch.float32 (or any other non-16-bit dtype), flash_dtype could end up being a dtype that FlashAttention does not support, leading to the same crash.
We should catch exceptions during the autocast dtype lookup and defensively ensure that flash_dtype is restricted to (torch.float16, torch.bfloat16), falling back to the default 16-bit dtype if not. Note that we should avoid broad except Exception: pass blocks; instead, we should catch specific exceptions or log them at a debug level to aid in troubleshooting.
if backend in (FLASH_DENSE, FLASH_VARLEN) and Q.dtype == torch.float32:
flash_dtype = torch.bfloat16 if SUPPORTS_BFLOAT16 else torch.float16
if torch.is_autocast_enabled():
try:
flash_dtype = torch.get_autocast_dtype("cuda")
except Exception as e:
import logging
logging.getLogger(__name__).debug("Failed to get autocast dtype: %s", e)
try:
flash_dtype = torch.get_autocast_gpu_dtype()
except Exception as e_gpu:
logging.getLogger(__name__).debug("Failed to get autocast GPU dtype: %s", e_gpu)
if flash_dtype not in (torch.float16, torch.bfloat16):
flash_dtype = torch.bfloat16 if SUPPORTS_BFLOAT16 else torch.float16
Q, K, V = Q.to(flash_dtype), K.to(flash_dtype), V.to(flash_dtype)References
- When handling exceptions, avoid broad
except Exception: passclauses. Instead, catch specific exceptions and log them (at least at a debug level) to aid in troubleshooting.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 30a376cf0d
ℹ️ 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".
| # FlashAttention only supports fp16/bf16. DoRA upcasts its magnitude vector to | ||
| # fp32 for the optimizer, which promotes the q/k/v_proj output to fp32 and would | ||
| # raise "FlashAttention only support fp16 and bf16 data type". Downcast here. | ||
| if backend in (FLASH_DENSE, FLASH_VARLEN) and Q.dtype == torch.float32: |
There was a problem hiding this comment.
Downcast K/V when only key/value projections are fp32
This guard only runs when Q is fp32, but users can configure DoRA for a subset of attention targets, e.g. target_modules=["k_proj", "v_proj"]. In that case the base q_proj can still produce bf16/fp16 while PEFT DoRA promotes only K/V to fp32 under autocast, so this block is skipped and the subsequent FlashAttention call still receives fp32 tensors and raises the same dtype error this patch is meant to fix. Check/cast each of Q, K, and V (or trigger on any fp32 input) before dispatching to flash.
Useful? React with 👍 / 👎.
| flash_dtype = torch.get_autocast_dtype("cuda") | ||
| except (AttributeError, TypeError): | ||
| flash_dtype = torch.get_autocast_gpu_dtype() | ||
| Q, K, V = Q.to(flash_dtype), K.to(flash_dtype), V.to(flash_dtype) |
There was a problem hiding this comment.
Store the downcast KV tensors in the decode cache
When DoRA generation runs with use_cache=True, the attention callers save past_key_value = (K, V) before calling run_attention (for example unsloth/models/llama.py:727), so this reassignment only downcasts the local tensors passed to FlashAttention. The returned KV cache remains fp32, and each subsequent decode step concatenates that fp32 cache and then casts the entire prefix again here, doubling cache memory and adding an O(sequence length) dtype conversion per token despite the flash kernel using bf16/fp16. Ensure the cached K/V are the same downcast tensors used for flash.
Useful? React with 👍 / 👎.
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 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". |
|
The included test passes (3/3), and reverting the downcast block makes the dense and varlen tests fail (2), confirming it's what fixes it. The downcast is gated to FLASH_DENSE/FLASH_VARLEN only, so SDPA/eager and already-16bit q/k/v are untouched. LGTM ✅ |
Summary
Fixes the crash when combining FlashAttention 2 with DoRA (
use_dora=True):Root cause
For LoRA training we upcast the trainable adapter params (
lora_A,lora_Bandlora_magnitude_vector) to fp32 so the optimizer has fp32 master weights. That iscorrect and needed for DoRA.
The side effect is in PEFT's DoRA forward:
magnitudeis the fp32 magnitude vector, so type promotion makesresult_dorafp32.For the bnb 4bit/8bit layers PEFT only casts the variant output back to the compute
dtype when
requires_conversion = not torch.is_autocast_enabled(), i.e. only whenautocast is off. During normal mixed precision training autocast is on, so the fp32
q/k/v_proj output is kept and flows into attention. FlashAttention only accepts
fp16/bf16, hence the error. Standard LoRA is unaffected because its output stays bf16.
This is why the only workarounds reported on the issue were "remove flash-attn" or
manually casting every fp32 param back to bf16 after
get_peft_model.Fix
In
run_attention, before dispatching to the flash kernels, downcast fp32 q/k/v tothe compute dtype (autocast dtype if active, else bf16/fp16 based on hardware support).
This is the natural choke point: flash literally cannot take fp32, so downcasting is the
only valid action. SDPA/eager paths are untouched, and already-16bit q/k/v are left as is,
so standard LoRA, rsLoRA and non-FA2 runs are unchanged. The change is model agnostic
since every model routes attention through this dispatch.
Testing
Verified on a B200 with
unsloth/tinyllama-bnb-4bit, all 7 LoRA target modules,use_dora=True,attn_implementation="flash_attention_2", fwd + bwd under autocast:DoRA + FA2 and DoRA + SDPA give identical loss, confirming the downcast does not change
numerics.
Added
tests/utils/test_attention_dispatch_dora_dtype.py. It monkeypatches the flashfunctions so it runs on CPU without flash-attn, and fails on the unpatched dispatch
(2 failed) while passing with the fix (3 passed).
Fixes #1013