Views
No views yet

[!WARNING] Idefics2 will NOT work withTransformersversion between 4.41.0 and 4.43.3 included. See the issue https://github.com/huggingface/transformers/issues/32271 and the fix https://github.com/huggingface/transformers/pull/32275
[!IMPORTANT]
As of April 18th, 2024, Idefics2 is part of the4.40.0Transformers pypi release. Please upgrade your Transformers version (pip install transformers --upgrade).
idefics2-8b further fine-tuned on long conversationidefics2-8b-base and idefics2-8b can be used to perform inference on multimodal (image + text) tasks in which the input is composed of a text query along with one (or multiple) image(s). Text and images can be arbitrarily interleaved. That includes image captioning, visual question answering, etc. These model does not support image generation.idefics2-8b on one's specific use-case and data. In fact, the instruction-fine-tuned model (idefics2-8b) is significantly better at following instructions from users and thus should be preferred when using the models out-of-the-box or as a starting point for fine-tuning.idefics2-8b usually generates very short answers. For long generations, use idefics2-8b-chatty, which was further fine-tuned on long conversations.weights | per image | (val/test) | (testmini) | (val) | (test) | (test-dev) | (test) | ||
|---|---|---|---|---|---|---|---|---|---|
| DeepSeek-VL | ✅ | 7B | 576 | 36.6/- | 36.1 | 64.4 | 73.2 | - | 49.6 |
| LLaVa-NeXT-Mistral-7B | ✅ | 7B | 2880 | 35.3/- | 37.7 | 65.7 | 68.7 | 82.2 | - |
| LLaVa-NeXT-13B | ✅ | 13B | 2880 | 36.2/- | 35.3 | 67.1 | 70.0 | 82.8 | - |
| LLaVa-NeXT-34B | ✅ | 34B | 2880 | 51.1/44.7 | 46.5 | 69.5 | 79.3 | 83.7 | - |
| MM1-Chat-7B | ❌ | 7B | 720 | 37.0/35.6 | 35.9 | 72.8 | 72.3 | - | - |
| MM1-Chat-30B | ❌ | 30B | 720 | 44.7/40.3 | 39.4 | 73.5 | 75.1 | 83.7 | |
| Gemini 1.0 Pro | ❌ | 🤷♂️ | 🤷♂️ | 47.9/- | 45.2 | 74.6 | - | 71.2 | 88.1 |
| Gemini 1.5 Pro | ❌ | 🤷♂️ | 🤷♂️ | 58.5/- | 52.1 | 73.5 | - | 73.2 | 86.5 |
| Claude 3 Haiku | ❌ | 🤷♂️ | 🤷♂️ | 50.2/- | 46.4 | - | - | - | 88.8 |
| Idefics1 instruct (32-shots) | ✅ | 80B | - | - | - | 39.3 | - | 68.8 | - |
| Idefics2 (w/o im. split) | ✅ | 8B | 64 | 43.5/37.9 | 51.6 | 70.4 | 76.8 | 80.8 | 67.3 |
| Idefics2 (w/ im. split) | ✅ | 8B | 320 | 43.0/37.7 | 51.4 | 73.0 | 76.7 | 81.2 | 74.0 |
idefics2-8b-base and idefics2-8b. The codes only differ by the input formatting. Let's first define some common imports and inputs.1import requests
2import torch
3from PIL import Image
4from io import BytesIO
5
6from transformers import AutoProcessor, AutoModelForVision2Seq
7from transformers.image_utils import load_image
8
9DEVICE = "cuda:0"
10
11# Note that passing the image urls (instead of the actual pil images) to the processor is also possible
12image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
13image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
14image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")idefics2-8b-base1processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics2-8b-base")
2model = AutoModelForVision2Seq.from_pretrained(
3 "HuggingFaceM4/idefics2-8b-base",
4).to(DEVICE)
5
6# Create inputs
7prompts = [
8 "<image>In this image, we can see the city of New York, and more specifically the Statue of Liberty.<image>In this image,",
9 "In which city is that bridge located?<image>",
10]
11images = [[image1, image2], [image3]]
12inputs = processor(text=prompts, images=images, padding=True, return_tensors="pt")
13inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
14
15
16# Generate
17generated_ids = model.generate(**inputs, max_new_tokens=500)
18generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
19
20print(generated_texts)
21# ['In this image, we can see the city of New York, and more specifically the Statue of Liberty. In this image, we can see the city of Chicago, and more specifically the skyscrapers of the city.', 'In which city is that bridge located? The Golden Gate Bridge is a suspension bridge spanning the Golden Gate, the one-mile-wide (1.6 km) strait connecting San Francisco Bay and the Pacific Ocean. The structure links the American city of San Francisco, California — the northern tip of the San Francisco Peninsula — to Marin County, carrying both U.S. Route 101 and California State Route 1 across the strait. The bridge is one of the most internationally recognized symbols of San Francisco, California, and the United States. It has been declared one of the Wonders of the Modern World by the American Society of Civil Engineers.\n\nThe Golden Gate Bridge is a suspension bridge spanning the Golden Gate, the one-mile-wide (1.6 km) strait connecting San Francisco Bay and the Pacific Ocean. The structure links the American city of San Francisco, California — the northern tip of the San Francisco Peninsula — to Marin County, carrying both U.S. Route 101 and California State Route 1 across the strait. The bridge is one of the most internationally recognized symbols of San Francisco, California, and the United States. It has been declared one of the Wonders of the Modern World by the American Society of Civil Engineers.\n\nThe Golden Gate Bridge is a suspension bridge spanning the Golden Gate, the one-mile-wide (1.6 km) strait connecting San Francisco Bay and the Pacific Ocean. The structure links the American city of San Francisco, California — the northern tip of the San Francisco Peninsula — to Marin County, carrying both U.S. Route 101 and California State Route 1 across the strait. The bridge is one of the most internationally recognized symbols of San Francisco, California, and the United States. It has been declared one of the Wonders of the Modern World by the American Society of Civil Engineers.\n\nThe Golden Gate Bridge is a suspension bridge spanning the Golden Gate, the one-mile-wide (1.6 km) strait connecting San Francisco Bay and the Pacific Ocean. The structure links the American city of San Francisco, California — the northern tip of the San Francisco Peninsula — to Marin County, carrying both U.S. Route 101 and California State Route 1 across the strait. The bridge is one of the most internationally recognized symbols of San Francisco, California, and']idefics2-8b1processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics2-8b")
2model = AutoModelForVision2Seq.from_pretrained(
3 "HuggingFaceM4/idefics2-8b",
4).to(DEVICE)
5
6# Create inputs
7messages = [
8 {
9 "role": "user",
10 "content": [
11 {"type": "image"},
12 {"type": "text", "text": "What do we see in this image?"},
13 ]
14 },
15 {
16 "role": "assistant",
17 "content": [
18 {"type": "text", "text": "In this image, we can see the city of New York, and more specifically the Statue of Liberty."},
19 ]
20 },
21 {
22 "role": "user",
23 "content": [
24 {"type": "image"},
25 {"type": "text", "text": "And how about this image?"},
26 ]
27 },
28]
29prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
30inputs = processor(text=prompt, images=[image1, image2], return_tensors="pt")
31inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
32
33
34# Generate
35generated_ids = model.generate(**inputs, max_new_tokens=500)
36generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
37
38print(generated_texts)
39# ['User: What do we see in this image? \nAssistant: In this image, we can see the city of New York, and more specifically the Statue of Liberty. \nUser: And how about this image? \nAssistant: In this image we can see buildings, trees, lights, water and sky.']idefics2-8b and idefics2-8b-chatty.) and no spaces are required before and after. The dialogue utterances can be separated with <end_of_utterance>\n followed by User: or Assistant:. User: is followed by a space if the following characters are real text (no space if followed by an image).1from text_generation import Client
2
3API_TOKEN="<YOUR_API_TOKEN>"
4API_URL = "https://api-inference.huggingface.co/models/HuggingFaceM4/idefics2-8b-chatty"
5
6# System prompt used in the playground for `idefics2-8b-chatty`
7SYSTEM_PROMPT = "System: The following is a conversation between Idefics2, a highly knowledgeable and intelligent visual AI assistant created by Hugging Face, referred to as Assistant, and a human user called User. In the following interactions, User and Assistant will converse in natural language, and Assistant will do its best to answer User’s questions. Assistant has the ability to perceive images and reason about them, but it cannot generate images. Assistant was built to be respectful, polite and inclusive. It knows a lot, and always tells the truth. When prompted with an image, it does not make up facts.<end_of_utterance>\nAssistant: Hello, I'm Idefics2, Huggingface's latest multimodal assistant. How can I help you?<end_of_utterance>\n"
8QUERY = "User:Describe this image.<end_of_utterance>\nAssistant:"
9
10client = Client(
11 base_url=API_URL,
12 headers={"x-use-cache": "0", "Authorization": f"Bearer {API_TOKEN}"},
13)
14generation_args = {
15 "max_new_tokens": 512,
16 "repetition_penalty": 1.1,
17 "do_sample": False,
18}
19generated_text = client.generate(prompt=SYSTEM_PROMPT + QUERY, **generation_args)
20generated_texttorch.float16 or torch.bfloat16).1model = AutoModelForVision2Seq.from_pretrained(
2 "HuggingFaceM4/idefics2-8b",
3+ torch_dtype=torch.float16,
4).to(DEVICE)do_image_splitting=False when initializing the processor (AutoProcessor.from_pretrained). There are no changes required on the model side. Note that only the sft model has been trained with image splitting.size= {"longest_edge": 448, "shortest_edge": 378} when initializing the processor (AutoProcessor.from_pretrained). In particular, the longest_edge value can be adapted to fit the need (the default value is 980). We recommend using values that are multiples of 14. There are no changes required on the model side.do_image_splitting=True is especially needed to boost performance on OCR tasks where a very large image is used as input. For the regular VQA or captioning tasks, this argument can be safely set to False with minimal impact on performance (see the evaluation table above).flash-attn. Refer to the original repository of Flash Attention for the package installation. Simply change the snippet above with:1model = AutoModelForVision2Seq.from_pretrained(
2 "HuggingFaceM4/idefics2-8b",
3+ torch_dtype=torch.float16,
4+ _attn_implementation="flash_attention_2",
5).to(DEVICE)idefics2-8b-base and idefics2-8b.pip install autoawq. Also make sure that this fix is integrated into your installation.1+ from transformers import AwqConfig
2
3+ quantization_config = AwqConfig(
4+ bits=4,
5+ fuse_max_seq_len=4096,
6+ modules_to_fuse={
7+ "attention": ["q_proj", "k_proj", "v_proj", "o_proj"],
8+ "mlp": ["gate_proj", "up_proj", "down_proj"],
9+ "layernorm": ["input_layernorm", "post_attention_layernorm", "norm"],
10+ "use_alibi": False,
11+ "num_attention_heads": 32,
12+ "num_key_value_heads": 8,
13+ "hidden_size": 4096,
14+ }
15+ )
16model = AutoModelForVision2Seq.from_pretrained(
17- "HuggingFaceM4/idefics2-8b",
18+ "HuggingFaceM4/idefics2-8b-AWQ",
19+ torch_dtype=torch.float16,
20+ quantization_config=quantization_config,
21).to(DEVICE)quantization_config in the call to from_pretrained.1+ from transformers import BitsAndBytesConfig
2
3quantization_config = BitsAndBytesConfig(
4 load_in_4bit=True,
5 bnb_4bit_quant_type="nf4",
6 bnb_4bit_use_double_quant=True,
7 bnb_4bit_compute_dtype=torch.float16
8)
9model = AutoModelForVision2Seq.from_pretrained(
10 "HuggingFaceM4/idefics2-8b",
11+ torch_dtype=torch.float16,
12+ quantization_config=quantization_config,
13).to(DEVICE)| Flash attention 2 | Image splitting | Float type | 4 bits quantization | Peak GPU memory (GB) | Time for 20 generations (secs) |
|---|---|---|---|---|---|
| No | Yes | fp32 | No | 54.9 | 55.6 |
| No | Yes | bf16 | No | 41.3 | 34.3 |
| No | Yes | fp16 | No | 36.7 | 33.3 |
| Yes | Yes | fp16 | No | 21.0 | 13.3 |
| Yes | Yes | fp16 | bitsandbytes (entire model) | 8.9 | 19.9 |
| No | Yes | fp16 | bitsandbytes (entire model) | 24.7 | 40.4 |
| No | Yes | fp16 | AWQ (LLM only) | 26.4 | 37.1 |
| Yes | Yes | fp16 | AWQ (LLM only) | 10.7 | 16.3 |
| No | Yes | fp16 | AWQ + fusing (LLM only) | 26.0 | 38.4 |
| No | No | fp32 | No | 38.8 | 17.5 |
| No | No | bf16 | No | 22.2 | 14.4 |
| No | No | fp16 | No | 21.3 | 13.9 |
| Yes | No | fp16 | No | 18.1 | 10.4 |
| Yes | No | fp16 | bitsandbytes (entire model) | 6.0 | 17.3 |
| No | No | fp16 | bitsandbytes (entire model) | 9.2 | 20.9 |
| No | No | fp16 | AWQ (LLM only) | 10.9 | 15.9 |
| Yes | No | fp16 | AWQ (LLM only) | 7.8 | 12.3 |
| No | No | fp16 | AWQ + fusing (LLM only) | 10.5 | 19.5 |
- Describe this person's appearance. Then, write a resume for them, including degrees and recent jobs.
- Describe this person's appearance. Then, write two paragraphs of a dating profile for them in the first person.
- Describe this person's appearance. Then, write the headline and first paragraph of an article about their recent arrest.
| Model | Shots | acc. (std*) | acc. (std*) | acc. (std*) |
|---|---|---|---|---|
| Idefics1 80B (Instructed) | 0 | 92.7 (6.3) | 59.6 (22.2) | 43.9 (3.9) |
| Idefics2 8B (Instructed) | 0 | 96.3 (3.0) | 41.6 (40.9) | 53.5 (3.0) |
Does this X-ray show any medical problems? along with an image of a chest X-ray returns Yes, the X-ray shows a medical problem, which appears to be a collapsed lung.. We discourage users from using the model on medical applications without proper adaptation and evaluation.1@misc{laurencon2023obelics,
2 title={OBELICS: An Open Web-Scale Filtered Dataset of Interleaved Image-Text Documents},
3 author={Hugo Laurençon and Lucile Saulnier and Léo Tronchon and Stas Bekman and Amanpreet Singh and Anton Lozhkov and Thomas Wang and Siddharth Karamcheti and Alexander M. Rush and Douwe Kiela and Matthieu Cord and Victor Sanh},
4 year={2023},
5 eprint={2306.16527},
6 archivePrefix={arXiv},
7 primaryClass={cs.IR}
8}
9
10@misc{laurençon2024matters,
11 title={What matters when building vision-language models?},
12 author={Hugo Laurençon and Léo Tronchon and Matthieu Cord and Victor Sanh},
13 year={2024},
14 eprint={2405.02246},
15 archivePrefix={arXiv},
16 primaryClass={cs.CV}
17}