File size: 16,913 Bytes
36f2a72 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# (Frustratingly Easy) LLaVA OneVision Tutorial\n",
"\n",
"We know that it's always beneficial to have a unified interface for different tasks. So we are trying to unify the interface for image, text, image-text interleaved, and video input. And in this tutorial, we aim to provide the most straightforward way to use our model. \n",
"\n",
"We use our 0.5B version as an example. This could be running on a GPU with 4GB memory. And with the following examples, you could see it's surprisingly have promising performance on understanding the image, interleaved image-text, and video. Tiny but mighty!\n",
"\n",
"The same code could be used for 7B model as well.\n",
"\n",
"## Inference Guidance\n",
"\n",
"First please install our repo with code and environments: pip install git+https://github.com/LLaVA-VL/LLaVA-NeXT.git\n",
"\n",
"Here is a quick inference code using [lmms-lab/qwen2-0.5b-si](https://huggingface.co/lmms-lab/llava-onevision-qwen2-0.5b-si) as an example. You will need to install `flash-attn` to use this code snippet. If you don't want to install it, you can set `attn_implementation=None` when load_pretrained_model\n",
"\n",
"### Image Input\n",
"Tackling the single image input with LLaVA OneVision is pretty straightforward."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from llava.model.builder import load_pretrained_model\n",
"from llava.mm_utils import get_model_name_from_path, process_images, tokenizer_image_token\n",
"from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IGNORE_INDEX\n",
"from llava.conversation import conv_templates, SeparatorStyle\n",
"\n",
"from PIL import Image\n",
"import requests\n",
"import copy\n",
"import torch\n",
"\n",
"import sys\n",
"import warnings\n",
"\n",
"warnings.filterwarnings(\"ignore\")\n",
"pretrained = \"lmms-lab/llava-onevision-qwen2-0.5b-si\"\n",
"model_name = \"llava_qwen\"\n",
"device = \"cuda\"\n",
"device_map = \"auto\"\n",
"llava_model_args = {\n",
" \"multimodal\": True,\n",
" \"attn_implementation\": \"sdpa\",\n",
"}\n",
"tokenizer, model, image_processor, max_length = load_pretrained_model(pretrained, None, model_name, device_map=device_map, **llava_model_args) # Add any other thing you want to pass in llava_model_args\n",
"\n",
"model.eval()\n",
"\n",
"url = \"https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true\"\n",
"image = Image.open(requests.get(url, stream=True).raw)\n",
"image_tensor = process_images([image], image_processor, model.config)\n",
"image_tensor = [_image.to(dtype=torch.float16, device=device) for _image in image_tensor]\n",
"\n",
"conv_template = \"qwen_1_5\" # Make sure you use correct chat template for different models\n",
"question = DEFAULT_IMAGE_TOKEN + \"\\nWhat is shown in this image?\"\n",
"conv = copy.deepcopy(conv_templates[conv_template])\n",
"conv.append_message(conv.roles[0], question)\n",
"conv.append_message(conv.roles[1], None)\n",
"prompt_question = conv.get_prompt()\n",
"\n",
"input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors=\"pt\").unsqueeze(0).to(device)\n",
"image_sizes = [image.size]\n",
"\n",
"\n",
"cont = model.generate(\n",
" input_ids,\n",
" images=image_tensor,\n",
" image_sizes=image_sizes,\n",
" do_sample=False,\n",
" temperature=0,\n",
" max_new_tokens=4096,\n",
")\n",
"text_outputs = tokenizer.batch_decode(cont, skip_special_tokens=True)\n",
"print(text_outputs)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You could use the following code to make it streaming in terminal, this would be pretty useful when creating a chatbot."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from threading import Thread\n",
"from transformers import TextIteratorStreamer\n",
"import json\n",
"\n",
"url = \"https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true\"\n",
"image = Image.open(requests.get(url, stream=True).raw)\n",
"image_tensor = process_images([image], image_processor, model.config)\n",
"image_tensor = [_image.to(dtype=torch.float16, device=device) for _image in image_tensor]\n",
"\n",
"conv_template = \"qwen_1_5\"\n",
"question = DEFAULT_IMAGE_TOKEN + \"\\nWhat is shown in this image?\"\n",
"conv = copy.deepcopy(conv_templates[conv_template])\n",
"conv.append_message(conv.roles[0], question)\n",
"conv.append_message(conv.roles[1], None)\n",
"prompt_question = conv.get_prompt()\n",
"\n",
"input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors=\"pt\").unsqueeze(0).to(device)\n",
"image_sizes = [image.size]\n",
"\n",
"max_context_length = getattr(model.config, \"max_position_embeddings\", 2048)\n",
"num_image_tokens = question.count(DEFAULT_IMAGE_TOKEN) * model.get_vision_tower().num_patches\n",
"\n",
"streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15)\n",
"\n",
"max_new_tokens = min(4096, max_context_length - input_ids.shape[-1] - num_image_tokens)\n",
"\n",
"if max_new_tokens < 1:\n",
" print(\n",
" json.dumps(\n",
" {\n",
" \"text\": question + \"Exceeds max token length. Please start a new conversation, thanks.\",\n",
" \"error_code\": 0,\n",
" }\n",
" )\n",
" )\n",
"else:\n",
" gen_kwargs = {\n",
" \"do_sample\": False,\n",
" \"temperature\": 0,\n",
" \"max_new_tokens\": max_new_tokens,\n",
" \"images\": image_tensor,\n",
" \"image_sizes\": image_sizes,\n",
" }\n",
"\n",
" thread = Thread(\n",
" target=model.generate,\n",
" kwargs=dict(\n",
" inputs=input_ids,\n",
" streamer=streamer,\n",
" **gen_kwargs,\n",
" ),\n",
" )\n",
" thread.start()\n",
"\n",
" generated_text = \"\"\n",
" for new_text in streamer:\n",
" generated_text += new_text\n",
" print(generated_text, flush=True)\n",
" # print(json.dumps({\"text\": generated_text, \"error_code\": 0}), flush=True)\n",
"\n",
" print(\"Final output:\", generated_text)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Image-Text Interleaved Input\n",
"\n",
"Now switching to our onevision model for more complex tasks. You should start to use `llava-onevision-qwen2-0.5b-ov` for image-text interleaved input and video input.\n",
"\n",
"Processing image-text interleaved input is a bit more complicated. But following the code below should work."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Load model\n",
"pretrained = \"lmms-lab/llava-onevision-qwen2-0.5b-ov\"\n",
"model_name = \"llava_qwen\"\n",
"device = \"cuda\"\n",
"device_map = \"auto\"\n",
"llava_model_args = {\n",
" \"multimodal\": True,\n",
" }\n",
"overwrite_config = {}\n",
"overwrite_config[\"image_aspect_ratio\"] = \"pad\"\n",
"llava_model_args[\"overwrite_config\"] = overwrite_config\n",
"tokenizer, model, image_processor, max_length = load_pretrained_model(pretrained, None, model_name, device_map=device_map, **llava_model_args)\n",
"\n",
"model.eval()\n",
"\n",
"# Load two images\n",
"url1 = \"https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true\"\n",
"url2 = \"https://raw.githubusercontent.com/haotian-liu/LLaVA/main/images/llava_logo.png\"\n",
"\n",
"image1 = Image.open(requests.get(url1, stream=True).raw)\n",
"image2 = Image.open(requests.get(url2, stream=True).raw)\n",
"\n",
"images = [image1, image2]\n",
"image_tensors = process_images(images, image_processor, model.config)\n",
"image_tensors = [_image.to(dtype=torch.float16, device=device) for _image in image_tensors]\n",
"\n",
"# Prepare interleaved text-image input\n",
"conv_template = \"qwen_1_5\"\n",
"question = f\"{DEFAULT_IMAGE_TOKEN} This is the first image. Can you describe what you see?\\n\\nNow, let's look at another image: {DEFAULT_IMAGE_TOKEN}\\nWhat's the difference between these two images?\"\n",
"\n",
"conv = copy.deepcopy(conv_templates[conv_template])\n",
"conv.append_message(conv.roles[0], question)\n",
"conv.append_message(conv.roles[1], None)\n",
"prompt_question = conv.get_prompt()\n",
"\n",
"input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors=\"pt\").unsqueeze(0).to(device)\n",
"image_sizes = [image.size for image in images]\n",
"\n",
"# Generate response\n",
"cont = model.generate(\n",
" input_ids,\n",
" images=image_tensors,\n",
" image_sizes=image_sizes,\n",
" do_sample=False,\n",
" temperature=0,\n",
" max_new_tokens=4096,\n",
")\n",
"text_outputs = tokenizer.batch_decode(cont, skip_special_tokens=True)\n",
"print(text_outputs[0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Video Input\n",
"\n",
"Now let's try video input. It's the same as image input, but you need to pass in a list of video frames. And remember to set the `<image>` token only once in the prompt, e.g. \"<image>\\nWhat is shown in this video?\", not \"<image>\\n<image>\\n<image>\\nWhat is shown in this video?\". Since we trained on this format, it's important to keep the format consistent."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/tiger/miniconda3/envs/public_llava/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
" from .autonotebook import tqdm as notebook_tqdm\n",
"/home/tiger/miniconda3/envs/public_llava/lib/python3.10/site-packages/huggingface_hub/file_download.py:1150: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.\n",
" warnings.warn(\n",
"Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Loaded LLaVA model: lmms-lab/llava-onevision-qwen2-7b-ov\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
"You are using a model of type llava to instantiate a model of type llava_qwen. This is not supported for all configurations of models and can yield errors.\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Loading vision tower: google/siglip-so400m-patch14-384\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"Loading checkpoint shards: 100%|██████████| 4/4 [00:08<00:00, 2.07s/it]\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model Class: LlavaQwenForCausalLM\n",
"(16, 1024, 576, 3)\n",
"The video features a person standing on a stage, dressed in a black shirt and dark pants. A large hand appears from the background, reaching towards the person's pocket. The text 'Source: Joshua AG' is displayed at the top left corner of the frames, and 'EVAN CARMICHAEL' is shown in the top right corner. The text 'Anyone know what this pocket is for?' appears as the hand continues to reach into the pocket. The person then looks down at their pocket, and the text 'I've always wondered that' appears. The hand finally pulls out a small white device labeled 'iPod Nano'. The person holds up the iPod Nano, and the text 'is the new iPod Nano' appears. The video concludes with a close-up of the person holding the iPod Nano, showing it from different angles.\n"
]
}
],
"source": [
"from operator import attrgetter\n",
"from llava.model.builder import load_pretrained_model\n",
"from llava.mm_utils import get_model_name_from_path, process_images, tokenizer_image_token\n",
"from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IGNORE_INDEX\n",
"from llava.conversation import conv_templates, SeparatorStyle\n",
"\n",
"import torch\n",
"import cv2\n",
"import numpy as np\n",
"from PIL import Image\n",
"import requests\n",
"import copy\n",
"import warnings\n",
"from decord import VideoReader, cpu\n",
"\n",
"warnings.filterwarnings(\"ignore\")\n",
"# Load the OneVision model\n",
"pretrained = \"lmms-lab/llava-onevision-qwen2-7b-ov\"\n",
"model_name = \"llava_qwen\"\n",
"device = \"cuda\"\n",
"device_map = \"auto\"\n",
"llava_model_args = {\n",
" \"multimodal\": True,\n",
"}\n",
"tokenizer, model, image_processor, max_length = load_pretrained_model(pretrained, None, model_name, device_map=device_map, attn_implementation=\"sdpa\", **llava_model_args)\n",
"\n",
"model.eval()\n",
"\n",
"\n",
"# Function to extract frames from video\n",
"def load_video(video_path, max_frames_num):\n",
" if type(video_path) == str:\n",
" vr = VideoReader(video_path, ctx=cpu(0))\n",
" else:\n",
" vr = VideoReader(video_path[0], ctx=cpu(0))\n",
" total_frame_num = len(vr)\n",
" uniform_sampled_frames = np.linspace(0, total_frame_num - 1, max_frames_num, dtype=int)\n",
" frame_idx = uniform_sampled_frames.tolist()\n",
" spare_frames = vr.get_batch(frame_idx).asnumpy()\n",
" return spare_frames # (frames, height, width, channels)\n",
"\n",
"\n",
"# Load and process video\n",
"video_path = \"jobs.mp4\"\n",
"video_frames = load_video(video_path, 16)\n",
"print(video_frames.shape) # (16, 1024, 576, 3)\n",
"image_tensors = []\n",
"frames = image_processor.preprocess(video_frames, return_tensors=\"pt\")[\"pixel_values\"].half().cuda()\n",
"image_tensors.append(frames)\n",
"\n",
"# Prepare conversation input\n",
"conv_template = \"qwen_1_5\"\n",
"question = f\"{DEFAULT_IMAGE_TOKEN}\\nDescribe what's happening in this video.\"\n",
"\n",
"conv = copy.deepcopy(conv_templates[conv_template])\n",
"conv.append_message(conv.roles[0], question)\n",
"conv.append_message(conv.roles[1], None)\n",
"prompt_question = conv.get_prompt()\n",
"\n",
"input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors=\"pt\").unsqueeze(0).to(device)\n",
"image_sizes = [frame.size for frame in video_frames]\n",
"\n",
"# Generate response\n",
"cont = model.generate(\n",
" input_ids,\n",
" images=image_tensors,\n",
" image_sizes=image_sizes,\n",
" do_sample=False,\n",
" temperature=0,\n",
" max_new_tokens=4096,\n",
" modalities=[\"video\"],\n",
")\n",
"text_outputs = tokenizer.batch_decode(cont, skip_special_tokens=True)\n",
"print(text_outputs[0])"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3.9.2 64-bit",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.14"
},
"vscode": {
"interpreter": {
"hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|