Elffuss BraidHub

kikocis/mlx-vlm public

main · 16.6 KiBRawPermalink
1import inspect
2import math
3from collections import OrderedDict
4from dataclasses import dataclass, field
5from typing import List, Optional, Tuple, Union
6
7import mlx.core as mx
8import mlx.nn as nn
9
10
11@dataclass
12class VisionConfig:
13 """Configuration class for Florence2 Vision model (DaViT)."""
14
15 model_type: str = "davit"
16 in_chans: int = 3
17 num_classes: int = 1000
18 depths: List[int] = field(default_factory=lambda: [1, 1, 9, 1])
19 dim_embed: List[int] = field(default_factory=lambda: [128, 256, 512, 1024])
20 num_heads: List[int] = field(default_factory=lambda: [4, 8, 16, 32])
21 num_groups: List[int] = field(default_factory=lambda: [4, 8, 16, 32])
22 window_size: int = 12
23 mlp_ratio: float = 4.0
24 drop_path_rate: float = 0.1
25 patch_size: List[int] = field(default_factory=lambda: [7, 3, 3, 3])
26 patch_stride: List[int] = field(default_factory=lambda: [4, 2, 2, 2])
27 patch_padding: List[int] = field(default_factory=lambda: [3, 1, 1, 1])
28 patch_prenorm: List[bool] = field(
29 default_factory=lambda: [False, False, False, False]
30 )
31 qkv_bias: bool = True
32 conv_at_attn: bool = True
33 conv_at_ffn: bool = True
34 hidden_size: int = 768
35 image_size: Tuple[int, int] = (768, 768)
36
37 @classmethod
38 def from_dict(cls, params):
39 return cls(
40 **{
41 k: v
42 for k, v in params.items()
43 if k in inspect.signature(cls).parameters
44 }
45 )
46
47
48def check_array_shape(arr):
49 shape = arr.shape
50
51 # Check if the shape has 4 dimensions
52 if len(shape) != 4:
53 return False
54
55 out_channels, kH, KW, _ = shape
56
57 # Check if out_channels is the largest, and kH and KW are the same
58 if (out_channels >= kH) and (out_channels >= KW) and (kH == KW):
59 return True
60 else:
61 return False
62
63
64class MlpFC(nn.Module):
65 """MLP FC module"""
66
67 def __init__(
68 self,
69 in_features: int,
70 hidden_features: Optional[int] = None,
71 out_features: Optional[int] = None,
72 ):
73 super().__init__()
74 self.fc1 = nn.Linear(in_features, hidden_features)
75 self.fc2 = nn.Linear(hidden_features, out_features)
76 self.gelu = nn.GELU()
77
78 def __call__(self, x):
79 return self.fc2(self.gelu(self.fc1(x)))
80
81
82class Mlp(nn.Module):
83 """MLP module"""
84
85 def __init__(
86 self,
87 in_features: int,
88 hidden_features: Optional[int] = None,
89 out_features: Optional[int] = None,
90 ):
91 super().__init__()
92 out_features = out_features or in_features
93 hidden_features = hidden_features or in_features
94
95 self.net = MlpFC(in_features, hidden_features, out_features)
96
97 def __call__(self, x, size):
98 return self.net(x), size
99
100
101class DepthWiseConv2d(nn.Module):
102 """Depthwise Convolution"""
103
104 def __init__(
105 self,
106 dim_in: int,
107 kernel_size: int,
108 padding: int,
109 stride: int,
110 bias: bool = True,
111 ):
112 super().__init__()
113
114 self.dw = nn.Conv2d(
115 dim_in,
116 dim_in,
117 kernel_size=kernel_size,
118 padding=padding,
119 stride=stride,
120 bias=bias,
121 groups=dim_in,
122 )
123
124 def __call__(self, x, size):
125 B, N, C = x.shape
126 H, W = size
127 assert N == H * W
128
129 x = self.dw(x.reshape(B, H, W, C))
130
131 x = x.transpose(0, 3, 1, 2)
132
133 size = (x.shape[-2], x.shape[-1])
134 x = x.flatten(2).transpose(0, 2, 1)
135 return x, size
136
137
138class ConvEmbed(nn.Module):
139 """Image to Patch Embedding"""
140
141 def __init__(
142 self,
143 patch_size: int = 7,
144 in_chans: int = 3,
145 embed_dim: int = 64,
146 stride: int = 4,
147 padding: int = 2,
148 norm_layer: Optional[nn.Module] = None,
149 pre_norm: bool = True,
150 ):
151 super().__init__()
152 self.proj = nn.Conv2d(
153 in_chans, embed_dim, kernel_size=patch_size, stride=stride, padding=padding
154 )
155
156 if norm_layer and pre_norm:
157 self.norm = norm_layer(in_chans)
158 elif norm_layer:
159 self.norm = norm_layer(embed_dim)
160 else:
161 self.norm = None
162
163 self.pre_norm = pre_norm
164
165 def __call__(self, x, size):
166 H, W = size
167 if len(x.shape) == 3:
168
169 if self.norm and self.pre_norm:
170 x = self.norm(x)
171
172 x = x.reshape(-1, H, W, x.shape[-1])
173 else:
174 x = x.transpose(0, 2, 3, 1)
175
176 x = self.proj(x)
177
178 B, H, W, C = x.shape
179
180 x = x.reshape(B, H * W, C)
181
182 if self.norm and not self.pre_norm:
183 x = self.norm(x)
184
185 return x, (H, W)
186
187
188class ChannelAttention(nn.Module):
189 """Channel Attention module"""
190
191 def __init__(self, dim: int, groups: int = 8, qkv_bias: bool = True):
192 super().__init__()
193 self.groups = groups
194 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
195 self.proj = nn.Linear(dim, dim)
196
197 def __call__(self, x, size):
198 B, N, C = x.shape
199
200 qkv = self.qkv(x).reshape(B, N, 3, self.groups, C // self.groups)
201 qkv = qkv.transpose(2, 0, 3, 1, 4)
202 q, k, v = qkv[0], qkv[1], qkv[2] # Each has shape (B, groups, N, C//groups)
203
204 q = q * (float(N) ** -0.5)
205
206 # For multi-head attention, we need to keep the groups dimension
207 attention = mx.matmul(q.transpose(0, 1, 3, 2), k) # (B, groups, N, N)
208 attention = mx.softmax(attention, axis=-1)
209
210 x = mx.matmul(attention, v.transpose(0, 1, 3, 2)).transpose(
211 0, 1, 3, 2
212 ) # (B, groups, N, C//groups)
213 x = x.transpose(0, 2, 1, 3).reshape(B, N, C)
214 x = self.proj(x)
215
216 return x, size
217
218
219def window_partition(x: mx.array, window_size: int):
220 """Partition into non-overlapping windows"""
221 B, H, W, C = x.shape
222 x = mx.reshape(
223 x, (B, H // window_size, window_size, W // window_size, window_size, C)
224 )
225 windows = mx.reshape(
226 mx.transpose(x, (0, 1, 3, 2, 4, 5)), (-1, window_size, window_size, C)
227 )
228 return windows
229
230
231def window_reverse(
232 windows: mx.array, batch_size: int, window_size: int, H: int, W: int
233):
234 """Merge windows back to feature map"""
235 B = batch_size
236 x = mx.reshape(
237 windows, (B, H // window_size, W // window_size, window_size, window_size, -1)
238 )
239 x = mx.reshape(mx.transpose(x, (0, 1, 3, 2, 4, 5)), (B, H, W, -1))
240 return x
241
242
243class WindowAttention(nn.Module):
244 """Window based multi-head self attention module"""
245
246 def __init__(
247 self, dim: int, num_heads: int, window_size: int, qkv_bias: bool = True
248 ):
249 super().__init__()
250 self.dim = dim
251 self.window_size = window_size
252 self.num_heads = num_heads
253 head_dim = dim // num_heads
254 self.scale = float(head_dim) ** -0.5
255
256 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
257 self.proj = nn.Linear(dim, dim)
258
259 def __call__(self, x, size):
260 H, W = size
261 B, L, C = x.shape
262
263 assert L == H * W, f"input feature has wrong size {L} == {H * W}"
264
265 x = mx.reshape(x, (B, H, W, C))
266
267 # Calculate padding
268 pad_l = pad_t = 0
269 pad_r = (self.window_size - W % self.window_size) % self.window_size
270 pad_b = (self.window_size - H % self.window_size) % self.window_size
271
272 # MLX padding
273 x = mx.pad(x, [(0, 0), (pad_t, pad_b), (pad_l, pad_r), (0, 0)])
274
275 _, Hp, Wp, _ = x.shape
276
277 # Window partition
278 x = window_partition(x, self.window_size)
279 x = mx.reshape(x, (-1, self.window_size * self.window_size, C))
280
281 # Multi-head self attention
282 B_, N, C = x.shape
283 qkv = mx.reshape(self.qkv(x), (B_, N, 3, self.num_heads, C // self.num_heads))
284 qkv = mx.transpose(qkv, (2, 0, 3, 1, 4))
285 q, k, v = qkv[0], qkv[1], qkv[2]
286
287 # Scaled dot-product attention
288 q = q * self.scale
289 attn = mx.matmul(q, mx.transpose(k, (0, 1, 3, 2)))
290 attn = mx.softmax(attn, axis=-1)
291
292 x = mx.reshape(mx.transpose(mx.matmul(attn, v), (0, 2, 1, 3)), (B_, N, C))
293 x = self.proj(x)
294
295 # Merge windows
296 x = mx.reshape(x, (-1, self.window_size, self.window_size, C))
297 x = window_reverse(x, B, self.window_size, Hp, Wp)
298
299 if pad_r > 0 or pad_b > 0:
300 x = x[:, :H, :W, :]
301
302 x = mx.reshape(x, (B, H * W, C))
303 return x, size
304
305
306class PreNorm(nn.Module):
307 """Pre-normalization module"""
308
309 def __init__(self, norm, fn, drop_path=None):
310 super().__init__()
311 self.norm = norm
312 self.fn = fn
313 self.drop_path = drop_path
314
315 def __call__(self, x, size):
316 shortcut = x
317 if self.norm is not None:
318 x = self.norm(x)
319 x, size = self.fn(x, size)
320
321 if self.drop_path is not None:
322 x = self.drop_path(x)
323
324 x = shortcut + x
325 return x, size
326
327
328class DropPath(nn.Module):
329 """Drop paths (Stochastic Depth) per sample."""
330
331 def __init__(self, drop_prob: float = 0.0):
332 super().__init__()
333 self.drop_prob = drop_prob
334
335 def __call__(self, x):
336 if self.drop_prob == 0.0 or not self.training:
337 return x
338
339 keep_prob = 1 - self.drop_prob
340 shape = (x.shape[0],) + (1,) * (x.ndim - 1)
341 random_tensor = keep_prob + mx.random.uniform(shape)
342 random_tensor = mx.floor(random_tensor)
343 output = x * random_tensor / keep_prob
344 return output
345
346
347class SpatialBlock(nn.Module):
348 """Spatial attention block"""
349
350 def __init__(
351 self,
352 dim: int,
353 num_heads: int,
354 window_size: int,
355 mlp_ratio: float = 4.0,
356 qkv_bias: bool = True,
357 drop_path_rate: float = 0.0,
358 conv_at_attn: bool = True,
359 conv_at_ffn: bool = True,
360 ):
361 super().__init__()
362
363 drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else None
364
365 self.conv1 = (
366 PreNorm(None, DepthWiseConv2d(dim, 3, 1, 1), None) if conv_at_attn else None
367 )
368
369 self.window_attn = PreNorm(
370 nn.LayerNorm(dim),
371 WindowAttention(dim, num_heads, window_size, qkv_bias=qkv_bias),
372 drop_path,
373 )
374
375 self.conv2 = (
376 PreNorm(None, DepthWiseConv2d(dim, 3, 1, 1), None) if conv_at_ffn else None
377 )
378
379 self.ffn = PreNorm(
380 nn.LayerNorm(dim),
381 Mlp(
382 in_features=dim, hidden_features=int(dim * mlp_ratio), out_features=dim
383 ),
384 drop_path,
385 )
386
387 def __call__(self, x, size):
388 if self.conv1 is not None:
389 x, size = self.conv1(x, size)
390 x, size = self.window_attn(x, size)
391
392 if self.conv2 is not None:
393 x, size = self.conv2(x, size)
394 x, size = self.ffn(x, size)
395 return x, size
396
397
398class ChannelBlock(nn.Module):
399 """Channel attention block"""
400
401 def __init__(
402 self,
403 dim: int,
404 groups: int,
405 mlp_ratio: float = 4.0,
406 qkv_bias: bool = True,
407 drop_path_rate: float = 0.0,
408 conv_at_attn: bool = True,
409 conv_at_ffn: bool = True,
410 ):
411 super().__init__()
412
413 drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else None
414
415 self.conv1 = (
416 PreNorm(None, DepthWiseConv2d(dim, 3, 1, 1), None) if conv_at_attn else None
417 )
418
419 self.channel_attn = PreNorm(
420 nn.LayerNorm(dim),
421 ChannelAttention(dim, groups=groups, qkv_bias=qkv_bias),
422 drop_path,
423 )
424
425 self.conv2 = (
426 PreNorm(None, DepthWiseConv2d(dim, 3, 1, 1), None) if conv_at_ffn else None
427 )
428
429 self.ffn = PreNorm(
430 nn.LayerNorm(dim),
431 Mlp(
432 in_features=dim, hidden_features=int(dim * mlp_ratio), out_features=dim
433 ),
434 drop_path,
435 )
436
437 def __call__(self, x, size):
438 if self.conv1 is not None:
439 x, size = self.conv1(x, size)
440 x, size = self.channel_attn(x, size)
441
442 if self.conv2 is not None:
443 x, size = self.conv2(x, size)
444 x, size = self.ffn(x, size)
445
446 return x, size
447
448
449class Block(nn.Module):
450 def __init__(
451 self,
452 dim: int,
453 num_heads: int,
454 num_groups: int,
455 window_size: int,
456 mlp_ratio: float = 4.0,
457 qkv_bias: bool = True,
458 drop_path_rate: Tuple[float, float] = (0.0, 0.0),
459 conv_at_attn: bool = True,
460 conv_at_ffn: bool = True,
461 ):
462 super().__init__()
463 self.spatial_block = SpatialBlock(
464 dim,
465 num_heads,
466 window_size,
467 drop_path_rate=drop_path_rate[0],
468 qkv_bias=qkv_bias,
469 mlp_ratio=mlp_ratio,
470 conv_at_attn=conv_at_attn,
471 conv_at_ffn=conv_at_ffn,
472 )
473 self.channel_block = ChannelBlock(
474 dim,
475 num_groups,
476 drop_path_rate=drop_path_rate[1],
477 qkv_bias=qkv_bias,
478 mlp_ratio=mlp_ratio,
479 conv_at_attn=conv_at_attn,
480 conv_at_ffn=conv_at_ffn,
481 )
482
483 def __call__(self, x, size):
484 x, size = self.spatial_block(x, size)
485 x, size = self.channel_block(x, size)
486 return x, size
487
488
489class VisionModel(nn.Module):
490 """DaViT: Dual Attention Vision Transformer"""
491
492 def __init__(self, config: VisionConfig):
493 super().__init__()
494
495 self.num_classes = config.num_classes
496 self.model_type = config.model_type
497 self.dim_embed = config.dim_embed
498 self.num_heads = config.num_heads
499 self.num_groups = config.num_groups
500 self.num_stages = len(self.dim_embed)
501 assert self.num_stages == len(self.num_heads) == len(self.num_groups)
502
503 if self.model_type not in ["davit", ""]:
504 raise ValueError(
505 f"Model type {self.model_type} not supported. Currently only 'davit' is supported"
506 )
507
508 # Convert PyTorch's linspace to MLX equivalent
509 total_blocks = sum(config.depths) * 2
510 dpr = [
511 i * config.drop_path_rate / (total_blocks - 1) for i in range(total_blocks)
512 ]
513
514 depth_offset = 0
515 self.convs = []
516 self.blocks = []
517
518 for i in range(self.num_stages):
519
520 conv_embed = ConvEmbed(
521 patch_size=config.patch_size[i],
522 stride=config.patch_stride[i],
523 padding=config.patch_padding[i],
524 in_chans=config.in_chans if i == 0 else self.dim_embed[i - 1],
525 embed_dim=self.dim_embed[i],
526 norm_layer=nn.LayerNorm,
527 pre_norm=config.patch_prenorm[i],
528 )
529 self.convs.append(conv_embed)
530
531 block = []
532 for j in range(config.depths[i]):
533 block.append(
534 Block(
535 self.dim_embed[i],
536 config.num_heads[i],
537 config.num_groups[i],
538 config.window_size,
539 config.mlp_ratio,
540 config.qkv_bias,
541 (dpr[depth_offset + j * 2], dpr[depth_offset + j * 2 + 1]),
542 config.conv_at_attn,
543 config.conv_at_ffn,
544 )
545 )
546
547 self.blocks.append(block)
548
549 depth_offset += config.depths[i] * 2
550
551 def __call__(self, x):
552 input_size = x.shape[2:]
553
554 # Process through stages
555 for conv, blks in zip(self.convs, self.blocks):
556 x, input_size = conv(x, input_size)
557 for blk in blks:
558 x, input_size = blk(x, input_size)
559
560 return x
561
562 @staticmethod
563 def sanitize(weights):
564 sanitized_weights = {}
565 for k, v in weights.items():
566 if "position_ids" in k:
567 # Remove unused position_ids
568 continue
569 elif "convs" in k:
570 if "proj.weight" in k:
571 # PyTorch conv2d weight tensors have shape:
572 # [out_channels, in_channels, kH, KW]
573 # MLX conv2d expects the weight be of shape:
574 # [out_channels, kH, KW, in_channels]
575 if check_array_shape(v):
576 sanitized_weights[k] = v
577 else:
578 sanitized_weights[k] = v.transpose(0, 2, 3, 1)
579 else:
580 sanitized_weights[k] = v
581 elif "blocks" in k:
582 if "dw.weight" in k:
583 sanitized_weights[k] = (
584 v.transpose(0, 2, 3, 1) if v.shape[1] < v.shape[-1] else v
585 )
586 else:
587 sanitized_weights[k] = v
588 else:
589 sanitized_weights[k] = v
590
591 return sanitized_weights