Elffuss BraidHub

kikocis/mlx-vlm public

main · 14.5 KiBRawPermalink
1import inspect
2from dataclasses import dataclass, field
3from typing import Dict, List, Optional, Tuple, Union
4
5import mlx.core as mx
6import mlx.nn as nn
7
8from ..base import KVCache, LanguageModelOutput, create_attention_mask
9
10
11@dataclass
12class TextConfig:
13 model_type: str = "mllama"
14 vocab_size: int = 32000
15 hidden_size: int = 4096
16 intermediate_size: int = 14336
17 num_hidden_layers: int = 40
18 num_attention_heads: int = 32
19 num_key_value_heads: int = 8
20 hidden_act: str = "silu"
21 max_position_embeddings: int = 131072
22 initializer_range: float = 0.02
23 rms_norm_eps: float = 1e-6
24 tie_word_embeddings: bool = False
25 rope_theta: float = 10000.0
26 rope_traditional: bool = False
27 rope_scaling: Optional[Dict[str, Union[float, str]]] = None
28 cross_attention_layers: List[int] = field(
29 default_factory=lambda: [3, 8, 13, 18, 23, 28, 33, 38]
30 )
31
32 def __post_init__(self):
33 if self.num_key_value_heads is None:
34 self.num_key_value_heads = self.num_attention_heads
35
36 @classmethod
37 def from_dict(cls, params):
38 return cls(
39 **{
40 k: v
41 for k, v in params.items()
42 if k in inspect.signature(cls).parameters
43 }
44 )
45
46
47class MllamaTextCrossAttention(nn.Module):
48 def __init__(self, config: TextConfig, layer_idx: Optional[int] = None):
49 super().__init__()
50 self.config = config
51 self.hidden_size = config.hidden_size
52 self.num_heads = config.num_attention_heads
53 self.head_dim = self.hidden_size // self.num_heads
54 self.num_key_value_heads = config.num_key_value_heads
55 self.num_key_value_groups = self.num_heads // self.num_key_value_heads
56 self.layer_idx = layer_idx
57 self.scale = self.head_dim**-0.5
58 self.q_proj = nn.Linear(
59 self.hidden_size, self.num_heads * self.head_dim, bias=False
60 )
61 self.k_proj = nn.Linear(
62 self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
63 )
64 self.v_proj = nn.Linear(
65 self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
66 )
67 self.o_proj = nn.Linear(
68 self.num_heads * self.head_dim, self.hidden_size, bias=False
69 )
70
71 self.q_norm = nn.RMSNorm(self.head_dim, eps=config.rms_norm_eps)
72 self.k_norm = nn.RMSNorm(self.head_dim, eps=config.rms_norm_eps)
73
74 def __call__(
75 self,
76 hidden_states: mx.array,
77 cross_attention_states: Optional[mx.array] = None,
78 attention_mask: Optional[mx.array] = None,
79 cache: Optional[KVCache] = None,
80 ) -> mx.array:
81
82 bsz, q_len, _ = hidden_states.shape
83 query_states = (
84 self.q_proj(hidden_states)
85 .reshape(bsz, q_len, self.num_heads, self.head_dim)
86 .transpose(0, 2, 1, 3)
87 )
88 query_states = self.q_norm(query_states)
89
90 if cross_attention_states is not None:
91 key_states = (
92 self.k_proj(cross_attention_states)
93 .reshape(bsz, -1, self.num_key_value_heads, self.head_dim)
94 .transpose(0, 2, 1, 3)
95 )
96 value_states = (
97 self.v_proj(cross_attention_states)
98 .reshape(bsz, -1, self.num_key_value_heads, self.head_dim)
99 .transpose(0, 2, 1, 3)
100 )
101 key_states = self.k_norm(key_states)
102 if cache is not None:
103 key_states, value_states = cache.update_and_fetch(
104 key_states, value_states
105 )
106 else:
107 raise ValueError(
108 "Cross attention states must be provided for cross attention layer."
109 )
110
111 attn_output = mx.fast.scaled_dot_product_attention(
112 query_states,
113 key_states,
114 value_states,
115 scale=self.scale,
116 mask=attention_mask, # add a dim for batch processing
117 )
118 attn_output = attn_output.transpose(0, 2, 1, 3).reshape(
119 bsz, q_len, self.hidden_size
120 )
121 return self.o_proj(attn_output)
122
123
124class MllamaTextSelfAttention(nn.Module):
125 def __init__(self, config: TextConfig, layer_idx: int):
126 super().__init__()
127 self.config = config
128 self.hidden_size = config.hidden_size
129 self.num_heads = config.num_attention_heads
130 self.head_dim = self.hidden_size // self.num_heads
131 self.num_key_value_heads = config.num_key_value_heads
132 self.num_key_value_groups = self.num_heads // self.num_key_value_heads
133 self.scale = self.head_dim**-0.5
134 self.layer_idx = layer_idx
135
136 self.q_proj = nn.Linear(
137 self.hidden_size, self.num_heads * self.head_dim, bias=False
138 )
139 self.k_proj = nn.Linear(
140 self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
141 )
142 self.v_proj = nn.Linear(
143 self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
144 )
145 self.o_proj = nn.Linear(
146 self.num_heads * self.head_dim, self.hidden_size, bias=False
147 )
148
149 self.rope = nn.RoPE(
150 self.head_dim,
151 traditional=config.rope_traditional,
152 base=config.rope_theta,
153 scale=1,
154 )
155
156 def __call__(
157 self,
158 x: mx.array,
159 mask: Optional[mx.array] = None,
160 cache: Optional[KVCache] = None,
161 ) -> mx.array:
162 bsz, q_len, _ = x.shape
163 query_states = (
164 self.q_proj(x).reshape(bsz, q_len, self.num_heads, -1).transpose(0, 2, 1, 3)
165 )
166 key_states = (
167 self.k_proj(x)
168 .reshape(bsz, q_len, self.num_key_value_heads, -1)
169 .transpose(0, 2, 1, 3)
170 )
171 value_states = (
172 self.v_proj(x)
173 .reshape(bsz, q_len, self.num_key_value_heads, -1)
174 .transpose(0, 2, 1, 3)
175 )
176
177 if cache is not None:
178 query_states = self.rope(query_states, offset=cache.offset)
179 key_states = self.rope(key_states, offset=cache.offset)
180 key_states, value_states = cache.update_and_fetch(key_states, value_states)
181 else:
182 query_states = self.rope(query_states)
183 key_states = self.rope(key_states)
184
185 attn_output = mx.fast.scaled_dot_product_attention(
186 query_states, key_states, value_states, scale=self.scale, mask=mask
187 )
188 attn_output = attn_output.transpose(0, 2, 1, 3).reshape(
189 bsz, q_len, self.hidden_size
190 )
191 return self.o_proj(attn_output)
192
193
194class MllamaTextMLP(nn.Module):
195 def __init__(self, config: TextConfig):
196 super().__init__()
197 self.gate_proj = nn.Linear(
198 config.hidden_size, config.intermediate_size, bias=False
199 )
200 self.up_proj = nn.Linear(
201 config.hidden_size, config.intermediate_size, bias=False
202 )
203 self.down_proj = nn.Linear(
204 config.intermediate_size, config.hidden_size, bias=False
205 )
206 self.act_fn = lambda x: x * mx.sigmoid(x)
207
208 def __call__(self, x):
209 return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
210
211
212class MllamaSelfAttentionDecoderLayer(nn.Module):
213 def __init__(self, config: TextConfig, layer_idx: int):
214 super().__init__()
215 self.hidden_size = config.hidden_size
216 self.self_attn = MllamaTextSelfAttention(config, layer_idx=layer_idx)
217 self.mlp = MllamaTextMLP(config)
218 self.input_layernorm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
219 self.post_attention_layernorm = nn.RMSNorm(
220 config.hidden_size, eps=config.rms_norm_eps
221 )
222
223 def __call__(
224 self,
225 hidden_states: mx.array,
226 mask: Optional[mx.array] = None,
227 cache: Optional[KVCache] = None,
228 ) -> mx.array:
229 residual = hidden_states
230 hidden_states = self.input_layernorm(hidden_states)
231 hidden_states = self.self_attn(
232 x=hidden_states,
233 mask=mask,
234 cache=cache,
235 )
236 hidden_states = residual + hidden_states
237
238 residual = hidden_states
239 hidden_states = self.post_attention_layernorm(hidden_states)
240 hidden_states = self.mlp(hidden_states)
241 hidden_states = residual + hidden_states
242
243 return hidden_states
244
245
246class MllamaCrossAttentionDecoderLayer(nn.Module):
247 def __init__(self, config: TextConfig, layer_idx: int):
248 super().__init__()
249 self.hidden_size = config.hidden_size
250 self.cross_attn = MllamaTextCrossAttention(config, layer_idx=layer_idx)
251 self.mlp = MllamaTextMLP(config)
252 self.input_layernorm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
253 self.post_attention_layernorm = nn.RMSNorm(
254 config.hidden_size, eps=config.rms_norm_eps
255 )
256 self.cross_attn_attn_gate = mx.zeros(1)
257 self.cross_attn_mlp_gate = mx.zeros(1)
258
259 def __call__(
260 self,
261 hidden_states: mx.array,
262 cross_attention_states: mx.array,
263 attention_mask: Optional[mx.array] = None,
264 full_text_row_masked_out_mask: Optional[mx.array] = None,
265 cache: Optional[KVCache] = None,
266 ) -> mx.array:
267 residual = hidden_states
268 hidden_states = self.input_layernorm(hidden_states)
269 hidden_states = self.cross_attn(
270 hidden_states=hidden_states,
271 cross_attention_states=cross_attention_states,
272 attention_mask=attention_mask,
273 cache=cache,
274 )
275 hidden_states = residual + mx.tanh(self.cross_attn_attn_gate) * hidden_states
276
277 residual = hidden_states
278 hidden_states = self.post_attention_layernorm(hidden_states)
279 hidden_states = self.mlp(hidden_states)
280 if full_text_row_masked_out_mask is not None:
281 hidden_states = full_text_row_masked_out_mask[:, 0] * hidden_states
282 hidden_states = residual + mx.tanh(self.cross_attn_mlp_gate) * hidden_states
283
284 return hidden_states
285
286
287class MllamaTextModel(nn.Module):
288 def __init__(self, config: TextConfig):
289 super().__init__()
290 self.config = config
291 self.vocab_size = config.vocab_size
292 self.hidden_size = config.hidden_size
293
294 self.embed_tokens = nn.Embedding(config.vocab_size + 8, config.hidden_size)
295 self.layers = [
296 (
297 MllamaCrossAttentionDecoderLayer(config, layer_idx)
298 if layer_idx in config.cross_attention_layers
299 else MllamaSelfAttentionDecoderLayer(config, layer_idx)
300 )
301 for layer_idx in range(config.num_hidden_layers)
302 ]
303 self.norm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
304
305 def __call__(
306 self,
307 input_ids: Optional[mx.array] = None,
308 mask: Optional[mx.array] = None,
309 position_ids: Optional[mx.array] = None,
310 cross_attention_states: Optional[mx.array] = None,
311 cross_attention_mask: Optional[mx.array] = None,
312 full_text_row_masked_out_mask: Optional[mx.array] = None,
313 inputs_embeds: Optional[mx.array] = None,
314 cache: Optional[KVCache] = None,
315 ) -> mx.array:
316 if input_ids is not None and inputs_embeds is not None:
317 raise ValueError(
318 "You cannot specify both input_ids and inputs_embeds at the same time"
319 )
320 elif input_ids is not None:
321 batch_size, seq_length = input_ids.shape
322 inputs_embeds = self.embed_tokens(input_ids)
323 elif inputs_embeds is not None:
324 batch_size, seq_length, _ = inputs_embeds.shape
325 else:
326 raise ValueError("You have to specify either input_ids or inputs_embeds")
327
328 if position_ids is None:
329 position_ids = mx.expand_dims(mx.arange(seq_length), 0)
330 position_ids = mx.repeat(position_ids, batch_size, axis=0)
331
332 hidden_states = inputs_embeds
333
334 if cache is None:
335 cache = [None] * len(self.layers)
336
337 mask = create_attention_mask(hidden_states)
338
339 for idx, (decoder_layer, c) in enumerate(zip(self.layers, cache)):
340 if idx in self.config.cross_attention_layers:
341 if cross_attention_states is None:
342 raise ValueError(
343 f"Cross attention states must be provided for layer {idx}"
344 )
345 layer_outputs = decoder_layer(
346 hidden_states,
347 cross_attention_states=cross_attention_states,
348 attention_mask=cross_attention_mask,
349 full_text_row_masked_out_mask=full_text_row_masked_out_mask,
350 cache=c,
351 )
352 else:
353 layer_outputs = decoder_layer(
354 hidden_states,
355 mask=mask,
356 cache=c,
357 )
358 hidden_states = layer_outputs
359
360 hidden_states = self.norm(hidden_states)
361
362 return hidden_states
363
364
365class LanguageModel(nn.Module):
366 def __init__(self, config: TextConfig):
367 super().__init__()
368 self.config = config
369 self.model = MllamaTextModel(config)
370 self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
371
372 def __call__(
373 self,
374 input_ids: Optional[mx.array] = None,
375 mask: Optional[mx.array] = None,
376 cross_attention_states: Optional[mx.array] = None,
377 cross_attention_mask: Optional[mx.array] = None,
378 full_text_row_masked_out_mask: Optional[mx.array] = None,
379 inputs_embeds: Optional[mx.array] = None,
380 cache: Optional[KVCache] = None,
381 ) -> Tuple[mx.array, Optional[mx.array]]:
382
383 hidden_states = self.model(
384 input_ids=input_ids,
385 mask=mask,
386 cross_attention_states=cross_attention_states,
387 cross_attention_mask=cross_attention_mask,
388 full_text_row_masked_out_mask=full_text_row_masked_out_mask,
389 inputs_embeds=inputs_embeds,
390 cache=cache,
391 )
392
393 logits = self.lm_head(hidden_states)
394
395 return LanguageModelOutput(
396 logits=logits, cross_attention_states=cross_attention_states
397 )
398
399 @staticmethod
400 def sanitize(weights):
401 # Remove unused precomputed rotary freqs
402 return {
403 k: v for k, v in weights.items() if "self_attn.rotary_emb.inv_freq" not in k
404 }
405
406 @property
407 def layers(self):
408 return self.model.layers
409
410 @property
411 def head_dim(self):
412 return self.config.hidden_size // self.config.num_attention_heads
413
414 @property
415 def n_kv_heads(self):
416 return self.config.num_key_value_heads