Elffuss BraidHub

kikocis/mlx-vlm public

Trainer + Multi image v0.1.0 (#41)

* remove torch and mlx-lm

* remove torch and mlx-lm

* add peft model creation

* use tree flatten

* add dataset loader

* fix dataset

* fix masks and rename dataset

* support batch processing and train on completions

* fix trainer

* formatting

* add support for none splits and fix assistant id

* Add lora script and docs

* remove torch and mlx-lm

* add peft model creation

* use tree flatten

* add dataset loader

* fix dataset

* fix masks and rename dataset

* support batch processing and train on completions

* fix trainer

* formatting

* add support for none splits and fix assistant id

* Add lora script and docs

* remove duplicates

* fix batch load

* load trained adapters and add super to all models

* fix pixtral quant

* speed up qwen batch processing

* fix qlora training

* fix dataloader

* formatting

* fix pixtral pixel loading

* fix lora and dataset

* add batch processing suppor for qwen2_vl

* update lora docs

* add unit tests

* set stage for phi3_v support

* update logs and readme

* add utils tests and remove unused collate fn

* refactor prompt utils and add multi-image support for pixtral

* add llava interleave support

* multi image support

* add image resizing

* refactor data loading

* update data procesing and tqdm

* add llava interleave

* formatting

* add list of models with multi-image support

* remove trimmed labels

* remove warning

* pin reqs

* add config dict condition

* fix pixtral FT prompt

* formatting images

* remove unused

* update trainer init

* update lora

* update md and formatting

* bump version

* add tests for pixtral and qwen2_vl

* add tests for pixtral

* Merge branch 'pc/tuner' of https://github.com/Blaizzy/mlx-vlm into pc/tuner

* fix test

* remove rope scaling

* remove test args and update MD

* format dataset defaults

* add dataset formatting info

* Fix issues with multiple image handling (#78)

1. [IMG_BREAK] and [IMG_END] are lost after embedding
 2. image position encode should be done per image base
    https://github.com/mistralai/mistral-inference/blob/main/src/mistral_inference/vision_encoder.py#L85
    https://github.com/huggingface/transformers/blob/main/src/transformers/models/pixtral/modeling_pixtral.py#L492

Co-authored-by: Roger Xu <rogerxu@gmail.com>

* fix styling

* update model

* update default model

* rewrite comments

---------

Co-authored-by: hiima234 <98786318+hiima234@users.noreply.github.com>
Co-authored-by: Roger Xu <rogerxu@gmail.com>
Changeset298bbfc46d57a3c059d0e7e77df60006640a266de488fc2d0b0d5d0d6c611bc2
AuthorPrince Canuma <prince.gdt@gmail.com> · 2024-10-11 19:15 +02:00
CommitterGitHub <noreply@github.com> · 2024-10-11 19:15 +02:00
Parents5d7c46de2be5

Browse the files at this changeset

33 files changed

modified .gitignore +1 −0
@@ -20,3 +20,4 @@
2020 .installed.cfg
2121 *.egg
2222 .DS_Store
23+*.log
modified README.md +95 −19
@@ -1,43 +1,119 @@
11 # MLX-VLM
22
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:
419
20+```sh
21+pip install mlx-vlm
22+```
523
6-## Get started
24+## Usage
725
8-The easiest way to get started is to install the `mlx-vlm` package:
26+### Command Line Interface (CLI)
927
10-**With `pip`**:
28+Generate output from a model using the CLI:
1129
1230 ```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
1432 ```
1533
16-## Inference
34+### Chat UI with Gradio
1735
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:
2237
23-**Chat UI with Gradio**
2438 ```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
2640 ```
2741
28-**Script**
42+### Python Script
43+
44+Here's an example of how to use MLX-VLM in a Python script:
45+
2946 ```python
3047 import mlx.core as mx
3148 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
3290
33-model_path = "mlx-community/llava-1.5-7b-4bit"
91+model_path = "mlx-community/Qwen2-VL-2B-Instruct-4bit"
3492 model, processor = load(model_path)
3593
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)
4099 )
41100
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)
43103 ```
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
23 from .version import __version__
modified mlx_vlm/generate.py +19 −8
@@ -1,13 +1,11 @@
11 import argparse
22 import codecs
33
4-import mlx.core as mx
5-
64 from .prompt_utils import apply_chat_template
75 from .utils import generate, get_model_path, load, load_config, load_image_processor
86
97 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"]
119 DEFAULT_PROMPT = "What are these?"
1210 DEFAULT_MAX_TOKENS = 100
1311 DEFAULT_TEMP = 0.5
@@ -25,9 +23,16 @@
2523 default=DEFAULT_MODEL_PATH,
2624 help="The path to the local model directory or Hugging Face repo.",
2725 )
26+ parser.add_argument(
27+ "--adapter-path",
28+ type=str,
29+ default=None,
30+ help="The path to the adapter weights.",
31+ )
2832 parser.add_argument(
2933 "--image",
3034 type=str,
35+ nargs="+",
3136 default=DEFAULT_IMAGE,
3237 help="URL or path of the image to process.",
3338 )
@@ -50,22 +55,28 @@
5055 return parser.parse_args()
5156
5257
53-def get_model_and_processors(model_path):
58+def get_model_and_processors(model_path, adapter_path):
5459 model_path = get_model_path(model_path)
5560 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+ )
5764 image_processor = load_image_processor(model_path)
5865 return model, processor, image_processor, config
5966
6067
6168 def main():
6269 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+ )
6476
6577 prompt = codecs.decode(args.prompt, "unicode_escape")
6678
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))
6980
7081 output = generate(
7182 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 @@
197197
198198 class Model(nn.Module):
199199 def __init__(self, config: ModelConfig):
200+ super().__init__()
200201 self.model_type = config.model_type
201202 self.config = config
202203
modified mlx_vlm/models/llava/language.py +17 −6
@@ -21,6 +21,7 @@
2121 rope_theta: float = 10000
2222 rope_traditional: bool = False
2323 rope_scaling: Optional[Dict[str, Union[float, str]]] = None
24+ tie_word_embeddings: bool = False
2425
2526 @classmethod
2627 def from_dict(cls, params):
@@ -58,9 +59,14 @@
5859 head_dim = config.hidden_size // n_heads
5960 self.scale = head_dim**-0.5
6061
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)
6470 self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False)
6571
6672 rope_scale = (
@@ -184,12 +190,13 @@
184190 super().__init__()
185191 self.config = config
186192 self.model_type = config.model_type
187- if self.model_type != "llama":
193+ if self.model_type not in ["llama", "qwen2"]:
188194 raise ValueError(
189195 f"Model type {self.model_type} not supported. Currently only 'llama' is supported"
190196 )
191197 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)
193200
194201 def __call__(
195202 self,
@@ -199,7 +206,11 @@
199206 mask: Optional[mx.array] = None,
200207 ):
201208 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
203214
204215 @staticmethod
205216 def sanitize(weights):
modified mlx_vlm/models/llava/llava.py +1 −0
@@ -56,6 +56,7 @@
5656
5757 class Model(nn.Module):
5858 def __init__(self, config: ModelConfig):
59+ super().__init__()
5960 self.config = config
6061 self.vision_tower = VisionModel(config.vision_config)
6162 self.language_model = LanguageModel(config.text_config)
modified mlx_vlm/models/llava/vision.py +27 −11
@@ -151,31 +151,44 @@
151151 self.image_size = config.image_size
152152 self.patch_size = config.patch_size
153153
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,))
155160
156161 self.patch_embedding = nn.Conv2d(
157162 in_channels=config.num_channels,
158163 out_channels=self.embed_dim,
159164 kernel_size=self.patch_size,
160165 stride=self.patch_size,
161- bias=False,
166+ bias=bias,
162167 )
163168
164169 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+ )
166175 self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
167176
168177 def __call__(self, x: mx.array) -> mx.array:
169178 batch_size = x.shape[0]
170179 patch_embeddings = self.patch_embedding(x)
171180 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+
176190 position_ids = mx.array(np.arange(self.num_positions)[None, :])
177191
178- embeddings = mx.concatenate((cls_embeddings, patch_embeddings), axis=1)
179192 embeddings += self.position_embedding(position_ids)
180193 return embeddings
181194
@@ -183,8 +196,10 @@
183196 class ClipVisionModel(nn.Module):
184197 def __init__(self, config: VisionConfig):
185198 super().__init__()
199+ self.config = config
186200 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)
188203 self.encoder = Encoder(config)
189204 self.post_layernorm = nn.LayerNorm(config.hidden_size)
190205
@@ -194,7 +209,8 @@
194209 output_hidden_states: Optional[bool] = None,
195210 ) -> mx.array:
196211 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)
198214
199215 encoder_states = (x,) if output_hidden_states else None
200216
@@ -212,7 +228,7 @@
212228 super().__init__()
213229
214230 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"]:
216232 raise ValueError(f"Unsupported model type: {self.model_type}")
217233
218234 self.vision_model = ClipVisionModel(config)
modified mlx_vlm/models/llava_bunny/language.py +2 −1
@@ -167,6 +167,7 @@
167167 inputs: mx.array,
168168 cache=None,
169169 inputs_embeds: Optional[mx.array] = None,
170+ mask: Optional[mx.array] = None,
170171 ):
171172 # for passing merged input embeddings
172173 if inputs_embeds is None:
@@ -199,7 +200,7 @@
199200 inputs_embeds: Optional[mx.array] = None,
200201 mask: Optional[mx.array] = None,
201202 ):
202- out = self.model(inputs, cache=cache, inputs_embeds=inputs_embeds)
203+ out = self.model(inputs, cache=cache, inputs_embeds=inputs_embeds, mask=None)
203204 return out
204205
205206 def sanitize(self, weights):
modified mlx_vlm/models/llava_bunny/llava_bunny.py +18 −20
@@ -118,6 +118,7 @@
118118
119119 class Model(nn.Module):
120120 def __init__(self, config: ModelConfig):
121+ super().__init__()
121122 self.model_type = config.model_type
122123 self.config = config
123124
@@ -151,31 +152,28 @@
151152
152153 def _prepare_inputs_for_multimodal(self, image_features, inputs_embeds, input_ids):
153154 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
155157
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)
158160
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())
164166
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 :])
167170
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)
175173
176174 # 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)
179177
180178 def __call__(
181179 self,
@@ -187,7 +185,7 @@
187185 ):
188186 input_embeddings = self.get_input_embeddings(input_ids, pixel_values)
189187 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
191189 )
192190 return logits
193191
modified mlx_vlm/models/llava_bunny/vision.py +2 −2
@@ -207,9 +207,9 @@
207207 batch_size = x.shape[0]
208208 patch_embeddings = self.patch_embedding(x)
209209 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, :])
211211 embeddings = patch_embeddings
212- embeddings += self.position_embedding(self.position_ids)
212+ embeddings += self.position_embedding(position_ids)
213213 return embeddings
214214
215215
modified mlx_vlm/models/llava_next/llava_next.py +1 −0
@@ -56,6 +56,7 @@
5656
5757 class Model(nn.Module):
5858 def __init__(self, config: ModelConfig):
59+ super().__init__()
5960 self.config = config
6061 self.vision_tower = VisionModel(config.vision_config)
6162 self.language_model = LanguageModel(config.text_config)
modified mlx_vlm/models/multi_modality/multi_modality.py +1 −0
@@ -238,6 +238,7 @@
238238
239239 class Model(nn.Module):
240240 def __init__(self, config: ModelConfig):
241+ super().__init__()
241242 self.config = config
242243 self.vision_model = VisionModel(config.vision_config)
243244 self.language_model = LanguageModel(config.text_config)
modified mlx_vlm/models/paligemma/paligemma.py +1 −0
@@ -52,6 +52,7 @@
5252
5353 class Model(nn.Module):
5454 def __init__(self, config: ModelConfig):
55+ super().__init__()
5556 self.model_type = config.model_type
5657 self.config = config
5758
modified mlx_vlm/models/phi3_v/phi3_v.py +2 −1
@@ -209,9 +209,10 @@
209209 pixel_values=None,
210210 mask=None,
211211 cache=None,
212+ image_sizes=None,
212213 **kwargs,
213214 ):
214- out = self.model(inputs, pixel_values, mask, cache)
215+ out = self.model(inputs, pixel_values, image_sizes, cache)
215216 return self.lm_head(out).astype(self.lm_head.weight.dtype)
216217
217218 @property
modified mlx_vlm/models/pixtral/pixtral.py +25 −14
@@ -56,6 +56,7 @@
5656
5757 class Model(nn.Module):
5858 def __init__(self, config: ModelConfig):
59+ super().__init__()
5960 self.config = config
6061 self.vision_tower = VisionModel(config.vision_config)
6162 self.language_model = LanguageModel(config.text_config)
@@ -74,24 +75,33 @@
7475 # Get the input embeddings from the language model
7576 inputs_embeds = self.language_model.model.embed_tokens(input_ids)
7677
78+ # Get number of images
79+ num_images = len(pixel_values[0])
80+
7781 # 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
7899 *_, 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
80101 )
81-
82102 # Select the hidden states from the desired layer
83103 selected_image_feature = hidden_states[self.vision_feature_layer]
84104
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-
95105 # Pass image features through the multi-modal projector
96106 image_features = self.multi_modal_projector(selected_image_feature)
97107
@@ -117,7 +127,8 @@
117127 text_segments.append(inputs_embeds[:, start_idx:position])
118128 start_idx = position + 1
119129
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)
121132 final_embeddings = [v for p in zip(text_segments, image_embeddings) for v in p]
122133 final_embeddings += [inputs_embeds[:, start_idx:]]
123134
@@ -181,7 +192,7 @@
181192
182193 def sanitize(self, weights):
183194 def transform_key(key):
184- if "vision_tower" in key:
195+ if "vision_tower" in key and "vision_model" not in key:
185196 if "transformer" in key:
186197 key = key.replace("vision_tower", "vision_tower.vision_model")
187198 if "patch_conv" in key:
modified mlx_vlm/models/pixtral/vision.py +5 −5
@@ -1,6 +1,6 @@
11 import inspect
22 from dataclasses import dataclass
3-from typing import Optional
3+from typing import List, Optional
44
55 import mlx.core as mx
66 import mlx.nn as nn
@@ -253,11 +253,11 @@
253253
254254 def __call__(
255255 self,
256- x: mx.array,
256+ x: List[mx.array],
257257 output_hidden_states: Optional[bool] = None,
258258 ) -> 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]
261261
262262 patch_embeds = mx.concatenate(
263263 [p.reshape(B, -1, p.shape[-1]) for p in patch_embeds_list], axis=1
@@ -299,7 +299,7 @@
299299 self.vision_model = PixtralVisionModel(config)
300300
301301 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
303303 ) -> mx.array:
304304 return self.vision_model(x, output_hidden_states)
305305
modified mlx_vlm/models/qwen2_vl/language.py +4 −0
@@ -282,6 +282,10 @@
282282 self.args = args
283283 self.model_type = args.model_type
284284 self.model = Qwen2Model(args)
285+
286+ if args.model_type != "qwen2_vl":
287+ raise ValueError(f"Unsupported model type: {args.model_type}")
288+
285289 if not args.tie_word_embeddings:
286290 self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False)
287291
modified mlx_vlm/models/qwen2_vl/qwen2_vl.py +4 −1
@@ -18,7 +18,6 @@
1818 class ModelConfig:
1919 text_config: TextConfig
2020 vision_config: VisionConfig
21- rope_scaling: dict
2221 model_type: str
2322 ignore_index: int = -100
2423 image_token_index: int = 151655
@@ -39,6 +38,7 @@
3938
4039 class Model(nn.Module):
4140 def __init__(self, config: ModelConfig):
41+ super().__init__()
4242 self.config = config
4343 self.vision_tower = VisionModel(config.vision_config)
4444 self.language_model = LanguageModel(config.text_config)
@@ -61,6 +61,9 @@
6161 pixel_values, image_grid_thw, output_hidden_states=False
6262 )
6363
64+ if hidden_states.ndim == 2:
65+ hidden_states = hidden_states[None, :, :]
66+
6467 # Insert special image tokens in the input_ids
6568 final_inputs_embeds = self._merge_input_ids_with_image_features(
6669 hidden_states, inputs_embeds, input_ids
modified mlx_vlm/models/qwen2_vl/vision.py +14 −2
@@ -19,7 +19,7 @@
1919 mlp_ratio: float = 4.0
2020 in_channels: int = 3
2121 layer_norm_eps: float = 1e-6
22- spatial_patch_size = 14
22+ spatial_patch_size: int = 14
2323 spatial_merge_size: int = 2
2424 temporal_patch_size: int = 2
2525
@@ -320,10 +320,22 @@
320320 grid_thw: mx.array,
321321 output_hidden_states: Optional[bool] = None,
322322 ) -> mx.array:
323+
323324 hidden_states = self.patch_embed(hidden_states)
324325 rotary_pos_emb = self.rot_pos_emb(grid_thw)
325326
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+
327339 cu_seqlens = mx.cumsum(cu_seqlens.astype(mx.int32))
328340 cu_seqlens = mx.pad(cu_seqlens, (1, 0), mode="constant", constant_values=0)
329341
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+):
24 """
35 Get the appropriate JSON message based on the specified model.
46
57 Args:
68 model_name (str): The model for which to generate the message.
79 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).
1013
1114 Returns:
1215 dict: A dictionary representing the JSON message for the specified model.
1316 """
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]()
3384 else:
3485 raise ValueError(f"Unsupported model: {model_name}")
3586
36- return message
3787
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
38133
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]
41136
42137 if "chat_template" in processor.__dict__.keys():
43138 return processor.apply_chat_template(
44- [message],
139+ messages,
45140 tokenize=False,
46- add_generation_prompt=True,
141+ add_generation_prompt=add_generation_prompt,
47142 )
48143
49144 elif "tokenizer" in processor.__dict__.keys():
50145 return processor.tokenizer.apply_chat_template(
51- [message],
146+ messages,
52147 tokenize=False,
53- add_generation_prompt=True,
148+ add_generation_prompt=add_generation_prompt,
54149 )
55150
56151 else:
modified mlx_vlm/tests/test_models.py +44 −2
@@ -62,7 +62,6 @@
6262 shape=(batch_size, image_size[0], image_size[1], num_channels)
6363 )
6464
65- # Perform a forward pass
6665 hidden_states = vision_tower(input_tensor, output_hidden_states=True, **kwargs)
6766
6867 # Check vision hidden feature layer's shape matches the expected hidden size
@@ -620,6 +619,50 @@
620619 (config.vision_config.image_size, config.vision_config.image_size),
621620 )
622621
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+
623666 def test_qwen2_vl(self):
624667 from mlx_vlm.models import qwen2_vl
625668
@@ -656,7 +699,6 @@
656699 model_type="qwen2_vl",
657700 text_config=text_config,
658701 vision_config=vision_config,
659- rope_scaling=text_config.rope_scaling,
660702 image_token_index=151655,
661703 vocab_size=32000,
662704 )
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 @@
2626
2727 from .models.base import BaseImageProcessor, KVCache
2828 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
3031
3132 # Constants
3233 MODEL_REMAPPING = {"llava-qwen2": "llava_bunny", "bunny-llama": "llava_bunny"}
@@ -223,6 +224,7 @@
223224 def load(
224225 path_or_hf_repo: str,
225226 processor_config={},
227+ adapter_path: Optional[str] = None,
226228 lazy: bool = False,
227229 ) -> Tuple[nn.Module, Union[PreTrainedTokenizer, PreTrainedTokenizerFast]]:
228230 """
@@ -247,6 +249,11 @@
247249 model_path = get_model_path(path_or_hf_repo)
248250
249251 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+
250257 processor = load_processor(model_path, processor_config=processor_config)
251258
252259 return model, processor
@@ -288,14 +295,15 @@
288295
289296
290297 def load_processor(
291- model_path, processor_config={"trust_remote_code": True}
298+ model_path, processor_config={"trust_remote_code": True}, add_detokenizer=True
292299 ) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:
293300 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)
299307 return processor
300308
301309
@@ -304,8 +312,7 @@
304312 ) -> Tuple[nn.Module, dict, PreTrainedTokenizer]:
305313 model = load_model(model_path, lazy)
306314 config = load_config(model_path)
307- processor = load_processor(model_path)
308-
315+ processor = load_processor(model_path, add_detokenizer=False)
309316 return model, config, processor
310317
311318
@@ -637,7 +644,7 @@
637644 ):
638645 print("[INFO] Loading")
639646 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)
641648
642649 weights = dict(tree_flatten(model.parameters()))
643650 dtype = mx.float16 if quantize else getattr(mx, dtype)
@@ -666,7 +673,7 @@
666673 for file in py_files:
667674 shutil.copy(file, mlx_path)
668675
669- tokenizer.save_pretrained(mlx_path)
676+ processor.save_pretrained(mlx_path)
670677
671678 save_config(config, config_path=mlx_path / "config.json")
672679
@@ -704,46 +711,86 @@
704711 )
705712
706713
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+):
708731 from transformers.image_utils import load_image
709732
710733 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+ ]
713742
714743 image_grid_thw = None
744+ image_sizes = None
715745 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+ )
720775 else:
721776 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+ )
731780 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"]
735782 else:
736- raise ValueError(
737- f"Invalid pixel_values type: {type(inputs['pixel_values'])}"
738- )
739-
783+ pixel_values = mx.array(inputs["pixel_values"])
740784 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)
742789 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)
745792
746- return input_ids, pixel_values, mask, image_grid_thw
793+ return input_ids, pixel_values, mask, image_grid_thw, image_sizes
747794
748795
749796 def generate_step(
@@ -878,9 +925,11 @@
878925 tokenizer = processor.tokenizer
879926
880927 image_token_index = model.config.image_token_index
881- input_ids, pixel_values, mask = prepare_inputs(
928+ inputs = prepare_inputs(
882929 image_processor, processor, image, prompt, image_token_index
883930 )
931+ input_ids, pixel_values, mask = inputs[:3]
932+ kwargs = {k: v for k, v in zip(["image_grid_thw", "image_sizes"], inputs[3:])}
884933
885934 detokenizer = processor.detokenizer
886935
@@ -944,32 +993,32 @@
944993 tokenizer = processor.tokenizer
945994
946995 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(
948998 image_processor, processor, image, prompt, image_token_index
949999 )
1000+ input_ids, pixel_values, mask = inputs[:3]
1001+ kwargs = {k: v for k, v in zip(["image_grid_thw", "image_sizes"], inputs[3:])}
9501002
951- kwargs = {
952- "image_grid_thw": image_grid_thw,
953- }
954-
1003+ # Initialize timing and detokenizer
9551004 tic = time.perf_counter()
9561005 detokenizer = processor.detokenizer
9571006 detokenizer.reset()
9581007
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)):
9731022
9741023 if n == 0:
9751024 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 @@
11 mlx>=0.18.0
2-numpy
2+datasets>=2.19.1
3+tqdm>=4.66.2
4+numpy>=1.23.4
35 transformers>=4.45.1
46 scipy==1.13.1
57 gradio>=4.44.0
6-Pillow
7-requests
8+Pillow>=10.3.0
9+requests>=2.31.0