Elffuss BraidHub

kikocis/mlx-vlm public

main · 7.7 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 self.class_embedding = mx.zeros((config.hidden_size,))
155
156 self.patch_embedding = nn.Conv2d(
157 in_channels=config.num_channels,
158 out_channels=self.embed_dim,
159 kernel_size=self.patch_size,
160 stride=self.patch_size,
161 bias=False,
162 )
163
164 self.num_patches = (self.image_size // self.patch_size) ** 2
165 self.num_positions = self.num_patches + 1
166 self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
167
168 def __call__(self, x: mx.array) -> mx.array:
169 batch_size = x.shape[0]
170 patch_embeddings = self.patch_embedding(x)
171 patch_embeddings = mx.flatten(patch_embeddings, start_axis=1, end_axis=2)
172 embed_dim = patch_embeddings.shape[-1]
173 cls_embeddings = mx.broadcast_to(
174 self.class_embedding, (batch_size, 1, embed_dim)
175 )
176 position_ids = mx.array(np.arange(self.num_positions)[None, :])
177
178 embeddings = mx.concatenate((cls_embeddings, patch_embeddings), axis=1)
179 embeddings += self.position_embedding(position_ids)
180 return embeddings
181
182
183class ClipVisionModel(nn.Module):
184 def __init__(self, config: VisionConfig):
185 super().__init__()
186 self.embeddings = VisionEmbeddings(config)
187 self.pre_layrnorm = nn.LayerNorm(config.hidden_size)
188 self.encoder = Encoder(config)
189 self.post_layernorm = nn.LayerNorm(config.hidden_size)
190
191 def __call__(
192 self,
193 x: mx.array,
194 output_hidden_states: Optional[bool] = None,
195 ) -> mx.array:
196 x = self.embeddings(x)
197 x = self.pre_layrnorm(x)
198
199 encoder_states = (x,) if output_hidden_states else None
200
201 for l in self.encoder.layers:
202 x = l(x, mask=None)
203 if output_hidden_states:
204 encoder_states = encoder_states + (x,)
205
206 pooler_output = self.post_layernorm(x[:, 0, :])
207 return pooler_output, x, encoder_states
208
209
210class VisionModel(nn.Module):
211 def __init__(self, config: VisionConfig):
212 super().__init__()
213
214 self.model_type = config.model_type
215 if self.model_type != "clip_vision_model":
216 raise ValueError(f"Unsupported model type: {self.model_type}")
217
218 self.vision_model = ClipVisionModel(config)
219
220 def __call__(
221 self, x: mx.array, output_hidden_states: Optional[bool] = None
222 ) -> mx.array:
223 return self.vision_model(x, output_hidden_states)
224
225 def sanitize(self, weights):
226 sanitized_weights = {}
227 for k, v in weights.items():
228 if "position_ids" in k:
229 # Remove unused position_ids
230 continue
231 elif "patch_embedding.weight" in k:
232 # PyTorch conv2d weight tensors have shape:
233 # [out_channels, in_channels, kH, KW]
234 # MLX conv2d expects the weight be of shape:
235 # [out_channels, kH, KW, in_channels]
236 if check_array_shape(v):
237 sanitized_weights[k] = v
238 else:
239 sanitized_weights[k] = v.transpose(0, 2, 3, 1)
240 else:
241 sanitized_weights[k] = v
242
243 return sanitized_weights