Elffuss BraidHub

kikocis/mlx-vlm public

main · 13.3 KiBRawPermalink
1import glob
2import inspect
3import json
4from dataclasses import dataclass
5from pathlib import Path
6from typing import List, Optional, Tuple, Union
7
8import mlx.core as mx
9import mlx.nn as nn
10import numpy as np
11from huggingface_hub import snapshot_download
12from PIL import Image
13from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
14from transformers.image_utils import to_numpy_array
15
16from ..base import expand2square
17from .language import LanguageModel, TextConfig
18from .vision import VisionConfig, VisionModel
19
20
21@dataclass
22class AlignerConfig:
23 cls: str
24 model_type: str
25 params: dict
26
27 @classmethod
28 def from_dict(cls, params):
29 return cls(
30 **{
31 k: v
32 for k, v in params.items()
33 if k in inspect.signature(cls).parameters
34 }
35 )
36
37
38@dataclass
39class ModelConfig:
40 text_config: TextConfig
41 vision_config: VisionConfig
42 aligner_config: AlignerConfig
43 model_type: str
44 ignore_index: int = -100
45 image_token_index: int = 100015
46 vision_feature_select_strategy: str = "default"
47 select_layer: int = -1
48 pad_id: int = 100001
49 num_image_tokens: int = 576
50 vocab_size: int = 32000
51
52 @classmethod
53 def from_dict(cls, params):
54 return cls(
55 **{
56 k: v
57 for k, v in params.items()
58 if k in inspect.signature(cls).parameters
59 }
60 )
61
62
63class ImageProcessor(BaseImageProcessor):
64 model_input_names = ["pixel_values"]
65
66 def __init__(
67 self,
68 config,
69 image_size: int = 384,
70 min_size: int = 14,
71 image_mean: Union[Tuple[float, float, float], List[float]] = (
72 0.5,
73 0.5,
74 0.5,
75 ),
76 image_std: Union[Tuple[float, float, float], List[float]] = (
77 0.5,
78 0.5,
79 0.5,
80 ),
81 rescale_factor: float = 1.0 / 255.0,
82 do_normalize: bool = True,
83 **kwargs,
84 ):
85 super().__init__(**kwargs)
86 if "high_res_cfg" in config["vision_config"]["params"]:
87 self.image_size = config["vision_config"]["params"]["high_res_cfg"][
88 "image_size"
89 ]
90 self.image_mean = config["vision_config"]["params"]["high_res_cfg"][
91 "pixel_mean"
92 ]
93 self.image_std = config["vision_config"]["params"]["high_res_cfg"][
94 "pixel_std"
95 ]
96 self.do_normalize = False
97 else:
98 self.image_size = image_size
99 self.image_mean = image_mean
100 self.image_std = image_std
101 self.do_normalize = do_normalize
102
103 self.rescale_factor = rescale_factor
104 self.min_size = min_size
105
106 if image_mean is None:
107 self.background_color = (127, 127, 127)
108 else:
109 self.background_color = tuple([int(x * 255) for x in self.image_mean])
110
111 def resize(self, pil_img: Image) -> np.ndarray:
112 """
113
114 Args:
115 pil_img (PIL.Image): [H, W, 3] in PIL.Image in RGB
116
117 Returns:
118 x (np.ndarray): [3, self.image_size, self.image_size]
119 """
120
121 width, height = pil_img.size
122 max_size = max(width, height)
123
124 size = [
125 max(int(height / max_size * self.image_size), self.min_size),
126 max(int(width / max_size * self.image_size), self.min_size),
127 ]
128
129 if width <= 0 or height <= 0 or size[0] <= 0 or size[1] <= 0:
130 print(f"orig size = {pil_img.size}, new size = {size}")
131 raise ValueError("Invalid size!")
132
133 pil_img = pil_img.resize(size=tuple(size[::-1]), resample=Image.BICUBIC)
134
135 pil_img = expand2square(pil_img, self.background_color)
136 x = to_numpy_array(pil_img)
137
138 # [H, W, 3] -> [3, H, W]
139 x = np.transpose(x, (2, 0, 1))
140
141 return x
142
143 def preprocess(self, images, **kwargs) -> BatchFeature:
144 # resize and pad to [self.image_size, self.image_size]
145 # then convert from [H, W, 3] to [3, H, W]
146 images: List[np.ndarray] = [self.resize(image) for image in images]
147
148 # resacle from [0, 255] -> [0, 1]
149 images = [
150 self.rescale(
151 image=image,
152 scale=self.rescale_factor,
153 input_data_format="channels_first",
154 )
155 for image in images
156 ]
157
158 # normalize
159 if self.do_normalize:
160 images = [
161 self.normalize(
162 image=image,
163 mean=self.image_mean,
164 std=self.image_std,
165 input_data_format="channels_first",
166 )
167 for image in images
168 ]
169
170 return images
171
172
173class MlpProjector(nn.Module):
174 def __init__(self, config: ModelConfig):
175 super().__init__()
176
177 if config.aligner_config.params["projector_type"] == "mlp_gelu":
178 self.layers = [
179 nn.Linear(
180 config.vision_config.hidden_size,
181 config.text_config.hidden_size,
182 bias=True,
183 )
184 ]
185 mlp_depth = config.aligner_config.params["depth"]
186 for _ in range(1, mlp_depth):
187 self.layers.append(nn.GELU())
188 self.layers.append(
189 nn.Linear(
190 config.text_config.hidden_size,
191 config.text_config.hidden_size,
192 bias=True,
193 )
194 )
195 elif (
196 config.aligner_config.params["projector_type"]
197 == "low_high_hybrid_split_mlp_gelu"
198 ):
199 mlp_depth = config.aligner_config.params["depth"]
200 self.high_up_proj = nn.Linear(
201 config.vision_config.hidden_size, config.text_config.hidden_size // 2
202 )
203 self.low_up_proj = nn.Linear(
204 config.vision_config.hidden_size, config.text_config.hidden_size // 2
205 )
206
207 self.layers = []
208 for _ in range(1, mlp_depth):
209 self.layers.append(nn.GELU())
210 self.layers.append(
211 nn.Linear(
212 config.text_config.hidden_size, config.text_config.hidden_size
213 )
214 )
215
216 else:
217 projector_type = config.aligner_config.params["projector_type"]
218 raise ValueError(f"Unknown projector type: {projector_type}")
219
220 def __call__(self, x: Union[mx.array, Tuple]) -> mx.array:
221
222 if isinstance(x, tuple):
223 high_x, low_x = x
224
225 high_x = self.high_up_proj(high_x)
226 low_x = self.low_up_proj(low_x)
227
228 B, D = high_x.shape[0], high_x.shape[-1]
229 high_x = high_x.reshape(B, -1, D)
230
231 x = mx.concatenate([high_x, low_x], axis=-1)
232
233 for layer in self.layers:
234 x = layer(x)
235
236 return x
237
238
239class Model(nn.Module):
240 def __init__(self, config: ModelConfig):
241 super().__init__()
242 self.config = config
243 self.vision_model = VisionModel(config.vision_config)
244 self.language_model = LanguageModel(config.text_config)
245 self.aligner = MlpProjector(config)
246 self.vision_feature_layer = config.select_layer
247 self.vision_feature_select_strategy = config.vision_feature_select_strategy
248
249 def add_image_token(
250 self,
251 image_indices: list,
252 input_ids: np.ndarray,
253 image_token_index: int,
254 num_image_tokens: int,
255 add_special_token: bool = False,
256 ):
257 """
258 Inserts image tokens into an array of input IDs at specified indices.
259
260 Args:
261 image_indices (List[int]): Indices where image tokens should be inserted.
262 input_ids (np.ndarray): Original array of input IDs, expected to be two-dimensional.
263 image_token_index (int): The ID used to represent an image token.
264 num_image_tokens (int): Number of image tokens to insert at each index.
265 add_special_token (bool): If True, adjusts the indices to include a special token.
266
267 Returns:
268 Tuple of (np.ndarray, np.ndarray):
269 - Updated array of input IDs with image tokens inserted.
270 - Array indicating the number of image tokens added at each position.
271 """
272 input_slices = []
273
274 start = 0
275 flat_input_ids = input_ids.flatten()
276
277 for index in image_indices:
278 end = (index[0] + 1) if add_special_token else index[0]
279
280 input_slices.append(flat_input_ids[start:end])
281 input_slices.append(
282 np.full((num_image_tokens,), image_token_index, dtype=np.int64)
283 )
284 start = index[0] + 1 # Move start past the current image insertion point
285
286 input_slices.append(flat_input_ids[start:])
287
288 input_ids = np.concatenate(input_slices, axis=0)
289 num_image_tokens_array = np.array(
290 [num_image_tokens] * len(image_indices), dtype=np.int64
291 )
292 input_ids = input_ids.reshape(1, -1)
293
294 return input_ids, num_image_tokens_array
295
296 def get_input_embeddings(
297 self,
298 input_ids: Optional[mx.array] = None,
299 pixel_values: Optional[mx.array] = None,
300 ):
301 if pixel_values is None:
302 return self.language_model(input_ids)
303
304 image_token_index = self.config.image_token_index
305 num_image_tokens = self.config.num_image_tokens
306
307 image_token_mask = np.array(input_ids[0] == image_token_index).astype(bool)
308 image_indices = np.nonzero(image_token_mask)
309
310 input_ids, num_image_tokens = self.add_image_token(
311 image_indices=image_indices,
312 input_ids=np.array(input_ids),
313 image_token_index=image_token_index,
314 num_image_tokens=num_image_tokens,
315 )
316
317 input_ids = mx.array(input_ids)
318
319 # Get the input embeddings from the language model
320 inputs_embeds = self.language_model.model.embed_tokens(input_ids)
321
322 # Get the ouptut hidden states from the vision model
323 if self.config.vision_config.cls == "HybridVisionTower":
324 hidden_states = self.vision_model(
325 pixel_values.transpose(0, 2, 3, 1), output_hidden_states=True
326 )
327 else:
328 hidden_states, _, _ = self.vision_model(
329 pixel_values.transpose(0, 2, 3, 1), output_hidden_states=True
330 )
331
332 # Pass image features through the multi-modal projector
333 image_features = self.aligner(hidden_states)
334
335 # Insert special image tokens in the input_ids
336 final_inputs_embeds = self._merge_input_ids_with_image_features(
337 image_features, inputs_embeds, input_ids
338 )
339 return final_inputs_embeds
340
341 def _merge_input_ids_with_image_features(
342 self, image_features, inputs_embeds, input_ids
343 ):
344 image_token_index = self.config.image_token_index
345
346 # Positions of <image> tokens in input_ids, assuming batch size is 1
347 image_positions = np.where(input_ids[0] == image_token_index)[0].tolist()
348 text_segments = []
349 start_idx = 0
350
351 for position in image_positions:
352 text_segments.append(inputs_embeds[:, start_idx:position])
353 start_idx = position + 1
354
355 image_embeddings = mx.split(image_features, image_features.shape[0])
356 final_embeddings = [v for p in zip(text_segments, image_embeddings) for v in p]
357 final_embeddings += [inputs_embeds[:, start_idx:]]
358
359 # Create a final embedding of shape
360 # (1, num_image_patches*num_images + sequence_len, embed_dim)
361 return mx.concatenate(final_embeddings, axis=1)
362
363 def __call__(
364 self,
365 input_ids: mx.array,
366 pixel_values: mx.array,
367 mask: mx.array,
368 cache=None,
369 **kwargs,
370 ):
371
372 input_embeddings = self.get_input_embeddings(input_ids, pixel_values)
373 logits = self.language_model(
374 input_ids, cache=cache, inputs_embeds=input_embeddings
375 )
376 return logits
377
378 @staticmethod
379 def from_pretrained(path_or_hf_repo: str):
380 path = Path(path_or_hf_repo)
381 if not path.exists():
382 path = Path(
383 snapshot_download(
384 repo_id=path_or_hf_repo,
385 allow_patterns=[
386 "*.json",
387 "*.safetensors",
388 "*.py",
389 "tokenizer.model",
390 "*.tiktoken",
391 ],
392 )
393 )
394
395 with open(path / "config.json", "r") as f:
396 model_config = json.load(f)
397
398 model_config = ModelConfig.from_dict(model_config)
399
400 model_config.vision_config = VisionConfig.from_dict(model_config.vision_config)
401 model_config.aligner_config = AlignerConfig.from_dict(
402 model_config.aligner_config
403 )
404 model_config.text_config = TextConfig.from_dict(model_config.text_config)
405
406 model = Model(model_config)
407 weight_files = glob.glob(str(path / "*.safetensors"))
408 if not weight_files:
409 raise FileNotFoundError(f"No safetensors found in {path}")
410
411 weights = {}
412 for wf in weight_files:
413 weights.update(mx.load(wf))
414
415 weights = VisionModel.sanitize(weights)
416 weights = LanguageModel.sanitize(weights)
417
418 model.load_weights(list(weights.items()))
419 return model