| 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 | hidden_size: int |
| 14 | intermediate_size: int |
| 15 | num_hidden_layers: int |
| 16 | num_attention_heads: int |
| 17 | image_size: int |
| 18 | patch_size: int |
| 19 | layer_norm_eps: float |
| 20 | num_channels: int = 3 |
| 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 | ): |
| 60 | super().__init__() |
| 61 | |
| 62 | if (dims % num_heads) != 0: |
| 63 | raise ValueError( |
| 64 | "The input feature dimensions should be divisible by the " |
| 65 | f"number of heads ({dims} % {num_heads}) != 0" |
| 66 | ) |
| 67 | |
| 68 | query_input_dims = query_input_dims or dims |
| 69 | key_input_dims = key_input_dims or dims |
| 70 | value_input_dims = value_input_dims or key_input_dims |
| 71 | value_dims = value_dims or dims |
| 72 | value_output_dims = value_output_dims or dims |
| 73 | |
| 74 | self.num_heads = num_heads |
| 75 | head_dim = dims // num_heads |
| 76 | self.scale = head_dim**-0.5 |
| 77 | |
| 78 | self.q_proj = nn.Linear(query_input_dims, dims, bias=True) |
| 79 | self.k_proj = nn.Linear(key_input_dims, dims, bias=True) |
| 80 | self.v_proj = nn.Linear(value_input_dims, value_dims, bias=True) |
| 81 | self.out_proj = nn.Linear(value_dims, value_output_dims, bias=True) |
| 82 | |
| 83 | def __call__(self, x: mx.array, mask=None): |
| 84 | B, L, _ = x.shape |
| 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 | |
| 91 | queries = queries.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3) |
| 92 | keys = keys.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3) |
| 93 | values = values.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3) |
| 94 | if mask is not None: |
| 95 | mask = mask[:, :, mask.shape[-2] :, :] |
| 96 | |
| 97 | output = mx.fast.scaled_dot_product_attention( |
| 98 | queries, keys, values, scale=self.scale, mask=mask |
| 99 | ) |
| 100 | output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) |
| 101 | return self.out_proj(output) |
| 102 | |
| 103 | |
| 104 | class MLP(nn.Module): |
| 105 | def __init__(self, config: VisionConfig): |
| 106 | super().__init__() |
| 107 | self.activation_fn = nn.GELU(approx="fast") |
| 108 | self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size) |
| 109 | self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size) |
| 110 | |
| 111 | def __call__(self, x: mx.array) -> mx.array: |
| 112 | x = self.activation_fn(self.fc1(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(config.hidden_size, config.num_attention_heads) |
| 122 | self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) |
| 123 | self.mlp = MLP(config) |
| 124 | self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) |
| 125 | |
| 126 | def __call__(self, x: mx.array, mask: Optional[mx.array] = None) -> mx.array: |
| 127 | y = self.layer_norm1(x) |
| 128 | y = self.self_attn(y, mask) |
| 129 | x = x + y |
| 130 | y = self.layer_norm2(x) |
| 131 | y = self.mlp(y) |
| 132 | return x + y |
| 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[0] |
| 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 |
| 174 | self.num_positions = self.num_patches**2 |
| 175 | self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim) |
| 176 | |
| 177 | def __call__(self, x: mx.array, mask: Optional[mx.array] = None) -> mx.array: |
| 178 | B, H, W, C = x.shape |
| 179 | patch_embeddings = self.patch_embedding(x) |
| 180 | patch_embeddings = mx.flatten(patch_embeddings, start_axis=1, end_axis=2) |
| 181 | max_nb_patches_h, max_nb_patches_w = ( |
| 182 | H // self.patch_size, |
| 183 | W // self.patch_size, |
| 184 | ) |
| 185 | boundaries = np.linspace( |
| 186 | 1 / self.num_patches, 1.0, self.num_patches, endpoint=False |
| 187 | ) |
| 188 | position_ids = np.zeros((B, max_nb_patches_h * max_nb_patches_w), dtype=int) |
| 189 | |
| 190 | for batch_idx, p_attn_mask in enumerate(mask): |
| 191 | p_attn_mask = np.array(p_attn_mask) |
| 192 | nb_patches_h = p_attn_mask[:, 0].sum() |
| 193 | nb_patches_w = p_attn_mask[0, :].sum() |
| 194 | |
| 195 | fractional_coords_h = np.linspace(0, 1, nb_patches_h, endpoint=False) |
| 196 | fractional_coords_w = np.linspace(0, 1, nb_patches_w, endpoint=False) |
| 197 | |
| 198 | bucket_coords_h = ( |
| 199 | np.digitize(fractional_coords_h, boundaries, right=True) - 1 |
| 200 | ) |
| 201 | bucket_coords_w = ( |
| 202 | np.digitize(fractional_coords_w, boundaries, right=True) - 1 |
| 203 | ) |
| 204 | |
| 205 | pos_ids = ( |
| 206 | bucket_coords_h[:, None] * self.num_patches + bucket_coords_w |
| 207 | ).flatten() |
| 208 | position_ids[batch_idx][p_attn_mask.reshape(-1)] = pos_ids |
| 209 | |
| 210 | embeddings = patch_embeddings |
| 211 | embeddings += self.position_embedding(mx.array(position_ids)) |
| 212 | return embeddings |
| 213 | |
| 214 | |
| 215 | class VisionModel(nn.Module): |
| 216 | def __init__(self, config: VisionConfig): |
| 217 | super().__init__() |
| 218 | self.config = config |
| 219 | self.model_type = config.model_type |
| 220 | if self.model_type != "idefics2": |
| 221 | raise ValueError(f"Unsupported model type: {self.model_type}") |
| 222 | self.embeddings = VisionEmbeddings(config) |
| 223 | self.encoder = Encoder(config) |
| 224 | self.post_layernorm = nn.LayerNorm(config.hidden_size) |
| 225 | |
| 226 | def __call__( |
| 227 | self, |
| 228 | x: mx.array, |
| 229 | patch_attention_mask: Optional[mx.array] = None, |
| 230 | output_hidden_states: Optional[bool] = None, |
| 231 | ) -> mx.array: |
| 232 | |
| 233 | B, L, D, C = x.shape |
| 234 | if patch_attention_mask is None: |
| 235 | patch_size = self.config.patch_size |
| 236 | patch_attention_mask = mx.ones( |
| 237 | ( |
| 238 | B, |
| 239 | L // patch_size, |
| 240 | D // patch_size, |
| 241 | ), |
| 242 | dtype=mx.bool_, |
| 243 | ) |
| 244 | |
| 245 | x = self.embeddings(x, mask=patch_attention_mask) |
| 246 | |
| 247 | encoder_outputs = self.encoder(x=x, output_hidden_states=output_hidden_states) |
| 248 | |
| 249 | pooler_output = self.post_layernorm(encoder_outputs[0]) |
| 250 | |
| 251 | return pooler_output, x, encoder_outputs[-1] |
| 252 | |
| 253 | def sanitize(self, weights): |
| 254 | sanitized_weights = {} |
| 255 | for k, v in weights.items(): |
| 256 | if "patch_embedding.weight" in k: |
| 257 | # PyTorch conv2d weight tensors have shape: |
| 258 | # [out_channels, in_channels, kH, KW] |
| 259 | # MLX conv2d expects the weight be of shape: |
| 260 | # [out_channels, kH, KW, in_channels] |
| 261 | if check_array_shape(v): |
| 262 | sanitized_weights[k] = v |
| 263 | else: |
| 264 | sanitized_weights[k] = v.transpose(0, 2, 3, 1) |
| 265 | else: |
| 266 | sanitized_weights[k] = v |
| 267 | |
| 268 | return sanitized_weights |