Skip to content

Fix FlashAttention fp32 crash with DoRA (use_dora=True) - #6526

Merged
danielhanchen merged 4 commits into
unslothai:mainfrom
danielhanchen:fix-fa2-dora-1013
Jun 23, 2026
Merged

danielhanchen merged 4 commits into
unslothai:mainfrom
danielhanchen:fix-fa2-dora-1013

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Fixes the crash when combining FlashAttention 2 with DoRA (use_dora=True):

RuntimeError: FlashAttention only support fp16 and bf16 data type

Root cause

For LoRA training we upcast the trainable adapter params (lora_A, lora_B and
lora_magnitude_vector) to fp32 so the optimizer has fp32 master weights. That is
correct and needed for DoRA.

The side effect is in PEFT's DoRA forward:

mag_norm_scale = (magnitude / weight_norm).view(1, -1)
result_dora = (mag_norm_scale - 1) * base_result + mag_norm_scale * lora_result * scaling

magnitude is the fp32 magnitude vector, so type promotion makes result_dora fp32.
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 when
autocast 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 to
the 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:

Config Before After
DoRA + FA2 RuntimeError PASS (loss 7.55)
standard LoRA + FA2 PASS PASS (loss 7.53)
DoRA + SDPA PASS PASS (loss 7.55)

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 flash
functions 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

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

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread unsloth/utils/attention_dispatch.py Outdated
Comment on lines +143 to +150
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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
  1. When handling exceptions, avoid broad except Exception: pass clauses. Instead, catch specific exceptions and log them (at least at a debug level) to aid in troubleshooting.

@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: 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".

Comment thread unsloth/utils/attention_dispatch.py Outdated
# 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:

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 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)

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 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 👍 / 👎.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 7cb13d5bb9

ℹ️ 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".

@oobabooga

Copy link
Copy Markdown
Member

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 ✅

@danielhanchen
danielhanchen merged commit 9780cdc into unslothai:main Jun 23, 2026
37 of 46 checks passed
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.

When Flash Attention 2 is used and "use_dora = True", errored out: "RuntimeError: FlashAttention only support fp16 and bf16 data type"

3 participants