Repository navigation
Conversation
Summary of ChangesHello, 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
Changelog
Using Gemini Code AssistThe 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
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 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
|
There was a problem hiding this comment.
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.
| 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: |
There was a problem hiding this comment.
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")There was a problem hiding this comment.
💡 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".
| pass | ||
|
|
||
| # 3. SDPA | ||
| if model_class is not None and getattr(model_class, "_supports_sdpa", False): |
There was a problem hiding this comment.
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 👍 / 👎.
| if ( | ||
| HAS_FLASH_ATTENTION | ||
| and model_type not in ("gpt_oss", "mllama") | ||
| and not model_type.startswith("gemma3") |
There was a problem hiding this comment.
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 👍 / 👎.
Review: PR #4250 - Refactor attn impl replacementTested on B200 (SM100), torch 2.9.1, transformers 4.57.6, no FA2 installed. SummaryThe 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
|
| 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).
|
I think that was my oversight wrt gemma vs gemma3n. I addressed it now :) |
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: Note on Unsloth's two attention paths:
With xformers working, Unsloth's patched layers use xformers memory-efficient attention regardless of the config-level Llama-3.2-1B-Instruct (no regression)
Losses nearly identical. No regression. Gemma-3-4b-it (REGRESSION: flex_attention -> eager)
Bug 1 confirmed: Gemma3 regresses from 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 |
|
The change has been made. Perhaps codex/claude code didn't pull/check properly? |
Re-review after fix (commit c230eb5)Confirming the Unit Tests (16/16 pass)Updated decision function now correctly handles all model types:
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):
No regression. Losses nearly identical. Gemma-3-4b-it (4-bit LoRA):
Bug 1 is fixed. Gemma3 now correctly gets Remaining minor issues
None of these are blockers. The critical gemma3 regression (Bug 1) is resolved. |
5cab625 to
c4f0105
Compare
79e6796 to
0bfe7e3
Compare
There was a problem hiding this comment.
💡 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".
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
81941aa to
1185188
Compare
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
1185188 to
0bfe7e3
Compare
|
Closing in favor of #4734 |
danielhanchen
left a comment
There was a problem hiding this comment.
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:
- Add
nemotron_hto FA2 and flex exclusion lists - Add
attention_dropout > 0check before selecting flex - Restore gemma3n eager override in vision.py
- Preserve sdpa fallback for unmapped vision configs
- Extract
_set_attn_implhelper to reduce boilerplate - Restore original SDPA warning default
Concrete suggestions in inline comments.
| 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"): |
There was a problem hiding this comment.
[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.
| 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"): |
| # 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"): |
There was a problem hiding this comment.
[10/12 reviewers] Two issues here:
-
Missing
attention_dropout > 0guard. Main branch added this because flex attention does not support dropout (transformers raisesValueError). This check was dropped during the refactor. -
Missing
nemotron_hin the flex exclusion list.
| 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: |
| model_class = None | ||
| flex_attn_impl = prefer_flex_attn_if_supported(model_class, auto_config) | ||
|
|
||
| attn_impl = determine_attention_implementation(model_class, auto_config) |
There was a problem hiding this comment.
[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.
| 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) |
| 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": |
There was a problem hiding this comment.
[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.
| if os.environ.get("UNSLOTH_ENABLE_FLEX_ATTENTION", "1") == "0": | |
| if os.environ.get("UNSLOTH_ENABLE_FLEX_ATTENTION", "0") == "0": |
|
/gemini review |
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
|
I pushed the fixes to The fixes address:
All 27 unit tests pass. You can cherry-pick from that branch or I can create a separate PR against yours. |
|
Updated Full diff of the fixes I applied on top of the PR: 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. |
|
I just took a glance at the said branch 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 |
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