| 1 | import glob |
| 2 | import inspect |
| 3 | import json |
| 4 | import re |
| 5 | from dataclasses import dataclass |
| 6 | from pathlib import Path |
| 7 | from typing import Optional |
| 8 | |
| 9 | import mlx.core as mx |
| 10 | import mlx.nn as nn |
| 11 | import numpy as np |
| 12 | from huggingface_hub import snapshot_download |
| 13 | from transformers import AutoConfig |
| 14 | |
| 15 | from .language import LanguageModel, TextConfig |
| 16 | from .vision import VisionConfig, VisionModel |
| 17 | |
| 18 | |
| 19 | @dataclass |
| 20 | class ModelConfig: |
| 21 | text_config: TextConfig |
| 22 | vision_config: VisionConfig |
| 23 | model_type: str |
| 24 | ignore_index: int = -100 |
| 25 | image_token_id: int = 128257 |
| 26 | vocab_size: int = 128259 |
| 27 | scale_factor: int = 2 |
| 28 | |
| 29 | @classmethod |
| 30 | def from_dict(cls, params): |
| 31 | return cls( |
| 32 | **{ |
| 33 | k: v |
| 34 | for k, v in params.items() |
| 35 | if k in inspect.signature(cls).parameters |
| 36 | } |
| 37 | ) |
| 38 | |
| 39 | |
| 40 | class MLP(nn.Module): |
| 41 | def __init__(self, config: ModelConfig): |
| 42 | super().__init__() |
| 43 | input_size = config.vision_config.hidden_size * (config.scale_factor**2) |
| 44 | output_size = config.text_config.hidden_size |
| 45 | self.proj = nn.Linear(input_size, output_size, bias=False) |
| 46 | |
| 47 | def __call__(self, x): |
| 48 | return self.proj(x) |
| 49 | |
| 50 | |
| 51 | class Idefics3Connector(nn.Module): |
| 52 | def __init__(self, config: ModelConfig): |
| 53 | super().__init__() |
| 54 | self.scale_factor = config.scale_factor |
| 55 | self.modality_projection = MLP(config) |
| 56 | |
| 57 | def pixel_shuffle(self, x, scale_factor=2): |
| 58 | bsz, seq, embed_dim = x.shape |
| 59 | height = width = int(seq**0.5) |
| 60 | x = x.reshape(bsz, height, width, embed_dim) |
| 61 | x = x.reshape(bsz, height, int(width / scale_factor), embed_dim * scale_factor) |
| 62 | x = x.transpose(0, 2, 1, 3) |
| 63 | x = x.reshape( |
| 64 | bsz, |
| 65 | int(width / scale_factor), |
| 66 | int(height / scale_factor), |
| 67 | embed_dim * (scale_factor**2), |
| 68 | ) |
| 69 | x = x.transpose(0, 2, 1, 3) |
| 70 | x = x.reshape(bsz, int(seq / (scale_factor**2)), embed_dim * (scale_factor**2)) |
| 71 | return x |
| 72 | |
| 73 | def __call__(self, image_hidden_states): |
| 74 | image_hidden_states = self.pixel_shuffle(image_hidden_states, self.scale_factor) |
| 75 | image_hidden_states = self.modality_projection(image_hidden_states) |
| 76 | return image_hidden_states |
| 77 | |
| 78 | |
| 79 | class Model(nn.Module): |
| 80 | def __init__(self, config: ModelConfig): |
| 81 | super().__init__() |
| 82 | self.model_type = config.model_type |
| 83 | self.config = config |
| 84 | |
| 85 | self.vision_model = VisionModel(config.vision_config) |
| 86 | self.language_model = LanguageModel(config.text_config) |
| 87 | self.connector = Idefics3Connector(config) |
| 88 | |
| 89 | def get_input_embeddings( |
| 90 | self, |
| 91 | input_ids: Optional[mx.array] = None, |
| 92 | pixel_values: Optional[mx.array] = None, |
| 93 | pixel_attention_mask: Optional[mx.array] = None, |
| 94 | ): |
| 95 | if pixel_values is None: |
| 96 | return self.language_model(input_ids) |
| 97 | |
| 98 | inputs_embeds = self.language_model.embed_tokens(input_ids) |
| 99 | |
| 100 | pooler_output, embeddings, hidden_state = self.vision_model( |
| 101 | pixel_values[0].transpose(0, 2, 3, 1), output_hidden_states=True |
| 102 | ) |
| 103 | |
| 104 | # image_features = pooler_output[None, :].astype(pixel_values.dtype) |
| 105 | image_features = pooler_output.astype(pixel_values.dtype) |
| 106 | image_features = self.connector(image_features) |
| 107 | |
| 108 | final_inputs_embeds = self._prepare_inputs_for_multimodal( |
| 109 | image_features, inputs_embeds, input_ids |
| 110 | ) |
| 111 | return final_inputs_embeds |
| 112 | |
| 113 | def _prepare_inputs_for_multimodal(self, image_features, inputs_embeds, input_ids): |
| 114 | image_token_index = self.config.image_token_id |
| 115 | num_images, num_image_patches, embed_dim = image_features.shape |
| 116 | |
| 117 | # Positions of <image> tokens in input_ids, assuming batch size is 1 |
| 118 | image_positions = np.where(input_ids[0] == image_token_index)[0].tolist() |
| 119 | |
| 120 | text_segments = [] |
| 121 | start_idx = 0 |
| 122 | |
| 123 | for position in image_positions: |
| 124 | text_segments.append(inputs_embeds[:, start_idx:position]) |
| 125 | start_idx = position + 1 |
| 126 | |
| 127 | image_embeddings = mx.split(image_features, image_features.shape[0]) |
| 128 | final_embeddings = [v for p in zip(text_segments, image_embeddings) for v in p] |
| 129 | final_embeddings += [inputs_embeds[:, start_idx:]] |
| 130 | |
| 131 | # Create a final embedding of shape |
| 132 | # (1, num_image_patches*num_images + sequence_len, embed_dim) |
| 133 | return mx.concatenate(final_embeddings, axis=1) |
| 134 | |
| 135 | def __call__( |
| 136 | self, |
| 137 | input_ids: mx.array, |
| 138 | pixel_values: mx.array, |
| 139 | cache=None, |
| 140 | **kwargs, |
| 141 | ): |
| 142 | input_embeddings = self.get_input_embeddings(input_ids, pixel_values) |
| 143 | logits = self.language_model( |
| 144 | inputs=input_ids, cache=cache, inputs_embeds=input_embeddings |
| 145 | ) |
| 146 | return logits |
| 147 | |
| 148 | @staticmethod |
| 149 | def from_pretrained(path_or_hf_repo: str): |
| 150 | path = Path(path_or_hf_repo) |
| 151 | if not path.exists(): |
| 152 | path = Path( |
| 153 | snapshot_download( |
| 154 | repo_id=path_or_hf_repo, |
| 155 | allow_patterns=[ |
| 156 | "*.json", |
| 157 | "*.safetensors", |
| 158 | "*.py", |
| 159 | "tokenizer.model", |
| 160 | "*.tiktoken", |
| 161 | ], |
| 162 | ) |
| 163 | ) |
| 164 | |
| 165 | with open(path / "config.json", "r") as f: |
| 166 | config = json.load(f) |
| 167 | |
| 168 | text_config = AutoConfig.from_pretrained(config["text_config"]["model_type"]) |
| 169 | text_config = text_config.to_dict() |
| 170 | config["text_config"] = text_config |
| 171 | model_config = ModelConfig.from_dict(config) |
| 172 | model_config.vision_config = VisionConfig.from_dict(config["vision_config"]) |
| 173 | model_config.text_config = TextConfig.from_dict(config["text_config"]) |
| 174 | |
| 175 | model = Model(model_config) |
| 176 | weight_files = glob.glob(str(path / "*.safetensors")) |
| 177 | if not weight_files: |
| 178 | raise FileNotFoundError(f"No safetensors found in {path}") |
| 179 | |
| 180 | weights = {} |
| 181 | for wf in weight_files: |
| 182 | weights.update(mx.load(wf)) |
| 183 | |
| 184 | weights = model.sanitize(weights=weights) |
| 185 | weights = VisionModel(model_config.vision_config).sanitize(weights=weights) |
| 186 | weights = LanguageModel(model_config.text_config).sanitize(weights=weights) |
| 187 | model.load_weights(list(weights.items())) |
| 188 | return model |
| 189 | |
| 190 | def sanitize(self, weights): |
| 191 | weights = { |
| 192 | ( |
| 193 | f"{k.split('.', 1)[1]}" |
| 194 | if re.match(r"^model\.", k) |
| 195 | else (f"language_model.{k}" if re.match(r"^lm_head\.", k) else k) |
| 196 | ): v |
| 197 | for k, v in weights.items() |
| 198 | } |
| 199 | |
| 200 | weights = { |
| 201 | ( |
| 202 | f"language_model.{k.split('.', 1)[1]}" |
| 203 | if re.match( |
| 204 | r"^text_model\.", |
| 205 | k, |
| 206 | ) |
| 207 | else k |
| 208 | ): v |
| 209 | for k, v in weights.items() |
| 210 | } |
| 211 | |
| 212 | return weights |