Views
No views yet

transformers installed from branch or transformers >= 4.45.0.
The model supports multi-image and multi-prompt generation. Meaning that you can pass multiple images in your prompt. Make sure also to follow the correct prompt template by applying chat template:pipeline:"llava-hf/llava-onevision-qwen2-0.5b-ov-hf" checkpoint.1from transformers import pipeline
2
3pipe = pipeline("image-text-to-text", model="llava-onevision-qwen2-0.5b-ov-hf")
4messages = [
5 {
6 "role": "user",
7 "content": [
8 {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"},
9 {"type": "text", "text": "What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud"},
10 ],
11 },
12]
13
14out = pipe(text=messages, max_new_tokens=20)
15print(out)
16>>> [{'input_text': [{'role': 'user', 'content': [{'type': 'image', 'url': 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'}, {'type': 'text', 'text': 'What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud'}]}], 'generated_text': 'Lava'}]transformers:float16 precision on a GPU device:1import requests
2from PIL import Image
3
4import torch
5from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration
6
7model_id = "llava-hf/llava-onevision-qwen2-0.5b-ov-hf"
8model = LlavaOnevisionForConditionalGeneration.from_pretrained(
9 model_id,
10 torch_dtype=torch.float16,
11 low_cpu_mem_usage=True,
12).to(0)
13
14processor = AutoProcessor.from_pretrained(model_id)
15
16# Define a chat history and use `apply_chat_template` to get correctly formatted prompt
17# Each value in "content" has to be a list of dicts with types ("text", "image")
18conversation = [
19 {
20
21 "role": "user",
22 "content": [
23 {"type": "text", "text": "What are these?"},
24 {"type": "image"},
25 ],
26 },
27]
28prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
29
30image_file = "http://images.cocodataset.org/val2017/000000039769.jpg"
31raw_image = Image.open(requests.get(image_file, stream=True).raw)
32inputs = processor(images=raw_image, text=prompt, return_tensors='pt').to(0, torch.float16)
33
34output = model.generate(**inputs, max_new_tokens=200, do_sample=False)
35print(processor.decode(output[0][2:], skip_special_tokens=True))torch.Tensor which you can pass directly to model.generate()1messages = [
2 {
3 "role": "user",
4 "content": [
5 {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"}
6 {"type": "text", "text": "What is shown in this image?"},
7 ],
8 },
9]
10
11inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors"pt")
12output = model.generate(**inputs, max_new_tokens=50)bitsandbytes librarybitsandbytes, pip install bitsandbytes and make sure to have access to a CUDA compatible GPU device. Simply change the snippet above with:1model = LlavaOnevisionForConditionalGeneration.from_pretrained(
2 model_id,
3 torch_dtype=torch.float16,
4 low_cpu_mem_usage=True,
5+ load_in_4bit=True
6)flash-attn. Refer to the original repository of Flash Attention regarding that package installation. Simply change the snippet above with:1model = LlavaOnevisionForConditionalGeneration.from_pretrained(
2 model_id,
3 torch_dtype=torch.float16,
4 low_cpu_mem_usage=True,
5+ use_flash_attention_2=True
6).to(0)npm i @huggingface/transformers1import { AutoProcessor, AutoTokenizer, LlavaOnevisionForConditionalGeneration, RawImage } from '@huggingface/transformers';
2
3// Load tokenizer, processor and model
4const model_id = 'llava-hf/llava-onevision-qwen2-0.5b-ov-hf';
5
6const tokenizer = await AutoTokenizer.from_pretrained(model_id);
7const processor = await AutoProcessor.from_pretrained(model_id);
8const model = await LlavaOnevisionForConditionalGeneration.from_pretrained(model_id, {
9 dtype: {
10 embed_tokens: 'fp16', // or 'fp32' or 'q8'
11 vision_encoder: 'fp16', // or 'fp32' or 'q8'
12 decoder_model_merged: 'q4', // or 'q8'
13 },
14 // device: 'webgpu',
15});
16
17// Prepare text inputs
18const prompt = 'What does the text say?';
19const messages = [
20 { role: 'system', content: 'Answer the question.' },
21 { role: 'user', content: `<image>\n${prompt}` }
22]
23const text = tokenizer.apply_chat_template(messages, { tokenize: false, add_generation_prompt: true });
24const text_inputs = tokenizer(text);
25
26// Prepare vision inputs
27const url = 'https://huggingface.co/qnguyen3/nanoLLaVA/resolve/main/example_1.png';
28const image = await RawImage.fromURL(url);
29const vision_inputs = await processor(image);
30
31// Generate response
32const { past_key_values, sequences } = await model.generate({
33 ...text_inputs,
34 ...vision_inputs,
35 do_sample: false,
36 max_new_tokens: 64,
37 return_dict_in_generate: true,
38});
39
40// Decode output
41const answer = tokenizer.decode(
42 sequences.slice(0, [text_inputs.input_ids.dims[1], null]),
43 { skip_special_tokens: true },
44);
45console.log(answer);
46// The text says "small but mighty" in a playful font.
47
48const new_messages = [
49 ...messages,
50 { role: 'assistant', content: answer },
51 { role: 'user', content: 'How does the text correlate to the context of the image?' }
52]
53const new_text = tokenizer.apply_chat_template(new_messages, { tokenize: false, add_generation_prompt: true });
54const new_text_inputs = tokenizer(new_text);
55
56// Generate another response
57const output = await model.generate({
58 ...new_text_inputs,
59 past_key_values,
60 do_sample: false,
61 max_new_tokens: 256,
62});
63const new_answer = tokenizer.decode(
64 output.slice(0, [new_text_inputs.input_ids.dims[1], null]),
65 { skip_special_tokens: true },
66);
67console.log(new_answer);
68// The text "small but mighty" is likely a playful or humorous reference to the image of the blue mouse with the orange dumbbell. It could be used as a motivational phrase or a playful way to express the idea that even small things can be impressive or powerful.@misc{li2024llavaonevisioneasyvisualtask,
title={LLaVA-OneVision: Easy Visual Task Transfer},
author={Bo Li and Yuanhan Zhang and Dong Guo and Renrui Zhang and Feng Li and Hao Zhang and Kaichen Zhang and Yanwei Li and Ziwei Liu and Chunyuan Li},
year={2024},
eprint={2408.03326},
archivePrefix={arXiv},
primaryClass={cs.CV},
url={https://arxiv.org/abs/2408.03326},
}