| 1 | import glob |
| 2 | import inspect |
| 3 | import json |
| 4 | import math |
| 5 | from dataclasses import dataclass, field |
| 6 | from pathlib import Path |
| 7 | from typing import List, Optional, Tuple, Union |
| 8 | |
| 9 | import mlx.core as mx |
| 10 | import mlx.nn as nn |
| 11 | from huggingface_hub import snapshot_download |
| 12 | from mlx.utils import tree_map |
| 13 | |
| 14 | from .language import LanguageModel, TextConfig |
| 15 | from .vision import VisionConfig, VisionModel |
| 16 | |
| 17 | |
| 18 | @dataclass |
| 19 | class ModelConfig: |
| 20 | """Configuration class for Florence2.""" |
| 21 | |
| 22 | vision_config: VisionConfig |
| 23 | text_config: TextConfig |
| 24 | model_type: str = "florence2" |
| 25 | vocab_size: int = 50265 |
| 26 | max_position_embeddings: int = 1024 |
| 27 | pad_token_id: int = 1 |
| 28 | bos_token_id: int = 0 |
| 29 | eos_token_id: int = 2 |
| 30 | image_token_index: int = 0 |
| 31 | image_feature_source: List[str] = field( |
| 32 | default_factory=lambda: ["temporal_avg_pool", "spatial_avg_pool"] |
| 33 | ) |
| 34 | visual_temporal_embedding: Optional[dict] = field( |
| 35 | default_factory=lambda: {"type": "COSINE", "max_temporal_embeddings": 100} |
| 36 | ) |
| 37 | image_pos_embed: Optional[dict] = field( |
| 38 | default_factory=lambda: {"type": "learned_abs_2d", "max_pos_embeddings": 50} |
| 39 | ) |
| 40 | |
| 41 | @classmethod |
| 42 | def from_dict(cls, params): |
| 43 | return cls( |
| 44 | **{ |
| 45 | k: v |
| 46 | for k, v in params.items() |
| 47 | if k in inspect.signature(cls).parameters |
| 48 | } |
| 49 | ) |
| 50 | |
| 51 | |
| 52 | def shift_tokens_right( |
| 53 | input_ids: mx.array, pad_token_id: int, decoder_start_token_id: int |
| 54 | ) -> mx.array: |
| 55 | """Shift input tokens right, adding decoder start token at beginning.""" |
| 56 | shifted = mx.roll(input_ids, 1, axis=-1) |
| 57 | shifted = tree_map(lambda x: x.at[:, 0].set(decoder_start_token_id), shifted) |
| 58 | shifted = mx.where(shifted == -100, pad_token_id, shifted) |
| 59 | return shifted |
| 60 | |
| 61 | |
| 62 | class LearnedPositionEmbedding2D(nn.Module): |
| 63 | """2D learned position embeddings.""" |
| 64 | |
| 65 | def __init__(self, embedding_dim: int = 256, num_pos: int = 50): |
| 66 | super().__init__() |
| 67 | self.row_embeddings = nn.Embedding(num_pos, embedding_dim // 2) |
| 68 | self.column_embeddings = nn.Embedding( |
| 69 | num_pos, embedding_dim - (embedding_dim // 2) |
| 70 | ) |
| 71 | |
| 72 | def __call__(self, x): |
| 73 | batch_size, height, width, channels = x.shape |
| 74 | width_pos = mx.arange(width) |
| 75 | height_pos = mx.arange(height) |
| 76 | |
| 77 | x_emb = self.column_embeddings(width_pos) |
| 78 | y_emb = self.row_embeddings(height_pos) |
| 79 | |
| 80 | pos = mx.concatenate( |
| 81 | [ |
| 82 | mx.broadcast_to(x_emb[None, :, :], (height, width, x_emb.shape[-1])), |
| 83 | mx.broadcast_to(y_emb[:, None, :], (height, width, y_emb.shape[-1])), |
| 84 | ], |
| 85 | axis=-1, |
| 86 | ) |
| 87 | |
| 88 | return mx.broadcast_to(pos[None, ...], (batch_size, height, width, channels)) |
| 89 | |
| 90 | |
| 91 | class PositionalEmbeddingCosine1D(nn.Module): |
| 92 | """ |
| 93 | MLX implementation of 1D cosine positional embeddings. |
| 94 | |
| 95 | Args: |
| 96 | embed_dim: The dimension of the embeddings |
| 97 | max_seq_len: The maximum length to precompute the positional encodings |
| 98 | """ |
| 99 | |
| 100 | def __init__(self, embed_dim: int = 512, max_seq_len: int = 1024) -> None: |
| 101 | super().__init__() |
| 102 | self.embed_dim = embed_dim |
| 103 | self.max_seq_len = max_seq_len |
| 104 | |
| 105 | # Generate position indices and dimension indices |
| 106 | position = mx.arange(max_seq_len) |
| 107 | dim_pos = mx.arange(0, embed_dim // 2) # Half the dimensions for sin/cos pairs |
| 108 | |
| 109 | # Calculate frequency bands |
| 110 | factor = math.log(10000) |
| 111 | denominator = mx.exp(-factor * dim_pos / embed_dim) |
| 112 | |
| 113 | # Create position-frequency product matrix [max_seq_len, embed_dim//2] |
| 114 | frequencies = mx.reshape(position, (-1, 1)) * denominator |
| 115 | |
| 116 | # Calculate sin and cos values [max_seq_len, embed_dim//2] |
| 117 | sin_values = mx.sin(frequencies) |
| 118 | cos_values = mx.cos(frequencies) |
| 119 | |
| 120 | # Interleave sin and cos values to create final embeddings |
| 121 | pos_idx_to_embed = mx.zeros((max_seq_len, embed_dim)) |
| 122 | pos_idx_to_embed = mx.concatenate( |
| 123 | [mx.expand_dims(sin_values, -1), mx.expand_dims(cos_values, -1)], axis=-1 |
| 124 | ).reshape(max_seq_len, embed_dim) |
| 125 | |
| 126 | # Store the positional embeddings |
| 127 | self.pos_idx_to_embed = pos_idx_to_embed |
| 128 | |
| 129 | def __call__(self, seq_embeds: mx.array) -> mx.array: |
| 130 | """ |
| 131 | Apply positional embeddings to the input sequence. |
| 132 | |
| 133 | Args: |
| 134 | seq_embeds: Input sequence embeddings with shape: |
| 135 | - [T, D] where T is sequence length and D is embedding dimension |
| 136 | - [B, T, D] where B is batch size |
| 137 | |
| 138 | Returns: |
| 139 | Positional embeddings matching input shape |
| 140 | """ |
| 141 | shape_len = len(seq_embeds.shape) |
| 142 | assert 2 <= shape_len <= 3, "Input must be 2D or 3D tensor" |
| 143 | |
| 144 | len_seq = seq_embeds.shape[-2] |
| 145 | assert ( |
| 146 | len_seq <= self.max_seq_len |
| 147 | ), f"Sequence length {len_seq} exceeds maximum length {self.max_seq_len}" |
| 148 | |
| 149 | # Get relevant portion of pre-computed embeddings |
| 150 | pos_embeds = self.pos_idx_to_embed[:len_seq] |
| 151 | |
| 152 | # Add batch dimension if input is 3D |
| 153 | if shape_len == 3: |
| 154 | pos_embeds = mx.expand_dims(pos_embeds, 0) |
| 155 | |
| 156 | return pos_embeds |
| 157 | |
| 158 | |
| 159 | class Model(nn.Module): |
| 160 | """Florence-2 model for conditional generation.""" |
| 161 | |
| 162 | def __init__(self, config: ModelConfig): |
| 163 | super().__init__() |
| 164 | self.config = config |
| 165 | |
| 166 | # Initialize vision model |
| 167 | self.vision_tower = VisionModel(config.vision_config) |
| 168 | |
| 169 | # Initialize language model |
| 170 | self.language_model = LanguageModel(config.text_config) |
| 171 | |
| 172 | # Image projection layers |
| 173 | image_dim = config.vision_config.dim_embed[-1] |
| 174 | text_dim = config.text_config.d_model |
| 175 | self.image_projection = mx.zeros((image_dim, text_dim)) |
| 176 | |
| 177 | self.image_proj_norm = nn.LayerNorm(text_dim) |
| 178 | |
| 179 | # Position embeddings |
| 180 | if config.image_pos_embed["type"] == "learned_abs_2d": |
| 181 | self.image_pos_embed = LearnedPositionEmbedding2D( |
| 182 | embedding_dim=image_dim, |
| 183 | num_pos=config.image_pos_embed["max_pos_embeddings"], |
| 184 | ) |
| 185 | else: |
| 186 | raise NotImplementedError( |
| 187 | f"Position embedding type {config.image_pos_embed['type']} not supported" |
| 188 | ) |
| 189 | |
| 190 | # Temporal embeddings |
| 191 | if config.visual_temporal_embedding["type"] == "COSINE": |
| 192 | self.visual_temporal_embed = PositionalEmbeddingCosine1D( |
| 193 | embed_dim=image_dim, |
| 194 | max_seq_len=config.visual_temporal_embedding["max_temporal_embeddings"], |
| 195 | ) |
| 196 | else: |
| 197 | raise NotImplementedError( |
| 198 | f"Temporal embedding type {config.visual_temporal_embedding['type']} not supported" |
| 199 | ) |
| 200 | |
| 201 | self.image_feature_source = config.image_feature_source |
| 202 | |
| 203 | def _encode_image(self, pixel_values, extract_features=True): |
| 204 | """Encode image using vision model and add position embeddings.""" |
| 205 | T = 1 # Single frame for now |
| 206 | |
| 207 | # Get vision features |
| 208 | if extract_features: |
| 209 | batch_size, C, H, W = pixel_values.shape |
| 210 | x = self.vision_tower(pixel_values) |
| 211 | else: |
| 212 | x = pixel_values |
| 213 | batch_size = pixel_values.shape[0] |
| 214 | |
| 215 | # Assuming this is part of a class method, keeping the same structure |
| 216 | if self.image_pos_embed is not None: |
| 217 | # Reshape to (batch_size * T, -1, feature_dim) |
| 218 | x = mx.reshape(x, (batch_size * T, -1, x.shape[-1])) |
| 219 | num_tokens = x.shape[-2] |
| 220 | h, w = int(num_tokens**0.5), int(num_tokens**0.5) |
| 221 | assert h * w == num_tokens, "only support square feature maps for now" |
| 222 | # Reshape to (batch_size * T, h, w, feature_dim) |
| 223 | x = mx.reshape(x, (batch_size * T, h, w, x.shape[-1])) |
| 224 | pos_embed = self.image_pos_embed(x) |
| 225 | x = x + pos_embed |
| 226 | # Reshape to (batch_size, T * h * w, feature_dim) |
| 227 | x = mx.reshape(x, (batch_size, T * h * w, x.shape[-1])) |
| 228 | |
| 229 | if self.visual_temporal_embed is not None: |
| 230 | # Reshape for temporal embedding |
| 231 | x_temp = mx.reshape(x, (batch_size, T, -1, x.shape[-1])) |
| 232 | temporal_input = x_temp[:, :, 0] |
| 233 | visual_temporal_embed = self.visual_temporal_embed(temporal_input) |
| 234 | # Expand dims for broadcasting |
| 235 | visual_temporal_embed = mx.expand_dims(visual_temporal_embed, axis=2) |
| 236 | x = mx.reshape(x, (batch_size, T, -1, x.shape[-1])) + visual_temporal_embed |
| 237 | |
| 238 | x_feat_dict = {} |
| 239 | |
| 240 | # Spatial average pooling |
| 241 | x_spatial = mx.reshape(x, (batch_size, T, -1, x.shape[-1])) |
| 242 | spatial_avg_pool_x = mx.mean(x_spatial, axis=2) |
| 243 | x_feat_dict["spatial_avg_pool"] = spatial_avg_pool_x |
| 244 | |
| 245 | # Temporal average pooling |
| 246 | x_temporal = mx.reshape(x, (batch_size, T, -1, x.shape[-1])) |
| 247 | temporal_avg_pool_x = mx.mean(x_temporal, axis=1) |
| 248 | x_feat_dict["temporal_avg_pool"] = temporal_avg_pool_x |
| 249 | |
| 250 | # Last frame features |
| 251 | x_last = mx.reshape(x, (batch_size, T, -1, x.shape[-1])) |
| 252 | x = x_last[:, -1] |
| 253 | x_feat_dict["last_frame"] = x |
| 254 | |
| 255 | # Gather features based on source configuration |
| 256 | new_x = [] |
| 257 | for _image_feature_source in self.image_feature_source: |
| 258 | if _image_feature_source not in x_feat_dict: |
| 259 | raise ValueError( |
| 260 | f"invalid image feature source: {_image_feature_source}" |
| 261 | ) |
| 262 | new_x.append(x_feat_dict[_image_feature_source]) |
| 263 | |
| 264 | # Concatenate features |
| 265 | x = mx.concatenate(new_x, axis=1) |
| 266 | |
| 267 | # Final projection and normalization |
| 268 | x = x @ self.image_projection |
| 269 | x = self.image_proj_norm(x) |
| 270 | |
| 271 | return x |
| 272 | |
| 273 | def _merge_input_ids_with_image_features(self, image_features, inputs_embeds=None): |
| 274 | batch_size, image_token_length, _ = image_features.shape |
| 275 | image_attention_mask = mx.ones((batch_size, image_token_length)) |
| 276 | |
| 277 | if inputs_embeds is None: |
| 278 | return image_features, image_attention_mask |
| 279 | |
| 280 | task_prefix_embeds = inputs_embeds |
| 281 | task_prefix_attention_mask = mx.ones((batch_size, task_prefix_embeds.shape[1])) |
| 282 | |
| 283 | if len(task_prefix_attention_mask.shape) == 3: |
| 284 | task_prefix_attention_mask = task_prefix_attention_mask[:, 0] |
| 285 | |
| 286 | # Concatenate image features and task prefix embeddings |
| 287 | inputs_embeds = mx.concatenate([image_features, task_prefix_embeds], axis=1) |
| 288 | attention_mask = mx.concatenate( |
| 289 | [image_attention_mask, task_prefix_attention_mask], axis=1 |
| 290 | ) |
| 291 | return inputs_embeds, attention_mask |
| 292 | |
| 293 | def __call__( |
| 294 | self, |
| 295 | input_ids=None, |
| 296 | pixel_values=None, |
| 297 | cache=None, |
| 298 | decoder_input_ids=None, |
| 299 | decoder_attention_mask=None, |
| 300 | labels=None, |
| 301 | **kwargs, |
| 302 | ): |
| 303 | """Forward pass.""" |
| 304 | attention_mask = None |
| 305 | decoder_inputs_embeds = None |
| 306 | |
| 307 | # Process image if provided |
| 308 | if pixel_values is not None: |
| 309 | image_features = self._encode_image(pixel_values) |
| 310 | |
| 311 | # Get input embeddings if needed |
| 312 | inputs_embeds = None |
| 313 | if input_ids is not None: |
| 314 | inputs_embeds = self.language_model.model.shared(input_ids) |
| 315 | |
| 316 | # Merge image features with text embeddings |
| 317 | inputs_embeds, attention_mask = self._merge_input_ids_with_image_features( |
| 318 | image_features, inputs_embeds |
| 319 | ) |
| 320 | |
| 321 | # Handle decoder input IDs |
| 322 | if labels is not None and decoder_input_ids is None: |
| 323 | decoder_input_ids = shift_tokens_right( |
| 324 | labels, self.config.pad_token_id, self.config.bos_token_id |
| 325 | ) |
| 326 | |
| 327 | if decoder_input_ids is None and decoder_inputs_embeds is None: |
| 328 | decoder_start_token_id = getattr( |
| 329 | self.config, "decoder_start_token_id", 0 |
| 330 | ) # 2 is common for many models |
| 331 | if decoder_start_token_id is None: |
| 332 | decoder_start_token_id = 0 |
| 333 | |
| 334 | decoder_input_ids = mx.array([decoder_start_token_id])[None, :] |
| 335 | decoder_inputs_embeds = self.language_model.model.shared(decoder_input_ids) |
| 336 | decoder_input_ids = None |
| 337 | |
| 338 | # Forward through language model |
| 339 | outputs = self.language_model( |
| 340 | input_ids=input_ids, |
| 341 | inputs_embeds=inputs_embeds, |
| 342 | attention_mask=attention_mask, |
| 343 | decoder_input_ids=decoder_input_ids, |
| 344 | decoder_inputs_embeds=decoder_inputs_embeds, |
| 345 | decoder_attention_mask=decoder_attention_mask, |
| 346 | cache=cache, |
| 347 | ) |
| 348 | |
| 349 | return outputs |
| 350 | |
| 351 | @staticmethod |
| 352 | def from_pretrained(path_or_hf_repo: str): |
| 353 | path = Path(path_or_hf_repo) |
| 354 | if not path.exists(): |
| 355 | path = Path( |
| 356 | snapshot_download( |
| 357 | repo_id=path_or_hf_repo, |
| 358 | allow_patterns=[ |
| 359 | "*.json", |
| 360 | "*.safetensors", |
| 361 | "*.py", |
| 362 | "tokenizer.model", |
| 363 | "*.tiktoken", |
| 364 | ], |
| 365 | ) |
| 366 | ) |
| 367 | |
| 368 | with open(path / "config.json", "r") as f: |
| 369 | model_config = json.load(f) |
| 370 | |
| 371 | model_config = ModelConfig.from_dict(model_config) |
| 372 | |
| 373 | model_config.vision_config = VisionConfig.from_dict(model_config.vision_config) |
| 374 | model_config.text_config = TextConfig.from_dict(model_config) |
| 375 | |
| 376 | model = Model(model_config) |
| 377 | weight_files = glob.glob(str(path / "*.safetensors")) |
| 378 | if not weight_files: |
| 379 | raise FileNotFoundError(f"No safetensors found in {path}") |
| 380 | |
| 381 | weights = {} |
| 382 | for wf in weight_files: |
| 383 | weights.update(mx.load(wf)) |
| 384 | |
| 385 | weights = VisionModel.sanitize(weights) |
| 386 | weights = LanguageModel.sanitize(weights) |
| 387 | |
| 388 | model.load_weights(list(weights.items())) |
| 389 | return model |
| 390 | |
| 391 | @staticmethod |
| 392 | def sanitize(weights): |
| 393 | sanitized_weights = {} |
| 394 | for k, v in weights.items(): |
| 395 | if "final_logits_bias" in k: |
| 396 | continue |
| 397 | sanitized_weights[k] = v |
| 398 | return sanitized_weights |