| 1 | import inspect |
| 2 | from dataclasses import dataclass |
| 3 | from typing import Optional |
| 4 | |
| 5 | import mlx.core as mx |
| 6 | import mlx.nn as nn |
| 7 | import numpy as np |
| 8 | |
| 9 | |
| 10 | @dataclass |
| 11 | class VisionConfig: |
| 12 | model_type: str |
| 13 | num_hidden_layers: int |
| 14 | hidden_size: int |
| 15 | intermediate_size: int |
| 16 | num_attention_heads: int |
| 17 | patch_size: int |
| 18 | image_size: int = 224 |
| 19 | num_channels: int = 3 |
| 20 | layer_norm_eps: float = 1e-6 |
| 21 | |
| 22 | @classmethod |
| 23 | def from_dict(cls, params): |
| 24 | return cls( |
| 25 | **{ |
| 26 | k: v |
| 27 | for k, v in params.items() |
| 28 | if k in inspect.signature(cls).parameters |
| 29 | } |
| 30 | ) |
| 31 | |
| 32 | |
| 33 | def check_array_shape(arr): |
| 34 | shape = arr.shape |
| 35 | |
| 36 | # Check if the shape has 4 dimensions |
| 37 | if len(shape) != 4: |
| 38 | return False |
| 39 | |
| 40 | out_channels, kH, KW, _ = shape |
| 41 | |
| 42 | # Check if out_channels is the largest, and kH and KW are the same |
| 43 | if (out_channels >= kH) and (out_channels >= KW) and (kH == KW): |
| 44 | return True |
| 45 | else: |
| 46 | return False |
| 47 | |
| 48 | |
| 49 | class Attention(nn.Module): |
| 50 | def __init__( |
| 51 | self, |
| 52 | dims: int, |
| 53 | num_heads: int, |
| 54 | query_input_dims: Optional[int] = None, |
| 55 | key_input_dims: Optional[int] = None, |
| 56 | value_input_dims: Optional[int] = None, |
| 57 | value_dims: Optional[int] = None, |
| 58 | value_output_dims: Optional[int] = None, |
| 59 | bias: bool = True, |
| 60 | ): |
| 61 | super().__init__() |
| 62 | |
| 63 | if (dims % num_heads) != 0: |
| 64 | raise ValueError( |
| 65 | "The input feature dimensions should be divisible by the " |
| 66 | f"number of heads ({dims} % {num_heads}) != 0" |
| 67 | ) |
| 68 | |
| 69 | query_input_dims = query_input_dims or dims |
| 70 | key_input_dims = key_input_dims or dims |
| 71 | value_input_dims = value_input_dims or key_input_dims |
| 72 | value_dims = value_dims or dims |
| 73 | value_output_dims = value_output_dims or dims |
| 74 | |
| 75 | self.num_heads = num_heads |
| 76 | head_dim = dims // num_heads |
| 77 | self.scale = head_dim**-0.5 |
| 78 | |
| 79 | self.q_proj = nn.Linear(query_input_dims, dims, bias=bias) |
| 80 | self.k_proj = nn.Linear(key_input_dims, dims, bias=bias) |
| 81 | self.v_proj = nn.Linear(value_input_dims, value_dims, bias=bias) |
| 82 | self.out_proj = nn.Linear(value_dims, value_output_dims, bias=bias) |
| 83 | |
| 84 | def __call__(self, x, mask=None): |
| 85 | queries = self.q_proj(x) |
| 86 | keys = self.k_proj(x) |
| 87 | values = self.v_proj(x) |
| 88 | |
| 89 | num_heads = self.num_heads |
| 90 | B, L, D = queries.shape |
| 91 | _, S, _ = keys.shape |
| 92 | queries = queries.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3) |
| 93 | keys = keys.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3) |
| 94 | values = values.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3) |
| 95 | |
| 96 | output = mx.fast.scaled_dot_product_attention( |
| 97 | queries, keys, values, scale=self.scale, mask=mask |
| 98 | ) |
| 99 | output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) |
| 100 | return self.out_proj(output) |
| 101 | |
| 102 | |
| 103 | class MLP(nn.Module): |
| 104 | def __init__(self, config: VisionConfig): |
| 105 | super().__init__() |
| 106 | self.activation_fn = nn.GELU(approx="precise") |
| 107 | self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=True) |
| 108 | self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=True) |
| 109 | |
| 110 | def __call__(self, x: mx.array) -> mx.array: |
| 111 | x = self.fc1(x) |
| 112 | x = self.activation_fn(x) |
| 113 | x = self.fc2(x) |
| 114 | return x |
| 115 | |
| 116 | |
| 117 | class EncoderLayer(nn.Module): |
| 118 | def __init__(self, config: VisionConfig): |
| 119 | super().__init__() |
| 120 | self.embed_dim = config.hidden_size |
| 121 | self.self_attn = Attention( |
| 122 | config.hidden_size, config.num_attention_heads, bias=True |
| 123 | ) |
| 124 | self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) |
| 125 | self.mlp = MLP(config) |
| 126 | self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) |
| 127 | |
| 128 | def __call__(self, x: mx.array, mask: Optional[mx.array] = None) -> mx.array: |
| 129 | r = self.self_attn(self.layer_norm1(x), mask) |
| 130 | h = x + r |
| 131 | r = self.mlp(self.layer_norm2(h)) |
| 132 | return h + r |
| 133 | |
| 134 | |
| 135 | class Encoder(nn.Module): |
| 136 | def __init__(self, config: VisionConfig): |
| 137 | super().__init__() |
| 138 | self.layers = [EncoderLayer(config) for _ in range(config.num_hidden_layers)] |
| 139 | |
| 140 | def __call__( |
| 141 | self, |
| 142 | x: mx.array, |
| 143 | output_hidden_states: Optional[bool] = None, |
| 144 | mask: Optional[mx.array] = None, |
| 145 | ) -> mx.array: |
| 146 | encoder_states = (x,) if output_hidden_states else None |
| 147 | h = x |
| 148 | for l in self.layers: |
| 149 | x = l(x, mask=mask) |
| 150 | if output_hidden_states: |
| 151 | encoder_states = encoder_states + (x,) |
| 152 | |
| 153 | h = x |
| 154 | |
| 155 | return (h, encoder_states) |
| 156 | |
| 157 | |
| 158 | class VisionEmbeddings(nn.Module): |
| 159 | def __init__(self, config: VisionConfig): |
| 160 | super().__init__() |
| 161 | self.config = config |
| 162 | self.embed_dim = config.hidden_size |
| 163 | self.image_size = config.image_size |
| 164 | self.patch_size = config.patch_size |
| 165 | |
| 166 | self.patch_embedding = nn.Conv2d( |
| 167 | in_channels=config.num_channels, |
| 168 | out_channels=self.embed_dim, |
| 169 | kernel_size=self.patch_size, |
| 170 | stride=self.patch_size, |
| 171 | ) |
| 172 | |
| 173 | self.num_patches = (self.image_size // self.patch_size) ** 2 |
| 174 | self.num_positions = self.num_patches |
| 175 | self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim) |
| 176 | |
| 177 | def __call__(self, x: mx.array) -> mx.array: |
| 178 | patch_embeddings = self.patch_embedding(x) |
| 179 | patch_embeddings = mx.flatten(patch_embeddings, start_axis=1, end_axis=2) |
| 180 | position_ids = mx.array(mx.arange(self.num_positions)[None, :]) |
| 181 | embeddings = patch_embeddings |
| 182 | embeddings += self.position_embedding(position_ids) |
| 183 | return embeddings |
| 184 | |
| 185 | |
| 186 | class VisionModel(nn.Module): |
| 187 | def __init__(self, config: VisionConfig): |
| 188 | super().__init__() |
| 189 | self.model_type = config.model_type |
| 190 | if self.model_type != "siglip_vision_model" and self.model_type != "idefics3": |
| 191 | raise ValueError(f"Unsupported model type: {self.model_type}") |
| 192 | |
| 193 | self.embeddings = VisionEmbeddings(config) |
| 194 | self.encoder = Encoder(config) |
| 195 | self.post_layernorm = nn.LayerNorm(config.hidden_size) |
| 196 | |
| 197 | def __call__( |
| 198 | self, |
| 199 | x: mx.array, |
| 200 | output_hidden_states: Optional[bool] = None, |
| 201 | ) -> mx.array: |
| 202 | x = self.embeddings(x) |
| 203 | x = x.astype(self.embeddings.patch_embedding.weight.dtype) |
| 204 | encoder_outputs = self.encoder( |
| 205 | x=x, output_hidden_states=output_hidden_states, mask=None |
| 206 | ) |
| 207 | pooler_output = self.post_layernorm(encoder_outputs[0]) |
| 208 | return pooler_output, x, encoder_outputs[-1] |
| 209 | |
| 210 | def sanitize(self, weights): |
| 211 | sanitized_weights = {} |
| 212 | for k, v in weights.items(): |
| 213 | if "position_ids" in k: |
| 214 | # Remove unused position_ids |
| 215 | continue |
| 216 | elif "patch_embedding.weight" in k: |
| 217 | # PyTorch conv2d weight tensors have shape: |
| 218 | # [out_channels, in_channels, kH, KW] |
| 219 | # MLX conv2d expects the weight be of shape: |
| 220 | # [out_channels, kH, KW, in_channels] |
| 221 | if check_array_shape(v): |
| 222 | sanitized_weights[k] = v |
| 223 | else: |
| 224 | sanitized_weights[k] = v.transpose(0, 2, 3, 1) |
| 225 | else: |
| 226 | sanitized_weights[k] = v |
| 227 | |
| 228 | return sanitized_weights |