| 1 | import copy |
| 2 | import glob |
| 3 | import importlib |
| 4 | import json |
| 5 | import logging |
| 6 | import shutil |
| 7 | import time |
| 8 | from dataclasses import asdict |
| 9 | from io import BytesIO |
| 10 | from pathlib import Path |
| 11 | from textwrap import dedent |
| 12 | from typing import Any, Callable, Dict, Generator, Optional, Tuple, Union |
| 13 | |
| 14 | import mlx.core as mx |
| 15 | import mlx.nn as nn |
| 16 | import numpy as np |
| 17 | import requests |
| 18 | from huggingface_hub import snapshot_download |
| 19 | from mlx.utils import tree_flatten, tree_unflatten |
| 20 | from PIL import Image |
| 21 | from transformers import ( |
| 22 | AutoConfig, |
| 23 | AutoProcessor, |
| 24 | PreTrainedTokenizer, |
| 25 | PreTrainedTokenizerFast, |
| 26 | ) |
| 27 | |
| 28 | from .models.base import BaseImageProcessor, KVCache, SimpleKVCache |
| 29 | from .sample_utils import top_p_sampling |
| 30 | from .tokenizer_utils import load_tokenizer |
| 31 | from .trainer import apply_lora_layers |
| 32 | |
| 33 | # Constants |
| 34 | MODEL_REMAPPING = {"llava-qwen2": "llava_bunny", "bunny-llama": "llava_bunny"} |
| 35 | |
| 36 | MAX_FILE_SIZE_GB = 5 |
| 37 | |
| 38 | linear_class_predicate = ( |
| 39 | lambda m: isinstance(m, nn.Linear) |
| 40 | and m.weight.shape[0] |
| 41 | != 8 # avoid quantizing gate layers, otherwise we have to re-quant and upload all the mixtral models |
| 42 | ) |
| 43 | |
| 44 | |
| 45 | def get_model_and_args(config: dict): |
| 46 | """ |
| 47 | Retrieve the model object based on the configuration. |
| 48 | |
| 49 | Args: |
| 50 | config (dict): The model configuration. |
| 51 | |
| 52 | Returns: |
| 53 | A tuple containing the Model class and the ModelArgs class. |
| 54 | """ |
| 55 | model_type = config["model_type"] |
| 56 | model_type = MODEL_REMAPPING.get(model_type, model_type) |
| 57 | try: |
| 58 | arch = importlib.import_module(f"mlx_vlm.models.{model_type}") |
| 59 | except ImportError: |
| 60 | msg = f"Model type {model_type} not supported." |
| 61 | logging.error(msg) |
| 62 | raise ValueError(msg) |
| 63 | |
| 64 | return arch, model_type |
| 65 | |
| 66 | |
| 67 | def get_model_path(path_or_hf_repo: str, revision: Optional[str] = None) -> Path: |
| 68 | """ |
| 69 | Ensures the model is available locally. If the path does not exist locally, |
| 70 | it is downloaded from the Hugging Face Hub. |
| 71 | |
| 72 | Args: |
| 73 | path_or_hf_repo (str): The local path or Hugging Face repository ID of the model. |
| 74 | revision (str, optional): A revision id which can be a branch name, a tag, or a commit hash. |
| 75 | |
| 76 | Returns: |
| 77 | Path: The path to the model. |
| 78 | """ |
| 79 | model_path = Path(path_or_hf_repo) |
| 80 | if not model_path.exists(): |
| 81 | model_path = Path( |
| 82 | snapshot_download( |
| 83 | repo_id=path_or_hf_repo, |
| 84 | revision=revision, |
| 85 | allow_patterns=[ |
| 86 | "*.json", |
| 87 | "*.safetensors", |
| 88 | "*.py", |
| 89 | "tokenizer.model", |
| 90 | "*.tiktoken", |
| 91 | "*.txt", |
| 92 | ], |
| 93 | resume_download=True, |
| 94 | ) |
| 95 | ) |
| 96 | return model_path |
| 97 | |
| 98 | |
| 99 | def load_model(model_path: Path, lazy: bool = False) -> nn.Module: |
| 100 | """ |
| 101 | Load and initialize the model from a given path. |
| 102 | |
| 103 | Args: |
| 104 | model_path (Path): The path to load the model from. |
| 105 | lazy (bool): If False eval the model parameters to make sure they are |
| 106 | loaded in memory before returning, otherwise they will be loaded |
| 107 | when needed. Default: ``False`` |
| 108 | |
| 109 | Returns: |
| 110 | nn.Module: The loaded and initialized model. |
| 111 | |
| 112 | Raises: |
| 113 | FileNotFoundError: If the weight files (.safetensors) are not found. |
| 114 | ValueError: If the model class or args class are not found or cannot be instantiated. |
| 115 | """ |
| 116 | |
| 117 | config = load_config(model_path) |
| 118 | quantization = config.get("quantization", None) |
| 119 | |
| 120 | weight_files = glob.glob(str(model_path / "*.safetensors")) |
| 121 | if not weight_files: |
| 122 | logging.error(f"No safetensors found in {model_path}") |
| 123 | message = f""" |
| 124 | No safetensors found in {model_path} |
| 125 | Create safetensors using the following code: |
| 126 | ``` |
| 127 | from transformers import AutoModelForCausalLM, AutoProcessor |
| 128 | |
| 129 | model_id= "<huggingface_model_id>" |
| 130 | model = AutoModelForCausalLM.from_pretrained(model_id) |
| 131 | processor = AutoProcessor.from_pretrained(model_id) |
| 132 | |
| 133 | model.save_pretrained("<local_dir>") |
| 134 | processor.save_pretrained("<local_dir>") |
| 135 | ``` |
| 136 | Then use the <local_dir> as the --hf-path in the convert script. |
| 137 | ``` |
| 138 | python -m mlx_vlm.convert --hf-path <local_dir> --mlx-path <mlx_dir> |
| 139 | ``` |
| 140 | """ |
| 141 | raise FileNotFoundError(message) |
| 142 | |
| 143 | weights = {} |
| 144 | for wf in weight_files: |
| 145 | weights.update(mx.load(wf)) |
| 146 | |
| 147 | if "language_config" in config: |
| 148 | config["text_config"] = config["language_config"] |
| 149 | del config["language_config"] |
| 150 | |
| 151 | model_class, model_type = get_model_and_args(config=config) |
| 152 | |
| 153 | if "vision_config" in config: |
| 154 | skip_vision = config["vision_config"].get("skip_vision", False) |
| 155 | skip_vision_non_divisible = config["vision_config"].get( |
| 156 | "skip_vision_non_divisible", False |
| 157 | ) |
| 158 | else: |
| 159 | skip_vision = False |
| 160 | skip_vision_non_divisible = False |
| 161 | |
| 162 | if model_type == "llava_bunny": |
| 163 | vision_config = AutoConfig.from_pretrained(config["mm_vision_tower"]) |
| 164 | text_config = AutoConfig.from_pretrained(config["language_model"]) |
| 165 | vision_config = vision_config.to_dict() |
| 166 | text_config = text_config.to_dict() |
| 167 | config["vision_config"] = { |
| 168 | **vision_config["vision_config"], |
| 169 | **config.get("vision_config", {}), |
| 170 | } |
| 171 | config["text_config"] = text_config |
| 172 | if model_type == "idefics2": |
| 173 | config = AutoConfig.from_pretrained(model_path).to_dict() |
| 174 | if model_type == "phi3_v": |
| 175 | config["vision_config"] = config["img_processor"] |
| 176 | config["text_config"] = {} |
| 177 | if model_type == "qwen2_vl": |
| 178 | config["text_config"] = { |
| 179 | k: v for k, v in config.items() if k != "vision_config" |
| 180 | } |
| 181 | if model_type == "molmo": |
| 182 | intermediate_size = None |
| 183 | if "vision_config" in config and "intermediate_size" in config["vision_config"]: |
| 184 | intermediate_size = config["vision_config"]["intermediate_size"] |
| 185 | |
| 186 | config["text_config"] = asdict(model_class.TextConfig()) |
| 187 | config["vision_config"] = asdict(model_class.VisionConfig()) |
| 188 | config["vision_config"]["intermediate_size"] = intermediate_size |
| 189 | |
| 190 | config["vision_config"]["skip_vision"] = skip_vision |
| 191 | config["vision_config"]["skip_vision_non_divisible"] = skip_vision_non_divisible |
| 192 | |
| 193 | model_config = model_class.ModelConfig.from_dict(config) |
| 194 | |
| 195 | model_config.vision_config = model_class.VisionConfig.from_dict( |
| 196 | config["vision_config"] |
| 197 | ) |
| 198 | |
| 199 | model_config.text_config = model_class.TextConfig.from_dict(config["text_config"]) |
| 200 | |
| 201 | if hasattr(model_config, "perceiver_config"): |
| 202 | model_config.perceiver_config = model_class.PerceiverConfig.from_dict( |
| 203 | config["perceiver_config"] |
| 204 | ) |
| 205 | if hasattr(model_config, "aligner_config"): |
| 206 | model_config.aligner_config = model_class.AlignerConfig.from_dict( |
| 207 | config["aligner_config"] |
| 208 | ) |
| 209 | |
| 210 | model = model_class.Model(model_config) |
| 211 | |
| 212 | if hasattr(model, "sanitize"): |
| 213 | weights = model.sanitize(weights) |
| 214 | |
| 215 | if hasattr(model_class.VisionModel, "sanitize"): |
| 216 | weights = model_class.VisionModel(model_config.vision_config).sanitize( |
| 217 | weights=weights |
| 218 | ) |
| 219 | |
| 220 | if hasattr(model_class.LanguageModel, "sanitize"): |
| 221 | weights = model_class.LanguageModel(model_config.text_config).sanitize( |
| 222 | weights=weights |
| 223 | ) |
| 224 | |
| 225 | if (quantization := config.get("quantization", None)) is not None: |
| 226 | # Handle legacy models which may not have everything quantized |
| 227 | skip_vision = config.get("vision_config", {}).get("skip_vision", False) |
| 228 | skip_vision_non_divisible = config.get("vision_config", {}).get( |
| 229 | "skip_vision_non_divisible", False |
| 230 | ) |
| 231 | if skip_vision: |
| 232 | class_predicate = lambda _, m: not ( |
| 233 | "vision_model" in m.name or "vision_tower" in m.name |
| 234 | ) |
| 235 | elif skip_vision_non_divisible: |
| 236 | class_predicate = ( |
| 237 | lambda _, m: hasattr(m, "to_quantized") and m.weight.shape[-1] % 64 == 0 |
| 238 | ) |
| 239 | else: |
| 240 | class_predicate = ( |
| 241 | lambda p, m: isinstance(m, (nn.Linear, nn.Embedding)) |
| 242 | and f"{p}.scales" in weights |
| 243 | ) |
| 244 | |
| 245 | nn.quantize( |
| 246 | model, |
| 247 | **quantization, |
| 248 | class_predicate=class_predicate, |
| 249 | ) |
| 250 | |
| 251 | model.load_weights(list(weights.items())) |
| 252 | if not lazy: |
| 253 | mx.eval(model.parameters()) |
| 254 | |
| 255 | model.eval() |
| 256 | return model |
| 257 | |
| 258 | |
| 259 | def load( |
| 260 | path_or_hf_repo: str, |
| 261 | processor_config={}, |
| 262 | adapter_path: Optional[str] = None, |
| 263 | lazy: bool = False, |
| 264 | ) -> Tuple[nn.Module, Union[PreTrainedTokenizer, PreTrainedTokenizerFast]]: |
| 265 | """ |
| 266 | Load the model and tokenizer from a given path or a huggingface repository. |
| 267 | |
| 268 | Args: |
| 269 | path_or_hf_repo (Path): The path or the huggingface repository to load the model from. |
| 270 | tokenizer_config (dict, optional): Configuration parameters specifically for the tokenizer. |
| 271 | Defaults to an empty dictionary. |
| 272 | adapter_path (str, optional): Path to the LoRA adapters. If provided, applies LoRA layers |
| 273 | to the model. Default: ``None``. |
| 274 | lazy (bool): If False eval the model parameters to make sure they are |
| 275 | loaded in memory before returning, otherwise they will be loaded |
| 276 | when needed. Default: ``False`` |
| 277 | Returns: |
| 278 | Tuple[nn.Module, TokenizerWrapper]: A tuple containing the loaded model and tokenizer. |
| 279 | |
| 280 | Raises: |
| 281 | FileNotFoundError: If config file or safetensors are not found. |
| 282 | ValueError: If model class or args class are not found. |
| 283 | """ |
| 284 | model_path = get_model_path(path_or_hf_repo) |
| 285 | |
| 286 | model = load_model(model_path, lazy) |
| 287 | if adapter_path is not None: |
| 288 | # TODO: Support more modules than just language_model |
| 289 | model = apply_lora_layers(model, adapter_path) |
| 290 | model.eval() |
| 291 | |
| 292 | processor = load_processor(model_path, processor_config=processor_config) |
| 293 | |
| 294 | return model, processor |
| 295 | |
| 296 | |
| 297 | def load_config(model_path: Union[str, Path]) -> dict: |
| 298 | |
| 299 | if isinstance(model_path, str): |
| 300 | model_path = get_model_path(model_path) |
| 301 | |
| 302 | try: |
| 303 | with open(model_path / "config.json", "r") as f: |
| 304 | config = json.load(f) |
| 305 | except FileNotFoundError: |
| 306 | logging.error(f"Config file not found in {model_path}") |
| 307 | raise |
| 308 | return config |
| 309 | |
| 310 | |
| 311 | def load_image_processor(model_path: Union[str, Path]) -> BaseImageProcessor: |
| 312 | if isinstance(model_path, str): |
| 313 | model_path = get_model_path(model_path) |
| 314 | |
| 315 | config = load_config(model_path) |
| 316 | model_class, _ = get_model_and_args(config) |
| 317 | image_processor = None |
| 318 | |
| 319 | if hasattr(model_class, "ImageProcessor"): |
| 320 | import inspect |
| 321 | |
| 322 | init_signature = inspect.signature(model_class.ImageProcessor.__init__) |
| 323 | |
| 324 | if "config" in init_signature.parameters: |
| 325 | image_processor = model_class.ImageProcessor(config=config) |
| 326 | else: |
| 327 | image_processor = model_class.ImageProcessor() |
| 328 | |
| 329 | return image_processor |
| 330 | |
| 331 | |
| 332 | def load_processor( |
| 333 | model_path, processor_config={"trust_remote_code": True}, add_detokenizer=True |
| 334 | ) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]: |
| 335 | processor = AutoProcessor.from_pretrained(model_path, **processor_config) |
| 336 | if add_detokenizer: |
| 337 | detokenizer_class = load_tokenizer(model_path, return_tokenizer=False) |
| 338 | if "tokenizer" in processor.__dict__.keys(): |
| 339 | processor.detokenizer = detokenizer_class(processor.tokenizer) |
| 340 | else: |
| 341 | processor.detokenizer = detokenizer_class(processor) |
| 342 | return processor |
| 343 | |
| 344 | |
| 345 | def fetch_from_hub( |
| 346 | model_path: Path, lazy: bool = False |
| 347 | ) -> Tuple[nn.Module, dict, PreTrainedTokenizer]: |
| 348 | model = load_model(model_path, lazy) |
| 349 | config = load_config(model_path) |
| 350 | processor = load_processor(model_path, add_detokenizer=False) |
| 351 | return model, config, processor |
| 352 | |
| 353 | |
| 354 | def make_shards(weights: dict, max_file_size_gb: int = MAX_FILE_SIZE_GB) -> list: |
| 355 | """ |
| 356 | Splits the weights into smaller shards. |
| 357 | |
| 358 | Args: |
| 359 | weights (dict): Model weights. |
| 360 | max_file_size_gb (int): Maximum size of each shard in gigabytes. |
| 361 | |
| 362 | Returns: |
| 363 | list: List of weight shards. |
| 364 | """ |
| 365 | max_file_size_bytes = max_file_size_gb << 30 |
| 366 | shards = [] |
| 367 | shard, shard_size = {}, 0 |
| 368 | for k, v in weights.items(): |
| 369 | if shard_size + v.nbytes > max_file_size_bytes: |
| 370 | shards.append(shard) |
| 371 | shard, shard_size = {}, 0 |
| 372 | shard[k] = v |
| 373 | shard_size += v.nbytes |
| 374 | shards.append(shard) |
| 375 | return shards |
| 376 | |
| 377 | |
| 378 | def upload_to_hub(path: str, upload_repo: str, hf_path: str): |
| 379 | """ |
| 380 | Uploads the model to Hugging Face hub. |
| 381 | |
| 382 | Args: |
| 383 | path (str): Local path to the model. |
| 384 | upload_repo (str): Name of the HF repo to upload to. |
| 385 | hf_path (str): Path to the original Hugging Face model. |
| 386 | """ |
| 387 | import os |
| 388 | |
| 389 | from huggingface_hub import HfApi, ModelCard, logging |
| 390 | |
| 391 | from . import __version__ |
| 392 | |
| 393 | card = ModelCard.load(hf_path) |
| 394 | card.data.tags = ["mlx"] if card.data.tags is None else card.data.tags + ["mlx"] |
| 395 | card.text = dedent( |
| 396 | f""" |
| 397 | # {upload_repo} |
| 398 | This model was converted to MLX format from [`{hf_path}`]() using mlx-vlm version **{__version__}**. |
| 399 | Refer to the [original model card](https://huggingface.co/{hf_path}) for more details on the model. |
| 400 | ## Use with mlx |
| 401 | |
| 402 | ```bash |
| 403 | pip install -U mlx-vlm |
| 404 | ``` |
| 405 | |
| 406 | ```bash |
| 407 | python -m mlx_vlm.generate --model {upload_repo} --max-tokens 100 --temp 0.0 |
| 408 | ``` |
| 409 | """ |
| 410 | ) |
| 411 | card.save(os.path.join(path, "README.md")) |
| 412 | |
| 413 | logging.set_verbosity_info() |
| 414 | |
| 415 | api = HfApi() |
| 416 | api.create_repo(repo_id=upload_repo, exist_ok=True) |
| 417 | api.upload_folder( |
| 418 | folder_path=path, |
| 419 | repo_id=upload_repo, |
| 420 | repo_type="model", |
| 421 | ) |
| 422 | print(f"Upload successful, go to https://huggingface.co/{upload_repo} for details.") |
| 423 | |
| 424 | |
| 425 | def get_model_path(path_or_hf_repo: str, revision: Optional[str] = None) -> Path: |
| 426 | """ |
| 427 | Ensures the model is available locally. If the path does not exist locally, |
| 428 | it is downloaded from the Hugging Face Hub. |
| 429 | |
| 430 | Args: |
| 431 | path_or_hf_repo (str): The local path or Hugging Face repository ID of the model. |
| 432 | revision (str, optional): A revision id which can be a branch name, a tag, or a commit hash. |
| 433 | |
| 434 | Returns: |
| 435 | Path: The path to the model. |
| 436 | """ |
| 437 | model_path = Path(path_or_hf_repo) |
| 438 | if not model_path.exists(): |
| 439 | model_path = Path( |
| 440 | snapshot_download( |
| 441 | repo_id=path_or_hf_repo, |
| 442 | revision=revision, |
| 443 | allow_patterns=[ |
| 444 | "*.json", |
| 445 | "*.safetensors", |
| 446 | "*.py", |
| 447 | "tokenizer.model", |
| 448 | "*.tiktoken", |
| 449 | "*.txt", |
| 450 | ], |
| 451 | ) |
| 452 | ) |
| 453 | return model_path |
| 454 | |
| 455 | |
| 456 | def apply_repetition_penalty(logits: mx.array, generated_tokens: Any, penalty: float): |
| 457 | """ |
| 458 | Apply repetition penalty to specific logits based on the given context. |
| 459 | |
| 460 | Paper: https://arxiv.org/abs/1909.05858 |
| 461 | |
| 462 | Args: |
| 463 | logits (mx.array): The logits produced by the language model. |
| 464 | generated_tokens (any): A list of N previous tokens. |
| 465 | penalty (float): The repetition penalty factor to be applied. |
| 466 | |
| 467 | Returns: |
| 468 | logits (mx.array): Logits with repetition penalty applied to generated tokens. |
| 469 | """ |
| 470 | if len(generated_tokens) > 0: |
| 471 | indices = mx.array([token for token in generated_tokens]) |
| 472 | selected_logits = logits[:, indices] |
| 473 | selected_logits = mx.where( |
| 474 | selected_logits < 0, selected_logits * penalty, selected_logits / penalty |
| 475 | ) |
| 476 | logits[:, indices] = selected_logits |
| 477 | return logits |
| 478 | |
| 479 | |
| 480 | def save_weights( |
| 481 | save_path: Union[str, Path], |
| 482 | weights: Dict[str, Any], |
| 483 | *, |
| 484 | donate_weights: bool = False, |
| 485 | ) -> None: |
| 486 | """Save model weights into specified directory.""" |
| 487 | if isinstance(save_path, str): |
| 488 | save_path = Path(save_path) |
| 489 | save_path.mkdir(parents=True, exist_ok=True) |
| 490 | |
| 491 | shards = make_shards(weights) |
| 492 | shards_count = len(shards) |
| 493 | shard_file_format = ( |
| 494 | "model-{:05d}-of-{:05d}.safetensors" |
| 495 | if shards_count > 1 |
| 496 | else "model.safetensors" |
| 497 | ) |
| 498 | |
| 499 | total_size = sum(v.nbytes for v in weights.values()) |
| 500 | index_data = {"metadata": {"total_size": total_size}, "weight_map": {}} |
| 501 | |
| 502 | # Write the weights and make sure no references are kept other than the |
| 503 | # necessary ones |
| 504 | if donate_weights: |
| 505 | weights.clear() |
| 506 | del weights |
| 507 | |
| 508 | for i in range(len(shards)): |
| 509 | shard = shards[i] |
| 510 | shards[i] = None |
| 511 | shard_name = shard_file_format.format(i + 1, shards_count) |
| 512 | shard_path = save_path / shard_name |
| 513 | |
| 514 | mx.save_safetensors(str(shard_path), shard, metadata={"format": "mlx"}) |
| 515 | |
| 516 | for weight_name in shard.keys(): |
| 517 | index_data["weight_map"][weight_name] = shard_name |
| 518 | del shard |
| 519 | |
| 520 | index_data["weight_map"] = { |
| 521 | k: index_data["weight_map"][k] for k in sorted(index_data["weight_map"]) |
| 522 | } |
| 523 | |
| 524 | with open(save_path / "model.safetensors.index.json", "w") as f: |
| 525 | json.dump( |
| 526 | index_data, |
| 527 | f, |
| 528 | indent=4, |
| 529 | ) |
| 530 | |
| 531 | |
| 532 | def quantize_model( |
| 533 | model: nn.Module, |
| 534 | config: dict, |
| 535 | q_group_size: int, |
| 536 | q_bits: int, |
| 537 | skip_vision: bool = False, |
| 538 | skip_vision_non_divisible: bool = False, |
| 539 | ) -> Tuple[dict, dict]: |
| 540 | """ |
| 541 | Applies quantization to the model weights. |
| 542 | |
| 543 | Args: |
| 544 | model (nn.Module): The model to be quantized. |
| 545 | config (dict): Model configuration. |
| 546 | q_group_size (int): Group size for quantization. |
| 547 | q_bits (int): Bits per weight for quantization. |
| 548 | skip_vision (bool): Whether to skip quantizing vision model weights. |
| 549 | |
| 550 | Returns: |
| 551 | Tuple[dict, dict]: Tuple containing quantized weights and updated config. |
| 552 | """ |
| 553 | quantized_config = copy.deepcopy(config) |
| 554 | quantized_config.setdefault("vision_config", {}) |
| 555 | |
| 556 | # Get vision model size |
| 557 | vision_size = _get_vision_size(model) |
| 558 | |
| 559 | # Apply quantization |
| 560 | if skip_vision: |
| 561 | # Quantize only non-vision modules |
| 562 | nn.quantize( |
| 563 | model, |
| 564 | q_group_size, |
| 565 | q_bits, |
| 566 | class_predicate=lambda x: not ( |
| 567 | "vision_model" in x.name or "vision_tower" in x.name |
| 568 | ), |
| 569 | ) |
| 570 | quantized_config["vision_config"]["skip_vision"] = skip_vision |
| 571 | elif skip_vision_non_divisible: |
| 572 | # Quantize only layers with to_quantized method and divisible by 64 |
| 573 | nn.quantize( |
| 574 | model, |
| 575 | q_group_size, |
| 576 | q_bits, |
| 577 | class_predicate=lambda _, m: hasattr(m, "to_quantized") |
| 578 | and m.weight.shape[-1] % 64 == 0, |
| 579 | ) |
| 580 | quantized_config["vision_config"][ |
| 581 | "skip_vision_non_divisible" |
| 582 | ] = skip_vision_non_divisible |
| 583 | else: |
| 584 | # Pad vision model if needed |
| 585 | _pad_vision_model(model, vision_size) |
| 586 | if hasattr(model.config.vision_config, "intermediate_size"): |
| 587 | _update_vision_config( |
| 588 | quantized_config, vision_size, key="intermediate_size" |
| 589 | ) |
| 590 | elif hasattr(model.config.vision_config, "hidden_size"): |
| 591 | _update_vision_config(quantized_config, vision_size, key="hidden_size") |
| 592 | else: |
| 593 | raise ValueError( |
| 594 | "No intermediate_size or hidden_size found in vision_config" |
| 595 | ) |
| 596 | |
| 597 | nn.quantize(model, q_group_size, q_bits) |
| 598 | |
| 599 | # Update config and get weights |
| 600 | quantized_config["quantization"] = {"group_size": q_group_size, "bits": q_bits} |
| 601 | quantized_weights = dict(tree_flatten(model.parameters())) |
| 602 | |
| 603 | return quantized_weights, quantized_config |
| 604 | |
| 605 | |
| 606 | def _get_vision_size(model: nn.Module) -> int: |
| 607 | """Get vision model intermediate/hidden size.""" |
| 608 | if hasattr(model.config.vision_config, "intermediate_size"): |
| 609 | return model.config.vision_config.intermediate_size |
| 610 | return model.config.vision_config.hidden_size |
| 611 | |
| 612 | |
| 613 | def _pad_vision_model(model: nn.Module, vision_size: int, divisor: int = 64) -> None: |
| 614 | """Pad vision model layers to be divisible by divisor.""" |
| 615 | if any(vision_size % size != 0 for size in [64, 128]): |
| 616 | for name, module in model.named_modules(): |
| 617 | if isinstance(module, nn.Linear) and ( |
| 618 | "vision_model" in name or "vision_tower" in name |
| 619 | ): |
| 620 | out_features, in_features = module.weight.shape |
| 621 | |
| 622 | new_out = ( |
| 623 | ((out_features // divisor) + 1) * divisor |
| 624 | if out_features % divisor |
| 625 | else out_features |
| 626 | ) |
| 627 | new_in = ( |
| 628 | ((in_features // divisor) + 1) * divisor |
| 629 | if in_features % divisor |
| 630 | else in_features |
| 631 | ) |
| 632 | |
| 633 | if new_out != out_features or new_in != in_features: |
| 634 | new_weight = mx.zeros((new_out, new_in), dtype=module.weight.dtype) |
| 635 | new_bias = mx.zeros((new_out), dtype=module.bias.dtype) |
| 636 | |
| 637 | new_weight[:out_features, :in_features] = module.weight |
| 638 | module.weight = new_weight |
| 639 | |
| 640 | if hasattr(module, "bias"): |
| 641 | new_bias[:out_features] = module.bias |
| 642 | module.bias = new_bias |
| 643 | |
| 644 | |
| 645 | def _update_vision_config( |
| 646 | config: dict, |
| 647 | value: Union[int, bool], |
| 648 | divisor: int = 64, |
| 649 | key: str = "intermediate_size", |
| 650 | ) -> None: |
| 651 | """Update vision config with padded sizes.""" |
| 652 | if key in ["intermediate_size", "hidden_size"]: |
| 653 | config["vision_config"][key] = ( |
| 654 | ((value // divisor) + 1) * divisor if value % divisor != 0 else value |
| 655 | ) |
| 656 | else: |
| 657 | config["vision_config"][key] = value |
| 658 | |
| 659 | |
| 660 | def save_config( |
| 661 | config: dict, |
| 662 | config_path: Union[str, Path], |
| 663 | ) -> None: |
| 664 | """Save the model configuration to the ``config_path``. |
| 665 | |
| 666 | The final configuration will be sorted before saving for better readability. |
| 667 | |
| 668 | Args: |
| 669 | config (dict): The model configuration. |
| 670 | config_path (Union[str, Path]): Model configuration file path. |
| 671 | """ |
| 672 | # Clean unused keys |
| 673 | config.pop("_name_or_path", None) |
| 674 | |
| 675 | # sort the config for better readability |
| 676 | config = dict(sorted(config.items())) |
| 677 | |
| 678 | # write the updated config to the config_path (if provided) |
| 679 | with open(config_path, "w") as fid: |
| 680 | json.dump(config, fid, indent=4) |
| 681 | |
| 682 | |
| 683 | def dequantize_model(model: nn.Module) -> nn.Module: |
| 684 | """ |
| 685 | Dequantize the quantized linear layers in the model. |
| 686 | |
| 687 | Args: |
| 688 | model (nn.Module): The model with quantized linear layers. |
| 689 | |
| 690 | Returns: |
| 691 | nn.Module: The model with dequantized layers. |
| 692 | """ |
| 693 | de_quantize_layers = [] |
| 694 | for name, module in model.named_modules(): |
| 695 | if isinstance(module, nn.QuantizedLinear): |
| 696 | bias = "bias" in module |
| 697 | weight = module.weight |
| 698 | weight = mx.dequantize( |
| 699 | weight, |
| 700 | module.scales, |
| 701 | module.biases, |
| 702 | module.group_size, |
| 703 | module.bits, |
| 704 | ).astype(mx.float16) |
| 705 | output_dims, input_dims = weight.shape |
| 706 | linear = nn.Linear(input_dims, output_dims, bias=bias) |
| 707 | linear.weight = weight |
| 708 | if bias: |
| 709 | linear.bias = module.bias |
| 710 | de_quantize_layers.append((name, linear)) |
| 711 | if len(de_quantize_layers) > 0: |
| 712 | model.update_modules(tree_unflatten(de_quantize_layers)) |
| 713 | return model |
| 714 | |
| 715 | |
| 716 | def convert( |
| 717 | hf_path: str, |
| 718 | mlx_path: str = "mlx_model", |
| 719 | quantize: bool = False, |
| 720 | q_group_size: int = 64, |
| 721 | q_bits: int = 4, |
| 722 | dtype: str = "float16", |
| 723 | upload_repo: str = None, |
| 724 | revision: Optional[str] = None, |
| 725 | dequantize: bool = False, |
| 726 | skip_vision: bool = False, |
| 727 | skip_vision_non_divisible: bool = False, |
| 728 | ): |
| 729 | print("[INFO] Loading") |
| 730 | model_path = get_model_path(hf_path, revision=revision) |
| 731 | model, config, processor = fetch_from_hub(model_path, lazy=True) |
| 732 | |
| 733 | weights = dict(tree_flatten(model.parameters())) |
| 734 | dtype = mx.float16 if quantize else getattr(mx, dtype) |
| 735 | weights = {k: v.astype(dtype) for k, v in weights.items()} |
| 736 | |
| 737 | if quantize and dequantize: |
| 738 | raise ValueError("Choose either quantize or dequantize, not both.") |
| 739 | |
| 740 | if quantize: |
| 741 | print("[INFO] Quantizing") |
| 742 | model.load_weights(list(weights.items())) |
| 743 | weights, config = quantize_model( |
| 744 | model, config, q_group_size, q_bits, skip_vision, skip_vision_non_divisible |
| 745 | ) |
| 746 | |
| 747 | if dequantize: |
| 748 | print("[INFO] Dequantizing") |
| 749 | model = dequantize_model(model) |
| 750 | weights = dict(tree_flatten(model.parameters())) |
| 751 | |
| 752 | if isinstance(mlx_path, str): |
| 753 | mlx_path = Path(mlx_path) |
| 754 | |
| 755 | del model |
| 756 | save_weights(mlx_path, weights, donate_weights=True) |
| 757 | |
| 758 | py_files = glob.glob(str(model_path / "*.py")) |
| 759 | for file in py_files: |
| 760 | shutil.copy(file, mlx_path) |
| 761 | |
| 762 | processor.save_pretrained(mlx_path) |
| 763 | |
| 764 | save_config(config, config_path=mlx_path / "config.json") |
| 765 | |
| 766 | if upload_repo is not None: |
| 767 | upload_to_hub(mlx_path, upload_repo, hf_path) |
| 768 | |
| 769 | |
| 770 | def load_image(image_source: Union[str, Path, BytesIO]): |
| 771 | """ |
| 772 | Helper function to load an image from either a URL or file. |
| 773 | """ |
| 774 | if isinstance(image_source, BytesIO): |
| 775 | # for base64 encoded images |
| 776 | try: |
| 777 | return Image.open(image_source) |
| 778 | except IOError as e: |
| 779 | raise ValueError(f"Failed to load image from BytesIO with error: {e}") |
| 780 | elif image_source.startswith(("http://", "https://")): |
| 781 | try: |
| 782 | response = requests.get(image_source, stream=True) |
| 783 | response.raise_for_status() |
| 784 | return Image.open(response.raw) |
| 785 | except Exception as e: |
| 786 | raise ValueError( |
| 787 | f"Failed to load image from URL: {image_source} with error {e}" |
| 788 | ) |
| 789 | elif Path(image_source).is_file(): |
| 790 | try: |
| 791 | return Image.open(image_source) |
| 792 | except IOError as e: |
| 793 | raise ValueError(f"Failed to load image {image_source} with error: {e}") |
| 794 | else: |
| 795 | raise ValueError( |
| 796 | f"The image {image_source} must be a valid URL or existing file." |
| 797 | ) |
| 798 | |
| 799 | |
| 800 | def resize_image(img, max_size): |
| 801 | ratio = min(max_size[0] / img.width, max_size[1] / img.height) |
| 802 | new_size = (int(img.width * ratio), int(img.height * ratio)) |
| 803 | return img.resize(new_size) |
| 804 | |
| 805 | |
| 806 | def process_image(img, resize_shape, image_processor): |
| 807 | if isinstance(img, str): |
| 808 | img = load_image(img) |
| 809 | if resize_shape is not None and image_processor is None: |
| 810 | img = resize_image(img, resize_shape) |
| 811 | return img |
| 812 | |
| 813 | |
| 814 | def prepare_inputs( |
| 815 | image_processor, processor, images, prompts, image_token_index, resize_shape=None |
| 816 | ): |
| 817 | from transformers.image_utils import load_image |
| 818 | |
| 819 | mask = None |
| 820 | if not isinstance(images, list): |
| 821 | images = [images] |
| 822 | |
| 823 | # Process images |
| 824 | images = [process_image(img, resize_shape, image_processor) for img in images] |
| 825 | |
| 826 | image_grid_thw = None |
| 827 | image_sizes = None |
| 828 | aspect_ratio_ids = None |
| 829 | aspect_ratio_mask = None |
| 830 | cross_attention_mask = None |
| 831 | image_input_idx = None |
| 832 | image_masks = None |
| 833 | |
| 834 | if image_processor is not None: |
| 835 | if not isinstance(prompts, list): |
| 836 | prompts = [prompts] |
| 837 | |
| 838 | processor.pad_token = processor.eos_token |
| 839 | text_chunks = [ |
| 840 | [processor(chunk).input_ids for chunk in prompt.split("<image>")] |
| 841 | for prompt in prompts |
| 842 | ] |
| 843 | |
| 844 | # Find the maximum length for padding |
| 845 | max_length = max( |
| 846 | sum(len(chunk) for chunk in chunks) + 1 for chunks in text_chunks |
| 847 | ) |
| 848 | |
| 849 | # Pad and create input_ids |
| 850 | input_ids = [] |
| 851 | for chunks in text_chunks: |
| 852 | ids = chunks[0] + [image_token_index] + chunks[1] |
| 853 | padding = [processor.pad_token_id] * (max_length - len(ids)) |
| 854 | input_ids.append(mx.array(ids + padding)) |
| 855 | |
| 856 | input_ids = mx.array(input_ids) |
| 857 | |
| 858 | pixel_values = image_processor.preprocess(images=images) |
| 859 | pixel_values = mx.array(np.stack(pixel_values)) |
| 860 | |
| 861 | mask = mx.array([(ids != processor.pad_token_id) for ids in input_ids]).astype( |
| 862 | mx.int32 |
| 863 | ) |
| 864 | else: |
| 865 | processor.tokenizer.pad_token = processor.tokenizer.eos_token |
| 866 | if hasattr(processor, "process"): |
| 867 | inputs = processor.process( |
| 868 | text=prompts, images=images, padding=True, return_tensors="mlx" |
| 869 | ) |
| 870 | else: |
| 871 | inputs = processor( |
| 872 | text=prompts, images=images, padding=True, return_tensors="mlx" |
| 873 | ) |
| 874 | if "images" in inputs: |
| 875 | inputs["pixel_values"] = inputs["images"] |
| 876 | inputs.pop("images") |
| 877 | |
| 878 | if isinstance(inputs["pixel_values"], list): |
| 879 | pixel_values = inputs["pixel_values"] |
| 880 | else: |
| 881 | pixel_values = mx.array(inputs["pixel_values"]) |
| 882 | input_ids = mx.array(inputs["input_ids"]) |
| 883 | mask = ( |
| 884 | mx.array(inputs["attention_mask"]) if "attention_mask" in inputs else None |
| 885 | ) |
| 886 | |
| 887 | image_input_idx = inputs.get("image_input_idx", None) |
| 888 | if image_input_idx is not None: |
| 889 | image_input_idx = mx.array(image_input_idx) |
| 890 | |
| 891 | image_masks = inputs.get("image_masks", None) |
| 892 | if image_masks is not None: |
| 893 | image_masks = mx.array(image_masks) |
| 894 | |
| 895 | image_sizes = inputs.get("image_sizes", None) |
| 896 | if image_sizes is not None: |
| 897 | image_sizes = mx.array(image_sizes) |
| 898 | |
| 899 | image_grid_thw = inputs.get("image_grid_thw", None) |
| 900 | if image_grid_thw is not None: |
| 901 | image_grid_thw = mx.array(image_grid_thw) |
| 902 | |
| 903 | aspect_ratio_ids = inputs.get("aspect_ratio_ids", None) |
| 904 | if aspect_ratio_ids is not None: |
| 905 | aspect_ratio_ids = mx.array(aspect_ratio_ids) |
| 906 | |
| 907 | aspect_ratio_mask = inputs.get("aspect_ratio_mask", None) |
| 908 | if aspect_ratio_mask is not None: |
| 909 | aspect_ratio_mask = mx.array(aspect_ratio_mask) |
| 910 | |
| 911 | cross_attention_mask = inputs.get("cross_attention_mask", None) |
| 912 | if cross_attention_mask is not None: |
| 913 | cross_attention_mask = mx.array(cross_attention_mask) |
| 914 | |
| 915 | return ( |
| 916 | input_ids, |
| 917 | pixel_values, |
| 918 | mask, |
| 919 | image_grid_thw, |
| 920 | image_sizes, |
| 921 | aspect_ratio_ids, |
| 922 | aspect_ratio_mask, |
| 923 | cross_attention_mask, |
| 924 | image_input_idx, |
| 925 | image_masks, |
| 926 | ) |
| 927 | |
| 928 | |
| 929 | def generate_step( |
| 930 | input_ids: mx.array, |
| 931 | model: nn.Module, |
| 932 | pixel_values, |
| 933 | mask, |
| 934 | temp: float = 0.0, |
| 935 | repetition_penalty: Optional[float] = None, |
| 936 | repetition_context_size: Optional[int] = 20, |
| 937 | top_p: float = 1.0, |
| 938 | logit_bias: Optional[Dict[int, float]] = None, |
| 939 | **kwargs, |
| 940 | ) -> Generator[Tuple[mx.array, mx.array], None, None]: |
| 941 | """ |
| 942 | A generator producing token ids based on the given prompt from the model. |
| 943 | |
| 944 | Args: |
| 945 | prompt (mx.array): The input prompt. |
| 946 | model (nn.Module): The model to use for generation. |
| 947 | temp (float): The temperature for sampling, if 0 the argmax is used. |
| 948 | Default: ``0``. |
| 949 | repetition_penalty (float, optional): The penalty factor for repeating |
| 950 | tokens. |
| 951 | repetition_context_size (int, optional): The number of tokens to |
| 952 | consider for repetition penalty. Default: ``20``. |
| 953 | top_p (float, optional): Nulceus sampling, higher means model considers |
| 954 | more less likely words. |
| 955 | logit_bias (dictionary, optional): Additive logit bias. |
| 956 | |
| 957 | Yields: |
| 958 | Generator[Tuple[mx.array, mx.array], None, None]: A generator producing |
| 959 | one token and a vector of log probabilities. |
| 960 | """ |
| 961 | |
| 962 | def sample(logits: mx.array) -> Tuple[mx.array, float]: |
| 963 | if logit_bias: |
| 964 | indices = mx.array(list(logit_bias.keys())) |
| 965 | values = mx.array(list(logit_bias.values())) |
| 966 | logits[:, indices] += values |
| 967 | logprobs = logits - mx.logsumexp(logits) |
| 968 | |
| 969 | if temp == 0: |
| 970 | token = mx.argmax(logits, axis=-1) |
| 971 | else: |
| 972 | if top_p > 0 and top_p < 1.0: |
| 973 | token = top_p_sampling(logits, top_p, temp) |
| 974 | else: |
| 975 | token = mx.random.categorical(logits * (1 / temp)) |
| 976 | |
| 977 | return token, logprobs |
| 978 | |
| 979 | if repetition_penalty and ( |
| 980 | repetition_penalty < 0 or not isinstance(repetition_penalty, float) |
| 981 | ): |
| 982 | raise ValueError( |
| 983 | f"repetition_penalty must be a non-negative float, got {repetition_penalty}" |
| 984 | ) |
| 985 | |
| 986 | y = input_ids |
| 987 | if hasattr(model.language_model, "make_cache"): |
| 988 | cache = model.language_model.make_cache() |
| 989 | else: |
| 990 | kv_heads = ( |
| 991 | [model.language_model.n_kv_heads] * len(model.language_model.layers) |
| 992 | if isinstance(model.language_model.n_kv_heads, int) |
| 993 | else model.language_model.n_kv_heads |
| 994 | ) |
| 995 | if model.config.model_type == "florence2": |
| 996 | cache = [ |
| 997 | (SimpleKVCache(), SimpleKVCache()) for n in model.language_model.layers |
| 998 | ] |
| 999 | else: |
| 1000 | cache = [KVCache(model.language_model.head_dim, n) for n in kv_heads] |
| 1001 | |
| 1002 | repetition_context = input_ids.reshape(-1).tolist() |
| 1003 | |
| 1004 | if repetition_context_size: |
| 1005 | repetition_context = repetition_context[-repetition_context_size:] |
| 1006 | |
| 1007 | def _step(y, **kwargs): |
| 1008 | nonlocal repetition_context |
| 1009 | if "decoder_input_ids" in kwargs: |
| 1010 | outputs = model.language_model( |
| 1011 | cache=cache, |
| 1012 | **kwargs, |
| 1013 | ) |
| 1014 | else: |
| 1015 | |
| 1016 | outputs = model.language_model( |
| 1017 | y[None], |
| 1018 | cache=cache, |
| 1019 | mask=mask, |
| 1020 | **kwargs, |
| 1021 | ) |
| 1022 | |
| 1023 | logits = outputs.logits[:, -1, :] |
| 1024 | |
| 1025 | if repetition_penalty: |
| 1026 | logits = apply_repetition_penalty( |
| 1027 | logits, repetition_context, repetition_penalty |
| 1028 | ) |
| 1029 | y, logprobs = sample(logits) |
| 1030 | repetition_context.append(y.item()) |
| 1031 | else: |
| 1032 | y, logprobs = sample(logits) |
| 1033 | |
| 1034 | if repetition_context_size: |
| 1035 | if len(repetition_context) > repetition_context_size: |
| 1036 | repetition_context = repetition_context[-repetition_context_size:] |
| 1037 | return y, logprobs.squeeze(0) |
| 1038 | |
| 1039 | outputs = model(input_ids, pixel_values, cache=cache, mask=mask, **kwargs) |
| 1040 | |
| 1041 | logits = outputs.logits[:, -1, :] |
| 1042 | y, logprobs = sample(logits) |
| 1043 | mx.async_eval(y) |
| 1044 | |
| 1045 | if outputs.cross_attention_states is not None: |
| 1046 | kwargs = { |
| 1047 | k: v |
| 1048 | for k, v in zip( |
| 1049 | ["cross_attention_states"], [outputs.cross_attention_states] |
| 1050 | ) |
| 1051 | } |
| 1052 | elif outputs.encoder_outputs is not None: |
| 1053 | kwargs = { |
| 1054 | "decoder_input_ids": y[None], |
| 1055 | "encoder_outputs": outputs.encoder_outputs, |
| 1056 | } |
| 1057 | else: |
| 1058 | kwargs = {} |
| 1059 | |
| 1060 | while True: |
| 1061 | next_y, next_logprobs = _step(y, **kwargs) |
| 1062 | mx.async_eval(next_y) |
| 1063 | if "decoder_input_ids" in kwargs: |
| 1064 | kwargs["decoder_input_ids"] = next_y[None] |
| 1065 | yield y.item(), logprobs |
| 1066 | y, logprobs = next_y, next_logprobs |
| 1067 | |
| 1068 | |
| 1069 | def stream_generate( |
| 1070 | model: nn.Module, |
| 1071 | processor: PreTrainedTokenizer, |
| 1072 | image: str, |
| 1073 | prompt: str, |
| 1074 | image_processor=None, |
| 1075 | max_tokens: int = 100, |
| 1076 | **kwargs, |
| 1077 | ) -> Union[str, Generator[str, None, None]]: |
| 1078 | """ |
| 1079 | A generator producing text based on the given prompt from the model. |
| 1080 | |
| 1081 | Args: |
| 1082 | prompt (mx.array): The input prompt. |
| 1083 | model (nn.Module): The model to use for generation. |
| 1084 | max_tokens (int): The ma |
| 1085 | kwargs: The remaining options get passed to :func:`generate_step`. |
| 1086 | See :func:`generate_step` for more details. |
| 1087 | |
| 1088 | Yields: |
| 1089 | Generator[Tuple[mx.array, mx.array]]: A generator producing text. |
| 1090 | """ |
| 1091 | |
| 1092 | if image_processor is not None: |
| 1093 | tokenizer = processor |
| 1094 | else: |
| 1095 | tokenizer = processor.tokenizer |
| 1096 | |
| 1097 | resize_shape = kwargs.pop("resize_shape", None) |
| 1098 | image_token_index = model.config.image_token_index |
| 1099 | |
| 1100 | # Prepare inputs |
| 1101 | inputs = prepare_inputs( |
| 1102 | image_processor, processor, image, prompt, image_token_index, resize_shape |
| 1103 | ) |
| 1104 | input_ids, pixel_values, mask = inputs[:3] |
| 1105 | kwargs = {k: v for k, v in zip(["image_grid_thw", "image_sizes"], inputs[3:])} |
| 1106 | |
| 1107 | detokenizer = processor.detokenizer |
| 1108 | |
| 1109 | detokenizer.reset() |
| 1110 | for (token, _), n in zip( |
| 1111 | generate_step(input_ids, model, pixel_values, mask, **kwargs), |
| 1112 | range(max_tokens), |
| 1113 | ): |
| 1114 | if token == tokenizer.eos_token_id: |
| 1115 | break |
| 1116 | detokenizer.add_token(token) |
| 1117 | |
| 1118 | # Yield the last segment if streaming |
| 1119 | yield detokenizer.last_segment |
| 1120 | |
| 1121 | detokenizer.finalize() |
| 1122 | yield detokenizer.last_segment |
| 1123 | |
| 1124 | |
| 1125 | def generate( |
| 1126 | model: nn.Module, |
| 1127 | processor: PreTrainedTokenizer, |
| 1128 | image: str, |
| 1129 | prompt: str, |
| 1130 | image_processor=None, |
| 1131 | temp: float = 0.0, |
| 1132 | max_tokens: int = 100, |
| 1133 | verbose: bool = False, |
| 1134 | formatter: Optional[Callable] = None, |
| 1135 | repetition_penalty: Optional[float] = 1.1, |
| 1136 | repetition_context_size: Optional[int] = 20, |
| 1137 | top_p: float = 1.0, |
| 1138 | **kwargs, |
| 1139 | ) -> str: |
| 1140 | """ |
| 1141 | Generate text from the model. |
| 1142 | |
| 1143 | Args: |
| 1144 | model (nn.Module): The language model. |
| 1145 | tokenizer (PreTrainedTokenizer): The tokenizer. |
| 1146 | prompt (str): The string prompt. |
| 1147 | temp (float): The temperature for sampling (default 0). |
| 1148 | max_tokens (int): The maximum number of tokens (default 100). |
| 1149 | verbose (bool): If ``True``, print tokens and timing information |
| 1150 | (default ``False``). |
| 1151 | formatter (Optional[Callable]): A function which takes a token and a |
| 1152 | probability and displays it. |
| 1153 | repetition_penalty (float, optional): The penalty factor for repeating tokens. |
| 1154 | repetition_context_size (int, optional): The number of tokens to consider for repetition penalty. |
| 1155 | """ |
| 1156 | |
| 1157 | if verbose: |
| 1158 | print("=" * 10) |
| 1159 | print("Image:", image, "\n") |
| 1160 | print("Prompt:", prompt) |
| 1161 | |
| 1162 | if image_processor is not None: |
| 1163 | prompt_tokens = mx.array(processor.encode(prompt)) |
| 1164 | tokenizer = processor |
| 1165 | else: |
| 1166 | prompt_tokens = mx.array(processor.tokenizer.encode(prompt)) |
| 1167 | tokenizer = processor.tokenizer |
| 1168 | |
| 1169 | resize_shape = kwargs.pop("resize_shape", None) |
| 1170 | if hasattr(model.config, "image_token_index"): |
| 1171 | image_token_index = model.config.image_token_index |
| 1172 | else: |
| 1173 | image_token_index = None |
| 1174 | |
| 1175 | # Prepare inputs |
| 1176 | inputs = prepare_inputs( |
| 1177 | image_processor, processor, image, prompt, image_token_index, resize_shape |
| 1178 | ) |
| 1179 | input_ids, pixel_values, mask = inputs[:3] |
| 1180 | kwargs = { |
| 1181 | k: v |
| 1182 | for k, v in zip( |
| 1183 | [ |
| 1184 | "image_grid_thw", |
| 1185 | "image_sizes", |
| 1186 | "aspect_ratio_ids", |
| 1187 | "aspect_ratio_mask", |
| 1188 | "cross_attention_mask", |
| 1189 | "image_input_idx", |
| 1190 | "image_masks", |
| 1191 | ], |
| 1192 | inputs[3:], |
| 1193 | ) |
| 1194 | } |
| 1195 | |
| 1196 | # Initialize timing and detokenizer |
| 1197 | tic = time.perf_counter() |
| 1198 | detokenizer = processor.detokenizer |
| 1199 | detokenizer.reset() |
| 1200 | |
| 1201 | # Generate tokens |
| 1202 | generator = generate_step( |
| 1203 | input_ids, |
| 1204 | model, |
| 1205 | pixel_values, |
| 1206 | mask, |
| 1207 | temp, |
| 1208 | repetition_penalty, |
| 1209 | repetition_context_size, |
| 1210 | top_p, |
| 1211 | **kwargs, |
| 1212 | ) |
| 1213 | |
| 1214 | for (token, prob), n in zip(generator, range(max_tokens)): |
| 1215 | |
| 1216 | if n == 0: |
| 1217 | prompt_time = time.perf_counter() - tic |
| 1218 | tic = time.perf_counter() |
| 1219 | # TODO: Fix <eos> as first token |
| 1220 | # Handle special case for DeepSeek-vl-7b-chat and PaliGemma models |
| 1221 | # These models may generate EOS token as the first token (n == 0) |
| 1222 | # For all other cases, break the loop when EOS is encountered after the first token |
| 1223 | if token == tokenizer.eos_token_id and n > 0: |
| 1224 | break |
| 1225 | |
| 1226 | detokenizer.add_token(token) |
| 1227 | |
| 1228 | if verbose: |
| 1229 | if formatter: |
| 1230 | # We have to finalize so that the prob corresponds to the last segment |
| 1231 | detokenizer.finalize() |
| 1232 | formatter(detokenizer.last_segment, prob.item()) |
| 1233 | else: |
| 1234 | print(detokenizer.last_segment, end="", flush=True) |
| 1235 | |
| 1236 | token_count = n + 1 |
| 1237 | detokenizer.finalize() |
| 1238 | |
| 1239 | if verbose: |
| 1240 | print(detokenizer.last_segment, flush=True) |
| 1241 | gen_time = time.perf_counter() - tic |
| 1242 | print("=" * 10) |
| 1243 | if token_count == 0: |
| 1244 | print("No tokens generated for this prompt") |
| 1245 | return |
| 1246 | prompt_tps = prompt_tokens.size / prompt_time |
| 1247 | gen_tps = (token_count - 1) / gen_time |
| 1248 | |
| 1249 | print(f"Prompt: {prompt_tps:.3f} tokens-per-sec") |
| 1250 | print(f"Generation: {gen_tps:.3f} tokens-per-sec") |
| 1251 | |
| 1252 | return detokenizer.text |