| 1 | import copy |
| 2 | import inspect |
| 3 | from dataclasses import dataclass |
| 4 | from functools import partial |
| 5 | from math import sqrt |
| 6 | from typing import Dict, Optional, Union |
| 7 | |
| 8 | import mlx.core as mx |
| 9 | import mlx.nn as nn |
| 10 | import numpy as np |
| 11 | from scipy.ndimage import zoom |
| 12 | |
| 13 | from .sam import SAMEncoder |
| 14 | |
| 15 | |
| 16 | @dataclass |
| 17 | class VisionConfig: |
| 18 | model_type: str |
| 19 | num_hidden_layers: int = 24 |
| 20 | hidden_size: int = 1024 |
| 21 | intermediate_size: int = 4096 |
| 22 | num_attention_heads: int = 16 |
| 23 | image_size: int = 384 |
| 24 | patch_size: int = 16 |
| 25 | num_channels: int = 3 |
| 26 | layer_norm_eps: float = 1e-5 |
| 27 | cls: str = None |
| 28 | params: dict = None |
| 29 | |
| 30 | def __post_init__(self): |
| 31 | if "high_res_cfg" in self.params: |
| 32 | self.image_size = self.params["high_res_cfg"]["image_size"] |
| 33 | |
| 34 | @classmethod |
| 35 | def from_dict(cls, params): |
| 36 | return cls( |
| 37 | **{ |
| 38 | k: v |
| 39 | for k, v in params.items() |
| 40 | if k in inspect.signature(cls).parameters |
| 41 | } |
| 42 | ) |
| 43 | |
| 44 | |
| 45 | @dataclass |
| 46 | class MLPConfig: |
| 47 | hidden_size: int |
| 48 | intermediate_size: int |
| 49 | |
| 50 | |
| 51 | def check_array_shape(arr): |
| 52 | shape = arr.shape |
| 53 | |
| 54 | # Check if the shape has 4 dimensions |
| 55 | if len(shape) != 4: |
| 56 | return False |
| 57 | |
| 58 | out_channels, kH, KW, _ = shape |
| 59 | |
| 60 | # Check if out_channels is the largest, and kH and KW are the same |
| 61 | if (out_channels >= kH) and (out_channels >= KW) and (kH == KW): |
| 62 | return True |
| 63 | else: |
| 64 | return False |
| 65 | |
| 66 | |
| 67 | class AttentionPoolLatent(nn.Module): |
| 68 | """Attention pooling w/ latent query""" |
| 69 | |
| 70 | def __init__( |
| 71 | self, |
| 72 | in_features: int, |
| 73 | out_features: int = None, |
| 74 | embed_dim: int = None, |
| 75 | num_heads: int = 8, |
| 76 | mlp_ratio: float = 4.0, |
| 77 | qkv_bias: bool = True, |
| 78 | qk_norm: bool = False, |
| 79 | latent_len: int = 1, |
| 80 | latent_dim: int = None, |
| 81 | pos_embed: str = "", |
| 82 | pool_type: str = "token", |
| 83 | norm_layer: Optional[nn.Module] = None, |
| 84 | drop: float = 0.0, |
| 85 | ): |
| 86 | super().__init__() |
| 87 | |
| 88 | embed_dim = embed_dim or in_features |
| 89 | out_features = out_features or in_features |
| 90 | assert embed_dim % num_heads == 0 |
| 91 | self.num_heads = num_heads |
| 92 | self.head_dim = embed_dim // num_heads |
| 93 | self.scale = self.head_dim**-0.5 |
| 94 | self.pool = pool_type |
| 95 | |
| 96 | self.latent_dim = latent_dim or embed_dim |
| 97 | self.latent_len = latent_len |
| 98 | self.latent = mx.zeros((self.latent_len, embed_dim))[None, :] |
| 99 | |
| 100 | self.q = nn.Linear(embed_dim, embed_dim, bias=qkv_bias) |
| 101 | self.kv = nn.Linear(embed_dim, embed_dim * 2, bias=qkv_bias) |
| 102 | self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() |
| 103 | self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() |
| 104 | self.proj = nn.Linear(embed_dim, embed_dim) |
| 105 | self.proj_drop = nn.Dropout(drop) |
| 106 | |
| 107 | if pos_embed == "abs": |
| 108 | spatial_len = self.feat_size |
| 109 | self.pos_embed = mx.zeros((spatial_len, in_features)) |
| 110 | else: |
| 111 | self.pos_embed = None |
| 112 | |
| 113 | self.norm = nn.LayerNorm(out_features) |
| 114 | config = MLPConfig( |
| 115 | hidden_size=embed_dim, intermediate_size=int(embed_dim * mlp_ratio) |
| 116 | ) |
| 117 | self.mlp = MLP(config) |
| 118 | |
| 119 | def __call__(self, x: mx.array): |
| 120 | B, N, C = x.shape |
| 121 | |
| 122 | if self.pos_embed is not None: |
| 123 | x = x + self.pos_embed.unsqueeze(0).to(x.dtype) |
| 124 | |
| 125 | q_latent = mx.array(self.latent) |
| 126 | |
| 127 | q = ( |
| 128 | self.q(q_latent) |
| 129 | .reshape(B, self.latent_len, self.num_heads, self.head_dim) |
| 130 | .transpose(0, 2, 1, 3) |
| 131 | ) |
| 132 | |
| 133 | kv = ( |
| 134 | self.kv(x) |
| 135 | .reshape(B, N, 2, self.num_heads, self.head_dim) |
| 136 | .transpose(2, 0, 3, 1, 4) |
| 137 | ) |
| 138 | k, v = mx.split(kv, 2, axis=0) |
| 139 | |
| 140 | q, k = self.q_norm(q), self.k_norm(k) |
| 141 | |
| 142 | x = mx.fast.scaled_dot_product_attention( |
| 143 | q, k[0], v[0], scale=(1.0 / sqrt(q.shape[-1])), mask=None |
| 144 | ) |
| 145 | |
| 146 | x = x.transpose(0, 2, 1, 3).reshape(B, self.latent_len, C) |
| 147 | x = self.proj(x) |
| 148 | x = self.proj_drop(x) |
| 149 | |
| 150 | x = x + self.mlp(self.norm(x)) |
| 151 | |
| 152 | # optional pool if latent seq_len > 1 and pooled output is desired |
| 153 | if self.pool == "token": |
| 154 | x = x[:, 0] |
| 155 | elif self.pool == "avg": |
| 156 | x = x.mean(1) |
| 157 | return x |
| 158 | |
| 159 | |
| 160 | class Attention(nn.Module): |
| 161 | def __init__( |
| 162 | self, |
| 163 | dims: int, |
| 164 | num_heads: int, |
| 165 | qkv_bias: bool = False, |
| 166 | ): |
| 167 | super().__init__() |
| 168 | |
| 169 | if (dims % num_heads) != 0: |
| 170 | raise ValueError( |
| 171 | "The input feature dimensions should be divisible by the " |
| 172 | f"number of heads ({dims} % {num_heads}) != 0" |
| 173 | ) |
| 174 | |
| 175 | self.num_heads = num_heads = num_heads |
| 176 | head_dim = dims // num_heads |
| 177 | self.scale = head_dim**-0.5 |
| 178 | |
| 179 | self.qkv = nn.Linear(dims, dims * 3, bias=qkv_bias) |
| 180 | self.proj = nn.Linear(dims, dims, bias=True) |
| 181 | |
| 182 | def __call__(self, x, mask=None): |
| 183 | qkv = self.qkv(x) |
| 184 | queries, keys, values = mx.split(qkv, 3, axis=-1) |
| 185 | |
| 186 | num_heads = self.num_heads |
| 187 | B, L, D = queries.shape |
| 188 | _, S, _ = keys.shape |
| 189 | queries = queries.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3) |
| 190 | keys = keys.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3) |
| 191 | values = values.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3) |
| 192 | |
| 193 | output = mx.fast.scaled_dot_product_attention( |
| 194 | queries, keys, values, scale=self.scale, mask=mask |
| 195 | ) |
| 196 | output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) |
| 197 | |
| 198 | return self.proj(output) |
| 199 | |
| 200 | |
| 201 | class FastGELUActivation(nn.Module): |
| 202 | """ |
| 203 | Applies GELU approximation that is slower than QuickGELU but more accurate. See: https://github.com/hendrycks/GELUs |
| 204 | """ |
| 205 | |
| 206 | def __call__(self, input: mx.array) -> mx.array: |
| 207 | return ( |
| 208 | 0.5 |
| 209 | * input |
| 210 | * (1.0 + mx.tanh(np.sqrt(2 / np.pi) * (input + 0.044715 * (input**3)))) |
| 211 | ) |
| 212 | |
| 213 | |
| 214 | class MLP(nn.Module): |
| 215 | def __init__(self, config: Union[VisionConfig, Dict], bias: bool = True): |
| 216 | super().__init__() |
| 217 | self.activation_fn = FastGELUActivation() |
| 218 | self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=bias) |
| 219 | self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=bias) |
| 220 | |
| 221 | def __call__(self, x: mx.array) -> mx.array: |
| 222 | x = self.activation_fn(self.fc1(x)) |
| 223 | x = self.fc2(x) |
| 224 | return x |
| 225 | |
| 226 | |
| 227 | class EncoderLayer(nn.Module): |
| 228 | def __init__(self, config: VisionConfig): |
| 229 | super().__init__() |
| 230 | self.embed_dim = config.hidden_size |
| 231 | self.attn = Attention( |
| 232 | config.hidden_size, config.num_attention_heads, qkv_bias=True |
| 233 | ) |
| 234 | self.norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) |
| 235 | self.mlp = MLP(config) |
| 236 | self.norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) |
| 237 | |
| 238 | def __call__(self, x: mx.array, mask: Optional[mx.array] = None) -> mx.array: |
| 239 | y = self.norm1(x) |
| 240 | y = self.attn(y, mask) |
| 241 | x = x + y |
| 242 | y = self.norm2(x) |
| 243 | y = self.mlp(y) |
| 244 | return x + y |
| 245 | |
| 246 | |
| 247 | class VisionEmbeddings(nn.Module): |
| 248 | def __init__(self, config: VisionConfig, norm_layer: bool = False): |
| 249 | super().__init__() |
| 250 | self.config = config |
| 251 | self.embed_dim = config.hidden_size |
| 252 | self.image_size = config.image_size |
| 253 | self.patch_size = config.patch_size |
| 254 | |
| 255 | self.proj = nn.Conv2d( |
| 256 | in_channels=config.num_channels, |
| 257 | out_channels=self.embed_dim, |
| 258 | kernel_size=self.patch_size, |
| 259 | stride=self.patch_size, |
| 260 | ) |
| 261 | |
| 262 | self.num_patches = (self.image_size // self.patch_size) ** 2 |
| 263 | self.num_positions = self.num_patches |
| 264 | |
| 265 | self.norm = ( |
| 266 | nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) |
| 267 | if norm_layer |
| 268 | else nn.Identity() |
| 269 | ) |
| 270 | |
| 271 | def __call__(self, x: mx.array) -> mx.array: |
| 272 | patch_embeddings = self.proj(x) |
| 273 | patch_embeddings = mx.flatten(patch_embeddings, start_axis=1, end_axis=2) |
| 274 | return self.norm(patch_embeddings) |
| 275 | |
| 276 | |
| 277 | class SigLipVisionModel(nn.Module): |
| 278 | def __init__( |
| 279 | self, |
| 280 | config: VisionConfig, |
| 281 | ignore_head: bool, |
| 282 | pre_norm: bool = False, |
| 283 | no_embed_class: bool = True, |
| 284 | ): |
| 285 | super().__init__() |
| 286 | self.num_prefix_tokens = 1 |
| 287 | self.no_embed_class = False |
| 288 | self.dynamic_img_size = False |
| 289 | self.ignore_head = ignore_head |
| 290 | self.cls_token = None |
| 291 | self.reg_token = None |
| 292 | self.patch_embed = VisionEmbeddings(config) |
| 293 | self.norm_pre = nn.LayerNorm(config.hidden_size) if pre_norm else nn.Identity() |
| 294 | self.blocks = [EncoderLayer(config) for _ in range(config.num_hidden_layers)] |
| 295 | self.norm = nn.LayerNorm(config.hidden_size) |
| 296 | num_patches = self.patch_embed.num_patches |
| 297 | embed_len = ( |
| 298 | num_patches if no_embed_class else num_patches + self.num_prefix_tokens |
| 299 | ) |
| 300 | self.pos_embed = mx.random.normal((embed_len, config.hidden_size))[None, :] |
| 301 | |
| 302 | norm_layer = partial(nn.LayerNorm, eps=1e-5) |
| 303 | self.attn_pool = AttentionPoolLatent( |
| 304 | config.hidden_size, |
| 305 | num_heads=config.num_attention_heads, |
| 306 | norm_layer=norm_layer, |
| 307 | ) |
| 308 | |
| 309 | def __call__( |
| 310 | self, |
| 311 | x: mx.array, |
| 312 | output_hidden_states: Optional[bool] = None, |
| 313 | ) -> mx.array: |
| 314 | x = self.patch_embed(x) |
| 315 | x += self.pos_embed |
| 316 | x = self.norm_pre(x) |
| 317 | |
| 318 | encoder_states = (x,) if output_hidden_states else None |
| 319 | for l in self.blocks: |
| 320 | x = l(x, mask=None) |
| 321 | if output_hidden_states: |
| 322 | encoder_states = encoder_states + (x,) |
| 323 | |
| 324 | pooler_output = self.norm(x) |
| 325 | |
| 326 | if not self.ignore_head: |
| 327 | pooler_output = self.attn_pool(pooler_output) |
| 328 | return pooler_output, x, encoder_states |
| 329 | |
| 330 | |
| 331 | class HybridVisionModel(nn.Module): |
| 332 | def __init__(self, config: VisionConfig, resolution: str, ignore_head: bool = True): |
| 333 | super().__init__() |
| 334 | |
| 335 | self.model_type = config.model_type |
| 336 | self.resolution = resolution |
| 337 | if self.model_type != "vision": |
| 338 | raise ValueError(f"Unsupported model type: {self.model_type}") |
| 339 | |
| 340 | if resolution == "high": |
| 341 | self.vision_tower = SAMEncoder() |
| 342 | else: |
| 343 | self.vision_tower = SigLipVisionModel(config, ignore_head) |
| 344 | |
| 345 | def __call__(self, x: mx.array) -> mx.array: |
| 346 | if self.resolution == "high": |
| 347 | return self.vision_tower(x) |
| 348 | else: |
| 349 | return self.vision_tower(x)[0] |
| 350 | |
| 351 | |
| 352 | def resize_image(image, size, antialias=True): |
| 353 | """ |
| 354 | Resize an image using scipy.ndimage.zoom with an option for bicubic interpolation. |
| 355 | |
| 356 | Args: |
| 357 | image (numpy.ndarray): The input image array. |
| 358 | size (tuple): The target size as (width, height). |
| 359 | antialias (bool): True to use bicubic interpolation, False to use nearest neighbor. |
| 360 | |
| 361 | Returns: |
| 362 | numpy.ndarray: The resized image array. |
| 363 | """ |
| 364 | # Ensure the image is an array and remove singleton dimensions |
| 365 | image = np.array(image[0]) |
| 366 | |
| 367 | # Calculate zoom factors for the spatial dimensions |
| 368 | # Note: size is expected as (width, height) but image.shape gives (height, width) |
| 369 | current_height, current_width = image.shape[:2] |
| 370 | width_factor = size[0] / current_width |
| 371 | height_factor = size[1] / current_height |
| 372 | zoom_factors = (height_factor, width_factor) # Apply zoom to height and width |
| 373 | |
| 374 | # Choose the interpolation order: 3 for bicubic, 0 for nearest |
| 375 | order = 3 if antialias else 0 |
| 376 | |
| 377 | # Apply zoom to the image. Handle both grayscale and color images. |
| 378 | if image.ndim == 2: # Grayscale image |
| 379 | resized_image = zoom(image, zoom_factors, order=order) |
| 380 | elif image.ndim == 3: # Color image |
| 381 | # Apply zoom separately for each channel |
| 382 | resized_channels = [ |
| 383 | zoom(image[:, :, i], zoom_factors, order=order) |
| 384 | for i in range(image.shape[2]) |
| 385 | ] |
| 386 | resized_image = np.stack(resized_channels, axis=2) |
| 387 | |
| 388 | return resized_image |
| 389 | |
| 390 | |
| 391 | class VisionModel(nn.Module): |
| 392 | def __init__(self, config: VisionConfig, ignore_head: bool = True): |
| 393 | super().__init__() |
| 394 | |
| 395 | self.model_type = config.model_type |
| 396 | self.config = config |
| 397 | if self.model_type != "vision": |
| 398 | raise ValueError(f"Unsupported model type: {self.model_type}") |
| 399 | |
| 400 | if config.cls == "HybridVisionTower": |
| 401 | self.high_layer_norm = nn.LayerNorm( |
| 402 | config.params["high_res_cfg"]["output_dim"] |
| 403 | ) |
| 404 | self.low_layer_norm = nn.LayerNorm( |
| 405 | config.params["low_res_cfg"]["output_dim"] |
| 406 | ) |
| 407 | |
| 408 | high_res_cfg = copy.deepcopy(config) |
| 409 | high_res_cfg.image_size = config.params["high_res_cfg"]["image_size"] |
| 410 | self.vision_tower_high = HybridVisionModel( |
| 411 | high_res_cfg, "high", ignore_head |
| 412 | ) |
| 413 | |
| 414 | low_res_cfg = copy.deepcopy(config) |
| 415 | low_res_cfg.image_size = config.params["low_res_cfg"]["image_size"] |
| 416 | |
| 417 | self.vision_tower_low = HybridVisionModel(low_res_cfg, "low", ignore_head) |
| 418 | self.low_res_size = config.params["low_res_cfg"]["image_size"] |
| 419 | self.resize = lambda image: resize_image( |
| 420 | image, (self.low_res_size, self.low_res_size), antialias=True |
| 421 | ) |
| 422 | |
| 423 | else: |
| 424 | self.vision_tower = SigLipVisionModel(config, ignore_head) |
| 425 | |
| 426 | def __call__( |
| 427 | self, x: mx.array, output_hidden_states: Optional[bool] = None |
| 428 | ) -> mx.array: |
| 429 | if self.config.cls == "HybridVisionTower": |
| 430 | high_images = x |
| 431 | low_images = mx.array(self.resize(np.array(x)))[None, :] |
| 432 | |
| 433 | high_res = self.vision_tower_high(high_images) |
| 434 | low_res = self.vision_tower_low(low_images) |
| 435 | |
| 436 | return (high_res, low_res) |
| 437 | else: |
| 438 | return self.vision_tower(x, output_hidden_states) |
| 439 | |
| 440 | def sanitize(self, weights): |
| 441 | sanitized_weights = {} |
| 442 | weight_keys = { |
| 443 | "neck.0.weight", |
| 444 | "neck.2.weight", |
| 445 | "neck_hd.0.weight", |
| 446 | "neck_hd.2.weight", |
| 447 | "downsamples.0.weight", |
| 448 | "downsamples.1.weight", |
| 449 | "patch_embed.proj.weight", |
| 450 | } |
| 451 | for k, v in weights.items(): |
| 452 | if "position_ids" in k: |
| 453 | # Remove unused position_ids |
| 454 | continue |
| 455 | |
| 456 | elif ".".join(k.split(".")[-3:]) in weight_keys: |
| 457 | # PyTorch conv2d weight tensors have shape: |
| 458 | # [out_channels, in_channels, kH, KW] |
| 459 | # MLX conv2d expects the weight be of shape: |
| 460 | # [out_channels, kH, KW, in_channels] |
| 461 | if check_array_shape(v): |
| 462 | sanitized_weights[k] = v |
| 463 | else: |
| 464 | sanitized_weights[k] = v.transpose(0, 2, 3, 1) |
| 465 | |
| 466 | else: |
| 467 | sanitized_weights[k] = v |
| 468 | |
| 469 | return sanitized_weights |