Changesets · Branches · Tags · Compare
| Changeset | 9705b4e74fecbd194af4c07c9c39b1c1962b5ca5b86bea188cccbcb0c6fe26b1 |
|---|---|
| Author | Prince Canuma <prince.gdt@gmail.com> · 2024-04-24 09:45 +02:00 |
| Committer | GitHub <noreply@github.com> · 2024-04-24 09:45 +02:00 |
| Parents | a23299d7284d, f16f6128be34 |
15 files changed
modified mlx_vlm/__init__.py +1 −1
| @@ -1,2 +1,2 @@ | ||
| 1 | 1 | from .utils import convert, generate, load |
| 2 | -from .version import __version__ | |
| No newline at the end of the file | ||
| 2 | +from .version import __version__ |
modified mlx_vlm/convert.py +1 −1
| @@ -59,4 +59,4 @@ | ||
| 59 | 59 | |
| 60 | 60 | |
| 61 | 61 | if __name__ == "__main__": |
| 62 | - main() | |
| No newline at the end of the file | ||
| 62 | + main() |
modified mlx_vlm/generate.py +8 −6
| @@ -2,10 +2,12 @@ | ||
| 2 | 2 | import codecs |
| 3 | 3 | |
| 4 | 4 | import mlx.core as mx |
| 5 | -from .utils import load, load_config, load_image_processor, generate, get_model_path | |
| 6 | 5 | |
| 6 | +from .utils import generate, get_model_path, load, load_config, load_image_processor | |
| 7 | 7 | |
| 8 | 8 | MODEL_TYPE = "" |
| 9 | + | |
| 10 | + | |
| 9 | 11 | def parse_arguments(): |
| 10 | 12 | parser = argparse.ArgumentParser( |
| 11 | 13 | description="Generate text from an image using a model." |
| @@ -43,8 +45,7 @@ | ||
| 43 | 45 | def get_model_and_processors(model_path): |
| 44 | 46 | model_path = get_model_path(model_path) |
| 45 | 47 | model, processor = load(model_path, {"trust_remote_code": True}) |
| 46 | - config = load_config(model_path) | |
| 47 | - image_processor = load_image_processor(config) | |
| 48 | + image_processor = load_image_processor(model_path) | |
| 48 | 49 | return model, processor, image_processor |
| 49 | 50 | |
| 50 | 51 | |
| @@ -55,7 +56,6 @@ | ||
| 55 | 56 | return mx.random.categorical(logits * (1 / temperature)) |
| 56 | 57 | |
| 57 | 58 | |
| 58 | - | |
| 59 | 59 | def main(): |
| 60 | 60 | args = parse_arguments() |
| 61 | 61 | model, processor, image_processor = get_model_and_processors(args.model) |
| @@ -75,7 +75,9 @@ | ||
| 75 | 75 | add_generation_prompt=True, |
| 76 | 76 | ) |
| 77 | 77 | else: |
| 78 | - ValueError("Error: processor does not have 'chat_template' or 'tokenizer' attribute.") | |
| 78 | + ValueError( | |
| 79 | + "Error: processor does not have 'chat_template' or 'tokenizer' attribute." | |
| 80 | + ) | |
| 79 | 81 | |
| 80 | 82 | generate( |
| 81 | 83 | model, |
| @@ -85,7 +87,7 @@ | ||
| 85 | 87 | image_processor, |
| 86 | 88 | args.temp, |
| 87 | 89 | args.max_tokens, |
| 88 | - True | |
| 90 | + True, | |
| 89 | 91 | ) |
| 90 | 92 | |
| 91 | 93 |
modified mlx_vlm/models/base.py +17 −13
| @@ -1,22 +1,27 @@ | ||
| 1 | - | |
| 2 | 1 | from abc import ABC, abstractmethod |
| 3 | 2 | from typing import Dict |
| 4 | 3 | |
| 5 | 4 | from transformers.image_processing_utils import get_size_dict |
| 6 | -from transformers.image_utils import (ChannelDimension, PILImageResampling ) | |
| 5 | +from transformers.image_utils import ChannelDimension, PILImageResampling | |
| 7 | 6 | |
| 8 | 7 | |
| 9 | 8 | class BaseImageProcessor(ABC): |
| 10 | - def __init__(self, | |
| 11 | - image_mean=(0.5, 0.5, 0.5), | |
| 12 | - image_std=(0.5, 0.5, 0.5), | |
| 13 | - size=(384, 384), | |
| 14 | - crop_size: Dict[str, int] = None, | |
| 15 | - resample=PILImageResampling.BICUBIC, | |
| 16 | - rescale_factor=1 / 255, | |
| 17 | - data_format=ChannelDimension.FIRST): | |
| 18 | - crop_size = crop_size if crop_size is not None else {"height": 384, "width": 384} | |
| 19 | - crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size") | |
| 9 | + def __init__( | |
| 10 | + self, | |
| 11 | + image_mean=(0.5, 0.5, 0.5), | |
| 12 | + image_std=(0.5, 0.5, 0.5), | |
| 13 | + size=(384, 384), | |
| 14 | + crop_size: Dict[str, int] = None, | |
| 15 | + resample=PILImageResampling.BICUBIC, | |
| 16 | + rescale_factor=1 / 255, | |
| 17 | + data_format=ChannelDimension.FIRST, | |
| 18 | + ): | |
| 19 | + crop_size = ( | |
| 20 | + crop_size if crop_size is not None else {"height": 384, "width": 384} | |
| 21 | + ) | |
| 22 | + crop_size = get_size_dict( | |
| 23 | + crop_size, default_to_square=True, param_name="crop_size" | |
| 24 | + ) | |
| 20 | 25 | |
| 21 | 26 | self.image_mean = image_mean |
| 22 | 27 | self.image_std = image_std |
| @@ -29,4 +34,3 @@ | ||
| 29 | 34 | @abstractmethod |
| 30 | 35 | def preprocess(self, images): |
| 31 | 36 | pass |
| 32 | - |
modified mlx_vlm/models/llava/__init__.py +8 −1
| @@ -1,1 +1,8 @@ | ||
| 1 | -from .llava import Model, ModelConfig, VisionConfig, TextConfig, VisionModel, LanguageModel | |
| 1 | +from .llava import ( | |
| 2 | + LanguageModel, | |
| 3 | + Model, | |
| 4 | + ModelConfig, | |
| 5 | + TextConfig, | |
| 6 | + VisionConfig, | |
| 7 | + VisionModel, | |
| 8 | +) |
modified mlx_vlm/models/llava/language.py +0 −1
| @@ -1,4 +1,3 @@ | ||
| 1 | - | |
| 2 | 1 | import inspect |
| 3 | 2 | from dataclasses import dataclass |
| 4 | 3 | from typing import Dict, Optional, Tuple, Union |
modified mlx_vlm/models/llava/llava.py +1 −2
| @@ -1,5 +1,3 @@ | ||
| 1 | - | |
| 2 | - | |
| 3 | 1 | import glob |
| 4 | 2 | import inspect |
| 5 | 3 | import json |
| @@ -11,6 +9,7 @@ | ||
| 11 | 9 | import mlx.nn as nn |
| 12 | 10 | import numpy as np |
| 13 | 11 | from huggingface_hub import snapshot_download |
| 12 | + | |
| 14 | 13 | from .language import LanguageModel, TextConfig |
| 15 | 14 | from .vision import VisionConfig, VisionModel |
| 16 | 15 |
modified mlx_vlm/models/llava/vision.py +2 −2
| @@ -1,5 +1,3 @@ | ||
| 1 | - | |
| 2 | - | |
| 3 | 1 | import inspect |
| 4 | 2 | import math |
| 5 | 3 | from dataclasses import dataclass |
| @@ -33,6 +31,7 @@ | ||
| 33 | 31 | } |
| 34 | 32 | ) |
| 35 | 33 | |
| 34 | + | |
| 36 | 35 | def check_array_shape(arr): |
| 37 | 36 | shape = arr.shape |
| 38 | 37 | |
| @@ -48,6 +47,7 @@ | ||
| 48 | 47 | else: |
| 49 | 48 | return False |
| 50 | 49 | |
| 50 | + | |
| 51 | 51 | class Attention(nn.Module): |
| 52 | 52 | def __init__( |
| 53 | 53 | self, |
modified mlx_vlm/models/nanoLlava/__init__.py +9 −1
| @@ -1,1 +1,9 @@ | ||
| 1 | -from .nanoLlava import Model, ImageProcessor, ModelConfig, TextConfig, VisionConfig, VisionModel, LanguageModel | |
| 1 | +from .nanoLlava import ( | |
| 2 | + ImageProcessor, | |
| 3 | + LanguageModel, | |
| 4 | + Model, | |
| 5 | + ModelConfig, | |
| 6 | + TextConfig, | |
| 7 | + VisionConfig, | |
| 8 | + VisionModel, | |
| 9 | +) |
modified mlx_vlm/models/nanoLlava/language.py +8 −6
| @@ -6,7 +6,6 @@ | ||
| 6 | 6 | import mlx.nn as nn |
| 7 | 7 | |
| 8 | 8 | |
| 9 | - | |
| 10 | 9 | @dataclass |
| 11 | 10 | class TextConfig: |
| 12 | 11 | model_type: str |
| @@ -162,13 +161,12 @@ | ||
| 162 | 161 | cache=None, |
| 163 | 162 | inputs_embeds=None, |
| 164 | 163 | ): |
| 165 | - # for passing merged input embeddings | |
| 164 | + # for passing merged input embeddings | |
| 166 | 165 | if inputs_embeds is None: |
| 167 | 166 | h = self.embed_tokens(inputs) |
| 168 | 167 | else: |
| 169 | 168 | h = inputs_embeds |
| 170 | 169 | |
| 171 | - | |
| 172 | 170 | mask = None |
| 173 | 171 | if h.shape[1] > 1: |
| 174 | 172 | mask = nn.MultiHeadAttention.create_additive_causal_mask(h.shape[1]) |
| @@ -180,7 +178,6 @@ | ||
| 180 | 178 | for e, layer in enumerate(self.layers): |
| 181 | 179 | h, cache[e] = layer(h, mask, cache[e]) |
| 182 | 180 | |
| 183 | - | |
| 184 | 181 | return self.lm_head(self.norm(h)), cache |
| 185 | 182 | |
| 186 | 183 | |
| @@ -201,8 +198,13 @@ | ||
| 201 | 198 | return out, cache |
| 202 | 199 | |
| 203 | 200 | def sanitize(self, weights): |
| 204 | - if self.args.tie_word_embeddings and "language_model.model.lm_head.weight" not in weights: | |
| 205 | - weights["language_model.model.lm_head.weight"] = weights["language_model.model.embed_tokens.weight"] | |
| 201 | + if ( | |
| 202 | + self.args.tie_word_embeddings | |
| 203 | + and "language_model.model.lm_head.weight" not in weights | |
| 204 | + ): | |
| 205 | + weights["language_model.model.lm_head.weight"] = weights[ | |
| 206 | + "language_model.model.embed_tokens.weight" | |
| 207 | + ] | |
| 206 | 208 | |
| 207 | 209 | return { |
| 208 | 210 | k: v for k, v in weights.items() if "self_attn.rotary_emb.inv_freq" not in k |
modified mlx_vlm/models/nanoLlava/nanoLlava.py +73 −34
| @@ -1,28 +1,31 @@ | ||
| 1 | - | |
| 2 | -import re | |
| 3 | 1 | import glob |
| 4 | 2 | import inspect |
| 5 | 3 | import json |
| 4 | +import re | |
| 6 | 5 | from dataclasses import dataclass |
| 6 | +from functools import partial, reduce | |
| 7 | 7 | from pathlib import Path |
| 8 | -from typing import Optional | |
| 8 | +from typing import Dict, Optional | |
| 9 | 9 | |
| 10 | 10 | import mlx.core as mx |
| 11 | 11 | import mlx.nn as nn |
| 12 | 12 | import numpy as np |
| 13 | 13 | from huggingface_hub import snapshot_download |
| 14 | +from PIL import Image | |
| 14 | 15 | from transformers import AutoConfig |
| 16 | +from transformers.image_transforms import ( | |
| 17 | + convert_to_rgb, | |
| 18 | + normalize, | |
| 19 | + rescale, | |
| 20 | + resize, | |
| 21 | + to_channel_dimension_format, | |
| 22 | +) | |
| 23 | +from transformers.image_utils import to_numpy_array | |
| 24 | + | |
| 25 | +from ..base import BaseImageProcessor | |
| 15 | 26 | from .language import LanguageModel, TextConfig |
| 16 | 27 | from .vision import VisionConfig, VisionModel |
| 17 | -from ..base import BaseImageProcessor | |
| 18 | - | |
| 19 | 28 | |
| 20 | -from typing import Optional, Dict | |
| 21 | -from dataclasses import dataclass | |
| 22 | -from functools import partial, reduce | |
| 23 | -from PIL import Image | |
| 24 | -from transformers.image_transforms import (convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format, ) | |
| 25 | -from transformers.image_utils import ( to_numpy_array, ) | |
| 26 | 29 | |
| 27 | 30 | @dataclass |
| 28 | 31 | class ModelConfig: |
| @@ -39,7 +42,6 @@ | ||
| 39 | 42 | image_token_index: int = -200 |
| 40 | 43 | vocab_size: int = 151936 |
| 41 | 44 | |
| 42 | - | |
| 43 | 45 | @classmethod |
| 44 | 46 | def from_dict(cls, params): |
| 45 | 47 | return cls( |
| @@ -61,16 +63,31 @@ | ||
| 61 | 63 | transforms = [ |
| 62 | 64 | convert_to_rgb, |
| 63 | 65 | to_numpy_array, |
| 64 | - partial(resize, size=self.size, resample=self.resample, data_format=self.data_format), | |
| 66 | + partial( | |
| 67 | + resize, | |
| 68 | + size=self.size, | |
| 69 | + resample=self.resample, | |
| 70 | + data_format=self.data_format, | |
| 71 | + ), | |
| 65 | 72 | partial(rescale, scale=self.rescale_factor, data_format=self.data_format), |
| 66 | - partial(normalize, mean=self.image_mean, std=self.image_std, data_format=self.data_format), | |
| 67 | - partial(to_channel_dimension_format, channel_dim=self.data_format, input_channel_dim=self.data_format), | |
| 73 | + partial( | |
| 74 | + normalize, | |
| 75 | + mean=self.image_mean, | |
| 76 | + std=self.image_std, | |
| 77 | + data_format=self.data_format, | |
| 78 | + ), | |
| 79 | + partial( | |
| 80 | + to_channel_dimension_format, | |
| 81 | + channel_dim=self.data_format, | |
| 82 | + input_channel_dim=self.data_format, | |
| 83 | + ), | |
| 68 | 84 | ] |
| 69 | 85 | |
| 70 | 86 | images = reduce(lambda x, f: [*map(f, x)], transforms, images) |
| 71 | 87 | |
| 72 | 88 | return images |
| 73 | 89 | |
| 90 | + | |
| 74 | 91 | class LlavaMultiModalProjector(nn.Module): |
| 75 | 92 | def __init__(self, config: ModelConfig): |
| 76 | 93 | super().__init__() |
| @@ -88,6 +105,7 @@ | ||
| 88 | 105 | x = self.linear_2(x) |
| 89 | 106 | return x |
| 90 | 107 | |
| 108 | + | |
| 91 | 109 | class SigLipVisionTower(nn.Module): |
| 92 | 110 | def __init__(self, config: VisionConfig): |
| 93 | 111 | super().__init__() |
| @@ -98,6 +116,7 @@ | ||
| 98 | 116 | ) -> mx.array: |
| 99 | 117 | return self.vision_tower(x, output_hidden_states) |
| 100 | 118 | |
| 119 | + | |
| 101 | 120 | class Model(nn.Module): |
| 102 | 121 | def __init__(self, config: ModelConfig): |
| 103 | 122 | self.model_type = config.model_type |
| @@ -131,9 +150,7 @@ | ||
| 131 | 150 | ) |
| 132 | 151 | return final_inputs_embeds |
| 133 | 152 | |
| 134 | - def _prepare_inputs_for_multimodal( | |
| 135 | - self, image_features, inputs_embeds, input_ids | |
| 136 | - ): | |
| 153 | + def _prepare_inputs_for_multimodal(self, image_features, inputs_embeds, input_ids): | |
| 137 | 154 | image_token_index = self.config.image_token_index |
| 138 | 155 | num_images, num_image_patches, embed_dim = image_features.shape |
| 139 | 156 | |
| @@ -161,12 +178,7 @@ | ||
| 161 | 178 | # (1, num_image_patches*num_images + sequence_len, embed_dim) |
| 162 | 179 | return mx.concatenate(final_embeddings, axis=1) |
| 163 | 180 | |
| 164 | - def __call__( | |
| 165 | - self, | |
| 166 | - input_ids: mx.array, | |
| 167 | - pixel_values: mx.array, | |
| 168 | - cache=None | |
| 169 | - ): | |
| 181 | + def __call__(self, input_ids: mx.array, pixel_values: mx.array, cache=None): | |
| 170 | 182 | input_embeddings = self.get_input_embeddings(input_ids, pixel_values) |
| 171 | 183 | logits, cache = self.language_model( |
| 172 | 184 | inputs=input_ids, cache=cache, inputs_embeds=input_embeddings |
| @@ -187,7 +199,6 @@ | ||
| 187 | 199 | "tokenizer.model", |
| 188 | 200 | "*.tiktoken", |
| 189 | 201 | ], |
| 190 | - | |
| 191 | 202 | ) |
| 192 | 203 | ) |
| 193 | 204 | |
| @@ -221,21 +232,49 @@ | ||
| 221 | 232 | model.load_weights(list(weights.items())) |
| 222 | 233 | return model |
| 223 | 234 | |
| 224 | - | |
| 225 | 235 | def sanitize(self, weights): |
| 226 | 236 | weights = { |
| 227 | - f"{k.split('.', 1)[1]}" if re.match(r'^model\.vision_tower', k) else | |
| 228 | - f"mm_projector.linear_1.{k.split('.')[-1]}" if re.match(r'^model\.mm_projector\.0', k) else | |
| 229 | - f"mm_projector.linear_2.{k.split('.')[-1]}" if re.match(r'^model\.mm_projector\.2', k) else | |
| 230 | - f"language_model.model.{k}" if re.match(r'^lm_head', k) else | |
| 231 | - f"language_model.{k}" if re.match(r'^model\.(embed_tokens|norm|layers)', k) else k: v | |
| 237 | + ( | |
| 238 | + f"{k.split('.', 1)[1]}" | |
| 239 | + if re.match(r"^model\.vision_tower", k) | |
| 240 | + else ( | |
| 241 | + f"mm_projector.linear_1.{k.split('.')[-1]}" | |
| 242 | + if re.match(r"^model\.mm_projector\.0", k) | |
| 243 | + else ( | |
| 244 | + f"mm_projector.linear_2.{k.split('.')[-1]}" | |
| 245 | + if re.match(r"^model\.mm_projector\.2", k) | |
| 246 | + else ( | |
| 247 | + f"language_model.model.{k}" | |
| 248 | + if re.match(r"^lm_head", k) | |
| 249 | + else ( | |
| 250 | + f"language_model.{k}" | |
| 251 | + if re.match(r"^model\.(embed_tokens|norm|layers)", k) | |
| 252 | + else k | |
| 253 | + ) | |
| 254 | + ) | |
| 255 | + ) | |
| 256 | + ) | |
| 257 | + ): v | |
| 232 | 258 | for k, v in weights.items() |
| 233 | 259 | } |
| 234 | 260 | |
| 235 | 261 | weights = { |
| 236 | - f"vision_tower.vision_tower.vision_model.head.attention.in_proj.bias" if re.match(r'^vision_tower\.vision_tower\.vision_model\.head\.attention\.in_proj_bias', k) else | |
| 237 | - f"vision_tower.vision_tower.vision_model.head.attention.in_proj.weight" if re.match(r'^vision_tower\.vision_tower\.vision_model\.head\.attention\.in_proj_weight', k) else k: v | |
| 262 | + ( | |
| 263 | + f"vision_tower.vision_tower.vision_model.head.attention.in_proj.bias" | |
| 264 | + if re.match( | |
| 265 | + r"^vision_tower\.vision_tower\.vision_model\.head\.attention\.in_proj_bias", | |
| 266 | + k, | |
| 267 | + ) | |
| 268 | + else ( | |
| 269 | + f"vision_tower.vision_tower.vision_model.head.attention.in_proj.weight" | |
| 270 | + if re.match( | |
| 271 | + r"^vision_tower\.vision_tower\.vision_model\.head\.attention\.in_proj_weight", | |
| 272 | + k, | |
| 273 | + ) | |
| 274 | + else k | |
| 275 | + ) | |
| 276 | + ): v | |
| 238 | 277 | for k, v in weights.items() |
| 239 | 278 | } |
| 240 | 279 | |
| 241 | - return weights | |
| No newline at the end of the file | ||
| 280 | + return weights |
modified mlx_vlm/models/nanoLlava/vision.py +2 −2
| @@ -1,5 +1,3 @@ | ||
| 1 | - | |
| 2 | - | |
| 3 | 1 | import inspect |
| 4 | 2 | from dataclasses import dataclass |
| 5 | 3 | from typing import Optional |
| @@ -32,6 +30,7 @@ | ||
| 32 | 30 | } |
| 33 | 31 | ) |
| 34 | 32 | |
| 33 | + | |
| 35 | 34 | def check_array_shape(arr): |
| 36 | 35 | shape = arr.shape |
| 37 | 36 | |
| @@ -47,6 +46,7 @@ | ||
| 47 | 46 | else: |
| 48 | 47 | return False |
| 49 | 48 | |
| 49 | + | |
| 50 | 50 | class Attention(nn.Module): |
| 51 | 51 | def __init__( |
| 52 | 52 | self, |
modified mlx_vlm/tokenizer_utils.py +1 −1
| @@ -329,4 +329,4 @@ | ||
| 329 | 329 | detokenizer_class, |
| 330 | 330 | ) |
| 331 | 331 | else: |
| 332 | - return detokenizer_class | |
| No newline at the end of the file | ||
| 332 | + return detokenizer_class |
modified mlx_vlm/utils.py +47 −25
| @@ -1,28 +1,32 @@ | ||
| 1 | - | |
| 2 | 1 | import copy |
| 3 | -import re | |
| 4 | 2 | import glob |
| 5 | 3 | import importlib |
| 6 | 4 | import json |
| 7 | 5 | import logging |
| 6 | +import re | |
| 8 | 7 | import shutil |
| 9 | 8 | import time |
| 10 | 9 | from pathlib import Path |
| 11 | 10 | from textwrap import dedent |
| 12 | 11 | from typing import Any, Callable, Dict, Generator, Optional, Tuple, Union |
| 13 | -import requests | |
| 14 | 12 | |
| 15 | 13 | import mlx.core as mx |
| 16 | 14 | import mlx.nn as nn |
| 17 | 15 | import numpy as np |
| 18 | -from PIL import Image | |
| 16 | +import requests | |
| 19 | 17 | from huggingface_hub import snapshot_download |
| 20 | 18 | from mlx.utils import tree_flatten, tree_unflatten |
| 21 | -from transformers import AutoConfig, AutoProcessor, PreTrainedTokenizer, PreTrainedTokenizerFast | |
| 19 | +from PIL import Image | |
| 20 | +from transformers import ( | |
| 21 | + AutoConfig, | |
| 22 | + AutoProcessor, | |
| 23 | + PreTrainedTokenizer, | |
| 24 | + PreTrainedTokenizerFast, | |
| 25 | +) | |
| 22 | 26 | |
| 23 | -from .tokenizer_utils import TokenizerWrapper, load_tokenizer | |
| 24 | 27 | from .models.base import BaseImageProcessor |
| 25 | 28 | from .sample_utils import top_p_sampling |
| 29 | +from .tokenizer_utils import TokenizerWrapper, load_tokenizer | |
| 26 | 30 | |
| 27 | 31 | # Constants |
| 28 | 32 | MODEL_REMAPPING = { |
| @@ -37,6 +41,7 @@ | ||
| 37 | 41 | != 8 # avoid quantizing gate layers, otherwise we have to re-quant and upload all the mixtral models |
| 38 | 42 | ) |
| 39 | 43 | |
| 44 | + | |
| 40 | 45 | def get_model_and_args(config: dict): |
| 41 | 46 | """ |
| 42 | 47 | Retrieve the model object based on the configuration. |
| @@ -56,7 +61,6 @@ | ||
| 56 | 61 | logging.error(msg) |
| 57 | 62 | raise ValueError(msg) |
| 58 | 63 | |
| 59 | - | |
| 60 | 64 | return arch, model_type |
| 61 | 65 | |
| 62 | 66 | |
| @@ -110,11 +114,9 @@ | ||
| 110 | 114 | ValueError: If the model class or args class are not found or cannot be instantiated. |
| 111 | 115 | """ |
| 112 | 116 | |
| 113 | - | |
| 114 | 117 | config = load_config(model_path) |
| 115 | 118 | quantization = config.get("quantization", None) |
| 116 | 119 | |
| 117 | - | |
| 118 | 120 | weight_files = glob.glob(str(model_path / "*.safetensors")) |
| 119 | 121 | if not weight_files: |
| 120 | 122 | logging.error(f"No safetensors found in {model_path}") |
| @@ -124,7 +126,6 @@ | ||
| 124 | 126 | for wf in weight_files: |
| 125 | 127 | weights.update(mx.load(wf)) |
| 126 | 128 | |
| 127 | - | |
| 128 | 129 | model_class, model_type = get_model_and_args(config=config) |
| 129 | 130 | |
| 130 | 131 | if model_type == "nanoLlava": |
| @@ -136,15 +137,21 @@ | ||
| 136 | 137 | config["text_config"] = text_config |
| 137 | 138 | |
| 138 | 139 | model_config = model_class.ModelConfig.from_dict(config) |
| 139 | - model_config.vision_config = model_class.VisionConfig.from_dict(config["vision_config"]) | |
| 140 | + model_config.vision_config = model_class.VisionConfig.from_dict( | |
| 141 | + config["vision_config"] | |
| 142 | + ) | |
| 140 | 143 | model_config.text_config = model_class.TextConfig.from_dict(config["text_config"]) |
| 141 | 144 | model = model_class.Model(model_config) |
| 142 | 145 | |
| 143 | 146 | if hasattr(model, "sanitize"): |
| 144 | 147 | weights = model.sanitize(weights) |
| 145 | 148 | |
| 146 | - weights = model_class.VisionModel(model_config.vision_config).sanitize(weights=weights) | |
| 147 | - weights = model_class.LanguageModel(model_config.text_config).sanitize(weights=weights) | |
| 149 | + weights = model_class.VisionModel(model_config.vision_config).sanitize( | |
| 150 | + weights=weights | |
| 151 | + ) | |
| 152 | + weights = model_class.LanguageModel(model_config.text_config).sanitize( | |
| 153 | + weights=weights | |
| 154 | + ) | |
| 148 | 155 | |
| 149 | 156 | if (quantization := config.get("quantization", None)) is not None: |
| 150 | 157 | # Handle legacy models which may not have everything quantized |
| @@ -197,6 +204,7 @@ | ||
| 197 | 204 | |
| 198 | 205 | return model, processor |
| 199 | 206 | |
| 207 | + | |
| 200 | 208 | def load_config(model_path: Path) -> dict: |
| 201 | 209 | try: |
| 202 | 210 | with open(model_path / "config.json", "r") as f: |
| @@ -206,7 +214,12 @@ | ||
| 206 | 214 | raise |
| 207 | 215 | return config |
| 208 | 216 | |
| 209 | -def load_image_processor(config: dict) -> BaseImageProcessor: | |
| 217 | + | |
| 218 | +def load_image_processor(model_path: Union[str, Path]) -> BaseImageProcessor: | |
| 219 | + if isinstance(model_path, str): | |
| 220 | + model_path = get_model_path(model_path) | |
| 221 | + | |
| 222 | + config = load_config(model_path) | |
| 210 | 223 | model_class, _ = get_model_and_args(config) |
| 211 | 224 | image_processor = None |
| 212 | 225 | |
| @@ -215,7 +228,10 @@ | ||
| 215 | 228 | |
| 216 | 229 | return image_processor |
| 217 | 230 | |
| 218 | -def load_processor(model_path, processor_config={"trust_remote_code": True}) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]: | |
| 231 | + | |
| 232 | +def load_processor( | |
| 233 | + model_path, processor_config={"trust_remote_code": True} | |
| 234 | +) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]: | |
| 219 | 235 | processor = AutoProcessor.from_pretrained(model_path, **processor_config) |
| 220 | 236 | detokenizer_class = load_tokenizer(model_path, return_tokenizer=False) |
| 221 | 237 | if "tokenizer" in processor.__dict__.keys(): |
| @@ -224,6 +240,7 @@ | ||
| 224 | 240 | processor.detokenizer = detokenizer_class(processor) |
| 225 | 241 | return processor |
| 226 | 242 | |
| 243 | + | |
| 227 | 244 | def fetch_from_hub( |
| 228 | 245 | model_path: Path, lazy: bool = False |
| 229 | 246 | ) -> Tuple[nn.Module, dict, PreTrainedTokenizer]: |
| @@ -270,6 +287,7 @@ | ||
| 270 | 287 | import os |
| 271 | 288 | |
| 272 | 289 | from huggingface_hub import HfApi, ModelCard, logging |
| 290 | + | |
| 273 | 291 | from . import __version__ |
| 274 | 292 | |
| 275 | 293 | card = ModelCard.load(hf_path) |
| @@ -303,6 +321,7 @@ | ||
| 303 | 321 | ) |
| 304 | 322 | print(f"Upload successful, go to https://huggingface.co/{upload_repo} for details.") |
| 305 | 323 | |
| 324 | + | |
| 306 | 325 | def get_model_path(path_or_hf_repo: str, revision: Optional[str] = None) -> Path: |
| 307 | 326 | """ |
| 308 | 327 | Ensures the model is available locally. If the path does not exist locally, |
| @@ -357,6 +376,7 @@ | ||
| 357 | 376 | logits[:, indices] = selected_logits |
| 358 | 377 | return logits |
| 359 | 378 | |
| 379 | + | |
| 360 | 380 | def save_weights( |
| 361 | 381 | save_path: Union[str, Path], |
| 362 | 382 | weights: Dict[str, Any], |
| @@ -408,9 +428,11 @@ | ||
| 408 | 428 | indent=4, |
| 409 | 429 | ) |
| 410 | 430 | |
| 431 | + | |
| 411 | 432 | def class_predicate(path, m): |
| 412 | 433 | return isinstance(m, nn.Linear) and not isinstance(m, nn.Embedding) |
| 413 | 434 | |
| 435 | + | |
| 414 | 436 | def quantize_model( |
| 415 | 437 | model: nn.Module, config: dict, q_group_size: int, q_bits: int |
| 416 | 438 | ) -> Tuple: |
| @@ -456,6 +478,7 @@ | ||
| 456 | 478 | with open(config_path, "w") as fid: |
| 457 | 479 | json.dump(config, fid, indent=4) |
| 458 | 480 | |
| 481 | + | |
| 459 | 482 | def dequantize_model(model: nn.Module) -> nn.Module: |
| 460 | 483 | """ |
| 461 | 484 | Dequantize the quantized linear layers in the model. |
| @@ -488,6 +511,7 @@ | ||
| 488 | 511 | model.update_modules(tree_unflatten(de_quantize_layers)) |
| 489 | 512 | return model |
| 490 | 513 | |
| 514 | + | |
| 491 | 515 | def convert( |
| 492 | 516 | hf_path: str, |
| 493 | 517 | mlx_path: str = "mlx_model", |
| @@ -530,16 +554,14 @@ | ||
| 530 | 554 | for file in py_files: |
| 531 | 555 | shutil.copy(file, mlx_path) |
| 532 | 556 | |
| 533 | - | |
| 534 | 557 | tokenizer.save_pretrained(mlx_path) |
| 535 | 558 | |
| 536 | - | |
| 537 | 559 | save_config(config, config_path=mlx_path / "config.json") |
| 538 | 560 | |
| 539 | - | |
| 540 | 561 | if upload_repo is not None: |
| 541 | 562 | upload_to_hub(mlx_path, upload_repo, hf_path) |
| 542 | 563 | |
| 564 | + | |
| 543 | 565 | def load_image(image_source): |
| 544 | 566 | """ |
| 545 | 567 | Helper function to load an image from either a URL or file. |
| @@ -563,6 +585,7 @@ | ||
| 563 | 585 | f"The image {image_source} must be a valid URL or existing file." |
| 564 | 586 | ) |
| 565 | 587 | |
| 588 | + | |
| 566 | 589 | def prepare_inputs(image_processor, processor, image, prompt): |
| 567 | 590 | if isinstance(image, str): |
| 568 | 591 | image = load_image(image) |
| @@ -579,7 +602,8 @@ | ||
| 579 | 602 | |
| 580 | 603 | return input_ids, pixel_values |
| 581 | 604 | |
| 582 | -def sample(logits: mx.array, temp:float, top_p:float) -> Tuple[mx.array, float]: | |
| 605 | + | |
| 606 | +def sample(logits: mx.array, temp: float, top_p: float) -> Tuple[mx.array, float]: | |
| 583 | 607 | softmax_logits = mx.softmax(logits) |
| 584 | 608 | |
| 585 | 609 | if temp == 0: |
| @@ -593,10 +617,11 @@ | ||
| 593 | 617 | prob = softmax_logits[0, token] |
| 594 | 618 | return token, prob |
| 595 | 619 | |
| 620 | + | |
| 596 | 621 | def generate_step( |
| 597 | 622 | model: nn.Module, |
| 598 | 623 | prompt: mx.array, |
| 599 | - cache = None, | |
| 624 | + cache=None, | |
| 600 | 625 | temp: float = 0.0, |
| 601 | 626 | repetition_penalty: Optional[float] = None, |
| 602 | 627 | repetition_context_size: Optional[int] = 20, |
| @@ -656,7 +681,7 @@ | ||
| 656 | 681 | processor: PreTrainedTokenizer, |
| 657 | 682 | image: str, |
| 658 | 683 | prompt: str, |
| 659 | - image_processor = None, | |
| 684 | + image_processor=None, | |
| 660 | 685 | temp: float = 0.0, |
| 661 | 686 | max_tokens: int = 100, |
| 662 | 687 | verbose: bool = False, |
| @@ -686,7 +711,6 @@ | ||
| 686 | 711 | print("Image:", image, "\n") |
| 687 | 712 | print("Prompt:", prompt) |
| 688 | 713 | |
| 689 | - | |
| 690 | 714 | if image_processor is not None: |
| 691 | 715 | prompt_tokens = mx.array(processor.encode(prompt)) |
| 692 | 716 | tokenizer = processor |
| @@ -699,7 +723,6 @@ | ||
| 699 | 723 | logits = logits[:, -1, :] |
| 700 | 724 | y, _ = sample(logits, temp, top_p) |
| 701 | 725 | |
| 702 | - | |
| 703 | 726 | tic = time.perf_counter() |
| 704 | 727 | detokenizer = processor.detokenizer |
| 705 | 728 | detokenizer.reset() |
| @@ -726,7 +749,6 @@ | ||
| 726 | 749 | if token == tokenizer.eos_token_id: |
| 727 | 750 | break |
| 728 | 751 | |
| 729 | - | |
| 730 | 752 | detokenizer.add_token(token) |
| 731 | 753 | |
| 732 | 754 | if verbose: |
| @@ -753,4 +775,4 @@ | ||
| 753 | 775 | print(f"Prompt: {prompt_tps:.3f} tokens-per-sec") |
| 754 | 776 | print(f"Generation: {gen_tps:.3f} tokens-per-sec") |
| 755 | 777 | |
| 756 | - return detokenizer.text | |
| No newline at the end of the file | ||
| 778 | + return detokenizer.text |
modified setup.py +3 −2
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | import sys |
| 2 | 2 | from pathlib import Path |
| 3 | -from setuptools import setup, find_packages | |
| 3 | + | |
| 4 | +from setuptools import find_packages, setup | |
| 4 | 5 | |
| 5 | 6 | # Get the project root directory |
| 6 | 7 | root_dir = Path(__file__).parent |
| @@ -31,4 +32,4 @@ | ||
| 31 | 32 | install_requires=requirements, |
| 32 | 33 | packages=find_packages(where=root_dir), |
| 33 | 34 | python_requires=">=3.8", |
| 34 | -) | |
| No newline at the end of the file | ||
| 35 | +) |