Changesets · Branches · Tags · Compare
| Changeset | 7c44ddfdd473a376d7356ad13a949d19953995b9c17be982b560c4f0e47bfb9c |
|---|---|
| Author | JosefAlbers <146810011+JosefAlbers@users.noreply.github.com> · 2024-06-25 01:12 +09:00 |
| Committer | GitHub <noreply@github.com> · 2024-06-24 18:12 +02:00 |
| Parents | 9a3345f9faa1 |
9 files changed
added mlx_vlm/models/phi3_v/__init__.py +8 −0
| @@ -0,0 +1,8 @@ | ||
| 1 | +from .phi3_v import ( | |
| 2 | + LanguageModel, | |
| 3 | + Model, | |
| 4 | + ModelConfig, | |
| 5 | + TextConfig, | |
| 6 | + VisionConfig, | |
| 7 | + VisionModel, | |
| 8 | +) |
added mlx_vlm/models/phi3_v/language.py +19 −0
| @@ -0,0 +1,19 @@ | ||
| 1 | +import inspect | |
| 2 | +from dataclasses import dataclass | |
| 3 | + | |
| 4 | + | |
| 5 | +@dataclass | |
| 6 | +class TextConfig: | |
| 7 | + @classmethod | |
| 8 | + def from_dict(cls, params): | |
| 9 | + return cls( | |
| 10 | + **{ | |
| 11 | + k: v | |
| 12 | + for k, v in params.items() | |
| 13 | + if k in inspect.signature(cls).parameters | |
| 14 | + } | |
| 15 | + ) | |
| 16 | + | |
| 17 | + | |
| 18 | +class LanguageModel: | |
| 19 | + pass |
added mlx_vlm/models/phi3_v/phi3_v.py +234 −0
| @@ -0,0 +1,234 @@ | ||
| 1 | +import inspect | |
| 2 | +import math | |
| 3 | +from dataclasses import dataclass | |
| 4 | +from types import SimpleNamespace | |
| 5 | +from typing import Dict, Optional, Tuple, Union | |
| 6 | + | |
| 7 | +import mlx.core as mx | |
| 8 | +import mlx.nn as nn | |
| 9 | +import numpy as np | |
| 10 | + | |
| 11 | +from .language import LanguageModel, TextConfig | |
| 12 | +from .su_rope import Phi3SuScaledRotaryEmbedding | |
| 13 | +from .vision import VisionConfig, VisionModel | |
| 14 | + | |
| 15 | + | |
| 16 | +@dataclass | |
| 17 | +class ModelConfig: | |
| 18 | + text_config: TextConfig | |
| 19 | + vision_config: VisionConfig | |
| 20 | + model_type: str | |
| 21 | + vocab_size: int | |
| 22 | + | |
| 23 | + num_hidden_layers: int | |
| 24 | + intermediate_size: int | |
| 25 | + num_attention_heads: int | |
| 26 | + rms_norm_eps: float | |
| 27 | + | |
| 28 | + ignore_index: int = -100 | |
| 29 | + image_token_index: int = 257152 | |
| 30 | + hidden_size: int = 2048 | |
| 31 | + pad_token_id: int = 0 | |
| 32 | + | |
| 33 | + num_key_value_heads: int = None | |
| 34 | + rope_theta: float = 10000 | |
| 35 | + rope_traditional: bool = False | |
| 36 | + rope_scaling: Optional[Dict[str, Union[float, str]]] = None | |
| 37 | + max_position_embeddings: int = 131072 | |
| 38 | + original_max_position_embeddings: int = 4096 | |
| 39 | + | |
| 40 | + @classmethod | |
| 41 | + def from_dict(cls, params): | |
| 42 | + return cls( | |
| 43 | + **{ | |
| 44 | + k: v | |
| 45 | + for k, v in params.items() | |
| 46 | + if k in inspect.signature(cls).parameters | |
| 47 | + } | |
| 48 | + ) | |
| 49 | + | |
| 50 | + | |
| 51 | +class Attention(nn.Module): | |
| 52 | + def __init__(self, args: TextConfig): | |
| 53 | + super().__init__() | |
| 54 | + | |
| 55 | + dim = args.hidden_size | |
| 56 | + self.n_heads = n_heads = args.num_attention_heads | |
| 57 | + self.n_kv_heads = n_kv_heads = args.num_key_value_heads | |
| 58 | + self.num_hidden_layers = args.num_hidden_layers | |
| 59 | + | |
| 60 | + self.head_dim = head_dim = args.hidden_size // n_heads | |
| 61 | + self.scale = head_dim**-0.5 | |
| 62 | + | |
| 63 | + op_size = n_heads * head_dim + 2 * (n_kv_heads * head_dim) | |
| 64 | + self.qkv_proj = nn.Linear(dim, op_size, bias=False) | |
| 65 | + self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False) | |
| 66 | + | |
| 67 | + rope_scale = 1.0 | |
| 68 | + if args.rope_scaling and args.rope_scaling["type"] == "su": | |
| 69 | + self.rope = Phi3SuScaledRotaryEmbedding( | |
| 70 | + head_dim, | |
| 71 | + traditional=False, | |
| 72 | + base=args.rope_theta, | |
| 73 | + scale=rope_scale, | |
| 74 | + max_position_embeddings=args.max_position_embeddings, | |
| 75 | + original_max_position_embeddings=args.original_max_position_embeddings, | |
| 76 | + short_factor=args.rope_scaling["short_factor"], | |
| 77 | + long_factor=args.rope_scaling["long_factor"], | |
| 78 | + ) | |
| 79 | + else: | |
| 80 | + if args.rope_scaling and args.rope_scaling["type"] == "linear": | |
| 81 | + rope_scale = 1 / args.rope_scaling["factor"] | |
| 82 | + self.rope = nn.RoPE( | |
| 83 | + head_dim, | |
| 84 | + traditional=args.rope_traditional, | |
| 85 | + base=args.rope_theta, | |
| 86 | + scale=rope_scale, | |
| 87 | + ) | |
| 88 | + | |
| 89 | + def __call__( | |
| 90 | + self, | |
| 91 | + x: mx.array, | |
| 92 | + mask: Optional[mx.array] = None, | |
| 93 | + cache: Optional[Tuple[mx.array, mx.array]] = None, | |
| 94 | + ) -> mx.array: | |
| 95 | + B, L, D = x.shape | |
| 96 | + | |
| 97 | + qkv = self.qkv_proj(x) | |
| 98 | + query_pos = self.n_heads * self.head_dim | |
| 99 | + queries, keys, values = mx.split( | |
| 100 | + qkv, [query_pos, query_pos + self.n_kv_heads * self.head_dim], axis=-1 | |
| 101 | + ) | |
| 102 | + | |
| 103 | + queries = queries.reshape(B, L, self.n_heads, -1).transpose(0, 2, 1, 3) | |
| 104 | + keys = keys.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3) | |
| 105 | + values = values.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3) | |
| 106 | + | |
| 107 | + if cache is not None: | |
| 108 | + offset = cache[0].shape[2] | |
| 109 | + queries = self.rope(queries, offset=offset) | |
| 110 | + keys = self.rope(keys, offset=offset) | |
| 111 | + keys = mx.concatenate([cache[0], keys], axis=2) | |
| 112 | + values = mx.concatenate([cache[1], values], axis=2) | |
| 113 | + else: | |
| 114 | + queries = self.rope(queries) | |
| 115 | + keys = self.rope(keys) | |
| 116 | + | |
| 117 | + output = mx.fast.scaled_dot_product_attention( | |
| 118 | + queries, keys, values, scale=self.scale, mask=mask | |
| 119 | + ) | |
| 120 | + output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) | |
| 121 | + return self.o_proj(output), (keys, values) | |
| 122 | + | |
| 123 | + | |
| 124 | +class MLP(nn.Module): | |
| 125 | + def __init__(self, dim, hidden_dim): | |
| 126 | + super().__init__() | |
| 127 | + self.gate_up_proj = nn.Linear(dim, 2 * hidden_dim, bias=False) | |
| 128 | + self.down_proj = nn.Linear(hidden_dim, dim, bias=False) | |
| 129 | + | |
| 130 | + def __call__(self, x) -> mx.array: | |
| 131 | + x = self.gate_up_proj(x) | |
| 132 | + gate, x = mx.split(x, 2, axis=-1) | |
| 133 | + return self.down_proj(nn.silu(gate) * x) | |
| 134 | + | |
| 135 | + | |
| 136 | +class TransformerBlock(nn.Module): | |
| 137 | + def __init__(self, args: TextConfig): | |
| 138 | + super().__init__() | |
| 139 | + self.num_attention_heads = args.num_attention_heads | |
| 140 | + self.hidden_size = args.hidden_size | |
| 141 | + self.self_attn = Attention(args) | |
| 142 | + self.mlp = MLP(args.hidden_size, args.intermediate_size) | |
| 143 | + self.input_layernorm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) | |
| 144 | + self.post_attention_layernorm = nn.RMSNorm( | |
| 145 | + args.hidden_size, eps=args.rms_norm_eps | |
| 146 | + ) | |
| 147 | + self.args = args | |
| 148 | + | |
| 149 | + def __call__( | |
| 150 | + self, | |
| 151 | + x: mx.array, | |
| 152 | + mask: Optional[mx.array] = None, | |
| 153 | + cache: Optional[Tuple[mx.array, mx.array]] = None, | |
| 154 | + ) -> mx.array: | |
| 155 | + r, cache = self.self_attn(self.input_layernorm(x), mask, cache) | |
| 156 | + h = x + r | |
| 157 | + r = self.mlp(self.post_attention_layernorm(h)) | |
| 158 | + out = h + r | |
| 159 | + return out, cache | |
| 160 | + | |
| 161 | + | |
| 162 | +class Phi3V(nn.Module): | |
| 163 | + def __init__(self, args: TextConfig): | |
| 164 | + super().__init__() | |
| 165 | + self.args = args | |
| 166 | + self.vocab_size = args.vocab_size | |
| 167 | + self.num_hidden_layers = args.num_hidden_layers | |
| 168 | + self.embed_tokens = nn.Embedding(args.vocab_size, args.hidden_size) | |
| 169 | + self.vision_embed_tokens = VisionModel(args) | |
| 170 | + self.layers = [ | |
| 171 | + TransformerBlock(args=args) for _ in range(args.num_hidden_layers) | |
| 172 | + ] | |
| 173 | + self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) | |
| 174 | + | |
| 175 | + def __call__( | |
| 176 | + self, | |
| 177 | + inputs: mx.array, | |
| 178 | + pixel_values=None, | |
| 179 | + image_sizes=None, | |
| 180 | + cache=None, | |
| 181 | + ): | |
| 182 | + # print('inputs', inputs) # debug | |
| 183 | + h = self.embed_tokens(inputs) | |
| 184 | + p = np.argwhere(inputs < 0).tolist() | |
| 185 | + if pixel_values is not None: | |
| 186 | + h = self.vision_embed_tokens(pixel_values, h, image_sizes, p) | |
| 187 | + mask = None | |
| 188 | + if h.shape[1] > 1: | |
| 189 | + mask = nn.MultiHeadAttention.create_additive_causal_mask(h.shape[1]) | |
| 190 | + mask = mask.astype(h.dtype) | |
| 191 | + if cache is None: | |
| 192 | + cache = [None] * len(self.layers) | |
| 193 | + for i, layer in enumerate(self.layers): | |
| 194 | + h, cache[i] = layer(h, mask, cache[i]) | |
| 195 | + return self.norm(h), cache | |
| 196 | + | |
| 197 | + | |
| 198 | +class Model(nn.Module): | |
| 199 | + def __init__(self, args: TextConfig): | |
| 200 | + super().__init__() | |
| 201 | + self.model_type = args.model_type | |
| 202 | + self.model = Phi3V(args) | |
| 203 | + self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False) | |
| 204 | + self.config = args | |
| 205 | + | |
| 206 | + def __call__( | |
| 207 | + self, | |
| 208 | + inputs: mx.array, | |
| 209 | + pixel_values=None, | |
| 210 | + mask=None, | |
| 211 | + cache=None, | |
| 212 | + ): | |
| 213 | + out, cache = self.model(inputs, pixel_values, mask, cache) | |
| 214 | + return self.lm_head(out).astype(self.lm_head.weight.dtype), cache | |
| 215 | + | |
| 216 | + @property | |
| 217 | + def layers(self): | |
| 218 | + return self.model.layers | |
| 219 | + | |
| 220 | + @property | |
| 221 | + def head_dim(self): | |
| 222 | + return self.args.hidden_size // self.args.num_attention_heads | |
| 223 | + | |
| 224 | + @property | |
| 225 | + def n_kv_heads(self): | |
| 226 | + return self.args.num_key_value_heads | |
| 227 | + | |
| 228 | + @property | |
| 229 | + def language_model(self): | |
| 230 | + return self | |
| 231 | + | |
| 232 | + @property | |
| 233 | + def vision_model(self): | |
| 234 | + return self.model.vision_embed_tokens |
added mlx_vlm/models/phi3_v/su_rope.py +71 −0
| @@ -0,0 +1,71 @@ | ||
| 1 | +import math | |
| 2 | + | |
| 3 | +import mlx.core as mx | |
| 4 | + | |
| 5 | + | |
| 6 | +class Phi3SuScaledRotaryEmbedding: | |
| 7 | + def __init__( | |
| 8 | + self, | |
| 9 | + dims: int, | |
| 10 | + traditional: bool = False, | |
| 11 | + base: float = 10000.0, | |
| 12 | + scale: float = 1.0, | |
| 13 | + max_position_embeddings: int = 131072, | |
| 14 | + original_max_position_embeddings: int = 4096, | |
| 15 | + short_factor: list[float] | float = 1.0, | |
| 16 | + long_factor: list[float] | float = 1.0, | |
| 17 | + ): | |
| 18 | + """ | |
| 19 | + Phi3Su Scaled Rotary Embedding layer for Phi-3 models. | |
| 20 | + | |
| 21 | + Args: | |
| 22 | + dims (int): The feature dimensions to be rotated. | |
| 23 | + traditional (bool, optional): Unused. Default: ``False``. | |
| 24 | + base (int, optional): Base for the exponential scaling. | |
| 25 | + scale (float, optional): The scale used to scale the positions. Default: 1.0. | |
| 26 | + max_position_embeddings (int, optional): The maximum sequence length that this model was trained with. This is used to determine the size of the original RoPE embeddings when using long scaling. Default: 131072. | |
| 27 | + original_max_position_embeddings (int, optional): The maximum sequence length that this model was trained with. This is used to determine the size of the original RoPE embeddings when using long scaling. Default: 4096. | |
| 28 | + short_factor (float or list of floats, optional): List of scaling factors for sequences of length lesser than original_max_position_embeddings. Default: 1.0. | |
| 29 | + long_factor (float or list of floats, optional): List of scaling factors for sequences of length greater than original_max_position_embeddings. Default: 1.0. | |
| 30 | + """ | |
| 31 | + self.inv_freq_short = 1.0 / ( | |
| 32 | + mx.array(short_factor, dtype=mx.float32) | |
| 33 | + * base ** (mx.arange(0, dims, 2, dtype=mx.float32) / dims) | |
| 34 | + ) | |
| 35 | + self.inv_freq_long = 1.0 / ( | |
| 36 | + scale | |
| 37 | + * mx.array(long_factor, dtype=mx.float32) | |
| 38 | + * base ** (mx.arange(0, dims, 2, dtype=mx.float32) / dims) | |
| 39 | + ) | |
| 40 | + self.original_max_position_embeddings = original_max_position_embeddings | |
| 41 | + self.scaling_factor = math.sqrt( | |
| 42 | + 1 | |
| 43 | + + math.log(max_position_embeddings / original_max_position_embeddings) | |
| 44 | + / math.log(original_max_position_embeddings) | |
| 45 | + ) | |
| 46 | + | |
| 47 | + def _get_cos_sin(self, offset, L): | |
| 48 | + position_ids = mx.arange(offset, offset + L, dtype=mx.float32)[None] | |
| 49 | + inv_freq = ( | |
| 50 | + self.inv_freq_long | |
| 51 | + if position_ids.max() + 1 > self.original_max_position_embeddings | |
| 52 | + else self.inv_freq_short | |
| 53 | + ) | |
| 54 | + inv_freq_expanded = mx.repeat( | |
| 55 | + inv_freq[None, :, None], position_ids.shape[0], axis=0 | |
| 56 | + ) | |
| 57 | + position_ids_expanded = position_ids[:, None, :] | |
| 58 | + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(0, 2, 1) | |
| 59 | + emb = mx.concatenate([freqs, freqs], axis=-1) | |
| 60 | + cos = mx.cos(emb) * self.scaling_factor | |
| 61 | + sin = mx.sin(emb) * self.scaling_factor | |
| 62 | + return mx.expand_dims(cos, axis=1), mx.expand_dims(sin, axis=1) | |
| 63 | + | |
| 64 | + def __call__(self, x, offset: int = 0): | |
| 65 | + def _rotate_half(_x): | |
| 66 | + midpoint = _x.shape[-1] // 2 | |
| 67 | + x1, x2 = _x[..., :midpoint], _x[..., midpoint:] | |
| 68 | + return mx.concatenate([-x2, x1], axis=-1) | |
| 69 | + | |
| 70 | + cos, sin = self._get_cos_sin(offset, x.shape[2]) | |
| 71 | + return (x * cos) + (_rotate_half(x) * sin) |
added mlx_vlm/models/phi3_v/vision.py +324 −0
| @@ -0,0 +1,324 @@ | ||
| 1 | +import inspect | |
| 2 | +import math | |
| 3 | +from dataclasses import dataclass | |
| 4 | +from types import SimpleNamespace | |
| 5 | +from typing import Optional | |
| 6 | + | |
| 7 | +import mlx.core as mx | |
| 8 | +import mlx.nn as nn | |
| 9 | +import numpy as np | |
| 10 | + | |
| 11 | + | |
| 12 | +@dataclass | |
| 13 | +class VisionConfig: | |
| 14 | + model_type: str = "phi3_v" | |
| 15 | + num_hidden_layers: int = 24 | |
| 16 | + hidden_size: int = 1024 | |
| 17 | + intermediate_size: int = 4096 | |
| 18 | + num_attention_heads: int = 16 | |
| 19 | + image_size: int = 336 | |
| 20 | + patch_size: int = 14 | |
| 21 | + projection_dim: int = 768 | |
| 22 | + vocab_size: int = 32000 | |
| 23 | + num_channels: int = 3 | |
| 24 | + layer_norm_eps: float = 1e-5 | |
| 25 | + image_dim_out: int = (1024,) | |
| 26 | + model_name: str = "openai/clip-vit-large-patch14-336" | |
| 27 | + name: str = "clip_vision_model" | |
| 28 | + num_img_tokens: int = 144 | |
| 29 | + | |
| 30 | + @classmethod | |
| 31 | + def from_dict(cls, params): | |
| 32 | + return cls( | |
| 33 | + **{ | |
| 34 | + k: v | |
| 35 | + for k, v in params.items() | |
| 36 | + if k in inspect.signature(cls).parameters | |
| 37 | + } | |
| 38 | + ) | |
| 39 | + | |
| 40 | + | |
| 41 | +def check_array_shape(arr): | |
| 42 | + shape = arr.shape | |
| 43 | + | |
| 44 | + # Check if the shape has 4 dimensions | |
| 45 | + if len(shape) != 4: | |
| 46 | + return False | |
| 47 | + | |
| 48 | + out_channels, kH, KW, _ = shape | |
| 49 | + | |
| 50 | + # Check if out_channels is the largest, and kH and KW are the same | |
| 51 | + if (out_channels >= kH) and (out_channels >= KW) and (kH == KW): | |
| 52 | + return True | |
| 53 | + else: | |
| 54 | + return False | |
| 55 | + | |
| 56 | + | |
| 57 | +class Attention(nn.Module): | |
| 58 | + def __init__( | |
| 59 | + self, | |
| 60 | + dims: int, | |
| 61 | + num_heads: int, | |
| 62 | + query_input_dims: Optional[int] = None, | |
| 63 | + key_input_dims: Optional[int] = None, | |
| 64 | + value_input_dims: Optional[int] = None, | |
| 65 | + value_dims: Optional[int] = None, | |
| 66 | + value_output_dims: Optional[int] = None, | |
| 67 | + bias: bool = False, | |
| 68 | + ): | |
| 69 | + super().__init__() | |
| 70 | + | |
| 71 | + if (dims % num_heads) != 0: | |
| 72 | + raise ValueError( | |
| 73 | + "The input feature dimensions should be divisible by the " | |
| 74 | + f"number of heads ({dims} % {num_heads}) != 0" | |
| 75 | + ) | |
| 76 | + | |
| 77 | + query_input_dims = query_input_dims or dims | |
| 78 | + key_input_dims = key_input_dims or dims | |
| 79 | + value_input_dims = value_input_dims or key_input_dims | |
| 80 | + value_dims = value_dims or dims | |
| 81 | + value_output_dims = value_output_dims or dims | |
| 82 | + | |
| 83 | + self.num_heads = num_heads = num_heads | |
| 84 | + head_dim = dims // num_heads | |
| 85 | + self.scale = head_dim**-0.5 | |
| 86 | + | |
| 87 | + self.q_proj = nn.Linear(query_input_dims, dims, bias=bias) | |
| 88 | + self.k_proj = nn.Linear(key_input_dims, dims, bias=bias) | |
| 89 | + self.v_proj = nn.Linear(value_input_dims, value_dims, bias=bias) | |
| 90 | + self.out_proj = nn.Linear(value_dims, value_output_dims, bias=bias) | |
| 91 | + | |
| 92 | + def __call__(self, queries, keys, values, mask=None): | |
| 93 | + queries = self.q_proj(queries) | |
| 94 | + keys = self.k_proj(keys) | |
| 95 | + values = self.v_proj(values) | |
| 96 | + | |
| 97 | + num_heads = self.num_heads | |
| 98 | + B, L, D = queries.shape | |
| 99 | + _, S, _ = keys.shape | |
| 100 | + queries = queries.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3) | |
| 101 | + keys = keys.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3) | |
| 102 | + values = values.reshape(B, S, num_heads, -1).transpose(0, 2, 1, 3) | |
| 103 | + | |
| 104 | + output = mx.fast.scaled_dot_product_attention( | |
| 105 | + queries, keys, values, scale=self.scale, mask=mask | |
| 106 | + ) | |
| 107 | + output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) | |
| 108 | + | |
| 109 | + return self.out_proj(output) | |
| 110 | + | |
| 111 | + | |
| 112 | +class MLP(nn.Module): | |
| 113 | + def __init__(self, config: VisionConfig): | |
| 114 | + super().__init__() | |
| 115 | + self.activation_fn = nn.GELU(approx="fast") | |
| 116 | + self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size) | |
| 117 | + self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size) | |
| 118 | + | |
| 119 | + def __call__(self, x: mx.array) -> mx.array: | |
| 120 | + x = self.activation_fn(self.fc1(x)) | |
| 121 | + x = self.fc2(x) | |
| 122 | + return x | |
| 123 | + | |
| 124 | + | |
| 125 | +class EncoderLayer(nn.Module): | |
| 126 | + def __init__(self, config: VisionConfig): | |
| 127 | + super().__init__() | |
| 128 | + self.embed_dim = config.hidden_size | |
| 129 | + self.self_attn = Attention( | |
| 130 | + config.hidden_size, config.num_attention_heads, bias=True | |
| 131 | + ) | |
| 132 | + self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) | |
| 133 | + self.mlp = MLP(config) | |
| 134 | + self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) | |
| 135 | + | |
| 136 | + def __call__(self, x: mx.array, mask: Optional[mx.array] = None) -> mx.array: | |
| 137 | + y = self.layer_norm1(x) | |
| 138 | + y = self.self_attn(y, y, y, mask) | |
| 139 | + x = x + y | |
| 140 | + y = self.layer_norm2(x) | |
| 141 | + y = self.mlp(y) | |
| 142 | + return x + y | |
| 143 | + | |
| 144 | + | |
| 145 | +class Encoder(nn.Module): | |
| 146 | + def __init__(self, config: VisionConfig): | |
| 147 | + super().__init__() | |
| 148 | + self.layers = [EncoderLayer(config) for _ in range(config.num_hidden_layers)] | |
| 149 | + | |
| 150 | + | |
| 151 | +class VisionEmbeddings(nn.Module): | |
| 152 | + def __init__(self, config: VisionConfig): | |
| 153 | + super().__init__() | |
| 154 | + self.config = config | |
| 155 | + self.embed_dim = config.hidden_size | |
| 156 | + self.image_size = config.image_size | |
| 157 | + self.patch_size = config.patch_size | |
| 158 | + | |
| 159 | + self.class_embedding = mx.zeros((config.hidden_size,)) | |
| 160 | + | |
| 161 | + self.patch_embedding = nn.Conv2d( | |
| 162 | + in_channels=config.num_channels, | |
| 163 | + out_channels=self.embed_dim, | |
| 164 | + kernel_size=self.patch_size, | |
| 165 | + stride=self.patch_size, | |
| 166 | + bias=False, | |
| 167 | + ) | |
| 168 | + | |
| 169 | + self.num_patches = (self.image_size // self.patch_size) ** 2 | |
| 170 | + self.num_positions = self.num_patches + 1 | |
| 171 | + self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim) | |
| 172 | + | |
| 173 | + def __call__(self, x: mx.array) -> mx.array: | |
| 174 | + batch_size = x.shape[0] | |
| 175 | + patch_embeddings = self.patch_embedding(x) | |
| 176 | + patch_embeddings = mx.flatten(patch_embeddings, start_axis=1, end_axis=2) | |
| 177 | + embed_dim = patch_embeddings.shape[-1] | |
| 178 | + cls_embeddings = mx.broadcast_to( | |
| 179 | + self.class_embedding, (batch_size, 1, embed_dim) | |
| 180 | + ) | |
| 181 | + position_ids = mx.array(np.arange(self.num_positions)[None, :]) | |
| 182 | + | |
| 183 | + embeddings = mx.concatenate((cls_embeddings, patch_embeddings), axis=1) | |
| 184 | + embeddings += self.position_embedding(position_ids) | |
| 185 | + return embeddings | |
| 186 | + | |
| 187 | + | |
| 188 | +class ClipModel(nn.Module): | |
| 189 | + def __init__(self, config: VisionConfig): | |
| 190 | + super().__init__() | |
| 191 | + self.model_type = config.model_type | |
| 192 | + self.embeddings = VisionEmbeddings(config) | |
| 193 | + self.pre_layrnorm = nn.LayerNorm(config.hidden_size) | |
| 194 | + self.encoder = Encoder(config) | |
| 195 | + self.post_layernorm = nn.LayerNorm(config.hidden_size) | |
| 196 | + | |
| 197 | + def __call__( | |
| 198 | + self, | |
| 199 | + x: mx.array, | |
| 200 | + output_hidden_states: Optional[bool] = None, | |
| 201 | + ) -> mx.array: | |
| 202 | + x = self.embeddings(x) | |
| 203 | + x = self.pre_layrnorm(x) | |
| 204 | + | |
| 205 | + encoder_states = (x,) if output_hidden_states else None | |
| 206 | + | |
| 207 | + for l in self.encoder.layers: | |
| 208 | + x = l(x, mask=None) | |
| 209 | + if output_hidden_states: | |
| 210 | + encoder_states = encoder_states + (x,) | |
| 211 | + | |
| 212 | + pooler_output = self.post_layernorm(x[:, 0, :]) | |
| 213 | + return pooler_output, x, encoder_states | |
| 214 | + | |
| 215 | + | |
| 216 | +class ClipVModel(nn.Module): | |
| 217 | + def __init__(self, config): | |
| 218 | + super().__init__() | |
| 219 | + self.model_type = config.model_type | |
| 220 | + self.vision_model = ClipModel(config) | |
| 221 | + | |
| 222 | + | |
| 223 | +class VisionModel(nn.Module): | |
| 224 | + CLIP_VIT_LARGE_PATCH14_336_CONFIG = SimpleNamespace( | |
| 225 | + model_type="phi3_v", | |
| 226 | + hidden_size=1024, | |
| 227 | + image_size=336, | |
| 228 | + intermediate_size=4096, | |
| 229 | + layer_norm_eps=1e-05, | |
| 230 | + num_attention_heads=16, | |
| 231 | + num_channels=3, | |
| 232 | + num_hidden_layers=24, | |
| 233 | + patch_size=14, | |
| 234 | + ) | |
| 235 | + | |
| 236 | + def __init__(self, config): | |
| 237 | + super().__init__() | |
| 238 | + self.model_type = config.model_type | |
| 239 | + self.img_processor = ClipVModel(self.CLIP_VIT_LARGE_PATCH14_336_CONFIG) | |
| 240 | + self.image_dim_out = image_dim_out = 1024 | |
| 241 | + self.glb_GN = mx.zeros([1, 1, image_dim_out * 4]) | |
| 242 | + self.sub_GN = mx.zeros([1, 1, 1, image_dim_out * 4]) | |
| 243 | + self.img_projection = [ | |
| 244 | + nn.Linear(image_dim_out * 4, config.hidden_size), | |
| 245 | + nn.GELU(), | |
| 246 | + nn.Linear(config.hidden_size, config.hidden_size), | |
| 247 | + ] | |
| 248 | + | |
| 249 | + def __call__( | |
| 250 | + self, | |
| 251 | + img_embeds, | |
| 252 | + txt_embeds=None, | |
| 253 | + img_sizes=None, | |
| 254 | + positions=None, | |
| 255 | + output_hidden_states=None, | |
| 256 | + ): | |
| 257 | + if output_hidden_states: | |
| 258 | + return self.img_processor.vision_model( | |
| 259 | + img_embeds, output_hidden_states=output_hidden_states | |
| 260 | + ) | |
| 261 | + img_embeds = mx.array(img_embeds) | |
| 262 | + img_sizes = mx.array(img_sizes) | |
| 263 | + B = img_embeds.shape[0] | |
| 264 | + img_sizes = (img_sizes // 336).tolist() | |
| 265 | + img_features = self.img_processor.vision_model( | |
| 266 | + img_embeds.reshape(-1, *img_embeds.shape[2:]).transpose(0, 2, 3, 1), True | |
| 267 | + )[-1][-2][:, 1:] | |
| 268 | + img_features = img_features.reshape(B, -1, *img_features.shape[1:]) | |
| 269 | + C, H = self.image_dim_out, int(img_features.shape[2] ** 0.5) | |
| 270 | + output_imgs, output_len = [], [] | |
| 271 | + for _bs in range(B): | |
| 272 | + h, w = img_sizes[_bs] | |
| 273 | + B_ = h * w | |
| 274 | + | |
| 275 | + def _reshape_and_concatenate(img, shape, tile_shape): | |
| 276 | + return mx.concatenate( | |
| 277 | + [ | |
| 278 | + img.reshape(shape) | |
| 279 | + .transpose(0, 1, 3, 2, 4, 5) | |
| 280 | + .reshape(tile_shape), | |
| 281 | + mx.tile(self.sub_GN, (1, tile_shape[1], 1, 1)), | |
| 282 | + ], | |
| 283 | + axis=2, | |
| 284 | + ).reshape(1, -1, 4 * C) | |
| 285 | + | |
| 286 | + glb_img = _reshape_and_concatenate( | |
| 287 | + img_features[_bs, :1], | |
| 288 | + (1, H // 2, 2, H // 2, 2, C), | |
| 289 | + (1, H // 2, H // 2, 4 * C), | |
| 290 | + ) | |
| 291 | + sub_img = _reshape_and_concatenate( | |
| 292 | + img_features[_bs, 1 : B_ + 1], | |
| 293 | + (B_, H // 2, 2, H // 2, 2, C), | |
| 294 | + (1, h * 12, w * 12, 4 * C), | |
| 295 | + ) | |
| 296 | + x = mx.concatenate([sub_img, self.glb_GN, glb_img], axis=1) | |
| 297 | + for l in self.img_projection: | |
| 298 | + x = l(x) | |
| 299 | + output_imgs.append(np.array(x.astype(mx.float32))) | |
| 300 | + output_len.append(int((h * w + 1) * 144 + 1 + (h + 1) * 12)) | |
| 301 | + idx = 0 | |
| 302 | + txt_embeds = np.array(txt_embeds.astype(mx.float32)) | |
| 303 | + for i, cnt in enumerate(output_len): | |
| 304 | + txt_embeds[ | |
| 305 | + positions[idx][0], positions[idx][1] : positions[idx][1] + cnt | |
| 306 | + ] = output_imgs[i] | |
| 307 | + idx += cnt | |
| 308 | + txt_embeds = mx.array(txt_embeds) | |
| 309 | + return txt_embeds | |
| 310 | + | |
| 311 | + def sanitize(self, weights): | |
| 312 | + sanitized_weights = {} | |
| 313 | + for k, v in weights.items(): | |
| 314 | + if "position_ids" in k: | |
| 315 | + continue | |
| 316 | + elif "patch_embedding.weight" in k: | |
| 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/prompt_utils.py +2 −0
| @@ -18,6 +18,8 @@ | ||
| 18 | 18 | } |
| 19 | 19 | elif model_name.lower() in ["llava-qwen2", "llava", "llava_next"]: |
| 20 | 20 | message = {"role": "user", "content": f"<image>\n{prompt}"} |
| 21 | + elif model_name.lower() == "phi3_v": | |
| 22 | + message = {"role": "user", "content": f"<|image_1|>\n{prompt}"} | |
| 21 | 23 | elif model_name.lower() == "multi_modality": |
| 22 | 24 | message = {"role": "user", "content": f"<image>{prompt}"} |
| 23 | 25 | elif model_name.lower() == "paligemma": |
modified mlx_vlm/tests/test_models.py +151 −0
| @@ -469,6 +469,157 @@ | ||
| 469 | 469 | (args.vision_config.image_size, args.vision_config.image_size), |
| 470 | 470 | ) |
| 471 | 471 | |
| 472 | + def test_phi3_v(self): | |
| 473 | + from mlx_vlm.models import phi3_v | |
| 474 | + | |
| 475 | + text_config = phi3_v.TextConfig() | |
| 476 | + | |
| 477 | + vision_config = phi3_v.VisionConfig( | |
| 478 | + model_type="phi3_v", | |
| 479 | + image_dim_out=1024, | |
| 480 | + model_name="openai/clip-vit-large-patch14-336", | |
| 481 | + name="clip_vision_model", | |
| 482 | + num_img_tokens=144, | |
| 483 | + ) | |
| 484 | + | |
| 485 | + args = phi3_v.ModelConfig( | |
| 486 | + text_config=text_config, | |
| 487 | + vision_config=vision_config, | |
| 488 | + **{ | |
| 489 | + "hidden_size": 3072, | |
| 490 | + "intermediate_size": 8192, | |
| 491 | + "max_position_embeddings": 131072, | |
| 492 | + "model_type": "phi3_v", | |
| 493 | + "num_attention_heads": 32, | |
| 494 | + "num_hidden_layers": 32, | |
| 495 | + "num_key_value_heads": 32, | |
| 496 | + "original_max_position_embeddings": 4096, | |
| 497 | + "rms_norm_eps": 1e-05, | |
| 498 | + "rope_scaling": { | |
| 499 | + "long_factor": [ | |
| 500 | + 1.0299999713897705, | |
| 501 | + 1.0499999523162842, | |
| 502 | + 1.0499999523162842, | |
| 503 | + 1.0799999237060547, | |
| 504 | + 1.2299998998641968, | |
| 505 | + 1.2299998998641968, | |
| 506 | + 1.2999999523162842, | |
| 507 | + 1.4499999284744263, | |
| 508 | + 1.5999999046325684, | |
| 509 | + 1.6499998569488525, | |
| 510 | + 1.8999998569488525, | |
| 511 | + 2.859999895095825, | |
| 512 | + 3.68999981880188, | |
| 513 | + 5.419999599456787, | |
| 514 | + 5.489999771118164, | |
| 515 | + 5.489999771118164, | |
| 516 | + 9.09000015258789, | |
| 517 | + 11.579999923706055, | |
| 518 | + 15.65999984741211, | |
| 519 | + 15.769999504089355, | |
| 520 | + 15.789999961853027, | |
| 521 | + 18.360000610351562, | |
| 522 | + 21.989999771118164, | |
| 523 | + 23.079999923706055, | |
| 524 | + 30.009998321533203, | |
| 525 | + 32.35000228881836, | |
| 526 | + 32.590003967285156, | |
| 527 | + 35.56000518798828, | |
| 528 | + 39.95000457763672, | |
| 529 | + 53.840003967285156, | |
| 530 | + 56.20000457763672, | |
| 531 | + 57.95000457763672, | |
| 532 | + 59.29000473022461, | |
| 533 | + 59.77000427246094, | |
| 534 | + 59.920005798339844, | |
| 535 | + 61.190006256103516, | |
| 536 | + 61.96000671386719, | |
| 537 | + 62.50000762939453, | |
| 538 | + 63.3700065612793, | |
| 539 | + 63.48000717163086, | |
| 540 | + 63.48000717163086, | |
| 541 | + 63.66000747680664, | |
| 542 | + 63.850006103515625, | |
| 543 | + 64.08000946044922, | |
| 544 | + 64.760009765625, | |
| 545 | + 64.80001068115234, | |
| 546 | + 64.81001281738281, | |
| 547 | + 64.81001281738281, | |
| 548 | + ], | |
| 549 | + "short_factor": [ | |
| 550 | + 1.05, | |
| 551 | + 1.05, | |
| 552 | + 1.05, | |
| 553 | + 1.1, | |
| 554 | + 1.1, | |
| 555 | + 1.1, | |
| 556 | + 1.2500000000000002, | |
| 557 | + 1.2500000000000002, | |
| 558 | + 1.4000000000000004, | |
| 559 | + 1.4500000000000004, | |
| 560 | + 1.5500000000000005, | |
| 561 | + 1.8500000000000008, | |
| 562 | + 1.9000000000000008, | |
| 563 | + 2.000000000000001, | |
| 564 | + 2.000000000000001, | |
| 565 | + 2.000000000000001, | |
| 566 | + 2.000000000000001, | |
| 567 | + 2.000000000000001, | |
| 568 | + 2.000000000000001, | |
| 569 | + 2.000000000000001, | |
| 570 | + 2.000000000000001, | |
| 571 | + 2.000000000000001, | |
| 572 | + 2.000000000000001, | |
| 573 | + 2.000000000000001, | |
| 574 | + 2.000000000000001, | |
| 575 | + 2.000000000000001, | |
| 576 | + 2.000000000000001, | |
| 577 | + 2.000000000000001, | |
| 578 | + 2.000000000000001, | |
| 579 | + 2.000000000000001, | |
| 580 | + 2.000000000000001, | |
| 581 | + 2.000000000000001, | |
| 582 | + 2.1000000000000005, | |
| 583 | + 2.1000000000000005, | |
| 584 | + 2.2, | |
| 585 | + 2.3499999999999996, | |
| 586 | + 2.3499999999999996, | |
| 587 | + 2.3499999999999996, | |
| 588 | + 2.3499999999999996, | |
| 589 | + 2.3999999999999995, | |
| 590 | + 2.3999999999999995, | |
| 591 | + 2.6499999999999986, | |
| 592 | + 2.6999999999999984, | |
| 593 | + 2.8999999999999977, | |
| 594 | + 2.9499999999999975, | |
| 595 | + 3.049999999999997, | |
| 596 | + 3.049999999999997, | |
| 597 | + 3.049999999999997, | |
| 598 | + ], | |
| 599 | + "type": "su", | |
| 600 | + }, | |
| 601 | + "rope_theta": 10000.0, | |
| 602 | + "vocab_size": 32064, | |
| 603 | + }, | |
| 604 | + ) | |
| 605 | + | |
| 606 | + model = phi3_v.Model(args) | |
| 607 | + | |
| 608 | + self.language_test_runner( | |
| 609 | + model.language_model, | |
| 610 | + args.model_type, | |
| 611 | + args.vocab_size, | |
| 612 | + args.num_hidden_layers, | |
| 613 | + ) | |
| 614 | + | |
| 615 | + self.vision_test_runner( | |
| 616 | + model.vision_model, | |
| 617 | + args.vision_config.model_type, | |
| 618 | + args.vision_config.hidden_size, | |
| 619 | + args.vision_config.num_channels, | |
| 620 | + (args.vision_config.image_size, args.vision_config.image_size), | |
| 621 | + ) | |
| 622 | + | |
| 472 | 623 | |
| 473 | 624 | if __name__ == "__main__": |
| 474 | 625 | unittest.main() |
modified mlx_vlm/utils.py +11 −5
| @@ -159,6 +159,9 @@ | ||
| 159 | 159 | config["text_config"] = text_config |
| 160 | 160 | if model_type == "idefics2": |
| 161 | 161 | config = AutoConfig.from_pretrained(model_path).to_dict() |
| 162 | + if model_type == "phi3_v": | |
| 163 | + config["vision_config"] = config["img_processor"] | |
| 164 | + config["text_config"] = {} | |
| 162 | 165 | |
| 163 | 166 | model_config = model_class.ModelConfig.from_dict(config) |
| 164 | 167 | |
| @@ -539,11 +542,12 @@ | ||
| 539 | 542 | new_bias[:out_features] = module.bias |
| 540 | 543 | module.bias = new_bias |
| 541 | 544 | |
| 542 | - quantized_config["vision_config"]["intermediate_size"] = ( | |
| 543 | - ((vision_intermediate_size // divisor) + 1) * divisor | |
| 544 | - if vision_intermediate_size % divisor != 0 | |
| 545 | - else vision_intermediate_size | |
| 546 | - ) | |
| 545 | + if "vision_config" in quantized_config: | |
| 546 | + quantized_config["vision_config"]["intermediate_size"] = ( | |
| 547 | + ((vision_intermediate_size // divisor) + 1) * divisor | |
| 548 | + if vision_intermediate_size % divisor != 0 | |
| 549 | + else vision_intermediate_size | |
| 550 | + ) | |
| 547 | 551 | |
| 548 | 552 | nn.quantize(model, q_group_size, q_bits) |
| 549 | 553 | quantized_config["quantization"] = {"group_size": q_group_size, "bits": q_bits} |
| @@ -705,6 +709,8 @@ | ||
| 705 | 709 | pixel_values = mx.array(inputs["pixel_values"]) |
| 706 | 710 | input_ids = mx.array(inputs["input_ids"]) |
| 707 | 711 | mask = mx.array(inputs["attention_mask"]) |
| 712 | + if "image_sizes" in inputs: | |
| 713 | + return input_ids, pixel_values, inputs["image_sizes"] | |
| 708 | 714 | return input_ids, pixel_values, mask |
| 709 | 715 | |
| 710 | 716 |
modified mlx_vlm/version.py +1 −1
| @@ -1,1 +1,1 @@ | ||
| 1 | -__version__ = "0.0.9" | |
| 1 | +__version__ = "0.0.10" |