| 1 | import glob |
| 2 | import inspect |
| 3 | import json |
| 4 | from dataclasses import dataclass |
| 5 | from pathlib import Path |
| 6 | from typing import Optional |
| 7 | |
| 8 | import mlx.core as mx |
| 9 | import mlx.nn as nn |
| 10 | import numpy as np |
| 11 | from huggingface_hub import snapshot_download |
| 12 | |
| 13 | from .language import LanguageModel, TextConfig |
| 14 | from .vision import VisionConfig, VisionModel |
| 15 | |
| 16 | |
| 17 | @dataclass |
| 18 | class ModelConfig: |
| 19 | text_config: TextConfig |
| 20 | vision_config: VisionConfig |
| 21 | model_type: str |
| 22 | ignore_index: int = -100 |
| 23 | image_token_index: int = 10 |
| 24 | vision_feature_select_strategy: str = "full" |
| 25 | vision_feature_layer: int = -1 |
| 26 | vocab_size: int = 32000 |
| 27 | |
| 28 | @classmethod |
| 29 | def from_dict(cls, params): |
| 30 | return cls( |
| 31 | **{ |
| 32 | k: v |
| 33 | for k, v in params.items() |
| 34 | if k in inspect.signature(cls).parameters |
| 35 | } |
| 36 | ) |
| 37 | |
| 38 | |
| 39 | class LlavaMultiModalProjector(nn.Module): |
| 40 | def __init__(self, config: ModelConfig): |
| 41 | super().__init__() |
| 42 | self.linear_1 = nn.Linear( |
| 43 | config.vision_config.hidden_size, config.text_config.hidden_size, bias=True |
| 44 | ) |
| 45 | self.gelu = nn.GELU() |
| 46 | self.linear_2 = nn.Linear( |
| 47 | config.text_config.hidden_size, config.text_config.hidden_size, bias=True |
| 48 | ) |
| 49 | |
| 50 | def __call__(self, x: mx.array) -> mx.array: |
| 51 | x = self.linear_1(x) |
| 52 | x = self.gelu(x) |
| 53 | x = self.linear_2(x) |
| 54 | return x |
| 55 | |
| 56 | |
| 57 | class Model(nn.Module): |
| 58 | def __init__(self, config: ModelConfig): |
| 59 | super().__init__() |
| 60 | self.config = config |
| 61 | self.vision_tower = VisionModel(config.vision_config) |
| 62 | self.language_model = LanguageModel(config.text_config) |
| 63 | self.multi_modal_projector = LlavaMultiModalProjector(config) |
| 64 | self.vision_feature_layer = config.vision_feature_layer |
| 65 | self.vision_feature_select_strategy = config.vision_feature_select_strategy |
| 66 | |
| 67 | def get_input_embeddings( |
| 68 | self, |
| 69 | input_ids: Optional[mx.array] = None, |
| 70 | pixel_values: Optional[mx.array] = None, |
| 71 | ): |
| 72 | if pixel_values is None: |
| 73 | return self.language_model(input_ids) |
| 74 | |
| 75 | # Get the input embeddings from the language model |
| 76 | inputs_embeds = self.language_model.model.embed_tokens(input_ids) |
| 77 | |
| 78 | # Get number of images |
| 79 | num_images = len(pixel_values[0]) |
| 80 | |
| 81 | # Get the ouptut hidden states from the vision model |
| 82 | if isinstance(pixel_values, list): |
| 83 | if input_ids.shape[0] == 1: # Batch size is 1 |
| 84 | pixel_values = mx.concatenate( |
| 85 | [mx.array(pv) for pv in pixel_values[0]], axis=1 |
| 86 | )[None, ...] |
| 87 | else: # Batch size is greater than 1 |
| 88 | pixel_values = mx.concatenate( |
| 89 | [mx.array(pv) for pv in pixel_values], axis=0 |
| 90 | ) |
| 91 | if pixel_values.ndim == 3: |
| 92 | pixel_values = pixel_values[None, ...] |
| 93 | |
| 94 | pixel_values = mx.split(pixel_values, num_images, axis=2) |
| 95 | |
| 96 | # Pass pixel_values as list of images, as each image is individually run through conv2d and position encoding |
| 97 | # Reference code from transformers: https://github.com/huggingface/transformers/blob/main/src/transformers/models/pixtral/modeling_pixtral.py#L479C9-L479C21 |
| 98 | # and mistral_inference: https://github.com/mistralai/mistral-inference/blob/main/src/mistral_inference/vision_encoder.py#L85 |
| 99 | *_, hidden_states = self.vision_tower( |
| 100 | [pv.transpose(0, 2, 3, 1) for pv in pixel_values], output_hidden_states=True |
| 101 | ) |
| 102 | # Select the hidden states from the desired layer |
| 103 | selected_image_feature = hidden_states[self.vision_feature_layer] |
| 104 | |
| 105 | # Pass image features through the multi-modal projector |
| 106 | image_features = self.multi_modal_projector(selected_image_feature) |
| 107 | |
| 108 | # Insert special image tokens in the input_ids |
| 109 | final_inputs_embeds = self._merge_input_ids_with_image_features( |
| 110 | image_features, inputs_embeds, input_ids |
| 111 | ) |
| 112 | return final_inputs_embeds |
| 113 | |
| 114 | def _merge_input_ids_with_image_features( |
| 115 | self, image_features, inputs_embeds, input_ids |
| 116 | ): |
| 117 | image_token_index = self.config.image_token_index |
| 118 | num_images, num_image_patches, embed_dim = image_features.shape |
| 119 | |
| 120 | # Positions of <image> tokens in input_ids, assuming batch size is 1 |
| 121 | image_positions = np.where(input_ids[0] == image_token_index)[0].tolist() |
| 122 | |
| 123 | text_segments = [] |
| 124 | start_idx = 0 |
| 125 | |
| 126 | for position in image_positions: |
| 127 | text_segments.append(inputs_embeds[:, start_idx:position]) |
| 128 | start_idx = position + 1 |
| 129 | |
| 130 | # Split image features into separate embeddings for each image |
| 131 | image_embeddings = mx.split(image_features, num_image_patches, axis=1) |
| 132 | final_embeddings = [v for p in zip(text_segments, image_embeddings) for v in p] |
| 133 | final_embeddings += [inputs_embeds[:, start_idx:]] |
| 134 | |
| 135 | # Create a final embedding of shape |
| 136 | # (1, num_image_patches*num_images + sequence_len, embed_dim) |
| 137 | return mx.concatenate(final_embeddings, axis=1) |
| 138 | |
| 139 | def __call__( |
| 140 | self, |
| 141 | input_ids: mx.array, |
| 142 | pixel_values: mx.array, |
| 143 | mask: mx.array, |
| 144 | cache=None, |
| 145 | **kwargs, |
| 146 | ): |
| 147 | input_embddings = self.get_input_embeddings(input_ids, pixel_values) |
| 148 | logits = self.language_model( |
| 149 | input_ids, cache=cache, inputs_embeds=input_embddings |
| 150 | ) |
| 151 | return logits |
| 152 | |
| 153 | @staticmethod |
| 154 | def from_pretrained(path_or_hf_repo: str): |
| 155 | path = Path(path_or_hf_repo) |
| 156 | if not path.exists(): |
| 157 | path = Path( |
| 158 | snapshot_download( |
| 159 | repo_id=path_or_hf_repo, |
| 160 | allow_patterns=[ |
| 161 | "*.json", |
| 162 | "*.safetensors", |
| 163 | "*.py", |
| 164 | "tokenizer.model", |
| 165 | "*.tiktoken", |
| 166 | ], |
| 167 | ) |
| 168 | ) |
| 169 | |
| 170 | with open(path / "config.json", "r") as f: |
| 171 | model_config = json.load(f) |
| 172 | |
| 173 | model_config = ModelConfig.from_dict(model_config) |
| 174 | |
| 175 | model_config.vision_config = VisionConfig.from_dict(model_config.vision_config) |
| 176 | model_config.text_config = TextConfig.from_dict(model_config.text_config) |
| 177 | |
| 178 | model = Model(model_config) |
| 179 | weight_files = glob.glob(str(path / "*.safetensors")) |
| 180 | if not weight_files: |
| 181 | raise FileNotFoundError(f"No safetensors found in {path}") |
| 182 | |
| 183 | weights = {} |
| 184 | for wf in weight_files: |
| 185 | weights.update(mx.load(wf)) |
| 186 | |
| 187 | weights = VisionModel.sanitize(weights) |
| 188 | weights = LanguageModel.sanitize(weights) |
| 189 | |
| 190 | model.load_weights(list(weights.items())) |
| 191 | return model |
| 192 | |
| 193 | def sanitize(self, weights): |
| 194 | def transform_key(key): |
| 195 | if "vision_tower" in key and "vision_model" not in key: |
| 196 | if "transformer" in key: |
| 197 | key = key.replace("vision_tower", "vision_tower.vision_model") |
| 198 | if "patch_conv" in key: |
| 199 | key = key.replace("vision_tower", "vision_tower.vision_model") |
| 200 | if "ln_pre" in key: |
| 201 | key = key.replace("vision_tower", "vision_tower.vision_model") |
| 202 | return key |
| 203 | |
| 204 | return {transform_key(k): v for k, v in weights.items()} |