Changesets · Branches · Tags · Compare
| Changeset | 298bbfc46d57a3c059d0e7e77df60006640a266de488fc2d0b0d5d0d6c611bc2 |
|---|---|
| Author | Prince Canuma <prince.gdt@gmail.com> · 2024-10-11 19:15 +02:00 |
| Committer | GitHub <noreply@github.com> · 2024-10-11 19:15 +02:00 |
| Parents | 5d7c46de2be5 |
33 files changed
modified .gitignore +1 −0
| @@ -20,3 +20,4 @@ | ||
| 20 | 20 | .installed.cfg |
| 21 | 21 | *.egg |
| 22 | 22 | .DS_Store |
| 23 | +*.log |
modified README.md +95 −19
| @@ -1,43 +1,119 @@ | ||
| 1 | 1 | # MLX-VLM |
| 2 | 2 | |
| 3 | -MLX-VLM a package for running Vision LLMs on your Mac using MLX. | |
| 3 | +MLX-VLM is a package for inference and fine-tuning of Vision Language Models (VLMs) on your Mac using MLX. | |
| 4 | + | |
| 5 | +## Table of Contents | |
| 6 | +- [Installation](#installation) | |
| 7 | +- [Usage](#usage) | |
| 8 | + - [Command Line Interface (CLI)](#command-line-interface-cli) | |
| 9 | + - [Chat UI with Gradio](#chat-ui-with-gradio) | |
| 10 | + - [Python Script](#python-script) | |
| 11 | +- [Multi-Image Chat Support](#multi-image-chat-support) | |
| 12 | + - [Supported Models](#supported-models) | |
| 13 | + - [Usage Examples](#usage-examples) | |
| 14 | +- [Fine-tuning](#fine-tuning) | |
| 15 | + | |
| 16 | +## Installation | |
| 17 | + | |
| 18 | +The easiest way to get started is to install the `mlx-vlm` package using pip: | |
| 4 | 19 | |
| 20 | +```sh | |
| 21 | +pip install mlx-vlm | |
| 22 | +``` | |
| 5 | 23 | |
| 6 | -## Get started | |
| 24 | +## Usage | |
| 7 | 25 | |
| 8 | -The easiest way to get started is to install the `mlx-vlm` package: | |
| 26 | +### Command Line Interface (CLI) | |
| 9 | 27 | |
| 10 | -**With `pip`**: | |
| 28 | +Generate output from a model using the CLI: | |
| 11 | 29 | |
| 12 | 30 | ```sh |
| 13 | -pip install mlx-vlm | |
| 31 | +python -m mlx_vlm.generate --model mlx-community/Qwen2-VL-2B-Instruct-4bit --max-tokens 100 --temp 0.0 --image http://images.cocodataset.org/val2017/000000039769.jpg | |
| 14 | 32 | ``` |
| 15 | 33 | |
| 16 | -## Inference | |
| 34 | +### Chat UI with Gradio | |
| 17 | 35 | |
| 18 | -**CLI** | |
| 19 | -```sh | |
| 20 | -python -m mlx_vlm.generate --model qnguyen3/nanoLLaVA --max-tokens 100 --temp 0.0 | |
| 21 | -``` | |
| 36 | +Launch a chat interface using Gradio: | |
| 22 | 37 | |
| 23 | -**Chat UI with Gradio** | |
| 24 | 38 | ```sh |
| 25 | -python -m mlx_vlm.chat_ui --model qnguyen3/nanoLLaVA | |
| 39 | +python -m mlx_vlm.chat_ui --model mlx-community/Qwen2-VL-2B-Instruct-4bit | |
| 26 | 40 | ``` |
| 27 | 41 | |
| 28 | -**Script** | |
| 42 | +### Python Script | |
| 43 | + | |
| 44 | +Here's an example of how to use MLX-VLM in a Python script: | |
| 45 | + | |
| 29 | 46 | ```python |
| 30 | 47 | import mlx.core as mx |
| 31 | 48 | from mlx_vlm import load, generate |
| 49 | +from mlx_vlm.prompt_utils import apply_chat_template | |
| 50 | + | |
| 51 | +# Load the model | |
| 52 | +model_path = "mlx-community/Qwen2-VL-2B-Instruct-4bit" | |
| 53 | +model, processor = load(model_path) | |
| 54 | + | |
| 55 | +# Prepare input | |
| 56 | +image = ["http://images.cocodataset.org/val2017/000000039769.jpg"] | |
| 57 | +prompt = "Describe this image." | |
| 58 | + | |
| 59 | +# Apply chat template | |
| 60 | +formatted_prompt = apply_chat_template( | |
| 61 | + processor, config, prompt, num_images=len(image) | |
| 62 | +) | |
| 63 | + | |
| 64 | +# Generate output | |
| 65 | +output = generate(model, processor, image, formatted_prompt, verbose=False) | |
| 66 | +print(output) | |
| 67 | +``` | |
| 68 | + | |
| 69 | +## Multi-Image Chat Support | |
| 70 | + | |
| 71 | +MLX-VLM supports analyzing multiple images simultaneously with select models. This feature enables more complex visual reasoning tasks and comprehensive analysis across multiple images in a single conversation. | |
| 72 | + | |
| 73 | +### Supported Models | |
| 74 | + | |
| 75 | +The following models support multi-image chat: | |
| 76 | + | |
| 77 | +1. Idefics 2 | |
| 78 | +2. LLaVA (Interleave) | |
| 79 | +3. Qwen2-VL | |
| 80 | +4. Phi3-Vision | |
| 81 | +5. Pixtral | |
| 82 | + | |
| 83 | +### Usage Examples | |
| 84 | + | |
| 85 | +#### Python Script | |
| 86 | + | |
| 87 | +```python | |
| 88 | +from mlx_vlm import load, generate | |
| 89 | +from mlx_vlm.prompt_utils import apply_chat_template | |
| 32 | 90 | |
| 33 | -model_path = "mlx-community/llava-1.5-7b-4bit" | |
| 91 | +model_path = "mlx-community/Qwen2-VL-2B-Instruct-4bit" | |
| 34 | 92 | model, processor = load(model_path) |
| 35 | 93 | |
| 36 | -prompt = processor.tokenizer.apply_chat_template( | |
| 37 | - [{"role": "user", "content": f"<image>\nWhat are these?"}], | |
| 38 | - tokenize=False, | |
| 39 | - add_generation_prompt=True, | |
| 94 | +images = ["path/to/image1.jpg", "path/to/image2.jpg"] | |
| 95 | +prompt = "Compare these two images." | |
| 96 | + | |
| 97 | +formatted_prompt = apply_chat_template( | |
| 98 | + processor, config, prompt, num_images=len(images) | |
| 40 | 99 | ) |
| 41 | 100 | |
| 42 | -output = generate(model, processor, "http://images.cocodataset.org/val2017/000000039769.jpg", prompt, verbose=False) | |
| 101 | +output = generate(model, processor, images, formatted_prompt, verbose=False) | |
| 102 | +print(output) | |
| 43 | 103 | ``` |
| 104 | + | |
| 105 | +#### Command Line | |
| 106 | + | |
| 107 | +```sh | |
| 108 | +python -m mlx_vlm.generate --model mlx-community/Qwen2-VL-2B-Instruct-4bit --max-tokens 100 --prompt "Compare these images" --image path/to/image1.jpg path/to/image2.jpg | |
| 109 | +``` | |
| 110 | + | |
| 111 | +These examples demonstrate how to use multiple images with MLX-VLM for more complex visual reasoning tasks. | |
| 112 | + | |
| 113 | +# Fine-tuning | |
| 114 | + | |
| 115 | +MLX-VLM supports fine-tuning models with LoRA and QLoRA. | |
| 116 | + | |
| 117 | +## LoRA & QLoRA | |
| 118 | + | |
| 119 | +To learn more about LoRA, please refer to the [LoRA.md](./mlx_vlm/LoRA.md) file. |
added mlx_vlm/LORA.MD +77 −0
| @@ -0,0 +1,77 @@ | ||
| 1 | +# LoRA Training Script | |
| 2 | + | |
| 3 | +## Overview | |
| 4 | + | |
| 5 | +`lora.py` is a Python script for fine-tuning a vision language models (VLMs) using Low-Rank Adaptation (LoRA or QLoRA). This script allows you to train the model on your custom dataset, adjusting various parameters through command-line arguments. | |
| 6 | + | |
| 7 | +## Requirements | |
| 8 | + | |
| 9 | +- Python 3.7+ | |
| 10 | +- Required Python packages: `mlx-vlm`, `numpy`, `transformers`, `datasets`, `PIL` | |
| 11 | + | |
| 12 | +## Supported Models | |
| 13 | +- Qwen2 | |
| 14 | +- LLaVA (except for LLaVA-Next) | |
| 15 | +- Pixtral | |
| 16 | +- Idefics 2 | |
| 17 | +- Deepseek-VL | |
| 18 | +- Paligemma | |
| 19 | + | |
| 20 | +## Coming Soon | |
| 21 | +- LLaVA-Next | |
| 22 | +- Phi3_vision | |
| 23 | + | |
| 24 | +## Usage | |
| 25 | + | |
| 26 | +To use the script, run it from the command line with the desired arguments: | |
| 27 | + | |
| 28 | +``` | |
| 29 | +python lora.py --dataset /path/to/your/dataset [other options] | |
| 30 | +``` | |
| 31 | + | |
| 32 | +## Dataset format | |
| 33 | + | |
| 34 | +The dataset should be a Hugging Face dataset with a `images` column and a `messages` column. | |
| 35 | + | |
| 36 | +``` | |
| 37 | +{ | |
| 38 | + "images": ..., | |
| 39 | + "messages": ..., | |
| 40 | +} | |
| 41 | +``` | |
| 42 | + | |
| 43 | +Support for other formats and column names will be added soon. | |
| 44 | + | |
| 45 | +## Arguments | |
| 46 | + | |
| 47 | +The script accepts the following command-line arguments: | |
| 48 | + | |
| 49 | +- `--model_path`: Path to the pre-trained model (default: "mlx-community/Qwen2-VL-2B-Instruct-bf16") | |
| 50 | +- `--dataset`: Path to your dataset (required) | |
| 51 | +- `--learning_rate`: Learning rate for the optimizer (default: 1e-4) | |
| 52 | +- `--batch_size`: Batch size for training (default: 1) | |
| 53 | +- `--epochs`: Number of epochs to train (default: 1) | |
| 54 | +- `--steps`: Number of steps per epoch (default: 0) | |
| 55 | +- `--print_every`: Print loss every n steps (default: 10) | |
| 56 | +- `--output_path`: Path to save the trained adapter (default: "adapters.safetensors") | |
| 57 | + | |
| 58 | +## Example | |
| 59 | + | |
| 60 | +Here's an example of how to run the script with custom parameters: | |
| 61 | + | |
| 62 | +``` | |
| 63 | +python lora.py --dataset /path/to/your/dataset --model_path /path/to/your/model --epochs 2 --batch_size 4 --learning_rate 5e-5 | |
| 64 | +``` | |
| 65 | + | |
| 66 | +## Output | |
| 67 | + | |
| 68 | +The script will print the training loss at regular intervals (defined by `--print_every`). After training, it will save the LoRA adapter to the specified output path. | |
| 69 | + | |
| 70 | +## Note | |
| 71 | + | |
| 72 | +If you want to use QLoRA, you need to pass a pre-quantized model to the script using the `--model_path` argument (i.e. `mlx-community/Qwen2-VL-2B-Instruct-4bit`). | |
| 73 | +Make sure you have the necessary permissions to read the dataset and write the output file. Also, ensure that your system has sufficient computational resources to handle the specified batch size and model. | |
| 74 | + | |
| 75 | +## Contributing | |
| 76 | + | |
| 77 | +Feel free to submit issues or pull requests if you find any bugs or have suggestions for improvements. |
modified mlx_vlm/__init__.py +2 −1
| @@ -1,2 +1,3 @@ | ||
| 1 | -from .utils import convert, generate, load | |
| 1 | +from .prompt_utils import apply_chat_template, get_message_json | |
| 2 | +from .utils import convert, generate, load, prepare_inputs | |
| 2 | 3 | from .version import __version__ |
modified mlx_vlm/generate.py +19 −8
| @@ -1,13 +1,11 @@ | ||
| 1 | 1 | import argparse |
| 2 | 2 | import codecs |
| 3 | 3 | |
| 4 | -import mlx.core as mx | |
| 5 | - | |
| 6 | 4 | from .prompt_utils import apply_chat_template |
| 7 | 5 | from .utils import generate, get_model_path, load, load_config, load_image_processor |
| 8 | 6 | |
| 9 | 7 | DEFAULT_MODEL_PATH = "mlx-community/nanoLLaVA-1.5-8bit" |
| 10 | -DEFAULT_IMAGE = "http://images.cocodataset.org/val2017/000000039769.jpg" | |
| 8 | +DEFAULT_IMAGE = ["http://images.cocodataset.org/val2017/000000039769.jpg"] | |
| 11 | 9 | DEFAULT_PROMPT = "What are these?" |
| 12 | 10 | DEFAULT_MAX_TOKENS = 100 |
| 13 | 11 | DEFAULT_TEMP = 0.5 |
| @@ -25,9 +23,16 @@ | ||
| 25 | 23 | default=DEFAULT_MODEL_PATH, |
| 26 | 24 | help="The path to the local model directory or Hugging Face repo.", |
| 27 | 25 | ) |
| 26 | + parser.add_argument( | |
| 27 | + "--adapter-path", | |
| 28 | + type=str, | |
| 29 | + default=None, | |
| 30 | + help="The path to the adapter weights.", | |
| 31 | + ) | |
| 28 | 32 | parser.add_argument( |
| 29 | 33 | "--image", |
| 30 | 34 | type=str, |
| 35 | + nargs="+", | |
| 31 | 36 | default=DEFAULT_IMAGE, |
| 32 | 37 | help="URL or path of the image to process.", |
| 33 | 38 | ) |
| @@ -50,22 +55,28 @@ | ||
| 50 | 55 | return parser.parse_args() |
| 51 | 56 | |
| 52 | 57 | |
| 53 | -def get_model_and_processors(model_path): | |
| 58 | +def get_model_and_processors(model_path, adapter_path): | |
| 54 | 59 | model_path = get_model_path(model_path) |
| 55 | 60 | config = load_config(model_path) |
| 56 | - model, processor = load(model_path, {"trust_remote_code": True}) | |
| 61 | + model, processor = load( | |
| 62 | + model_path, {"trust_remote_code": True}, adapter_path=adapter_path | |
| 63 | + ) | |
| 57 | 64 | image_processor = load_image_processor(model_path) |
| 58 | 65 | return model, processor, image_processor, config |
| 59 | 66 | |
| 60 | 67 | |
| 61 | 68 | def main(): |
| 62 | 69 | args = parse_arguments() |
| 63 | - model, processor, image_processor, config = get_model_and_processors(args.model) | |
| 70 | + if isinstance(args.image, str): | |
| 71 | + args.image = [args.image] | |
| 72 | + | |
| 73 | + model, processor, image_processor, config = get_model_and_processors( | |
| 74 | + args.model, args.adapter_path | |
| 75 | + ) | |
| 64 | 76 | |
| 65 | 77 | prompt = codecs.decode(args.prompt, "unicode_escape") |
| 66 | 78 | |
| 67 | - if model.config.model_type != "paligemma": | |
| 68 | - prompt = apply_chat_template(processor, config, prompt) | |
| 79 | + prompt = apply_chat_template(processor, config, prompt, num_images=len(args.image)) | |
| 69 | 80 | |
| 70 | 81 | output = generate( |
| 71 | 82 | model, |
added mlx_vlm/lora.py +169 −0
| @@ -0,0 +1,169 @@ | ||
| 1 | +import argparse | |
| 2 | +import json | |
| 3 | +import logging | |
| 4 | + | |
| 5 | +import mlx.optimizers as optim | |
| 6 | +from datasets import load_dataset | |
| 7 | +from tqdm import tqdm | |
| 8 | + | |
| 9 | +from .prompt_utils import apply_chat_template | |
| 10 | +from .trainer import Dataset, Trainer, save_adapter | |
| 11 | +from .trainer.utils import find_all_linear_names, get_peft_model | |
| 12 | +from .utils import load, load_image_processor | |
| 13 | + | |
| 14 | +logging.basicConfig(level=logging.INFO) | |
| 15 | +logger = logging.getLogger(__name__) | |
| 16 | + | |
| 17 | + | |
| 18 | +def custom_print(*args, **kwargs): | |
| 19 | + tqdm.write(" ".join(map(str, args)), **kwargs) | |
| 20 | + | |
| 21 | + | |
| 22 | +def main(args): | |
| 23 | + logger.info(f"\033[32mLoading model from {args.model_path}\033[0m") | |
| 24 | + model, processor = load( | |
| 25 | + args.model_path, processor_config={"trust_remote_code": True} | |
| 26 | + ) | |
| 27 | + config = model.config.__dict__ | |
| 28 | + image_processor = load_image_processor(args.model_path) | |
| 29 | + | |
| 30 | + logger.info(f"\033[32mLoading dataset from {args.dataset}\033[0m") | |
| 31 | + dataset = load_dataset(args.dataset, split=args.split) | |
| 32 | + | |
| 33 | + if "messages" not in dataset.column_names: | |
| 34 | + raise ValueError("Dataset must have a 'messages' column") | |
| 35 | + if "images" not in dataset.column_names: | |
| 36 | + raise ValueError("Dataset must have an 'images' column") | |
| 37 | + | |
| 38 | + if args.apply_chat_template: | |
| 39 | + logger.info(f"\033[32mApplying chat template to the dataset\033[0m") | |
| 40 | + | |
| 41 | + def process_data(examples): | |
| 42 | + if config["model_type"] == "pixtral": | |
| 43 | + conversations = apply_chat_template( | |
| 44 | + config=config, | |
| 45 | + processor=processor, | |
| 46 | + prompt=examples["messages"], | |
| 47 | + return_messages=True, | |
| 48 | + ) | |
| 49 | + examples["messages"] = [ | |
| 50 | + json.dumps(item, ensure_ascii=False) for item in conversations | |
| 51 | + ] | |
| 52 | + else: | |
| 53 | + examples["messages"] = apply_chat_template( | |
| 54 | + config=config, | |
| 55 | + processor=processor, | |
| 56 | + prompt=examples["messages"], | |
| 57 | + return_messages=True, | |
| 58 | + ) | |
| 59 | + return examples | |
| 60 | + | |
| 61 | + dataset = dataset.map(process_data) | |
| 62 | + | |
| 63 | + dataset = Dataset( | |
| 64 | + dataset, | |
| 65 | + config, | |
| 66 | + processor, | |
| 67 | + image_processor=image_processor, | |
| 68 | + ) | |
| 69 | + | |
| 70 | + logger.info(f"\033[32mSetting up LoRA\033[0m") | |
| 71 | + list_of_modules = find_all_linear_names(model.language_model) | |
| 72 | + model = get_peft_model( | |
| 73 | + model, | |
| 74 | + list_of_modules, | |
| 75 | + rank=args.lora_rank, | |
| 76 | + alpha=args.lora_alpha, | |
| 77 | + dropout=args.lora_dropout, | |
| 78 | + ) | |
| 79 | + | |
| 80 | + logger.info(f"\033[32mSetting up optimizer\033[0m") | |
| 81 | + optimizer = optim.Adam(learning_rate=args.learning_rate) | |
| 82 | + | |
| 83 | + logger.info(f"\033[32mSetting up trainer\033[0m") | |
| 84 | + trainer = Trainer(model, optimizer) | |
| 85 | + | |
| 86 | + model.train() | |
| 87 | + | |
| 88 | + # Training loop | |
| 89 | + logger.info(f"\033[32mTraining model\033[0m") | |
| 90 | + for epoch in range(args.epochs): | |
| 91 | + if args.steps == 0: | |
| 92 | + args.steps = len(dataset) // args.batch_size | |
| 93 | + | |
| 94 | + progress_bar = tqdm(range(args.steps), position=0, leave=True) | |
| 95 | + for i in progress_bar: | |
| 96 | + loss = trainer.train_step( | |
| 97 | + dataset[i * args.batch_size : (i + 1) * args.batch_size] | |
| 98 | + ) | |
| 99 | + # Update progress bar | |
| 100 | + progress_bar.update(1) | |
| 101 | + progress_bar.set_postfix( | |
| 102 | + {"Epoch": epoch, "Step": i, "Loss": f"{loss.item():.4f}"} | |
| 103 | + ) | |
| 104 | + | |
| 105 | + if i % args.print_every == 0: | |
| 106 | + # Log additional information | |
| 107 | + custom_print( | |
| 108 | + { | |
| 109 | + "Epoch": epoch, | |
| 110 | + "Step": i, | |
| 111 | + "Loss": f"{loss.item():.4f}", | |
| 112 | + } | |
| 113 | + ) | |
| 114 | + | |
| 115 | + # Save the adapter | |
| 116 | + save_adapter(model, args.output_path) | |
| 117 | + | |
| 118 | + | |
| 119 | +if __name__ == "__main__": | |
| 120 | + parser = argparse.ArgumentParser(description="Train NanoLLaVA model") | |
| 121 | + parser.add_argument( | |
| 122 | + "--model-path", | |
| 123 | + type=str, | |
| 124 | + default="mlx-community/Qwen2-VL-2B-Instruct-bf16", | |
| 125 | + help="Path to the pre-trained model", | |
| 126 | + ) | |
| 127 | + parser.add_argument( | |
| 128 | + "--dataset", type=str, required=True, help="Path to the dataset" | |
| 129 | + ) | |
| 130 | + parser.add_argument( | |
| 131 | + "--split", type=str, default="train", help="Split to use for training" | |
| 132 | + ) | |
| 133 | + parser.add_argument( | |
| 134 | + "--apply-chat-template", | |
| 135 | + action="store_false", | |
| 136 | + help="Apply chat template to the dataset", | |
| 137 | + ) | |
| 138 | + parser.add_argument( | |
| 139 | + "--learning-rate", | |
| 140 | + type=float, | |
| 141 | + default=1e-4, | |
| 142 | + help="Learning rate for the optimizer", | |
| 143 | + ) | |
| 144 | + parser.add_argument( | |
| 145 | + "--batch-size", type=int, default=1, help="Batch size for training" | |
| 146 | + ) | |
| 147 | + parser.add_argument( | |
| 148 | + "--epochs", type=int, default=1, help="Number of epochs to train" | |
| 149 | + ) | |
| 150 | + parser.add_argument( | |
| 151 | + "--steps", type=int, default=0, help="Number of steps per epoch" | |
| 152 | + ) | |
| 153 | + parser.add_argument( | |
| 154 | + "--print-every", type=int, default=10, help="Print loss every n steps" | |
| 155 | + ) | |
| 156 | + parser.add_argument( | |
| 157 | + "--lora-alpha", type=int, default=0.1, help="LoRA alpha parameter" | |
| 158 | + ) | |
| 159 | + parser.add_argument("--lora-rank", type=int, default=10, help="LoRA rank") | |
| 160 | + parser.add_argument("--lora-dropout", type=float, default=0.1, help="LoRA dropout") | |
| 161 | + parser.add_argument( | |
| 162 | + "--output-path", | |
| 163 | + type=str, | |
| 164 | + default="adapters", | |
| 165 | + help="Path to save the trained adapter", | |
| 166 | + ) | |
| 167 | + | |
| 168 | + args = parser.parse_args() | |
| 169 | + main(args) |
modified mlx_vlm/models/idefics2/idefics2.py +1 −0
| @@ -197,6 +197,7 @@ | ||
| 197 | 197 | |
| 198 | 198 | class Model(nn.Module): |
| 199 | 199 | def __init__(self, config: ModelConfig): |
| 200 | + super().__init__() | |
| 200 | 201 | self.model_type = config.model_type |
| 201 | 202 | self.config = config |
| 202 | 203 |
modified mlx_vlm/models/llava/language.py +17 −6
| @@ -21,6 +21,7 @@ | ||
| 21 | 21 | rope_theta: float = 10000 |
| 22 | 22 | rope_traditional: bool = False |
| 23 | 23 | rope_scaling: Optional[Dict[str, Union[float, str]]] = None |
| 24 | + tie_word_embeddings: bool = False | |
| 24 | 25 | |
| 25 | 26 | @classmethod |
| 26 | 27 | def from_dict(cls, params): |
| @@ -58,9 +59,14 @@ | ||
| 58 | 59 | head_dim = config.hidden_size // n_heads |
| 59 | 60 | self.scale = head_dim**-0.5 |
| 60 | 61 | |
| 61 | - self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=False) | |
| 62 | - self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False) | |
| 63 | - self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False) | |
| 62 | + if config.model_type == "qwen2": | |
| 63 | + attention_bias = True | |
| 64 | + else: | |
| 65 | + attention_bias = False | |
| 66 | + | |
| 67 | + self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=attention_bias) | |
| 68 | + self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=attention_bias) | |
| 69 | + self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=attention_bias) | |
| 64 | 70 | self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False) |
| 65 | 71 | |
| 66 | 72 | rope_scale = ( |
| @@ -184,12 +190,13 @@ | ||
| 184 | 190 | super().__init__() |
| 185 | 191 | self.config = config |
| 186 | 192 | self.model_type = config.model_type |
| 187 | - if self.model_type != "llama": | |
| 193 | + if self.model_type not in ["llama", "qwen2"]: | |
| 188 | 194 | raise ValueError( |
| 189 | 195 | f"Model type {self.model_type} not supported. Currently only 'llama' is supported" |
| 190 | 196 | ) |
| 191 | 197 | self.model = Llama(config) |
| 192 | - self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) | |
| 198 | + if not config.tie_word_embeddings: | |
| 199 | + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) | |
| 193 | 200 | |
| 194 | 201 | def __call__( |
| 195 | 202 | self, |
| @@ -199,7 +206,11 @@ | ||
| 199 | 206 | mask: Optional[mx.array] = None, |
| 200 | 207 | ): |
| 201 | 208 | out = self.model(inputs, cache, inputs_embeds) |
| 202 | - return self.lm_head(out) | |
| 209 | + if self.config.tie_word_embeddings: | |
| 210 | + out = self.model.embed_tokens.as_linear(out) | |
| 211 | + else: | |
| 212 | + out = self.lm_head(out) | |
| 213 | + return out | |
| 203 | 214 | |
| 204 | 215 | @staticmethod |
| 205 | 216 | def sanitize(weights): |
modified mlx_vlm/models/llava/llava.py +1 −0
| @@ -56,6 +56,7 @@ | ||
| 56 | 56 | |
| 57 | 57 | class Model(nn.Module): |
| 58 | 58 | def __init__(self, config: ModelConfig): |
| 59 | + super().__init__() | |
| 59 | 60 | self.config = config |
| 60 | 61 | self.vision_tower = VisionModel(config.vision_config) |
| 61 | 62 | self.language_model = LanguageModel(config.text_config) |
modified mlx_vlm/models/llava/vision.py +27 −11
| @@ -151,31 +151,44 @@ | ||
| 151 | 151 | self.image_size = config.image_size |
| 152 | 152 | self.patch_size = config.patch_size |
| 153 | 153 | |
| 154 | - self.class_embedding = mx.zeros((config.hidden_size,)) | |
| 154 | + if config.model_type == "siglip_vision_model": | |
| 155 | + bias = True | |
| 156 | + self.class_embedding = None | |
| 157 | + else: | |
| 158 | + bias = False | |
| 159 | + self.class_embedding = mx.zeros((config.hidden_size,)) | |
| 155 | 160 | |
| 156 | 161 | self.patch_embedding = nn.Conv2d( |
| 157 | 162 | in_channels=config.num_channels, |
| 158 | 163 | out_channels=self.embed_dim, |
| 159 | 164 | kernel_size=self.patch_size, |
| 160 | 165 | stride=self.patch_size, |
| 161 | - bias=False, | |
| 166 | + bias=bias, | |
| 162 | 167 | ) |
| 163 | 168 | |
| 164 | 169 | self.num_patches = (self.image_size // self.patch_size) ** 2 |
| 165 | - self.num_positions = self.num_patches + 1 | |
| 170 | + self.num_positions = ( | |
| 171 | + self.num_patches + 1 | |
| 172 | + if config.model_type == "clip_vision_model" | |
| 173 | + else self.num_patches | |
| 174 | + ) | |
| 166 | 175 | self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim) |
| 167 | 176 | |
| 168 | 177 | def __call__(self, x: mx.array) -> mx.array: |
| 169 | 178 | batch_size = x.shape[0] |
| 170 | 179 | patch_embeddings = self.patch_embedding(x) |
| 171 | 180 | patch_embeddings = mx.flatten(patch_embeddings, start_axis=1, end_axis=2) |
| 172 | - embed_dim = patch_embeddings.shape[-1] | |
| 173 | - cls_embeddings = mx.broadcast_to( | |
| 174 | - self.class_embedding, (batch_size, 1, embed_dim) | |
| 175 | - ) | |
| 181 | + if self.config.model_type == "siglip_vision_model": | |
| 182 | + embeddings = patch_embeddings | |
| 183 | + else: | |
| 184 | + embed_dim = patch_embeddings.shape[-1] | |
| 185 | + cls_embeddings = mx.broadcast_to( | |
| 186 | + self.class_embedding, (batch_size, 1, embed_dim) | |
| 187 | + ) | |
| 188 | + embeddings = mx.concatenate((cls_embeddings, patch_embeddings), axis=1) | |
| 189 | + | |
| 176 | 190 | position_ids = mx.array(np.arange(self.num_positions)[None, :]) |
| 177 | 191 | |
| 178 | - embeddings = mx.concatenate((cls_embeddings, patch_embeddings), axis=1) | |
| 179 | 192 | embeddings += self.position_embedding(position_ids) |
| 180 | 193 | return embeddings |
| 181 | 194 | |
| @@ -183,8 +196,10 @@ | ||
| 183 | 196 | class ClipVisionModel(nn.Module): |
| 184 | 197 | def __init__(self, config: VisionConfig): |
| 185 | 198 | super().__init__() |
| 199 | + self.config = config | |
| 186 | 200 | self.embeddings = VisionEmbeddings(config) |
| 187 | - self.pre_layrnorm = nn.LayerNorm(config.hidden_size) | |
| 201 | + if self.config.model_type == "clip_vision_model": | |
| 202 | + self.pre_layrnorm = nn.LayerNorm(config.hidden_size) | |
| 188 | 203 | self.encoder = Encoder(config) |
| 189 | 204 | self.post_layernorm = nn.LayerNorm(config.hidden_size) |
| 190 | 205 | |
| @@ -194,7 +209,8 @@ | ||
| 194 | 209 | output_hidden_states: Optional[bool] = None, |
| 195 | 210 | ) -> mx.array: |
| 196 | 211 | x = self.embeddings(x) |
| 197 | - x = self.pre_layrnorm(x) | |
| 212 | + if self.config.model_type == "clip_vision_model": | |
| 213 | + x = self.pre_layrnorm(x) | |
| 198 | 214 | |
| 199 | 215 | encoder_states = (x,) if output_hidden_states else None |
| 200 | 216 | |
| @@ -212,7 +228,7 @@ | ||
| 212 | 228 | super().__init__() |
| 213 | 229 | |
| 214 | 230 | self.model_type = config.model_type |
| 215 | - if self.model_type != "clip_vision_model": | |
| 231 | + if self.model_type not in ["clip_vision_model", "siglip_vision_model"]: | |
| 216 | 232 | raise ValueError(f"Unsupported model type: {self.model_type}") |
| 217 | 233 | |
| 218 | 234 | self.vision_model = ClipVisionModel(config) |
modified mlx_vlm/models/llava_bunny/language.py +2 −1
| @@ -167,6 +167,7 @@ | ||
| 167 | 167 | inputs: mx.array, |
| 168 | 168 | cache=None, |
| 169 | 169 | inputs_embeds: Optional[mx.array] = None, |
| 170 | + mask: Optional[mx.array] = None, | |
| 170 | 171 | ): |
| 171 | 172 | # for passing merged input embeddings |
| 172 | 173 | if inputs_embeds is None: |
| @@ -199,7 +200,7 @@ | ||
| 199 | 200 | inputs_embeds: Optional[mx.array] = None, |
| 200 | 201 | mask: Optional[mx.array] = None, |
| 201 | 202 | ): |
| 202 | - out = self.model(inputs, cache=cache, inputs_embeds=inputs_embeds) | |
| 203 | + out = self.model(inputs, cache=cache, inputs_embeds=inputs_embeds, mask=None) | |
| 203 | 204 | return out |
| 204 | 205 | |
| 205 | 206 | def sanitize(self, weights): |
modified mlx_vlm/models/llava_bunny/llava_bunny.py +18 −20
| @@ -118,6 +118,7 @@ | ||
| 118 | 118 | |
| 119 | 119 | class Model(nn.Module): |
| 120 | 120 | def __init__(self, config: ModelConfig): |
| 121 | + super().__init__() | |
| 121 | 122 | self.model_type = config.model_type |
| 122 | 123 | self.config = config |
| 123 | 124 | |
| @@ -151,31 +152,28 @@ | ||
| 151 | 152 | |
| 152 | 153 | def _prepare_inputs_for_multimodal(self, image_features, inputs_embeds, input_ids): |
| 153 | 154 | image_token_index = self.config.image_token_index |
| 154 | - num_images, num_image_patches, embed_dim = image_features.shape | |
| 155 | + batch_size, seq_length, embed_dim = inputs_embeds.shape | |
| 156 | + num_images, num_image_patches, _ = image_features.shape | |
| 155 | 157 | |
| 156 | - # Positions of <image> tokens in input_ids, assuming batch size is 1 | |
| 157 | - image_positions = np.where(input_ids[0] == image_token_index)[0].tolist() | |
| 158 | + # Positions of <image> tokens in input_ids for each batch | |
| 159 | + image_positions = mx.argmax(input_ids == image_token_index, axis=1) | |
| 158 | 160 | |
| 159 | - if len(image_positions) != num_images: | |
| 160 | - raise ValueError( | |
| 161 | - f"The number of image tokens ({len(image_positions)}) does not " | |
| 162 | - f" match the number of image inputs ({num_images})." | |
| 163 | - ) | |
| 161 | + final_embeddings = [] | |
| 162 | + for b in range(batch_size): | |
| 163 | + text_segments = [] | |
| 164 | + start_idx = 0 | |
| 165 | + position = int(image_positions[b].item()) | |
| 164 | 166 | |
| 165 | - text_segments = [] | |
| 166 | - start_idx = 0 | |
| 167 | + text_segments.append(inputs_embeds[b : b + 1, start_idx:position]) | |
| 168 | + text_segments.append(image_features[b : b + 1]) | |
| 169 | + text_segments.append(inputs_embeds[b : b + 1, position + 1 :]) | |
| 167 | 170 | |
| 168 | - for position in image_positions: | |
| 169 | - text_segments.append(inputs_embeds[:, start_idx:position]) | |
| 170 | - start_idx = position + 1 | |
| 171 | - | |
| 172 | - image_embeddings = mx.split(image_features, image_features.shape[0]) | |
| 173 | - final_embeddings = [v for p in zip(text_segments, image_embeddings) for v in p] | |
| 174 | - final_embeddings += [inputs_embeds[:, start_idx:]] | |
| 171 | + batch_embeddings = mx.concatenate(text_segments, axis=1) | |
| 172 | + final_embeddings.append(batch_embeddings) | |
| 175 | 173 | |
| 176 | 174 | # Create a final embedding of shape |
| 177 | - # (1, num_image_patches*num_images + sequence_len, embed_dim) | |
| 178 | - return mx.concatenate(final_embeddings, axis=1) | |
| 175 | + # (batch_size, num_image_patches + sequence_len, embed_dim) | |
| 176 | + return mx.concatenate(final_embeddings, axis=0) | |
| 179 | 177 | |
| 180 | 178 | def __call__( |
| 181 | 179 | self, |
| @@ -187,7 +185,7 @@ | ||
| 187 | 185 | ): |
| 188 | 186 | input_embeddings = self.get_input_embeddings(input_ids, pixel_values) |
| 189 | 187 | logits = self.language_model( |
| 190 | - inputs=input_ids, cache=cache, inputs_embeds=input_embeddings | |
| 188 | + inputs=input_ids, cache=cache, inputs_embeds=input_embeddings, mask=mask | |
| 191 | 189 | ) |
| 192 | 190 | return logits |
| 193 | 191 |
modified mlx_vlm/models/llava_bunny/vision.py +2 −2
| @@ -207,9 +207,9 @@ | ||
| 207 | 207 | batch_size = x.shape[0] |
| 208 | 208 | patch_embeddings = self.patch_embedding(x) |
| 209 | 209 | patch_embeddings = mx.flatten(patch_embeddings, start_axis=1, end_axis=2) |
| 210 | - self.position_ids = mx.array(np.arange(self.num_positions)[None, :]) | |
| 210 | + position_ids = mx.array(np.arange(self.num_positions)[None, :]) | |
| 211 | 211 | embeddings = patch_embeddings |
| 212 | - embeddings += self.position_embedding(self.position_ids) | |
| 212 | + embeddings += self.position_embedding(position_ids) | |
| 213 | 213 | return embeddings |
| 214 | 214 | |
| 215 | 215 |
modified mlx_vlm/models/llava_next/llava_next.py +1 −0
| @@ -56,6 +56,7 @@ | ||
| 56 | 56 | |
| 57 | 57 | class Model(nn.Module): |
| 58 | 58 | def __init__(self, config: ModelConfig): |
| 59 | + super().__init__() | |
| 59 | 60 | self.config = config |
| 60 | 61 | self.vision_tower = VisionModel(config.vision_config) |
| 61 | 62 | self.language_model = LanguageModel(config.text_config) |
modified mlx_vlm/models/multi_modality/multi_modality.py +1 −0
| @@ -238,6 +238,7 @@ | ||
| 238 | 238 | |
| 239 | 239 | class Model(nn.Module): |
| 240 | 240 | def __init__(self, config: ModelConfig): |
| 241 | + super().__init__() | |
| 241 | 242 | self.config = config |
| 242 | 243 | self.vision_model = VisionModel(config.vision_config) |
| 243 | 244 | self.language_model = LanguageModel(config.text_config) |
modified mlx_vlm/models/paligemma/paligemma.py +1 −0
| @@ -52,6 +52,7 @@ | ||
| 52 | 52 | |
| 53 | 53 | class Model(nn.Module): |
| 54 | 54 | def __init__(self, config: ModelConfig): |
| 55 | + super().__init__() | |
| 55 | 56 | self.model_type = config.model_type |
| 56 | 57 | self.config = config |
| 57 | 58 |
modified mlx_vlm/models/phi3_v/phi3_v.py +2 −1
| @@ -209,9 +209,10 @@ | ||
| 209 | 209 | pixel_values=None, |
| 210 | 210 | mask=None, |
| 211 | 211 | cache=None, |
| 212 | + image_sizes=None, | |
| 212 | 213 | **kwargs, |
| 213 | 214 | ): |
| 214 | - out = self.model(inputs, pixel_values, mask, cache) | |
| 215 | + out = self.model(inputs, pixel_values, image_sizes, cache) | |
| 215 | 216 | return self.lm_head(out).astype(self.lm_head.weight.dtype) |
| 216 | 217 | |
| 217 | 218 | @property |
modified mlx_vlm/models/pixtral/pixtral.py +25 −14
| @@ -56,6 +56,7 @@ | ||
| 56 | 56 | |
| 57 | 57 | class Model(nn.Module): |
| 58 | 58 | def __init__(self, config: ModelConfig): |
| 59 | + super().__init__() | |
| 59 | 60 | self.config = config |
| 60 | 61 | self.vision_tower = VisionModel(config.vision_config) |
| 61 | 62 | self.language_model = LanguageModel(config.text_config) |
| @@ -74,24 +75,33 @@ | ||
| 74 | 75 | # Get the input embeddings from the language model |
| 75 | 76 | inputs_embeds = self.language_model.model.embed_tokens(input_ids) |
| 76 | 77 | |
| 78 | + # Get number of images | |
| 79 | + num_images = len(pixel_values[0]) | |
| 80 | + | |
| 77 | 81 | # Get the ouptut hidden states from the vision model |
| 82 | + if isinstance(pixel_values, list): | |
| 83 | + if input_ids.shape[0] == 1: # Batch size is 1 | |
| 84 | + pixel_values = mx.concatenate( | |
| 85 | + [mx.array(pv) for pv in pixel_values[0]], axis=1 | |
| 86 | + )[None, ...] | |
| 87 | + else: # Batch size is greater than 1 | |
| 88 | + pixel_values = mx.concatenate( | |
| 89 | + [mx.array(pv) for pv in pixel_values], axis=0 | |
| 90 | + ) | |
| 91 | + if pixel_values.ndim == 3: | |
| 92 | + pixel_values = pixel_values[None, ...] | |
| 93 | + | |
| 94 | + pixel_values = mx.split(pixel_values, num_images, axis=2) | |
| 95 | + | |
| 96 | + # Pass pixel_values as list of images, as each image is individually run through conv2d and position encoding | |
| 97 | + # Reference code from transformers: https://github.com/huggingface/transformers/blob/main/src/transformers/models/pixtral/modeling_pixtral.py#L479C9-L479C21 | |
| 98 | + # and mistral_inference: https://github.com/mistralai/mistral-inference/blob/main/src/mistral_inference/vision_encoder.py#L85 | |
| 78 | 99 | *_, hidden_states = self.vision_tower( |
| 79 | - pixel_values.transpose(0, 2, 3, 1), output_hidden_states=True | |
| 100 | + [pv.transpose(0, 2, 3, 1) for pv in pixel_values], output_hidden_states=True | |
| 80 | 101 | ) |
| 81 | - | |
| 82 | 102 | # Select the hidden states from the desired layer |
| 83 | 103 | selected_image_feature = hidden_states[self.vision_feature_layer] |
| 84 | 104 | |
| 85 | - if self.vision_feature_select_strategy == "default": | |
| 86 | - selected_image_feature = selected_image_feature[:, 1:] | |
| 87 | - elif self.vision_feature_select_strategy == "full": | |
| 88 | - selected_image_feature = selected_image_feature | |
| 89 | - else: | |
| 90 | - raise ValueError( | |
| 91 | - "Unexpected feature selection strategy: " | |
| 92 | - f"{self.vision_feature_select_strategy}" | |
| 93 | - ) | |
| 94 | - | |
| 95 | 105 | # Pass image features through the multi-modal projector |
| 96 | 106 | image_features = self.multi_modal_projector(selected_image_feature) |
| 97 | 107 | |
| @@ -117,7 +127,8 @@ | ||
| 117 | 127 | text_segments.append(inputs_embeds[:, start_idx:position]) |
| 118 | 128 | start_idx = position + 1 |
| 119 | 129 | |
| 120 | - image_embeddings = mx.split(image_features, image_features.shape[0]) | |
| 130 | + # Split image features into separate embeddings for each image | |
| 131 | + image_embeddings = mx.split(image_features, num_image_patches, axis=1) | |
| 121 | 132 | final_embeddings = [v for p in zip(text_segments, image_embeddings) for v in p] |
| 122 | 133 | final_embeddings += [inputs_embeds[:, start_idx:]] |
| 123 | 134 | |
| @@ -181,7 +192,7 @@ | ||
| 181 | 192 | |
| 182 | 193 | def sanitize(self, weights): |
| 183 | 194 | def transform_key(key): |
| 184 | - if "vision_tower" in key: | |
| 195 | + if "vision_tower" in key and "vision_model" not in key: | |
| 185 | 196 | if "transformer" in key: |
| 186 | 197 | key = key.replace("vision_tower", "vision_tower.vision_model") |
| 187 | 198 | if "patch_conv" in key: |
modified mlx_vlm/models/pixtral/vision.py +5 −5
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | import inspect |
| 2 | 2 | from dataclasses import dataclass |
| 3 | -from typing import Optional | |
| 3 | +from typing import List, Optional | |
| 4 | 4 | |
| 5 | 5 | import mlx.core as mx |
| 6 | 6 | import mlx.nn as nn |
| @@ -253,11 +253,11 @@ | ||
| 253 | 253 | |
| 254 | 254 | def __call__( |
| 255 | 255 | self, |
| 256 | - x: mx.array, | |
| 256 | + x: List[mx.array], | |
| 257 | 257 | output_hidden_states: Optional[bool] = None, |
| 258 | 258 | ) -> mx.array: |
| 259 | - B, H, W, C = x.shape | |
| 260 | - patch_embeds_list = [self.patch_conv(img[None, :]) for img in x] | |
| 259 | + B, H, W, C = x[0].shape | |
| 260 | + patch_embeds_list = [self.patch_conv(img) for img in x] | |
| 261 | 261 | |
| 262 | 262 | patch_embeds = mx.concatenate( |
| 263 | 263 | [p.reshape(B, -1, p.shape[-1]) for p in patch_embeds_list], axis=1 |
| @@ -299,7 +299,7 @@ | ||
| 299 | 299 | self.vision_model = PixtralVisionModel(config) |
| 300 | 300 | |
| 301 | 301 | def __call__( |
| 302 | - self, x: mx.array, output_hidden_states: Optional[bool] = None | |
| 302 | + self, x: List[mx.array], output_hidden_states: Optional[bool] = None | |
| 303 | 303 | ) -> mx.array: |
| 304 | 304 | return self.vision_model(x, output_hidden_states) |
| 305 | 305 |
modified mlx_vlm/models/qwen2_vl/language.py +4 −0
| @@ -282,6 +282,10 @@ | ||
| 282 | 282 | self.args = args |
| 283 | 283 | self.model_type = args.model_type |
| 284 | 284 | self.model = Qwen2Model(args) |
| 285 | + | |
| 286 | + if args.model_type != "qwen2_vl": | |
| 287 | + raise ValueError(f"Unsupported model type: {args.model_type}") | |
| 288 | + | |
| 285 | 289 | if not args.tie_word_embeddings: |
| 286 | 290 | self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False) |
| 287 | 291 |
modified mlx_vlm/models/qwen2_vl/qwen2_vl.py +4 −1
| @@ -18,7 +18,6 @@ | ||
| 18 | 18 | class ModelConfig: |
| 19 | 19 | text_config: TextConfig |
| 20 | 20 | vision_config: VisionConfig |
| 21 | - rope_scaling: dict | |
| 22 | 21 | model_type: str |
| 23 | 22 | ignore_index: int = -100 |
| 24 | 23 | image_token_index: int = 151655 |
| @@ -39,6 +38,7 @@ | ||
| 39 | 38 | |
| 40 | 39 | class Model(nn.Module): |
| 41 | 40 | def __init__(self, config: ModelConfig): |
| 41 | + super().__init__() | |
| 42 | 42 | self.config = config |
| 43 | 43 | self.vision_tower = VisionModel(config.vision_config) |
| 44 | 44 | self.language_model = LanguageModel(config.text_config) |
| @@ -61,6 +61,9 @@ | ||
| 61 | 61 | pixel_values, image_grid_thw, output_hidden_states=False |
| 62 | 62 | ) |
| 63 | 63 | |
| 64 | + if hidden_states.ndim == 2: | |
| 65 | + hidden_states = hidden_states[None, :, :] | |
| 66 | + | |
| 64 | 67 | # Insert special image tokens in the input_ids |
| 65 | 68 | final_inputs_embeds = self._merge_input_ids_with_image_features( |
| 66 | 69 | hidden_states, inputs_embeds, input_ids |
modified mlx_vlm/models/qwen2_vl/vision.py +14 −2
| @@ -19,7 +19,7 @@ | ||
| 19 | 19 | mlp_ratio: float = 4.0 |
| 20 | 20 | in_channels: int = 3 |
| 21 | 21 | layer_norm_eps: float = 1e-6 |
| 22 | - spatial_patch_size = 14 | |
| 22 | + spatial_patch_size: int = 14 | |
| 23 | 23 | spatial_merge_size: int = 2 |
| 24 | 24 | temporal_patch_size: int = 2 |
| 25 | 25 | |
| @@ -320,10 +320,22 @@ | ||
| 320 | 320 | grid_thw: mx.array, |
| 321 | 321 | output_hidden_states: Optional[bool] = None, |
| 322 | 322 | ) -> mx.array: |
| 323 | + | |
| 323 | 324 | hidden_states = self.patch_embed(hidden_states) |
| 324 | 325 | rotary_pos_emb = self.rot_pos_emb(grid_thw) |
| 325 | 326 | |
| 326 | - cu_seqlens = mx.repeat(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]) | |
| 327 | + # Assuming grid_thw has shape (batch_size, 3) | |
| 328 | + batch_size = grid_thw.shape[0] | |
| 329 | + | |
| 330 | + # Calculate cu_seqlens for each item in the batch | |
| 331 | + cu_seqlens = [] | |
| 332 | + for i in range(batch_size): | |
| 333 | + seq_len = grid_thw[i, 1] * grid_thw[i, 2] | |
| 334 | + cu_seqlens.append(mx.repeat(seq_len, grid_thw[i, 0])) | |
| 335 | + | |
| 336 | + # Concatenate the cu_seqlens for all items in the batch | |
| 337 | + cu_seqlens = mx.concatenate(cu_seqlens) | |
| 338 | + | |
| 327 | 339 | cu_seqlens = mx.cumsum(cu_seqlens.astype(mx.int32)) |
| 328 | 340 | cu_seqlens = mx.pad(cu_seqlens, (1, 0), mode="constant", constant_values=0) |
| 329 | 341 |
modified mlx_vlm/prompt_utils.py +124 −29
| @@ -1,56 +1,151 @@ | ||
| 1 | -def get_message_json(model_name, prompt): | |
| 1 | +def get_message_json( | |
| 2 | + model_name, prompt, role="user", skip_image_token=False, num_images=1 | |
| 3 | +): | |
| 2 | 4 | """ |
| 3 | 5 | Get the appropriate JSON message based on the specified model. |
| 4 | 6 | |
| 5 | 7 | Args: |
| 6 | 8 | model_name (str): The model for which to generate the message. |
| 7 | 9 | prompt (str): The text prompt to be included in the message. |
| 8 | - *args: Additional positional arguments (unused). | |
| 9 | - **kwargs: Additional keyword arguments (unused). | |
| 10 | + role (str): The role of the message (default: "user"). | |
| 11 | + skip_image_token (bool): Whether to skip adding image tokens (default: False). | |
| 12 | + num_images (int): Number of image tokens to add (default: 1). | |
| 10 | 13 | |
| 11 | 14 | Returns: |
| 12 | 15 | dict: A dictionary representing the JSON message for the specified model. |
| 13 | 16 | """ |
| 14 | - if model_name.lower() in ["idefics2", "qwen2_vl", "llava"]: | |
| 15 | - message = { | |
| 16 | - "role": "user", | |
| 17 | - "content": [{"type": "image"}, {"type": "text", "text": prompt}], | |
| 18 | - } | |
| 19 | - | |
| 20 | - elif model_name.lower() in ["llava-qwen2", "llava_next", "bunny-llama"]: | |
| 21 | - message = {"role": "user", "content": f"<image>\n{prompt}"} | |
| 22 | - elif model_name.lower() == "phi3_v": | |
| 23 | - message = {"role": "user", "content": f"<|image_1|>\n{prompt}"} | |
| 24 | - elif model_name.lower() == "multi_modality": | |
| 25 | - message = {"role": "user", "content": f"<image>{prompt}"} | |
| 26 | - elif model_name.lower() == "paligemma": | |
| 27 | - message = prompt | |
| 28 | - elif model_name.lower() == "pixtral": | |
| 29 | - message = { | |
| 30 | - "role": "user", | |
| 31 | - "content": [{"type": "image"}, {"type": "text", "content": prompt}], | |
| 32 | - } | |
| 17 | + model_name = model_name.lower() | |
| 18 | + | |
| 19 | + def create_message(role, prompt): | |
| 20 | + return {"role": role, "content": prompt} | |
| 21 | + | |
| 22 | + def add_image_tokens(message, token_format): | |
| 23 | + if role == "user" and not skip_image_token: | |
| 24 | + if isinstance(message["content"], list): | |
| 25 | + message["content"].extend([{"type": "image"}] * num_images) | |
| 26 | + else: | |
| 27 | + if model_name == "phi3_v": | |
| 28 | + message["content"] = f"{token_format}{message['content']}" | |
| 29 | + else: | |
| 30 | + message["content"] = ( | |
| 31 | + f"{token_format * num_images}{message['content']}" | |
| 32 | + ) | |
| 33 | + if role == "assistant" and model_name == "pixtral": | |
| 34 | + message["content"] = message["content"][0]["content"] | |
| 35 | + return message | |
| 36 | + | |
| 37 | + message_formats = { | |
| 38 | + "message_list_with_image": lambda: add_image_tokens( | |
| 39 | + {"role": role, "content": [{"type": "text", "text": prompt}]}, "" | |
| 40 | + ), | |
| 41 | + "message_list_with_image_type": lambda: add_image_tokens( | |
| 42 | + {"role": role, "content": [{"type": "text", "content": prompt}]}, "" | |
| 43 | + ), | |
| 44 | + "message_with_image_token": lambda: add_image_tokens( | |
| 45 | + create_message(role, prompt), "<image>" | |
| 46 | + ), | |
| 47 | + "message_with_image_token_new_line": lambda: add_image_tokens( | |
| 48 | + create_message(role, prompt), "<image>\n" | |
| 49 | + ), | |
| 50 | + "message_with_numbered_image_tokens": lambda: add_image_tokens( | |
| 51 | + create_message(role, prompt), | |
| 52 | + " ".join([f"<|image_{i+1}|>" for i in range(num_images)]), | |
| 53 | + ), | |
| 54 | + "prompt_only": lambda: prompt, | |
| 55 | + } | |
| 56 | + | |
| 57 | + model_to_format = { | |
| 58 | + "idefics2": "message_list_with_image", | |
| 59 | + "qwen2_vl": "message_list_with_image", | |
| 60 | + "llava": "message_list_with_image", | |
| 61 | + "llava_next": "message_list_with_image", | |
| 62 | + "llava-qwen2": "message_with_image_token_new_line", | |
| 63 | + "bunny-llama": "message_with_image_token_new_line", | |
| 64 | + "phi3_v": "message_with_numbered_image_tokens", | |
| 65 | + "multi_modality": "message_with_image_token", | |
| 66 | + "pixtral": "message_list_with_image_type", | |
| 67 | + "paligemma": "prompt_only", | |
| 68 | + } | |
| 69 | + | |
| 70 | + if num_images > 1 and model_name in [ | |
| 71 | + "llava_next", | |
| 72 | + "llava-qwen2", | |
| 73 | + "bunny-llama", | |
| 74 | + "paligemma", | |
| 75 | + "multi_modality", | |
| 76 | + ]: | |
| 77 | + raise ValueError( | |
| 78 | + f"Model {model_name} does not support multi-image chat. Please only use 1 image." | |
| 79 | + ) | |
| 80 | + | |
| 81 | + format_key = model_to_format.get(model_name) | |
| 82 | + if format_key: | |
| 83 | + return message_formats[format_key]() | |
| 33 | 84 | else: |
| 34 | 85 | raise ValueError(f"Unsupported model: {model_name}") |
| 35 | 86 | |
| 36 | - return message | |
| 37 | 87 | |
| 88 | +def apply_chat_template( | |
| 89 | + processor, | |
| 90 | + config, | |
| 91 | + prompt, | |
| 92 | + add_generation_prompt=True, | |
| 93 | + return_messages=False, | |
| 94 | + num_images=1, | |
| 95 | +): | |
| 96 | + config = config if isinstance(config, dict) else config.__dict__ | |
| 97 | + | |
| 98 | + def process_single_prompt(p, is_first=True): | |
| 99 | + if isinstance(p, str): | |
| 100 | + return get_message_json( | |
| 101 | + config["model_type"], | |
| 102 | + p, | |
| 103 | + skip_image_token=not is_first, | |
| 104 | + num_images=num_images, | |
| 105 | + ) | |
| 106 | + elif isinstance(p, dict) and "role" in p: | |
| 107 | + return get_message_json( | |
| 108 | + config["model_type"], | |
| 109 | + p["content"], | |
| 110 | + p["role"], | |
| 111 | + skip_image_token=not is_first, | |
| 112 | + num_images=num_images, | |
| 113 | + ) | |
| 114 | + else: | |
| 115 | + raise ValueError("Invalid prompt type") | |
| 116 | + | |
| 117 | + messages = [] | |
| 118 | + if isinstance(prompt, list): | |
| 119 | + if isinstance(prompt[0], dict): | |
| 120 | + messages = [process_single_prompt(p, i == 0) for i, p in enumerate(prompt)] | |
| 121 | + else: | |
| 122 | + messages = [ | |
| 123 | + msg | |
| 124 | + for prompts in prompt | |
| 125 | + for i, p in enumerate(prompts) | |
| 126 | + for msg in [process_single_prompt(p, i == 0)] | |
| 127 | + ] | |
| 128 | + else: | |
| 129 | + messages = [process_single_prompt(prompt)] | |
| 130 | + | |
| 131 | + if return_messages: | |
| 132 | + return messages | |
| 38 | 133 | |
| 39 | -def apply_chat_template(processor, config, prompt): | |
| 40 | - message = get_message_json(config["model_type"], prompt) | |
| 134 | + if config["model_type"] == "paligemma": | |
| 135 | + return messages[-1] | |
| 41 | 136 | |
| 42 | 137 | if "chat_template" in processor.__dict__.keys(): |
| 43 | 138 | return processor.apply_chat_template( |
| 44 | - [message], | |
| 139 | + messages, | |
| 45 | 140 | tokenize=False, |
| 46 | - add_generation_prompt=True, | |
| 141 | + add_generation_prompt=add_generation_prompt, | |
| 47 | 142 | ) |
| 48 | 143 | |
| 49 | 144 | elif "tokenizer" in processor.__dict__.keys(): |
| 50 | 145 | return processor.tokenizer.apply_chat_template( |
| 51 | - [message], | |
| 146 | + messages, | |
| 52 | 147 | tokenize=False, |
| 53 | - add_generation_prompt=True, | |
| 148 | + add_generation_prompt=add_generation_prompt, | |
| 54 | 149 | ) |
| 55 | 150 | |
| 56 | 151 | else: |
modified mlx_vlm/tests/test_models.py +44 −2
| @@ -62,7 +62,6 @@ | ||
| 62 | 62 | shape=(batch_size, image_size[0], image_size[1], num_channels) |
| 63 | 63 | ) |
| 64 | 64 | |
| 65 | - # Perform a forward pass | |
| 66 | 65 | hidden_states = vision_tower(input_tensor, output_hidden_states=True, **kwargs) |
| 67 | 66 | |
| 68 | 67 | # Check vision hidden feature layer's shape matches the expected hidden size |
| @@ -620,6 +619,50 @@ | ||
| 620 | 619 | (config.vision_config.image_size, config.vision_config.image_size), |
| 621 | 620 | ) |
| 622 | 621 | |
| 622 | + def test_pixtral(self): | |
| 623 | + from mlx_vlm.models import pixtral | |
| 624 | + | |
| 625 | + text_config = pixtral.TextConfig( | |
| 626 | + model_type="mistral", | |
| 627 | + hidden_size=4096, | |
| 628 | + num_hidden_layers=32, | |
| 629 | + intermediate_size=11008, | |
| 630 | + num_attention_heads=32, | |
| 631 | + rms_norm_eps=1e-5, | |
| 632 | + vocab_size=32000, | |
| 633 | + num_key_value_heads=32, | |
| 634 | + rope_theta=10000.0, | |
| 635 | + rope_traditional=False, | |
| 636 | + rope_scaling=None, | |
| 637 | + ) | |
| 638 | + | |
| 639 | + vision_config = pixtral.VisionConfig( | |
| 640 | + model_type="pixtral", | |
| 641 | + num_hidden_layers=24, | |
| 642 | + hidden_size=1024, | |
| 643 | + intermediate_size=4096, | |
| 644 | + num_attention_heads=16, | |
| 645 | + image_size=336, | |
| 646 | + patch_size=14, | |
| 647 | + projection_dim=768, | |
| 648 | + vocab_size=32000, | |
| 649 | + num_channels=3, | |
| 650 | + rms_norm_eps=1e-6, | |
| 651 | + ) | |
| 652 | + | |
| 653 | + config = pixtral.ModelConfig( | |
| 654 | + text_config=text_config, | |
| 655 | + vision_config=vision_config, | |
| 656 | + model_type="pixtral", | |
| 657 | + ignore_index=-100, | |
| 658 | + image_token_index=32000, | |
| 659 | + vocab_size=32000, | |
| 660 | + vision_feature_layer=-2, | |
| 661 | + vision_feature_select_strategy="default", | |
| 662 | + ) | |
| 663 | + | |
| 664 | + model = pixtral.Model(config) | |
| 665 | + | |
| 623 | 666 | def test_qwen2_vl(self): |
| 624 | 667 | from mlx_vlm.models import qwen2_vl |
| 625 | 668 | |
| @@ -656,7 +699,6 @@ | ||
| 656 | 699 | model_type="qwen2_vl", |
| 657 | 700 | text_config=text_config, |
| 658 | 701 | vision_config=vision_config, |
| 659 | - rope_scaling=text_config.rope_scaling, | |
| 660 | 702 | image_token_index=151655, |
| 661 | 703 | vocab_size=32000, |
| 662 | 704 | ) |
added mlx_vlm/tests/test_trainer.py +133 −0
| @@ -0,0 +1,133 @@ | ||
| 1 | +import unittest | |
| 2 | +from unittest.mock import MagicMock, patch | |
| 3 | + | |
| 4 | +import mlx.core as mx | |
| 5 | +import mlx.nn as nn | |
| 6 | + | |
| 7 | +from mlx_vlm.trainer.trainer import Dataset, Trainer, TrainingArgs | |
| 8 | +from mlx_vlm.utils import prepare_inputs | |
| 9 | + | |
| 10 | + | |
| 11 | +class TestDataset(unittest.TestCase): | |
| 12 | + def setUp(self): | |
| 13 | + self.mock_hf_dataset = MagicMock() | |
| 14 | + self.mock_config = {"model_type": "test_model", "image_token_index": 1} | |
| 15 | + self.mock_processor = MagicMock() | |
| 16 | + self.mock_image_processor = MagicMock() | |
| 17 | + | |
| 18 | + @patch("mlx_vlm.utils.prepare_inputs") | |
| 19 | + def test_dataset_initialization(self, mock_prepare_inputs): | |
| 20 | + dataset = Dataset( | |
| 21 | + self.mock_hf_dataset, | |
| 22 | + self.mock_config, | |
| 23 | + self.mock_processor, | |
| 24 | + self.mock_image_processor, | |
| 25 | + take=10, | |
| 26 | + split="train", | |
| 27 | + ) | |
| 28 | + | |
| 29 | + self.assertEqual(len(dataset), len(self.mock_hf_dataset["train"].take(10))) | |
| 30 | + self.assertEqual(dataset.config, self.mock_config) | |
| 31 | + self.assertEqual(dataset.processor, self.mock_processor) | |
| 32 | + self.assertEqual(dataset.image_processor, self.mock_image_processor) | |
| 33 | + | |
| 34 | + @patch("mlx_vlm.trainer.trainer.get_prompt") | |
| 35 | + @patch("mlx_vlm.utils.prepare_inputs") | |
| 36 | + def test_dataset_getitem(self, mock_prepare_inputs, mock_get_prompt): | |
| 37 | + dataset = Dataset( | |
| 38 | + self.mock_hf_dataset, | |
| 39 | + self.mock_config, | |
| 40 | + self.mock_processor, | |
| 41 | + self.mock_image_processor, | |
| 42 | + ) | |
| 43 | + | |
| 44 | + mock_item = { | |
| 45 | + "images": ["image1.jpg"], | |
| 46 | + "messages": [{"role": "user", "content": "Hello"}], | |
| 47 | + } | |
| 48 | + self.mock_hf_dataset.__getitem__.return_value = mock_item | |
| 49 | + | |
| 50 | + mock_get_prompt.return_value = "Mocked prompt" | |
| 51 | + | |
| 52 | + mock_prepare_inputs.return_value = ( | |
| 53 | + mx.array([1, 2, 3]), # input_ids | |
| 54 | + mx.array( | |
| 55 | + [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]] | |
| 56 | + ), # pixel_values | |
| 57 | + mx.array([1, 1, 1]), # mask | |
| 58 | + (1, 1, 1), # image_grid_thw | |
| 59 | + [224, 224], # image_sizes | |
| 60 | + ) | |
| 61 | + | |
| 62 | + result = dataset[0] | |
| 63 | + | |
| 64 | + mock_prepare_inputs.assert_called_once() | |
| 65 | + self.assertIn("pixel_values", result) | |
| 66 | + self.assertIn("input_ids", result) | |
| 67 | + self.assertIn("attention_mask", result) | |
| 68 | + self.assertIn("image_grid_thw", result) | |
| 69 | + self.assertIn("image_sizes", result) | |
| 70 | + | |
| 71 | + # Check if the returned values match the mocked input | |
| 72 | + self.assertTrue(mx.array_equal(result["input_ids"], mx.array([1, 2, 3]))) | |
| 73 | + self.assertTrue( | |
| 74 | + mx.array_equal( | |
| 75 | + result["pixel_values"], | |
| 76 | + mx.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]]), | |
| 77 | + ) | |
| 78 | + ) | |
| 79 | + self.assertTrue(mx.array_equal(result["attention_mask"], mx.array([1, 1, 1]))) | |
| 80 | + self.assertEqual(result["image_grid_thw"], (1, 1, 1)) | |
| 81 | + self.assertEqual(result["image_sizes"], [224, 224]) | |
| 82 | + | |
| 83 | + | |
| 84 | +class TestTrainer(unittest.TestCase): | |
| 85 | + def setUp(self): | |
| 86 | + self.mock_model = MagicMock(spec=nn.Module) | |
| 87 | + self.mock_optimizer = MagicMock() | |
| 88 | + self.trainer = Trainer(self.mock_model, self.mock_optimizer) | |
| 89 | + | |
| 90 | + def test_trainer_initialization(self): | |
| 91 | + self.assertEqual(self.trainer.model, self.mock_model) | |
| 92 | + self.assertEqual(self.trainer.optimizer, self.mock_optimizer) | |
| 93 | + self.assertFalse(self.trainer.train_on_completions) | |
| 94 | + self.assertEqual(self.trainer.assistant_id, 77091) | |
| 95 | + | |
| 96 | + @patch("mlx.nn.losses.cross_entropy") | |
| 97 | + def test_loss_fn(self, mock_cross_entropy): | |
| 98 | + batch = { | |
| 99 | + "pixel_values": mx.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]), | |
| 100 | + "input_ids": mx.array([[1, 2, 3], [4, 5, 6]]), | |
| 101 | + "attention_mask": mx.array([[1, 1, 1], [1, 1, 0]]), | |
| 102 | + "image_grid_thw": (1, 1, 1), | |
| 103 | + "image_sizes": [224, 224], | |
| 104 | + } | |
| 105 | + | |
| 106 | + self.mock_model.return_value = mx.array([[[0.1, 0.2, 0.3]], [[0.4, 0.5, 0.6]]]) | |
| 107 | + mock_cross_entropy.return_value = mx.array([[0.1, 0.2], [0.3, 0.4]]) | |
| 108 | + | |
| 109 | + loss = self.trainer.loss_fn(self.mock_model, batch) | |
| 110 | + | |
| 111 | + self.assertIsInstance(loss, mx.array) | |
| 112 | + self.assertEqual(loss.shape, ()) # Scalar value | |
| 113 | + | |
| 114 | + @patch.object(Trainer, "loss_fn") | |
| 115 | + @patch("mlx.nn.value_and_grad") | |
| 116 | + def test_train_step(self, mock_value_and_grad, mock_loss_fn): | |
| 117 | + mock_batch = MagicMock() | |
| 118 | + mock_loss = mx.array(0.5) | |
| 119 | + mock_grads = {"param1": mx.array([0.1, 0.2]), "param2": mx.array([0.3, 0.4])} | |
| 120 | + | |
| 121 | + mock_value_and_grad.return_value = lambda *args, **kwargs: ( | |
| 122 | + mock_loss, | |
| 123 | + mock_grads, | |
| 124 | + ) | |
| 125 | + | |
| 126 | + loss = self.trainer.train_step(mock_batch) | |
| 127 | + | |
| 128 | + self.mock_optimizer.update.assert_called_once_with(self.mock_model, mock_grads) | |
| 129 | + self.assertEqual(loss, mock_loss) | |
| 130 | + | |
| 131 | + | |
| 132 | +if __name__ == "__main__": | |
| 133 | + unittest.main() |
added mlx_vlm/tests/test_trainer_utils.py +59 −0
| @@ -0,0 +1,59 @@ | ||
| 1 | +import unittest | |
| 2 | +from unittest.mock import MagicMock, patch | |
| 3 | + | |
| 4 | +import mlx.nn as nn | |
| 5 | + | |
| 6 | +from mlx_vlm.trainer.utils import ( | |
| 7 | + find_all_linear_names, | |
| 8 | + get_module_by_name, | |
| 9 | + get_peft_model, | |
| 10 | + set_module_by_name, | |
| 11 | +) | |
| 12 | + | |
| 13 | + | |
| 14 | +class TestTrainerUtils(unittest.TestCase): | |
| 15 | + | |
| 16 | + def test_get_module_by_name(self): | |
| 17 | + model = MagicMock() | |
| 18 | + model.layer1.layer2.layer3 = "test_module" | |
| 19 | + | |
| 20 | + result = get_module_by_name(model, "layer1.layer2.layer3") | |
| 21 | + self.assertEqual(result, "test_module") | |
| 22 | + | |
| 23 | + def test_set_module_by_name(self): | |
| 24 | + model = MagicMock() | |
| 25 | + new_module = MagicMock() | |
| 26 | + | |
| 27 | + set_module_by_name(model, "layer1.layer2.layer3", new_module) | |
| 28 | + self.assertEqual(model.layer1.layer2.layer3, new_module) | |
| 29 | + | |
| 30 | + @patch("mlx_vlm.trainer.utils.freeze_model") | |
| 31 | + @patch("mlx_vlm.trainer.utils.print_trainable_parameters") | |
| 32 | + def test_get_peft_model(self, mock_print, mock_freeze): | |
| 33 | + model = MagicMock() | |
| 34 | + model.language_model.named_modules.return_value = [ | |
| 35 | + ("layer1", nn.Linear(256, 512)), | |
| 36 | + ("layer2", nn.QuantizedLinear(256, 512, 8)), | |
| 37 | + ] | |
| 38 | + | |
| 39 | + result = get_peft_model(model, ["layer1", "layer2"]) | |
| 40 | + | |
| 41 | + self.assertTrue(mock_freeze.called) | |
| 42 | + self.assertTrue(mock_print.called) | |
| 43 | + self.assertTrue(hasattr(model.config, "lora")) | |
| 44 | + | |
| 45 | + def test_find_all_linear_names(self): | |
| 46 | + model = MagicMock() | |
| 47 | + model.named_modules.return_value = [ | |
| 48 | + ("layer1", nn.Linear(256, 512)), | |
| 49 | + ("layer2", nn.QuantizedLinear(256, 512, 8)), | |
| 50 | + ("mm_projector", nn.Linear(256, 512)), | |
| 51 | + ("lm_head", nn.Linear(256, 512)), | |
| 52 | + ] | |
| 53 | + | |
| 54 | + result = find_all_linear_names(model) | |
| 55 | + self.assertEqual(set(result), {"layer1", "layer2"}) | |
| 56 | + | |
| 57 | + | |
| 58 | +if __name__ == "__main__": | |
| 59 | + unittest.main() |
added mlx_vlm/trainer/__init__.py +9 −0
| @@ -0,0 +1,9 @@ | ||
| 1 | +from .lora import LoRaLayer, replace_lora_with_linear | |
| 2 | +from .trainer import Dataset, Trainer, save_adapter | |
| 3 | +from .utils import ( | |
| 4 | + apply_lora_layers, | |
| 5 | + count_parameters, | |
| 6 | + find_all_linear_names, | |
| 7 | + get_peft_model, | |
| 8 | + print_trainable_parameters, | |
| 9 | +) |
added mlx_vlm/trainer/lora.py +70 −0
| @@ -0,0 +1,70 @@ | ||
| 1 | +import math | |
| 2 | +from typing import Union | |
| 3 | + | |
| 4 | +import mlx.core as mx | |
| 5 | +import mlx.nn as nn | |
| 6 | + | |
| 7 | + | |
| 8 | +class LoRaLayer(nn.Module): | |
| 9 | + def __init__( | |
| 10 | + self, | |
| 11 | + linear: Union[nn.Linear, nn.QuantizedLinear], | |
| 12 | + rank: int, | |
| 13 | + alpha: float = 0.1, | |
| 14 | + dropout: float = 0.0, | |
| 15 | + ): | |
| 16 | + super().__init__() | |
| 17 | + | |
| 18 | + self.original_layer = linear | |
| 19 | + | |
| 20 | + self.dropout = nn.Dropout(p=dropout) | |
| 21 | + | |
| 22 | + output_dims, input_dims = linear.weight.shape | |
| 23 | + if isinstance(linear, nn.QuantizedLinear): | |
| 24 | + input_dims *= 32 // linear.bits | |
| 25 | + | |
| 26 | + std_dev = 1 / math.sqrt(rank) | |
| 27 | + | |
| 28 | + self.A = mx.random.uniform( | |
| 29 | + low=-std_dev, | |
| 30 | + high=std_dev, | |
| 31 | + shape=(input_dims, rank), | |
| 32 | + ) | |
| 33 | + self.B = mx.zeros((rank, output_dims)) | |
| 34 | + self.alpha = alpha | |
| 35 | + | |
| 36 | + def __call__(self, x): | |
| 37 | + y = self.original_layer(x) | |
| 38 | + lora_update = (self.dropout(x) @ self.A) @ self.B | |
| 39 | + return y + (self.alpha * lora_update).astype(x.dtype) | |
| 40 | + | |
| 41 | + | |
| 42 | +def replace_lora_with_linear(model): | |
| 43 | + for i, layer in enumerate(model.layers): | |
| 44 | + if isinstance(layer, LoRaLayer): | |
| 45 | + # Compute the final merged weight | |
| 46 | + lora_update = layer.alpha * (layer.A @ layer.B) | |
| 47 | + updated_weight = layer.original_layer.weight + lora_update | |
| 48 | + use_bias = layer.original_layer.bias is not None | |
| 49 | + | |
| 50 | + updated_bias = layer.original_layer.bias | |
| 51 | + | |
| 52 | + # Create a new Linear layer with the updated parameters | |
| 53 | + new_linear_layer = nn.Linear( | |
| 54 | + updated_weight.size(1), updated_weight.size(0), bias=use_bias | |
| 55 | + ) | |
| 56 | + | |
| 57 | + new_linear_layer.weight = updated_weight | |
| 58 | + | |
| 59 | + if use_bias: | |
| 60 | + new_linear_layer.bias = updated_bias | |
| 61 | + | |
| 62 | + if isinstance(layer.original_layer, nn.QuantizedLinear): | |
| 63 | + new_linear_layer = nn.QuantizedLinear.from_linear( | |
| 64 | + new_linear_layer, | |
| 65 | + new_linear_layer.group_size, | |
| 66 | + new_linear_layer.bits, | |
| 67 | + ) | |
| 68 | + | |
| 69 | + # Replace the LoRaLayer with the new Linear layer in the model | |
| 70 | + model.layers[i] = new_linear_layer |
added mlx_vlm/trainer/trainer.py +275 −0
| @@ -0,0 +1,275 @@ | ||
| 1 | +import json | |
| 2 | +import os | |
| 3 | +import time | |
| 4 | +import warnings | |
| 5 | +from dataclasses import dataclass, field | |
| 6 | +from pathlib import Path | |
| 7 | +from typing import Union | |
| 8 | + | |
| 9 | +import mlx.core as mx | |
| 10 | +import mlx.nn as nn | |
| 11 | +import numpy as np | |
| 12 | +from mlx.utils import tree_flatten | |
| 13 | + | |
| 14 | + | |
| 15 | +def get_prompt(model_type, processor, conversation): | |
| 16 | + if model_type == "paligemma": | |
| 17 | + return conversation | |
| 18 | + | |
| 19 | + if "chat_template" in processor.__dict__.keys(): | |
| 20 | + prompt = processor.apply_chat_template( | |
| 21 | + conversation, | |
| 22 | + tokenize=False, | |
| 23 | + add_generation_prompt=False, | |
| 24 | + ) | |
| 25 | + elif "tokenizer" in processor.__dict__.keys(): | |
| 26 | + prompt = processor.tokenizer.apply_chat_template( | |
| 27 | + conversation, | |
| 28 | + tokenize=False, | |
| 29 | + add_generation_prompt=False, | |
| 30 | + ) | |
| 31 | + | |
| 32 | + return prompt | |
| 33 | + | |
| 34 | + | |
| 35 | +class Dataset: | |
| 36 | + def __init__( | |
| 37 | + self, | |
| 38 | + hf_dataset, | |
| 39 | + config, | |
| 40 | + processor, | |
| 41 | + image_processor=None, | |
| 42 | + take=None, | |
| 43 | + split=None, | |
| 44 | + ): | |
| 45 | + if split is not None: | |
| 46 | + self.dataset = hf_dataset[split] | |
| 47 | + else: | |
| 48 | + self.dataset = hf_dataset | |
| 49 | + if take is not None: | |
| 50 | + self.dataset = self.dataset.take(take) | |
| 51 | + self.processor = processor | |
| 52 | + self.config = config | |
| 53 | + self.image_processor = image_processor | |
| 54 | + | |
| 55 | + def __len__(self): | |
| 56 | + return len(self.dataset) | |
| 57 | + | |
| 58 | + def __getitem__(self, idx): | |
| 59 | + from mlx_vlm.utils import prepare_inputs | |
| 60 | + | |
| 61 | + item = self.dataset[idx] | |
| 62 | + | |
| 63 | + images = item["images"] | |
| 64 | + conversations = item["messages"] | |
| 65 | + prompts = [] | |
| 66 | + | |
| 67 | + if isinstance(conversations, list) and isinstance(conversations[0], list): | |
| 68 | + for conversation in conversations: | |
| 69 | + if self.config["model_type"] == "pixtral": | |
| 70 | + conversation = [json.loads(i) for i in conversation] | |
| 71 | + if len(conversations) > 1: | |
| 72 | + warnings.warn( | |
| 73 | + "Pixtral batch processing is not supported yet. Set batch size to 1." | |
| 74 | + ) | |
| 75 | + | |
| 76 | + prompt = get_prompt( | |
| 77 | + self.config["model_type"], self.processor, conversation | |
| 78 | + ) | |
| 79 | + prompts.append(prompt) | |
| 80 | + | |
| 81 | + else: | |
| 82 | + if self.config["model_type"] == "pixtral": | |
| 83 | + conversations = [json.loads(i) for i in conversations] | |
| 84 | + prompt = get_prompt( | |
| 85 | + self.config["model_type"], self.processor, conversations | |
| 86 | + ) | |
| 87 | + prompts.append(prompt) | |
| 88 | + | |
| 89 | + image_token_index = self.config["image_token_index"] | |
| 90 | + | |
| 91 | + inputs = prepare_inputs( | |
| 92 | + self.image_processor, self.processor, images, prompts, image_token_index | |
| 93 | + ) | |
| 94 | + input_ids, pixel_values, mask = inputs[:3] | |
| 95 | + kwargs = {k: v for k, v in zip(["image_grid_thw", "image_sizes"], inputs[3:])} | |
| 96 | + if mask is None: | |
| 97 | + mask = mx.ones_like(input_ids) | |
| 98 | + | |
| 99 | + return { | |
| 100 | + "pixel_values": pixel_values, | |
| 101 | + "input_ids": input_ids, | |
| 102 | + "attention_mask": mask, | |
| 103 | + **kwargs, | |
| 104 | + } | |
| 105 | + | |
| 106 | + | |
| 107 | +def grad_checkpoint(layer): | |
| 108 | + """ | |
| 109 | + Update all instances of type(layer) to use gradient checkpointing. | |
| 110 | + """ | |
| 111 | + fn = type(layer).__call__ | |
| 112 | + | |
| 113 | + def checkpointed_fn(model, *args, **kwargs): | |
| 114 | + def inner_fn(params, *args, **kwargs): | |
| 115 | + model.update(params) | |
| 116 | + return fn(model, *args, **kwargs) | |
| 117 | + | |
| 118 | + return mx.checkpoint(inner_fn)(model.trainable_parameters(), *args, **kwargs) | |
| 119 | + | |
| 120 | + type(layer).__call__ = checkpointed_fn | |
| 121 | + | |
| 122 | + | |
| 123 | +@dataclass | |
| 124 | +class TrainingArgs: | |
| 125 | + batch_size: int = field(default=4, metadata={"help": "Minibatch size."}) | |
| 126 | + iters: int = field(default=100, metadata={"help": "Iterations to train for."}) | |
| 127 | + val_batches: int = field( | |
| 128 | + default=25, | |
| 129 | + metadata={ | |
| 130 | + "help": "Number of validation batches, -1 uses the entire validation set." | |
| 131 | + }, | |
| 132 | + ) | |
| 133 | + steps_per_report: int = field( | |
| 134 | + default=10, | |
| 135 | + metadata={"help": "Number of training steps between loss reporting."}, | |
| 136 | + ) | |
| 137 | + steps_per_eval: int = field( | |
| 138 | + default=200, metadata={"help": "Number of training steps between validations."} | |
| 139 | + ) | |
| 140 | + steps_per_save: int = field( | |
| 141 | + default=100, metadata={"help": "Save the model every number steps"} | |
| 142 | + ) | |
| 143 | + max_seq_length: int = field( | |
| 144 | + default=2048, metadata={"help": "Maximum sequence length."} | |
| 145 | + ) | |
| 146 | + adapter_file: str = field( | |
| 147 | + default="adapters.safetensors", | |
| 148 | + metadata={"help": "Save/load path for the trained adapter weights."}, | |
| 149 | + ) | |
| 150 | + grad_checkpoint: bool = field( | |
| 151 | + default=False, | |
| 152 | + metadata={"help": "Use gradient checkpointing to reduce memory use."}, | |
| 153 | + ) | |
| 154 | + | |
| 155 | + | |
| 156 | +def default_loss(model, inputs, targets, lengths): | |
| 157 | + logits = model(inputs) | |
| 158 | + logits = logits.astype(mx.float32) | |
| 159 | + | |
| 160 | + length_mask = mx.arange(inputs.shape[1])[None, :] < lengths[:, None] | |
| 161 | + | |
| 162 | + ce = nn.losses.cross_entropy(logits, targets) * length_mask | |
| 163 | + ntoks = length_mask.sum() | |
| 164 | + ce = ce.sum() / ntoks | |
| 165 | + | |
| 166 | + return ce, ntoks | |
| 167 | + | |
| 168 | + | |
| 169 | +class Trainer: | |
| 170 | + def __init__( | |
| 171 | + self, model, optimizer, train_on_completions=False, assistant_id=77091 | |
| 172 | + ): | |
| 173 | + self.model = model | |
| 174 | + self.optimizer = optimizer | |
| 175 | + self.train_on_completions = train_on_completions | |
| 176 | + self.assistant_id = assistant_id | |
| 177 | + | |
| 178 | + def loss_fn(self, model, batch): | |
| 179 | + pixel_values = batch["pixel_values"] | |
| 180 | + input_ids = batch["input_ids"] | |
| 181 | + attention_mask = batch["attention_mask"] | |
| 182 | + lengths = mx.sum(attention_mask, axis=1) | |
| 183 | + labels = input_ids[:, 1:] | |
| 184 | + | |
| 185 | + batch_size, seq_length = input_ids.shape | |
| 186 | + | |
| 187 | + if self.train_on_completions: | |
| 188 | + weight_mask = mx.ones_like(attention_mask) | |
| 189 | + | |
| 190 | + assistant_response_index = np.where(input_ids == self.assistant_id)[1] | |
| 191 | + range_matrix = mx.repeat( | |
| 192 | + mx.expand_dims(mx.arange(seq_length), 0), batch_size, axis=0 | |
| 193 | + ) | |
| 194 | + assistant_mask = range_matrix <= mx.array(assistant_response_index).reshape( | |
| 195 | + -1, 1 | |
| 196 | + ) | |
| 197 | + # Apply the mask to weight_mask | |
| 198 | + weight_mask = mx.where( | |
| 199 | + assistant_mask, mx.zeros_like(weight_mask), weight_mask | |
| 200 | + )[:, 1:] | |
| 201 | + else: | |
| 202 | + weight_mask = None | |
| 203 | + | |
| 204 | + input_ids = input_ids[:, :-1] | |
| 205 | + | |
| 206 | + kwargs = ( | |
| 207 | + { | |
| 208 | + "image_grid_thw": batch["image_grid_thw"], | |
| 209 | + "image_sizes": batch["image_sizes"], | |
| 210 | + } | |
| 211 | + if "image_grid_thw" in batch or "image_sizes" in batch | |
| 212 | + else {} | |
| 213 | + ) | |
| 214 | + | |
| 215 | + # Forward pass | |
| 216 | + logits = model(input_ids, pixel_values, attention_mask, **kwargs) | |
| 217 | + | |
| 218 | + # Cast to float32 | |
| 219 | + logits.astype(mx.float32) | |
| 220 | + | |
| 221 | + # Ensure logits and labels have the same sequence length | |
| 222 | + def align_logits_with_labels(logits, labels): | |
| 223 | + if logits.shape[1] < labels.shape[1]: | |
| 224 | + pad_length = labels.shape[1] - logits.shape[1] | |
| 225 | + pad_width = ((0, 0), (0, pad_length), (0, 0)) | |
| 226 | + return mx.pad(logits, pad_width, mode="constant", constant_values=-100) | |
| 227 | + elif logits.shape[1] > labels.shape[1]: | |
| 228 | + return logits[:, -labels.shape[1] :, :] | |
| 229 | + return logits | |
| 230 | + | |
| 231 | + logits = align_logits_with_labels(logits, labels) | |
| 232 | + | |
| 233 | + length_mask = mx.arange(input_ids.shape[1])[None, :] < lengths[:, None] | |
| 234 | + | |
| 235 | + # Compute loss only on non-padded tokens | |
| 236 | + ce = ( | |
| 237 | + nn.losses.cross_entropy( | |
| 238 | + logits, | |
| 239 | + labels, | |
| 240 | + weights=weight_mask, | |
| 241 | + ) | |
| 242 | + * length_mask | |
| 243 | + ) | |
| 244 | + ntoks = length_mask.sum() | |
| 245 | + ce = ce.sum() / ntoks | |
| 246 | + | |
| 247 | + return ce | |
| 248 | + | |
| 249 | + def train_step(self, batch): | |
| 250 | + loss_and_grad_fn = nn.value_and_grad(self.model, self.loss_fn) | |
| 251 | + loss, grads = loss_and_grad_fn(self.model, batch) | |
| 252 | + self.optimizer.update(self.model, grads) | |
| 253 | + | |
| 254 | + return loss | |
| 255 | + | |
| 256 | + @mx.compile | |
| 257 | + def train_epoch(self, dataloader): | |
| 258 | + total_loss = 0 | |
| 259 | + for batch in dataloader: | |
| 260 | + loss = self.train_step(batch) | |
| 261 | + mx.eval(self.model, self.optimizer.state) | |
| 262 | + total_loss += loss | |
| 263 | + return total_loss / len(dataloader) | |
| 264 | + | |
| 265 | + | |
| 266 | +def save_adapter( | |
| 267 | + model: nn.Module, | |
| 268 | + adapter_file: Union[str, Path], | |
| 269 | +): | |
| 270 | + path = Path(adapter_file) | |
| 271 | + if hasattr(model.config, "lora"): | |
| 272 | + with open(path.parent / "adapter_config.json", "w") as f: | |
| 273 | + json.dump(model.config.lora, f) | |
| 274 | + flattened_tree = tree_flatten(model.trainable_parameters()) | |
| 275 | + mx.save_safetensors(str(adapter_file), dict(flattened_tree)) |
added mlx_vlm/trainer/utils.py +150 −0
| @@ -0,0 +1,150 @@ | ||
| 1 | +from pathlib import Path | |
| 2 | + | |
| 3 | +import mlx.nn as nn | |
| 4 | +from mlx.utils import tree_flatten | |
| 5 | + | |
| 6 | +from .lora import LoRaLayer | |
| 7 | + | |
| 8 | + | |
| 9 | +def get_module_by_name(model, name): | |
| 10 | + parts = name.split(".") | |
| 11 | + module = model | |
| 12 | + for part in parts: | |
| 13 | + if part.isdigit(): | |
| 14 | + module = module[int(part)] | |
| 15 | + else: | |
| 16 | + module = getattr(module, part) | |
| 17 | + return module | |
| 18 | + | |
| 19 | + | |
| 20 | +def set_module_by_name(model, name, new_module): | |
| 21 | + parts = name.split(".") | |
| 22 | + module = model | |
| 23 | + for part in parts[:-1]: | |
| 24 | + if part.isdigit(): | |
| 25 | + module = module[int(part)] | |
| 26 | + else: | |
| 27 | + module = getattr(module, part) | |
| 28 | + if parts[-1].isdigit(): | |
| 29 | + module[int(parts[-1])] = new_module | |
| 30 | + else: | |
| 31 | + setattr(module, parts[-1], new_module) | |
| 32 | + | |
| 33 | + | |
| 34 | +def get_peft_model( | |
| 35 | + model, linear_layers, rank=10, alpha=0.1, dropout=0.1, freeze=True, verbose=True | |
| 36 | +): | |
| 37 | + if freeze: | |
| 38 | + freeze_model(model) | |
| 39 | + | |
| 40 | + for name, module in model.language_model.named_modules(): | |
| 41 | + if isinstance(module, nn.Linear) or isinstance(module, nn.QuantizedLinear): | |
| 42 | + if name.split(".")[-1] in linear_layers: | |
| 43 | + lora_layer = LoRaLayer(module, rank, alpha, dropout) | |
| 44 | + set_module_by_name(model.language_model, name, lora_layer) | |
| 45 | + | |
| 46 | + model.config.lora = {} | |
| 47 | + model.config.lora["rank"] = rank | |
| 48 | + model.config.lora["alpha"] = alpha | |
| 49 | + model.config.lora["dropout"] = dropout | |
| 50 | + | |
| 51 | + if verbose: | |
| 52 | + print_trainable_parameters(model.language_model) | |
| 53 | + | |
| 54 | + return model | |
| 55 | + | |
| 56 | + | |
| 57 | +def freeze_model(model): | |
| 58 | + for name, module in model.named_modules(): | |
| 59 | + name = name.split(".")[0] | |
| 60 | + if name in [ | |
| 61 | + "language_model", | |
| 62 | + "vision_model", | |
| 63 | + "vision_tower", | |
| 64 | + "aligner", | |
| 65 | + "connector", | |
| 66 | + "multi_modal_projector", | |
| 67 | + "mm_projector", | |
| 68 | + ]: | |
| 69 | + model[f"{name}"].freeze() | |
| 70 | + | |
| 71 | + | |
| 72 | +def find_all_linear_names(model): | |
| 73 | + cls = nn.Linear | |
| 74 | + quantized_cls = nn.QuantizedLinear | |
| 75 | + lora_module_names = set() | |
| 76 | + multimodal_keywords = [ | |
| 77 | + "mm_projector", | |
| 78 | + "vision_tower", | |
| 79 | + "vision_resampler", | |
| 80 | + "aligner", | |
| 81 | + ] | |
| 82 | + for name, module in model.named_modules(): | |
| 83 | + if any(mm_keyword in name for mm_keyword in multimodal_keywords): | |
| 84 | + continue | |
| 85 | + if isinstance(module, cls) or isinstance(module, quantized_cls): | |
| 86 | + names = name.split(".") | |
| 87 | + lora_module_names.add(names[0] if len(names) == 1 else names[-1]) | |
| 88 | + | |
| 89 | + if "lm_head" in lora_module_names: # needed for 16-bit | |
| 90 | + lora_module_names.remove("lm_head") | |
| 91 | + return list(lora_module_names) | |
| 92 | + | |
| 93 | + | |
| 94 | +def count_parameters(model): | |
| 95 | + def nparams(m): | |
| 96 | + if isinstance(m, (nn.QuantizedLinear, nn.QuantizedEmbedding)): | |
| 97 | + return m.weight.size * (32 // m.bits) | |
| 98 | + return sum(v.size for _, v in tree_flatten(m.parameters())) | |
| 99 | + | |
| 100 | + leaf_modules = tree_flatten( | |
| 101 | + model.leaf_modules(), is_leaf=lambda m: isinstance(m, nn.Module) | |
| 102 | + ) | |
| 103 | + total_p = sum(nparams(m) for _, m in leaf_modules) / 10**6 | |
| 104 | + | |
| 105 | + return total_p | |
| 106 | + | |
| 107 | + | |
| 108 | +def print_trainable_parameters(model): | |
| 109 | + def nparams(m): | |
| 110 | + if isinstance(m, (nn.QuantizedLinear, nn.QuantizedEmbedding)): | |
| 111 | + return m.weight.size * (32 // m.bits) | |
| 112 | + return sum(v.size for _, v in tree_flatten(m.parameters())) | |
| 113 | + | |
| 114 | + leaf_modules = tree_flatten( | |
| 115 | + model.leaf_modules(), is_leaf=lambda m: isinstance(m, nn.Module) | |
| 116 | + ) | |
| 117 | + total_p = sum(nparams(m) for _, m in leaf_modules) / 10**6 | |
| 118 | + trainable_p = ( | |
| 119 | + sum(v.size for _, v in tree_flatten(model.trainable_parameters())) / 10**6 | |
| 120 | + ) | |
| 121 | + | |
| 122 | + print( | |
| 123 | + f"#trainable params: {trainable_p} M || all params: {total_p} M || trainable%: {(trainable_p * 100 / total_p):.3f}%" | |
| 124 | + ) | |
| 125 | + | |
| 126 | + | |
| 127 | +def apply_lora_layers(model: nn.Module, adapter_path: str) -> nn.Module: | |
| 128 | + """ | |
| 129 | + Apply LoRA layers to the model. | |
| 130 | + | |
| 131 | + Args: | |
| 132 | + model (nn.Module): The neural network model. | |
| 133 | + adapter_path (str): Path to the adapter configuration file. | |
| 134 | + | |
| 135 | + Returns: | |
| 136 | + nn.Module: The updated model with LoRA layers applied. | |
| 137 | + """ | |
| 138 | + adapter_path = Path(adapter_path) | |
| 139 | + | |
| 140 | + if not adapter_path.exists(): | |
| 141 | + raise FileNotFoundError(f"The adapter path does not exist: {adapter_path}") | |
| 142 | + | |
| 143 | + # TODO: add lora params to the config and load them here | |
| 144 | + list_of_modules = find_all_linear_names(model.language_model.model) | |
| 145 | + model = get_peft_model(model, list_of_modules) | |
| 146 | + | |
| 147 | + # TODO: Use custom adapter name | |
| 148 | + model.load_weights(str(adapter_path / "adapters.safetensors"), strict=False) | |
| 149 | + | |
| 150 | + return model |
modified mlx_vlm/utils.py +107 −58
| @@ -26,7 +26,8 @@ | ||
| 26 | 26 | |
| 27 | 27 | from .models.base import BaseImageProcessor, KVCache |
| 28 | 28 | from .sample_utils import top_p_sampling |
| 29 | -from .tokenizer_utils import TokenizerWrapper, load_tokenizer | |
| 29 | +from .tokenizer_utils import load_tokenizer | |
| 30 | +from .trainer import apply_lora_layers | |
| 30 | 31 | |
| 31 | 32 | # Constants |
| 32 | 33 | MODEL_REMAPPING = {"llava-qwen2": "llava_bunny", "bunny-llama": "llava_bunny"} |
| @@ -223,6 +224,7 @@ | ||
| 223 | 224 | def load( |
| 224 | 225 | path_or_hf_repo: str, |
| 225 | 226 | processor_config={}, |
| 227 | + adapter_path: Optional[str] = None, | |
| 226 | 228 | lazy: bool = False, |
| 227 | 229 | ) -> Tuple[nn.Module, Union[PreTrainedTokenizer, PreTrainedTokenizerFast]]: |
| 228 | 230 | """ |
| @@ -247,6 +249,11 @@ | ||
| 247 | 249 | model_path = get_model_path(path_or_hf_repo) |
| 248 | 250 | |
| 249 | 251 | model = load_model(model_path, lazy) |
| 252 | + if adapter_path is not None: | |
| 253 | + # TODO: Support more modules than just language_model | |
| 254 | + model = apply_lora_layers(model, adapter_path) | |
| 255 | + model.eval() | |
| 256 | + | |
| 250 | 257 | processor = load_processor(model_path, processor_config=processor_config) |
| 251 | 258 | |
| 252 | 259 | return model, processor |
| @@ -288,14 +295,15 @@ | ||
| 288 | 295 | |
| 289 | 296 | |
| 290 | 297 | def load_processor( |
| 291 | - model_path, processor_config={"trust_remote_code": True} | |
| 298 | + model_path, processor_config={"trust_remote_code": True}, add_detokenizer=True | |
| 292 | 299 | ) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]: |
| 293 | 300 | processor = AutoProcessor.from_pretrained(model_path, **processor_config) |
| 294 | - detokenizer_class = load_tokenizer(model_path, return_tokenizer=False) | |
| 295 | - if "tokenizer" in processor.__dict__.keys(): | |
| 296 | - processor.detokenizer = detokenizer_class(processor.tokenizer) | |
| 297 | - else: | |
| 298 | - processor.detokenizer = detokenizer_class(processor) | |
| 301 | + if add_detokenizer: | |
| 302 | + detokenizer_class = load_tokenizer(model_path, return_tokenizer=False) | |
| 303 | + if "tokenizer" in processor.__dict__.keys(): | |
| 304 | + processor.detokenizer = detokenizer_class(processor.tokenizer) | |
| 305 | + else: | |
| 306 | + processor.detokenizer = detokenizer_class(processor) | |
| 299 | 307 | return processor |
| 300 | 308 | |
| 301 | 309 | |
| @@ -304,8 +312,7 @@ | ||
| 304 | 312 | ) -> Tuple[nn.Module, dict, PreTrainedTokenizer]: |
| 305 | 313 | model = load_model(model_path, lazy) |
| 306 | 314 | config = load_config(model_path) |
| 307 | - processor = load_processor(model_path) | |
| 308 | - | |
| 315 | + processor = load_processor(model_path, add_detokenizer=False) | |
| 309 | 316 | return model, config, processor |
| 310 | 317 | |
| 311 | 318 | |
| @@ -637,7 +644,7 @@ | ||
| 637 | 644 | ): |
| 638 | 645 | print("[INFO] Loading") |
| 639 | 646 | model_path = get_model_path(hf_path, revision=revision) |
| 640 | - model, config, tokenizer = fetch_from_hub(model_path, lazy=False) | |
| 647 | + model, config, processor = fetch_from_hub(model_path, lazy=False) | |
| 641 | 648 | |
| 642 | 649 | weights = dict(tree_flatten(model.parameters())) |
| 643 | 650 | dtype = mx.float16 if quantize else getattr(mx, dtype) |
| @@ -666,7 +673,7 @@ | ||
| 666 | 673 | for file in py_files: |
| 667 | 674 | shutil.copy(file, mlx_path) |
| 668 | 675 | |
| 669 | - tokenizer.save_pretrained(mlx_path) | |
| 676 | + processor.save_pretrained(mlx_path) | |
| 670 | 677 | |
| 671 | 678 | save_config(config, config_path=mlx_path / "config.json") |
| 672 | 679 | |
| @@ -704,46 +711,86 @@ | ||
| 704 | 711 | ) |
| 705 | 712 | |
| 706 | 713 | |
| 707 | -def prepare_inputs(image_processor, processor, image, prompt, image_token_index): | |
| 714 | +def resize_image(img, max_size): | |
| 715 | + ratio = min(max_size[0] / img.width, max_size[1] / img.height) | |
| 716 | + new_size = (int(img.width * ratio), int(img.height * ratio)) | |
| 717 | + return img.resize(new_size) | |
| 718 | + | |
| 719 | + | |
| 720 | +def process_image(img, resize_shape): | |
| 721 | + if isinstance(img, str): | |
| 722 | + img = load_image(img) | |
| 723 | + if resize_shape is not None: | |
| 724 | + img = resize_image(img, resize_shape) | |
| 725 | + return img | |
| 726 | + | |
| 727 | + | |
| 728 | +def prepare_inputs( | |
| 729 | + image_processor, processor, images, prompts, image_token_index, resize_shape=None | |
| 730 | +): | |
| 708 | 731 | from transformers.image_utils import load_image |
| 709 | 732 | |
| 710 | 733 | mask = None |
| 711 | - if isinstance(image, str): | |
| 712 | - image = load_image(image) | |
| 734 | + if not isinstance(images, list): | |
| 735 | + images = [images] | |
| 736 | + | |
| 737 | + # Process images | |
| 738 | + images = [ | |
| 739 | + process_image(img, resize_shape) if isinstance(img, str) else img | |
| 740 | + for img in images | |
| 741 | + ] | |
| 713 | 742 | |
| 714 | 743 | image_grid_thw = None |
| 744 | + image_sizes = None | |
| 715 | 745 | if image_processor is not None: |
| 716 | - text_chunks = [processor(chunk).input_ids for chunk in prompt.split("<image>")] | |
| 717 | - input_ids = mx.array([text_chunks[0] + [image_token_index] + text_chunks[1]]) | |
| 718 | - pixel_values = mx.array(image_processor.preprocess(images=[image])[0]) | |
| 719 | - pixel_values = mx.array(mx.expand_dims(pixel_values, axis=0)) | |
| 746 | + if not isinstance(prompts, list): | |
| 747 | + prompts = [prompts] | |
| 748 | + | |
| 749 | + processor.pad_token = processor.eos_token | |
| 750 | + text_chunks = [ | |
| 751 | + [processor(chunk).input_ids for chunk in prompt.split("<image>")] | |
| 752 | + for prompt in prompts | |
| 753 | + ] | |
| 754 | + | |
| 755 | + # Find the maximum length for padding | |
| 756 | + max_length = max( | |
| 757 | + sum(len(chunk) for chunk in chunks) + 1 for chunks in text_chunks | |
| 758 | + ) | |
| 759 | + | |
| 760 | + # Pad and create input_ids | |
| 761 | + input_ids = [] | |
| 762 | + for chunks in text_chunks: | |
| 763 | + ids = chunks[0] + [image_token_index] + chunks[1] | |
| 764 | + padding = [processor.pad_token_id] * (max_length - len(ids)) | |
| 765 | + input_ids.append(mx.array(ids + padding)) | |
| 766 | + | |
| 767 | + input_ids = mx.array(input_ids) | |
| 768 | + | |
| 769 | + pixel_values = image_processor.preprocess(images=images) | |
| 770 | + pixel_values = mx.array(np.stack(pixel_values)) | |
| 771 | + | |
| 772 | + mask = mx.array([(ids != processor.pad_token_id) for ids in input_ids]).astype( | |
| 773 | + mx.int32 | |
| 774 | + ) | |
| 720 | 775 | else: |
| 721 | 776 | processor.tokenizer.pad_token = processor.tokenizer.eos_token |
| 722 | - try: | |
| 723 | - inputs = processor( | |
| 724 | - text=[prompt], images=[image], padding=True, return_tensors="mlx" | |
| 725 | - ) | |
| 726 | - except Exception as e: | |
| 727 | - inputs = processor( | |
| 728 | - text=prompt, images=[image], padding=True, return_tensors="mlx" | |
| 729 | - ) # for phi3_v model | |
| 730 | - | |
| 777 | + inputs = processor( | |
| 778 | + text=prompts, images=images, padding=True, return_tensors="mlx" | |
| 779 | + ) | |
| 731 | 780 | if isinstance(inputs["pixel_values"], list): |
| 732 | - pixel_values = mx.array(inputs["pixel_values"][0][0])[None, :] | |
| 733 | - elif isinstance(inputs["pixel_values"], np.ndarray): | |
| 734 | - pixel_values = mx.array(inputs["pixel_values"]) | |
| 781 | + pixel_values = inputs["pixel_values"] | |
| 735 | 782 | else: |
| 736 | - raise ValueError( | |
| 737 | - f"Invalid pixel_values type: {type(inputs['pixel_values'])}" | |
| 738 | - ) | |
| 739 | - | |
| 783 | + pixel_values = mx.array(inputs["pixel_values"]) | |
| 740 | 784 | input_ids = mx.array(inputs["input_ids"]) |
| 741 | - mask = inputs["attention_mask"] | |
| 785 | + mask = mx.array(inputs["attention_mask"]) | |
| 786 | + image_sizes = inputs.get("image_sizes", None) | |
| 787 | + if image_sizes is not None: | |
| 788 | + image_sizes = mx.array(image_sizes) | |
| 742 | 789 | image_grid_thw = inputs.get("image_grid_thw", None) |
| 743 | - if "image_sizes" in inputs: | |
| 744 | - return input_ids, pixel_values, inputs["image_sizes"], image_grid_thw | |
| 790 | + if image_grid_thw is not None: | |
| 791 | + image_grid_thw = mx.array(image_grid_thw) | |
| 745 | 792 | |
| 746 | - return input_ids, pixel_values, mask, image_grid_thw | |
| 793 | + return input_ids, pixel_values, mask, image_grid_thw, image_sizes | |
| 747 | 794 | |
| 748 | 795 | |
| 749 | 796 | def generate_step( |
| @@ -878,9 +925,11 @@ | ||
| 878 | 925 | tokenizer = processor.tokenizer |
| 879 | 926 | |
| 880 | 927 | image_token_index = model.config.image_token_index |
| 881 | - input_ids, pixel_values, mask = prepare_inputs( | |
| 928 | + inputs = prepare_inputs( | |
| 882 | 929 | image_processor, processor, image, prompt, image_token_index |
| 883 | 930 | ) |
| 931 | + input_ids, pixel_values, mask = inputs[:3] | |
| 932 | + kwargs = {k: v for k, v in zip(["image_grid_thw", "image_sizes"], inputs[3:])} | |
| 884 | 933 | |
| 885 | 934 | detokenizer = processor.detokenizer |
| 886 | 935 | |
| @@ -944,32 +993,32 @@ | ||
| 944 | 993 | tokenizer = processor.tokenizer |
| 945 | 994 | |
| 946 | 995 | image_token_index = model.config.image_token_index |
| 947 | - input_ids, pixel_values, mask, image_grid_thw = prepare_inputs( | |
| 996 | + # Prepare inputs | |
| 997 | + inputs = prepare_inputs( | |
| 948 | 998 | image_processor, processor, image, prompt, image_token_index |
| 949 | 999 | ) |
| 1000 | + input_ids, pixel_values, mask = inputs[:3] | |
| 1001 | + kwargs = {k: v for k, v in zip(["image_grid_thw", "image_sizes"], inputs[3:])} | |
| 950 | 1002 | |
| 951 | - kwargs = { | |
| 952 | - "image_grid_thw": image_grid_thw, | |
| 953 | - } | |
| 954 | - | |
| 1003 | + # Initialize timing and detokenizer | |
| 955 | 1004 | tic = time.perf_counter() |
| 956 | 1005 | detokenizer = processor.detokenizer |
| 957 | 1006 | detokenizer.reset() |
| 958 | 1007 | |
| 959 | - for (token, prob), n in zip( | |
| 960 | - generate_step( | |
| 961 | - input_ids, | |
| 962 | - model, | |
| 963 | - pixel_values, | |
| 964 | - mask, | |
| 965 | - temp, | |
| 966 | - repetition_penalty, | |
| 967 | - repetition_context_size, | |
| 968 | - top_p, | |
| 969 | - **kwargs, | |
| 970 | - ), | |
| 971 | - range(max_tokens), | |
| 972 | - ): | |
| 1008 | + # Generate tokens | |
| 1009 | + generator = generate_step( | |
| 1010 | + input_ids, | |
| 1011 | + model, | |
| 1012 | + pixel_values, | |
| 1013 | + mask, | |
| 1014 | + temp, | |
| 1015 | + repetition_penalty, | |
| 1016 | + repetition_context_size, | |
| 1017 | + top_p, | |
| 1018 | + **kwargs, | |
| 1019 | + ) | |
| 1020 | + | |
| 1021 | + for (token, prob), n in zip(generator, range(max_tokens)): | |
| 973 | 1022 | |
| 974 | 1023 | if n == 0: |
| 975 | 1024 | prompt_time = time.perf_counter() - tic |
modified mlx_vlm/version.py +1 −1
| @@ -1,1 +1,1 @@ | ||
| 1 | -__version__ = "0.0.15" | |
| 1 | +__version__ = "0.1.0" |
modified requirements.txt +5 −3
| @@ -1,7 +1,9 @@ | ||
| 1 | 1 | mlx>=0.18.0 |
| 2 | -numpy | |
| 2 | +datasets>=2.19.1 | |
| 3 | +tqdm>=4.66.2 | |
| 4 | +numpy>=1.23.4 | |
| 3 | 5 | transformers>=4.45.1 |
| 4 | 6 | scipy==1.13.1 |
| 5 | 7 | gradio>=4.44.0 |
| 6 | -Pillow | |
| 7 | -requests | |
| 8 | +Pillow>=10.3.0 | |
| 9 | +requests>=2.31.0 |