-
Notifications
You must be signed in to change notification settings - Fork 95
Add unified arch for gemma4 #305
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
3838c80
gemma4 unified
neilmehta24 12750c7
wire in per layers inputs
neilmehta24 bdde0af
refactor
neilmehta24 476c740
inline
neilmehta24 21750de
gemma4 unified tests
neilmehta24 fbaed17
refactor tests
neilmehta24 d1f3c64
simplify
neilmehta24 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| """ | ||
| Patch Gemma 4 so unified multimodal prompts reuse the full prompt's masked | ||
| per-layer-input token ids during chunked prefill. | ||
| """ | ||
|
|
||
| from typing import Any, Optional | ||
|
|
||
| import mlx.core as mx | ||
|
|
||
| from mlx_lm.models.gemma4_text import Gemma4TextModel | ||
|
|
||
| # Stable alias to the pristine mlx-lm class captured before apply_patches() | ||
| # mutates mlx_lm.models.gemma4_text in place. | ||
| OriginalGemma4TextModel = Gemma4TextModel | ||
|
|
||
|
|
||
| class PatchedGemma4TextModel(OriginalGemma4TextModel): | ||
| def __init__(self, config): | ||
| super().__init__(config) | ||
| self.prompt_per_layer_input_ids = None | ||
|
|
||
| def __call__( | ||
| self, | ||
| inputs: mx.array = None, | ||
| cache=None, | ||
| input_embeddings: Optional[mx.array] = None, | ||
| per_layer_inputs: Optional[mx.array] = None, | ||
| ): | ||
| if ( | ||
| per_layer_inputs is None | ||
| and input_embeddings is not None | ||
| and self.prompt_per_layer_input_ids is not None | ||
| ): | ||
| prompt_per_layer_input_ids = self.prompt_per_layer_input_ids | ||
| if prompt_per_layer_input_ids.shape[1] != input_embeddings.shape[-2]: | ||
| start = self._cache_offset(cache) | ||
| target_len = input_embeddings.shape[-2] | ||
| prompt_per_layer_input_ids = prompt_per_layer_input_ids[ | ||
| :, start : start + target_len | ||
| ] | ||
| per_layer_inputs = self._get_per_layer_inputs(prompt_per_layer_input_ids) | ||
|
|
||
| return super().__call__( | ||
| inputs, | ||
| cache=cache, | ||
| input_embeddings=input_embeddings, | ||
| per_layer_inputs=per_layer_inputs, | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def _cache_offset(cache: Optional[Any]) -> int: | ||
| for layer_cache in cache or []: | ||
| offset = getattr(layer_cache, "offset", None) | ||
| if offset is None: | ||
| continue | ||
| if isinstance(offset, int): | ||
| return offset | ||
| if isinstance(offset, mx.array) and offset.ndim == 0: | ||
| return offset.item() | ||
| if isinstance(offset, mx.array): | ||
| return offset[0].item() | ||
| return 0 | ||
|
|
||
|
|
||
| def apply_patches(): | ||
| import mlx_lm.models.gemma4_text | ||
|
|
||
| mlx_lm.models.gemma4_text.Gemma4TextModel = PatchedGemma4TextModel |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| import logging | ||
| from pathlib import Path | ||
|
|
||
| from mlx import nn | ||
| import mlx.core as mx | ||
|
|
||
| from mlx_vlm.models.gemma4 import ( | ||
| ModelConfig as Gemma4ModelConfig, | ||
| TextConfig as Gemma4TextConfig, | ||
| VisionConfig as Gemma4VisionConfig, | ||
| VisionModel as Gemma4VisionTower, | ||
| ) | ||
| from mlx_vlm.models.gemma4.gemma4 import MultimodalEmbedder, masked_scatter | ||
| from mlx_vlm.utils import load_processor, sanitize_weights | ||
|
|
||
| from mlx_engine.model_kit.vision_add_ons.base import BaseVisionAddOn | ||
| from mlx_engine.model_kit.vision_add_ons.load_utils import ( | ||
| load_and_filter_weights, | ||
| load_and_parse_config, | ||
| maybe_apply_quantization, | ||
| prepare_components, | ||
| ) | ||
| from mlx_engine.model_kit.vision_add_ons.process_prompt_with_images import ( | ||
| common_process_prompt_with_images, | ||
| ) | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class Gemma4VisionComponents(nn.Module): | ||
| def __init__(self, vision_tower: nn.Module, embed_vision: nn.Module): | ||
| super().__init__() | ||
| self.vision_tower = vision_tower | ||
| self.embed_vision = embed_vision | ||
|
|
||
|
|
||
| class Gemma4VisionAddOn(BaseVisionAddOn): | ||
| """ | ||
| Vision add-on for Gemma4 models. | ||
|
|
||
| Gemma4's text model still applies `embed_scale` when `input_embeddings` are | ||
| provided, so image features must be pre-divided by that scale before being | ||
| scattered into the mixed prompt embeddings. | ||
| """ | ||
|
|
||
| def __init__(self, model_path: Path): | ||
| super().__init__() | ||
|
|
||
| config, config_dict = load_and_parse_config( | ||
| model_path=model_path, | ||
| model_config_class=Gemma4ModelConfig, | ||
| vision_config_class=Gemma4VisionConfig, | ||
| text_config_class=Gemma4TextConfig, | ||
| ) | ||
|
|
||
| components = Gemma4VisionComponents( | ||
| vision_tower=Gemma4VisionTower(config.vision_config), | ||
| embed_vision=MultimodalEmbedder( | ||
| embedding_dim=config.vision_config.hidden_size, | ||
| text_hidden_size=config.text_config.hidden_size, | ||
| eps=config.vision_config.rms_norm_eps, | ||
| ), | ||
| ) | ||
|
|
||
| processor = load_processor(model_path=model_path, add_detokenizer=True) | ||
| vision_weights = load_and_filter_weights(model_path, components) | ||
| vision_weights = sanitize_weights( | ||
| components.vision_tower.__class__, vision_weights, config.vision_config | ||
| ) | ||
| maybe_apply_quantization(components, config_dict, vision_weights) | ||
| prepare_components(components, vision_weights) | ||
|
|
||
| logger.info(f"Vision add-on loaded successfully from {model_path}") | ||
|
|
||
| self.vision_tower = components.vision_tower | ||
| self.embed_vision = components.embed_vision | ||
| self.config = config | ||
| self.processor = processor | ||
|
|
||
| def compute_embeddings( | ||
| self, | ||
| text_model: nn.Module, | ||
| prompt_tokens: mx.array, | ||
| images_b64: list[str], | ||
| max_size: tuple[int, int] | None, | ||
| ) -> tuple[mx.array, mx.array]: | ||
| """Compute input_ids and embeddings for text with images.""" | ||
| input_ids, pixel_values, _, _ = common_process_prompt_with_images( | ||
| prompt_tokens=prompt_tokens, | ||
| images_b64=images_b64, | ||
| processor=self.processor, | ||
| config=self.config, | ||
| max_size=max_size, | ||
| ) | ||
|
|
||
| language_model = text_model.language_model.model | ||
| input_embeddings = language_model.embed_tokens(input_ids) | ||
|
|
||
| image_features = self.vision_tower(pixel_values) | ||
| image_features = self.embed_vision(image_features).astype( | ||
| input_embeddings.dtype | ||
| ) | ||
|
|
||
| # Gemma4TextModel applies embed_scale even when input_embeddings are provided. | ||
| scaled_image_features = image_features / language_model.embed_scale | ||
|
|
||
| image_mask = input_ids == self.config.image_token_id | ||
| image_mask_expanded = mx.expand_dims(image_mask, -1) | ||
| image_mask_expanded = mx.broadcast_to( | ||
| image_mask_expanded, input_embeddings.shape | ||
| ) | ||
|
|
||
| final_inputs_embeds = masked_scatter( | ||
| input_embeddings, image_mask_expanded, scaled_image_features | ||
| ) | ||
|
|
||
| if language_model.hidden_size_per_layer_input: | ||
| masked_input_ids = mx.where( | ||
| input_ids == self.config.image_token_id, 0, input_ids | ||
| ) | ||
| language_model.prompt_per_layer_input_ids = mx.where( | ||
| input_ids == self.config.audio_token_id, 0, masked_input_ids | ||
| ) | ||
|
|
||
| return input_ids.squeeze(0), final_inputs_embeds.squeeze(0) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Did you confirm the logits are the same for both text-only and vision prompts before and after the patch? Consider adding tests to
test_patched_models.pyin line with the Qwen 3.5 heavy tests to verify.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I verified that the logits matched for text-only work, and that the logits are close-enough within a tolerance for image+text work. I added a test for each of these cases.