Changesets · Branches · Tags · Compare
| Changeset | 2a43fc6f4b0835d974bf9e58cf3ba679ce0852f4e570e378b6f5cd06d0cb92c9 |
|---|---|
| Author | Prince Canuma <prince.gdt@gmail.com> · 2024-04-22 21:20 +02:00 |
| Committer | GitHub <noreply@github.com> · 2024-04-22 21:20 +02:00 |
| Parents | 3eff94f57038, c5ec3b228066 |
17 files changed
added .gitignore +21 −0
| @@ -0,0 +1,21 @@ | ||
| 1 | +**.ipynb | |
| 2 | +**.pyc | |
| 3 | + | |
| 4 | + Byte-compiled / optimized / DLL files | |
| 5 | +__pycache__/ | |
| 6 | +*.py[cod] | |
| 7 | + | |
| 8 | +# Distribution / packaging | |
| 9 | +bin/ | |
| 10 | +build/ | |
| 11 | +develop-eggs/ | |
| 12 | +dist/ | |
| 13 | +eggs/ | |
| 14 | +lib/ | |
| 15 | +lib64/ | |
| 16 | +parts/ | |
| 17 | +sdist/ | |
| 18 | +var/ | |
| 19 | +*.egg-info/ | |
| 20 | +.installed.cfg | |
| 21 | +*.egg | |
| No newline at the end of the file |
deleted build/lib/mlx_vlm/__init__.py +0 −2
| @@ -1,2 +0,0 @@ | ||
| 1 | -from .utils import convert, load | |
| 2 | -from .version import __version__ | |
| No newline at the end of the file |
deleted build/lib/mlx_vlm/generate.py +0 −153
| @@ -1,153 +0,0 @@ | ||
| 1 | -import argparse | |
| 2 | -import codecs | |
| 3 | -from pathlib import Path | |
| 4 | - | |
| 5 | -import mlx.core as mx | |
| 6 | -import numpy as np | |
| 7 | -import requests | |
| 8 | -from .utils import get_model_class | |
| 9 | -from PIL import Image | |
| 10 | -from transformers import AutoProcessor, AutoConfig | |
| 11 | - | |
| 12 | -MODEL_TYPE = "" | |
| 13 | -def parse_arguments(): | |
| 14 | - parser = argparse.ArgumentParser( | |
| 15 | - description="Generate text from an image using a model." | |
| 16 | - ) | |
| 17 | - parser.add_argument( | |
| 18 | - "--model", | |
| 19 | - type=str, | |
| 20 | - default="qnguyen3/nanoLLaVA", | |
| 21 | - help="The path to the local model directory or Hugging Face repo.", | |
| 22 | - ) | |
| 23 | - parser.add_argument( | |
| 24 | - "--image", | |
| 25 | - type=str, | |
| 26 | - default="http://images.cocodataset.org/val2017/000000039769.jpg", | |
| 27 | - help="URL or path of the image to process.", | |
| 28 | - ) | |
| 29 | - parser.add_argument( | |
| 30 | - "--prompt", | |
| 31 | - type=str, | |
| 32 | - default="<image>\nWhat are these?", | |
| 33 | - help="Message to be processed by the model.", | |
| 34 | - ) | |
| 35 | - parser.add_argument( | |
| 36 | - "--max-tokens", | |
| 37 | - type=int, | |
| 38 | - default=100, | |
| 39 | - help="Maximum number of tokens to generate.", | |
| 40 | - ) | |
| 41 | - parser.add_argument( | |
| 42 | - "--temp", type=float, default=0.3, help="Temperature for sampling." | |
| 43 | - ) | |
| 44 | - return parser.parse_args() | |
| 45 | - | |
| 46 | - | |
| 47 | -def load_image(image_source): | |
| 48 | - """ | |
| 49 | - Helper function to load an image from either a URL or file. | |
| 50 | - """ | |
| 51 | - if image_source.startswith(("http://", "https://")): | |
| 52 | - try: | |
| 53 | - response = requests.get(image_source, stream=True) | |
| 54 | - response.raise_for_status() | |
| 55 | - return Image.open(response.raw) | |
| 56 | - except Exception as e: | |
| 57 | - raise ValueError( | |
| 58 | - f"Failed to load image from URL: {image_source} with error {e}" | |
| 59 | - ) | |
| 60 | - elif Path(image_source).is_file(): | |
| 61 | - try: | |
| 62 | - return Image.open(image_source) | |
| 63 | - except IOError as e: | |
| 64 | - raise ValueError(f"Failed to load image {image_source} with error: {e}") | |
| 65 | - else: | |
| 66 | - raise ValueError( | |
| 67 | - f"The image {image_source} must be a valid URL or existing file." | |
| 68 | - ) | |
| 69 | - | |
| 70 | - | |
| 71 | -def prepare_inputs(image_processor, processor, image, prompt): | |
| 72 | - if isinstance(image, str): | |
| 73 | - image = load_image(image) | |
| 74 | - | |
| 75 | - if MODEL_TYPE == "nanoLlava": | |
| 76 | - text_chunks = [processor(chunk).input_ids for chunk in prompt.split("<image>")] | |
| 77 | - input_ids = mx.array([text_chunks[0] + [-200] + text_chunks[1]]) | |
| 78 | - pixel_values = image_processor.preprocess([image])[0] | |
| 79 | - pixel_values = mx.array(np.expand_dims(pixel_values, axis=0)) | |
| 80 | - else: | |
| 81 | - inputs = processor(prompt, image, return_tensors="np") | |
| 82 | - pixel_values = mx.array(inputs["pixel_values"]) | |
| 83 | - input_ids = mx.array(inputs["input_ids"]) | |
| 84 | - | |
| 85 | - return input_ids, pixel_values | |
| 86 | - | |
| 87 | - | |
| 88 | -def load_model(model_path): | |
| 89 | - global MODEL_TYPE | |
| 90 | - processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True) | |
| 91 | - config = AutoConfig.from_pretrained(model_path, trust_remote_code=True) | |
| 92 | - model_class, MODEL_TYPE, image_processor = get_model_class(config.to_dict()) | |
| 93 | - model = model_class.Model.from_pretrained(model_path) | |
| 94 | - return processor, model, image_processor | |
| 95 | - | |
| 96 | - | |
| 97 | -def sample(logits, temperature=0.0): | |
| 98 | - if temperature == 0: | |
| 99 | - return mx.argmax(logits, axis=-1) | |
| 100 | - else: | |
| 101 | - return mx.random.categorical(logits * (1 / temperature)) | |
| 102 | - | |
| 103 | - | |
| 104 | -def generate_text(input_ids, pixel_values, model, processor, max_tokens, temperature): | |
| 105 | - | |
| 106 | - logits, cache = model(input_ids, pixel_values) | |
| 107 | - logits = logits[:, -1, :] | |
| 108 | - y = sample(logits, temperature=temperature) | |
| 109 | - tokens = [y.item()] | |
| 110 | - | |
| 111 | - for n in range(max_tokens - 1): | |
| 112 | - logits, cache = model.language_model(y[None], cache=cache) | |
| 113 | - logits = logits[:, -1, :] | |
| 114 | - y = sample(logits, temperature) | |
| 115 | - token = y.item() | |
| 116 | - if token == processor.eos_token_id: | |
| 117 | - break | |
| 118 | - tokens.append(token) | |
| 119 | - | |
| 120 | - return processor.decode(tokens) | |
| 121 | - | |
| 122 | - | |
| 123 | -def main(): | |
| 124 | - args = parse_arguments() | |
| 125 | - processor, model, image_processor = load_model(args.model) | |
| 126 | - | |
| 127 | - prompt = codecs.decode(args.prompt, "unicode_escape") | |
| 128 | - | |
| 129 | - if "chat_template" in processor.__dict__.keys(): | |
| 130 | - prompt = processor.apply_chat_template( | |
| 131 | - [{"role": "user", "content": f"{prompt}"}], | |
| 132 | - tokenize=False, | |
| 133 | - add_generation_prompt=True, | |
| 134 | - ) | |
| 135 | - elif "tokenizer" in processor.__dict__.keys(): | |
| 136 | - prompt = processor.tokenizer.apply_chat_template( | |
| 137 | - [{"role": "user", "content": f"{prompt}"}], | |
| 138 | - tokenize=False, | |
| 139 | - add_generation_prompt=True, | |
| 140 | - ) | |
| 141 | - else: | |
| 142 | - ValueError("Error: processor does not have 'chat_template' or 'tokenizer' attribute.") | |
| 143 | - | |
| 144 | - input_ids, pixel_values = prepare_inputs(image_processor, processor, args.image, prompt) | |
| 145 | - | |
| 146 | - generated_text = generate_text( | |
| 147 | - input_ids, pixel_values, model, processor, args.max_tokens, args.temp | |
| 148 | - ) | |
| 149 | - print(generated_text) | |
| 150 | - | |
| 151 | - | |
| 152 | -if __name__ == "__main__": | |
| 153 | - main() |
deleted build/lib/mlx_vlm/models/__init__.py +0 −0
deleted build/lib/mlx_vlm/sample_utils.py +0 −39
| @@ -1,39 +0,0 @@ | ||
| 1 | -import mlx.core as mx | |
| 2 | - | |
| 3 | - | |
| 4 | -def top_p_sampling(logits: mx.array, top_p: float, temperature: float) -> mx.array: | |
| 5 | - """ | |
| 6 | - Apply top-p (nucleus) sampling to logits. | |
| 7 | - | |
| 8 | - Args: | |
| 9 | - logits: The logits from the model's output. | |
| 10 | - top_p: The cumulative probability threshold for top-p filtering. | |
| 11 | - temperature: Temperature parameter for softmax distribution reshaping. | |
| 12 | - Returns: | |
| 13 | - token selected based on the top-p criterion. | |
| 14 | - """ | |
| 15 | - if ( | |
| 16 | - logits.dtype == mx.bfloat16 | |
| 17 | - ): # workaround for unable to load kernel contiguous_scan_inclusive_sum_bfloat16_bfloat16 | |
| 18 | - logits = logits.astype(mx.float32) | |
| 19 | - | |
| 20 | - # referenced implementation from https://github.com/huggingface/transformers/blob/main/src/transformers/generation/logits_process.py#L449-L460 | |
| 21 | - probs = mx.softmax(logits / temperature, axis=-1) | |
| 22 | - | |
| 23 | - # sort probs in ascending order | |
| 24 | - sorted_indices = mx.argsort(probs, axis=-1) | |
| 25 | - sorted_probs = probs[..., sorted_indices.squeeze(0)] | |
| 26 | - | |
| 27 | - cumulative_probs = mx.cumsum(sorted_probs, axis=-1) | |
| 28 | - | |
| 29 | - # select tokens with cumulative probs below threshold | |
| 30 | - top_probs = mx.where( | |
| 31 | - cumulative_probs > 1 - top_p, | |
| 32 | - sorted_probs, | |
| 33 | - mx.zeros_like(sorted_probs), | |
| 34 | - ) | |
| 35 | - | |
| 36 | - sorted_token = mx.random.categorical(mx.log(top_probs)) | |
| 37 | - token = sorted_indices.squeeze(0)[sorted_token] | |
| 38 | - | |
| 39 | - return token |
deleted build/lib/mlx_vlm/utils.py +0 −632
| @@ -1,632 +0,0 @@ | ||
| 1 | - | |
| 2 | -import copy | |
| 3 | -import re | |
| 4 | -import glob | |
| 5 | -import importlib | |
| 6 | -import json | |
| 7 | -import logging | |
| 8 | -import shutil | |
| 9 | -import time | |
| 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 | -from huggingface_hub import snapshot_download | |
| 17 | -from mlx.utils import tree_flatten, tree_unflatten | |
| 18 | -from transformers import AutoConfig, AutoProcessor, PreTrainedTokenizer | |
| 19 | - | |
| 20 | -from .sample_utils import top_p_sampling | |
| 21 | - | |
| 22 | -# Constants | |
| 23 | -MODEL_REMAPPING = { | |
| 24 | - "llava-qwen2": "nanoLlava", | |
| 25 | -} | |
| 26 | - | |
| 27 | -MAX_FILE_SIZE_GB = 5 | |
| 28 | - | |
| 29 | -linear_class_predicate = ( | |
| 30 | - lambda m: isinstance(m, nn.Linear) | |
| 31 | - and m.weight.shape[0] | |
| 32 | - != 8 # avoid quantizing gate layers, otherwise we have to re-quant and upload all the mixtral models | |
| 33 | -) | |
| 34 | - | |
| 35 | -def get_model_class(config: dict): | |
| 36 | - """ | |
| 37 | - Retrieve the model clas based on the configuration. | |
| 38 | - | |
| 39 | - Args: | |
| 40 | - config (dict): The model configuration. | |
| 41 | - | |
| 42 | - Returns: | |
| 43 | - A tuple containing the Model class and the ModelArgs class. | |
| 44 | - """ | |
| 45 | - model_type = config["model_type"] | |
| 46 | - model_type = MODEL_REMAPPING.get(model_type, model_type) | |
| 47 | - try: | |
| 48 | - arch = importlib.import_module(f"mlx_vlm.models.{model_type}") | |
| 49 | - if model_type == "nanoLlava": | |
| 50 | - image_processor = arch.SigLipImageProcessor() | |
| 51 | - else: | |
| 52 | - image_processor = "" | |
| 53 | - except ImportError: | |
| 54 | - msg = f"Model type {model_type} not supported." | |
| 55 | - logging.error(msg) | |
| 56 | - raise ValueError(msg) | |
| 57 | - | |
| 58 | - | |
| 59 | - return arch, model_type, image_processor | |
| 60 | - | |
| 61 | -def load(model_path: Path, lazy: bool = False) -> nn.Module: | |
| 62 | - """ | |
| 63 | - Load and initialize the model and processor from a given path. | |
| 64 | - | |
| 65 | - Args: | |
| 66 | - model_path (Path): The path to load the model from. | |
| 67 | - lazy (bool): If False eval the model parameters to make sure they are | |
| 68 | - loaded in memory before returning, otherwise they will be loaded | |
| 69 | - when needed. Default: ``False`` | |
| 70 | - | |
| 71 | - Returns: | |
| 72 | - nn.Module: The loaded and initialized model. | |
| 73 | - | |
| 74 | - Raises: | |
| 75 | - FileNotFoundError: If the weight files (.safetensors) are not found. | |
| 76 | - ValueError: If the model class or args class are not found or cannot be instantiated. | |
| 77 | - """ | |
| 78 | - try: | |
| 79 | - with open(model_path / "config.json", "r") as f: | |
| 80 | - config = json.load(f) | |
| 81 | - quantization = config.get("quantization", None) | |
| 82 | - except FileNotFoundError: | |
| 83 | - logging.error(f"Config file not found in {model_path}") | |
| 84 | - raise | |
| 85 | - | |
| 86 | - weight_files = glob.glob(str(model_path / "*.safetensors")) | |
| 87 | - if not weight_files: | |
| 88 | - logging.error(f"No safetensors found in {model_path}") | |
| 89 | - raise FileNotFoundError(f"No safetensors found in {model_path}") | |
| 90 | - | |
| 91 | - weights = {} | |
| 92 | - for wf in weight_files: | |
| 93 | - weights.update(mx.load(wf)) | |
| 94 | - | |
| 95 | - | |
| 96 | - model_class, model_type, image_processor = get_model_class(config=config) | |
| 97 | - | |
| 98 | - if model_type == "nanoLlava": | |
| 99 | - vision_config = AutoConfig.from_pretrained(config["mm_vision_tower"]) | |
| 100 | - text_config = AutoConfig.from_pretrained(config["language_model"]) | |
| 101 | - vision_config = vision_config.to_dict() | |
| 102 | - text_config = text_config.to_dict() | |
| 103 | - config["vision_config"] = vision_config["vision_config"] | |
| 104 | - config["text_config"] = text_config | |
| 105 | - | |
| 106 | - processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True) | |
| 107 | - | |
| 108 | - model_config = model_class.ModelConfig.from_dict(config) | |
| 109 | - model_config.vision_config = model_class.VisionConfig.from_dict(config["vision_config"]) | |
| 110 | - model_config.text_config = model_class.TextConfig.from_dict(config["text_config"]) | |
| 111 | - model = model_class.Model(model_config) | |
| 112 | - | |
| 113 | - if hasattr(model, "sanitize"): | |
| 114 | - weights = model.sanitize(weights) | |
| 115 | - | |
| 116 | - if model_type == "nanoLlava": | |
| 117 | - weights = { | |
| 118 | - f"{k.split('.', 1)[1]}" if re.match(r'^model\.vision_tower', k) else | |
| 119 | - f"mm_projector.linear_1.{k.split('.')[-1]}" if re.match(r'^model\.mm_projector\.0', k) else | |
| 120 | - f"mm_projector.linear_2.{k.split('.')[-1]}" if re.match(r'^model\.mm_projector\.2', k) else | |
| 121 | - f"language_model.model.{k}" if re.match(r'^lm_head', k) else | |
| 122 | - f"language_model.{k}" if re.match(r'^model\.(embed_tokens|norm|layers)', k) else k: v | |
| 123 | - for k, v in weights.items() | |
| 124 | - } | |
| 125 | - | |
| 126 | - weights = { | |
| 127 | - 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 | |
| 128 | - 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 | |
| 129 | - for k, v in weights.items() | |
| 130 | - } | |
| 131 | - | |
| 132 | - if quantization is not None: | |
| 133 | - # for legacy models that don't have lm_head quant due to non-32 dims | |
| 134 | - if "lm_head.scales" not in weights.keys(): | |
| 135 | - vocab_size = config["vocab_size"] | |
| 136 | - extended_linear_class_predicate = ( | |
| 137 | - lambda layer: linear_class_predicate(layer) | |
| 138 | - and layer.weight.shape[0] != vocab_size | |
| 139 | - ) | |
| 140 | - nn.QuantizedLinear.quantize_module( | |
| 141 | - model, | |
| 142 | - **quantization, | |
| 143 | - linear_class_predicate=extended_linear_class_predicate, | |
| 144 | - ) | |
| 145 | - # for models that have lm_head quant | |
| 146 | - else: | |
| 147 | - nn.QuantizedLinear.quantize_module( | |
| 148 | - model, | |
| 149 | - **quantization, | |
| 150 | - linear_class_predicate=linear_class_predicate, | |
| 151 | - ) | |
| 152 | - | |
| 153 | - weights = model_class.VisionModel(model_config.vision_config).sanitize(weights=weights) | |
| 154 | - weights = model_class.LanguageModel(model_config.text_config).sanitize(weights=weights) | |
| 155 | - | |
| 156 | - model.load_weights(list(weights.items())) | |
| 157 | - | |
| 158 | - if not lazy: | |
| 159 | - mx.eval(model.parameters()) | |
| 160 | - | |
| 161 | - model.eval() | |
| 162 | - return model, config, model_type, processor, image_processor | |
| 163 | - | |
| 164 | -def fetch_from_hub( | |
| 165 | - model_path: Path, lazy: bool = False | |
| 166 | -) -> Tuple[nn.Module, dict, PreTrainedTokenizer]: | |
| 167 | - model, config, _, processor, _ = load(model_path, lazy) | |
| 168 | - | |
| 169 | - return model, config, processor | |
| 170 | - | |
| 171 | - | |
| 172 | -def make_shards(weights: dict, max_file_size_gb: int = MAX_FILE_SIZE_GB) -> list: | |
| 173 | - """ | |
| 174 | - Splits the weights into smaller shards. | |
| 175 | - | |
| 176 | - Args: | |
| 177 | - weights (dict): Model weights. | |
| 178 | - max_file_size_gb (int): Maximum size of each shard in gigabytes. | |
| 179 | - | |
| 180 | - Returns: | |
| 181 | - list: List of weight shards. | |
| 182 | - """ | |
| 183 | - max_file_size_bytes = max_file_size_gb << 30 | |
| 184 | - shards = [] | |
| 185 | - shard, shard_size = {}, 0 | |
| 186 | - for k, v in weights.items(): | |
| 187 | - if shard_size + v.nbytes > max_file_size_bytes: | |
| 188 | - shards.append(shard) | |
| 189 | - shard, shard_size = {}, 0 | |
| 190 | - shard[k] = v | |
| 191 | - shard_size += v.nbytes | |
| 192 | - shards.append(shard) | |
| 193 | - return shards | |
| 194 | - | |
| 195 | - | |
| 196 | -def upload_to_hub(path: str, upload_repo: str, hf_path: str): | |
| 197 | - """ | |
| 198 | - Uploads the model to Hugging Face hub. | |
| 199 | - | |
| 200 | - Args: | |
| 201 | - path (str): Local path to the model. | |
| 202 | - upload_repo (str): Name of the HF repo to upload to. | |
| 203 | - hf_path (str): Path to the original Hugging Face model. | |
| 204 | - """ | |
| 205 | - import os | |
| 206 | - | |
| 207 | - from huggingface_hub import HfApi, ModelCard, logging | |
| 208 | - | |
| 209 | - card = ModelCard.load(hf_path) | |
| 210 | - card.data.tags = ["mlx"] if card.data.tags is None else card.data.tags + ["mlx"] | |
| 211 | - card.text = dedent( | |
| 212 | - f""" | |
| 213 | - # {upload_repo} | |
| 214 | - This model was converted to MLX format from [`{hf_path}`]() using mlx-vllm version **0.0.0**. | |
| 215 | - Refer to the [original model card](https://huggingface.co/{hf_path}) for more details on the model. | |
| 216 | - ## Use with mlx | |
| 217 | - | |
| 218 | - ```bash | |
| 219 | - git clone https://github.com/ml-explore/mlx-examples.git | |
| 220 | - ``` | |
| 221 | - | |
| 222 | - ```bash | |
| 223 | - cd mlx-lm/vllms | |
| 224 | - python -m generate --model {path} --max-tokens 10 --temp 0.0 | |
| 225 | - ``` | |
| 226 | - """ | |
| 227 | - ) | |
| 228 | - card.save(os.path.join(path, "README.md")) | |
| 229 | - | |
| 230 | - logging.set_verbosity_info() | |
| 231 | - | |
| 232 | - api = HfApi() | |
| 233 | - api.create_repo(repo_id=upload_repo, exist_ok=True) | |
| 234 | - api.upload_folder( | |
| 235 | - folder_path=path, | |
| 236 | - repo_id=upload_repo, | |
| 237 | - repo_type="model", | |
| 238 | - ) | |
| 239 | - print(f"Upload successful, go to https://huggingface.co/{upload_repo} for details.") | |
| 240 | - | |
| 241 | -def get_model_path(path_or_hf_repo: str, revision: Optional[str] = None) -> Path: | |
| 242 | - """ | |
| 243 | - Ensures the model is available locally. If the path does not exist locally, | |
| 244 | - it is downloaded from the Hugging Face Hub. | |
| 245 | - | |
| 246 | - Args: | |
| 247 | - path_or_hf_repo (str): The local path or Hugging Face repository ID of the model. | |
| 248 | - revision (str, optional): A revision id which can be a branch name, a tag, or a commit hash. | |
| 249 | - | |
| 250 | - Returns: | |
| 251 | - Path: The path to the model. | |
| 252 | - """ | |
| 253 | - model_path = Path(path_or_hf_repo) | |
| 254 | - if not model_path.exists(): | |
| 255 | - model_path = Path( | |
| 256 | - snapshot_download( | |
| 257 | - repo_id=path_or_hf_repo, | |
| 258 | - revision=revision, | |
| 259 | - allow_patterns=[ | |
| 260 | - "*.json", | |
| 261 | - "*.safetensors", | |
| 262 | - "*.py", | |
| 263 | - "tokenizer.model", | |
| 264 | - "*.tiktoken", | |
| 265 | - "*.txt", | |
| 266 | - ], | |
| 267 | - ) | |
| 268 | - ) | |
| 269 | - return model_path | |
| 270 | - | |
| 271 | - | |
| 272 | -def apply_repetition_penalty(logits: mx.array, generated_tokens: Any, penalty: float): | |
| 273 | - """ | |
| 274 | - Apply repetition penalty to specific logits based on the given context. | |
| 275 | - | |
| 276 | - Paper: https://arxiv.org/abs/1909.05858 | |
| 277 | - | |
| 278 | - Args: | |
| 279 | - logits (mx.array): The logits produced by the language model. | |
| 280 | - generated_tokens (any): A list of N previous tokens. | |
| 281 | - penalty (float): The repetition penalty factor to be applied. | |
| 282 | - | |
| 283 | - Returns: | |
| 284 | - logits (mx.array): Logits with repetition penalty applied to generated tokens. | |
| 285 | - """ | |
| 286 | - if len(generated_tokens) > 0: | |
| 287 | - indices = mx.array([token for token in generated_tokens]) | |
| 288 | - selected_logits = logits[:, indices] | |
| 289 | - selected_logits = mx.where( | |
| 290 | - selected_logits < 0, selected_logits * penalty, selected_logits / penalty | |
| 291 | - ) | |
| 292 | - logits[:, indices] = selected_logits | |
| 293 | - return logits | |
| 294 | - | |
| 295 | -def save_weights( | |
| 296 | - save_path: Union[str, Path], | |
| 297 | - weights: Dict[str, Any], | |
| 298 | - *, | |
| 299 | - donate_weights: bool = False, | |
| 300 | -) -> None: | |
| 301 | - """Save model weights into specified directory.""" | |
| 302 | - if isinstance(save_path, str): | |
| 303 | - save_path = Path(save_path) | |
| 304 | - save_path.mkdir(parents=True, exist_ok=True) | |
| 305 | - | |
| 306 | - shards = make_shards(weights) | |
| 307 | - shards_count = len(shards) | |
| 308 | - shard_file_format = ( | |
| 309 | - "model-{:05d}-of-{:05d}.safetensors" | |
| 310 | - if shards_count > 1 | |
| 311 | - else "model.safetensors" | |
| 312 | - ) | |
| 313 | - | |
| 314 | - total_size = sum(v.nbytes for v in weights.values()) | |
| 315 | - index_data = {"metadata": {"total_size": total_size}, "weight_map": {}} | |
| 316 | - | |
| 317 | - # Write the weights and make sure no references are kept other than the | |
| 318 | - # necessary ones | |
| 319 | - if donate_weights: | |
| 320 | - weights.clear() | |
| 321 | - del weights | |
| 322 | - | |
| 323 | - for i in range(len(shards)): | |
| 324 | - shard = shards[i] | |
| 325 | - shards[i] = None | |
| 326 | - shard_name = shard_file_format.format(i + 1, shards_count) | |
| 327 | - shard_path = save_path / shard_name | |
| 328 | - | |
| 329 | - mx.save_safetensors(str(shard_path), shard, metadata={"format": "mlx"}) | |
| 330 | - | |
| 331 | - for weight_name in shard.keys(): | |
| 332 | - index_data["weight_map"][weight_name] = shard_name | |
| 333 | - del shard | |
| 334 | - | |
| 335 | - index_data["weight_map"] = { | |
| 336 | - k: index_data["weight_map"][k] for k in sorted(index_data["weight_map"]) | |
| 337 | - } | |
| 338 | - | |
| 339 | - with open(save_path / "model.safetensors.index.json", "w") as f: | |
| 340 | - json.dump( | |
| 341 | - index_data, | |
| 342 | - f, | |
| 343 | - indent=4, | |
| 344 | - ) | |
| 345 | - | |
| 346 | - | |
| 347 | -def quantize_model( | |
| 348 | - model: nn.Module, config: dict, q_group_size: int, q_bits: int | |
| 349 | -) -> Tuple: | |
| 350 | - """ | |
| 351 | - Applies quantization to the model weights. | |
| 352 | - | |
| 353 | - Args: | |
| 354 | - model (nn.Module): The model to be quantized. | |
| 355 | - config (dict): Model configuration. | |
| 356 | - q_group_size (int): Group size for quantization. | |
| 357 | - q_bits (int): Bits per weight for quantization. | |
| 358 | - | |
| 359 | - Returns: | |
| 360 | - Tuple: Tuple containing quantized weights and config. | |
| 361 | - """ | |
| 362 | - quantized_config = copy.deepcopy(config) | |
| 363 | - | |
| 364 | - nn.QuantizedLinear.quantize_module( | |
| 365 | - model, q_group_size, q_bits, linear_class_predicate=linear_class_predicate | |
| 366 | - ) | |
| 367 | - quantized_config["quantization"] = {"group_size": q_group_size, "bits": q_bits} | |
| 368 | - quantized_weights = dict(tree_flatten(model.parameters())) | |
| 369 | - | |
| 370 | - return quantized_weights, quantized_config | |
| 371 | - | |
| 372 | - | |
| 373 | -def save_config( | |
| 374 | - config: dict, | |
| 375 | - config_path: Union[str, Path], | |
| 376 | -) -> None: | |
| 377 | - """Save the model configuration to the ``config_path``. | |
| 378 | - | |
| 379 | - The final configuration will be sorted before saving for better readability. | |
| 380 | - | |
| 381 | - Args: | |
| 382 | - config (dict): The model configuration. | |
| 383 | - config_path (Union[str, Path]): Model configuration file path. | |
| 384 | - """ | |
| 385 | - # Clean unused keys | |
| 386 | - config.pop("_name_or_path", None) | |
| 387 | - | |
| 388 | - # sort the config for better readability | |
| 389 | - config = dict(sorted(config.items())) | |
| 390 | - | |
| 391 | - # write the updated config to the config_path (if provided) | |
| 392 | - with open(config_path, "w") as fid: | |
| 393 | - json.dump(config, fid, indent=4) | |
| 394 | - | |
| 395 | -def dequantize_model(model: nn.Module) -> nn.Module: | |
| 396 | - """ | |
| 397 | - Dequantize the quantized linear layers in the model. | |
| 398 | - | |
| 399 | - Args: | |
| 400 | - model (nn.Module): The model with quantized linear layers. | |
| 401 | - | |
| 402 | - Returns: | |
| 403 | - nn.Module: The model with dequantized layers. | |
| 404 | - """ | |
| 405 | - de_quantize_layers = [] | |
| 406 | - for name, module in model.named_modules(): | |
| 407 | - if isinstance(module, nn.QuantizedLinear): | |
| 408 | - bias = "bias" in module | |
| 409 | - weight = module.weight | |
| 410 | - weight = mx.dequantize( | |
| 411 | - weight, | |
| 412 | - module.scales, | |
| 413 | - module.biases, | |
| 414 | - module.group_size, | |
| 415 | - module.bits, | |
| 416 | - ).astype(mx.float16) | |
| 417 | - output_dims, input_dims = weight.shape | |
| 418 | - linear = nn.Linear(input_dims, output_dims, bias=bias) | |
| 419 | - linear.weight = weight | |
| 420 | - if bias: | |
| 421 | - linear.bias = module.bias | |
| 422 | - de_quantize_layers.append((name, linear)) | |
| 423 | - if len(de_quantize_layers) > 0: | |
| 424 | - model.update_modules(tree_unflatten(de_quantize_layers)) | |
| 425 | - return model | |
| 426 | - | |
| 427 | -def convert( | |
| 428 | - hf_path: str, | |
| 429 | - mlx_path: str = "mlx_model", | |
| 430 | - quantize: bool = False, | |
| 431 | - q_group_size: int = 64, | |
| 432 | - q_bits: int = 4, | |
| 433 | - dtype: str = "float16", | |
| 434 | - upload_repo: str = None, | |
| 435 | - revision: Optional[str] = None, | |
| 436 | - dequantize: bool = False, | |
| 437 | -): | |
| 438 | - print("[INFO] Loading") | |
| 439 | - model_path = get_model_path(hf_path, revision=revision) | |
| 440 | - model, config, tokenizer = fetch_from_hub(model_path, lazy=True) | |
| 441 | - | |
| 442 | - weights = dict(tree_flatten(model.parameters())) | |
| 443 | - dtype = mx.float16 if quantize else getattr(mx, dtype) | |
| 444 | - weights = {k: v.astype(dtype) for k, v in weights.items()} | |
| 445 | - | |
| 446 | - if quantize and dequantize: | |
| 447 | - raise ValueError("Choose either quantize or dequantize, not both.") | |
| 448 | - | |
| 449 | - if quantize: | |
| 450 | - print("[INFO] Quantizing") | |
| 451 | - model.load_weights(list(weights.items())) | |
| 452 | - weights, config = quantize_model(model, config, q_group_size, q_bits) | |
| 453 | - | |
| 454 | - if dequantize: | |
| 455 | - print("[INFO] Dequantizing") | |
| 456 | - model = dequantize_model(model) | |
| 457 | - weights = dict(tree_flatten(model.parameters())) | |
| 458 | - | |
| 459 | - if isinstance(mlx_path, str): | |
| 460 | - mlx_path = Path(mlx_path) | |
| 461 | - | |
| 462 | - del model | |
| 463 | - save_weights(mlx_path, weights, donate_weights=True) | |
| 464 | - | |
| 465 | - py_files = glob.glob(str(model_path / "*.py")) | |
| 466 | - for file in py_files: | |
| 467 | - shutil.copy(file, mlx_path) | |
| 468 | - | |
| 469 | - if "tokenizer" in tokenizer.__dict__.keys(): | |
| 470 | - tokenizer.tokenizer.save_pretrained(mlx_path) | |
| 471 | - else: | |
| 472 | - tokenizer.save_pretrained(mlx_path) | |
| 473 | - | |
| 474 | - | |
| 475 | - save_config(config, config_path=mlx_path / "config.json") | |
| 476 | - | |
| 477 | - if upload_repo is not None: | |
| 478 | - upload_to_hub(mlx_path, upload_repo, hf_path) | |
| 479 | - | |
| 480 | -def generate_step( | |
| 481 | - prompt: mx.array, | |
| 482 | - model: nn.Module, | |
| 483 | - temp: float = 0.0, | |
| 484 | - repetition_penalty: Optional[float] = None, | |
| 485 | - repetition_context_size: Optional[int] = 20, | |
| 486 | - top_p: float = 1.0, | |
| 487 | -) -> Generator[Tuple[mx.array, mx.array], None, None]: | |
| 488 | - """ | |
| 489 | - A generator producing text based on the given prompt from the model. | |
| 490 | - | |
| 491 | - Args: | |
| 492 | - prompt (mx.array): The input prompt. | |
| 493 | - model (nn.Module): The model to use for generation. | |
| 494 | - temp (float): The temperature for sampling, if 0 the argmax is used. | |
| 495 | - repetition_penalty (float, optional): The penalty factor for repeating tokens. | |
| 496 | - repetition_context_size (int, optional): The number of tokens to consider for repetition penalty (default 20). | |
| 497 | - top_p (float, optional): Nulceus sampling, higher means model considers more less likely words | |
| 498 | - | |
| 499 | - Yields: | |
| 500 | - Generator[Tuple[mx.array, mx.array]]: A generator producing | |
| 501 | - one token and probability per call. | |
| 502 | - """ | |
| 503 | - | |
| 504 | - def sample(logits: mx.array) -> Tuple[mx.array, float]: | |
| 505 | - softmax_logits = mx.softmax(logits) | |
| 506 | - | |
| 507 | - if temp == 0: | |
| 508 | - token = mx.argmax(logits, axis=-1) | |
| 509 | - else: | |
| 510 | - if top_p > 0 and top_p < 1.0: | |
| 511 | - token = top_p_sampling(logits, top_p, temp) | |
| 512 | - else: | |
| 513 | - token = mx.random.categorical(logits * (1 / temp)) | |
| 514 | - | |
| 515 | - prob = softmax_logits[0, token] | |
| 516 | - return token, prob | |
| 517 | - | |
| 518 | - if repetition_penalty and ( | |
| 519 | - repetition_penalty < 0 or not isinstance(repetition_penalty, float) | |
| 520 | - ): | |
| 521 | - raise ValueError( | |
| 522 | - f"repetition_penalty must be a non-negative float, got {repetition_penalty}" | |
| 523 | - ) | |
| 524 | - | |
| 525 | - y = prompt | |
| 526 | - cache = None | |
| 527 | - | |
| 528 | - repetition_context = prompt.tolist() | |
| 529 | - | |
| 530 | - if repetition_context_size: | |
| 531 | - repetition_context = repetition_context[-repetition_context_size:] | |
| 532 | - | |
| 533 | - while True: | |
| 534 | - logits, cache = model(y[None], cache=cache) | |
| 535 | - logits = logits[:, -1, :] | |
| 536 | - | |
| 537 | - if repetition_penalty: | |
| 538 | - logits = apply_repetition_penalty( | |
| 539 | - logits, repetition_context, repetition_penalty | |
| 540 | - ) | |
| 541 | - y, prob = sample(logits) | |
| 542 | - repetition_context.append(y.item()) | |
| 543 | - else: | |
| 544 | - y, prob = sample(logits) | |
| 545 | - | |
| 546 | - if repetition_context_size: | |
| 547 | - if len(repetition_context) > repetition_context_size: | |
| 548 | - repetition_context = repetition_context[-repetition_context_size:] | |
| 549 | - yield y, prob | |
| 550 | - | |
| 551 | - | |
| 552 | -def generate( | |
| 553 | - model: nn.Module, | |
| 554 | - tokenizer: PreTrainedTokenizer, | |
| 555 | - prompt: str, | |
| 556 | - temp: float = 0.0, | |
| 557 | - max_tokens: int = 100, | |
| 558 | - verbose: bool = False, | |
| 559 | - formatter: Optional[Callable] = None, | |
| 560 | - repetition_penalty: Optional[float] = None, | |
| 561 | - repetition_context_size: Optional[int] = None, | |
| 562 | - top_p: float = 1.0, | |
| 563 | -) -> str: | |
| 564 | - """ | |
| 565 | - Generate text from the model. | |
| 566 | - | |
| 567 | - Args: | |
| 568 | - model (nn.Module): The language model. | |
| 569 | - tokenizer (PreTrainedTokenizer): The tokenizer. | |
| 570 | - prompt (str): The string prompt. | |
| 571 | - temp (float): The temperature for sampling (default 0). | |
| 572 | - max_tokens (int): The maximum number of tokens (default 100). | |
| 573 | - verbose (bool): If ``True``, print tokens and timing information | |
| 574 | - (default ``False``). | |
| 575 | - formatter (Optional[Callable]): A function which takes a token and a | |
| 576 | - probability and displays it. | |
| 577 | - repetition_penalty (float, optional): The penalty factor for repeating tokens. | |
| 578 | - repetition_context_size (int, optional): The number of tokens to consider for repetition penalty. | |
| 579 | - """ | |
| 580 | - if verbose: | |
| 581 | - print("=" * 10) | |
| 582 | - print("Prompt:", prompt) | |
| 583 | - | |
| 584 | - prompt_tokens = mx.array(tokenizer.encode(prompt)) | |
| 585 | - detokenizer = tokenizer.detokenizer | |
| 586 | - | |
| 587 | - tic = time.perf_counter() | |
| 588 | - detokenizer.reset() | |
| 589 | - | |
| 590 | - for (token, prob), n in zip( | |
| 591 | - generate_step( | |
| 592 | - prompt_tokens, | |
| 593 | - model, | |
| 594 | - temp, | |
| 595 | - repetition_penalty, | |
| 596 | - repetition_context_size, | |
| 597 | - top_p, | |
| 598 | - ), | |
| 599 | - range(max_tokens), | |
| 600 | - ): | |
| 601 | - token = token.item() | |
| 602 | - if n == 0: | |
| 603 | - prompt_time = time.perf_counter() - tic | |
| 604 | - tic = time.perf_counter() | |
| 605 | - if token == tokenizer.eos_token_id: | |
| 606 | - break | |
| 607 | - detokenizer.add_token(token) | |
| 608 | - | |
| 609 | - if verbose: | |
| 610 | - if formatter: | |
| 611 | - # We have to finalize so that the prob corresponds to the last segment | |
| 612 | - detokenizer.finalize() | |
| 613 | - formatter(detokenizer.last_segment, prob.item()) | |
| 614 | - else: | |
| 615 | - print(detokenizer.last_segment, end="", flush=True) | |
| 616 | - | |
| 617 | - token_count = n + 1 | |
| 618 | - detokenizer.finalize() | |
| 619 | - | |
| 620 | - if verbose: | |
| 621 | - print(detokenizer.last_segment, flush=True) | |
| 622 | - gen_time = time.perf_counter() - tic | |
| 623 | - print("=" * 10) | |
| 624 | - if token_count == 0: | |
| 625 | - print("No tokens generated for this prompt") | |
| 626 | - return | |
| 627 | - prompt_tps = prompt_tokens.size / prompt_time | |
| 628 | - gen_tps = (token_count - 1) / gen_time | |
| 629 | - print(f"Prompt: {prompt_tps:.3f} tokens-per-sec") | |
| 630 | - print(f"Generation: {gen_tps:.3f} tokens-per-sec") | |
| 631 | - | |
| 632 | - return detokenizer.text | |
| No newline at the end of the file |
deleted build/lib/mlx_vlm/version.py +0 −3
| @@ -1,3 +0,0 @@ | ||
| 1 | - | |
| 2 | - | |
| 3 | -__version__ = "0.0.1" |
deleted mlx_vlm/.gitignore +0 −2
| @@ -1,2 +0,0 @@ | ||
| 1 | -**.ipynb | |
| 2 | -**.pyc | |
| No newline at the end of the file |
added mlx_vlm/convert.py +62 −0
| @@ -0,0 +1,62 @@ | ||
| 1 | +# Copyright © 2023-2024 Apple Inc. | |
| 2 | + | |
| 3 | +import argparse | |
| 4 | + | |
| 5 | +from .utils import convert | |
| 6 | + | |
| 7 | + | |
| 8 | +def configure_parser() -> argparse.ArgumentParser: | |
| 9 | + """ | |
| 10 | + Configures and returns the argument parser for the script. | |
| 11 | + | |
| 12 | + Returns: | |
| 13 | + argparse.ArgumentParser: Configured argument parser. | |
| 14 | + """ | |
| 15 | + parser = argparse.ArgumentParser( | |
| 16 | + description="Convert Hugging Face model to MLX format" | |
| 17 | + ) | |
| 18 | + | |
| 19 | + parser.add_argument("--hf-path", type=str, help="Path to the Hugging Face model.") | |
| 20 | + parser.add_argument( | |
| 21 | + "--mlx-path", type=str, default="mlx_model", help="Path to save the MLX model." | |
| 22 | + ) | |
| 23 | + parser.add_argument( | |
| 24 | + "-q", "--quantize", help="Generate a quantized model.", action="store_true" | |
| 25 | + ) | |
| 26 | + parser.add_argument( | |
| 27 | + "--q-group-size", help="Group size for quantization.", type=int, default=64 | |
| 28 | + ) | |
| 29 | + parser.add_argument( | |
| 30 | + "--q-bits", help="Bits per weight for quantization.", type=int, default=4 | |
| 31 | + ) | |
| 32 | + parser.add_argument( | |
| 33 | + "--dtype", | |
| 34 | + help="Type to save the parameters, ignored if -q is given.", | |
| 35 | + type=str, | |
| 36 | + choices=["float16", "bfloat16", "float32"], | |
| 37 | + default="float16", | |
| 38 | + ) | |
| 39 | + parser.add_argument( | |
| 40 | + "--upload-repo", | |
| 41 | + help="The Hugging Face repo to upload the model to.", | |
| 42 | + type=str, | |
| 43 | + default=None, | |
| 44 | + ) | |
| 45 | + parser.add_argument( | |
| 46 | + "-d", | |
| 47 | + "--dequantize", | |
| 48 | + help="Dequantize a quantized model.", | |
| 49 | + action="store_true", | |
| 50 | + default=False, | |
| 51 | + ) | |
| 52 | + return parser | |
| 53 | + | |
| 54 | + | |
| 55 | +def main(): | |
| 56 | + parser = configure_parser() | |
| 57 | + args = parser.parse_args() | |
| 58 | + convert(**vars(args)) | |
| 59 | + | |
| 60 | + | |
| 61 | +if __name__ == "__main__": | |
| 62 | + main() | |
| No newline at the end of the file |
modified mlx_vlm/generate.py +18 −84
| @@ -1,13 +1,9 @@ | ||
| 1 | 1 | import argparse |
| 2 | 2 | import codecs |
| 3 | -from pathlib import Path | |
| 4 | 3 | |
| 5 | 4 | import mlx.core as mx |
| 6 | -import numpy as np | |
| 7 | -import requests | |
| 8 | -from .utils import load | |
| 9 | -from PIL import Image | |
| 10 | -from transformers import AutoTokenizer, AutoConfig | |
| 5 | +from .utils import load, load_config, load_image_processor, generate, get_model_path | |
| 6 | + | |
| 11 | 7 | |
| 12 | 8 | MODEL_TYPE = "" |
| 13 | 9 | def parse_arguments(): |
| @@ -44,52 +40,12 @@ | ||
| 44 | 40 | return parser.parse_args() |
| 45 | 41 | |
| 46 | 42 | |
| 47 | -def load_image(image_source): | |
| 48 | - """ | |
| 49 | - Helper function to load an image from either a URL or file. | |
| 50 | - """ | |
| 51 | - if image_source.startswith(("http://", "https://")): | |
| 52 | - try: | |
| 53 | - response = requests.get(image_source, stream=True) | |
| 54 | - response.raise_for_status() | |
| 55 | - return Image.open(response.raw) | |
| 56 | - except Exception as e: | |
| 57 | - raise ValueError( | |
| 58 | - f"Failed to load image from URL: {image_source} with error {e}" | |
| 59 | - ) | |
| 60 | - elif Path(image_source).is_file(): | |
| 61 | - try: | |
| 62 | - return Image.open(image_source) | |
| 63 | - except IOError as e: | |
| 64 | - raise ValueError(f"Failed to load image {image_source} with error: {e}") | |
| 65 | - else: | |
| 66 | - raise ValueError( | |
| 67 | - f"The image {image_source} must be a valid URL or existing file." | |
| 68 | - ) | |
| 69 | - | |
| 70 | - | |
| 71 | -def prepare_inputs(image_processor, processor, image, prompt): | |
| 72 | - if isinstance(image, str): | |
| 73 | - image = load_image(image) | |
| 74 | - | |
| 75 | - if MODEL_TYPE == "nanoLlava": | |
| 76 | - text_chunks = [processor(chunk).input_ids for chunk in prompt.split("<image>")] | |
| 77 | - input_ids = mx.array([text_chunks[0] + [-200] + text_chunks[1]]) | |
| 78 | - pixel_values = image_processor.preprocess([image])[0] | |
| 79 | - pixel_values = mx.array(np.expand_dims(pixel_values, axis=0)) | |
| 80 | - else: | |
| 81 | - inputs = processor(prompt, image, return_tensors="np") | |
| 82 | - pixel_values = mx.array(inputs["pixel_values"]) | |
| 83 | - input_ids = mx.array(inputs["input_ids"]) | |
| 84 | - | |
| 85 | - return input_ids, pixel_values | |
| 86 | - | |
| 87 | - | |
| 88 | -def load_model(model_path): | |
| 89 | - global MODEL_TYPE | |
| 90 | - model, _, MODEL_TYPE, processor, image_processor = load(model_path) | |
| 91 | - | |
| 92 | - return processor, model, image_processor | |
| 43 | +def get_model_and_processors(model_path): | |
| 44 | + model_path = get_model_path(model_path) | |
| 45 | + model, processor = load(model_path, {"trust_remote_code": True}) | |
| 46 | + config = load_config(model_path) | |
| 47 | + image_processor = load_image_processor(config) | |
| 48 | + return model, processor, image_processor | |
| 93 | 49 | |
| 94 | 50 | |
| 95 | 51 | def sample(logits, temperature=0.0): |
| @@ -99,28 +55,10 @@ | ||
| 99 | 55 | return mx.random.categorical(logits * (1 / temperature)) |
| 100 | 56 | |
| 101 | 57 | |
| 102 | -def generate_text(input_ids, pixel_values, model, processor, max_tokens, temperature): | |
| 103 | - | |
| 104 | - logits, cache = model(input_ids, pixel_values) | |
| 105 | - logits = logits[:, -1, :] | |
| 106 | - y = sample(logits, temperature=temperature) | |
| 107 | - tokens = [y.item()] | |
| 108 | - | |
| 109 | - for n in range(max_tokens - 1): | |
| 110 | - logits, cache = model.language_model(y[None], cache=cache) | |
| 111 | - logits = logits[:, -1, :] | |
| 112 | - y = sample(logits, temperature) | |
| 113 | - token = y.item() | |
| 114 | - if token == processor.eos_token_id: | |
| 115 | - break | |
| 116 | - tokens.append(token) | |
| 117 | - | |
| 118 | - return processor.decode(tokens) | |
| 119 | - | |
| 120 | 58 | |
| 121 | 59 | def main(): |
| 122 | 60 | args = parse_arguments() |
| 123 | - processor, model, image_processor = load_model(args.model) | |
| 61 | + model, processor, image_processor = get_model_and_processors(args.model) | |
| 124 | 62 | |
| 125 | 63 | prompt = codecs.decode(args.prompt, "unicode_escape") |
| 126 | 64 | |
| @@ -139,20 +77,16 @@ | ||
| 139 | 77 | else: |
| 140 | 78 | ValueError("Error: processor does not have 'chat_template' or 'tokenizer' attribute.") |
| 141 | 79 | |
| 142 | - print("\nImage Path:\n") | |
| 143 | - print(args.image) | |
| 144 | - print("="*20+"\n") | |
| 145 | - | |
| 146 | - print("Prompt:\n") | |
| 147 | - print(prompt) | |
| 148 | - print("="*20+"\n") | |
| 149 | - input_ids, pixel_values = prepare_inputs(image_processor, processor, args.image, prompt) | |
| 150 | - | |
| 151 | - generated_text = generate_text( | |
| 152 | - input_ids, pixel_values, model, processor, args.max_tokens, args.temp | |
| 80 | + generate( | |
| 81 | + model, | |
| 82 | + processor, | |
| 83 | + args.image, | |
| 84 | + prompt, | |
| 85 | + image_processor, | |
| 86 | + args.temp, | |
| 87 | + args.max_tokens, | |
| 88 | + True | |
| 153 | 89 | ) |
| 154 | - print("Generated_text:\n") | |
| 155 | - print(generated_text+"\n") | |
| 156 | 90 | |
| 157 | 91 | |
| 158 | 92 | if __name__ == "__main__": |
added mlx_vlm/models/base.py +32 −0
| @@ -0,0 +1,32 @@ | ||
| 1 | + | |
| 2 | +from abc import ABC, abstractmethod | |
| 3 | +from typing import Dict | |
| 4 | + | |
| 5 | +from transformers.image_processing_utils import get_size_dict | |
| 6 | +from transformers.image_utils import (ChannelDimension, PILImageResampling ) | |
| 7 | + | |
| 8 | + | |
| 9 | +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") | |
| 20 | + | |
| 21 | + self.image_mean = image_mean | |
| 22 | + self.image_std = image_std | |
| 23 | + self.size = size | |
| 24 | + self.resample = resample | |
| 25 | + self.rescale_factor = rescale_factor | |
| 26 | + self.data_format = data_format | |
| 27 | + self.crop_size = crop_size | |
| 28 | + | |
| 29 | + @abstractmethod | |
| 30 | + def preprocess(self, images): | |
| 31 | + pass | |
| 32 | + |
modified mlx_vlm/models/nanoLlava/__init__.py +1 −2
| @@ -1,2 +1,1 @@ | ||
| 1 | - | |
| 2 | -from .nanoLlava import Model, SigLipImageProcessor, ModelConfig, TextConfig, VisionConfig, VisionModel, LanguageModel | |
| 1 | +from .nanoLlava import Model, ImageProcessor, ModelConfig, TextConfig, VisionConfig, VisionModel, LanguageModel |
modified mlx_vlm/models/nanoLlava/nanoLlava.py +13 −26
| @@ -14,15 +14,15 @@ | ||
| 14 | 14 | from transformers import AutoConfig |
| 15 | 15 | from .language import LanguageModel, TextConfig |
| 16 | 16 | from .vision import VisionConfig, VisionModel |
| 17 | +from ..base import BaseImageProcessor | |
| 17 | 18 | |
| 18 | 19 | |
| 19 | 20 | from typing import Optional, Dict |
| 20 | 21 | from dataclasses import dataclass |
| 21 | 22 | from functools import partial, reduce |
| 22 | 23 | from PIL import Image |
| 23 | -from transformers.image_processing_utils import get_size_dict | |
| 24 | 24 | from transformers.image_transforms import (convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format, ) |
| 25 | -from transformers.image_utils import (ChannelDimension, PILImageResampling, to_numpy_array, ) | |
| 25 | +from transformers.image_utils import ( to_numpy_array, ) | |
| 26 | 26 | |
| 27 | 27 | @dataclass |
| 28 | 28 | class ModelConfig: |
| @@ -51,26 +51,7 @@ | ||
| 51 | 51 | ) |
| 52 | 52 | |
| 53 | 53 | |
| 54 | -class SigLipImageProcessor: | |
| 55 | - def __init__(self, | |
| 56 | - image_mean=(0.5, 0.5, 0.5), | |
| 57 | - image_std=(0.5, 0.5, 0.5), | |
| 58 | - size=(384, 384), | |
| 59 | - crop_size: Dict[str, int] = None, | |
| 60 | - resample=PILImageResampling.BICUBIC, | |
| 61 | - rescale_factor=1 / 255, | |
| 62 | - data_format=ChannelDimension.FIRST): | |
| 63 | - crop_size = crop_size if crop_size is not None else {"height": 384, "width": 384} | |
| 64 | - crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size") | |
| 65 | - | |
| 66 | - self.image_mean = image_mean | |
| 67 | - self.image_std = image_std | |
| 68 | - self.size = size | |
| 69 | - self.resample = resample | |
| 70 | - self.rescale_factor = rescale_factor | |
| 71 | - self.data_format = data_format | |
| 72 | - self.crop_size = crop_size | |
| 73 | - | |
| 54 | +class ImageProcessor(BaseImageProcessor): | |
| 74 | 55 | def preprocess(self, images): |
| 75 | 56 | if isinstance(images, Image.Image): |
| 76 | 57 | images = [images] |
| @@ -233,6 +214,15 @@ | ||
| 233 | 214 | for wf in weight_files: |
| 234 | 215 | weights.update(mx.load(wf)) |
| 235 | 216 | |
| 217 | + weights = model.sanitize(weights=weights) | |
| 218 | + | |
| 219 | + weights = VisionModel(model_config.vision_config).sanitize(weights=weights) | |
| 220 | + weights = LanguageModel(model_config.text_config).sanitize(weights=weights) | |
| 221 | + model.load_weights(list(weights.items())) | |
| 222 | + return model | |
| 223 | + | |
| 224 | + | |
| 225 | + def sanitize(self, weights): | |
| 236 | 226 | weights = { |
| 237 | 227 | f"{k.split('.', 1)[1]}" if re.match(r'^model\.vision_tower', k) else |
| 238 | 228 | f"mm_projector.linear_1.{k.split('.')[-1]}" if re.match(r'^model\.mm_projector\.0', k) else |
| @@ -248,7 +238,4 @@ | ||
| 248 | 238 | for k, v in weights.items() |
| 249 | 239 | } |
| 250 | 240 | |
| 251 | - weights = VisionModel(model_config.vision_config).sanitize(weights=weights) | |
| 252 | - weights = LanguageModel(model_config.text_config).sanitize(weights=weights) | |
| 253 | - model.load_weights(list(weights.items())) | |
| 254 | - return model | |
| 241 | + return weights | |
| No newline at the end of the file |
modified mlx_vlm/models/nanoLlava/vision.py +0 −1
| @@ -1,7 +1,6 @@ | ||
| 1 | 1 | |
| 2 | 2 | |
| 3 | 3 | import inspect |
| 4 | -import math | |
| 5 | 4 | from dataclasses import dataclass |
| 6 | 5 | from typing import Optional |
| 7 | 6 |
added mlx_vlm/tokenizer_utils.py +332 −0
| @@ -0,0 +1,332 @@ | ||
| 1 | +import json | |
| 2 | +from functools import partial | |
| 3 | + | |
| 4 | +from transformers import AutoTokenizer | |
| 5 | + | |
| 6 | +REPLACEMENT_CHAR = "\ufffd" | |
| 7 | + | |
| 8 | + | |
| 9 | +def _remove_space(x): | |
| 10 | + if x and x[0] == " ": | |
| 11 | + return x[1:] | |
| 12 | + return x | |
| 13 | + | |
| 14 | + | |
| 15 | +class StreamingDetokenizer: | |
| 16 | + """The streaming detokenizer interface so that we can detokenize one token at a time. | |
| 17 | + | |
| 18 | + Example usage is as follows: | |
| 19 | + | |
| 20 | + detokenizer = ... | |
| 21 | + | |
| 22 | + # Reset the tokenizer state | |
| 23 | + detokenizer.reset() | |
| 24 | + | |
| 25 | + for token in generate(...): | |
| 26 | + detokenizer.add_token(token.item()) | |
| 27 | + | |
| 28 | + # Contains the whole text so far. Some tokens may not be included | |
| 29 | + # since it contains whole words usually. | |
| 30 | + detokenizer.text | |
| 31 | + | |
| 32 | + # Contains the printable segment (usually a word) since the last | |
| 33 | + # time it was accessed | |
| 34 | + detokenizer.last_segment | |
| 35 | + | |
| 36 | + # Contains all the tokens added so far | |
| 37 | + detokenizer.tokens | |
| 38 | + | |
| 39 | + # Make sure that we detokenize any remaining tokens | |
| 40 | + detokenizer.finalize() | |
| 41 | + | |
| 42 | + # Now detokenizer.text should match tokenizer.decode(detokenizer.tokens) | |
| 43 | + """ | |
| 44 | + | |
| 45 | + __slots__ = ("text", "tokens", "offset") | |
| 46 | + | |
| 47 | + def reset(self): | |
| 48 | + raise NotImplementedError() | |
| 49 | + | |
| 50 | + def add_token(self, token): | |
| 51 | + raise NotImplementedError() | |
| 52 | + | |
| 53 | + def finalize(self): | |
| 54 | + raise NotImplementedError() | |
| 55 | + | |
| 56 | + @property | |
| 57 | + def last_segment(self): | |
| 58 | + """Return the last segment of readable text since last time this property was accessed.""" | |
| 59 | + text = self.text | |
| 60 | + if text and text[-1] != REPLACEMENT_CHAR: | |
| 61 | + segment = text[self.offset :] | |
| 62 | + self.offset = len(text) | |
| 63 | + return segment | |
| 64 | + return "" | |
| 65 | + | |
| 66 | + | |
| 67 | +class NaiveStreamingDetokenizer(StreamingDetokenizer): | |
| 68 | + """NaiveStreamingDetokenizer relies on the underlying tokenizer | |
| 69 | + implementation and should work with every tokenizer. | |
| 70 | + | |
| 71 | + Its complexity is O(T^2) where T is the longest line since it will | |
| 72 | + repeatedly detokenize the same tokens until a new line is generated. | |
| 73 | + """ | |
| 74 | + | |
| 75 | + def __init__(self, tokenizer): | |
| 76 | + self._tokenizer = tokenizer | |
| 77 | + self._tokenizer.decode([0]) | |
| 78 | + self.reset() | |
| 79 | + | |
| 80 | + def reset(self): | |
| 81 | + self.offset = 0 | |
| 82 | + self._tokens = [] | |
| 83 | + self._text = "" | |
| 84 | + self._current_tokens = [] | |
| 85 | + self._current_text = "" | |
| 86 | + | |
| 87 | + def add_token(self, token): | |
| 88 | + self._current_tokens.append(token) | |
| 89 | + | |
| 90 | + def finalize(self): | |
| 91 | + self._tokens.extend(self._current_tokens) | |
| 92 | + self._text += self._tokenizer.decode(self._current_tokens) | |
| 93 | + self._current_tokens = [] | |
| 94 | + self._current_text = "" | |
| 95 | + | |
| 96 | + @property | |
| 97 | + def text(self): | |
| 98 | + if self._current_tokens: | |
| 99 | + self._current_text = self._tokenizer.decode(self._current_tokens) | |
| 100 | + if self._current_text and self._current_text[-1] == "\n": | |
| 101 | + self._tokens.extend(self._current_tokens) | |
| 102 | + self._text += self._current_text | |
| 103 | + self._current_tokens.clear() | |
| 104 | + self._current_text = "" | |
| 105 | + return self._text + self._current_text | |
| 106 | + | |
| 107 | + @property | |
| 108 | + def tokens(self): | |
| 109 | + return self._tokens | |
| 110 | + | |
| 111 | + | |
| 112 | +class SPMStreamingDetokenizer(StreamingDetokenizer): | |
| 113 | + """A streaming detokenizer for SPM models. | |
| 114 | + | |
| 115 | + It adds tokens to the text if the next token starts with the special SPM | |
| 116 | + underscore which results in linear complexity. | |
| 117 | + """ | |
| 118 | + | |
| 119 | + def __init__(self, tokenizer, trim_space=True): | |
| 120 | + self.trim_space = trim_space | |
| 121 | + | |
| 122 | + # Extract the tokens in a list from id to text | |
| 123 | + self.tokenmap = [None] * len(tokenizer.vocab) | |
| 124 | + for value, tokenid in tokenizer.vocab.items(): | |
| 125 | + self.tokenmap[tokenid] = value | |
| 126 | + | |
| 127 | + # Replace bytes with their value | |
| 128 | + for i in range(len(self.tokenmap)): | |
| 129 | + if self.tokenmap[i].startswith("<0x"): | |
| 130 | + self.tokenmap[i] = chr(int(self.tokenmap[i][3:5], 16)) | |
| 131 | + | |
| 132 | + self.reset() | |
| 133 | + | |
| 134 | + def reset(self): | |
| 135 | + self.offset = 0 | |
| 136 | + self._unflushed = "" | |
| 137 | + self.text = "" | |
| 138 | + self.tokens = [] | |
| 139 | + | |
| 140 | + def add_token(self, token): | |
| 141 | + v = self.tokenmap[token] | |
| 142 | + if v[0] == "\u2581": | |
| 143 | + if self.text or not self.trim_space: | |
| 144 | + self.text += self._unflushed.replace("\u2581", " ") | |
| 145 | + else: | |
| 146 | + self.text = _remove_space(self._unflushed.replace("\u2581", " ")) | |
| 147 | + self._unflushed = v | |
| 148 | + else: | |
| 149 | + self._unflushed += v | |
| 150 | + | |
| 151 | + def finalize(self): | |
| 152 | + if self.text or not self.trim_space: | |
| 153 | + self.text += self._unflushed.replace("\u2581", " ") | |
| 154 | + else: | |
| 155 | + self.text = _remove_space(self._unflushed.replace("\u2581", " ")) | |
| 156 | + self._unflushed = "" | |
| 157 | + | |
| 158 | + | |
| 159 | +class BPEStreamingDetokenizer(StreamingDetokenizer): | |
| 160 | + """A streaming detokenizer for OpenAI style BPE models. | |
| 161 | + | |
| 162 | + It adds tokens to the text if the next token starts with a space similar to | |
| 163 | + the SPM detokenizer. | |
| 164 | + """ | |
| 165 | + | |
| 166 | + _byte_decoder = None | |
| 167 | + | |
| 168 | + def __init__(self, tokenizer, trim_space=False): | |
| 169 | + self.trim_space = trim_space | |
| 170 | + | |
| 171 | + # Extract the tokens in a list from id to text | |
| 172 | + self.tokenmap = [None] * len(tokenizer.vocab) | |
| 173 | + for value, tokenid in tokenizer.vocab.items(): | |
| 174 | + self.tokenmap[tokenid] = value | |
| 175 | + | |
| 176 | + self.reset() | |
| 177 | + | |
| 178 | + # Make the BPE byte decoder from | |
| 179 | + # https://github.com/openai/gpt-2/blob/master/src/encoder.py | |
| 180 | + self.make_byte_decoder() | |
| 181 | + | |
| 182 | + def reset(self): | |
| 183 | + self.offset = 0 | |
| 184 | + self._unflushed = "" | |
| 185 | + self.text = "" | |
| 186 | + self.tokens = [] | |
| 187 | + | |
| 188 | + def add_token(self, token): | |
| 189 | + v = self.tokenmap[token] | |
| 190 | + # if the token starts with space | |
| 191 | + if self._byte_decoder[v[0]] == 32: | |
| 192 | + current_text = bytearray( | |
| 193 | + self._byte_decoder[c] for c in self._unflushed | |
| 194 | + ).decode("utf-8") | |
| 195 | + if self.text or not self.trim_space: | |
| 196 | + self.text += current_text | |
| 197 | + else: | |
| 198 | + self.text += _remove_space(current_text) | |
| 199 | + self._unflushed = v | |
| 200 | + else: | |
| 201 | + self._unflushed += v | |
| 202 | + | |
| 203 | + def finalize(self): | |
| 204 | + current_text = bytearray(self._byte_decoder[c] for c in self._unflushed).decode( | |
| 205 | + "utf-8" | |
| 206 | + ) | |
| 207 | + if self.text or not self.trim_space: | |
| 208 | + self.text += current_text | |
| 209 | + else: | |
| 210 | + self.text += _remove_space(current_text) | |
| 211 | + self._unflushed = "" | |
| 212 | + | |
| 213 | + @classmethod | |
| 214 | + def make_byte_decoder(cls): | |
| 215 | + """See https://github.com/openai/gpt-2/blob/master/src/encoder.py for the rationale.""" | |
| 216 | + if cls._byte_decoder is not None: | |
| 217 | + return | |
| 218 | + | |
| 219 | + char_to_bytes = {} | |
| 220 | + limits = [ | |
| 221 | + 0, | |
| 222 | + ord("!"), | |
| 223 | + ord("~") + 1, | |
| 224 | + ord("¡"), | |
| 225 | + ord("¬") + 1, | |
| 226 | + ord("®"), | |
| 227 | + ord("ÿ") + 1, | |
| 228 | + ] | |
| 229 | + n = 0 | |
| 230 | + for i, (start, stop) in enumerate(zip(limits, limits[1:])): | |
| 231 | + if i % 2 == 0: | |
| 232 | + for b in range(start, stop): | |
| 233 | + char_to_bytes[chr(2**8 + n)] = b | |
| 234 | + n += 1 | |
| 235 | + else: | |
| 236 | + for b in range(start, stop): | |
| 237 | + char_to_bytes[chr(b)] = b | |
| 238 | + cls._byte_decoder = char_to_bytes | |
| 239 | + | |
| 240 | + | |
| 241 | +class TokenizerWrapper: | |
| 242 | + """A wrapper that combines an HF tokenizer and a detokenizer. | |
| 243 | + | |
| 244 | + Accessing any attribute other than the ``detokenizer`` is forwarded to the | |
| 245 | + huggingface tokenizer. | |
| 246 | + """ | |
| 247 | + | |
| 248 | + def __init__(self, tokenizer, detokenizer_class=NaiveStreamingDetokenizer): | |
| 249 | + self._tokenizer = tokenizer | |
| 250 | + self._detokenizer = detokenizer_class(tokenizer) | |
| 251 | + | |
| 252 | + def __getattr__(self, attr): | |
| 253 | + if attr == "detokenizer": | |
| 254 | + return self._detokenizer | |
| 255 | + else: | |
| 256 | + return getattr(self._tokenizer, attr) | |
| 257 | + | |
| 258 | + | |
| 259 | +def _match(a, b): | |
| 260 | + if type(a) != type(b): | |
| 261 | + return False | |
| 262 | + if isinstance(a, dict): | |
| 263 | + return len(a) == len(b) and all(k in b and _match(a[k], b[k]) for k in a) | |
| 264 | + if isinstance(a, list): | |
| 265 | + return len(a) == len(b) and all(_match(ai, bi) for ai, bi in zip(a, b)) | |
| 266 | + | |
| 267 | + return a == b | |
| 268 | + | |
| 269 | + | |
| 270 | +def _is_spm_decoder(decoder): | |
| 271 | + _target_description = { | |
| 272 | + "type": "Sequence", | |
| 273 | + "decoders": [ | |
| 274 | + {"type": "Replace", "pattern": {"String": "▁"}, "content": " "}, | |
| 275 | + {"type": "ByteFallback"}, | |
| 276 | + {"type": "Fuse"}, | |
| 277 | + {"type": "Strip", "content": " ", "start": 1, "stop": 0}, | |
| 278 | + ], | |
| 279 | + } | |
| 280 | + return _match(_target_description, decoder) | |
| 281 | + | |
| 282 | + | |
| 283 | +def _is_spm_decoder_no_space(decoder): | |
| 284 | + _target_description = { | |
| 285 | + "type": "Sequence", | |
| 286 | + "decoders": [ | |
| 287 | + {"type": "Replace", "pattern": {"String": "▁"}, "content": " "}, | |
| 288 | + {"type": "ByteFallback"}, | |
| 289 | + {"type": "Fuse"}, | |
| 290 | + ], | |
| 291 | + } | |
| 292 | + return _match(_target_description, decoder) | |
| 293 | + | |
| 294 | + | |
| 295 | +def _is_bpe_decoder(decoder): | |
| 296 | + _target_description = { | |
| 297 | + "type": "ByteLevel", | |
| 298 | + "add_prefix_space": False, | |
| 299 | + "trim_offsets": False, | |
| 300 | + "use_regex": False, | |
| 301 | + } | |
| 302 | + | |
| 303 | + return _match(_target_description, decoder) | |
| 304 | + | |
| 305 | + | |
| 306 | +def load_tokenizer(model_path, return_tokenizer=True, tokenizer_config_extra={}): | |
| 307 | + """Load a huggingface tokenizer and try to infer the type of streaming | |
| 308 | + detokenizer to use. | |
| 309 | + | |
| 310 | + Note, to use a fast streaming tokenizer, pass a local file path rather than | |
| 311 | + a Hugging Face repo ID. | |
| 312 | + """ | |
| 313 | + detokenizer_class = NaiveStreamingDetokenizer | |
| 314 | + | |
| 315 | + tokenizer_file = model_path / "tokenizer.json" | |
| 316 | + if tokenizer_file.exists(): | |
| 317 | + tokenizer_content = json.load(tokenizer_file.open()) | |
| 318 | + if "decoder" in tokenizer_content: | |
| 319 | + if _is_spm_decoder(tokenizer_content["decoder"]): | |
| 320 | + detokenizer_class = SPMStreamingDetokenizer | |
| 321 | + elif _is_spm_decoder_no_space(tokenizer_content["decoder"]): | |
| 322 | + detokenizer_class = partial(SPMStreamingDetokenizer, trim_space=False) | |
| 323 | + elif _is_bpe_decoder(tokenizer_content["decoder"]): | |
| 324 | + detokenizer_class = BPEStreamingDetokenizer | |
| 325 | + | |
| 326 | + if return_tokenizer: | |
| 327 | + return TokenizerWrapper( | |
| 328 | + AutoTokenizer.from_pretrained(model_path, **tokenizer_config_extra), | |
| 329 | + detokenizer_class, | |
| 330 | + ) | |
| 331 | + else: | |
| 332 | + return detokenizer_class | |
| No newline at the end of the file |
modified mlx_vlm/utils.py +202 −87
| @@ -10,13 +10,18 @@ | ||
| 10 | 10 | from pathlib import Path |
| 11 | 11 | from textwrap import dedent |
| 12 | 12 | from typing import Any, Callable, Dict, Generator, Optional, Tuple, Union |
| 13 | +import requests | |
| 13 | 14 | |
| 14 | 15 | import mlx.core as mx |
| 15 | 16 | import mlx.nn as nn |
| 17 | +import numpy as np | |
| 18 | +from PIL import Image | |
| 16 | 19 | from huggingface_hub import snapshot_download |
| 17 | 20 | from mlx.utils import tree_flatten, tree_unflatten |
| 18 | -from transformers import AutoConfig, AutoProcessor, PreTrainedTokenizer | |
| 21 | +from transformers import AutoConfig, AutoProcessor, PreTrainedTokenizer, PreTrainedTokenizerFast | |
| 19 | 22 | |
| 23 | +from .tokenizer_utils import TokenizerWrapper, load_tokenizer | |
| 24 | +from .models.base import BaseImageProcessor | |
| 20 | 25 | from .sample_utils import top_p_sampling |
| 21 | 26 | |
| 22 | 27 | # Constants |
| @@ -32,9 +37,9 @@ | ||
| 32 | 37 | != 8 # avoid quantizing gate layers, otherwise we have to re-quant and upload all the mixtral models |
| 33 | 38 | ) |
| 34 | 39 | |
| 35 | -def get_model_class(config: dict): | |
| 40 | +def get_model_and_args(config: dict): | |
| 36 | 41 | """ |
| 37 | - Retrieve the model clas based on the configuration. | |
| 42 | + Retrieve the model object based on the configuration. | |
| 38 | 43 | |
| 39 | 44 | Args: |
| 40 | 45 | config (dict): The model configuration. |
| @@ -46,21 +51,50 @@ | ||
| 46 | 51 | model_type = MODEL_REMAPPING.get(model_type, model_type) |
| 47 | 52 | try: |
| 48 | 53 | arch = importlib.import_module(f"mlx_vlm.models.{model_type}") |
| 49 | - if model_type == "nanoLlava": | |
| 50 | - image_processor = arch.SigLipImageProcessor() | |
| 51 | - else: | |
| 52 | - image_processor = "" | |
| 53 | 54 | except ImportError: |
| 54 | 55 | msg = f"Model type {model_type} not supported." |
| 55 | 56 | logging.error(msg) |
| 56 | 57 | raise ValueError(msg) |
| 57 | 58 | |
| 58 | 59 | |
| 59 | - return arch, model_type, image_processor | |
| 60 | + return arch, model_type | |
| 61 | + | |
| 62 | + | |
| 63 | +def get_model_path(path_or_hf_repo: str, revision: Optional[str] = None) -> Path: | |
| 64 | + """ | |
| 65 | + Ensures the model is available locally. If the path does not exist locally, | |
| 66 | + it is downloaded from the Hugging Face Hub. | |
| 67 | + | |
| 68 | + Args: | |
| 69 | + path_or_hf_repo (str): The local path or Hugging Face repository ID of the model. | |
| 70 | + revision (str, optional): A revision id which can be a branch name, a tag, or a commit hash. | |
| 71 | + | |
| 72 | + Returns: | |
| 73 | + Path: The path to the model. | |
| 74 | + """ | |
| 75 | + model_path = Path(path_or_hf_repo) | |
| 76 | + if not model_path.exists(): | |
| 77 | + model_path = Path( | |
| 78 | + snapshot_download( | |
| 79 | + repo_id=path_or_hf_repo, | |
| 80 | + revision=revision, | |
| 81 | + allow_patterns=[ | |
| 82 | + "*.json", | |
| 83 | + "*.safetensors", | |
| 84 | + "*.py", | |
| 85 | + "tokenizer.model", | |
| 86 | + "*.tiktoken", | |
| 87 | + "*.txt", | |
| 88 | + ], | |
| 89 | + resume_download=True, | |
| 90 | + ) | |
| 91 | + ) | |
| 92 | + return model_path | |
| 93 | + | |
| 60 | 94 | |
| 61 | -def load(model_path: Path, lazy: bool = False) -> nn.Module: | |
| 95 | +def load_model(model_path: Path, lazy: bool = False) -> nn.Module: | |
| 62 | 96 | """ |
| 63 | - Load and initialize the model and processor from a given path. | |
| 97 | + Load and initialize the model from a given path. | |
| 64 | 98 | |
| 65 | 99 | Args: |
| 66 | 100 | model_path (Path): The path to load the model from. |
| @@ -76,42 +110,22 @@ | ||
| 76 | 110 | ValueError: If the model class or args class are not found or cannot be instantiated. |
| 77 | 111 | """ |
| 78 | 112 | |
| 79 | - path = Path(model_path) | |
| 80 | - if not path.exists(): | |
| 81 | - path = Path( | |
| 82 | - snapshot_download( | |
| 83 | - repo_id=model_path, | |
| 84 | - allow_patterns=[ | |
| 85 | - "*.json", | |
| 86 | - "*.safetensors", | |
| 87 | - "*.py", | |
| 88 | - "tokenizer.model", | |
| 89 | - "*.tiktoken", | |
| 90 | - ], | |
| 91 | 113 | |
| 92 | - ) | |
| 93 | - ) | |
| 114 | + config = load_config(model_path) | |
| 115 | + quantization = config.get("quantization", None) | |
| 94 | 116 | |
| 95 | - try: | |
| 96 | - with open(path / "config.json", "r") as f: | |
| 97 | - config = json.load(f) | |
| 98 | - quantization = config.get("quantization", None) | |
| 99 | - | |
| 100 | - except FileNotFoundError: | |
| 101 | - logging.error(f"Config file not found in {path}") | |
| 102 | - raise | |
| 103 | 117 | |
| 104 | - weight_files = glob.glob(str(path / "*.safetensors")) | |
| 118 | + weight_files = glob.glob(str(model_path / "*.safetensors")) | |
| 105 | 119 | if not weight_files: |
| 106 | - logging.error(f"No safetensors found in {path}") | |
| 107 | - raise FileNotFoundError(f"No safetensors found in {path}") | |
| 120 | + logging.error(f"No safetensors found in {model_path}") | |
| 121 | + raise FileNotFoundError(f"No safetensors found in {model_path}") | |
| 108 | 122 | |
| 109 | 123 | weights = {} |
| 110 | 124 | for wf in weight_files: |
| 111 | 125 | weights.update(mx.load(wf)) |
| 112 | 126 | |
| 113 | 127 | |
| 114 | - model_class, model_type, image_processor = get_model_class(config=config) | |
| 128 | + model_class, model_type = get_model_and_args(config=config) | |
| 115 | 129 | |
| 116 | 130 | if model_type == "nanoLlava": |
| 117 | 131 | vision_config = AutoConfig.from_pretrained(config["mm_vision_tower"]) |
| @@ -121,8 +135,6 @@ | ||
| 121 | 135 | config["vision_config"] = vision_config["vision_config"] |
| 122 | 136 | config["text_config"] = text_config |
| 123 | 137 | |
| 124 | - processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True) | |
| 125 | - | |
| 126 | 138 | model_config = model_class.ModelConfig.from_dict(config) |
| 127 | 139 | model_config.vision_config = model_class.VisionConfig.from_dict(config["vision_config"]) |
| 128 | 140 | model_config.text_config = model_class.TextConfig.from_dict(config["text_config"]) |
| @@ -131,22 +143,6 @@ | ||
| 131 | 143 | if hasattr(model, "sanitize"): |
| 132 | 144 | weights = model.sanitize(weights) |
| 133 | 145 | |
| 134 | - if model_type == "nanoLlava": | |
| 135 | - weights = { | |
| 136 | - f"{k.split('.', 1)[1]}" if re.match(r'^model\.vision_tower', k) else | |
| 137 | - f"mm_projector.linear_1.{k.split('.')[-1]}" if re.match(r'^model\.mm_projector\.0', k) else | |
| 138 | - f"mm_projector.linear_2.{k.split('.')[-1]}" if re.match(r'^model\.mm_projector\.2', k) else | |
| 139 | - f"language_model.model.{k}" if re.match(r'^lm_head', k) else | |
| 140 | - f"language_model.{k}" if re.match(r'^model\.(embed_tokens|norm|layers)', k) else k: v | |
| 141 | - for k, v in weights.items() | |
| 142 | - } | |
| 143 | - | |
| 144 | - weights = { | |
| 145 | - 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 | |
| 146 | - 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 | |
| 147 | - for k, v in weights.items() | |
| 148 | - } | |
| 149 | - | |
| 150 | 146 | weights = model_class.VisionModel(model_config.vision_config).sanitize(weights=weights) |
| 151 | 147 | weights = model_class.LanguageModel(model_config.text_config).sanitize(weights=weights) |
| 152 | 148 | |
| @@ -172,16 +168,77 @@ | ||
| 172 | 168 | ) |
| 173 | 169 | |
| 174 | 170 | model.load_weights(list(weights.items())) |
| 175 | - # if not lazy: | |
| 176 | - # mx.eval(model.parameters()) | |
| 171 | + if not lazy: | |
| 172 | + mx.eval(model.parameters()) | |
| 173 | + | |
| 174 | + model.eval() | |
| 175 | + return model | |
| 176 | + | |
| 177 | + | |
| 178 | +def load( | |
| 179 | + path_or_hf_repo: str, | |
| 180 | + processor_config={}, | |
| 181 | + lazy: bool = False, | |
| 182 | +) -> Tuple[nn.Module, Union[PreTrainedTokenizer, PreTrainedTokenizerFast]]: | |
| 183 | + """ | |
| 184 | + Load the model and tokenizer from a given path or a huggingface repository. | |
| 185 | + | |
| 186 | + Args: | |
| 187 | + path_or_hf_repo (Path): The path or the huggingface repository to load the model from. | |
| 188 | + tokenizer_config (dict, optional): Configuration parameters specifically for the tokenizer. | |
| 189 | + Defaults to an empty dictionary. | |
| 190 | + adapter_path (str, optional): Path to the LoRA adapters. If provided, applies LoRA layers | |
| 191 | + to the model. Default: ``None``. | |
| 192 | + lazy (bool): If False eval the model parameters to make sure they are | |
| 193 | + loaded in memory before returning, otherwise they will be loaded | |
| 194 | + when needed. Default: ``False`` | |
| 195 | + Returns: | |
| 196 | + Tuple[nn.Module, TokenizerWrapper]: A tuple containing the loaded model and tokenizer. | |
| 197 | + | |
| 198 | + Raises: | |
| 199 | + FileNotFoundError: If config file or safetensors are not found. | |
| 200 | + ValueError: If model class or args class are not found. | |
| 201 | + """ | |
| 202 | + model_path = get_model_path(path_or_hf_repo) | |
| 203 | + | |
| 204 | + model = load_model(model_path, lazy) | |
| 205 | + processor = load_processor(model_path, processor_config=processor_config) | |
| 206 | + | |
| 207 | + return model, processor | |
| 208 | + | |
| 209 | +def load_config(model_path: Path) -> dict: | |
| 210 | + try: | |
| 211 | + with open(model_path / "config.json", "r") as f: | |
| 212 | + config = json.load(f) | |
| 213 | + except FileNotFoundError: | |
| 214 | + logging.error(f"Config file not found in {model_path}") | |
| 215 | + raise | |
| 216 | + return config | |
| 217 | + | |
| 218 | +def load_image_processor(config: dict) -> BaseImageProcessor: | |
| 219 | + model_class, _ = get_model_and_args(config) | |
| 220 | + image_processor = None | |
| 221 | + | |
| 222 | + if hasattr(model_class, "ImageProcessor"): | |
| 223 | + image_processor = model_class.ImageProcessor() | |
| 224 | + | |
| 225 | + return image_processor | |
| 177 | 226 | |
| 178 | - # model.eval() | |
| 179 | - return model, config, model_type, processor, image_processor | |
| 227 | +def load_processor(model_path, processor_config={"trust_remote_code": True}) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]: | |
| 228 | + processor = AutoProcessor.from_pretrained(model_path, **processor_config) | |
| 229 | + detokenizer_class = load_tokenizer(model_path, return_tokenizer=False) | |
| 230 | + if "tokenizer" in processor.__dict__.keys(): | |
| 231 | + processor.detokenizer = detokenizer_class(processor.tokenizer) | |
| 232 | + else: | |
| 233 | + processor.detokenizer = detokenizer_class(processor) | |
| 234 | + return processor | |
| 180 | 235 | |
| 181 | 236 | def fetch_from_hub( |
| 182 | 237 | model_path: Path, lazy: bool = False |
| 183 | 238 | ) -> Tuple[nn.Module, dict, PreTrainedTokenizer]: |
| 184 | - model, config, _, processor, _ = load(model_path, lazy) | |
| 239 | + model = load_model(model_path, lazy) | |
| 240 | + config = load_config(model_path) | |
| 241 | + processor = load_processor(model_path) | |
| 185 | 242 | |
| 186 | 243 | return model, config, processor |
| 187 | 244 | |
| @@ -377,10 +434,7 @@ | ||
| 377 | 434 | Tuple: Tuple containing quantized weights and config. |
| 378 | 435 | """ |
| 379 | 436 | quantized_config = copy.deepcopy(config) |
| 380 | - | |
| 381 | - nn.QuantizedLinear.quantize_module( | |
| 382 | - model, q_group_size, q_bits, linear_class_predicate=linear_class_predicate | |
| 383 | - ) | |
| 437 | + nn.quantize(model, q_group_size, q_bits) | |
| 384 | 438 | quantized_config["quantization"] = {"group_size": q_group_size, "bits": q_bits} |
| 385 | 439 | quantized_weights = dict(tree_flatten(model.parameters())) |
| 386 | 440 | |
| @@ -494,9 +548,63 @@ | ||
| 494 | 548 | if upload_repo is not None: |
| 495 | 549 | upload_to_hub(mlx_path, upload_repo, hf_path) |
| 496 | 550 | |
| 551 | +def load_image(image_source): | |
| 552 | + """ | |
| 553 | + Helper function to load an image from either a URL or file. | |
| 554 | + """ | |
| 555 | + if image_source.startswith(("http://", "https://")): | |
| 556 | + try: | |
| 557 | + response = requests.get(image_source, stream=True) | |
| 558 | + response.raise_for_status() | |
| 559 | + return Image.open(response.raw) | |
| 560 | + except Exception as e: | |
| 561 | + raise ValueError( | |
| 562 | + f"Failed to load image from URL: {image_source} with error {e}" | |
| 563 | + ) | |
| 564 | + elif Path(image_source).is_file(): | |
| 565 | + try: | |
| 566 | + return Image.open(image_source) | |
| 567 | + except IOError as e: | |
| 568 | + raise ValueError(f"Failed to load image {image_source} with error: {e}") | |
| 569 | + else: | |
| 570 | + raise ValueError( | |
| 571 | + f"The image {image_source} must be a valid URL or existing file." | |
| 572 | + ) | |
| 573 | + | |
| 574 | +def prepare_inputs(image_processor, processor, image, prompt): | |
| 575 | + if isinstance(image, str): | |
| 576 | + image = load_image(image) | |
| 577 | + | |
| 578 | + if image_processor is not None: | |
| 579 | + text_chunks = [processor(chunk).input_ids for chunk in prompt.split("<image>")] | |
| 580 | + input_ids = mx.array([text_chunks[0] + [-200] + text_chunks[1]]) | |
| 581 | + pixel_values = image_processor.preprocess(images=[image])[0] | |
| 582 | + pixel_values = mx.array(np.expand_dims(pixel_values, axis=0)) | |
| 583 | + else: | |
| 584 | + inputs = processor(prompt, image, return_tensors="np") | |
| 585 | + pixel_values = mx.array(inputs["pixel_values"]) | |
| 586 | + input_ids = mx.array(inputs["input_ids"]) | |
| 587 | + | |
| 588 | + return input_ids, pixel_values | |
| 589 | + | |
| 590 | +def sample(logits: mx.array, temp:float, top_p:float) -> Tuple[mx.array, float]: | |
| 591 | + softmax_logits = mx.softmax(logits) | |
| 592 | + | |
| 593 | + if temp == 0: | |
| 594 | + token = mx.argmax(logits, axis=-1) | |
| 595 | + else: | |
| 596 | + if top_p > 0 and top_p < 1.0: | |
| 597 | + token = top_p_sampling(logits, top_p, temp) | |
| 598 | + else: | |
| 599 | + token = mx.random.categorical(logits * (1 / temp)) | |
| 600 | + | |
| 601 | + prob = softmax_logits[0, token] | |
| 602 | + return token, prob | |
| 603 | + | |
| 497 | 604 | def generate_step( |
| 498 | - prompt: mx.array, | |
| 499 | 605 | model: nn.Module, |
| 606 | + prompt: mx.array, | |
| 607 | + cache = None, | |
| 500 | 608 | temp: float = 0.0, |
| 501 | 609 | repetition_penalty: Optional[float] = None, |
| 502 | 610 | repetition_context_size: Optional[int] = 20, |
| @@ -518,20 +626,6 @@ | ||
| 518 | 626 | one token and probability per call. |
| 519 | 627 | """ |
| 520 | 628 | |
| 521 | - def sample(logits: mx.array) -> Tuple[mx.array, float]: | |
| 522 | - softmax_logits = mx.softmax(logits) | |
| 523 | - | |
| 524 | - if temp == 0: | |
| 525 | - token = mx.argmax(logits, axis=-1) | |
| 526 | - else: | |
| 527 | - if top_p > 0 and top_p < 1.0: | |
| 528 | - token = top_p_sampling(logits, top_p, temp) | |
| 529 | - else: | |
| 530 | - token = mx.random.categorical(logits * (1 / temp)) | |
| 531 | - | |
| 532 | - prob = softmax_logits[0, token] | |
| 533 | - return token, prob | |
| 534 | - | |
| 535 | 629 | if repetition_penalty and ( |
| 536 | 630 | repetition_penalty < 0 or not isinstance(repetition_penalty, float) |
| 537 | 631 | ): |
| @@ -539,8 +633,7 @@ | ||
| 539 | 633 | f"repetition_penalty must be a non-negative float, got {repetition_penalty}" |
| 540 | 634 | ) |
| 541 | 635 | |
| 542 | - y = prompt | |
| 543 | - cache = None | |
| 636 | + y, prob = sample(prompt, temp, top_p) | |
| 544 | 637 | |
| 545 | 638 | repetition_context = prompt.tolist() |
| 546 | 639 | |
| @@ -555,10 +648,10 @@ | ||
| 555 | 648 | logits = apply_repetition_penalty( |
| 556 | 649 | logits, repetition_context, repetition_penalty |
| 557 | 650 | ) |
| 558 | - y, prob = sample(logits) | |
| 651 | + y, prob = sample(logits, temp, top_p) | |
| 559 | 652 | repetition_context.append(y.item()) |
| 560 | 653 | else: |
| 561 | - y, prob = sample(logits) | |
| 654 | + y, prob = sample(logits, temp, top_p) | |
| 562 | 655 | |
| 563 | 656 | if repetition_context_size: |
| 564 | 657 | if len(repetition_context) > repetition_context_size: |
| @@ -568,8 +661,10 @@ | ||
| 568 | 661 | |
| 569 | 662 | def generate( |
| 570 | 663 | model: nn.Module, |
| 571 | - tokenizer: PreTrainedTokenizer, | |
| 664 | + processor: PreTrainedTokenizer, | |
| 665 | + image: str, | |
| 572 | 666 | prompt: str, |
| 667 | + image_processor = None, | |
| 573 | 668 | temp: float = 0.0, |
| 574 | 669 | max_tokens: int = 100, |
| 575 | 670 | verbose: bool = False, |
| @@ -596,18 +691,34 @@ | ||
| 596 | 691 | """ |
| 597 | 692 | if verbose: |
| 598 | 693 | print("=" * 10) |
| 694 | + print("Image:", image, "\n") | |
| 599 | 695 | print("Prompt:", prompt) |
| 600 | 696 | |
| 601 | - prompt_tokens = mx.array(tokenizer.encode(prompt)) | |
| 602 | - detokenizer = tokenizer.detokenizer | |
| 697 | + | |
| 698 | + if image_processor is not None: | |
| 699 | + prompt_tokens = mx.array(processor.encode(prompt)) | |
| 700 | + tokenizer = processor | |
| 701 | + else: | |
| 702 | + prompt_tokens = mx.array(processor.tokenizer.encode(prompt)) | |
| 703 | + tokenizer = processor.tokenizer | |
| 704 | + | |
| 705 | + input_ids, pixel_values = prepare_inputs(image_processor, processor, image, prompt) | |
| 706 | + logits, cache = model(input_ids, pixel_values) | |
| 707 | + logits = logits[:, -1, :] | |
| 708 | + y, _ = sample(logits, temp, top_p) | |
| 709 | + | |
| 603 | 710 | |
| 604 | 711 | tic = time.perf_counter() |
| 712 | + detokenizer = processor.detokenizer | |
| 605 | 713 | detokenizer.reset() |
| 606 | 714 | |
| 715 | + detokenizer.add_token(y.item()) | |
| 716 | + | |
| 607 | 717 | for (token, prob), n in zip( |
| 608 | 718 | generate_step( |
| 609 | - prompt_tokens, | |
| 610 | - model, | |
| 719 | + model.language_model, | |
| 720 | + logits, | |
| 721 | + cache, | |
| 611 | 722 | temp, |
| 612 | 723 | repetition_penalty, |
| 613 | 724 | repetition_context_size, |
| @@ -619,8 +730,11 @@ | ||
| 619 | 730 | if n == 0: |
| 620 | 731 | prompt_time = time.perf_counter() - tic |
| 621 | 732 | tic = time.perf_counter() |
| 733 | + | |
| 622 | 734 | if token == tokenizer.eos_token_id: |
| 623 | 735 | break |
| 736 | + | |
| 737 | + | |
| 624 | 738 | detokenizer.add_token(token) |
| 625 | 739 | |
| 626 | 740 | if verbose: |
| @@ -643,6 +757,7 @@ | ||
| 643 | 757 | return |
| 644 | 758 | prompt_tps = prompt_tokens.size / prompt_time |
| 645 | 759 | gen_tps = (token_count - 1) / gen_time |
| 760 | + | |
| 646 | 761 | print(f"Prompt: {prompt_tps:.3f} tokens-per-sec") |
| 647 | 762 | print(f"Generation: {gen_tps:.3f} tokens-per-sec") |
| 648 | 763 |
modified setup.py +3 −3
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | import sys |
| 2 | 2 | from pathlib import Path |
| 3 | 3 | |
| 4 | -from setuptools import setup | |
| 4 | +from setuptools import setup, find_packages | |
| 5 | 5 | |
| 6 | 6 | package_dir = Path(__file__).parent / "mlx_vlm" |
| 7 | 7 | with open(package_dir / "requirements.txt") as fid: |
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | setup( |
| 14 | 14 | name="mlx-vlm", |
| 15 | 15 | version=__version__, |
| 16 | - description="Visual LLMs on Apple silicon with MLX and the Hugging Face Hub", | |
| 16 | + description="Vision LLMs on Apple silicon with MLX and the Hugging Face Hub", | |
| 17 | 17 | long_description=open("README.md", encoding="utf-8").read(), |
| 18 | 18 | long_description_content_type="text/markdown", |
| 19 | 19 | readme="README.md", |
| @@ -22,6 +22,6 @@ | ||
| 22 | 22 | url="https://github.com/Blaizzy/mlx-vlm", |
| 23 | 23 | license="MIT", |
| 24 | 24 | install_requires=requirements, |
| 25 | - packages=["mlx_vlm", "mlx_vlm.models"], | |
| 25 | + packages=find_packages(), | |
| 26 | 26 | python_requires=">=3.8", |
| 27 | 27 | ) |