Elffuss BraidHub

kikocis/mlx-vlm public

Add example notebooks and support for system role  (#95)

* update use case examples

* add multi-image and text extraction examples

* add process image

* formatting
Changeset76521ecd98b88b2b4d4e1e20f4337a285034383561b1b302bde79a89e4eb8a89
AuthorPrince Canuma <prince.gdt@gmail.com> · 2024-10-19 18:31 +02:00
CommitterGitHub <noreply@github.com> · 2024-10-19 18:31 +02:00
Parentsc9c73c098953

Browse the files at this changeset

13 files changed

modified .gitignore +1 −1
@@ -1,4 +1,4 @@
1-**.ipynb
1+test.ipynb
22 **.pyc
33
44 Byte-compiled / optimized / DLL files
added examples/images/cats.jpg +0 −0

Binary content is not shown. View the file.

added examples/images/desktop_setup.png +0 −0

Binary content is not shown. View the file.

added examples/images/graph.png +0 −0

Binary content is not shown. View the file.

added examples/images/handwritten_hard.webp +0 −0

Binary content is not shown. View the file.

added examples/images/latex.png +0 −0

Binary content is not shown. View the file.

added examples/images/paper.png +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

added examples/multi_image_generation.ipynb +281 −0
@@ -0,0 +1,281 @@
1+{
2+ "cells": [
3+ {
4+ "cell_type": "markdown",
5+ "metadata": {},
6+ "source": [
7+ "# Multi-Image Generation\n",
8+ "\n",
9+ "In this example, you will learn how to generate text from multiple images using the supported models: `Qwen2-VL`, `Pixtral` and `llava-interleaved`.\n",
10+ "\n",
11+ "Multi-image generation allows you to pass a list of images to the model and generate text conditioned on all the images.\n"
12+ ]
13+ },
14+ {
15+ "cell_type": "code",
16+ "execution_count": 1,
17+ "metadata": {},
18+ "outputs": [],
19+ "source": [
20+ "from mlx_vlm import load, apply_chat_template, generate\n",
21+ "from mlx_vlm.utils import load_image\n",
22+ "from mlx_vlm.utils import process_image"
23+ ]
24+ },
25+ {
26+ "cell_type": "code",
27+ "execution_count": 2,
28+ "metadata": {},
29+ "outputs": [],
30+ "source": [
31+ "images = [\"images/cats.jpg\", \"images/desktop_setup.png\"]\n",
32+ "\n",
33+ "messages = [\n",
34+ " {\"role\": \"user\", \"content\": \"Describe what you see in the images.\"}\n",
35+ "]"
36+ ]
37+ },
38+ {
39+ "cell_type": "markdown",
40+ "metadata": {},
41+ "source": [
42+ "## Qwen2-VL"
43+ ]
44+ },
45+ {
46+ "cell_type": "code",
47+ "execution_count": null,
48+ "metadata": {},
49+ "outputs": [],
50+ "source": [
51+ "# Load model and processor\n",
52+ "qwen_vl_model, qwen_vl_processor = load(\"mlx-community/Qwen2-VL-7B-Instruct-4bit\")\n",
53+ "qwen_vl_config = qwen_vl_model.config"
54+ ]
55+ },
56+ {
57+ "cell_type": "code",
58+ "execution_count": 4,
59+ "metadata": {},
60+ "outputs": [],
61+ "source": [
62+ "prompt = apply_chat_template(qwen_vl_processor, qwen_vl_config, messages, num_images=len(images))"
63+ ]
64+ },
65+ {
66+ "cell_type": "code",
67+ "execution_count": 5,
68+ "metadata": {},
69+ "outputs": [
70+ {
71+ "name": "stdout",
72+ "output_type": "stream",
73+ "text": [
74+ "==========\n",
75+ "Image: ['images/cats.jpg', 'images/desktop_setup.png'] \n",
76+ "\n",
77+ "Prompt: <|im_start|>system\n",
78+ "You are a helpful assistant.<|im_end|>\n",
79+ "<|im_start|>user\n",
80+ "Describe what you see in the images.<|vision_start|><|image_pad|><|vision_end|><|vision_start|><|image_pad|><|vision_end|><|im_end|>\n",
81+ "<|im_start|>assistant\n",
82+ "\n",
83+ "The image shows a cozy home office setup with a pink blanket covering the desk and chair. There are two cats lounging on the blanket, one on the left side and the other on the right side of the desk. The desk has a computer monitor, keyboard, and mouse. There are also speakers on either side of the monitor, a remote control, and a small plant on the left side of the desk. The wall behind the desk has a framed text that says, \"Don't grow up, it's a trap.\" The overall scene is playful and relaxed, with the cats adding a touch of whimsy to the workspace.\n",
84+ "==========\n",
85+ "Prompt: 10.047 tokens-per-sec\n",
86+ "Generation: 28.392 tokens-per-sec\n"
87+ ]
88+ }
89+ ],
90+ "source": [
91+ "qwen_vl_output = generate(\n",
92+ " qwen_vl_model,\n",
93+ " qwen_vl_processor,\n",
94+ " images,\n",
95+ " prompt,\n",
96+ " max_tokens=1000,\n",
97+ " temperature=0.7,\n",
98+ " verbose=True\n",
99+ ")"
100+ ]
101+ },
102+ {
103+ "cell_type": "markdown",
104+ "metadata": {},
105+ "source": [
106+ "## Pixtral"
107+ ]
108+ },
109+ {
110+ "cell_type": "code",
111+ "execution_count": null,
112+ "metadata": {},
113+ "outputs": [],
114+ "source": [
115+ "# Load model and processor\n",
116+ "pixtral_model, pixtral_processor = load(\"mlx-community/pixtral-12b-4bit\")\n",
117+ "pixtral_config = pixtral_model.config"
118+ ]
119+ },
120+ {
121+ "cell_type": "code",
122+ "execution_count": 4,
123+ "metadata": {},
124+ "outputs": [],
125+ "source": [
126+ "\n",
127+ "prompt = apply_chat_template(pixtral_processor, pixtral_config, messages, num_images=len(images))"
128+ ]
129+ },
130+ {
131+ "cell_type": "code",
132+ "execution_count": 14,
133+ "metadata": {},
134+ "outputs": [],
135+ "source": [
136+ "# Pixtral requires images to be resized to the same shape in multi-image generation\n",
137+ "resized_images = [process_image(load_image(image), (560, 560), None) for image in images]"
138+ ]
139+ },
140+ {
141+ "cell_type": "code",
142+ "execution_count": 16,
143+ "metadata": {},
144+ "outputs": [
145+ {
146+ "name": "stdout",
147+ "output_type": "stream",
148+ "text": [
149+ "==========\n",
150+ "Image: [<PIL.Image.Image image mode=RGB size=560x420 at 0x3ACDD5FF0>, <PIL.Image.Image image mode=RGB size=560x347 at 0x39D697820>] \n",
151+ "\n",
152+ "Prompt: <s>[INST]Describe what you see in the images.[IMG][IMG][/INST]\n",
153+ "The first image shows two cats lying on a pink couch. One cat is on the left side, and the other is on the right side. Both cats appear to be relaxed and comfortable. There are two remote controls on the couch, one near each cat. The background of the image is a plain, light-colored wall.\n",
154+ "\n",
155+ "The second image depicts a home office setup. The main elements include:\n",
156+ "\n",
157+ "1. A wooden desk with a computer monitor in the center.\n",
158+ "2. Two black speakers on either side of the monitor.\n",
159+ "3. A black office chair in front of the desk.\n",
160+ "4. A wooden shelf on the left side of the desk, holding various items including records and a potted plant.\n",
161+ "5. A framed poster on the wall behind the desk with the text \"Don't Grow Up, It's a Trap.\"\n",
162+ "6. A drum set on the right side of the image, partially visible.\n",
163+ "\n",
164+ "The overall setting of the second image is a modern, minimalist workspace with personal touches.\n",
165+ "==========\n",
166+ "Prompt: 2.203 tokens-per-sec\n",
167+ "Generation: 24.366 tokens-per-sec\n"
168+ ]
169+ }
170+ ],
171+ "source": [
172+ "pixtral_output = generate(\n",
173+ " pixtral_model,\n",
174+ " pixtral_processor,\n",
175+ " resized_images,\n",
176+ " prompt,\n",
177+ " max_tokens=1000,\n",
178+ " temperature=0.7,\n",
179+ " verbose=True\n",
180+ ")"
181+ ]
182+ },
183+ {
184+ "cell_type": "markdown",
185+ "metadata": {},
186+ "source": [
187+ "## Llava-Interleaved"
188+ ]
189+ },
190+ {
191+ "cell_type": "code",
192+ "execution_count": null,
193+ "metadata": {},
194+ "outputs": [],
195+ "source": [
196+ "# Load model and processor\n",
197+ "llava_model, llava_processor = load(\"mlx-community/llava-interleave-qwen-0.5b-bf16\")\n",
198+ "llava_config = llava_model.config"
199+ ]
200+ },
201+ {
202+ "cell_type": "code",
203+ "execution_count": 4,
204+ "metadata": {},
205+ "outputs": [],
206+ "source": [
207+ "prompt = apply_chat_template(llava_processor, llava_config, messages, num_images=len(images))"
208+ ]
209+ },
210+ {
211+ "cell_type": "code",
212+ "execution_count": 5,
213+ "metadata": {},
214+ "outputs": [
215+ {
216+ "name": "stderr",
217+ "output_type": "stream",
218+ "text": [
219+ "Expanding inputs for image tokens in LLaVa should be done in processing. Please add `patch_size` and `vision_feature_select_strategy` to the model's processing config or set directly with `processor.patch_size = {{patch_size}}` and processor.vision_feature_select_strategy = {{vision_feature_select_strategy}}`. Using processors without these attributes in the config is deprecated and will throw an error in v4.47.\n"
220+ ]
221+ },
222+ {
223+ "name": "stdout",
224+ "output_type": "stream",
225+ "text": [
226+ "==========\n",
227+ "Image: ['images/cats.jpg', 'images/desktop_setup.png'] \n",
228+ "\n",
229+ "Prompt: <|im_start|>user\n",
230+ "<image><image>\n",
231+ "Describe what you see in the images.<|im_end|>\n",
232+ "<|im_start|>assistant\n",
233+ "\n",
234+ "The image captures a cozy scene in a room. Two cats, one gray and the other brown and white, are lying on a pink couch. The gray cat is resting its head on the back of the couch, while the brown and white cat is lying on its side. They are both facing the camera, their relaxed postures suggesting a sense of comfort and tranquility.\n",
235+ "\n",
236+ "The room itself is a study in simplicity. A whiteboard hangs on the wall, a black computer monitor sits on a wooden desk, and a black speaker stands tall on a shelf. The walls are painted a light pink, providing a warm and inviting backdrop to the scene.\n",
237+ "\n",
238+ "On the desk, there's a black keyboard and a white mouse, ready for use. A plant sits on a small table next to the desk, adding a touch of nature to the room. A whiteboard eraser is also present on the desk, perhaps used for cleaning or marking.\n",
239+ "\n",
240+ "Overall, the image paints a picture of a comfortable and well-organized living space, where the cats have found their place and are enjoying their time.\n",
241+ "==========\n",
242+ "Prompt: 28.728 tokens-per-sec\n",
243+ "Generation: 52.317 tokens-per-sec\n"
244+ ]
245+ }
246+ ],
247+ "source": [
248+ "llava_output = generate(\n",
249+ " llava_model,\n",
250+ " llava_processor,\n",
251+ " images,\n",
252+ " prompt,\n",
253+ " max_tokens=1000,\n",
254+ " temperature=0.7,\n",
255+ " verbose=True\n",
256+ ")"
257+ ]
258+ }
259+ ],
260+ "metadata": {
261+ "kernelspec": {
262+ "display_name": "mlx_code",
263+ "language": "python",
264+ "name": "python3"
265+ },
266+ "language_info": {
267+ "codemirror_mode": {
268+ "name": "ipython",
269+ "version": 3
270+ },
271+ "file_extension": ".py",
272+ "mimetype": "text/x-python",
273+ "name": "python",
274+ "nbconvert_exporter": "python",
275+ "pygments_lexer": "ipython3",
276+ "version": "3.10.13"
277+ }
278+ },
279+ "nbformat": 4,
280+ "nbformat_minor": 2
281+}
added examples/object_detection.ipynb +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

added examples/text_extraction.ipynb +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

added examples/utils.py +143 −0
@@ -0,0 +1,143 @@
1+import json
2+import re
3+
4+import matplotlib.patches as patches
5+import matplotlib.pyplot as plt
6+import numpy as np
7+from PIL import Image
8+
9+
10+def normalize_bbox(model_type, x_min, y_min, x_max, y_max, image_width, image_height):
11+ # Normalize coordinates
12+ if model_type == "paligemma":
13+ y_min_norm = max(0, min(y_min / 1024 * image_height, image_height))
14+ x_min_norm = max(0, min(x_min / 1024 * image_width, image_width))
15+ y_max_norm = max(0, min(y_max / 1024 * image_height, image_height))
16+ x_max_norm = max(0, min(x_max / 1024 * image_width, image_width))
17+ elif model_type == "qwen":
18+ y_min_norm = y_min / 1000 * image_height
19+ x_min_norm = x_min / 1000 * image_width
20+ y_max_norm = y_max / 1000 * image_height
21+ x_max_norm = x_max / 1000 * image_width
22+ return x_min_norm, y_min_norm, x_max_norm, y_max_norm
23+
24+
25+def plot_image_with_bboxes(image, bboxes=None, labels=None, model_type="qwen"):
26+ # Load the image if it's a string path, otherwise use the image object
27+ image = Image.open(image) if isinstance(image, str) else image
28+ image_width, image_height = image.size
29+
30+ # Create figure and axes
31+ fig, ax = plt.subplots(1)
32+
33+ # Display the image
34+ ax.imshow(image)
35+
36+ if bboxes is not None:
37+ # Check if bboxes is a list of dictionaries
38+ if isinstance(bboxes, list) and all(isinstance(bbox, dict) for bbox in bboxes):
39+ # Define colors for different objects
40+ num_boxes = len(bboxes)
41+ colors = plt.cm.rainbow(np.linspace(0, 1, num_boxes))
42+
43+ # Iterate over each bbox dictionary
44+ for i, (bbox, color) in enumerate(zip(bboxes, colors)):
45+ label = bbox.get("object", None)
46+ bbox_coords = bbox.get("bboxes", None)
47+ x_min, y_min, x_max, y_max = bbox_coords[0]
48+
49+ # Normalize coordinates
50+ x_min_norm, y_min_norm, x_max_norm, y_max_norm = normalize_bbox(
51+ model_type, x_min, y_min, x_max, y_max, image_width, image_height
52+ )
53+
54+ # Calculate width and height
55+ width = x_max_norm - x_min_norm
56+ height = y_max_norm - y_min_norm
57+
58+ # Create and add the rectangle patch
59+ rect = patches.Rectangle(
60+ (x_min_norm, y_min_norm),
61+ width,
62+ height,
63+ linewidth=2,
64+ edgecolor=color,
65+ facecolor="none",
66+ )
67+ ax.add_patch(rect)
68+
69+ # Add label if available
70+ if label is not None:
71+ ax.text(
72+ x_min_norm,
73+ y_min_norm,
74+ label,
75+ color=color,
76+ fontweight="bold",
77+ bbox=dict(facecolor="white", edgecolor=color, alpha=0.8),
78+ )
79+ else:
80+ # Original code for handling bboxes as a flat list
81+ num_boxes = len(bboxes) // 4
82+ colors = plt.cm.rainbow(np.linspace(0, 1, num_boxes))
83+
84+ for i, color in zip(range(0, len(bboxes), 4), colors):
85+ x_min, y_min, x_max, y_max = bboxes[i : i + 4]
86+
87+ # Normalize coordinates
88+ x_min_norm, y_min_norm, x_max_norm, y_max_norm = normalize_bbox(
89+ model_type, x_min, y_min, x_max, y_max, image_width, image_height
90+ )
91+
92+ # Calculate width and height
93+ width = x_max_norm - x_min_norm
94+ height = y_max_norm - y_min_norm
95+
96+ # Create and add the rectangle patch
97+ rect = patches.Rectangle(
98+ (x_min_norm, y_min_norm),
99+ width,
100+ height,
101+ linewidth=2,
102+ edgecolor=color,
103+ facecolor="none",
104+ )
105+ ax.add_patch(rect)
106+
107+ # Add label if available
108+ if labels is not None and i // 4 < len(labels):
109+ ax.text(
110+ x_min_norm,
111+ y_min_norm,
112+ labels[i // 4],
113+ color=color,
114+ fontweight="bold",
115+ bbox=dict(facecolor="white", edgecolor=color, alpha=0.8),
116+ )
117+
118+ plt.axis("off")
119+ plt.tight_layout()
120+
121+
122+def swap_x_y(bboxes):
123+ bboxes[0], bboxes[1] = bboxes[1], bboxes[0]
124+ bboxes[2], bboxes[3] = bboxes[3], bboxes[2]
125+ return bboxes
126+
127+
128+def parse_bbox(bbox_str, model_type="paligemma"):
129+ if model_type == "paligemma":
130+ objects = []
131+ bboxes = bbox_str.split(";")
132+ for bbox in bboxes:
133+ reg = re.finditer(r"<loc(\d+)>", bbox)
134+ name = bbox.split(">")[-1].strip()
135+ objects.append(
136+ {
137+ "object": name,
138+ "bboxes": [swap_x_y([int(loc.group(1)) for loc in reg])],
139+ }
140+ )
141+ return objects
142+ if model_type == "qwen":
143+ return json.loads(bbox_str.replace("```json", "").replace("```", ""))
modified mlx_vlm/__init__.py +1 −1
@@ -1,3 +1,3 @@
11 from .prompt_utils import apply_chat_template, get_message_json
2-from .utils import convert, generate, load, prepare_inputs
2+from .utils import convert, generate, load, prepare_inputs, process_image
33 from .version import __version__
modified mlx_vlm/prompt_utils.py +15 −7
@@ -20,6 +20,8 @@
2020 return {"role": role, "content": prompt}
2121
2222 def add_image_tokens(message, token_format):
23+ if role == "system":
24+ return message
2325 if role == "user" and not skip_image_token:
2426 if isinstance(message["content"], list):
2527 message["content"].extend([{"type": "image"}] * num_images)
@@ -119,14 +121,20 @@
119121 messages = []
120122 if isinstance(prompt, list):
121123 if isinstance(prompt[0], dict):
122- messages = [process_single_prompt(p, i == 0) for i, p in enumerate(prompt)]
124+ for i, p in enumerate(prompt):
125+ if p.get("role") in ["system", "assistant"]:
126+ messages.append(process_single_prompt(p, False))
127+ else:
128+ is_first = i == 0 or i == 1
129+ messages.append(process_single_prompt(p, is_first))
123130 else:
124- messages = [
125- msg
126- for prompts in prompt
127- for i, p in enumerate(prompts)
128- for msg in [process_single_prompt(p, i == 0)]
129- ]
131+ for prompts in prompt:
132+ for i, p in enumerate(prompts):
133+ if p.get("role") in ["system", "assistant"]:
134+ messages.append(process_single_prompt(p, False))
135+ else:
136+ is_first = i == 0 or i == 1
137+ messages.append(process_single_prompt(p, is_first))
130138 else:
131139 messages = [process_single_prompt(prompt)]
132140