Elffuss BraidHub

kikocis/mlx-vlm public

Add support for Llama-3.2-vision & Resize image (#83)

* add resize to generate and stream

* add llama-3.2-vision

* doesn't support multi-image

* add LM output abstraction

* add tests

* formatting

* update lora docs

* use nn.rmsnorm (fix nan loss)

* add image resize

* add img resize

* add loading lora adapter config

* add mllama to the supported list

* removing np code

* remove numpy
Changeset4fc1dd1991c40fe3294b6dfd9b34fb03a55cd8fccfcdfe3b6d963b8efbb80487
AuthorPrince Canuma <prince.gdt@gmail.com> · 2024-10-18 01:51 +02:00
CommitterGitHub <noreply@github.com> · 2024-10-18 01:51 +02:00
Parentsb9a53acb9499

Browse the files at this changeset

24 files changed

modified mlx_vlm/LORA.MD +1 −0
@@ -16,6 +16,7 @@
1616 - Idefics 2
1717 - Deepseek-VL
1818 - Paligemma
19+- Mllama (Llama-3.2-vision)
1920
2021 ## Coming Soon
2122 - LLaVA-Next
modified mlx_vlm/generate.py +15 −0
@@ -36,6 +36,13 @@
3636 default=DEFAULT_IMAGE,
3737 help="URL or path of the image to process.",
3838 )
39+ parser.add_argument(
40+ "--resize-shape",
41+ type=int,
42+ nargs=2,
43+ default=None,
44+ help="Resize shape for the image.",
45+ )
3946 parser.add_argument(
4047 "--prompt",
4148 type=str,
@@ -78,6 +85,13 @@
7885
7986 prompt = apply_chat_template(processor, config, prompt, num_images=len(args.image))
8087
88+ kwargs = {}
89+ if args.resize_shape is not None:
90+ assert (
91+ len(args.resize_shape) == 2
92+ ), "Resize shape must be a tuple of two integers"
93+ kwargs["resize_shape"] = args.resize_shape
94+
8195 output = generate(
8296 model,
8397 processor,
@@ -87,6 +101,7 @@
87101 args.temp,
88102 args.max_tokens,
89103 args.verbose,
104+ **kwargs,
90105 )
91106 if not args.verbose:
92107 print(output)
modified mlx_vlm/lora.py +8 −0
@@ -65,6 +65,7 @@
6565 config,
6666 processor,
6767 image_processor=image_processor,
68+ image_resize_shape=args.image_resize_shape,
6869 )
6970
7071 logger.info(f"\033[32mSetting up LoRA\033[0m")
@@ -130,6 +131,13 @@
130131 parser.add_argument(
131132 "--split", type=str, default="train", help="Split to use for training"
132133 )
134+ parser.add_argument(
135+ "--image-resize-shape",
136+ type=int,
137+ nargs=2,
138+ default=None,
139+ help="Resize images to this shape",
140+ )
133141 parser.add_argument(
134142 "--apply-chat-template",
135143 action="store_false",
modified mlx_vlm/models/base.py +8 −1
@@ -1,5 +1,6 @@
11 from abc import ABC, abstractmethod
2-from typing import Any, Dict, Optional
2+from dataclasses import dataclass
3+from typing import Any, Dict, List, Optional
34
45 import mlx.core as mx
56 from PIL import Image
@@ -205,3 +206,9 @@
205206 else:
206207 mask = None
207208 return mask
209+
210+
211+@dataclass
212+class LanguageModelOutput:
213+ logits: mx.array
214+ cross_attention_states: Optional[List[mx.array]] = None
modified mlx_vlm/models/idefics2/language.py +3 −2
@@ -6,7 +6,7 @@
66 import mlx.core as mx
77 import mlx.nn as nn
88
9-from ..base import KVCache, create_attention_mask
9+from ..base import KVCache, LanguageModelOutput, create_attention_mask
1010
1111
1212 @dataclass
@@ -163,7 +163,8 @@
163163 for layer, c in zip(self.layers, cache):
164164 h = layer(h, mask, c)
165165
166- return self.lm_head(self.norm(h))
166+ logits = self.lm_head(self.norm(h))
167+ return LanguageModelOutput(logits=logits)
167168
168169 def sanitize(self, weights):
169170 # Remove unused precomputed rotary freqs
modified mlx_vlm/models/llava/language.py +2 −2
@@ -5,7 +5,7 @@
55 import mlx.core as mx
66 import mlx.nn as nn
77
8-from ..base import KVCache, create_attention_mask
8+from ..base import KVCache, LanguageModelOutput, create_attention_mask
99
1010
1111 @dataclass
@@ -210,7 +210,7 @@
210210 out = self.model.embed_tokens.as_linear(out)
211211 else:
212212 out = self.lm_head(out)
213- return out
213+ return LanguageModelOutput(logits=out)
214214
215215 @staticmethod
216216 def sanitize(weights):
modified mlx_vlm/models/llava_bunny/language.py +3 −3
@@ -5,7 +5,7 @@
55 import mlx.core as mx
66 import mlx.nn as nn
77
8-from ..base import KVCache, create_attention_mask
8+from ..base import KVCache, LanguageModelOutput, create_attention_mask
99
1010
1111 @dataclass
@@ -200,8 +200,8 @@
200200 inputs_embeds: Optional[mx.array] = None,
201201 mask: Optional[mx.array] = None,
202202 ):
203- out = self.model(inputs, cache=cache, inputs_embeds=inputs_embeds, mask=None)
204- return out
203+ out = self.model(inputs, cache=cache, inputs_embeds=inputs_embeds, mask=mask)
204+ return LanguageModelOutput(logits=out)
205205
206206 def sanitize(self, weights):
207207 if (
modified mlx_vlm/models/llava_next/language.py +3 −2
@@ -5,7 +5,7 @@
55 import mlx.core as mx
66 import mlx.nn as nn
77
8-from ..base import KVCache, create_attention_mask
8+from ..base import KVCache, LanguageModelOutput, create_attention_mask
99
1010
1111 @dataclass
@@ -199,7 +199,8 @@
199199 mask: Optional[mx.array] = None,
200200 ):
201201 out = self.model(inputs, cache, inputs_embeds)
202- return self.lm_head(out)
202+ logits = self.lm_head(out)
203+ return LanguageModelOutput(logits=logits)
203204
204205 @staticmethod
205206 def sanitize(weights):
added mlx_vlm/models/mllama/__init__.py +8 −0
@@ -0,0 +1,8 @@
1+from .mllama import (
2+ LanguageModel,
3+ Model,
4+ ModelConfig,
5+ TextConfig,
6+ VisionConfig,
7+ VisionModel,
8+)
added mlx_vlm/models/mllama/language.py +416 −0
@@ -0,0 +1,416 @@
1+import inspect
2+from dataclasses import dataclass, field
3+from typing import Dict, List, Optional, Tuple, Union
4+
5+import mlx.core as mx
6+import mlx.nn as nn
7+
8+from ..base import KVCache, LanguageModelOutput, create_attention_mask
9+
10+
11+@dataclass
12+class 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+
47+class 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+
124+class 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+
194+class 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+
212+class 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+
246+class 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+
287+class 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+
365+class 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
added mlx_vlm/models/mllama/mllama.py +207 −0
@@ -0,0 +1,207 @@
1+import glob
2+import inspect
3+import json
4+from dataclasses import dataclass
5+from pathlib import Path
6+from typing import Optional, Tuple
7+
8+import mlx.core as mx
9+import mlx.nn as nn
10+from huggingface_hub import snapshot_download
11+
12+from ..base import KVCache
13+from .language import LanguageModel, TextConfig
14+from .vision import VisionConfig, VisionModel
15+
16+
17+@dataclass
18+class ModelConfig:
19+ text_config: TextConfig
20+ vision_config: VisionConfig
21+ model_type: str
22+ ignore_index: int = -100
23+ image_token_index: int = 128256
24+ vision_feature_select_strategy: str = "default"
25+ vision_feature_layer: int = -2
26+ vocab_size: int = 32000
27+
28+ @classmethod
29+ def from_dict(cls, params):
30+ return cls(
31+ **{
32+ k: v
33+ for k, v in params.items()
34+ if k in inspect.signature(cls).parameters
35+ }
36+ )
37+
38+
39+class Model(nn.Module):
40+ def __init__(self, config: ModelConfig):
41+ super().__init__()
42+ self.config = config
43+ self.vision_tower = VisionModel(config.vision_config)
44+ self.language_model = LanguageModel(config.text_config)
45+ self.multi_modal_projector = nn.Linear(
46+ config.vision_config.vision_output_dim,
47+ config.text_config.hidden_size,
48+ bias=True,
49+ )
50+
51+ def __call__(
52+ self,
53+ input_ids: mx.array,
54+ pixel_values: mx.array,
55+ mask: mx.array,
56+ cache: Optional[KVCache] = None,
57+ **kwargs,
58+ ) -> Tuple[mx.array, Optional[mx.array]]:
59+
60+ aspect_ratio_ids = kwargs.pop("aspect_ratio_ids", None)
61+ aspect_ratio_mask = kwargs.pop("aspect_ratio_mask", None)
62+ cross_attention_mask = kwargs.pop("cross_attention_mask", None)
63+
64+ inputs_embeds = None
65+
66+ # Process vision input if provided
67+ if pixel_values is not None:
68+ if aspect_ratio_ids is None:
69+ raise ValueError(
70+ "`aspect_ratio_ids` must be provided if `pixel_values` is provided"
71+ )
72+
73+ vision_outputs = self.vision_tower(
74+ pixel_values=pixel_values,
75+ aspect_ratio_ids=aspect_ratio_ids,
76+ aspect_ratio_mask=aspect_ratio_mask,
77+ )
78+ cross_attention_states = vision_outputs[0]
79+
80+ cross_attention_states = self.multi_modal_projector(
81+ cross_attention_states
82+ ).reshape(
83+ -1,
84+ cross_attention_states.shape[-2],
85+ self.config.text_config.hidden_size,
86+ )
87+
88+ else:
89+ cross_attention_states = None
90+
91+ # Prepare cross attention mask
92+ if cross_attention_mask is not None:
93+ cross_attention_mask, full_text_row_masked_out_mask = (
94+ self._prepare_cross_attention_mask(
95+ cross_attention_mask,
96+ num_vision_tokens=(
97+ self.config.vision_config.image_size
98+ // self.config.vision_config.patch_size
99+ )
100+ ** 2
101+ + 1,
102+ )
103+ )
104+ else:
105+ full_text_row_masked_out_mask = None
106+
107+ if cross_attention_mask is not None:
108+ cache_position = mx.arange(input_ids.shape[1], dtype=mx.int32)
109+ cross_attention_mask = cross_attention_mask[:, :, cache_position]
110+ full_text_row_masked_out_mask = full_text_row_masked_out_mask[
111+ :, :, cache_position
112+ ]
113+
114+ # Process language input
115+ outputs = self.language_model(
116+ input_ids=input_ids,
117+ mask=mask,
118+ cross_attention_states=cross_attention_states,
119+ cross_attention_mask=cross_attention_mask,
120+ full_text_row_masked_out_mask=full_text_row_masked_out_mask,
121+ inputs_embeds=inputs_embeds,
122+ cache=cache,
123+ )
124+
125+ return outputs
126+
127+ def _prepare_cross_attention_mask(
128+ self,
129+ cross_attention_mask: mx.array,
130+ num_vision_tokens: int,
131+ ) -> Tuple[mx.array, mx.array]:
132+ batch_size, text_total_length, *_ = cross_attention_mask.shape
133+ cross_attention_mask = mx.repeat(
134+ cross_attention_mask, num_vision_tokens, axis=3
135+ )
136+ cross_attention_mask = cross_attention_mask.reshape(
137+ batch_size, text_total_length, -1
138+ )
139+ cross_attention_mask = mx.expand_dims(cross_attention_mask, 1)
140+
141+ # Invert the mask
142+ inverted_cross_attn_mask = 1.0 - cross_attention_mask
143+ fill_array = mx.array(-1e9)
144+ fill_array = mx.broadcast_to(fill_array, inverted_cross_attn_mask.shape)
145+ cross_attention_mask = mx.where(
146+ inverted_cross_attn_mask,
147+ fill_array,
148+ cross_attention_mask,
149+ )
150+
151+ # Apply full-row bias
152+ full_text_row_masked_out_mask = mx.any(
153+ cross_attention_mask != -1e9,
154+ axis=-1,
155+ keepdims=True,
156+ )
157+ cross_attention_mask *= full_text_row_masked_out_mask
158+
159+ return cross_attention_mask, full_text_row_masked_out_mask
160+
161+ @staticmethod
162+ def from_pretrained(path_or_hf_repo: str):
163+ path = Path(path_or_hf_repo)
164+ if not path.exists():
165+ path = Path(
166+ snapshot_download(
167+ repo_id=path_or_hf_repo,
168+ allow_patterns=[
169+ "*.json",
170+ "*.safetensors",
171+ "*.py",
172+ "tokenizer.model",
173+ "*.tiktoken",
174+ ],
175+ )
176+ )
177+
178+ with open(path / "config.json", "r") as f:
179+ model_config = json.load(f)
180+
181+ model_config = ModelConfig.from_dict(model_config)
182+
183+ model_config.vision_config = VisionConfig.from_dict(model_config.vision_config)
184+ model_config.text_config = TextConfig.from_dict(model_config)
185+
186+ model = Model(model_config)
187+ weight_files = glob.glob(str(path / "*.safetensors"))
188+ if not weight_files:
189+ raise FileNotFoundError(f"No safetensors found in {path}")
190+
191+ weights = {}
192+ for wf in weight_files:
193+ weights.update(mx.load(wf))
194+
195+ weights = VisionModel.sanitize(weights)
196+ weights = LanguageModel.sanitize(weights)
197+
198+ model.load_weights(list(weights.items()))
199+ return model
200+
201+ def sanitize(self, weights):
202+ def transform_key(key):
203+ if "vision_tower" not in key:
204+ key = key.replace("vision_model", "vision_tower")
205+ return key
206+
207+ return {transform_key(k): v for k, v in weights.items()}
added mlx_vlm/models/mllama/vision.py +499 −0
@@ -0,0 +1,499 @@
1+import inspect
2+from dataclasses import dataclass, field
3+from typing import List, Optional, Tuple
4+
5+import mlx.core as mx
6+import mlx.nn as nn
7+
8+
9+@dataclass
10+class VisionConfig:
11+ image_size: int = 560
12+ patch_size: int = 14
13+ num_channels: int = 3
14+ hidden_size: int = 1280
15+ intermediate_size: int = 5120
16+ num_hidden_layers: int = 32
17+ num_attention_heads: int = 16
18+ max_num_tiles: int = 4
19+ max_aspect_ratio_id: int = 8
20+ num_global_layers: int = 8
21+ norm_eps: float = 1e-5
22+ attention_dropout: float = 0.0
23+ hidden_dropout: float = 0.0
24+ vision_output_dim: int = 7680
25+ intermediate_layers_indices: List[int] = field(
26+ default_factory=lambda: [3, 7, 15, 23, 30]
27+ )
28+ supported_aspect_ratios: Tuple[List[int]] = (
29+ [1, 1],
30+ [1, 2],
31+ [1, 3],
32+ [1, 4],
33+ [2, 1],
34+ [2, 2],
35+ [3, 1],
36+ [4, 1],
37+ )
38+
39+ @classmethod
40+ def from_dict(cls, params):
41+ return cls(
42+ **{
43+ k: v
44+ for k, v in params.items()
45+ if k in inspect.signature(cls).parameters
46+ }
47+ )
48+
49+
50+def check_array_shape(arr):
51+ shape = arr.shape
52+
53+ # Check if the shape has 4 dimensions
54+ if len(shape) != 4:
55+ return False
56+
57+ out_channels, kH, KW, _ = shape
58+
59+ # Check if out_channels is the largest, and kH and KW are the same
60+ if (out_channels >= kH) and (out_channels >= KW) and (kH == KW):
61+ return True
62+ else:
63+ return False
64+
65+
66+class MllamaVisionAttention(nn.Module):
67+ def __init__(self, config: VisionConfig):
68+ super().__init__()
69+ self.embed_dim = config.hidden_size
70+ self.num_heads = config.num_attention_heads
71+ self.head_dim = config.hidden_size // config.num_attention_heads
72+ self.scale = self.head_dim**-0.5
73+
74+ self.q_proj = nn.Linear(
75+ self.embed_dim, self.num_heads * self.head_dim, bias=False
76+ )
77+ self.k_proj = nn.Linear(
78+ self.embed_dim, self.num_heads * self.head_dim, bias=False
79+ )
80+ self.v_proj = nn.Linear(
81+ self.embed_dim, self.num_heads * self.head_dim, bias=False
82+ )
83+ self.o_proj = nn.Linear(
84+ self.num_heads * self.head_dim, self.embed_dim, bias=False
85+ )
86+
87+ def __call__(
88+ self,
89+ hidden_state: mx.array,
90+ attention_mask: Optional[mx.array] = None,
91+ ) -> mx.array:
92+ query = self.q_proj(hidden_state)
93+ key = self.k_proj(hidden_state)
94+ value = self.v_proj(hidden_state)
95+
96+ batch_size, q_seq_len, _ = query.shape
97+ _, kv_seq_len, _ = key.shape
98+
99+ query = query.reshape(
100+ batch_size, q_seq_len, self.num_heads, self.head_dim
101+ ).transpose(0, 2, 1, 3)
102+ key = key.reshape(
103+ batch_size, kv_seq_len, self.num_heads, self.head_dim
104+ ).transpose(0, 2, 1, 3)
105+ value = value.reshape(
106+ batch_size, kv_seq_len, self.num_heads, self.head_dim
107+ ).transpose(0, 2, 1, 3)
108+
109+ if attention_mask is not None:
110+ attention_mask = attention_mask[:, :, : key.shape[-2], :]
111+
112+ attn_output = mx.fast.scaled_dot_product_attention(
113+ query, key, value, scale=self.scale, mask=attention_mask
114+ )
115+
116+ attn_output = attn_output.transpose(0, 2, 1, 3)
117+ attn_output = attn_output.reshape(batch_size, q_seq_len, -1)
118+
119+ return self.o_proj(attn_output)
120+
121+
122+class MllamaVisionMLP(nn.Module):
123+ def __init__(self, config: VisionConfig):
124+ super().__init__()
125+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=True)
126+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=True)
127+ self.gelu = nn.GELU()
128+
129+ def __call__(self, hidden_states: mx.array) -> mx.array:
130+ hidden_states = self.fc1(hidden_states)
131+ hidden_states = self.gelu(hidden_states)
132+ hidden_states = self.fc2(hidden_states)
133+ return hidden_states
134+
135+
136+class MllamaVisionEncoderLayer(nn.Module):
137+ def __init__(self, config: VisionConfig, is_gated: bool = False):
138+ super().__init__()
139+ self.hidden_size = config.hidden_size
140+ self.num_attention_heads = config.num_attention_heads
141+ self.is_gated = is_gated
142+
143+ self.self_attn = MllamaVisionAttention(config)
144+ self.mlp = MllamaVisionMLP(config)
145+
146+ self.input_layernorm = nn.LayerNorm(self.hidden_size, eps=config.norm_eps)
147+ self.post_attention_layernorm = nn.LayerNorm(
148+ self.hidden_size, eps=config.norm_eps
149+ )
150+
151+ if is_gated:
152+ self.gate_attn = mx.zeros(1)
153+ self.gate_ffn = mx.zeros(1)
154+
155+ def __call__(
156+ self,
157+ hidden_state: mx.array,
158+ attention_mask: Optional[mx.array] = None,
159+ ) -> mx.array:
160+ # Self Attention
161+ residual = hidden_state
162+ hidden_state = self.input_layernorm(hidden_state)
163+ hidden_state = self.self_attn(hidden_state, attention_mask=attention_mask)
164+ if self.is_gated:
165+ hidden_state = mx.tanh(self.gate_attn) * hidden_state
166+ hidden_state = residual + hidden_state
167+
168+ # Feed forward
169+ residual = hidden_state
170+ hidden_state = self.post_attention_layernorm(hidden_state)
171+ hidden_state = self.mlp(hidden_state)
172+ if self.is_gated:
173+ hidden_state = mx.tanh(self.gate_ffn) * hidden_state
174+ hidden_state = residual + hidden_state
175+
176+ return hidden_state
177+
178+
179+class MllamaVisionEncoder(nn.Module):
180+ def __init__(self, config: VisionConfig, num_layers=32, is_gated=False):
181+ super().__init__()
182+ self.layers = [
183+ MllamaVisionEncoderLayer(config, is_gated) for _ in range(num_layers)
184+ ]
185+
186+ def __call__(
187+ self,
188+ hidden_states: mx.array,
189+ attention_mask: Optional[mx.array] = None,
190+ ) -> Tuple[mx.array, List[mx.array]]:
191+ encoder_states = ()
192+ for layer in self.layers:
193+ hidden_states = layer(hidden_states, attention_mask=attention_mask)
194+ encoder_states = encoder_states + (hidden_states,)
195+ return hidden_states, encoder_states
196+
197+
198+class MllamaPrecomputedAspectRatioEmbedding(nn.Module):
199+ def __init__(self, config: VisionConfig, is_gated: bool = True):
200+ super().__init__()
201+ self.max_num_tiles = config.max_num_tiles
202+ self.hidden_size = config.hidden_size
203+ self.max_aspect_ratio_id = config.max_aspect_ratio_id
204+ self.is_gated = is_gated
205+
206+ self.embedding = nn.Embedding(
207+ self.max_aspect_ratio_id + 1, self.max_num_tiles * self.hidden_size
208+ )
209+ if is_gated:
210+ self.gate = mx.zeros(1)
211+
212+ def __call__(self, hidden_state: mx.array, aspect_ratio_ids: mx.array) -> mx.array:
213+ embeddings = self.embedding(aspect_ratio_ids)
214+ embeddings = embeddings.reshape(-1, self.max_num_tiles, 1, self.hidden_size)
215+
216+ if self.is_gated:
217+ embeddings = embeddings * mx.tanh(self.gate)
218+
219+ hidden_state = hidden_state + embeddings
220+ return hidden_state
221+
222+
223+class MllamaPrecomputedPositionEmbedding(nn.Module):
224+ def __init__(self, config: VisionConfig):
225+ super().__init__()
226+ self.max_num_tiles = config.max_num_tiles
227+ self.max_aspect_ratio_id = config.max_aspect_ratio_id
228+ self.num_patches = (config.image_size // config.patch_size) ** 2 + 1
229+ self.hidden_size = config.hidden_size
230+ self.scale = config.hidden_size**-0.5
231+
232+ self.gate = mx.zeros(1)
233+
234+ # position embedding
235+ self.embedding = (
236+ mx.random.normal((self.num_patches, self.hidden_size)) * self.scale
237+ )
238+
239+ # tile position embedding
240+ self.tile_embedding = nn.Embedding(
241+ self.max_aspect_ratio_id + 1,
242+ self.max_num_tiles * self.num_patches * self.hidden_size,
243+ )
244+
245+ def __call__(self, hidden_state: mx.array, aspect_ratio_ids: mx.array) -> mx.array:
246+ # position embeddings
247+ gated_position_embedding = (1 - mx.tanh(self.gate)) * self.embedding
248+ hidden_state = hidden_state + gated_position_embedding.reshape(
249+ 1, 1, self.num_patches, self.hidden_size
250+ )
251+
252+ # precomputed tile position embeddings
253+ tile_position_embedding = self.tile_embedding(aspect_ratio_ids)
254+ batch_size = hidden_state.shape[0]
255+ tile_position_embedding = tile_position_embedding.reshape(
256+ batch_size, self.max_num_tiles, self.num_patches, self.hidden_size
257+ )
258+ gated_tile_position_embedding = mx.tanh(self.gate) * tile_position_embedding
259+ hidden_state = hidden_state + gated_tile_position_embedding
260+
261+ return hidden_state
262+
263+
264+class VisionModel(nn.Module):
265+ def __init__(self, config: VisionConfig):
266+ super().__init__()
267+ self.image_size = config.image_size
268+ self.patch_size = config.patch_size
269+ self.max_num_tiles = config.max_num_tiles
270+ self.hidden_size = config.hidden_size
271+ self.num_channels = config.num_channels
272+ self.intermediate_layers_indices = config.intermediate_layers_indices
273+
274+ self.num_patches = (self.image_size // self.patch_size) ** 2 + 1
275+ self.scale = config.hidden_size**-0.5
276+
277+ self.patch_embedding = nn.Conv2d(
278+ in_channels=config.num_channels,
279+ out_channels=self.hidden_size,
280+ kernel_size=self.patch_size,
281+ stride=self.patch_size,
282+ bias=False,
283+ )
284+
285+ self.class_embedding = mx.random.normal((self.hidden_size,)) * self.scale
286+ self.gated_positional_embedding = MllamaPrecomputedPositionEmbedding(config)
287+
288+ self.pre_tile_positional_embedding = MllamaPrecomputedAspectRatioEmbedding(
289+ config, is_gated=True
290+ )
291+ self.post_tile_positional_embedding = MllamaPrecomputedAspectRatioEmbedding(
292+ config, is_gated=True
293+ )
294+
295+ # layer norms
296+ self.layernorm_pre = nn.LayerNorm(self.hidden_size, eps=config.norm_eps)
297+ self.layernorm_post = nn.LayerNorm(self.hidden_size, eps=config.norm_eps)
298+
299+ # encoders
300+ self.transformer = MllamaVisionEncoder(
301+ config, config.num_hidden_layers, is_gated=False
302+ )
303+ self.global_transformer = MllamaVisionEncoder(
304+ config, config.num_global_layers, is_gated=True
305+ )
306+
307+ def __call__(
308+ self,
309+ pixel_values: mx.array,
310+ aspect_ratio_ids: mx.array,
311+ aspect_ratio_mask: mx.array,
312+ ) -> mx.array:
313+ batch_size, num_concurrent_media, num_tiles, num_channels, height, width = (
314+ pixel_values.shape
315+ )
316+ aspect_ratio_ids = aspect_ratio_ids.reshape(
317+ batch_size * num_concurrent_media, -1
318+ )
319+
320+ pixel_values = pixel_values.reshape(
321+ batch_size * num_concurrent_media * num_tiles, num_channels, height, width
322+ )
323+ # Patch embedding
324+ patch_embeds = self.patch_embedding(pixel_values.moveaxis(1, 3)).moveaxis(3, 1)
325+
326+ hidden_state = patch_embeds.reshape(
327+ patch_embeds.shape[0], patch_embeds.shape[1], -1
328+ ).transpose(0, 2, 1)
329+
330+ # Tile embeddings
331+ _, num_patches, dim = hidden_state.shape
332+ hidden_state = hidden_state.reshape(
333+ batch_size * num_concurrent_media, num_tiles, -1, dim
334+ )
335+ hidden_state = self.pre_tile_positional_embedding(
336+ hidden_state, aspect_ratio_ids
337+ )
338+
339+ # Add cls token
340+ hidden_state = hidden_state.reshape(
341+ batch_size * num_concurrent_media * num_tiles, num_patches, dim
342+ )
343+ class_embedding = mx.broadcast_to(
344+ self.class_embedding,
345+ (batch_size * num_concurrent_media * num_tiles, 1, dim),
346+ )
347+ hidden_state = mx.concatenate([class_embedding, hidden_state], axis=1)
348+ num_patches += 1
349+
350+ # Position embeddings
351+ hidden_state = hidden_state.reshape(
352+ batch_size * num_concurrent_media, num_tiles, num_patches, dim
353+ )
354+ hidden_state = self.gated_positional_embedding(hidden_state, aspect_ratio_ids)
355+
356+ hidden_state = self.layernorm_pre(hidden_state)
357+
358+ # Compute the number of tokens to pad
359+ num_padding_patches = (8 - (hidden_state.shape[-2] % 8)) % 8
360+
361+ # Pad the tensor
362+ padding = [(0, 0), (0, 0), (0, num_padding_patches), (0, 0)]
363+ hidden_state = mx.pad(hidden_state, padding)
364+ slice_index = -num_padding_patches if num_padding_patches > 0 else None
365+
366+ # Prepare attention mask
367+ attention_mask = aspect_ratio_mask.reshape(
368+ batch_size * num_concurrent_media, -1
369+ )
370+ attention_mask = _prepare_aspect_ratio_attention_mask(
371+ aspect_ratio_mask=attention_mask,
372+ num_patches=self.num_patches,
373+ target_length=hidden_state.shape[2],
374+ )
375+
376+ # Apply encoder
377+ hidden_state = hidden_state.reshape(
378+ batch_size * num_concurrent_media, -1, self.hidden_size
379+ )
380+ output = self.transformer(hidden_state, attention_mask=attention_mask)
381+
382+ hidden_state = output[0]
383+
384+ hidden_state = self.layernorm_post(hidden_state)
385+
386+ # Apply global encoder
387+ hidden_state = hidden_state.reshape(
388+ batch_size * num_concurrent_media,
389+ num_tiles,
390+ num_patches + num_padding_patches,
391+ self.hidden_size,
392+ )
393+ hidden_state = self.post_tile_positional_embedding(
394+ hidden_state, aspect_ratio_ids
395+ )
396+ hidden_state = hidden_state.reshape(
397+ batch_size * num_concurrent_media,
398+ num_tiles * (num_patches + num_padding_patches),
399+ self.hidden_size,
400+ )
401+ global_output = self.global_transformer(
402+ hidden_state, attention_mask=attention_mask
403+ )
404+
405+ hidden_state = global_output[0]
406+
407+ hidden_state = hidden_state.reshape(
408+ batch_size * num_concurrent_media,
409+ num_tiles,
410+ num_patches + num_padding_patches,
411+ dim,
412+ )
413+
414+ hidden_state = hidden_state[:, :, :slice_index]
415+ hidden_state = hidden_state.reshape(
416+ batch_size, num_concurrent_media, num_tiles, num_patches, dim
417+ )
418+
419+ # Collect intermediate layer outputs from encoder output
420+ all_intermediate_hidden_states = output[1]
421+ intermediate_hidden_states = mx.stack(all_intermediate_hidden_states, axis=-1)
422+ intermediate_hidden_states = intermediate_hidden_states[
423+ ..., self.intermediate_layers_indices
424+ ]
425+
426+ # Remove padding from intermediate hidden states
427+ intermediate_hidden_states = intermediate_hidden_states.reshape(
428+ batch_size * num_concurrent_media,
429+ num_tiles,
430+ num_patches + num_padding_patches,
431+ -1,
432+ )
433+ intermediate_hidden_states = intermediate_hidden_states[:, :, :slice_index]
434+ intermediate_hidden_states = intermediate_hidden_states.reshape(
435+ batch_size, num_concurrent_media, num_tiles, num_patches, -1
436+ )
437+
438+ # Concatenate final hidden state and intermediate hidden states
439+ hidden_state = mx.concatenate(
440+ [hidden_state, intermediate_hidden_states], axis=-1
441+ )
442+
443+ return hidden_state
444+
445+ @staticmethod
446+ def sanitize(weights):
447+ sanitized_weights = {}
448+ for k, v in weights.items():
449+ if "position_ids" in k:
450+ # Remove unused position_ids
451+ continue
452+ elif "patch_embedding.weight" in k:
453+ # PyTorch conv2d weight tensors have shape:
454+ # [out_channels, in_channels, kH, KW]
455+ # MLX conv2d expects the weight be of shape:
456+ # [out_channels, kH, KW, in_channels]
457+ if check_array_shape(v):
458+ sanitized_weights[k] = v
459+ else:
460+ sanitized_weights[k] = v.transpose(0, 2, 3, 1)
461+ else:
462+ sanitized_weights[k] = v
463+
464+ return sanitized_weights
465+
466+
467+def _prepare_aspect_ratio_attention_mask(
468+ aspect_ratio_mask: mx.array,
469+ num_patches: int,
470+ target_length: int,
471+) -> mx.array:
472+ dtype = mx.float32
473+ aspect_ratio_mask = aspect_ratio_mask.astype(dtype)
474+
475+ # Expand aspect ratio mask to target_length
476+ batch_size, max_num_tiles = aspect_ratio_mask.shape
477+ attention_mask = aspect_ratio_mask.reshape(batch_size, max_num_tiles, 1, 1).astype(
478+ dtype
479+ )
480+ attention_mask = mx.tile(attention_mask, (1, 1, target_length, 1))
481+
482+ # Mask padding patches
483+ pad_patches = target_length - num_patches
484+ attention_mask[:, :, -pad_patches:] = 0
485+
486+ # Invert the mask (0 -> 1, 1 -> 0)
487+ attention_mask = 1 - attention_mask
488+
489+ # Reshape to 2D and create 4D attention mask
490+ # (batch_size, 1, max_num_tiles * target_length, max_num_tiles * target_length)
491+ attention_mask = attention_mask.reshape(
492+ batch_size, max_num_tiles * target_length, 1
493+ )
494+
495+ min_value = -1e9
496+ attention_mask = attention_mask @ attention_mask.transpose(0, 2, 1) * min_value
497+ attention_mask = attention_mask[:, None, :, :]
498+
499+ return attention_mask
modified mlx_vlm/models/multi_modality/language.py +3 −2
@@ -5,7 +5,7 @@
55 import mlx.core as mx
66 import mlx.nn as nn
77
8-from ..base import KVCache, create_attention_mask
8+from ..base import KVCache, LanguageModelOutput, create_attention_mask
99
1010
1111 @dataclass
@@ -199,7 +199,8 @@
199199 mask: Optional[mx.array] = None,
200200 ):
201201 out = self.model(inputs, cache, inputs_embeds)
202- return self.lm_head(out)
202+ logits = self.lm_head(out)
203+ return LanguageModelOutput(logits=logits)
203204
204205 @staticmethod
205206 def sanitize(weights):
modified mlx_vlm/models/paligemma/language.py +2 −2
@@ -5,7 +5,7 @@
55 import mlx.core as mx
66 import mlx.nn as nn
77
8-from ..base import KVCache, create_attention_mask
8+from ..base import KVCache, LanguageModelOutput, create_attention_mask
99
1010
1111 @dataclass
@@ -186,7 +186,7 @@
186186 ):
187187 out = self.model(inputs, cache, inputs_embeds=inputs_embeds, mask=mask)
188188 out = self.model.embed_tokens.as_linear(out)
189- return out
189+ return LanguageModelOutput(logits=out)
190190
191191 def sanitize(self, weights):
192192 return {
modified mlx_vlm/models/phi3_v/phi3_v.py +3 −2
@@ -8,7 +8,7 @@
88 import mlx.nn as nn
99 import numpy as np
1010
11-from ..base import KVCache, create_attention_mask
11+from ..base import KVCache, LanguageModelOutput, create_attention_mask
1212 from .language import LanguageModel, TextConfig
1313 from .su_rope import Phi3SuScaledRotaryEmbedding
1414 from .vision import VisionConfig, VisionModel
@@ -213,7 +213,8 @@
213213 **kwargs,
214214 ):
215215 out = self.model(inputs, pixel_values, image_sizes, cache)
216- return self.lm_head(out).astype(self.lm_head.weight.dtype)
216+ logits = self.lm_head(out).astype(self.lm_head.weight.dtype)
217+ return LanguageModelOutput(logits=logits)
217218
218219 @property
219220 def layers(self):
modified mlx_vlm/models/pixtral/language.py +3 −2
@@ -5,7 +5,7 @@
55 import mlx.core as mx
66 import mlx.nn as nn
77
8-from ..base import KVCache, create_attention_mask
8+from ..base import KVCache, LanguageModelOutput, create_attention_mask
99
1010
1111 @dataclass
@@ -198,7 +198,8 @@
198198 mask: Optional[mx.array] = None,
199199 ):
200200 out = self.model(inputs, cache, inputs_embeds)
201- return self.lm_head(out)
201+ logits = self.lm_head(out)
202+ return LanguageModelOutput(logits=logits)
202203
203204 @staticmethod
204205 def sanitize(weights):
modified mlx_vlm/models/qwen2_vl/language.py +2 −2
@@ -6,7 +6,7 @@
66 import mlx.nn as nn
77 import numpy as np
88
9-from ..base import KVCache, create_attention_mask
9+from ..base import KVCache, LanguageModelOutput, create_attention_mask
1010
1111
1212 @dataclass
@@ -301,7 +301,7 @@
301301 out = self.model.embed_tokens.as_linear(out)
302302 else:
303303 out = self.lm_head(out)
304- return out
304+ return LanguageModelOutput(logits=out)
305305
306306 @property
307307 def layers(self):
modified mlx_vlm/models/qwen2_vl/qwen2_vl.py +8 −4
@@ -3,11 +3,10 @@
33 import json
44 from dataclasses import dataclass
55 from pathlib import Path
6-from typing import Optional, Tuple
6+from typing import Optional
77
88 import mlx.core as mx
99 import mlx.nn as nn
10-import numpy as np
1110 from huggingface_hub import snapshot_download
1211
1312 from .language import LanguageModel, TextConfig
@@ -77,8 +76,13 @@
7776
7877 # Positions of <image> tokens in input_ids, assuming batch size is 1
7978 image_positions = input_ids == image_token_index
80- image_indices = np.where(image_positions)[1].tolist()
81- inputs_embeds[:, image_indices, :] = image_features.astype(mx.float32)
79+ # image_indices = mx.where(image_positions)
80+ image_features = image_features.astype(mx.float32)
81+ pad_size = inputs_embeds.shape[1] - image_features.shape[1]
82+ image_features = mx.pad(image_features, ((0, 0), (0, pad_size), (0, 0)))
83+ inputs_embeds = mx.where(
84+ image_positions[:, :, None], image_features, inputs_embeds
85+ )
8286
8387 # TODO: Add video features
8488
modified mlx_vlm/prompt_utils.py +2 −0
@@ -65,6 +65,7 @@
6565 "multi_modality": "message_with_image_token",
6666 "pixtral": "message_list_with_image_type",
6767 "paligemma": "prompt_only",
68+ "mllama": "message_list_with_image",
6869 }
6970
7071 if num_images > 1 and model_name in [
@@ -73,6 +74,7 @@
7374 "bunny-llama",
7475 "paligemma",
7576 "multi_modality",
77+ "mllama",
7678 ]:
7779 raise ValueError(
7880 f"Model {model_name} does not support multi-image chat. Please only use 1 image."
modified mlx_vlm/tests/test_models.py +78 −6
@@ -17,12 +17,14 @@
1717
1818 inputs = mx.array([[0, 1]])
1919 outputs = model(inputs)
20- self.assertEqual(outputs.shape, (batch_size, 2, vocab_size))
21- self.assertEqual(outputs.dtype, t)
22-
23- outputs = model(mx.argmax(outputs[0, -1:, :], keepdims=True), cache=None)
24- self.assertEqual(outputs.shape, (batch_size, 1, vocab_size))
25- self.assertEqual(outputs.dtype, t)
20+ logits = outputs.logits
21+ self.assertEqual(logits.shape, (batch_size, 2, vocab_size))
22+ self.assertEqual(logits.dtype, t)
23+
24+ outputs = model(mx.argmax(logits[0, -1:, :], keepdims=True), cache=None)
25+ logits = outputs.logits
26+ self.assertEqual(logits.shape, (batch_size, 1, vocab_size))
27+ self.assertEqual(logits.dtype, t)
2628
2729 def mm_projector_test_runner(
2830 self, mm_projector, vision_hidden_size, text_hidden_size
@@ -722,6 +724,76 @@
722724 grid_thw=mx.ones((1, 3)), # image temporals shape (num_images, 3)
723725 )
724726
727+ def test_mllama(self):
728+ from mlx_vlm.models import mllama
729+
730+ vision_config = mllama.VisionConfig(
731+ image_size=50,
732+ patch_size=14,
733+ num_channels=3,
734+ hidden_size=1280,
735+ intermediate_size=5120,
736+ num_hidden_layers=10,
737+ num_attention_heads=16,
738+ max_num_tiles=4,
739+ max_aspect_ratio_id=8,
740+ num_global_layers=8,
741+ norm_eps=1e-5,
742+ attention_dropout=0.0,
743+ hidden_dropout=0.0,
744+ vision_output_dim=7680,
745+ intermediate_layers_indices=[3, 7, 15, 23, 30],
746+ )
747+
748+ text_config = mllama.TextConfig(
749+ model_type="mllama",
750+ hidden_size=4096,
751+ num_hidden_layers=10,
752+ intermediate_size=14336,
753+ num_attention_heads=16,
754+ rms_norm_eps=1e-6,
755+ vocab_size=32000,
756+ )
757+
758+ model_config = mllama.ModelConfig(
759+ text_config=text_config,
760+ vision_config=vision_config,
761+ model_type="mllama",
762+ ignore_index=-100,
763+ image_token_index=128256,
764+ vision_feature_select_strategy="default",
765+ vision_feature_layer=-2,
766+ vocab_size=32000,
767+ )
768+
769+ # Create the model
770+ model = mllama.Model(model_config)
771+
772+ # Create dummy input data
773+ batch_size = 1
774+ seq_length = 5
775+ num_tiles = 4
776+ input_ids = mx.random.randint(0, 1000, (batch_size, seq_length))
777+ pixel_values = mx.random.normal((batch_size, 1, num_tiles, 3, 50, 50))
778+ mask = mx.ones((batch_size, seq_length))
779+ aspect_ratio_ids = mx.zeros((batch_size, 1), dtype=mx.int32)
780+ aspect_ratio_mask = mx.ones((batch_size, 1, num_tiles))
781+ cross_attention_mask = mx.ones((batch_size, seq_length, 1, num_tiles))
782+
783+ # Forward pass
784+ output = model(
785+ input_ids=input_ids,
786+ pixel_values=pixel_values,
787+ mask=mask,
788+ aspect_ratio_ids=aspect_ratio_ids,
789+ aspect_ratio_mask=aspect_ratio_mask,
790+ cross_attention_mask=cross_attention_mask,
791+ )
792+
793+ # Check output shape
794+ expected_shape = (batch_size, seq_length, model_config.vocab_size)
795+ self.assertEqual(output.logits.shape, expected_shape)
796+
725797
726798 if __name__ == "__main__":
727799 unittest.main()
modified mlx_vlm/tests/test_trainer.py +12 −9
@@ -1,11 +1,10 @@
11 import unittest
2-from unittest.mock import MagicMock, patch
2+from unittest.mock import MagicMock, Mock, patch
33
44 import mlx.core as mx
55 import mlx.nn as nn
66
7-from mlx_vlm.trainer.trainer import Dataset, Trainer, TrainingArgs
8-from mlx_vlm.utils import prepare_inputs
7+from mlx_vlm.trainer.trainer import Dataset, Trainer
98
109
1110 class TestDataset(unittest.TestCase):
@@ -15,8 +14,7 @@
1514 self.mock_processor = MagicMock()
1615 self.mock_image_processor = MagicMock()
1716
18- @patch("mlx_vlm.utils.prepare_inputs")
19- def test_dataset_initialization(self, mock_prepare_inputs):
17+ def test_dataset_initialization(self):
2018 dataset = Dataset(
2119 self.mock_hf_dataset,
2220 self.mock_config,
@@ -93,18 +91,23 @@
9391 self.assertFalse(self.trainer.train_on_completions)
9492 self.assertEqual(self.trainer.assistant_id, 77091)
9593
96- @patch("mlx.nn.losses.cross_entropy")
97- def test_loss_fn(self, mock_cross_entropy):
94+ def test_loss_fn(self):
9895 batch = {
9996 "pixel_values": mx.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]),
10097 "input_ids": mx.array([[1, 2, 3], [4, 5, 6]]),
10198 "attention_mask": mx.array([[1, 1, 1], [1, 1, 0]]),
10299 "image_grid_thw": (1, 1, 1),
103100 "image_sizes": [224, 224],
101+ "aspect_ratio_ids": mx.array([[1, 2], [3, 4]]),
102+ "aspect_ratio_mask": mx.array([[1, 1], [1, 0]]),
103+ "cross_attention_mask": mx.array([[1, 1], [1, 0]]),
104104 }
105105
106- self.mock_model.return_value = mx.array([[[0.1, 0.2, 0.3]], [[0.4, 0.5, 0.6]]])
107- mock_cross_entropy.return_value = mx.array([[0.1, 0.2], [0.3, 0.4]])
106+ mock_logits = mx.array([[[0.1, 0.2, 0.3]], [[0.4, 0.5, 0.6]]])
107+ # Create a mock LanguageModelOutput with the logits
108+ mock_output = Mock()
109+ mock_output.logits = mock_logits
110+ self.mock_model.return_value = mock_output
108111
109112 loss = self.trainer.loss_fn(self.mock_model, batch)
110113
modified mlx_vlm/trainer/trainer.py +48 −16
@@ -1,6 +1,4 @@
11 import json
2-import os
3-import time
42 import warnings
53 from dataclasses import dataclass, field
64 from pathlib import Path
@@ -9,7 +7,7 @@
97 import mlx.core as mx
108 import mlx.nn as nn
119 import numpy as np
12-from mlx.utils import tree_flatten
10+from mlx.utils import tree_flatten, tree_map
1311
1412
1513 def get_prompt(model_type, processor, conversation):
@@ -41,6 +39,7 @@
4139 image_processor=None,
4240 take=None,
4341 split=None,
42+ image_resize_shape=None,
4443 ):
4544 if split is not None:
4645 self.dataset = hf_dataset[split]
@@ -51,6 +50,7 @@
5150 self.processor = processor
5251 self.config = config
5352 self.image_processor = image_processor
53+ self.image_resize_shape = image_resize_shape
5454
5555 def __len__(self):
5656 return len(self.dataset)
@@ -89,10 +89,27 @@
8989 image_token_index = self.config["image_token_index"]
9090
9191 inputs = prepare_inputs(
92- self.image_processor, self.processor, images, prompts, image_token_index
92+ self.image_processor,
93+ self.processor,
94+ images,
95+ prompts,
96+ image_token_index,
97+ self.image_resize_shape,
9398 )
9499 input_ids, pixel_values, mask = inputs[:3]
95- kwargs = {k: v for k, v in zip(["image_grid_thw", "image_sizes"], inputs[3:])}
100+ kwargs = {
101+ k: v
102+ for k, v in zip(
103+ [
104+ "image_grid_thw",
105+ "image_sizes",
106+ "aspect_ratio_ids",
107+ "aspect_ratio_mask",
108+ "cross_attention_mask",
109+ ],
110+ inputs[3:],
111+ )
112+ }
96113 if mask is None:
97114 mask = mx.ones_like(input_ids)
98115
@@ -168,12 +185,18 @@
168185
169186 class Trainer:
170187 def __init__(
171- self, model, optimizer, train_on_completions=False, assistant_id=77091
188+ self,
189+ model,
190+ optimizer,
191+ train_on_completions=False,
192+ assistant_id=77091,
193+ clip_gradients=None,
172194 ):
173195 self.model = model
174196 self.optimizer = optimizer
175197 self.train_on_completions = train_on_completions
176198 self.assistant_id = assistant_id
199+ self.clip_gradients = clip_gradients
177200
178201 def loss_fn(self, model, batch):
179202 pixel_values = batch["pixel_values"]
@@ -203,20 +226,22 @@
203226
204227 input_ids = input_ids[:, :-1]
205228
206- kwargs = (
207- {
208- "image_grid_thw": batch["image_grid_thw"],
209- "image_sizes": batch["image_sizes"],
210- }
211- if "image_grid_thw" in batch or "image_sizes" in batch
212- else {}
213- )
229+ kwargs = {}
230+ image_keys = [
231+ "image_grid_thw",
232+ "image_sizes",
233+ "aspect_ratio_ids",
234+ "aspect_ratio_mask",
235+ "cross_attention_mask",
236+ ]
237+ if any(key in batch for key in image_keys):
238+ kwargs = {key: batch[key] for key in image_keys if key in batch}
214239
215240 # Forward pass
216- logits = model(input_ids, pixel_values, attention_mask, **kwargs)
241+ outputs = model(input_ids, pixel_values, attention_mask, **kwargs)
217242
218243 # Cast to float32
219- logits.astype(mx.float32)
244+ logits = outputs.logits.astype(mx.float32)
220245
221246 # Ensure logits and labels have the same sequence length
222247 def align_logits_with_labels(logits, labels):
@@ -249,6 +274,13 @@
249274 def train_step(self, batch):
250275 loss_and_grad_fn = nn.value_and_grad(self.model, self.loss_fn)
251276 loss, grads = loss_and_grad_fn(self.model, batch)
277+
278+ # Add gradient clipping
279+ if self.clip_gradients is not None:
280+ grads = tree_map(
281+ lambda g: mx.clip(g, -self.clip_gradients, self.clip_gradients), grads
282+ )
283+
252284 self.optimizer.update(self.model, grads)
253285
254286 return loss
modified mlx_vlm/trainer/utils.py +11 −1
@@ -1,3 +1,4 @@
1+import json
12 from pathlib import Path
23
34 import mlx.nn as nn
@@ -140,9 +141,18 @@
140141 if not adapter_path.exists():
141142 raise FileNotFoundError(f"The adapter path does not exist: {adapter_path}")
142143
144+ # Check if the adapter has lora params in the config (adapter_config.json)
145+ with open(adapter_path / "adapter_config.json", "r") as f:
146+ config = json.load(f)
147+ if "rank" not in config:
148+ raise ValueError("The adapter does not have lora params in the config")
149+
143150 # TODO: add lora params to the config and load them here
144151 list_of_modules = find_all_linear_names(model.language_model.model)
145- model = get_peft_model(model, list_of_modules)
152+ if config is not None:
153+ model = get_peft_model(model, list_of_modules, **config)
154+ else:
155+ model = get_peft_model(model, list_of_modules)
146156
147157 # TODO: Use custom adapter name
148158 model.load_weights(str(adapter_path / "adapters.safetensors"), strict=False)
modified mlx_vlm/utils.py +71 −16
@@ -717,10 +717,10 @@
717717 return img.resize(new_size)
718718
719719
720-def process_image(img, resize_shape):
720+def process_image(img, resize_shape, image_processor):
721721 if isinstance(img, str):
722722 img = load_image(img)
723- if resize_shape is not None:
723+ if resize_shape is not None and image_processor is None:
724724 img = resize_image(img, resize_shape)
725725 return img
726726
@@ -735,13 +735,14 @@
735735 images = [images]
736736
737737 # Process images
738- images = [
739- process_image(img, resize_shape) if isinstance(img, str) else img
740- for img in images
741- ]
738+ images = [process_image(img, resize_shape, image_processor) for img in images]
742739
743740 image_grid_thw = None
744741 image_sizes = None
742+ aspect_ratio_ids = None
743+ aspect_ratio_mask = None
744+ cross_attention_mask = None
745+
745746 if image_processor is not None:
746747 if not isinstance(prompts, list):
747748 prompts = [prompts]
@@ -790,7 +791,28 @@
790791 if image_grid_thw is not None:
791792 image_grid_thw = mx.array(image_grid_thw)
792793
793- return input_ids, pixel_values, mask, image_grid_thw, image_sizes
794+ aspect_ratio_ids = inputs.get("aspect_ratio_ids", None)
795+ if aspect_ratio_ids is not None:
796+ aspect_ratio_ids = mx.array(aspect_ratio_ids)
797+
798+ aspect_ratio_mask = inputs.get("aspect_ratio_mask", None)
799+ if aspect_ratio_mask is not None:
800+ aspect_ratio_mask = mx.array(aspect_ratio_mask)
801+
802+ cross_attention_mask = inputs.get("cross_attention_mask", None)
803+ if cross_attention_mask is not None:
804+ cross_attention_mask = mx.array(cross_attention_mask)
805+
806+ return (
807+ input_ids,
808+ pixel_values,
809+ mask,
810+ image_grid_thw,
811+ image_sizes,
812+ aspect_ratio_ids,
813+ aspect_ratio_mask,
814+ cross_attention_mask,
815+ )
794816
795817
796818 def generate_step(
@@ -866,10 +888,15 @@
866888 if repetition_context_size:
867889 repetition_context = repetition_context[-repetition_context_size:]
868890
869- def _step(y):
891+ def _step(y, **kwargs):
870892 nonlocal repetition_context
871- logits = model.language_model(y[None], cache=cache, mask=mask)
872- logits = logits[:, -1, :]
893+ outputs = model.language_model(
894+ y[None],
895+ cache=cache,
896+ mask=mask,
897+ **kwargs,
898+ )
899+ logits = outputs.logits[:, -1, :]
873900
874901 if repetition_penalty:
875902 logits = apply_repetition_penalty(
@@ -885,12 +912,22 @@
885912 repetition_context = repetition_context[-repetition_context_size:]
886913 return y, logprobs.squeeze(0)
887914
888- logits = model(input_ids, pixel_values, cache=cache, mask=mask, **kwargs)
889- logits = logits[:, -1, :]
915+ outputs = model(input_ids, pixel_values, cache=cache, mask=mask, **kwargs)
916+ if outputs.cross_attention_states is not None:
917+ kwargs = {
918+ k: v
919+ for k, v in zip(
920+ ["cross_attention_states"], [outputs.cross_attention_states]
921+ )
922+ }
923+ else:
924+ kwargs = {}
925+
926+ logits = outputs.logits[:, -1, :]
890927 y, logprobs = sample(logits)
891928 mx.async_eval(y)
892929 while True:
893- next_y, next_logprobs = _step(y)
930+ next_y, next_logprobs = _step(y, **kwargs)
894931 mx.async_eval(next_y)
895932 yield y.item(), logprobs
896933 y, logprobs = next_y, next_logprobs
@@ -924,9 +961,12 @@
924961 else:
925962 tokenizer = processor.tokenizer
926963
964+ resize_shape = kwargs.pop("resize_shape", None)
927965 image_token_index = model.config.image_token_index
966+
967+ # Prepare inputs
928968 inputs = prepare_inputs(
929- image_processor, processor, image, prompt, image_token_index
969+ image_processor, processor, image, prompt, image_token_index, resize_shape
930970 )
931971 input_ids, pixel_values, mask = inputs[:3]
932972 kwargs = {k: v for k, v in zip(["image_grid_thw", "image_sizes"], inputs[3:])}
@@ -962,6 +1002,7 @@
9621002 repetition_penalty: Optional[float] = None,
9631003 repetition_context_size: Optional[int] = None,
9641004 top_p: float = 1.0,
1005+ **kwargs,
9651006 ) -> str:
9661007 """
9671008 Generate text from the model.
@@ -992,13 +1033,27 @@
9921033 prompt_tokens = mx.array(processor.tokenizer.encode(prompt))
9931034 tokenizer = processor.tokenizer
9941035
1036+ resize_shape = kwargs.pop("resize_shape", None)
9951037 image_token_index = model.config.image_token_index
1038+
9961039 # Prepare inputs
9971040 inputs = prepare_inputs(
998- image_processor, processor, image, prompt, image_token_index
1041+ image_processor, processor, image, prompt, image_token_index, resize_shape
9991042 )
10001043 input_ids, pixel_values, mask = inputs[:3]
1001- kwargs = {k: v for k, v in zip(["image_grid_thw", "image_sizes"], inputs[3:])}
1044+ kwargs = {
1045+ k: v
1046+ for k, v in zip(
1047+ [
1048+ "image_grid_thw",
1049+ "image_sizes",
1050+ "aspect_ratio_ids",
1051+ "aspect_ratio_mask",
1052+ "cross_attention_mask",
1053+ ],
1054+ inputs[3:],
1055+ )
1056+ }
10021057
10031058 # Initialize timing and detokenizer
10041059 tic = time.perf_counter()