Elffuss BraidHub

kikocis/mlx-vlm public

main · 8.3 KiBRawPermalink
1import inspect
2import math
3from dataclasses import dataclass
4from typing import Optional
5
6import mlx.core as mx
7import mlx.nn as nn
8import numpy as np
9
10
11@dataclass
12class VisionConfig:
13 model_type: str
14 num_hidden_layers: int = 24
15 hidden_size: int = 1024
16 intermediate_size: int = 4096
17 num_attention_heads: int = 16
18 image_size: int = 336
19 patch_size: int = 14
20 projection_dim: int = 768
21 vocab_size: int = 32000
22 num_channels: int = 3
23 layer_norm_eps: float = 1e-5
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
36def 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
52class Attention(nn.Module):
53 def __init__(
54 self,
55 dims: int,
56 num_heads: int,
57 query_input_dims: Optional[int] = None,
58 key_input_dims: Optional[int] = None,
59 value_input_dims: Optional[int] = None,
60 value_dims: Optional[int] = None,
61 value_output_dims: Optional[int] = None,
62 bias: bool = False,
63 ):
64 super().__init__()
65
66 if (dims % num_heads) != 0:
67 raise ValueError(
68 "The input feature dimensions should be divisible by the "
69 f"number of heads ({dims} % {num_heads}) != 0"
70 )
71
72 query_input_dims = query_input_dims or dims
73 key_input_dims = key_input_dims or dims
74 value_input_dims = value_input_dims or key_input_dims
75 value_dims = value_dims or dims
76 value_output_dims = value_output_dims or dims
77
78 self.num_heads = num_heads = num_heads
79 head_dim = dims // num_heads
80 self.scale = head_dim**-0.5
81
82 self.q_proj = nn.Linear(query_input_dims, dims, bias=bias)
83 self.k_proj = nn.Linear(key_input_dims, dims, bias=bias)
84 self.v_proj = nn.Linear(value_input_dims, value_dims, bias=bias)
85 self.out_proj = nn.Linear(value_dims, value_output_dims, bias=bias)
86
87 def __call__(self, queries, keys, values, mask=None):
88 queries = self.q_proj(queries)
89 keys = self.k_proj(keys)
90 values = self.v_proj(values)
91
92 num_heads = self.num_heads
93 B, L, D = queries.shape
94 _, S, _ = keys.shape
95 queries = queries.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3)
96 keys = keys.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3)
97 values = values.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3)
98
99 output = mx.fast.scaled_dot_product_attention(
100 queries, keys, values, scale=self.scale, mask=mask
101 )
102 output = output.transpose(0, 2, 1, 3).reshape(B, L, -1)
103
104 return self.out_proj(output)
105
106
107class MLP(nn.Module):
108 def __init__(self, config: VisionConfig):
109 super().__init__()
110 self.activation_fn = nn.GELU(approx="fast")
111 self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
112 self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
113
114 def __call__(self, x: mx.array) -> mx.array:
115 x = self.activation_fn(self.fc1(x))
116 x = self.fc2(x)
117 return x
118
119
120class EncoderLayer(nn.Module):
121 def __init__(self, config: VisionConfig):
122 super().__init__()
123 self.embed_dim = config.hidden_size
124 self.self_attn = Attention(
125 config.hidden_size, config.num_attention_heads, bias=True
126 )
127 self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
128 self.mlp = MLP(config)
129 self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
130
131 def __call__(self, x: mx.array, mask: Optional[mx.array] = None) -> mx.array:
132 y = self.layer_norm1(x)
133 y = self.self_attn(y, y, y, mask)
134 x = x + y
135 y = self.layer_norm2(x)
136 y = self.mlp(y)
137 return x + y
138
139
140class Encoder(nn.Module):
141 def __init__(self, config: VisionConfig):
142 super().__init__()
143 self.layers = [EncoderLayer(config) for _ in range(config.num_hidden_layers)]
144
145
146class VisionEmbeddings(nn.Module):
147 def __init__(self, config: VisionConfig):
148 super().__init__()
149 self.config = config
150 self.embed_dim = config.hidden_size
151 self.image_size = config.image_size
152 self.patch_size = config.patch_size
153
154 if config.model_type == "siglip_vision_model":
155 bias = True
156 self.class_embedding = None
157 else:
158 bias = False
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=bias,
167 )
168
169 self.num_patches = (self.image_size // self.patch_size) ** 2
170 self.num_positions = (
171 self.num_patches + 1
172 if config.model_type == "clip_vision_model"
173 else self.num_patches
174 )
175 self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
176
177 def __call__(self, x: mx.array) -> mx.array:
178 batch_size = x.shape[0]
179 patch_embeddings = self.patch_embedding(x)
180 patch_embeddings = mx.flatten(patch_embeddings, start_axis=1, end_axis=2)
181 if self.config.model_type == "siglip_vision_model":
182 embeddings = patch_embeddings
183 else:
184 embed_dim = patch_embeddings.shape[-1]
185 cls_embeddings = mx.broadcast_to(
186 self.class_embedding, (batch_size, 1, embed_dim)
187 )
188 embeddings = mx.concatenate((cls_embeddings, patch_embeddings), axis=1)
189
190 position_ids = mx.array(np.arange(self.num_positions)[None, :])
191
192 embeddings += self.position_embedding(position_ids)
193 return embeddings
194
195
196class ClipVisionModel(nn.Module):
197 def __init__(self, config: VisionConfig):
198 super().__init__()
199 self.config = config
200 self.embeddings = VisionEmbeddings(config)
201 if self.config.model_type == "clip_vision_model":
202 self.pre_layrnorm = nn.LayerNorm(config.hidden_size)
203 self.encoder = Encoder(config)
204 self.post_layernorm = nn.LayerNorm(config.hidden_size)
205
206 def __call__(
207 self,
208 x: mx.array,
209 output_hidden_states: Optional[bool] = None,
210 ) -> mx.array:
211 x = self.embeddings(x)
212 if self.config.model_type == "clip_vision_model":
213 x = self.pre_layrnorm(x)
214
215 encoder_states = (x,) if output_hidden_states else None
216
217 for l in self.encoder.layers:
218 x = l(x, mask=None)
219 if output_hidden_states:
220 encoder_states = encoder_states + (x,)
221
222 pooler_output = self.post_layernorm(x[:, 0, :])
223 return pooler_output, x, encoder_states
224
225
226class VisionModel(nn.Module):
227 def __init__(self, config: VisionConfig):
228 super().__init__()
229
230 self.model_type = config.model_type
231 if self.model_type not in ["clip_vision_model", "siglip_vision_model"]:
232 raise ValueError(f"Unsupported model type: {self.model_type}")
233
234 self.vision_model = ClipVisionModel(config)
235
236 def __call__(
237 self, x: mx.array, output_hidden_states: Optional[bool] = None
238 ) -> mx.array:
239 return self.vision_model(x, output_hidden_states)
240
241 def sanitize(self, weights):
242 sanitized_weights = {}
243 for k, v in weights.items():
244 if "position_ids" in k:
245 # Remove unused position_ids
246 continue
247 elif "patch_embedding.weight" in k:
248 # PyTorch conv2d weight tensors have shape:
249 # [out_channels, in_channels, kH, KW]
250 # MLX conv2d expects the weight be of shape:
251 # [out_channels, kH, KW, in_channels]
252 if check_array_shape(v):
253 sanitized_weights[k] = v
254 else:
255 sanitized_weights[k] = v.transpose(0, 2, 3, 1)
256 else:
257 sanitized_weights[k] = v
258
259 return sanitized_weights