Elffuss BraidHub

kikocis/mlx-vlm public

main · 7.9 KiBRawPermalink
1import inspect
2from dataclasses import dataclass
3from typing import Optional
4
5import mlx.core as mx
6import mlx.nn as nn
7import numpy as np
8
9
10@dataclass
11class VisionConfig:
12 model_type: str
13 num_hidden_layers: int
14 hidden_size: int
15 intermediate_size: int
16 num_attention_heads: int
17 patch_size: int
18 projection_dim: int
19 image_size: int = 224
20 num_channels: int = 3
21 layer_norm_eps: float = 1e-6
22
23 @classmethod
24 def from_dict(cls, params):
25 return cls(
26 **{
27 k: v
28 for k, v in params.items()
29 if k in inspect.signature(cls).parameters
30 }
31 )
32
33
34def check_array_shape(arr):
35 shape = arr.shape
36
37 # Check if the shape has 4 dimensions
38 if len(shape) != 4:
39 return False
40
41 out_channels, kH, KW, _ = shape
42
43 # Check if out_channels is the largest, and kH and KW are the same
44 if (out_channels >= kH) and (out_channels >= KW) and (kH == KW):
45 return True
46 else:
47 return False
48
49
50class Attention(nn.Module):
51 def __init__(
52 self,
53 dims: int,
54 num_heads: int,
55 query_input_dims: Optional[int] = None,
56 key_input_dims: Optional[int] = None,
57 value_input_dims: Optional[int] = None,
58 value_dims: Optional[int] = None,
59 value_output_dims: Optional[int] = None,
60 bias: bool = True,
61 ):
62 super().__init__()
63
64 if (dims % num_heads) != 0:
65 raise ValueError(
66 "The input feature dimensions should be divisible by the "
67 f"number of heads ({dims} % {num_heads}) != 0"
68 )
69
70 query_input_dims = query_input_dims or dims
71 key_input_dims = key_input_dims or dims
72 value_input_dims = value_input_dims or key_input_dims
73 value_dims = value_dims or dims
74 value_output_dims = value_output_dims or dims
75
76 self.num_heads = num_heads
77 head_dim = dims // num_heads
78 self.scale = head_dim**-0.5
79
80 self.q_proj = nn.Linear(query_input_dims, dims, bias=bias)
81 self.k_proj = nn.Linear(key_input_dims, dims, bias=bias)
82 self.v_proj = nn.Linear(value_input_dims, value_dims, bias=bias)
83 self.out_proj = nn.Linear(value_dims, value_output_dims, bias=bias)
84
85 def __call__(self, x, mask=None):
86 queries = self.q_proj(x)
87 keys = self.k_proj(x)
88 values = self.v_proj(x)
89
90 num_heads = self.num_heads
91 B, L, D = queries.shape
92 _, S, _ = keys.shape
93 queries = queries.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3)
94 keys = keys.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3)
95 values = values.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3)
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
104class FastGELUActivation(nn.Module):
105 """
106 Applies GELU approximation that is slower than QuickGELU but more accurate. See: https://github.com/hendrycks/GELUs
107 """
108
109 def __call__(self, input: mx.array) -> mx.array:
110 return (
111 0.5
112 * input
113 * (1.0 + mx.tanh(np.sqrt(2 / np.pi) * (input + 0.044715 * (input**3))))
114 )
115
116
117class MLP(nn.Module):
118 def __init__(self, config: VisionConfig):
119 super().__init__()
120 self.activation_fn = FastGELUActivation()
121 self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=True)
122 self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=True)
123
124 def __call__(self, x: mx.array) -> mx.array:
125 x = self.fc1(x)
126 x = self.activation_fn(x)
127 x = self.fc2(x)
128 return x
129
130
131class EncoderLayer(nn.Module):
132 def __init__(self, config: VisionConfig):
133 super().__init__()
134 self.embed_dim = config.hidden_size
135 self.self_attn = Attention(
136 config.hidden_size, config.num_attention_heads, bias=True
137 )
138 self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
139 self.mlp = MLP(config)
140 self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
141
142 def __call__(self, x: mx.array, mask: Optional[mx.array] = None) -> mx.array:
143 r = self.self_attn(self.layer_norm1(x), mask)
144 h = x + r
145 r = self.mlp(self.layer_norm2(h))
146 return h + r
147
148
149class Encoder(nn.Module):
150 def __init__(self, config: VisionConfig):
151 super().__init__()
152 self.layers = [EncoderLayer(config) for _ in range(config.num_hidden_layers)]
153
154 def __call__(
155 self,
156 x: mx.array,
157 output_hidden_states: Optional[bool] = None,
158 mask: Optional[mx.array] = None,
159 ) -> mx.array:
160 encoder_states = (x,) if output_hidden_states else None
161 h = x
162 for l in self.layers:
163 x = l(x, mask=mask)
164 if output_hidden_states:
165 encoder_states = encoder_states + (x,)
166
167 h = x[0]
168
169 return (h, encoder_states)
170
171
172class VisionEmbeddings(nn.Module):
173 def __init__(self, config: VisionConfig):
174 super().__init__()
175 self.config = config
176 self.embed_dim = config.hidden_size
177 self.image_size = config.image_size
178 self.patch_size = config.patch_size
179
180 self.patch_embedding = nn.Conv2d(
181 in_channels=config.num_channels,
182 out_channels=self.embed_dim,
183 kernel_size=self.patch_size,
184 stride=self.patch_size,
185 )
186
187 self.num_patches = (self.image_size // self.patch_size) ** 2
188 self.num_positions = self.num_patches
189 self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
190
191 def __call__(self, x: mx.array) -> mx.array:
192 patch_embeddings = self.patch_embedding(x)
193 patch_embeddings = mx.flatten(patch_embeddings, start_axis=1, end_axis=2)
194 position_ids = mx.array(np.arange(self.num_positions)[None, :])
195 embeddings = patch_embeddings
196 embeddings += self.position_embedding(position_ids)
197 return embeddings
198
199
200class SigLipVisionModel(nn.Module):
201 def __init__(self, config: VisionConfig):
202 super().__init__()
203 self.embeddings = VisionEmbeddings(config)
204 self.encoder = Encoder(config)
205 self.post_layernorm = nn.LayerNorm(config.hidden_size)
206
207 def __call__(
208 self,
209 x: mx.array,
210 output_hidden_states: Optional[bool] = None,
211 ) -> mx.array:
212 x = self.embeddings(x)
213
214 encoder_outputs = self.encoder(
215 x=x, output_hidden_states=output_hidden_states, mask=None
216 )
217
218 pooler_output = self.post_layernorm(encoder_outputs[0])
219
220 return pooler_output, x, encoder_outputs[-1]
221
222
223class VisionModel(nn.Module):
224 def __init__(self, config: VisionConfig):
225 super().__init__()
226 self.model_type = config.model_type
227 if self.model_type != "siglip_vision_model":
228 raise ValueError(f"Unsupported model type: {self.model_type}")
229
230 self.vision_model = SigLipVisionModel(config)
231
232 def __call__(
233 self, x: mx.array, output_hidden_states: Optional[bool] = None
234 ) -> mx.array:
235 return self.vision_model(x, output_hidden_states)
236
237 def sanitize(self, weights):
238 sanitized_weights = {}
239 for k, v in weights.items():
240 if "position_ids" in k:
241 # Remove unused position_ids
242 continue
243 elif "patch_embedding.weight" in k:
244 # PyTorch conv2d weight tensors have shape:
245 # [out_channels, in_channels, kH, KW]
246 # MLX conv2d expects the weight be of shape:
247 # [out_channels, kH, KW, in_channels]
248 if check_array_shape(v):
249 sanitized_weights[k] = v
250 else:
251 sanitized_weights[k] = v.transpose(0, 2, 3, 1)
252 else:
253 sanitized_weights[k] = v
254
255 return sanitized_weights