| 1 | import inspect |
| 2 | from dataclasses import dataclass, field |
| 3 | from typing import List, Optional, Tuple |
| 4 | |
| 5 | import mlx.core as mx |
| 6 | import mlx.nn as nn |
| 7 | |
| 8 | |
| 9 | @dataclass |
| 10 | class VisionConfig: |
| 11 | model_type: str = "molmo" |
| 12 | num_channels: int = 3 |
| 13 | image_default_input_size: Tuple[int, int] = (336, 336) |
| 14 | image_patch_size: int = 14 |
| 15 | image_pos_patch_size: int = 14 |
| 16 | hidden_size: int = 18944 |
| 17 | image_emb_dim: int = 1024 |
| 18 | image_num_heads: int = 16 |
| 19 | image_num_key_value_heads: int = 16 |
| 20 | image_num_layers: int = 23 |
| 21 | image_head_dim: int = 64 |
| 22 | image_mlp_dim: int = 4096 |
| 23 | image_mlp_activations: str = "gelu" |
| 24 | image_dropout_rate: float = 0.0 |
| 25 | image_num_pos: int = 577 |
| 26 | image_norm_eps: float = 1e-5 |
| 27 | attention_dropout: float = 0.0 |
| 28 | residual_dropout: float = 0.0 |
| 29 | initializer_range: float = 0.02 |
| 30 | d_model: int = 3584 |
| 31 | image_pooling_h: int = 2 |
| 32 | image_pooling_w: int = 2 |
| 33 | vit_layers: Optional[List[int]] = field(default_factory=lambda: [-2, -9]) |
| 34 | image_pooling_2d: str = "attention-meanq" |
| 35 | image_padding_embed: str = "pad_and_partial_pad" |
| 36 | intermediate_size: Optional[int] = None |
| 37 | |
| 38 | def __post_init__(self): |
| 39 | if self.intermediate_size is None: |
| 40 | self.intermediate_size = self.image_patch_size * self.image_patch_size * 3 |
| 41 | |
| 42 | @property |
| 43 | def image_num_patch(self): |
| 44 | h, w = self.image_default_input_size |
| 45 | return h // self.image_patch_size, w // self.image_patch_size |
| 46 | |
| 47 | @property |
| 48 | def llm_patches_per_crop(self): |
| 49 | h, w = self.image_num_patch |
| 50 | # Round up in case we need to pad the image features for pooling |
| 51 | h = (h + self.image_pooling_h - 1) // self.image_pooling_h |
| 52 | w = (w + self.image_pooling_w - 1) // self.image_pooling_w |
| 53 | return h, w |
| 54 | |
| 55 | @classmethod |
| 56 | def from_dict(cls, params): |
| 57 | return cls( |
| 58 | **{ |
| 59 | k: v |
| 60 | for k, v in params.items() |
| 61 | if k in inspect.signature(cls).parameters |
| 62 | } |
| 63 | ) |
| 64 | |
| 65 | |
| 66 | class MLP(nn.Module): |
| 67 | def __init__(self, config: VisionConfig, input_dim: int): |
| 68 | super().__init__() |
| 69 | self.config = config |
| 70 | self.hidden_size = config.hidden_size |
| 71 | self.w1 = nn.Linear( |
| 72 | input_dim, |
| 73 | self.hidden_size, |
| 74 | bias=False, |
| 75 | ) |
| 76 | self.w2 = nn.Linear( |
| 77 | self.hidden_size, |
| 78 | config.d_model, |
| 79 | bias=False, |
| 80 | ) |
| 81 | self.w3 = nn.Linear( |
| 82 | input_dim, |
| 83 | self.hidden_size, |
| 84 | bias=False, |
| 85 | ) |
| 86 | |
| 87 | def __call__(self, x: mx.array) -> mx.array: |
| 88 | x = self.w2(nn.silu(self.w1(x)) * self.w3(x)) |
| 89 | return x |
| 90 | |
| 91 | |
| 92 | class ViTMLP(nn.Module): |
| 93 | def __init__(self, config: VisionConfig): |
| 94 | super().__init__() |
| 95 | self.config = config |
| 96 | self.w1 = nn.Linear(config.image_emb_dim, config.image_mlp_dim, bias=True) |
| 97 | self.w2 = nn.Linear(config.image_mlp_dim, config.image_emb_dim, bias=True) |
| 98 | self.act = nn.GELU(approx="fast") |
| 99 | |
| 100 | def __call__(self, x: mx.array) -> mx.array: |
| 101 | x = self.w1(x) |
| 102 | x = self.act(x) |
| 103 | x = self.w2(x) |
| 104 | return x |
| 105 | |
| 106 | |
| 107 | class MultiHeadDotProductAttention(nn.Module): |
| 108 | def __init__(self, config: VisionConfig, is_vit_layer: Optional[bool] = True): |
| 109 | super().__init__() |
| 110 | self.config = config |
| 111 | self.embed_dim = config.image_emb_dim |
| 112 | self.num_heads = config.image_num_heads |
| 113 | self.head_dim = config.image_head_dim |
| 114 | self.num_key_value_heads = config.image_num_key_value_heads |
| 115 | self.num_key_value_groups = self.num_heads // self.num_key_value_heads |
| 116 | self.scale = self.head_dim**-0.5 |
| 117 | self.is_vit_layer = is_vit_layer |
| 118 | |
| 119 | n_layers = ( |
| 120 | 1 if (is_vit_layer or config.vit_layers is None) else len(config.vit_layers) |
| 121 | ) |
| 122 | |
| 123 | self.wq = nn.Linear( |
| 124 | n_layers * self.embed_dim, self.num_heads * self.head_dim, bias=True |
| 125 | ) |
| 126 | self.wk = nn.Linear( |
| 127 | n_layers * self.embed_dim, |
| 128 | self.num_key_value_heads * self.head_dim, |
| 129 | bias=True, |
| 130 | ) |
| 131 | self.wv = nn.Linear( |
| 132 | n_layers * self.embed_dim, |
| 133 | self.num_key_value_heads * self.head_dim, |
| 134 | bias=True, |
| 135 | ) |
| 136 | self.wo = nn.Linear(self.num_heads * self.head_dim, self.embed_dim, bias=True) |
| 137 | |
| 138 | def _split_heads(self, hidden_states, num_heads) -> mx.array: |
| 139 | return hidden_states.reshape( |
| 140 | hidden_states.shape[:2] + (num_heads, self.head_dim) |
| 141 | ) |
| 142 | |
| 143 | def _merge_heads(self, hidden_states) -> mx.array: |
| 144 | return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,)) |
| 145 | |
| 146 | def __call__(self, x: mx.array, kv: mx.array = None) -> mx.array: |
| 147 | batch_size, seq_len, _ = x.shape |
| 148 | |
| 149 | if kv is None: |
| 150 | k = x |
| 151 | v = x |
| 152 | else: |
| 153 | k = kv |
| 154 | v = kv |
| 155 | q = self._split_heads(self.wq(x), self.num_heads).transpose(0, 2, 1, 3) |
| 156 | |
| 157 | k = self._split_heads(self.wk(k), self.num_key_value_heads).transpose( |
| 158 | 0, 2, 1, 3 |
| 159 | ) |
| 160 | v = self._split_heads(self.wv(v), self.num_key_value_heads).transpose( |
| 161 | 0, 2, 1, 3 |
| 162 | ) |
| 163 | |
| 164 | attn = mx.fast.scaled_dot_product_attention(q, k, v, scale=self.scale) |
| 165 | out = attn.transpose(0, 2, 1, 3) |
| 166 | out = self._merge_heads(out) |
| 167 | out = self.wo(out) |
| 168 | return out |
| 169 | |
| 170 | |
| 171 | class ResidualAttentionBlock(nn.Module): |
| 172 | def __init__(self, config: VisionConfig): |
| 173 | super().__init__() |
| 174 | self.config = config |
| 175 | self.attention = MultiHeadDotProductAttention(config) |
| 176 | self.feed_forward = ViTMLP(config) |
| 177 | self.attention_norm = nn.LayerNorm( |
| 178 | config.image_emb_dim, eps=config.image_norm_eps |
| 179 | ) |
| 180 | self.ffn_norm = nn.LayerNorm(config.image_emb_dim, eps=config.image_norm_eps) |
| 181 | |
| 182 | def __call__(self, x: mx.array) -> mx.array: |
| 183 | x = x + self.attention(self.attention_norm(x)) |
| 184 | x = x + self.feed_forward(self.ffn_norm(x)) |
| 185 | return x |
| 186 | |
| 187 | |
| 188 | class ResidualAttentionBlocks(nn.Module): |
| 189 | def __init__(self, config: VisionConfig): |
| 190 | super().__init__() |
| 191 | self.resblocks = [ |
| 192 | ResidualAttentionBlock(config) for _ in range(config.image_num_layers) |
| 193 | ] |
| 194 | |
| 195 | def __call__(self, x: mx.array) -> mx.array: |
| 196 | h = [] |
| 197 | for block in self.resblocks: |
| 198 | x = block(x) |
| 199 | h.append(x) |
| 200 | return h |
| 201 | |
| 202 | |
| 203 | def _expand_token(token, batch_size: int): |
| 204 | return mx.broadcast_to( |
| 205 | mx.reshape(token, (1, 1, -1)), (batch_size, 1, token.shape[-1]) |
| 206 | ) |
| 207 | |
| 208 | |
| 209 | def pad_to_multiple(x, target_size, pad_mode="edge", pad_value=0): |
| 210 | """ |
| 211 | Pad the last dimension of input tensor to match target size. |
| 212 | |
| 213 | Args: |
| 214 | x: Input tensor with shape [..., D] |
| 215 | target_size: Desired size for the last dimension |
| 216 | pad_mode: Padding mode ('constant', 'reflect', etc.) |
| 217 | pad_value: Value to use for constant padding |
| 218 | |
| 219 | Returns: |
| 220 | Padded tensor with shape [..., target_size] |
| 221 | """ |
| 222 | current_size = x.shape[-1] |
| 223 | |
| 224 | # Return early if no padding needed |
| 225 | if current_size == target_size: |
| 226 | return x |
| 227 | |
| 228 | # Ensure target size is larger |
| 229 | if current_size > target_size: |
| 230 | raise ValueError( |
| 231 | f"Current size {current_size} is larger than target size {target_size}" |
| 232 | ) |
| 233 | |
| 234 | # Calculate padding needed |
| 235 | pad_size = target_size - current_size |
| 236 | |
| 237 | # Create padding configuration |
| 238 | # No padding for batch and channel dimensions (0,0), only pad the last dim |
| 239 | pad_config = [(0, 0)] * (len(x.shape) - 1) + [(0, pad_size)] |
| 240 | |
| 241 | return mx.pad(x, pad_width=pad_config, mode=pad_mode, constant_values=pad_value) |
| 242 | |
| 243 | |
| 244 | class VisionTransformer(nn.Module): |
| 245 | def __init__(self, config: VisionConfig): |
| 246 | super().__init__() |
| 247 | self.config = config |
| 248 | self.class_embedding = mx.zeros((config.image_emb_dim,)) |
| 249 | self.positional_embedding = mx.zeros( |
| 250 | (config.image_num_pos, config.image_emb_dim) |
| 251 | ) |
| 252 | self.patch_embedding = nn.Linear( |
| 253 | config.intermediate_size, |
| 254 | config.image_emb_dim, |
| 255 | bias=False, |
| 256 | ) |
| 257 | self.pre_ln = nn.LayerNorm(config.image_emb_dim, eps=config.image_norm_eps) |
| 258 | self.transformer = ResidualAttentionBlocks(config) |
| 259 | |
| 260 | def add_pos_emb(self, x: mx.array, patch_num: int) -> mx.array: |
| 261 | cls_emb = self.positional_embedding[0:1] |
| 262 | pos_emb = self.positional_embedding[1:] |
| 263 | |
| 264 | # Reshape into 2D grid |
| 265 | pos_emb_size = int(pos_emb.shape[0] ** 0.5) |
| 266 | pos_emb = mx.reshape(pos_emb, (pos_emb_size, pos_emb_size, pos_emb.shape[1])) |
| 267 | |
| 268 | (patch_num_0, patch_num_1) = patch_num |
| 269 | |
| 270 | if pos_emb.shape[0] != patch_num_0 or pos_emb.shape[1] != patch_num_1: |
| 271 | # Reshape for upsampling (add batch and channel dims) |
| 272 | pos_emb = mx.expand_dims(pos_emb, 0) |
| 273 | pos_emb = mx.transpose(pos_emb, (0, 3, 1, 2)) |
| 274 | |
| 275 | # Create and apply upsampler |
| 276 | upsampler = nn.Upsample( |
| 277 | scale_factor=( |
| 278 | patch_num_0 / pos_emb.shape[2], |
| 279 | patch_num_1 / pos_emb.shape[3], |
| 280 | ), |
| 281 | mode="linear", # MLX doesn't have bicubic, using linear as closest alternative |
| 282 | align_corners=False, |
| 283 | ) |
| 284 | pos_emb = upsampler(pos_emb) |
| 285 | |
| 286 | # Restore original dimensions |
| 287 | pos_emb = mx.transpose(pos_emb, (0, 2, 3, 1)) |
| 288 | pos_emb = mx.squeeze(pos_emb, 0) |
| 289 | |
| 290 | pos_emb = mx.reshape(pos_emb, (-1, pos_emb.shape[-1])) |
| 291 | |
| 292 | # Expand cls_emb and pos_emb |
| 293 | expanded_cls = cls_emb[None, :, :] |
| 294 | expanded_pos = pos_emb[None, :, :] |
| 295 | |
| 296 | # Concatenate and add to x |
| 297 | pos_embedding = mx.concatenate([expanded_cls, expanded_pos], axis=1) |
| 298 | x = x + pos_embedding |
| 299 | return x |
| 300 | |
| 301 | def __call__(self, x: mx.array, patch_num: int = None) -> List[mx.array]: |
| 302 | """ |
| 303 | : param x: (batch_size, num_patch, n_pixels) |
| 304 | """ |
| 305 | if patch_num is None: |
| 306 | patch_num = self.config.image_num_patch |
| 307 | B, N, D = x.shape |
| 308 | |
| 309 | # (Optional) Due to quantization, pad around the image to match intermediate_size |
| 310 | x = pad_to_multiple(x, self.config.intermediate_size) |
| 311 | |
| 312 | x = self.patch_embedding(x) |
| 313 | |
| 314 | # class embeddings and positional embeddings |
| 315 | expanded_class_emb = _expand_token(self.class_embedding, x.shape[0]) |
| 316 | expanded_class_emb = expanded_class_emb |
| 317 | |
| 318 | x = mx.concatenate([expanded_class_emb, x], axis=1) |
| 319 | x = self.add_pos_emb(x, patch_num) |
| 320 | |
| 321 | x = self.pre_ln(x) |
| 322 | |
| 323 | hidden_states = self.transformer(x) |
| 324 | return hidden_states |
| 325 | |
| 326 | |
| 327 | class VisionModel(nn.Module): |
| 328 | def __init__(self, config): |
| 329 | super().__init__() |
| 330 | self.config = config |
| 331 | self.model_type = config.model_type |
| 332 | if self.model_type != "molmo": |
| 333 | raise ValueError( |
| 334 | f"Model type {self.model_type} not supported. Currently only 'molmo' is supported" |
| 335 | ) |
| 336 | self.image_vit = VisionTransformer(config) |
| 337 | self.num_prefix_tokens = 1 |
| 338 | |
| 339 | self.image_pooling_2d = MultiHeadDotProductAttention(config, is_vit_layer=False) |
| 340 | self.image_projector = MLP(config, config.image_emb_dim) |
| 341 | self.pad_embed = mx.zeros((2, config.image_emb_dim * 2)) |
| 342 | |
| 343 | def encode_image(self, images: mx.array) -> mx.array: |
| 344 | """ |
| 345 | : param images: (batch_size, num_crops, num_patch, n_pixels) |
| 346 | """ |
| 347 | cfg = self.config |
| 348 | B, T, N, D = images.shape |
| 349 | |
| 350 | # Check for -1 values across dimensions 1 and 2 |
| 351 | reshaped_images = mx.reshape(images, (B * T, N, D)) |
| 352 | mask = ~mx.all(reshaped_images == -1, axis=(1, 2), keepdims=True) |
| 353 | |
| 354 | # Output all hidden states |
| 355 | images = reshaped_images |
| 356 | image_features = self.image_vit(images) |
| 357 | |
| 358 | if cfg.vit_layers is not None: |
| 359 | features = [] |
| 360 | for layer in cfg.vit_layers: |
| 361 | features.append(image_features[layer]) |
| 362 | image_features = mx.concatenate(features, axis=-1) |
| 363 | else: |
| 364 | image_features = image_features[-1] |
| 365 | |
| 366 | cls_embed = None |
| 367 | if self.num_prefix_tokens > 0: |
| 368 | cls_embed = image_features[:, 0] |
| 369 | image_features = image_features[:, 1:] |
| 370 | |
| 371 | image_features = image_features * mask |
| 372 | image_features = mx.reshape(image_features, (B, T, N, -1)) |
| 373 | |
| 374 | cls_embed = mx.reshape(cls_embed, (B, T, -1)) if cls_embed is not None else None |
| 375 | |
| 376 | return image_features, cls_embed |
| 377 | |
| 378 | def __call__( |
| 379 | self, images: mx.array, image_masks: mx.array |
| 380 | ) -> Tuple[mx.array, Optional[mx.array]]: |
| 381 | cfg = self.config |
| 382 | |
| 383 | batch_size, num_image = images.shape[:2] |
| 384 | image_features, cls_embed = self.encode_image(images) |
| 385 | |
| 386 | if cfg.image_padding_embed: |
| 387 | assert image_masks is not None |
| 388 | if cfg.image_padding_embed == "pad_embed": |
| 389 | all_pad = image_masks == 0 |
| 390 | pad_embed = mx.reshape(self.pad_embed, (1, 1, 1, -1)) |
| 391 | image_features = image_features + pad_embed * mx.expand_dims( |
| 392 | all_pad, -1 |
| 393 | ) |
| 394 | elif cfg.image_padding_embed == "regress": |
| 395 | pad_embed = mx.reshape(self.pad_embed, (1, 1, 1, -1)) |
| 396 | image_features = image_features + pad_embed * mx.expand_dims( |
| 397 | mx.maximum(image_masks, mx.zeros_like(image_masks)), -1 |
| 398 | ) |
| 399 | elif cfg.image_padding_embed == "pad_and_partial_pad": |
| 400 | pad_embed = mx.reshape(self.pad_embed, (2, 1, 1, 1, -1)) |
| 401 | all_pad = image_masks == 0 |
| 402 | partial_pad = mx.logical_and(image_masks < 1, mx.logical_not(all_pad)) |
| 403 | partial_pad = partial_pad |
| 404 | all_pad = all_pad |
| 405 | image_features = image_features + pad_embed[0] * mx.expand_dims( |
| 406 | all_pad, -1 |
| 407 | ) |
| 408 | image_features = image_features + pad_embed[1] * mx.expand_dims( |
| 409 | partial_pad, -1 |
| 410 | ) |
| 411 | else: |
| 412 | raise ValueError(cfg.image_padding_embed) |
| 413 | |
| 414 | image_features = mx.reshape( |
| 415 | image_features, (batch_size, num_image) + cfg.image_num_patch + (-1,) |
| 416 | ) |
| 417 | |
| 418 | if cfg.image_num_patch[0] % cfg.image_pooling_h == 1: |
| 419 | # Pad so we can still pool 2x2 patches |
| 420 | image_features = mx.pad( |
| 421 | image_features, [(0, 0), (0, 0), (0, 1), (0, 1), (0, 0)] |
| 422 | ) |
| 423 | |
| 424 | # image pooling |
| 425 | # MLX equivalent of einops rearrange |
| 426 | h_blocks = image_features.shape[2] // cfg.image_pooling_h |
| 427 | w_blocks = image_features.shape[3] // cfg.image_pooling_w |
| 428 | image_features = mx.reshape( |
| 429 | mx.transpose( |
| 430 | mx.reshape( |
| 431 | image_features, |
| 432 | ( |
| 433 | batch_size, |
| 434 | num_image, |
| 435 | h_blocks, |
| 436 | cfg.image_pooling_h, |
| 437 | w_blocks, |
| 438 | cfg.image_pooling_w, |
| 439 | -1, |
| 440 | ), |
| 441 | ), |
| 442 | (0, 1, 2, 4, 3, 5, 6), |
| 443 | ), |
| 444 | ( |
| 445 | batch_size * num_image * h_blocks * w_blocks, |
| 446 | cfg.image_pooling_h * cfg.image_pooling_w, |
| 447 | -1, |
| 448 | ), |
| 449 | ) |
| 450 | |
| 451 | if cfg.image_pooling_2d == "attention-meanq": |
| 452 | query = mx.mean(image_features, axis=-2, keepdims=True) |
| 453 | image_features = self.image_pooling_2d(query, image_features) |
| 454 | elif cfg.image_pooling_2d not in {"none", "stack"}: |
| 455 | image_features = self.image_pooling_2d( |
| 456 | image_features[:, :1, :], image_features |
| 457 | ) |
| 458 | |
| 459 | h, w = cfg.llm_patches_per_crop |
| 460 | image_features = mx.reshape(image_features, (batch_size, num_image, h * w, -1)) |
| 461 | |
| 462 | # # MLP layer to map the feature |
| 463 | image_features = self.image_projector(image_features) |
| 464 | |
| 465 | return image_features, cls_embed |