Skip to content

refactor attn impl replacement - #4250

Closed
Datta0 wants to merge 6 commits into
unslothai:mainfrom
Datta0:flexattn_refactor
Closed

Datta0 wants to merge 6 commits into
unslothai:mainfrom
Datta0:flexattn_refactor

Conversation

@Datta0

@Datta0 Datta0 commented Mar 12, 2026

Copy link
Copy Markdown
Contributor

The previous impl was setting it to flex_attn for almost every model causing the models to not use FA2. This change creates a preference hierarchy

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly refactors how attention mechanisms are selected within the system. The primary goal is to ensure that models automatically utilize the most efficient attention implementation available, such as Flash Attention 2, by establishing a clear preference hierarchy. This change prevents scenarios where less optimal attention methods were inadvertently being used, thereby improving performance and stability across various models.

Highlights

  • Refactored Attention Implementation Logic: The core logic for determining the optimal attention mechanism has been completely rewritten and centralized into a new function, determine_attention_implementation.
  • Introduced Attention Preference Hierarchy: A clear hierarchy for attention mechanisms has been established: Flash Attention 2 is preferred, followed by Flex Attention, then SDPA, and finally Eager attention as a fallback. This ensures models utilize the most performant available option.
  • Addressed Incorrect Flex Attention Defaulting: The previous implementation often defaulted to flex_attn even when Flash Attention 2 was available, preventing models from leveraging FA2. This change resolves that issue by prioritizing FA2.
  • Improved Model Type Exclusions: Specific model types (e.g., gpt_oss, mllama, gemma3) are now explicitly excluded from using Flash Attention 2 and Flex Attention where they are known to cause issues, ensuring stability and correctness.
Changelog
  • unsloth/models/_utils.py
    • Renamed prefer_flex_attn_if_supported to determine_attention_implementation in the module's export list.
    • Replaced the entire prefer_flex_attn_if_supported function with the new determine_attention_implementation function, which implements a hierarchical selection process for attention mechanisms (Flash Attention 2 > Flex Attention > SDPA > Eager).
  • unsloth/models/llama.py
    • Updated the from_pretrained method to call the new determine_attention_implementation function instead of the deprecated prefer_flex_attn_if_supported.
  • unsloth/models/vision.py
    • Removed the flex_attn_impl variable initialization and related comments, replacing them with a new comment indicating the unified hierarchical attention fallback.
    • Updated the from_pretrained method to use the new determine_attention_implementation function to set attn_impl.
    • Simplified the logic for setting attn_implementation in kwargs, directly using the result from determine_attention_implementation and removing previous model-specific default attention logic.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@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 refactors the attention implementation selection logic, introducing a clear preference hierarchy (Flash Attention 2 > Flex Attention > SDPA > Eager). This is a significant improvement over the previous implementation which incorrectly favored flex attention, preventing the use of the more performant Flash Attention 2. The changes in llama.py and vision.py correctly adopt this new logic. I have one suggestion for the new determine_attention_implementation function in _utils.py to further improve its readability and maintainability by reducing some code duplication.

Comment thread unsloth/models/_utils.py
Comment on lines +225 to 279
def determine_attention_implementation(model_class, config):
model_type = getattr(config, "model_type", "").lower()

if not is_torch_flex_attn_available():
return None
if model_class is None or not getattr(
model_class, "_supports_flex_attn", False
):
return None
# GPT-OSS, Mllama and Gemma3N use eager/sdpa attention during
# inference since flex attention returns incorrect results or errors out.
# GPT-OSS: left padding issues cause incorrect outputs.
# Mllama: _update_causal_mask uses make_flex_block_causal_mask which
# creates BlockMask with Q_LEN=KV_LEN=total_seq_len, but during
# decode q_len=1, causing ValueError. Needs transformers update.
# Gemma3N: timm vision wrappers (eg Gemma3nVisionConfig) do not
# support flex_attention.
model_type = getattr(config, "model_type", "") if config else ""
if model_type in ("gpt_oss", "mllama") or str(model_type).startswith("gemma3n"):
return None
# 1. Flash Attention 2
if (
HAS_FLASH_ATTENTION
and model_type not in ("gpt_oss", "mllama")
and not model_type.startswith("gemma3")
):
supports_fa2 = False
if model_class is not None:
supports_fa2 = getattr(
model_class, "_supports_flash_attn_2", False
) or getattr(model_class, "_supports_flash_attn", False)

if supports_fa2:
if config is not None:
setattr(config, "_attn_implementation", "flash_attention_2")
if hasattr(config, "attn_implementation"):
setattr(config, "attn_implementation", "flash_attention_2")
return "flash_attention_2"

# 2. Flex Attention
if os.environ.get("UNSLOTH_ENABLE_FLEX_ATTENTION", "1") != "0":
try:
from transformers.utils.import_utils import is_torch_flex_attn_available

if (
is_torch_flex_attn_available()
and (model_class is not None)
and getattr(model_class, "_supports_flex_attn", False)
):
# GPT-OSS, Mllama and Gemma3 use eager/sdpa attention during
# inference since flex attention returns incorrect results or errors out.
# GPT-OSS: left padding issues cause incorrect outputs.
# Mllama: _update_causal_mask uses make_flex_block_causal_mask which
# creates BlockMask with Q_LEN=KV_LEN=total_seq_len, but during
# decode q_len=1, causing ValueError. Needs transformers update.
# Gemma3N: timm vision wrappers (eg Gemma3nVisionConfig) do not
# support flex_attention.
if model_type not in (
"gpt_oss",
"mllama",
) and not model_type.startswith("gemma3"):
if config is not None:
setattr(config, "_attn_implementation", "flex_attention")
if hasattr(config, "attn_implementation"):
setattr(config, "attn_implementation", "flex_attention")
return "flex_attention"
except Exception:
pass

# 3. SDPA
if model_class is not None and getattr(model_class, "_supports_sdpa", False):
if config is not None:

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

This function can be refactored to improve readability and reduce code duplication. You can introduce a nested helper function to handle setting the attention implementation on the config object, and extract the repeated model_type check into a boolean variable. This will make the code more concise and easier to maintain.

def determine_attention_implementation(model_class, config):
    def _set_attn_impl(implementation):
        if config is not None:
            setattr(config, "_attn_implementation", implementation)
            if hasattr(config, "attn_implementation"):
                setattr(config, "attn_implementation", implementation)
        return implementation

    model_type = getattr(config, "model_type", "").lower()
    # Models that have issues with flex/flash attention
    is_problematic_for_fused_attn = model_type in ("gpt_oss", "mllama") or model_type.startswith("gemma3")

    # 1. Flash Attention 2
    if HAS_FLASH_ATTENTION and not is_problematic_for_fused_attn:
        supports_fa2 = False
        if model_class is not None:
            supports_fa2 = getattr(model_class, "_supports_flash_attn_2", False) or getattr(model_class, "_supports_flash_attn", False)

        if supports_fa2:
            return _set_attn_impl("flash_attention_2")

    # 2. Flex Attention
    if os.environ.get("UNSLOTH_ENABLE_FLEX_ATTENTION", "1") != "0":
        try:
            from transformers.utils.import_utils import is_torch_flex_attn_available

            if is_torch_flex_attn_available() and (model_class is not None) and getattr(
                model_class, "_supports_flex_attn", False
            ):
                # GPT-OSS, Mllama and Gemma3 use eager/sdpa attention during
                # inference since flex attention returns incorrect results or errors out.
                # GPT-OSS: left padding issues cause incorrect outputs.
                # Mllama: _update_causal_mask uses make_flex_block_causal_mask which
                # creates BlockMask with Q_LEN=KV_LEN=total_seq_len, but during
                # decode q_len=1, causing ValueError. Needs transformers update.
                # Gemma3N: timm vision wrappers (eg Gemma3nVisionConfig) do not
                # support flex_attention.
                if not is_problematic_for_fused_attn:
                    return _set_attn_impl("flex_attention")
        except Exception:
            pass

    # 3. SDPA
    if model_class is not None and getattr(model_class, "_supports_sdpa", False):
        return _set_attn_impl("sdpa")

    # 4. Eager
    return _set_attn_impl("eager")

@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: b85e7d0488

ℹ️ 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/models/_utils.py
pass

# 3. SDPA
if model_class is not None and getattr(model_class, "_supports_sdpa", 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.

P2 Badge Fall back to SDPA when model class is unavailable

This SDPA gate requires model_class to be non-None, so callers that intentionally catch _model_mapping failures (for example in vision.py around the try/except before calling this helper) now drop straight to eager attention even when SDPA is otherwise enabled for that architecture. That is a regression from the previous default behavior (sdpa fallback) and can significantly reduce throughput/memory efficiency for remote-code or unmapped models.

Useful? React with 👍 / 👎.

Comment thread unsloth/models/_utils.py Outdated
if (
HAS_FLASH_ATTENTION
and model_type not in ("gpt_oss", "mllama")
and not model_type.startswith("gemma3")

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 Limit Gemma exclusion to the incompatible Gemma3N path

Using startswith("gemma3") here disables Flash Attention 2 for all Gemma3 variants, even though the compatibility rationale in this function is specifically about Gemma3N vision wrappers. This broader predicate forces plain Gemma3 models onto slower SDPA/eager paths and prevents them from taking the new FA2-first preference hierarchy.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member

Review: PR #4250 - Refactor attn impl replacement

Tested on B200 (SM100), torch 2.9.1, transformers 4.57.6, no FA2 installed.

Summary

The hierarchy idea (FA2 > Flex > SDPA > Eager) is solid and the refactor centralizes attention selection nicely. However there is one critical regression and two behavior changes that need attention before merging.


Bug 1 (Critical): Gemma3 VLM regresses from flex_attention to eager

The exclusion not model_type.startswith("gemma3") in both the FA2 and Flex blocks is too broad. It blocks all gemma3 variants (gemma3, gemma3_text, gemma3n, etc.) from both FA2 and flex_attention.

Old code in prefer_flex_attn_if_supported only excluded gemma3n:

if model_type in ("gpt_oss", "mllama") or str(model_type).startswith("gemma3n"):

The new code excludes all gemma3:

and not model_type.startswith("gemma3"):  # in BOTH FA2 and Flex blocks

What happens for gemma3 VLMs:

  1. determine_attention_implementation returns "sdpa" (FA2 blocked, flex blocked, but _supports_sdpa=True)
  2. But DISABLE_SDPA_MODEL_NAMES in loader.py:122-124 contains "gemma3," which sets supports_sdpa=False
  3. vision.py:625-629 catches sdpa for non-sdpa models and deletes attn_implementation
  4. Falls through to eager

Fix: In the flex_attention block (line 268), narrow startswith("gemma3") to startswith("gemma3n"). The comment already says "Gemma3N: timm vision wrappers..." -- only gemma3n has this issue, not regular gemma3. The FA2 block exclusion of all gemma3 is more debatable but defensible for now since Unsloth doesn't ship FA2 by default.

Bug 2 (Medium): gemma3n changes from eager to sdpa

Old vision.py:624-627 explicitly set default_attn_impl = "eager" for gemma3n. The PR removes this special case. Now gemma3n gets sdpa from the new function (FA2 blocked, flex blocked, but _supports_sdpa=True). gemma3n is NOT in DISABLE_SDPA_MODEL_NAMES, so sdpa sticks.

Whether gemma3n's timm-based vision towers work correctly with SDPA needs verification.

Bug 3 (Medium): llama.py new sdpa code path

Old llama.py: prefer_flex_attn_if_supported(...) or "eager" -- only flex_attention or eager.
New llama.py: determine_attention_implementation(...) -- can also return "sdpa" or "flash_attention_2".

For models excluded from FA2 and flex (e.g., mllama, gemma3_text), the function now returns "sdpa" instead of the old "eager". This is a new code path that was never exercised before in llama.py.


Benchmark Results (B200, max_steps=61, batch=2, grad_accum=3, seed=3407)

Llama-3.2-1B-Instruct (unaffected -- both use flex_attention):

Branch Attn Impl Tokens/s Peak Mem Losses [1st, 2nd, 3rd, ..., n-1, nth]
main flex_attention 7707 1.68 GB [1.540, 1.738, 1.959, ..., 1.348, 1.255]
PR flex_attention 8083 1.68 GB [1.540, 1.738, 1.959, ..., 1.348, 1.255]

Losses are bit-for-bit identical. No regression for Llama.

Gemma-3-4b-it (REGRESSION: flex_attention -> eager):

Branch Attn Impl Tokens/s Peak Mem Losses [1st, 2nd, 3rd, ..., n-1, nth]
main flex_attention 1457 5.66 GB [1.811, 1.959, 2.173, ..., 1.144, 1.085]
PR eager 2564 5.67 GB [1.808, 1.960, 2.175, ..., 1.147, 1.075]

On B200 eager happens to be faster, but on smaller GPUs (L4, A100) eager uses more memory and is slower. Losses are close but not identical (expected between attention backends). Grad norms are more stable on eager (no inf/nan seen in flex runs), which may be worth investigating separately.


Suggested Fix (one-line change)

In _utils.py line 268, change:

) and not model_type.startswith("gemma3"):

to:

) and not model_type.startswith("gemma3n"):

This restores gemma3 VLM flex_attention behavior while keeping gemma3n excluded (which is the actual problematic model type due to timm vision wrappers).

@Datta0

Datta0 commented Mar 12, 2026

Copy link
Copy Markdown
Contributor Author

I think that was my oversight wrt gemma vs gemma3n. I addressed it now :)

@danielhanchen

Copy link
Copy Markdown
Member

Updated Benchmarks (with xformers 0.0.33.post2)

Previous benchmarks had broken xformers (0.0.35 was built for torch 2.10+cu130, this env has torch 2.9.1+cu128). After installing the correct version (0.0.33.post2), xformers loads properly: FA [Xformers = 0.0.33.post2. FA2 = False].

Note on Unsloth's two attention paths:

  • _attn_implementation (config-level): controls how transformers initializes attention modules (flex/sdpa/eager) -- this is what PR refactor attn impl replacement #4250 changes
  • select_attention_backend (kernel-level): Unsloth's patched attention dispatch (flash_attn > xformers > sdpa) -- operates independently

With xformers working, Unsloth's patched layers use xformers memory-efficient attention regardless of the config-level _attn_implementation. This somewhat masks the regression on this B200 machine, but on environments without xformers, the full flex->eager regression applies.


Llama-3.2-1B-Instruct (no regression)

Branch attn_impl Tokens/s Peak Mem Losses [1st, 2nd, 3rd, ..., n-1, nth]
main flex_attention 8230 1.68 GB [1.540, 1.738, 1.957, ..., 1.351, 1.253]
PR flex_attention 8193 1.68 GB [1.540, 1.738, 1.959, ..., 1.351, 1.254]

Losses nearly identical. No regression.

Gemma-3-4b-it (REGRESSION: flex_attention -> eager)

Branch attn_impl Tokens/s Peak Mem Losses [1st, 2nd, 3rd, ..., n-1, nth]
main flex_attention 2472 5.66 GB [1.811, 1.959, 2.173, ..., 1.151, 1.092]
PR eager 2820 5.66 GB [1.808, 1.960, 2.175, ..., 1.147, 1.075]

Bug 1 confirmed: Gemma3 regresses from flex_attention to eager due to startswith("gemma3") being too broad in the flex block. On B200 with xformers handling actual compute, the eager path happens to be ~14% faster (less overhead from flex mask setup). But on smaller GPUs without xformers, eager attention is slower and uses more memory.

Losses are close but not identical (small numerical differences expected between attention backends). Grad norms on eager are more stable (no inf/nan as seen in flex runs).

Fix remains the same: Line 268 of _utils.py, change startswith("gemma3") to startswith("gemma3n").

@Datta0

Datta0 commented Mar 12, 2026

Copy link
Copy Markdown
Contributor Author

The change has been made. Perhaps codex/claude code didn't pull/check properly?

@danielhanchen

Copy link
Copy Markdown
Member

Re-review after fix (commit c230eb5)

Confirming the gemma3 vs gemma3n fix works correctly. Re-tested from scratch.

Unit Tests (16/16 pass)

Updated decision function now correctly handles all model types:

Model type No FA2 result With FA2 result Change from main?
llama flex_attention flash_attention_2 Same (no FA2) / Upgrade (FA2)
gemma3 flex_attention flash_attention_2 Same (no FA2) / Upgrade (FA2)
gemma3_text flex_attention flash_attention_2 Same (no FA2) / Upgrade (FA2)
gemma3n sdpa sdpa eager -> sdpa
mllama sdpa sdpa eager -> sdpa
falcon_h1 flex_attention flash_attention_2 eager -> flex/FA2
gpt_oss eager eager No change

Training Benchmarks (B200, torch 2.9.1, xformers 0.0.33.post2, no FA2)

Settings: max_steps=61, batch_size=2, grad_accum=3, seed=3407, alpaca-cleaned dataset.

Llama-3.2-1B-Instruct (4-bit LoRA):

Branch attn_impl Tokens/s Peak Mem Losses [1st,2nd,3rd,n-1,nth] Grad-Norms [1st,2nd,3rd,n-1,nth]
main flex_attention 8230 1.68 GB [1.540, 1.738, 1.957, 1.351, 1.253] [1.097, 1.220, 1.724, 0.757, 0.725]
PR (updated) flex_attention 8688 1.68 GB [1.540, 1.738, 1.961, 1.350, 1.254] [1.097, 1.220, 1.725, 0.758, 0.725]

No regression. Losses nearly identical.

Gemma-3-4b-it (4-bit LoRA):

Branch attn_impl Tokens/s Peak Mem Losses [1st,2nd,3rd,n-1,nth] Grad-Norms [1st,2nd,3rd,n-1,nth]
main flex_attention 2472 5.66 GB [1.811, 1.959, 2.173, 1.151, 1.092] [3.732, 3.750, NaN, 0.760, 0.727]
PR (updated) flex_attention 2403 5.66 GB [1.811, 1.959, 2.173, 1.153, 1.093] [3.732, 3.750, NaN, 0.819, 0.750]

Bug 1 is fixed. Gemma3 now correctly gets flex_attention (was eager before the fix). Losses essentially identical to main.

Remaining minor issues

  1. Stale comment (line 257): Comment says "GPT-OSS, Mllama and Gemma3 use eager/sdpa attention..." but code now only excludes gemma3n (not all gemma3). Should say "Gemma3N".

  2. gemma3n: eager -> sdpa: Old code in vision.py explicitly set default_attn_impl = "eager" for gemma3n. PR removes this, so gemma3n now gets sdpa. The old comment says only flex was problematic (timm vision towers), not SDPA, so this should be safe -- but worth a quick sanity check if possible.

  3. mllama / falcon_h1: eager -> sdpa: Old llama.py only had flex or eager. New function can return sdpa. Both models support SDPA, so this is likely an improvement (sdpa is faster than eager). Just flagging the behavioral change.

  4. SDPA warning always prints: Old vision.py gated the SDPA-unsupported warning on UNSLOTH_ENABLE_FLEX_ATTENTION == "0". PR removes that gate, so the warning prints unconditionally. Minor noise change.

  5. Config double-stamping: determine_attention_implementation stamps config at every return path. vision.py:772 re-stamps afterward. Redundant but harmless.

None of these are blockers. The critical gemma3 regression (Bug 1) is resolved.

@Datta0
Datta0 force-pushed the flexattn_refactor branch from 5cab625 to c4f0105 Compare March 13, 2026 04:50
@Datta0
Datta0 force-pushed the flexattn_refactor branch from 79e6796 to 0bfe7e3 Compare March 13, 2026 04:50

@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: 3272ef08b4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread unsloth/models/_utils.py Resolved
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@Datta0
Datta0 force-pushed the flexattn_refactor branch from 81941aa to 1185188 Compare March 31, 2026 15:11
@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.
Repo admins can enable using credits for code reviews in their settings.

@Datta0
Datta0 force-pushed the flexattn_refactor branch from 1185188 to 0bfe7e3 Compare March 31, 2026 15:12
@Datta0

Datta0 commented Mar 31, 2026

Copy link
Copy Markdown
Contributor Author

Closing in favor of #4734

@danielhanchen danielhanchen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thank you for the PR! The goal of this PR is to centralize and improve the attention implementation selection by introducing a clear preference hierarchy (FA2 > Flex > SDPA > Eager). As a summary, this PR replaces prefer_flex_attn_if_supported with a new determine_attention_implementation function that selects the optimal attention backend based on model capabilities, and wires it into both the llama and vision loading paths.

The hierarchy idea is solid and the refactor is a clear improvement over the flex-only approach. However, there are a few regressions introduced that need to be addressed. I ran multiple independent reviews and separate behavioral analysis. Here is the summary:

Reviewers Severity Finding
10/12 High Missing nemotron_h exclusion -- main added nemotron_h to the flex exclusion list (raises NotImplementedError). This PR drops it from both the FA2 and flex blocks.
10/12 High Missing attention_dropout check -- main added a guard that skips flex_attention when attention_dropout > 0 (flex does not support dropout, transformers raises ValueError). This PR drops that check.
8/12 High Gemma3N vision regression -- Old code explicitly set default_attn_impl = "eager" for gemma3n in vision.py. PR removes this override, so gemma3n now gets sdpa via the hierarchy.
8/12 Medium Unmapped vision models regress from sdpa to eager -- When model_class is None (remote-code or unmapped configs), determine_attention_implementation(None, config) returns eager instead of the previous sdpa default.
2/12 Low SDPA warning default changed -- env var default changed from "0" to "1", suppressing the SDPA warning by default.

I pushed fixes to flexattn_refactor_fixed branch on the main repo. The key changes:

  1. Add nemotron_h to FA2 and flex exclusion lists
  2. Add attention_dropout > 0 check before selecting flex
  3. Restore gemma3n eager override in vision.py
  4. Preserve sdpa fallback for unmapped vision configs
  5. Extract _set_attn_impl helper to reduce boilerplate
  6. Restore original SDPA warning default

Concrete suggestions in inline comments.

Comment thread unsloth/models/_utils.py
if model_type in ("gpt_oss", "mllama") or str(model_type).startswith("gemma3n"):
return None
# 1. Flash Attention 2
if HAS_FLASH_ATTENTION and model_type not in ("gpt_oss", "mllama") and not model_type.startswith("gemma3n"):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[10/12 reviewers] Missing nemotron_h exclusion. Main branch added nemotron_h to the flex exclusion list because NemotronH raises NotImplementedError from transformers. This PR drops it.

Suggested change
if HAS_FLASH_ATTENTION and model_type not in ("gpt_oss", "mllama") and not model_type.startswith("gemma3n"):
if HAS_FLASH_ATTENTION and model_type not in ("gpt_oss", "mllama", "nemotron_h") and not model_type.startswith("gemma3n"):

Comment thread unsloth/models/_utils.py
# decode q_len=1, causing ValueError. Needs transformers update.
# Gemma3N: timm vision wrappers (eg Gemma3nVisionConfig) do not
# support flex_attention.
if model_type not in ("gpt_oss", "mllama") and not model_type.startswith("gemma3n"):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[10/12 reviewers] Two issues here:

  1. Missing attention_dropout > 0 guard. Main branch added this because flex attention does not support dropout (transformers raises ValueError). This check was dropped during the refactor.

  2. Missing nemotron_h in the flex exclusion list.

Suggested change
if model_type not in ("gpt_oss", "mllama") and not model_type.startswith("gemma3n"):
attention_dropout = getattr(config, "attention_dropout", 0) or 0
is_excluded = (
model_type in ("gpt_oss", "mllama", "nemotron_h")
or model_type.startswith("gemma3n")
)
if attention_dropout == 0 and not is_excluded:

Comment thread unsloth/models/vision.py
model_class = None
flex_attn_impl = prefer_flex_attn_if_supported(model_class, auto_config)

attn_impl = determine_attention_implementation(model_class, auto_config)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[8/12 reviewers] Gemma3N vision regression and unmapped model fallback. The old code explicitly set default_attn_impl = "eager" for gemma3n because timm-based vision towers have issues with non-eager attention. This PR removes that override.

Also, when model_class is None (unmapped/remote-code), determine_attention_implementation(None, config) returns eager instead of the previous sdpa default.

Suggested change
attn_impl = determine_attention_implementation(model_class, auto_config)
model_type = str(getattr(auto_config, "model_type", "")).lower()
if model_type.startswith("gemma3n"):
# Gemma3N variants use timm-based vision towers which do not support
# flex_attention. Preserve the old eager default.
attn_impl = "eager"
elif model_class is None and supports_sdpa:
# When model_class cannot be resolved (remote-code or unmapped
# configs), preserve the old sdpa default.
attn_impl = "sdpa"
else:
attn_impl = determine_attention_implementation(model_class, auto_config)

Comment thread unsloth/models/vision.py
kwargs["attn_implementation"] = attn_impl
if not supports_sdpa and kwargs.get("attn_implementation") == "sdpa":
if os.environ.get("UNSLOTH_ENABLE_FLEX_ATTENTION", "0") == "0":
if os.environ.get("UNSLOTH_ENABLE_FLEX_ATTENTION", "1") == "0":

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[2/12 reviewers] The default value changed from "0" to "1". When the env var is unset, the old code printed the SDPA warning; the new code suppresses it.

Suggested change
if os.environ.get("UNSLOTH_ENABLE_FLEX_ATTENTION", "1") == "0":
if os.environ.get("UNSLOTH_ENABLE_FLEX_ATTENTION", "0") == "0":

@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@danielhanchen

Copy link
Copy Markdown
Member

I pushed the fixes to flexattn_refactor_fixed on the main repo. The branch is based on your latest commit (0bfe7e3d) with all the fixes applied on top.

The fixes address:

  1. nemotron_h exclusion -- added to both FA2 and flex exclusion lists (from main's 52f9c305)
  2. attention_dropout check -- restored the attention_dropout > 0 guard for flex (from main's 74ddef14)
  3. gemma3n eager -- restored explicit eager override in vision.py for gemma3n timm vision towers
  4. unmapped model sdpa -- preserved the old sdpa default for remote-code/unmapped vision configs when model_class=None
  5. _set_attn_impl helper -- extracted to reduce config-stamping boilerplate
  6. SDPA warning default -- restored "0" default so the warning prints when env var is unset
  7. Consistent config stamping -- vision.py fallback paths now also stamp auto_config._attn_implementation

All 27 unit tests pass. You can cherry-pick from that branch or I can create a separate PR against yours.

@danielhanchen

Copy link
Copy Markdown
Member

Updated flexattn_refactor_fixed with one more fix: config re-stamping to eager when the supports_sdpa=False guard fires in vision.py. All 54 unit tests pass.

Full diff of the fixes I applied on top of the PR:
0bfe7e3...flexattn_refactor_fixed

The branch is ready to be cherry-picked or used as-is. The changes are minimal and focused only on the attention selection logic -- no unrelated changes to version strings, xformers guards, or monkey patches.

@Datta0

Datta0 commented Mar 31, 2026

Copy link
Copy Markdown
Contributor Author

I just took a glance at the said branch

model_type = str(getattr(auto_config, "model_type", "")).lower()
        if model_type.startswith("gemma3n"):
            # Gemma3N variants use timm-based vision towers which do not support
            # flex_attention. The old code defaulted gemma3n to eager; preserve
            # that behavior rather than letting the hierarchy pick sdpa.
            attn_impl = _set_attn_impl(auto_config, "eager")
        elif model_class is None and supports_sdpa:
            # When model_class cannot be resolved (remote-code or unmapped
            # configs), the old code defaulted to sdpa. Preserve that fallback
            # instead of falling through to eager.
            attn_impl = _set_attn_impl(auto_config, "sdpa")
        else:
            attn_impl = determine_attention_implementation(model_class, auto_config)

Shouldn't this (Currently in vision.py) be done in the same determine_attn_impl function?

Also as mentioned above, I closed the PR and opened a newer cleaner one at #4734

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.

2 participants