Elffuss BraidHub

kikocis/mlx-vlm public

main · 16.8 KiBRawPermalink
1import inspect
2from dataclasses import dataclass, field
3from typing import List, Optional, Tuple
4
5import mlx.core as mx
6import mlx.nn as nn
7
8
9@dataclass
10class VisionConfig:
11 image_size: int = 560
12 patch_size: int = 14
13 num_channels: int = 3
14 hidden_size: int = 1280
15 intermediate_size: int = 5120
16 num_hidden_layers: int = 32
17 num_attention_heads: int = 16
18 max_num_tiles: int = 4
19 max_aspect_ratio_id: int = 8
20 num_global_layers: int = 8
21 norm_eps: float = 1e-5
22 attention_dropout: float = 0.0
23 hidden_dropout: float = 0.0
24 vision_output_dim: int = 7680
25 intermediate_layers_indices: List[int] = field(
26 default_factory=lambda: [3, 7, 15, 23, 30]
27 )
28 supported_aspect_ratios: Tuple[List[int]] = (
29 [1, 1],
30 [1, 2],
31 [1, 3],
32 [1, 4],
33 [2, 1],
34 [2, 2],
35 [3, 1],
36 [4, 1],
37 )
38
39 @classmethod
40 def from_dict(cls, params):
41 return cls(
42 **{
43 k: v
44 for k, v in params.items()
45 if k in inspect.signature(cls).parameters
46 }
47 )
48
49
50def check_array_shape(arr):
51 shape = arr.shape
52
53 # Check if the shape has 4 dimensions
54 if len(shape) != 4:
55 return False
56
57 out_channels, kH, KW, _ = shape
58
59 # Check if out_channels is the largest, and kH and KW are the same
60 if (out_channels >= kH) and (out_channels >= KW) and (kH == KW):
61 return True
62 else:
63 return False
64
65
66class MllamaVisionAttention(nn.Module):
67 def __init__(self, config: VisionConfig):
68 super().__init__()
69 self.embed_dim = config.hidden_size
70 self.num_heads = config.num_attention_heads
71 self.head_dim = config.hidden_size // config.num_attention_heads
72 self.scale = self.head_dim**-0.5
73
74 self.q_proj = nn.Linear(
75 self.embed_dim, self.num_heads * self.head_dim, bias=False
76 )
77 self.k_proj = nn.Linear(
78 self.embed_dim, self.num_heads * self.head_dim, bias=False
79 )
80 self.v_proj = nn.Linear(
81 self.embed_dim, self.num_heads * self.head_dim, bias=False
82 )
83 self.o_proj = nn.Linear(
84 self.num_heads * self.head_dim, self.embed_dim, bias=False
85 )
86
87 def __call__(
88 self,
89 hidden_state: mx.array,
90 attention_mask: Optional[mx.array] = None,
91 ) -> mx.array:
92 query = self.q_proj(hidden_state)
93 key = self.k_proj(hidden_state)
94 value = self.v_proj(hidden_state)
95
96 batch_size, q_seq_len, _ = query.shape
97 _, kv_seq_len, _ = key.shape
98
99 query = query.reshape(
100 batch_size, q_seq_len, self.num_heads, self.head_dim
101 ).transpose(0, 2, 1, 3)
102 key = key.reshape(
103 batch_size, kv_seq_len, self.num_heads, self.head_dim
104 ).transpose(0, 2, 1, 3)
105 value = value.reshape(
106 batch_size, kv_seq_len, self.num_heads, self.head_dim
107 ).transpose(0, 2, 1, 3)
108
109 if attention_mask is not None:
110 attention_mask = attention_mask[:, :, : key.shape[-2], :]
111
112 attn_output = mx.fast.scaled_dot_product_attention(
113 query, key, value, scale=self.scale, mask=attention_mask
114 )
115
116 attn_output = attn_output.transpose(0, 2, 1, 3)
117 attn_output = attn_output.reshape(batch_size, q_seq_len, -1)
118
119 return self.o_proj(attn_output)
120
121
122class MllamaVisionMLP(nn.Module):
123 def __init__(self, config: VisionConfig):
124 super().__init__()
125 self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=True)
126 self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=True)
127 self.gelu = nn.GELU()
128
129 def __call__(self, hidden_states: mx.array) -> mx.array:
130 hidden_states = self.fc1(hidden_states)
131 hidden_states = self.gelu(hidden_states)
132 hidden_states = self.fc2(hidden_states)
133 return hidden_states
134
135
136class MllamaVisionEncoderLayer(nn.Module):
137 def __init__(self, config: VisionConfig, is_gated: bool = False):
138 super().__init__()
139 self.hidden_size = config.hidden_size
140 self.num_attention_heads = config.num_attention_heads
141 self.is_gated = is_gated
142
143 self.self_attn = MllamaVisionAttention(config)
144 self.mlp = MllamaVisionMLP(config)
145
146 self.input_layernorm = nn.LayerNorm(self.hidden_size, eps=config.norm_eps)
147 self.post_attention_layernorm = nn.LayerNorm(
148 self.hidden_size, eps=config.norm_eps
149 )
150
151 if is_gated:
152 self.gate_attn = mx.zeros(1)
153 self.gate_ffn = mx.zeros(1)
154
155 def __call__(
156 self,
157 hidden_state: mx.array,
158 attention_mask: Optional[mx.array] = None,
159 ) -> mx.array:
160 # Self Attention
161 residual = hidden_state
162 hidden_state = self.input_layernorm(hidden_state)
163 hidden_state = self.self_attn(hidden_state, attention_mask=attention_mask)
164 if self.is_gated:
165 hidden_state = mx.tanh(self.gate_attn) * hidden_state
166 hidden_state = residual + hidden_state
167
168 # Feed forward
169 residual = hidden_state
170 hidden_state = self.post_attention_layernorm(hidden_state)
171 hidden_state = self.mlp(hidden_state)
172 if self.is_gated:
173 hidden_state = mx.tanh(self.gate_ffn) * hidden_state
174 hidden_state = residual + hidden_state
175
176 return hidden_state
177
178
179class MllamaVisionEncoder(nn.Module):
180 def __init__(self, config: VisionConfig, num_layers=32, is_gated=False):
181 super().__init__()
182 self.layers = [
183 MllamaVisionEncoderLayer(config, is_gated) for _ in range(num_layers)
184 ]
185
186 def __call__(
187 self,
188 hidden_states: mx.array,
189 attention_mask: Optional[mx.array] = None,
190 ) -> Tuple[mx.array, List[mx.array]]:
191 encoder_states = ()
192 for layer in self.layers:
193 hidden_states = layer(hidden_states, attention_mask=attention_mask)
194 encoder_states = encoder_states + (hidden_states,)
195 return hidden_states, encoder_states
196
197
198class MllamaPrecomputedAspectRatioEmbedding(nn.Module):
199 def __init__(self, config: VisionConfig, is_gated: bool = True):
200 super().__init__()
201 self.max_num_tiles = config.max_num_tiles
202 self.hidden_size = config.hidden_size
203 self.max_aspect_ratio_id = config.max_aspect_ratio_id
204 self.is_gated = is_gated
205
206 self.embedding = nn.Embedding(
207 self.max_aspect_ratio_id + 1, self.max_num_tiles * self.hidden_size
208 )
209 if is_gated:
210 self.gate = mx.zeros(1)
211
212 def __call__(self, hidden_state: mx.array, aspect_ratio_ids: mx.array) -> mx.array:
213 embeddings = self.embedding(aspect_ratio_ids)
214 embeddings = embeddings.reshape(-1, self.max_num_tiles, 1, self.hidden_size)
215
216 if self.is_gated:
217 embeddings = embeddings * mx.tanh(self.gate)
218
219 hidden_state = hidden_state + embeddings
220 return hidden_state
221
222
223class MllamaPrecomputedPositionEmbedding(nn.Module):
224 def __init__(self, config: VisionConfig):
225 super().__init__()
226 self.max_num_tiles = config.max_num_tiles
227 self.max_aspect_ratio_id = config.max_aspect_ratio_id
228 self.num_patches = (config.image_size // config.patch_size) ** 2 + 1
229 self.hidden_size = config.hidden_size
230 self.scale = config.hidden_size**-0.5
231
232 self.gate = mx.zeros(1)
233
234 # position embedding
235 self.embedding = (
236 mx.random.normal((self.num_patches, self.hidden_size)) * self.scale
237 )
238
239 # tile position embedding
240 self.tile_embedding = nn.Embedding(
241 self.max_aspect_ratio_id + 1,
242 self.max_num_tiles * self.num_patches * self.hidden_size,
243 )
244
245 def __call__(self, hidden_state: mx.array, aspect_ratio_ids: mx.array) -> mx.array:
246 # position embeddings
247 gated_position_embedding = (1 - mx.tanh(self.gate)) * self.embedding
248 hidden_state = hidden_state + gated_position_embedding.reshape(
249 1, 1, self.num_patches, self.hidden_size
250 )
251
252 # precomputed tile position embeddings
253 tile_position_embedding = self.tile_embedding(aspect_ratio_ids)
254 batch_size = hidden_state.shape[0]
255 tile_position_embedding = tile_position_embedding.reshape(
256 batch_size, self.max_num_tiles, self.num_patches, self.hidden_size
257 )
258 gated_tile_position_embedding = mx.tanh(self.gate) * tile_position_embedding
259 hidden_state = hidden_state + gated_tile_position_embedding
260
261 return hidden_state
262
263
264class VisionModel(nn.Module):
265 def __init__(self, config: VisionConfig):
266 super().__init__()
267 self.image_size = config.image_size
268 self.patch_size = config.patch_size
269 self.max_num_tiles = config.max_num_tiles
270 self.hidden_size = config.hidden_size
271 self.num_channels = config.num_channels
272 self.intermediate_layers_indices = config.intermediate_layers_indices
273
274 self.num_patches = (self.image_size // self.patch_size) ** 2 + 1
275 self.scale = config.hidden_size**-0.5
276
277 self.patch_embedding = nn.Conv2d(
278 in_channels=config.num_channels,
279 out_channels=self.hidden_size,
280 kernel_size=self.patch_size,
281 stride=self.patch_size,
282 bias=False,
283 )
284
285 self.class_embedding = mx.random.normal((self.hidden_size,)) * self.scale
286 self.gated_positional_embedding = MllamaPrecomputedPositionEmbedding(config)
287
288 self.pre_tile_positional_embedding = MllamaPrecomputedAspectRatioEmbedding(
289 config, is_gated=True
290 )
291 self.post_tile_positional_embedding = MllamaPrecomputedAspectRatioEmbedding(
292 config, is_gated=True
293 )
294
295 # layer norms
296 self.layernorm_pre = nn.LayerNorm(self.hidden_size, eps=config.norm_eps)
297 self.layernorm_post = nn.LayerNorm(self.hidden_size, eps=config.norm_eps)
298
299 # encoders
300 self.transformer = MllamaVisionEncoder(
301 config, config.num_hidden_layers, is_gated=False
302 )
303 self.global_transformer = MllamaVisionEncoder(
304 config, config.num_global_layers, is_gated=True
305 )
306
307 def __call__(
308 self,
309 pixel_values: mx.array,
310 aspect_ratio_ids: mx.array,
311 aspect_ratio_mask: mx.array,
312 ) -> mx.array:
313 batch_size, num_concurrent_media, num_tiles, num_channels, height, width = (
314 pixel_values.shape
315 )
316 aspect_ratio_ids = aspect_ratio_ids.reshape(
317 batch_size * num_concurrent_media, -1
318 )
319
320 pixel_values = pixel_values.reshape(
321 batch_size * num_concurrent_media * num_tiles, num_channels, height, width
322 )
323 # Patch embedding
324 patch_embeds = self.patch_embedding(pixel_values.moveaxis(1, 3)).moveaxis(3, 1)
325
326 hidden_state = patch_embeds.reshape(
327 patch_embeds.shape[0], patch_embeds.shape[1], -1
328 ).transpose(0, 2, 1)
329
330 # Tile embeddings
331 _, num_patches, dim = hidden_state.shape
332 hidden_state = hidden_state.reshape(
333 batch_size * num_concurrent_media, num_tiles, -1, dim
334 )
335 hidden_state = self.pre_tile_positional_embedding(
336 hidden_state, aspect_ratio_ids
337 )
338
339 # Add cls token
340 hidden_state = hidden_state.reshape(
341 batch_size * num_concurrent_media * num_tiles, num_patches, dim
342 )
343 class_embedding = mx.broadcast_to(
344 self.class_embedding,
345 (batch_size * num_concurrent_media * num_tiles, 1, dim),
346 )
347 hidden_state = mx.concatenate([class_embedding, hidden_state], axis=1)
348 num_patches += 1
349
350 # Position embeddings
351 hidden_state = hidden_state.reshape(
352 batch_size * num_concurrent_media, num_tiles, num_patches, dim
353 )
354 hidden_state = self.gated_positional_embedding(hidden_state, aspect_ratio_ids)
355
356 hidden_state = self.layernorm_pre(hidden_state)
357
358 # Compute the number of tokens to pad
359 num_padding_patches = (8 - (hidden_state.shape[-2] % 8)) % 8
360
361 # Pad the tensor
362 padding = [(0, 0), (0, 0), (0, num_padding_patches), (0, 0)]
363 hidden_state = mx.pad(hidden_state, padding)
364 slice_index = -num_padding_patches if num_padding_patches > 0 else None
365
366 # Prepare attention mask
367 attention_mask = aspect_ratio_mask.reshape(
368 batch_size * num_concurrent_media, -1
369 )
370 attention_mask = _prepare_aspect_ratio_attention_mask(
371 aspect_ratio_mask=attention_mask,
372 num_patches=self.num_patches,
373 target_length=hidden_state.shape[2],
374 )
375
376 # Apply encoder
377 hidden_state = hidden_state.reshape(
378 batch_size * num_concurrent_media, -1, self.hidden_size
379 )
380 output = self.transformer(hidden_state, attention_mask=attention_mask)
381
382 hidden_state = output[0]
383
384 hidden_state = self.layernorm_post(hidden_state)
385
386 # Apply global encoder
387 hidden_state = hidden_state.reshape(
388 batch_size * num_concurrent_media,
389 num_tiles,
390 num_patches + num_padding_patches,
391 self.hidden_size,
392 )
393 hidden_state = self.post_tile_positional_embedding(
394 hidden_state, aspect_ratio_ids
395 )
396 hidden_state = hidden_state.reshape(
397 batch_size * num_concurrent_media,
398 num_tiles * (num_patches + num_padding_patches),
399 self.hidden_size,
400 )
401 global_output = self.global_transformer(
402 hidden_state, attention_mask=attention_mask
403 )
404
405 hidden_state = global_output[0]
406
407 hidden_state = hidden_state.reshape(
408 batch_size * num_concurrent_media,
409 num_tiles,
410 num_patches + num_padding_patches,
411 dim,
412 )
413
414 hidden_state = hidden_state[:, :, :slice_index]
415 hidden_state = hidden_state.reshape(
416 batch_size, num_concurrent_media, num_tiles, num_patches, dim
417 )
418
419 # Collect intermediate layer outputs from encoder output
420 all_intermediate_hidden_states = output[1]
421 intermediate_hidden_states = mx.stack(all_intermediate_hidden_states, axis=-1)
422 intermediate_hidden_states = intermediate_hidden_states[
423 ..., self.intermediate_layers_indices
424 ]
425
426 # Remove padding from intermediate hidden states
427 intermediate_hidden_states = intermediate_hidden_states.reshape(
428 batch_size * num_concurrent_media,
429 num_tiles,
430 num_patches + num_padding_patches,
431 -1,
432 )
433 intermediate_hidden_states = intermediate_hidden_states[:, :, :slice_index]
434 intermediate_hidden_states = intermediate_hidden_states.reshape(
435 batch_size, num_concurrent_media, num_tiles, num_patches, -1
436 )
437
438 # Concatenate final hidden state and intermediate hidden states
439 hidden_state = mx.concatenate(
440 [hidden_state, intermediate_hidden_states], axis=-1
441 )
442
443 return hidden_state
444
445 @staticmethod
446 def sanitize(weights):
447 sanitized_weights = {}
448 for k, v in weights.items():
449 if "position_ids" in k:
450 # Remove unused position_ids
451 continue
452 elif "patch_embedding.weight" in k:
453 # PyTorch conv2d weight tensors have shape:
454 # [out_channels, in_channels, kH, KW]
455 # MLX conv2d expects the weight be of shape:
456 # [out_channels, kH, KW, in_channels]
457 if check_array_shape(v):
458 sanitized_weights[k] = v
459 else:
460 sanitized_weights[k] = v.transpose(0, 2, 3, 1)
461 else:
462 sanitized_weights[k] = v
463
464 return sanitized_weights
465
466
467def _prepare_aspect_ratio_attention_mask(
468 aspect_ratio_mask: mx.array,
469 num_patches: int,
470 target_length: int,
471) -> mx.array:
472 dtype = mx.float32
473 aspect_ratio_mask = aspect_ratio_mask.astype(dtype)
474
475 # Expand aspect ratio mask to target_length
476 batch_size, max_num_tiles = aspect_ratio_mask.shape
477 attention_mask = aspect_ratio_mask.reshape(batch_size, max_num_tiles, 1, 1).astype(
478 dtype
479 )
480 attention_mask = mx.tile(attention_mask, (1, 1, target_length, 1))
481
482 # Mask padding patches
483 pad_patches = target_length - num_patches
484 attention_mask[:, :, -pad_patches:] = 0
485
486 # Invert the mask (0 -> 1, 1 -> 0)
487 attention_mask = 1 - attention_mask
488
489 # Reshape to 2D and create 4D attention mask
490 # (batch_size, 1, max_num_tiles * target_length, max_num_tiles * target_length)
491 attention_mask = attention_mask.reshape(
492 batch_size, max_num_tiles * target_length, 1
493 )
494
495 min_value = -1e9
496 attention_mask = attention_mask @ attention_mask.transpose(0, 2, 1) * min_value
497 attention_mask = attention_mask[:, None, :, :]
498
499 return attention_mask