| 1 | import inspect |
| 2 | import math |
| 3 | from dataclasses import dataclass |
| 4 | from types import SimpleNamespace |
| 5 | from typing import Optional |
| 6 | |
| 7 | import mlx.core as mx |
| 8 | import mlx.nn as nn |
| 9 | import numpy as np |
| 10 | |
| 11 | |
| 12 | @dataclass |
| 13 | class VisionConfig: |
| 14 | model_type: str = "phi3_v" |
| 15 | num_hidden_layers: int = 24 |
| 16 | hidden_size: int = 1024 |
| 17 | intermediate_size: int = 4096 |
| 18 | num_attention_heads: int = 16 |
| 19 | image_size: int = 336 |
| 20 | patch_size: int = 14 |
| 21 | projection_dim: int = 768 |
| 22 | vocab_size: int = 32000 |
| 23 | num_channels: int = 3 |
| 24 | layer_norm_eps: float = 1e-5 |
| 25 | image_dim_out: int = (1024,) |
| 26 | model_name: str = "openai/clip-vit-large-patch14-336" |
| 27 | name: str = "clip_vision_model" |
| 28 | num_img_tokens: int = 144 |
| 29 | |
| 30 | @classmethod |
| 31 | def from_dict(cls, params): |
| 32 | return cls( |
| 33 | **{ |
| 34 | k: v |
| 35 | for k, v in params.items() |
| 36 | if k in inspect.signature(cls).parameters |
| 37 | } |
| 38 | ) |
| 39 | |
| 40 | |
| 41 | def check_array_shape(arr): |
| 42 | shape = arr.shape |
| 43 | |
| 44 | # Check if the shape has 4 dimensions |
| 45 | if len(shape) != 4: |
| 46 | return False |
| 47 | |
| 48 | out_channels, kH, KW, _ = shape |
| 49 | |
| 50 | # Check if out_channels is the largest, and kH and KW are the same |
| 51 | if (out_channels >= kH) and (out_channels >= KW) and (kH == KW): |
| 52 | return True |
| 53 | else: |
| 54 | return False |
| 55 | |
| 56 | |
| 57 | class Attention(nn.Module): |
| 58 | def __init__( |
| 59 | self, |
| 60 | dims: int, |
| 61 | num_heads: int, |
| 62 | query_input_dims: Optional[int] = None, |
| 63 | key_input_dims: Optional[int] = None, |
| 64 | value_input_dims: Optional[int] = None, |
| 65 | value_dims: Optional[int] = None, |
| 66 | value_output_dims: Optional[int] = None, |
| 67 | bias: bool = False, |
| 68 | ): |
| 69 | super().__init__() |
| 70 | |
| 71 | if (dims % num_heads) != 0: |
| 72 | raise ValueError( |
| 73 | "The input feature dimensions should be divisible by the " |
| 74 | f"number of heads ({dims} % {num_heads}) != 0" |
| 75 | ) |
| 76 | |
| 77 | query_input_dims = query_input_dims or dims |
| 78 | key_input_dims = key_input_dims or dims |
| 79 | value_input_dims = value_input_dims or key_input_dims |
| 80 | value_dims = value_dims or dims |
| 81 | value_output_dims = value_output_dims or dims |
| 82 | |
| 83 | self.num_heads = num_heads = num_heads |
| 84 | head_dim = dims // num_heads |
| 85 | self.scale = head_dim**-0.5 |
| 86 | |
| 87 | self.q_proj = nn.Linear(query_input_dims, dims, bias=bias) |
| 88 | self.k_proj = nn.Linear(key_input_dims, dims, bias=bias) |
| 89 | self.v_proj = nn.Linear(value_input_dims, value_dims, bias=bias) |
| 90 | self.out_proj = nn.Linear(value_dims, value_output_dims, bias=bias) |
| 91 | |
| 92 | def __call__(self, queries, keys, values, mask=None): |
| 93 | queries = self.q_proj(queries) |
| 94 | keys = self.k_proj(keys) |
| 95 | values = self.v_proj(values) |
| 96 | |
| 97 | num_heads = self.num_heads |
| 98 | B, L, D = queries.shape |
| 99 | _, S, _ = keys.shape |
| 100 | queries = queries.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3) |
| 101 | keys = keys.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3) |
| 102 | values = values.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3) |
| 103 | |
| 104 | output = mx.fast.scaled_dot_product_attention( |
| 105 | queries, keys, values, scale=self.scale, mask=mask |
| 106 | ) |
| 107 | output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) |
| 108 | |
| 109 | return self.out_proj(output) |
| 110 | |
| 111 | |
| 112 | class MLP(nn.Module): |
| 113 | def __init__(self, config: VisionConfig): |
| 114 | super().__init__() |
| 115 | self.activation_fn = nn.GELU(approx="fast") |
| 116 | self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size) |
| 117 | self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size) |
| 118 | |
| 119 | def __call__(self, x: mx.array) -> mx.array: |
| 120 | x = self.activation_fn(self.fc1(x)) |
| 121 | x = self.fc2(x) |
| 122 | return x |
| 123 | |
| 124 | |
| 125 | class EncoderLayer(nn.Module): |
| 126 | def __init__(self, config: VisionConfig): |
| 127 | super().__init__() |
| 128 | self.embed_dim = config.hidden_size |
| 129 | self.self_attn = Attention( |
| 130 | config.hidden_size, config.num_attention_heads, bias=True |
| 131 | ) |
| 132 | self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) |
| 133 | self.mlp = MLP(config) |
| 134 | self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) |
| 135 | |
| 136 | def __call__(self, x: mx.array, mask: Optional[mx.array] = None) -> mx.array: |
| 137 | y = self.layer_norm1(x) |
| 138 | y = self.self_attn(y, y, y, mask) |
| 139 | x = x + y |
| 140 | y = self.layer_norm2(x) |
| 141 | y = self.mlp(y) |
| 142 | return x + y |
| 143 | |
| 144 | |
| 145 | class Encoder(nn.Module): |
| 146 | def __init__(self, config: VisionConfig): |
| 147 | super().__init__() |
| 148 | self.layers = [EncoderLayer(config) for _ in range(config.num_hidden_layers)] |
| 149 | |
| 150 | |
| 151 | class VisionEmbeddings(nn.Module): |
| 152 | def __init__(self, config: VisionConfig): |
| 153 | super().__init__() |
| 154 | self.config = config |
| 155 | self.embed_dim = config.hidden_size |
| 156 | self.image_size = config.image_size |
| 157 | self.patch_size = config.patch_size |
| 158 | |
| 159 | self.class_embedding = mx.zeros((config.hidden_size,)) |
| 160 | |
| 161 | self.patch_embedding = nn.Conv2d( |
| 162 | in_channels=config.num_channels, |
| 163 | out_channels=self.embed_dim, |
| 164 | kernel_size=self.patch_size, |
| 165 | stride=self.patch_size, |
| 166 | bias=False, |
| 167 | ) |
| 168 | |
| 169 | self.num_patches = (self.image_size // self.patch_size) ** 2 |
| 170 | self.num_positions = self.num_patches + 1 |
| 171 | self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim) |
| 172 | |
| 173 | def __call__(self, x: mx.array) -> mx.array: |
| 174 | batch_size = x.shape[0] |
| 175 | patch_embeddings = self.patch_embedding(x) |
| 176 | patch_embeddings = mx.flatten(patch_embeddings, start_axis=1, end_axis=2) |
| 177 | embed_dim = patch_embeddings.shape[-1] |
| 178 | cls_embeddings = mx.broadcast_to( |
| 179 | self.class_embedding, (batch_size, 1, embed_dim) |
| 180 | ) |
| 181 | position_ids = mx.array(np.arange(self.num_positions)[None, :]) |
| 182 | |
| 183 | embeddings = mx.concatenate((cls_embeddings, patch_embeddings), axis=1) |
| 184 | embeddings += self.position_embedding(position_ids) |
| 185 | return embeddings |
| 186 | |
| 187 | |
| 188 | class ClipModel(nn.Module): |
| 189 | def __init__(self, config: VisionConfig): |
| 190 | super().__init__() |
| 191 | self.model_type = config.model_type |
| 192 | self.embeddings = VisionEmbeddings(config) |
| 193 | self.pre_layrnorm = nn.LayerNorm(config.hidden_size) |
| 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 = self.pre_layrnorm(x) |
| 204 | |
| 205 | encoder_states = (x,) if output_hidden_states else None |
| 206 | |
| 207 | for l in self.encoder.layers: |
| 208 | x = l(x, mask=None) |
| 209 | if output_hidden_states: |
| 210 | encoder_states = encoder_states + (x,) |
| 211 | |
| 212 | pooler_output = self.post_layernorm(x[:, 0, :]) |
| 213 | return pooler_output, x, encoder_states |
| 214 | |
| 215 | |
| 216 | class ClipVModel(nn.Module): |
| 217 | def __init__(self, config): |
| 218 | super().__init__() |
| 219 | self.model_type = config.model_type |
| 220 | self.vision_model = ClipModel(config) |
| 221 | |
| 222 | |
| 223 | class VisionModel(nn.Module): |
| 224 | CLIP_VIT_LARGE_PATCH14_336_CONFIG = SimpleNamespace( |
| 225 | model_type="phi3_v", |
| 226 | hidden_size=1024, |
| 227 | image_size=336, |
| 228 | intermediate_size=4096, |
| 229 | layer_norm_eps=1e-05, |
| 230 | num_attention_heads=16, |
| 231 | num_channels=3, |
| 232 | num_hidden_layers=24, |
| 233 | patch_size=14, |
| 234 | ) |
| 235 | |
| 236 | def __init__(self, config): |
| 237 | super().__init__() |
| 238 | self.model_type = config.model_type |
| 239 | self.img_processor = ClipVModel(self.CLIP_VIT_LARGE_PATCH14_336_CONFIG) |
| 240 | self.image_dim_out = image_dim_out = 1024 |
| 241 | self.glb_GN = mx.zeros([1, 1, image_dim_out * 4]) |
| 242 | self.sub_GN = mx.zeros([1, 1, 1, image_dim_out * 4]) |
| 243 | self.img_projection = [ |
| 244 | nn.Linear(image_dim_out * 4, config.hidden_size), |
| 245 | nn.GELU(), |
| 246 | nn.Linear(config.hidden_size, config.hidden_size), |
| 247 | ] |
| 248 | |
| 249 | def __call__( |
| 250 | self, |
| 251 | img_embeds, |
| 252 | txt_embeds=None, |
| 253 | img_sizes=None, |
| 254 | positions=None, |
| 255 | output_hidden_states=None, |
| 256 | ): |
| 257 | if output_hidden_states: |
| 258 | return self.img_processor.vision_model( |
| 259 | img_embeds, output_hidden_states=output_hidden_states |
| 260 | ) |
| 261 | img_embeds = mx.array(img_embeds) |
| 262 | img_sizes = mx.array(img_sizes) |
| 263 | B = img_embeds.shape[0] |
| 264 | img_sizes = (img_sizes // 336).tolist() |
| 265 | img_features = self.img_processor.vision_model( |
| 266 | img_embeds.reshape(-1, *img_embeds.shape[2:]).transpose(0, 2, 3, 1), True |
| 267 | )[-1][-2][:, 1:] |
| 268 | img_features = img_features.reshape(B, -1, *img_features.shape[1:]) |
| 269 | C, H = self.image_dim_out, int(img_features.shape[2] ** 0.5) |
| 270 | output_imgs, output_len = [], [] |
| 271 | for _bs in range(B): |
| 272 | h, w = img_sizes[_bs] |
| 273 | B_ = h * w |
| 274 | |
| 275 | def _reshape_and_concatenate(img, shape, tile_shape): |
| 276 | return mx.concatenate( |
| 277 | [ |
| 278 | img.reshape(shape) |
| 279 | .transpose(0, 1, 3, 2, 4, 5) |
| 280 | .reshape(tile_shape), |
| 281 | mx.tile(self.sub_GN, (1, tile_shape[1], 1, 1)), |
| 282 | ], |
| 283 | axis=2, |
| 284 | ).reshape(1, -1, 4 * C) |
| 285 | |
| 286 | glb_img = _reshape_and_concatenate( |
| 287 | img_features[_bs, :1], |
| 288 | (1, H // 2, 2, H // 2, 2, C), |
| 289 | (1, H // 2, H // 2, 4 * C), |
| 290 | ) |
| 291 | sub_img = _reshape_and_concatenate( |
| 292 | img_features[_bs, 1 : B_ + 1], |
| 293 | (B_, H // 2, 2, H // 2, 2, C), |
| 294 | (1, h * 12, w * 12, 4 * C), |
| 295 | ) |
| 296 | x = mx.concatenate([sub_img, self.glb_GN, glb_img], axis=1) |
| 297 | for l in self.img_projection: |
| 298 | x = l(x) |
| 299 | output_imgs.append(np.array(x.astype(mx.float32))) |
| 300 | output_len.append(int((h * w + 1) * 144 + 1 + (h + 1) * 12)) |
| 301 | idx = 0 |
| 302 | txt_embeds = np.array(txt_embeds.astype(mx.float32)) |
| 303 | for i, cnt in enumerate(output_len): |
| 304 | txt_embeds[ |
| 305 | positions[idx][0], positions[idx][1] : positions[idx][1] + cnt |
| 306 | ] = output_imgs[i] |
| 307 | idx += cnt |
| 308 | txt_embeds = mx.array(txt_embeds) |
| 309 | return txt_embeds |
| 310 | |
| 311 | def sanitize(self, weights): |
| 312 | sanitized_weights = {} |
| 313 | for k, v in weights.items(): |
| 314 | if "position_ids" in k: |
| 315 | continue |
| 316 | elif "patch_embedding.weight" in k: |
| 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 |