Changesets · Branches · Tags · Compare
| Changeset | c3a46dfa242e300c0f0704e4abe689b01e99805ef5d8b6f5374f6423e0013c0b |
|---|---|
| Author | Prince Canuma <prince.gdt@gmail.com> · 2024-09-29 19:44 +02:00 |
| Committer | GitHub <noreply@github.com> · 2024-09-29 19:44 +02:00 |
| Parents | c7875dcb56da |
19 files changed
modified mlx_vlm/models/idefics2/idefics2.py +6 −1
| @@ -251,7 +251,12 @@ | ||
| 251 | 251 | return mx.concatenate(final_embeddings, axis=1) |
| 252 | 252 | |
| 253 | 253 | def __call__( |
| 254 | - self, input_ids: mx.array, pixel_values: mx.array, mask: mx.array, cache=None | |
| 254 | + self, | |
| 255 | + input_ids: mx.array, | |
| 256 | + pixel_values: mx.array, | |
| 257 | + mask: mx.array, | |
| 258 | + cache=None, | |
| 259 | + **kwargs, | |
| 255 | 260 | ): |
| 256 | 261 | input_embeddings = self.get_input_embeddings(input_ids, pixel_values) |
| 257 | 262 | logits = self.language_model( |
modified mlx_vlm/models/idefics2/language.py +5 −6
| @@ -6,6 +6,8 @@ | ||
| 6 | 6 | import mlx.core as mx |
| 7 | 7 | import mlx.nn as nn |
| 8 | 8 | |
| 9 | +from ..base import KVCache, create_attention_mask | |
| 10 | + | |
| 9 | 11 | |
| 10 | 12 | @dataclass |
| 11 | 13 | class TextConfig: |
| @@ -62,7 +64,7 @@ | ||
| 62 | 64 | self, |
| 63 | 65 | x: mx.array, |
| 64 | 66 | mask: Optional[mx.array] = None, |
| 65 | - cache: Optional[Tuple[mx.array, mx.array]] = None, | |
| 67 | + cache: Optional[KVCache] = None, | |
| 66 | 68 | ) -> mx.array: |
| 67 | 69 | B, L, D = x.shape |
| 68 | 70 | |
| @@ -116,7 +118,7 @@ | ||
| 116 | 118 | self, |
| 117 | 119 | x: mx.array, |
| 118 | 120 | mask: Optional[mx.array] = None, |
| 119 | - cache: Optional[Tuple[mx.array, mx.array]] = None, | |
| 121 | + cache: Optional[KVCache] = None, | |
| 120 | 122 | ) -> mx.array: |
| 121 | 123 | r = self.self_attn(self.input_layernorm(x), mask, cache) |
| 122 | 124 | h = x + r |
| @@ -153,10 +155,7 @@ | ||
| 153 | 155 | else: |
| 154 | 156 | h = inputs_embeds |
| 155 | 157 | |
| 156 | - mask = None | |
| 157 | - if h.shape[1] > 1: | |
| 158 | - mask = nn.MultiHeadAttention.create_additive_causal_mask(h.shape[1]) | |
| 159 | - mask = mask.astype(h.dtype) | |
| 158 | + mask = create_attention_mask(h) | |
| 160 | 159 | |
| 161 | 160 | if cache is None: |
| 162 | 161 | cache = [None] * len(self.layers) |
modified mlx_vlm/models/llava/language.py +5 −6
| @@ -5,6 +5,8 @@ | ||
| 5 | 5 | import mlx.core as mx |
| 6 | 6 | import mlx.nn as nn |
| 7 | 7 | |
| 8 | +from ..base import KVCache, create_attention_mask | |
| 9 | + | |
| 8 | 10 | |
| 9 | 11 | @dataclass |
| 10 | 12 | class TextConfig: |
| @@ -78,7 +80,7 @@ | ||
| 78 | 80 | self, |
| 79 | 81 | x: mx.array, |
| 80 | 82 | mask: Optional[mx.array] = None, |
| 81 | - cache: Optional[Tuple[mx.array, mx.array]] = None, | |
| 83 | + cache: Optional[KVCache] = None, | |
| 82 | 84 | ) -> mx.array: |
| 83 | 85 | B, L, D = x.shape |
| 84 | 86 | |
| @@ -132,7 +134,7 @@ | ||
| 132 | 134 | self, |
| 133 | 135 | x: mx.array, |
| 134 | 136 | mask: Optional[mx.array] = None, |
| 135 | - cache: Optional[Tuple[mx.array, mx.array]] = None, | |
| 137 | + cache: Optional[KVCache] = None, | |
| 136 | 138 | ) -> mx.array: |
| 137 | 139 | r = self.self_attn(self.input_layernorm(x), mask, cache) |
| 138 | 140 | h = x + r |
| @@ -166,10 +168,7 @@ | ||
| 166 | 168 | else: |
| 167 | 169 | h = inputs_embeds |
| 168 | 170 | |
| 169 | - mask = None | |
| 170 | - if h.shape[1] > 1: | |
| 171 | - mask = nn.MultiHeadAttention.create_additive_causal_mask(h.shape[1]) | |
| 172 | - mask = mask.astype(h.dtype) | |
| 171 | + mask = create_attention_mask(h) | |
| 173 | 172 | |
| 174 | 173 | if cache is None: |
| 175 | 174 | cache = [None] * len(self.layers) |
modified mlx_vlm/models/llava/llava.py +6 −1
| @@ -132,7 +132,12 @@ | ||
| 132 | 132 | return mx.concatenate(final_embeddings, axis=1) |
| 133 | 133 | |
| 134 | 134 | def __call__( |
| 135 | - self, input_ids: mx.array, pixel_values: mx.array, mask: mx.array, cache=None | |
| 135 | + self, | |
| 136 | + input_ids: mx.array, | |
| 137 | + pixel_values: mx.array, | |
| 138 | + mask: mx.array, | |
| 139 | + cache=None, | |
| 140 | + **kwargs, | |
| 136 | 141 | ): |
| 137 | 142 | input_embddings = self.get_input_embeddings(input_ids, pixel_values) |
| 138 | 143 | logits = self.language_model( |
modified mlx_vlm/models/llava_bunny/language.py +2 −5
| @@ -5,7 +5,7 @@ | ||
| 5 | 5 | import mlx.core as mx |
| 6 | 6 | import mlx.nn as nn |
| 7 | 7 | |
| 8 | -from ..base import KVCache | |
| 8 | +from ..base import KVCache, create_attention_mask | |
| 9 | 9 | |
| 10 | 10 | |
| 11 | 11 | @dataclass |
| @@ -174,10 +174,7 @@ | ||
| 174 | 174 | else: |
| 175 | 175 | h = inputs_embeds |
| 176 | 176 | |
| 177 | - mask = None | |
| 178 | - if h.shape[1] > 1: | |
| 179 | - mask = nn.MultiHeadAttention.create_additive_causal_mask(h.shape[1]) | |
| 180 | - mask = mask.astype(h.dtype) | |
| 177 | + mask = create_attention_mask(h) | |
| 181 | 178 | |
| 182 | 179 | if cache is None: |
| 183 | 180 | cache = [None] * len(self.layers) |
modified mlx_vlm/models/llava_bunny/llava_bunny.py +1 −0
| @@ -183,6 +183,7 @@ | ||
| 183 | 183 | pixel_values: mx.array, |
| 184 | 184 | mask: Optional[mx.array] = None, |
| 185 | 185 | cache: Optional[Tuple[mx.array, mx.array]] = None, |
| 186 | + **kwargs, | |
| 186 | 187 | ): |
| 187 | 188 | input_embeddings = self.get_input_embeddings(input_ids, pixel_values) |
| 188 | 189 | logits = self.language_model( |
modified mlx_vlm/models/llava_next/language.py +5 −6
| @@ -5,6 +5,8 @@ | ||
| 5 | 5 | import mlx.core as mx |
| 6 | 6 | import mlx.nn as nn |
| 7 | 7 | |
| 8 | +from ..base import KVCache, create_attention_mask | |
| 9 | + | |
| 8 | 10 | |
| 9 | 11 | @dataclass |
| 10 | 12 | class TextConfig: |
| @@ -78,7 +80,7 @@ | ||
| 78 | 80 | self, |
| 79 | 81 | x: mx.array, |
| 80 | 82 | mask: Optional[mx.array] = None, |
| 81 | - cache: Optional[Tuple[mx.array, mx.array]] = None, | |
| 83 | + cache: Optional[KVCache] = None, | |
| 82 | 84 | ) -> mx.array: |
| 83 | 85 | B, L, D = x.shape |
| 84 | 86 | |
| @@ -132,7 +134,7 @@ | ||
| 132 | 134 | self, |
| 133 | 135 | x: mx.array, |
| 134 | 136 | mask: Optional[mx.array] = None, |
| 135 | - cache: Optional[Tuple[mx.array, mx.array]] = None, | |
| 137 | + cache: Optional[KVCache] = None, | |
| 136 | 138 | ) -> mx.array: |
| 137 | 139 | r = self.self_attn(self.input_layernorm(x), mask, cache) |
| 138 | 140 | h = x + r |
| @@ -166,10 +168,7 @@ | ||
| 166 | 168 | else: |
| 167 | 169 | h = inputs_embeds |
| 168 | 170 | |
| 169 | - mask = None | |
| 170 | - if h.shape[1] > 1: | |
| 171 | - mask = nn.MultiHeadAttention.create_additive_causal_mask(h.shape[1]) | |
| 172 | - mask = mask.astype(h.dtype) | |
| 171 | + mask = create_attention_mask(h) | |
| 173 | 172 | |
| 174 | 173 | if cache is None: |
| 175 | 174 | cache = [None] * len(self.layers) |
modified mlx_vlm/models/llava_next/llava_next.py +6 −1
| @@ -136,7 +136,12 @@ | ||
| 136 | 136 | return mx.concatenate(final_embeddings, axis=1) |
| 137 | 137 | |
| 138 | 138 | def __call__( |
| 139 | - self, input_ids: mx.array, pixel_values: mx.array, mask: mx.array, cache=None | |
| 139 | + self, | |
| 140 | + input_ids: mx.array, | |
| 141 | + pixel_values: mx.array, | |
| 142 | + mask: mx.array, | |
| 143 | + cache=None, | |
| 144 | + **kwargs, | |
| 140 | 145 | ): |
| 141 | 146 | |
| 142 | 147 | input_embddings = self.get_input_embeddings(input_ids, pixel_values) |
modified mlx_vlm/models/multi_modality/language.py +5 −6
| @@ -5,6 +5,8 @@ | ||
| 5 | 5 | import mlx.core as mx |
| 6 | 6 | import mlx.nn as nn |
| 7 | 7 | |
| 8 | +from ..base import KVCache, create_attention_mask | |
| 9 | + | |
| 8 | 10 | |
| 9 | 11 | @dataclass |
| 10 | 12 | class TextConfig: |
| @@ -78,7 +80,7 @@ | ||
| 78 | 80 | self, |
| 79 | 81 | x: mx.array, |
| 80 | 82 | mask: Optional[mx.array] = None, |
| 81 | - cache: Optional[Tuple[mx.array, mx.array]] = None, | |
| 83 | + cache: Optional[KVCache] = None, | |
| 82 | 84 | ) -> mx.array: |
| 83 | 85 | B, L, D = x.shape |
| 84 | 86 | |
| @@ -132,7 +134,7 @@ | ||
| 132 | 134 | self, |
| 133 | 135 | x: mx.array, |
| 134 | 136 | mask: Optional[mx.array] = None, |
| 135 | - cache: Optional[Tuple[mx.array, mx.array]] = None, | |
| 137 | + cache: Optional[KVCache] = None, | |
| 136 | 138 | ) -> mx.array: |
| 137 | 139 | r = self.self_attn(self.input_layernorm(x), mask, cache) |
| 138 | 140 | h = x + r |
| @@ -166,10 +168,7 @@ | ||
| 166 | 168 | else: |
| 167 | 169 | h = inputs_embeds |
| 168 | 170 | |
| 169 | - mask = None | |
| 170 | - if h.shape[1] > 1: | |
| 171 | - mask = nn.MultiHeadAttention.create_additive_causal_mask(h.shape[1]) | |
| 172 | - mask = mask.astype(h.dtype) | |
| 171 | + mask = create_attention_mask(h) | |
| 173 | 172 | |
| 174 | 173 | if cache is None: |
| 175 | 174 | cache = [None] * len(self.layers) |
modified mlx_vlm/models/multi_modality/multi_modality.py +6 −1
| @@ -360,7 +360,12 @@ | ||
| 360 | 360 | return mx.concatenate(final_embeddings, axis=1) |
| 361 | 361 | |
| 362 | 362 | def __call__( |
| 363 | - self, input_ids: mx.array, pixel_values: mx.array, mask: mx.array, cache=None | |
| 363 | + self, | |
| 364 | + input_ids: mx.array, | |
| 365 | + pixel_values: mx.array, | |
| 366 | + mask: mx.array, | |
| 367 | + cache=None, | |
| 368 | + **kwargs, | |
| 364 | 369 | ): |
| 365 | 370 | |
| 366 | 371 | input_embeddings = self.get_input_embeddings(input_ids, pixel_values) |
modified mlx_vlm/models/paligemma/language.py +6 −6
| @@ -5,6 +5,8 @@ | ||
| 5 | 5 | import mlx.core as mx |
| 6 | 6 | import mlx.nn as nn |
| 7 | 7 | |
| 8 | +from ..base import KVCache, create_attention_mask | |
| 9 | + | |
| 8 | 10 | |
| 9 | 11 | @dataclass |
| 10 | 12 | class TextConfig: |
| @@ -66,7 +68,7 @@ | ||
| 66 | 68 | self, |
| 67 | 69 | x: mx.array, |
| 68 | 70 | mask: Optional[mx.array] = None, |
| 69 | - cache: Optional[Tuple[mx.array, mx.array]] = None, | |
| 71 | + cache: Optional[KVCache] = None, | |
| 70 | 72 | ) -> mx.array: |
| 71 | 73 | B, L, D = x.shape |
| 72 | 74 | |
| @@ -120,7 +122,7 @@ | ||
| 120 | 122 | self, |
| 121 | 123 | x: mx.array, |
| 122 | 124 | mask: Optional[mx.array] = None, |
| 123 | - cache: Optional[Tuple[mx.array, mx.array]] = None, | |
| 125 | + cache: Optional[KVCache] = None, | |
| 124 | 126 | ) -> mx.array: |
| 125 | 127 | r = self.self_attn(self.input_layernorm(x), mask, cache) |
| 126 | 128 | h = x + r |
| @@ -155,11 +157,9 @@ | ||
| 155 | 157 | else: |
| 156 | 158 | h = inputs_embeds |
| 157 | 159 | |
| 158 | - h = h * (self.config.hidden_size**0.5) | |
| 160 | + h *= self.config.hidden_size**0.5 | |
| 159 | 161 | |
| 160 | - if cache is not None: | |
| 161 | - mask = nn.MultiHeadAttention.create_additive_causal_mask(h.shape[1]) | |
| 162 | - mask = mask.astype(h.dtype) | |
| 162 | + mask = create_attention_mask(h) | |
| 163 | 163 | |
| 164 | 164 | if cache is None: |
| 165 | 165 | cache = [None] * len(self.layers) |
modified mlx_vlm/models/phi3_v/phi3_v.py +10 −6
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | import mlx.nn as nn |
| 9 | 9 | import numpy as np |
| 10 | 10 | |
| 11 | +from ..base import KVCache, create_attention_mask | |
| 11 | 12 | from .language import LanguageModel, TextConfig |
| 12 | 13 | from .su_rope import Phi3SuScaledRotaryEmbedding |
| 13 | 14 | from .vision import VisionConfig, VisionModel |
| @@ -90,7 +91,7 @@ | ||
| 90 | 91 | self, |
| 91 | 92 | x: mx.array, |
| 92 | 93 | mask: Optional[mx.array] = None, |
| 93 | - cache: Optional[Tuple[mx.array, mx.array]] = None, | |
| 94 | + cache: Optional[KVCache] = None, | |
| 94 | 95 | ) -> mx.array: |
| 95 | 96 | B, L, D = x.shape |
| 96 | 97 | |
| @@ -148,7 +149,7 @@ | ||
| 148 | 149 | self, |
| 149 | 150 | x: mx.array, |
| 150 | 151 | mask: Optional[mx.array] = None, |
| 151 | - cache: Optional[Tuple[mx.array, mx.array]] = None, | |
| 152 | + cache: Optional[KVCache] = None, | |
| 152 | 153 | ) -> mx.array: |
| 153 | 154 | r = self.self_attn(self.input_layernorm(x), mask, cache) |
| 154 | 155 | h = x + r |
| @@ -179,16 +180,18 @@ | ||
| 179 | 180 | ): |
| 180 | 181 | h = self.embed_tokens(inputs) |
| 181 | 182 | p = np.argwhere(inputs < 0).tolist() |
| 183 | + | |
| 182 | 184 | if pixel_values is not None: |
| 183 | 185 | h = self.vision_embed_tokens(pixel_values, h, image_sizes, p) |
| 184 | - mask = None | |
| 185 | - if h.shape[1] > 1: | |
| 186 | - mask = nn.MultiHeadAttention.create_additive_causal_mask(h.shape[1]) | |
| 187 | - mask = mask.astype(h.dtype) | |
| 186 | + | |
| 187 | + mask = create_attention_mask(h) | |
| 188 | + | |
| 188 | 189 | if cache is None: |
| 189 | 190 | cache = [None] * len(self.layers) |
| 191 | + | |
| 190 | 192 | for layer, c in zip(self.layers, cache): |
| 191 | 193 | h = layer(h, mask, c) |
| 194 | + | |
| 192 | 195 | return self.norm(h) |
| 193 | 196 | |
| 194 | 197 | |
| @@ -206,6 +209,7 @@ | ||
| 206 | 209 | pixel_values=None, |
| 207 | 210 | mask=None, |
| 208 | 211 | cache=None, |
| 212 | + **kwargs, | |
| 209 | 213 | ): |
| 210 | 214 | out = self.model(inputs, pixel_values, mask, cache) |
| 211 | 215 | return self.lm_head(out).astype(self.lm_head.weight.dtype) |
added mlx_vlm/models/pixtral/__init__.py +8 −0
| @@ -0,0 +1,8 @@ | ||
| 1 | +from .pixtral import ( | |
| 2 | + LanguageModel, | |
| 3 | + Model, | |
| 4 | + ModelConfig, | |
| 5 | + TextConfig, | |
| 6 | + VisionConfig, | |
| 7 | + VisionModel, | |
| 8 | +) |
added mlx_vlm/models/pixtral/language.py +220 −0
| @@ -0,0 +1,220 @@ | ||
| 1 | +import inspect | |
| 2 | +from dataclasses import dataclass | |
| 3 | +from typing import Dict, Optional, Tuple, Union | |
| 4 | + | |
| 5 | +import mlx.core as mx | |
| 6 | +import mlx.nn as nn | |
| 7 | + | |
| 8 | +from ..base import KVCache, create_attention_mask | |
| 9 | + | |
| 10 | + | |
| 11 | +@dataclass | |
| 12 | +class TextConfig: | |
| 13 | + model_type: str | |
| 14 | + hidden_size: int = 5120 | |
| 15 | + head_dim: int = 128 | |
| 16 | + num_hidden_layers: int = 40 | |
| 17 | + intermediate_size: int = 14336 | |
| 18 | + num_attention_heads: int = 32 | |
| 19 | + rms_norm_eps: float = 1e-06 | |
| 20 | + vocab_size: int = 131072 | |
| 21 | + num_key_value_heads: int = 8 | |
| 22 | + rope_theta: float = 1000000000.0 | |
| 23 | + rope_traditional: bool = False | |
| 24 | + rope_scaling: Optional[Dict[str, Union[float, str]]] = None | |
| 25 | + | |
| 26 | + @classmethod | |
| 27 | + def from_dict(cls, params): | |
| 28 | + return cls( | |
| 29 | + **{ | |
| 30 | + k: v | |
| 31 | + for k, v in params.items() | |
| 32 | + if k in inspect.signature(cls).parameters | |
| 33 | + } | |
| 34 | + ) | |
| 35 | + | |
| 36 | + def __post_init__(self): | |
| 37 | + if self.num_key_value_heads is None: | |
| 38 | + self.num_key_value_heads = self.num_attention_heads | |
| 39 | + | |
| 40 | + if self.rope_scaling: | |
| 41 | + required_keys = {"factor", "type"} | |
| 42 | + if not all(key in self.rope_scaling for key in required_keys): | |
| 43 | + raise ValueError(f"rope_scaling must contain keys {required_keys}") | |
| 44 | + | |
| 45 | + if self.rope_scaling["type"] != "linear": | |
| 46 | + raise ValueError("rope_scaling 'type' currently only supports 'linear'") | |
| 47 | + | |
| 48 | + | |
| 49 | +class Attention(nn.Module): | |
| 50 | + def __init__(self, config: TextConfig): | |
| 51 | + super().__init__() | |
| 52 | + | |
| 53 | + dim = config.hidden_size | |
| 54 | + self.n_heads = n_heads = config.num_attention_heads | |
| 55 | + self.n_kv_heads = n_kv_heads = config.num_key_value_heads | |
| 56 | + | |
| 57 | + head_dim = config.head_dim | |
| 58 | + self.scale = head_dim**-0.5 | |
| 59 | + | |
| 60 | + self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=False) | |
| 61 | + self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False) | |
| 62 | + self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False) | |
| 63 | + self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False) | |
| 64 | + | |
| 65 | + rope_scale = ( | |
| 66 | + 1 / config.rope_scaling["factor"] | |
| 67 | + if config.rope_scaling is not None | |
| 68 | + and config.rope_scaling["type"] == "linear" | |
| 69 | + else 1 | |
| 70 | + ) | |
| 71 | + self.rope = nn.RoPE( | |
| 72 | + head_dim, | |
| 73 | + traditional=config.rope_traditional, | |
| 74 | + base=config.rope_theta, | |
| 75 | + scale=rope_scale, | |
| 76 | + ) | |
| 77 | + | |
| 78 | + def __call__( | |
| 79 | + self, | |
| 80 | + x: mx.array, | |
| 81 | + mask: Optional[mx.array] = None, | |
| 82 | + cache: Optional[KVCache] = None, | |
| 83 | + ) -> mx.array: | |
| 84 | + B, L, D = x.shape | |
| 85 | + | |
| 86 | + queries, keys, values = self.q_proj(x), self.k_proj(x), self.v_proj(x) | |
| 87 | + | |
| 88 | + # Prepare the queries, keys and values for the attention computation | |
| 89 | + queries = queries.reshape(B, L, self.n_heads, -1).transpose(0, 2, 1, 3) | |
| 90 | + keys = keys.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3) | |
| 91 | + values = values.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3) | |
| 92 | + | |
| 93 | + if cache is not None: | |
| 94 | + queries = self.rope(queries, offset=cache.offset) | |
| 95 | + keys = self.rope(keys, offset=cache.offset) | |
| 96 | + keys, values = cache.update_and_fetch(keys, values) | |
| 97 | + else: | |
| 98 | + queries = self.rope(queries) | |
| 99 | + keys = self.rope(keys) | |
| 100 | + | |
| 101 | + output = mx.fast.scaled_dot_product_attention( | |
| 102 | + queries, keys, values, scale=self.scale, mask=mask | |
| 103 | + ) | |
| 104 | + output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) | |
| 105 | + return self.o_proj(output) | |
| 106 | + | |
| 107 | + | |
| 108 | +class MLP(nn.Module): | |
| 109 | + def __init__(self, dim, hidden_dim): | |
| 110 | + super().__init__() | |
| 111 | + self.gate_proj = nn.Linear(dim, hidden_dim, bias=False) | |
| 112 | + self.down_proj = nn.Linear(hidden_dim, dim, bias=False) | |
| 113 | + self.up_proj = nn.Linear(dim, hidden_dim, bias=False) | |
| 114 | + | |
| 115 | + def __call__(self, x) -> mx.array: | |
| 116 | + return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x)) | |
| 117 | + | |
| 118 | + | |
| 119 | +class TransformerBlock(nn.Module): | |
| 120 | + def __init__(self, config: TextConfig): | |
| 121 | + super().__init__() | |
| 122 | + self.num_attention_heads = config.num_attention_heads | |
| 123 | + self.hidden_size = config.hidden_size | |
| 124 | + self.self_attn = Attention(config) | |
| 125 | + self.mlp = MLP(config.hidden_size, config.intermediate_size) | |
| 126 | + self.input_layernorm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) | |
| 127 | + self.post_attention_layernorm = nn.RMSNorm( | |
| 128 | + config.hidden_size, eps=config.rms_norm_eps | |
| 129 | + ) | |
| 130 | + self.config = config | |
| 131 | + | |
| 132 | + def __call__( | |
| 133 | + self, | |
| 134 | + x: mx.array, | |
| 135 | + mask: Optional[mx.array] = None, | |
| 136 | + cache: Optional[KVCache] = None, | |
| 137 | + ) -> mx.array: | |
| 138 | + r = self.self_attn(self.input_layernorm(x), mask, cache) | |
| 139 | + h = x + r | |
| 140 | + r = self.mlp(self.post_attention_layernorm(h)) | |
| 141 | + out = h + r | |
| 142 | + return out | |
| 143 | + | |
| 144 | + | |
| 145 | +class Mistral(nn.Module): | |
| 146 | + def __init__(self, config: TextConfig): | |
| 147 | + super().__init__() | |
| 148 | + self.config = config | |
| 149 | + self.vocab_size = config.vocab_size | |
| 150 | + self.num_hidden_layers = config.num_hidden_layers | |
| 151 | + assert self.vocab_size > 0 | |
| 152 | + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) | |
| 153 | + self.layers = [ | |
| 154 | + TransformerBlock(config=config) for _ in range(config.num_hidden_layers) | |
| 155 | + ] | |
| 156 | + self.norm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) | |
| 157 | + | |
| 158 | + def __call__( | |
| 159 | + self, | |
| 160 | + inputs: mx.array, | |
| 161 | + cache=None, | |
| 162 | + inputs_embeds=None, | |
| 163 | + ): | |
| 164 | + # for passing merged input embeddings | |
| 165 | + if inputs_embeds is None: | |
| 166 | + h = self.embed_tokens(inputs) | |
| 167 | + else: | |
| 168 | + h = inputs_embeds | |
| 169 | + | |
| 170 | + mask = create_attention_mask(h, cache) | |
| 171 | + | |
| 172 | + if cache is None: | |
| 173 | + cache = [None] * len(self.layers) | |
| 174 | + | |
| 175 | + for layer, c in zip(self.layers, cache): | |
| 176 | + h = layer(h, mask, c) | |
| 177 | + | |
| 178 | + return self.norm(h) | |
| 179 | + | |
| 180 | + | |
| 181 | +class LanguageModel(nn.Module): | |
| 182 | + def __init__(self, config: TextConfig): | |
| 183 | + super().__init__() | |
| 184 | + self.config = config | |
| 185 | + self.model_type = config.model_type | |
| 186 | + if self.model_type != "mistral": | |
| 187 | + raise ValueError( | |
| 188 | + f"Model type {self.model_type} not supported. Currently only 'mistral' is supported" | |
| 189 | + ) | |
| 190 | + self.model = Mistral(config) | |
| 191 | + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) | |
| 192 | + | |
| 193 | + def __call__( | |
| 194 | + self, | |
| 195 | + inputs: mx.array, | |
| 196 | + cache=None, | |
| 197 | + inputs_embeds=None, | |
| 198 | + mask: Optional[mx.array] = None, | |
| 199 | + ): | |
| 200 | + out = self.model(inputs, cache, inputs_embeds) | |
| 201 | + return self.lm_head(out) | |
| 202 | + | |
| 203 | + @staticmethod | |
| 204 | + def sanitize(weights): | |
| 205 | + # Remove unused precomputed rotary freqs | |
| 206 | + return { | |
| 207 | + k: v for k, v in weights.items() if "self_attn.rotary_emb.inv_freq" not in k | |
| 208 | + } | |
| 209 | + | |
| 210 | + @property | |
| 211 | + def layers(self): | |
| 212 | + return self.model.layers | |
| 213 | + | |
| 214 | + @property | |
| 215 | + def head_dim(self): | |
| 216 | + return self.config.head_dim | |
| 217 | + | |
| 218 | + @property | |
| 219 | + def n_kv_heads(self): | |
| 220 | + return self.config.num_key_value_heads |
added mlx_vlm/models/pixtral/pixtral.py +193 −0
| @@ -0,0 +1,193 @@ | ||
| 1 | +import glob | |
| 2 | +import inspect | |
| 3 | +import json | |
| 4 | +from dataclasses import dataclass | |
| 5 | +from pathlib import Path | |
| 6 | +from typing import Optional | |
| 7 | + | |
| 8 | +import mlx.core as mx | |
| 9 | +import mlx.nn as nn | |
| 10 | +import numpy as np | |
| 11 | +from huggingface_hub import snapshot_download | |
| 12 | + | |
| 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 = 10 | |
| 24 | + vision_feature_select_strategy: str = "full" | |
| 25 | + vision_feature_layer: int = -1 | |
| 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 LlavaMultiModalProjector(nn.Module): | |
| 40 | + def __init__(self, config: ModelConfig): | |
| 41 | + super().__init__() | |
| 42 | + self.linear_1 = nn.Linear( | |
| 43 | + config.vision_config.hidden_size, config.text_config.hidden_size, bias=True | |
| 44 | + ) | |
| 45 | + self.gelu = nn.GELU() | |
| 46 | + self.linear_2 = nn.Linear( | |
| 47 | + config.text_config.hidden_size, config.text_config.hidden_size, bias=True | |
| 48 | + ) | |
| 49 | + | |
| 50 | + def __call__(self, x: mx.array) -> mx.array: | |
| 51 | + x = self.linear_1(x) | |
| 52 | + x = self.gelu(x) | |
| 53 | + x = self.linear_2(x) | |
| 54 | + return x | |
| 55 | + | |
| 56 | + | |
| 57 | +class Model(nn.Module): | |
| 58 | + def __init__(self, config: ModelConfig): | |
| 59 | + self.config = config | |
| 60 | + self.vision_tower = VisionModel(config.vision_config) | |
| 61 | + self.language_model = LanguageModel(config.text_config) | |
| 62 | + self.multi_modal_projector = LlavaMultiModalProjector(config) | |
| 63 | + self.vision_feature_layer = config.vision_feature_layer | |
| 64 | + self.vision_feature_select_strategy = config.vision_feature_select_strategy | |
| 65 | + | |
| 66 | + def get_input_embeddings( | |
| 67 | + self, | |
| 68 | + input_ids: Optional[mx.array] = None, | |
| 69 | + pixel_values: Optional[mx.array] = None, | |
| 70 | + ): | |
| 71 | + if pixel_values is None: | |
| 72 | + return self.language_model(input_ids) | |
| 73 | + | |
| 74 | + # Get the input embeddings from the language model | |
| 75 | + inputs_embeds = self.language_model.model.embed_tokens(input_ids) | |
| 76 | + | |
| 77 | + # Get the ouptut hidden states from the vision model | |
| 78 | + *_, hidden_states = self.vision_tower( | |
| 79 | + pixel_values.transpose(0, 2, 3, 1), output_hidden_states=True | |
| 80 | + ) | |
| 81 | + | |
| 82 | + # Select the hidden states from the desired layer | |
| 83 | + selected_image_feature = hidden_states[self.vision_feature_layer] | |
| 84 | + | |
| 85 | + if self.vision_feature_select_strategy == "default": | |
| 86 | + selected_image_feature = selected_image_feature[:, 1:] | |
| 87 | + elif self.vision_feature_select_strategy == "full": | |
| 88 | + selected_image_feature = selected_image_feature | |
| 89 | + else: | |
| 90 | + raise ValueError( | |
| 91 | + "Unexpected feature selection strategy: " | |
| 92 | + f"{self.vision_feature_select_strategy}" | |
| 93 | + ) | |
| 94 | + | |
| 95 | + # Pass image features through the multi-modal projector | |
| 96 | + image_features = self.multi_modal_projector(selected_image_feature) | |
| 97 | + | |
| 98 | + # Insert special image tokens in the input_ids | |
| 99 | + final_inputs_embeds = self._merge_input_ids_with_image_features( | |
| 100 | + image_features, inputs_embeds, input_ids | |
| 101 | + ) | |
| 102 | + return final_inputs_embeds | |
| 103 | + | |
| 104 | + def _merge_input_ids_with_image_features( | |
| 105 | + self, image_features, inputs_embeds, input_ids | |
| 106 | + ): | |
| 107 | + image_token_index = self.config.image_token_index | |
| 108 | + num_images, num_image_patches, embed_dim = image_features.shape | |
| 109 | + | |
| 110 | + # Positions of <image> tokens in input_ids, assuming batch size is 1 | |
| 111 | + image_positions = np.where(input_ids[0] == image_token_index)[0].tolist() | |
| 112 | + | |
| 113 | + text_segments = [] | |
| 114 | + start_idx = 0 | |
| 115 | + | |
| 116 | + for position in image_positions: | |
| 117 | + text_segments.append(inputs_embeds[:, start_idx:position]) | |
| 118 | + start_idx = position + 1 | |
| 119 | + | |
| 120 | + image_embeddings = mx.split(image_features, image_features.shape[0]) | |
| 121 | + final_embeddings = [v for p in zip(text_segments, image_embeddings) for v in p] | |
| 122 | + final_embeddings += [inputs_embeds[:, start_idx:]] | |
| 123 | + | |
| 124 | + # Create a final embedding of shape | |
| 125 | + # (1, num_image_patches*num_images + sequence_len, embed_dim) | |
| 126 | + return mx.concatenate(final_embeddings, axis=1) | |
| 127 | + | |
| 128 | + def __call__( | |
| 129 | + self, | |
| 130 | + input_ids: mx.array, | |
| 131 | + pixel_values: mx.array, | |
| 132 | + mask: mx.array, | |
| 133 | + cache=None, | |
| 134 | + **kwargs, | |
| 135 | + ): | |
| 136 | + input_embddings = self.get_input_embeddings(input_ids, pixel_values) | |
| 137 | + logits = self.language_model( | |
| 138 | + input_ids, cache=cache, inputs_embeds=input_embddings | |
| 139 | + ) | |
| 140 | + return logits | |
| 141 | + | |
| 142 | + @staticmethod | |
| 143 | + def from_pretrained(path_or_hf_repo: str): | |
| 144 | + path = Path(path_or_hf_repo) | |
| 145 | + if not path.exists(): | |
| 146 | + path = Path( | |
| 147 | + snapshot_download( | |
| 148 | + repo_id=path_or_hf_repo, | |
| 149 | + allow_patterns=[ | |
| 150 | + "*.json", | |
| 151 | + "*.safetensors", | |
| 152 | + "*.py", | |
| 153 | + "tokenizer.model", | |
| 154 | + "*.tiktoken", | |
| 155 | + ], | |
| 156 | + ) | |
| 157 | + ) | |
| 158 | + | |
| 159 | + with open(path / "config.json", "r") as f: | |
| 160 | + model_config = json.load(f) | |
| 161 | + | |
| 162 | + model_config = ModelConfig.from_dict(model_config) | |
| 163 | + | |
| 164 | + model_config.vision_config = VisionConfig.from_dict(model_config.vision_config) | |
| 165 | + model_config.text_config = TextConfig.from_dict(model_config.text_config) | |
| 166 | + | |
| 167 | + model = Model(model_config) | |
| 168 | + weight_files = glob.glob(str(path / "*.safetensors")) | |
| 169 | + if not weight_files: | |
| 170 | + raise FileNotFoundError(f"No safetensors found in {path}") | |
| 171 | + | |
| 172 | + weights = {} | |
| 173 | + for wf in weight_files: | |
| 174 | + weights.update(mx.load(wf)) | |
| 175 | + | |
| 176 | + weights = VisionModel.sanitize(weights) | |
| 177 | + weights = LanguageModel.sanitize(weights) | |
| 178 | + | |
| 179 | + model.load_weights(list(weights.items())) | |
| 180 | + return model | |
| 181 | + | |
| 182 | + def sanitize(self, weights): | |
| 183 | + def transform_key(key): | |
| 184 | + if "vision_tower" in key: | |
| 185 | + if "transformer" in key: | |
| 186 | + key = key.replace("vision_tower", "vision_tower.vision_model") | |
| 187 | + if "patch_conv" in key: | |
| 188 | + key = key.replace("vision_tower", "vision_tower.vision_model") | |
| 189 | + if "ln_pre" in key: | |
| 190 | + key = key.replace("vision_tower", "vision_tower.vision_model") | |
| 191 | + return key | |
| 192 | + | |
| 193 | + return {transform_key(k): v for k, v in weights.items()} |
added mlx_vlm/models/pixtral/vision.py +324 −0
| @@ -0,0 +1,324 @@ | ||
| 1 | +import inspect | |
| 2 | +from dataclasses import dataclass | |
| 3 | +from typing import Optional | |
| 4 | + | |
| 5 | +import mlx.core as mx | |
| 6 | +import mlx.nn as nn | |
| 7 | + | |
| 8 | + | |
| 9 | +@dataclass | |
| 10 | +class VisionConfig: | |
| 11 | + model_type: str | |
| 12 | + num_hidden_layers: int = 24 | |
| 13 | + hidden_size: int = 1024 | |
| 14 | + head_dim: int = 64 | |
| 15 | + intermediate_size: int = 4096 | |
| 16 | + num_attention_heads: int = 16 | |
| 17 | + image_size: int = 336 | |
| 18 | + patch_size: int = 14 | |
| 19 | + projection_dim: int = 768 | |
| 20 | + vocab_size: int = 32000 | |
| 21 | + num_channels: int = 3 | |
| 22 | + rms_norm_eps: float = 1e-5 | |
| 23 | + rope_theta: float = 10000.0 | |
| 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 | + | |
| 36 | +def 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 | + | |
| 52 | +def position_ids_in_meshgrid(patch_embeds_list, max_width): | |
| 53 | + positions = [] | |
| 54 | + for patch in patch_embeds_list: | |
| 55 | + height, width = patch.shape[1], patch.shape[2] | |
| 56 | + h_grid, v_grid = mx.meshgrid(mx.arange(height), mx.arange(width), indexing="ij") | |
| 57 | + h_grid = h_grid.reshape(-1, 1) | |
| 58 | + v_grid = v_grid.reshape(-1, 1) | |
| 59 | + ids = h_grid * max_width + v_grid | |
| 60 | + positions.append(ids.flatten()) | |
| 61 | + return mx.concatenate(positions) | |
| 62 | + | |
| 63 | + | |
| 64 | +def generate_block_attention_mask(patch_embeds_list, tensor): | |
| 65 | + seq_len = tensor.shape[1] | |
| 66 | + d_min = -1e9 # Using a large negative value as MLX doesn't have finfo | |
| 67 | + | |
| 68 | + causal_mask = mx.full((seq_len, seq_len), vals=d_min) | |
| 69 | + | |
| 70 | + block_end_idx = mx.cumsum(mx.array(patch_embeds_list)) | |
| 71 | + block_start_idx = mx.concatenate([mx.array([0]), mx.array(patch_embeds_list[:-1])]) | |
| 72 | + block_start_idx = mx.cumsum(block_start_idx) | |
| 73 | + | |
| 74 | + for start, end in zip(block_start_idx, block_end_idx): | |
| 75 | + start, end = int(start), int(end) # Convert to integers for indexing | |
| 76 | + causal_mask[start:end, start:end] = 0 | |
| 77 | + | |
| 78 | + causal_mask = mx.broadcast_to( | |
| 79 | + causal_mask[None, None, :, :], (tensor.shape[0], 1, seq_len, seq_len) | |
| 80 | + ) | |
| 81 | + return causal_mask | |
| 82 | + | |
| 83 | + | |
| 84 | +def rotate_half(x): | |
| 85 | + x1 = x[..., : x.shape[-1] // 2] | |
| 86 | + x2 = x[..., x.shape[-1] // 2 :] | |
| 87 | + return mx.concatenate((-x2, x1), axis=-1) | |
| 88 | + | |
| 89 | + | |
| 90 | +def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): | |
| 91 | + cos = mx.expand_dims(cos, axis=unsqueeze_dim) | |
| 92 | + sin = mx.expand_dims(sin, axis=unsqueeze_dim) | |
| 93 | + q_embed = (q * cos) + (rotate_half(q) * sin) | |
| 94 | + k_embed = (k * cos) + (rotate_half(k) * sin) | |
| 95 | + return q_embed, k_embed | |
| 96 | + | |
| 97 | + | |
| 98 | +class Attention(nn.Module): | |
| 99 | + def __init__( | |
| 100 | + self, | |
| 101 | + dims: int, | |
| 102 | + num_heads: int, | |
| 103 | + query_input_dims: Optional[int] = None, | |
| 104 | + key_input_dims: Optional[int] = None, | |
| 105 | + value_input_dims: Optional[int] = None, | |
| 106 | + value_dims: Optional[int] = None, | |
| 107 | + value_output_dims: Optional[int] = None, | |
| 108 | + bias: bool = False, | |
| 109 | + ): | |
| 110 | + super().__init__() | |
| 111 | + | |
| 112 | + if (dims % num_heads) != 0: | |
| 113 | + raise ValueError( | |
| 114 | + "The input feature dimensions should be divisible by the " | |
| 115 | + f"number of heads ({dims} % {num_heads}) != 0" | |
| 116 | + ) | |
| 117 | + | |
| 118 | + query_input_dims = query_input_dims or dims | |
| 119 | + key_input_dims = key_input_dims or dims | |
| 120 | + value_input_dims = value_input_dims or key_input_dims | |
| 121 | + value_dims = value_dims or dims | |
| 122 | + value_output_dims = value_output_dims or dims | |
| 123 | + | |
| 124 | + self.embed_dim = dims | |
| 125 | + self.num_heads = num_heads | |
| 126 | + self.head_dim = self.embed_dim // self.num_heads | |
| 127 | + | |
| 128 | + self.scale = self.head_dim**-0.5 | |
| 129 | + | |
| 130 | + self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False) | |
| 131 | + self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False) | |
| 132 | + self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False) | |
| 133 | + self.o_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False) | |
| 134 | + | |
| 135 | + def __call__(self, queries, keys, values, position_embeddings, mask=None): | |
| 136 | + queries = self.q_proj(queries) | |
| 137 | + keys = self.k_proj(keys) | |
| 138 | + values = self.v_proj(values) | |
| 139 | + | |
| 140 | + num_heads = self.num_heads | |
| 141 | + B, L, D = queries.shape | |
| 142 | + _, S, _ = keys.shape | |
| 143 | + queries = queries.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3) | |
| 144 | + keys = keys.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3) | |
| 145 | + values = values.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3) | |
| 146 | + | |
| 147 | + cos, sin = position_embeddings | |
| 148 | + queries, keys = apply_rotary_pos_emb(queries, keys, cos, sin, unsqueeze_dim=0) | |
| 149 | + | |
| 150 | + attn_weights = mx.matmul(queries, keys.transpose(0, 1, 3, 2)) * self.scale | |
| 151 | + | |
| 152 | + if mask is not None: | |
| 153 | + attn_weights = attn_weights + mask | |
| 154 | + | |
| 155 | + attn_weights = mx.softmax(attn_weights, axis=-1) | |
| 156 | + output = mx.matmul(attn_weights, values) | |
| 157 | + | |
| 158 | + output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) | |
| 159 | + | |
| 160 | + return self.o_proj(output) | |
| 161 | + | |
| 162 | + | |
| 163 | +class MLP(nn.Module): | |
| 164 | + def __init__(self, config: VisionConfig): | |
| 165 | + super().__init__() | |
| 166 | + dim = config.hidden_size | |
| 167 | + hidden_dim = config.intermediate_size | |
| 168 | + self.gate_proj = nn.Linear(dim, hidden_dim, bias=False) | |
| 169 | + self.down_proj = nn.Linear(hidden_dim, dim, bias=False) | |
| 170 | + self.up_proj = nn.Linear(dim, hidden_dim, bias=False) | |
| 171 | + | |
| 172 | + def __call__(self, x) -> mx.array: | |
| 173 | + return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x)) | |
| 174 | + | |
| 175 | + | |
| 176 | +class EncoderLayer(nn.Module): | |
| 177 | + def __init__(self, config: VisionConfig): | |
| 178 | + super().__init__() | |
| 179 | + self.embed_dim = config.hidden_size | |
| 180 | + self.attention = Attention( | |
| 181 | + config.hidden_size, config.num_attention_heads, bias=True | |
| 182 | + ) | |
| 183 | + self.attention_norm = nn.RMSNorm(self.embed_dim, eps=config.rms_norm_eps) | |
| 184 | + self.feed_forward = MLP(config) | |
| 185 | + self.ffn_norm = nn.RMSNorm(self.embed_dim, eps=config.rms_norm_eps) | |
| 186 | + | |
| 187 | + def __call__( | |
| 188 | + self, | |
| 189 | + x: mx.array, | |
| 190 | + position_embeddings: mx.array, | |
| 191 | + mask: Optional[mx.array] = None, | |
| 192 | + ) -> mx.array: | |
| 193 | + y = self.attention_norm(x) | |
| 194 | + y = self.attention(y, y, y, position_embeddings, mask) | |
| 195 | + x = x + y | |
| 196 | + y = self.ffn_norm(x) | |
| 197 | + y = self.feed_forward(y) | |
| 198 | + return x + y | |
| 199 | + | |
| 200 | + | |
| 201 | +class Encoder(nn.Module): | |
| 202 | + def __init__(self, config: VisionConfig): | |
| 203 | + super().__init__() | |
| 204 | + self.layers = [EncoderLayer(config) for _ in range(config.num_hidden_layers)] | |
| 205 | + | |
| 206 | + | |
| 207 | +class PixtralRotaryEmbedding: | |
| 208 | + def __init__(self, config): | |
| 209 | + self.dim = config.head_dim | |
| 210 | + self.base = config.rope_theta | |
| 211 | + max_patches_per_side = config.image_size // config.patch_size | |
| 212 | + freqs = 1.0 / ( | |
| 213 | + self.base ** (mx.arange(0, self.dim, 2).astype(mx.float32) / self.dim) | |
| 214 | + ) | |
| 215 | + | |
| 216 | + h = mx.arange(max_patches_per_side) | |
| 217 | + w = mx.arange(max_patches_per_side) | |
| 218 | + | |
| 219 | + freqs_h = mx.outer(h, freqs[::2]).astype(mx.float32) | |
| 220 | + freqs_w = mx.outer(w, freqs[1::2]).astype(mx.float32) | |
| 221 | + inv_freq = mx.concatenate( | |
| 222 | + [ | |
| 223 | + mx.tile(freqs_h[:, None, :], (1, max_patches_per_side, 1)), | |
| 224 | + mx.tile(freqs_w[None, :, :], (max_patches_per_side, 1, 1)), | |
| 225 | + ], | |
| 226 | + axis=-1, | |
| 227 | + ).reshape(-1, self.dim // 2) | |
| 228 | + | |
| 229 | + self.inv_freq = mx.concatenate((inv_freq, inv_freq), axis=-1) | |
| 230 | + | |
| 231 | + def __call__(self, x, position_ids): | |
| 232 | + freqs = self.inv_freq[position_ids] | |
| 233 | + emb = freqs | |
| 234 | + cos = mx.cos(emb) | |
| 235 | + sin = mx.sin(emb) | |
| 236 | + return cos.astype(x.dtype), sin.astype(x.dtype) | |
| 237 | + | |
| 238 | + | |
| 239 | +class PixtralVisionModel(nn.Module): | |
| 240 | + def __init__(self, config: VisionConfig): | |
| 241 | + super().__init__() | |
| 242 | + self.config = config | |
| 243 | + self.patch_conv = nn.Conv2d( | |
| 244 | + in_channels=config.num_channels, | |
| 245 | + out_channels=config.hidden_size, | |
| 246 | + kernel_size=config.patch_size, | |
| 247 | + stride=config.patch_size, | |
| 248 | + bias=False, | |
| 249 | + ) | |
| 250 | + self.ln_pre = nn.RMSNorm(config.hidden_size) | |
| 251 | + self.transformer = Encoder(config) | |
| 252 | + self.patch_positional_embedding = PixtralRotaryEmbedding(config) | |
| 253 | + | |
| 254 | + def __call__( | |
| 255 | + self, | |
| 256 | + x: mx.array, | |
| 257 | + output_hidden_states: Optional[bool] = None, | |
| 258 | + ) -> mx.array: | |
| 259 | + B, H, W, C = x.shape | |
| 260 | + patch_embeds_list = [self.patch_conv(img[None, :]) for img in x] | |
| 261 | + | |
| 262 | + patch_embeds = mx.concatenate( | |
| 263 | + [p.reshape(B, -1, p.shape[-1]) for p in patch_embeds_list], axis=1 | |
| 264 | + ) | |
| 265 | + | |
| 266 | + patch_embeds = self.ln_pre(patch_embeds) | |
| 267 | + | |
| 268 | + position_ids = position_ids_in_meshgrid( | |
| 269 | + patch_embeds_list, | |
| 270 | + max_width=self.config.image_size // self.config.patch_size, | |
| 271 | + ) | |
| 272 | + | |
| 273 | + position_embedding = self.patch_positional_embedding(patch_embeds, position_ids) | |
| 274 | + | |
| 275 | + mask = generate_block_attention_mask( | |
| 276 | + [p.shape[2] * p.shape[1] for p in patch_embeds_list], patch_embeds | |
| 277 | + ) | |
| 278 | + | |
| 279 | + encoder_states = (patch_embeds,) if output_hidden_states else None | |
| 280 | + | |
| 281 | + for l in self.transformer.layers: | |
| 282 | + patch_embeds = l( | |
| 283 | + patch_embeds, mask=mask, position_embeddings=position_embedding | |
| 284 | + ) | |
| 285 | + if output_hidden_states: | |
| 286 | + encoder_states = encoder_states + (patch_embeds,) | |
| 287 | + | |
| 288 | + return patch_embeds, encoder_states | |
| 289 | + | |
| 290 | + | |
| 291 | +class VisionModel(nn.Module): | |
| 292 | + def __init__(self, config: VisionConfig): | |
| 293 | + super().__init__() | |
| 294 | + | |
| 295 | + self.model_type = config.model_type | |
| 296 | + if self.model_type not in ["clip_vision_model", "pixtral"]: | |
| 297 | + raise ValueError(f"Unsupported model type: {self.model_type}") | |
| 298 | + | |
| 299 | + self.vision_model = PixtralVisionModel(config) | |
| 300 | + | |
| 301 | + def __call__( | |
| 302 | + self, x: mx.array, output_hidden_states: Optional[bool] = None | |
| 303 | + ) -> mx.array: | |
| 304 | + return self.vision_model(x, output_hidden_states) | |
| 305 | + | |
| 306 | + def sanitize(self, weights): | |
| 307 | + sanitized_weights = {} | |
| 308 | + for k, v in weights.items(): | |
| 309 | + if "position_ids" in k: | |
| 310 | + # Remove unused position_ids | |
| 311 | + continue | |
| 312 | + elif "patch_conv.weight" in k: | |
| 313 | + # PyTorch conv2d weight tensors have shape: | |
| 314 | + # [out_channels, in_channels, kH, KW] | |
| 315 | + # MLX conv2d expects the weight be of shape: | |
| 316 | + # [out_channels, kH, KW, in_channels] | |
| 317 | + if check_array_shape(v): | |
| 318 | + sanitized_weights[k] = v | |
| 319 | + else: | |
| 320 | + sanitized_weights[k] = v.transpose(0, 2, 3, 1) | |
| 321 | + else: | |
| 322 | + sanitized_weights[k] = v | |
| 323 | + | |
| 324 | + return sanitized_weights |
modified mlx_vlm/models/qwen2_vl/vision.py +2 −2
| @@ -310,9 +310,9 @@ | ||
| 310 | 310 | max_grid_size = mx.max(grid_thw[:, 1:]) |
| 311 | 311 | rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size) |
| 312 | 312 | |
| 313 | - rotary_pos_emb_np = rotary_pos_emb_full[pos_ids] | |
| 313 | + rotary_pos_emb_full = rotary_pos_emb_full[pos_ids] | |
| 314 | 314 | |
| 315 | - return rotary_pos_emb_np.reshape(pos_ids.shape[0], -1) | |
| 315 | + return rotary_pos_emb_full.reshape(pos_ids.shape[0], -1) | |
| 316 | 316 | |
| 317 | 317 | def __call__( |
| 318 | 318 | self, |
modified mlx_vlm/prompt_utils.py +7 −2
| @@ -11,13 +11,13 @@ | ||
| 11 | 11 | Returns: |
| 12 | 12 | dict: A dictionary representing the JSON message for the specified model. |
| 13 | 13 | """ |
| 14 | - if model_name.lower() in ["idefics2", "qwen2_vl"]: | |
| 14 | + if model_name.lower() in ["idefics2", "qwen2_vl", "llava"]: | |
| 15 | 15 | message = { |
| 16 | 16 | "role": "user", |
| 17 | 17 | "content": [{"type": "image"}, {"type": "text", "text": prompt}], |
| 18 | 18 | } |
| 19 | 19 | |
| 20 | - elif model_name.lower() in ["llava-qwen2", "llava", "llava_next", "bunny-llama"]: | |
| 20 | + elif model_name.lower() in ["llava-qwen2", "llava_next", "bunny-llama"]: | |
| 21 | 21 | message = {"role": "user", "content": f"<image>\n{prompt}"} |
| 22 | 22 | elif model_name.lower() == "phi3_v": |
| 23 | 23 | message = {"role": "user", "content": f"<|image_1|>\n{prompt}"} |
| @@ -25,6 +25,11 @@ | ||
| 25 | 25 | message = {"role": "user", "content": f"<image>{prompt}"} |
| 26 | 26 | elif model_name.lower() == "paligemma": |
| 27 | 27 | message = prompt |
| 28 | + elif model_name.lower() == "pixtral": | |
| 29 | + message = { | |
| 30 | + "role": "user", | |
| 31 | + "content": [{"type": "image"}, {"type": "text", "content": prompt}], | |
| 32 | + } | |
| 28 | 33 | else: |
| 29 | 34 | raise ValueError(f"Unsupported model: {model_name}") |
| 30 | 35 |
modified mlx_vlm/utils.py +25 −9
| @@ -711,21 +711,37 @@ | ||
| 711 | 711 | if isinstance(image, str): |
| 712 | 712 | image = load_image(image) |
| 713 | 713 | |
| 714 | + image_grid_thw = None | |
| 714 | 715 | if image_processor is not None: |
| 715 | 716 | text_chunks = [processor(chunk).input_ids for chunk in prompt.split("<image>")] |
| 716 | 717 | input_ids = mx.array([text_chunks[0] + [image_token_index] + text_chunks[1]]) |
| 717 | - pixel_values = image_processor.preprocess(images=[image])[0] | |
| 718 | - pixel_values = mx.array(np.expand_dims(pixel_values, axis=0)) | |
| 718 | + pixel_values = mx.array(image_processor.preprocess(images=[image])[0]) | |
| 719 | + pixel_values = mx.array(mx.expand_dims(pixel_values, axis=0)) | |
| 719 | 720 | else: |
| 720 | - inputs = processor( | |
| 721 | - text=[prompt], images=[image], padding=True, return_tensors="np" | |
| 722 | - ) | |
| 723 | - pixel_values = mx.array(inputs["pixel_values"]) | |
| 721 | + processor.tokenizer.pad_token = processor.tokenizer.eos_token | |
| 722 | + try: | |
| 723 | + inputs = processor( | |
| 724 | + text=[prompt], images=[image], padding=True, return_tensors="mlx" | |
| 725 | + ) | |
| 726 | + except Exception as e: | |
| 727 | + inputs = processor( | |
| 728 | + text=prompt, images=[image], padding=True, return_tensors="mlx" | |
| 729 | + ) # for phi3_v model | |
| 730 | + | |
| 731 | + if isinstance(inputs["pixel_values"], list): | |
| 732 | + pixel_values = mx.array(inputs["pixel_values"][0][0])[None, :] | |
| 733 | + elif isinstance(inputs["pixel_values"], np.ndarray): | |
| 734 | + pixel_values = mx.array(inputs["pixel_values"]) | |
| 735 | + else: | |
| 736 | + raise ValueError( | |
| 737 | + f"Invalid pixel_values type: {type(inputs['pixel_values'])}" | |
| 738 | + ) | |
| 739 | + | |
| 724 | 740 | input_ids = mx.array(inputs["input_ids"]) |
| 725 | - mask = mx.array(inputs["attention_mask"]) | |
| 726 | - if "image_sizes" in inputs: | |
| 727 | - return input_ids, pixel_values, inputs["image_sizes"] | |
| 741 | + mask = inputs["attention_mask"] | |
| 728 | 742 | image_grid_thw = inputs.get("image_grid_thw", None) |
| 743 | + if "image_sizes" in inputs: | |
| 744 | + return input_ids, pixel_values, inputs["image_sizes"], image_grid_thw | |
| 729 | 745 | |
| 730 | 746 | return input_ids, pixel_values, mask, image_grid_thw |
| 731 | 747 |