Fix Gemma3 Vision + Gemma3N audio inference on transformers 5.x#492
Fix Gemma3 Vision + Gemma3N audio inference on transformers 5.x#492danielhanchen wants to merge 2 commits intomainfrom
Conversation
Upstream bug in modeling_gemma3n.py: Gemma3nModel.forward overwrites audio_features with pooler_output (a tensor) before extracting audio_mel_mask from the dataclass, causing AttributeError. Patch get_audio_features to attach audio_mel_mask onto the pooler_output tensor so it survives the variable reassignment.
When using float16 dtype with Gemma3 (FORCE_FLOAT32 path), the model loads in bfloat16 but inference uses float16 autocast. This creates a dtype chain where RoPE returns bfloat16 cos/sin, attention projections produce float16 q/k/v under autocast, and apply_rotary_pos_emb promotes float16 * bfloat16 to float32. The result: float32 keys, float16 values, and flex_attention rejecting mismatched q/k/v dtypes. Two fixes: 1. compiler.py: Add fix_apply_rotary_pos_emb_mixed_dtype() source transformation that inserts dtype casting (cos/sin to match q dtype) inside apply_rotary_pos_emb during compilation. Applied in both create_standalone_class() and create_new_function() to cover all compiled code paths. 2. misc.py: Add patch_static_cache_dtype_mismatch() that patches StaticLayer and StaticSlidingWindowLayer to handle key/value dtype mismatches during cache initialization and updates. Uses lower precision dtype for cache allocation and casts incoming states to match cache dtype. Only activates when UNSLOTH_FORCE_FLOAT32=1.
Summary of ChangesHello @danielhanchen, 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 delivers crucial fixes to enhance the stability and correctness of Gemma3 Vision and Gemma3N Conversational audio inference within the transformers 5.x ecosystem. It addresses complex data type inconsistencies that led to crashes, particularly when using Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
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
|
| source, | ||
| ) | ||
| return source | ||
| pass |
| if hasattr(audio_outputs, "audio_mel_mask") and audio_outputs.audio_mel_mask is not None: | ||
| audio_outputs.pooler_output.audio_mel_mask = audio_outputs.audio_mel_mask | ||
| return audio_outputs | ||
| pass |
| return audio_outputs | ||
| pass | ||
| patch_function(transformers.models.gemma3n.modeling_gemma3n.Gemma3nModel, "get_audio_features", get_audio_features, match_level="relaxed") | ||
| pass |
| return _orig_sw_update(self, key_states, value_states, cache_kwargs) | ||
| patched_sw_update._unsloth_patched = True | ||
| StaticSlidingWindowLayer.update = patched_sw_update | ||
| pass |
| pass | ||
| TEMPORARY_PATCHES.append(patch_Gemma3nModel_get_placeholder_mask) | ||
|
|
||
| def patch_Gemma3nModel_get_audio_features(): |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9da41f099a
ℹ️ 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".
| # sees is_initialized=True and uses our casted states | ||
| if key_states.dtype != value_states.dtype: | ||
| target = _resolve_dtype(key_states, value_states) | ||
| self.lazy_initialization(key_states.to(target), value_states.to(target)) |
There was a problem hiding this comment.
Keep lazy_initialization call compatible across transformers
This wrapper now calls lazy_initialization with both key and value tensors, but in transformers 4.x (StaticLayer/StaticSlidingWindowLayer) the method only accepts key_states; with UNSLOTH_FORCE_FLOAT32=1, the first cache update raises TypeError before inference can proceed on static-cache paths. Because this patch has no version/arity guard, it introduces a runtime regression for 4.x users (the same issue is repeated in patched_sw_update).
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Code Review
This pull request introduces several important fixes for Gemma3 Vision and Gemma3N audio inference on transformers 5.x, addressing crashes related to data type mismatches and an upstream bug. The changes are well-targeted and include:
- A fix for mixed-precision RoPE calculations in
compiler.py. - A patch for static cache data type mismatches in
temporary_patches/misc.py. - A workaround for an audio feature bug in
temporary_patches/gemma3n.py.
The code is generally of high quality. I've included one suggestion to improve maintainability by refactoring duplicated code.
| def patched_update(self, key_states, value_states, cache_kwargs=None): | ||
| if not self.is_initialized: | ||
| # Eagerly initialize with consistent dtype so the original update | ||
| # sees is_initialized=True and uses our casted states | ||
| if key_states.dtype != value_states.dtype: | ||
| target = _resolve_dtype(key_states, value_states) | ||
| self.lazy_initialization(key_states.to(target), value_states.to(target)) | ||
| else: | ||
| self.lazy_initialization(key_states, value_states) | ||
| # Cast incoming states to match the cache dtype | ||
| if key_states.dtype != self.keys.dtype: | ||
| key_states = key_states.to(self.keys.dtype) | ||
| if value_states.dtype != self.values.dtype: | ||
| value_states = value_states.to(self.values.dtype) | ||
| return _orig_update(self, key_states, value_states, cache_kwargs) | ||
| patched_update._unsloth_patched = True | ||
| StaticLayer.update = patched_update | ||
|
|
||
| # StaticSlidingWindowLayer has its own update method (not inherited) | ||
| _orig_sw_update = StaticSlidingWindowLayer.update | ||
| def patched_sw_update(self, key_states, value_states, cache_kwargs=None): | ||
| if not self.is_initialized: | ||
| if key_states.dtype != value_states.dtype: | ||
| target = _resolve_dtype(key_states, value_states) | ||
| self.lazy_initialization(key_states.to(target), value_states.to(target)) | ||
| else: | ||
| self.lazy_initialization(key_states, value_states) | ||
| if key_states.dtype != self.keys.dtype: | ||
| key_states = key_states.to(self.keys.dtype) | ||
| if value_states.dtype != self.values.dtype: | ||
| value_states = value_states.to(self.values.dtype) | ||
| return _orig_sw_update(self, key_states, value_states, cache_kwargs) | ||
| patched_sw_update._unsloth_patched = True | ||
| StaticSlidingWindowLayer.update = patched_sw_update |
There was a problem hiding this comment.
The logic within patched_update and patched_sw_update is identical. To improve maintainability and reduce code duplication, you can extract the common logic into a helper function. This will make the code cleaner and easier to manage in the future.
def _patched_update_logic(self, key_states, value_states):
if not self.is_initialized:
# Eagerly initialize with consistent dtype so the original update
# sees is_initialized=True and uses our casted states
if key_states.dtype != value_states.dtype:
target = _resolve_dtype(key_states, value_states)
self.lazy_initialization(key_states.to(target), value_states.to(target))
else:
self.lazy_initialization(key_states, value_states)
# Cast incoming states to match the cache dtype
if key_states.dtype != self.keys.dtype:
key_states = key_states.to(self.keys.dtype)
if value_states.dtype != self.values.dtype:
value_states = value_states.to(self.values.dtype)
return key_states, value_states
# Patch StaticLayer.update
_orig_update = StaticLayer.update
def patched_update(self, key_states, value_states, cache_kwargs=None):
key_states, value_states = _patched_update_logic(self, key_states, value_states)
return _orig_update(self, key_states, value_states, cache_kwargs)
patched_update._unsloth_patched = True
StaticLayer.update = patched_update
# StaticSlidingWindowLayer has its own update method (not inherited)
_orig_sw_update = StaticSlidingWindowLayer.update
def patched_sw_update(self, key_states, value_states, cache_kwargs=None):
key_states, value_states = _patched_update_logic(self, key_states, value_states)
return _orig_sw_update(self, key_states, value_states, cache_kwargs)
patched_sw_update._unsloth_patched = True
StaticSlidingWindowLayer.update = patched_sw_update| def patch_static_cache_dtype_mismatch(): | ||
| """Fix StaticLayer/StaticSlidingWindowLayer index_copy_ dtype mismatch. | ||
|
|
||
| When using float16 autocast on a bfloat16 model (FORCE_FLOAT32 path for Gemma3), |
There was a problem hiding this comment.
This was effecting gpt_oss
That is why I had to do this conversion
Once this lands, can we explore removing that ?
Summary
index_copy_dtype mismatch + flex_attention dtype validation) when usingdtype=torch.float16on transformers 5.xAttributeError: 'Tensor' object has no attribute 'audio_mel_mask') on transformers 5.x (upstream transformers bug)Changes
1.
compiler.py-- RoPE mixed dtype fixWhen
FORCE_FLOAT32=1(Gemma3 float16 path), the model loads in bfloat16 but inference uses float16 autocast. RoPE returns bfloat16 cos/sin (from hidden_states dtype), attention projections produce float16 q/k/v (under autocast), andapply_rotary_pos_embpromotesfloat16 * bfloat16 = float32. This breaks flex_attention (requires matching q/k/v dtypes) and causes cache dtype mismatches.Adds
fix_apply_rotary_pos_emb_mixed_dtype()source transformation that insertscos/sindtype casting to matchqdtype insideapply_rotary_pos_embduring compilation. Applied in bothcreate_standalone_class()andcreate_new_function().2.
temporary_patches/misc.py-- Static cache dtype mismatchAdds
patch_static_cache_dtype_mismatch()that patchesStaticLayerandStaticSlidingWindowLayerto handle key/value dtype mismatches during cache initialization and updates. Uses lower precision dtype for cache allocation and casts incoming states to match cache dtype. Belt-and-suspenders defense for the FORCE_FLOAT32 path.3.
temporary_patches/gemma3n.py-- Audio mel mask fixUpstream transformers bug in
modeling_gemma3n.py:2114-2115:audio_features = audio_features.pooler_outputoverwrites the dataclass with a raw Tensor before.audio_mel_maskis extracted. Patchesget_audio_featuresto attachaudio_mel_maskonto thepooler_outputtensor so it survives the variable reassignment.Test plan
dtype=torch.float16on transformers 5.1.0 -- PASS