| 1 | import inspect |
| 2 | from dataclasses import dataclass |
| 3 | from typing import List, Optional |
| 4 | |
| 5 | import mlx.core as mx |
| 6 | import mlx.nn as nn |
| 7 | |
| 8 | |
| 9 | @dataclass |
| 10 | class VisionConfig: |
| 11 | model_type: str |
| 12 | num_hidden_layers: int = 24 |
| 13 | hidden_size: int = 1024 |
| 14 | head_dim: int = 64 |
| 15 | intermediate_size: int = 4096 |
| 16 | num_attention_heads: int = 16 |
| 17 | image_size: int = 336 |
| 18 | patch_size: int = 14 |
| 19 | projection_dim: int = 768 |
| 20 | vocab_size: int = 32000 |
| 21 | num_channels: int = 3 |
| 22 | rms_norm_eps: float = 1e-5 |
| 23 | rope_theta: float = 10000.0 |
| 24 | |
| 25 | @classmethod |
| 26 | def from_dict(cls, params): |
| 27 | return cls( |
| 28 | **{ |
| 29 | k: v |
| 30 | for k, v in params.items() |
| 31 | if k in inspect.signature(cls).parameters |
| 32 | } |
| 33 | ) |
| 34 | |
| 35 | |
| 36 | def check_array_shape(arr): |
| 37 | shape = arr.shape |
| 38 | |
| 39 | # Check if the shape has 4 dimensions |
| 40 | if len(shape) != 4: |
| 41 | return False |
| 42 | |
| 43 | out_channels, kH, KW, _ = shape |
| 44 | |
| 45 | # Check if out_channels is the largest, and kH and KW are the same |
| 46 | if (out_channels >= kH) and (out_channels >= KW) and (kH == KW): |
| 47 | return True |
| 48 | else: |
| 49 | return False |
| 50 | |
| 51 | |
| 52 | def position_ids_in_meshgrid(patch_embeds_list, max_width): |
| 53 | positions = [] |
| 54 | for patch in patch_embeds_list: |
| 55 | height, width = patch.shape[1], patch.shape[2] |
| 56 | h_grid, v_grid = mx.meshgrid(mx.arange(height), mx.arange(width), indexing="ij") |
| 57 | h_grid = h_grid.reshape(-1, 1) |
| 58 | v_grid = v_grid.reshape(-1, 1) |
| 59 | ids = h_grid * max_width + v_grid |
| 60 | positions.append(ids.flatten()) |
| 61 | return mx.concatenate(positions) |
| 62 | |
| 63 | |
| 64 | def generate_block_attention_mask(patch_embeds_list, tensor): |
| 65 | seq_len = tensor.shape[1] |
| 66 | d_min = -1e9 # Using a large negative value as MLX doesn't have finfo |
| 67 | |
| 68 | causal_mask = mx.full((seq_len, seq_len), vals=d_min) |
| 69 | |
| 70 | block_end_idx = mx.cumsum(mx.array(patch_embeds_list)) |
| 71 | block_start_idx = mx.concatenate([mx.array([0]), mx.array(patch_embeds_list[:-1])]) |
| 72 | block_start_idx = mx.cumsum(block_start_idx) |
| 73 | |
| 74 | for start, end in zip(block_start_idx, block_end_idx): |
| 75 | start, end = int(start), int(end) # Convert to integers for indexing |
| 76 | causal_mask[start:end, start:end] = 0 |
| 77 | |
| 78 | causal_mask = mx.broadcast_to( |
| 79 | causal_mask[None, None, :, :], (tensor.shape[0], 1, seq_len, seq_len) |
| 80 | ) |
| 81 | return causal_mask |
| 82 | |
| 83 | |
| 84 | def rotate_half(x): |
| 85 | x1 = x[..., : x.shape[-1] // 2] |
| 86 | x2 = x[..., x.shape[-1] // 2 :] |
| 87 | return mx.concatenate((-x2, x1), axis=-1) |
| 88 | |
| 89 | |
| 90 | def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): |
| 91 | cos = mx.expand_dims(cos, axis=unsqueeze_dim) |
| 92 | sin = mx.expand_dims(sin, axis=unsqueeze_dim) |
| 93 | q_embed = (q * cos) + (rotate_half(q) * sin) |
| 94 | k_embed = (k * cos) + (rotate_half(k) * sin) |
| 95 | return q_embed, k_embed |
| 96 | |
| 97 | |
| 98 | class Attention(nn.Module): |
| 99 | def __init__( |
| 100 | self, |
| 101 | dims: int, |
| 102 | num_heads: int, |
| 103 | query_input_dims: Optional[int] = None, |
| 104 | key_input_dims: Optional[int] = None, |
| 105 | value_input_dims: Optional[int] = None, |
| 106 | value_dims: Optional[int] = None, |
| 107 | value_output_dims: Optional[int] = None, |
| 108 | bias: bool = False, |
| 109 | ): |
| 110 | super().__init__() |
| 111 | |
| 112 | if (dims % num_heads) != 0: |
| 113 | raise ValueError( |
| 114 | "The input feature dimensions should be divisible by the " |
| 115 | f"number of heads ({dims} % {num_heads}) != 0" |
| 116 | ) |
| 117 | |
| 118 | query_input_dims = query_input_dims or dims |
| 119 | key_input_dims = key_input_dims or dims |
| 120 | value_input_dims = value_input_dims or key_input_dims |
| 121 | value_dims = value_dims or dims |
| 122 | value_output_dims = value_output_dims or dims |
| 123 | |
| 124 | self.embed_dim = dims |
| 125 | self.num_heads = num_heads |
| 126 | self.head_dim = self.embed_dim // self.num_heads |
| 127 | |
| 128 | self.scale = self.head_dim**-0.5 |
| 129 | |
| 130 | self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False) |
| 131 | self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False) |
| 132 | self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False) |
| 133 | self.o_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False) |
| 134 | |
| 135 | def __call__(self, queries, keys, values, position_embeddings, mask=None): |
| 136 | queries = self.q_proj(queries) |
| 137 | keys = self.k_proj(keys) |
| 138 | values = self.v_proj(values) |
| 139 | |
| 140 | num_heads = self.num_heads |
| 141 | B, L, D = queries.shape |
| 142 | _, S, _ = keys.shape |
| 143 | queries = queries.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3) |
| 144 | keys = keys.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3) |
| 145 | values = values.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3) |
| 146 | |
| 147 | cos, sin = position_embeddings |
| 148 | queries, keys = apply_rotary_pos_emb(queries, keys, cos, sin, unsqueeze_dim=0) |
| 149 | |
| 150 | attn_weights = mx.matmul(queries, keys.transpose(0, 1, 3, 2)) * self.scale |
| 151 | |
| 152 | if mask is not None: |
| 153 | attn_weights = attn_weights + mask |
| 154 | |
| 155 | attn_weights = mx.softmax(attn_weights, axis=-1) |
| 156 | output = mx.matmul(attn_weights, values) |
| 157 | |
| 158 | output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) |
| 159 | |
| 160 | return self.o_proj(output) |
| 161 | |
| 162 | |
| 163 | class MLP(nn.Module): |
| 164 | def __init__(self, config: VisionConfig): |
| 165 | super().__init__() |
| 166 | dim = config.hidden_size |
| 167 | hidden_dim = config.intermediate_size |
| 168 | self.gate_proj = nn.Linear(dim, hidden_dim, bias=False) |
| 169 | self.down_proj = nn.Linear(hidden_dim, dim, bias=False) |
| 170 | self.up_proj = nn.Linear(dim, hidden_dim, bias=False) |
| 171 | |
| 172 | def __call__(self, x) -> mx.array: |
| 173 | return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x)) |
| 174 | |
| 175 | |
| 176 | class EncoderLayer(nn.Module): |
| 177 | def __init__(self, config: VisionConfig): |
| 178 | super().__init__() |
| 179 | self.embed_dim = config.hidden_size |
| 180 | self.attention = Attention( |
| 181 | config.hidden_size, config.num_attention_heads, bias=True |
| 182 | ) |
| 183 | self.attention_norm = nn.RMSNorm(self.embed_dim, eps=config.rms_norm_eps) |
| 184 | self.feed_forward = MLP(config) |
| 185 | self.ffn_norm = nn.RMSNorm(self.embed_dim, eps=config.rms_norm_eps) |
| 186 | |
| 187 | def __call__( |
| 188 | self, |
| 189 | x: mx.array, |
| 190 | position_embeddings: mx.array, |
| 191 | mask: Optional[mx.array] = None, |
| 192 | ) -> mx.array: |
| 193 | y = self.attention_norm(x) |
| 194 | y = self.attention(y, y, y, position_embeddings, mask) |
| 195 | x = x + y |
| 196 | y = self.ffn_norm(x) |
| 197 | y = self.feed_forward(y) |
| 198 | return x + y |
| 199 | |
| 200 | |
| 201 | class Encoder(nn.Module): |
| 202 | def __init__(self, config: VisionConfig): |
| 203 | super().__init__() |
| 204 | self.layers = [EncoderLayer(config) for _ in range(config.num_hidden_layers)] |
| 205 | |
| 206 | |
| 207 | class PixtralRotaryEmbedding: |
| 208 | def __init__(self, config): |
| 209 | self.dim = config.head_dim |
| 210 | self.base = config.rope_theta |
| 211 | max_patches_per_side = config.image_size // config.patch_size |
| 212 | freqs = 1.0 / ( |
| 213 | self.base ** (mx.arange(0, self.dim, 2).astype(mx.float32) / self.dim) |
| 214 | ) |
| 215 | |
| 216 | h = mx.arange(max_patches_per_side) |
| 217 | w = mx.arange(max_patches_per_side) |
| 218 | |
| 219 | freqs_h = mx.outer(h, freqs[::2]).astype(mx.float32) |
| 220 | freqs_w = mx.outer(w, freqs[1::2]).astype(mx.float32) |
| 221 | inv_freq = mx.concatenate( |
| 222 | [ |
| 223 | mx.tile(freqs_h[:, None, :], (1, max_patches_per_side, 1)), |
| 224 | mx.tile(freqs_w[None, :, :], (max_patches_per_side, 1, 1)), |
| 225 | ], |
| 226 | axis=-1, |
| 227 | ).reshape(-1, self.dim // 2) |
| 228 | |
| 229 | self.inv_freq = mx.concatenate((inv_freq, inv_freq), axis=-1) |
| 230 | |
| 231 | def __call__(self, x, position_ids): |
| 232 | freqs = self.inv_freq[position_ids] |
| 233 | emb = freqs |
| 234 | cos = mx.cos(emb) |
| 235 | sin = mx.sin(emb) |
| 236 | return cos.astype(x.dtype), sin.astype(x.dtype) |
| 237 | |
| 238 | |
| 239 | class PixtralVisionModel(nn.Module): |
| 240 | def __init__(self, config: VisionConfig): |
| 241 | super().__init__() |
| 242 | self.config = config |
| 243 | self.patch_conv = nn.Conv2d( |
| 244 | in_channels=config.num_channels, |
| 245 | out_channels=config.hidden_size, |
| 246 | kernel_size=config.patch_size, |
| 247 | stride=config.patch_size, |
| 248 | bias=False, |
| 249 | ) |
| 250 | self.ln_pre = nn.RMSNorm(config.hidden_size) |
| 251 | self.transformer = Encoder(config) |
| 252 | self.patch_positional_embedding = PixtralRotaryEmbedding(config) |
| 253 | |
| 254 | def __call__( |
| 255 | self, |
| 256 | x: List[mx.array], |
| 257 | output_hidden_states: Optional[bool] = None, |
| 258 | ) -> mx.array: |
| 259 | B, H, W, C = x[0].shape |
| 260 | patch_embeds_list = [self.patch_conv(img) for img in x] |
| 261 | |
| 262 | patch_embeds = mx.concatenate( |
| 263 | [p.reshape(B, -1, p.shape[-1]) for p in patch_embeds_list], axis=1 |
| 264 | ) |
| 265 | |
| 266 | patch_embeds = self.ln_pre(patch_embeds) |
| 267 | |
| 268 | position_ids = position_ids_in_meshgrid( |
| 269 | patch_embeds_list, |
| 270 | max_width=self.config.image_size // self.config.patch_size, |
| 271 | ) |
| 272 | |
| 273 | position_embedding = self.patch_positional_embedding(patch_embeds, position_ids) |
| 274 | |
| 275 | mask = generate_block_attention_mask( |
| 276 | [p.shape[2] * p.shape[1] for p in patch_embeds_list], patch_embeds |
| 277 | ) |
| 278 | |
| 279 | encoder_states = (patch_embeds,) if output_hidden_states else None |
| 280 | |
| 281 | for l in self.transformer.layers: |
| 282 | patch_embeds = l( |
| 283 | patch_embeds, mask=mask, position_embeddings=position_embedding |
| 284 | ) |
| 285 | if output_hidden_states: |
| 286 | encoder_states = encoder_states + (patch_embeds,) |
| 287 | |
| 288 | return patch_embeds, encoder_states |
| 289 | |
| 290 | |
| 291 | class VisionModel(nn.Module): |
| 292 | def __init__(self, config: VisionConfig): |
| 293 | super().__init__() |
| 294 | |
| 295 | self.model_type = config.model_type |
| 296 | if self.model_type not in ["clip_vision_model", "pixtral"]: |
| 297 | raise ValueError(f"Unsupported model type: {self.model_type}") |
| 298 | |
| 299 | self.vision_model = PixtralVisionModel(config) |
| 300 | |
| 301 | def __call__( |
| 302 | self, x: List[mx.array], output_hidden_states: Optional[bool] = None |
| 303 | ) -> mx.array: |
| 304 | return self.vision_model(x, output_hidden_states) |
| 305 | |
| 306 | def sanitize(self, weights): |
| 307 | sanitized_weights = {} |
| 308 | for k, v in weights.items(): |
| 309 | if "position_ids" in k: |
| 310 | # Remove unused position_ids |
| 311 | continue |
| 312 | elif "patch_conv.weight" in k: |
| 313 | # PyTorch conv2d weight tensors have shape: |
| 314 | # [out_channels, in_channels, kH, KW] |
| 315 | # MLX conv2d expects the weight be of shape: |
| 316 | # [out_channels, kH, KW, in_channels] |
| 317 | if check_array_shape(v): |
| 318 | sanitized_weights[k] = v |
| 319 | else: |
| 320 | sanitized_weights[k] = v.transpose(0, 2, 3, 1) |
| 321 | else: |
| 322 | sanitized_weights[k] = v |
| 323 | |
| 324 | return sanitized_weights |