| 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, Tuple |
| 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 PerceiverConfig: |
| 21 | model_type: str |
| 22 | num_key_value_heads: int = 4 |
| 23 | resampler_depth: int = 3 |
| 24 | resampler_head_dim: int = 96 |
| 25 | resampler_n_heads: int = 16 |
| 26 | resampler_n_latents: int = 64 |
| 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 | @dataclass |
| 40 | class ModelConfig: |
| 41 | text_config: TextConfig |
| 42 | vision_config: VisionConfig |
| 43 | perceiver_config: PerceiverConfig |
| 44 | model_type: str |
| 45 | ignore_index: int = -100 |
| 46 | image_token_index: int = 32001 |
| 47 | vocab_size: int = 151936 |
| 48 | |
| 49 | @classmethod |
| 50 | def from_dict(cls, params): |
| 51 | return cls( |
| 52 | **{ |
| 53 | k: v |
| 54 | for k, v in params.items() |
| 55 | if k in inspect.signature(cls).parameters |
| 56 | } |
| 57 | ) |
| 58 | |
| 59 | |
| 60 | class Idefics2PerceiverAttention(nn.Module): |
| 61 | def __init__(self, config: ModelConfig): |
| 62 | super().__init__() |
| 63 | |
| 64 | dim = config.text_config.hidden_size |
| 65 | self.n_heads = n_heads = config.perceiver_config.resampler_n_heads |
| 66 | self.n_kv_heads = n_kv_heads = config.perceiver_config.num_key_value_heads |
| 67 | |
| 68 | head_dim = config.perceiver_config.resampler_head_dim |
| 69 | self.scale = head_dim**-0.5 |
| 70 | |
| 71 | self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=False) |
| 72 | self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False) |
| 73 | self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False) |
| 74 | self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False) |
| 75 | |
| 76 | def __call__( |
| 77 | self, |
| 78 | x: mx.array, |
| 79 | kv: mx.array, |
| 80 | mask: Optional[mx.array] = None, |
| 81 | cache: Optional[Tuple[mx.array, mx.array]] = None, |
| 82 | ) -> mx.array: |
| 83 | B, L, D = x.shape |
| 84 | kv_seq_len = L + kv.shape[1] |
| 85 | hidden_states = mx.concatenate([kv, x], axis=-2) |
| 86 | |
| 87 | queries = self.q_proj(x) |
| 88 | keys = self.k_proj(hidden_states) |
| 89 | values = self.v_proj(hidden_states) |
| 90 | |
| 91 | # Prepare the queries, keys and values for the attention computation |
| 92 | queries = queries.reshape(B, L, self.n_heads, -1).transpose(0, 2, 1, 3) |
| 93 | keys = keys.reshape(B, kv_seq_len, self.n_kv_heads, -1).transpose(0, 2, 1, 3) |
| 94 | values = values.reshape(B, kv_seq_len, self.n_kv_heads, -1).transpose( |
| 95 | 0, 2, 1, 3 |
| 96 | ) |
| 97 | |
| 98 | if cache is not None: |
| 99 | key_cache, value_cache = cache |
| 100 | keys = mx.concatenate([key_cache, keys], axis=2) |
| 101 | values = mx.concatenate([value_cache, values], axis=2) |
| 102 | |
| 103 | output = mx.fast.scaled_dot_product_attention( |
| 104 | queries, keys, values, scale=self.scale |
| 105 | ) |
| 106 | output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) |
| 107 | return self.o_proj(output) |
| 108 | |
| 109 | |
| 110 | class Idefics2PerceiverLayer(nn.Module): |
| 111 | def __init__(self, config: ModelConfig): |
| 112 | super().__init__() |
| 113 | self.hidden_size = config.text_config.hidden_size |
| 114 | self.n_latents = config.perceiver_config.resampler_n_latents |
| 115 | self.depth = config.perceiver_config.resampler_depth |
| 116 | self.rms_norm_eps = config.text_config.rms_norm_eps |
| 117 | |
| 118 | self.input_latents_norm = nn.RMSNorm(self.hidden_size, eps=self.rms_norm_eps) |
| 119 | self.input_context_norm = nn.RMSNorm(self.hidden_size, eps=self.rms_norm_eps) |
| 120 | self.self_attn = Idefics2PerceiverAttention(config) |
| 121 | self.post_attention_layernorm = nn.RMSNorm( |
| 122 | self.hidden_size, eps=self.rms_norm_eps |
| 123 | ) |
| 124 | self.mlp = MLP(self.hidden_size, self.hidden_size * 4, self.hidden_size) |
| 125 | |
| 126 | def __call__( |
| 127 | self, |
| 128 | x: mx.array, |
| 129 | hidden_states: mx.array, |
| 130 | mask: Optional[mx.array] = None, |
| 131 | ) -> mx.array: |
| 132 | latents = self.input_latents_norm(x) |
| 133 | context = self.input_context_norm(hidden_states) |
| 134 | |
| 135 | latents = self.self_attn(latents, context, mask=mask) |
| 136 | |
| 137 | latents = x + latents |
| 138 | r = latents |
| 139 | |
| 140 | latents = self.post_attention_layernorm(latents) |
| 141 | latents = self.mlp(latents) |
| 142 | latents = r + latents |
| 143 | return latents |
| 144 | |
| 145 | |
| 146 | class Idefics2PerceiverResampler(nn.Module): |
| 147 | def __init__(self, config: ModelConfig): |
| 148 | super().__init__() |
| 149 | self.hidden_size = config.text_config.hidden_size |
| 150 | self.n_latents = config.perceiver_config.resampler_n_latents |
| 151 | |
| 152 | self.latents = mx.ones((self.n_latents, self.hidden_size)) |
| 153 | self.layers = [ |
| 154 | Idefics2PerceiverLayer(config) |
| 155 | for _ in range(config.perceiver_config.resampler_depth) |
| 156 | ] |
| 157 | self.norm = nn.RMSNorm(self.hidden_size, eps=config.text_config.rms_norm_eps) |
| 158 | |
| 159 | def __call__(self, x: mx.array, mask: Optional[mx.array] = None): |
| 160 | |
| 161 | h = mx.expand_dims(self.latents, axis=0) |
| 162 | h = mx.repeat(h, x.shape[0], axis=0) |
| 163 | |
| 164 | for layer in self.layers: |
| 165 | h = layer(h, x, mask=mask) |
| 166 | |
| 167 | return self.norm(h) |
| 168 | |
| 169 | |
| 170 | class MLP(nn.Module): |
| 171 | def __init__(self, dim, hidden_dim, output_size): |
| 172 | super().__init__() |
| 173 | self.gate_proj = nn.Linear(dim, hidden_dim, bias=False) |
| 174 | self.down_proj = nn.Linear(hidden_dim, output_size, bias=False) |
| 175 | self.up_proj = nn.Linear(dim, hidden_dim, bias=False) |
| 176 | |
| 177 | def __call__(self, x) -> mx.array: |
| 178 | return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x)) |
| 179 | |
| 180 | |
| 181 | class Idefics2Connector(nn.Module): |
| 182 | def __init__(self, config: ModelConfig): |
| 183 | super().__init__() |
| 184 | self.modality_projection = MLP( |
| 185 | config.vision_config.hidden_size, |
| 186 | config.text_config.intermediate_size, |
| 187 | config.text_config.hidden_size, |
| 188 | ) |
| 189 | |
| 190 | self.perceiver_resampler = Idefics2PerceiverResampler(config) |
| 191 | |
| 192 | def __call__(self, x: mx.array, mask=None) -> mx.array: |
| 193 | x = self.modality_projection(x) |
| 194 | x = self.perceiver_resampler(x, mask=mask) |
| 195 | return x |
| 196 | |
| 197 | |
| 198 | class Model(nn.Module): |
| 199 | def __init__(self, config: ModelConfig): |
| 200 | super().__init__() |
| 201 | self.model_type = config.model_type |
| 202 | self.config = config |
| 203 | |
| 204 | self.vision_model = VisionModel(config.vision_config) |
| 205 | self.language_model = LanguageModel(config.text_config) |
| 206 | self.connector = Idefics2Connector(config) |
| 207 | |
| 208 | def get_input_embeddings( |
| 209 | self, |
| 210 | input_ids: Optional[mx.array] = None, |
| 211 | pixel_values: Optional[mx.array] = None, |
| 212 | pixel_attention_mask: Optional[mx.array] = None, |
| 213 | ): |
| 214 | if pixel_values is None: |
| 215 | return self.language_model(input_ids) |
| 216 | |
| 217 | inputs_embeds = self.language_model.embed_tokens(input_ids) |
| 218 | |
| 219 | pooler_output, embeddings, hidden_state = self.vision_model( |
| 220 | pixel_values[0].transpose(0, 2, 3, 1), output_hidden_states=True |
| 221 | ) |
| 222 | |
| 223 | image_features = pooler_output[None, :].astype(pixel_values.dtype) |
| 224 | |
| 225 | image_features = self.connector(image_features, mask=None) |
| 226 | |
| 227 | final_inputs_embeds = self._prepare_inputs_for_multimodal( |
| 228 | image_features, inputs_embeds, input_ids |
| 229 | ) |
| 230 | return final_inputs_embeds |
| 231 | |
| 232 | def _prepare_inputs_for_multimodal(self, image_features, inputs_embeds, input_ids): |
| 233 | image_token_index = self.config.image_token_index |
| 234 | num_images, num_image_patches, embed_dim = image_features.shape |
| 235 | |
| 236 | # Positions of <image> tokens in input_ids, assuming batch size is 1 |
| 237 | image_positions = np.where(input_ids[0] == image_token_index)[0].tolist() |
| 238 | |
| 239 | text_segments = [] |
| 240 | start_idx = 0 |
| 241 | |
| 242 | for position in image_positions: |
| 243 | text_segments.append(inputs_embeds[:, start_idx:position]) |
| 244 | start_idx = position + 1 |
| 245 | |
| 246 | image_embeddings = mx.split(image_features, image_features.shape[0]) |
| 247 | final_embeddings = [v for p in zip(text_segments, image_embeddings) for v in p] |
| 248 | final_embeddings += [inputs_embeds[:, start_idx:]] |
| 249 | |
| 250 | # Create a final embedding of shape |
| 251 | # (1, num_image_patches*num_images + sequence_len, embed_dim) |
| 252 | return mx.concatenate(final_embeddings, axis=1) |
| 253 | |
| 254 | def __call__( |
| 255 | self, |
| 256 | input_ids: mx.array, |
| 257 | pixel_values: mx.array, |
| 258 | mask: mx.array, |
| 259 | cache=None, |
| 260 | **kwargs, |
| 261 | ): |
| 262 | input_embeddings = self.get_input_embeddings(input_ids, pixel_values) |
| 263 | logits = self.language_model( |
| 264 | inputs=input_ids, cache=cache, inputs_embeds=input_embeddings |
| 265 | ) |
| 266 | return logits |
| 267 | |
| 268 | @staticmethod |
| 269 | def from_pretrained(path_or_hf_repo: str): |
| 270 | path = Path(path_or_hf_repo) |
| 271 | if not path.exists(): |
| 272 | path = Path( |
| 273 | snapshot_download( |
| 274 | repo_id=path_or_hf_repo, |
| 275 | allow_patterns=[ |
| 276 | "*.json", |
| 277 | "*.safetensors", |
| 278 | "*.py", |
| 279 | "tokenizer.model", |
| 280 | "*.tiktoken", |
| 281 | ], |
| 282 | ) |
| 283 | ) |
| 284 | |
| 285 | with open(path / "config.json", "r") as f: |
| 286 | config = json.load(f) |
| 287 | |
| 288 | text_config = AutoConfig.from_pretrained(config["text_config"]["model_type"]) |
| 289 | text_config = text_config.to_dict() |
| 290 | config["text_config"] = text_config |
| 291 | model_config = ModelConfig.from_dict(config) |
| 292 | model_config.vision_config = VisionConfig.from_dict(config["vision_config"]) |
| 293 | model_config.text_config = TextConfig.from_dict(config["text_config"]) |
| 294 | model_config.perceiver_config = PerceiverConfig.from_dict( |
| 295 | config["perceiver_config"] |
| 296 | ) |
| 297 | |
| 298 | model = Model(model_config) |
| 299 | weight_files = glob.glob(str(path / "*.safetensors")) |
| 300 | if not weight_files: |
| 301 | raise FileNotFoundError(f"No safetensors found in {path}") |
| 302 | |
| 303 | weights = {} |
| 304 | for wf in weight_files: |
| 305 | weights.update(mx.load(wf)) |
| 306 | |
| 307 | weights = model.sanitize(weights=weights) |
| 308 | weights = VisionModel(model_config.vision_config).sanitize(weights=weights) |
| 309 | weights = LanguageModel(model_config.text_config).sanitize(weights=weights) |
| 310 | model.load_weights(list(weights.items())) |
| 311 | return model |
| 312 | |
| 313 | def sanitize(self, weights): |
| 314 | weights = { |
| 315 | ( |
| 316 | f"{k.split('.', 1)[1]}" |
| 317 | if re.match(r"^model\.", k) |
| 318 | else (f"language_model.{k}" if re.match(r"^lm_head\.", k) else k) |
| 319 | ): v |
| 320 | for k, v in weights.items() |
| 321 | } |
| 322 | |
| 323 | weights = { |
| 324 | ( |
| 325 | f"language_model.{k.split('.', 1)[1]}" |
| 326 | if re.match( |
| 327 | r"^text_model\.", |
| 328 | k, |
| 329 | ) |
| 330 | else k |
| 331 | ): v |
| 332 | for k, v in weights.items() |
| 333 | } |
| 334 | |
| 335 | return weights |