/ Модель

Характеристики

Контекст
131 072 токена
Размер весов
16,9 ГБ
Лицензия
Apache 2.0
Архитектура
idefics3 · dense
Библиотека
transformers
Опубликована
5 авг 2024

Idefics3-8B-Llama3

Изображение и текст → текст10 профессий

Мультимодальная модель Hugging Face на базе Llama 3.1 и SigLIP для ответов на вопросы по изображениям, OCR и анализа документов.

95 833скачиваний за 30 дней307лайковвеса обновлены2 дек 2024

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Изображение → текст» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

Idefics3-8B-Llama3 — мультимодальная модель Hugging Face, принимающая текст и одно или несколько изображений в произвольном чередовании и формирующая текстовые ответы. Визуальная часть использует SigLIP SO400M, а языковая основана на Meta-Llama-3.1-8B-Instruct. Модель относится к семейству Idefics3 и доступна в формате safetensors через Transformers.

Модель предназначена для ответов на вопросы по изображениям, описания визуального содержимого, распознавания текста и анализа документов, а также визуальных рассуждений. Она может работать и с текстом без изображений; генерировать изображения не умеет. В README указан английский как язык модели. Для кодирования изображения 364×364 используются 169 визуальных токенов; большие изображения делятся на фрагменты и кодируются отдельно.

Модель улучшает результаты Idefics2 на приведённых в карточке тестах, особенно на задачах понимания документов. Постобучение включало supervised fine-tuning без RLHF, поэтому ответы могут быть краткими и иногда требуют уточнения запроса. Результаты могут содержать фактические ошибки; модель не предназначена для критически важных решений и сценариев, где необходимы достоверные выводы. Лицензия — Apache 2.0.

Сценарии применения

  • ответы на вопросы по одному или нескольким изображениям
  • описание содержимого фотографий и иллюстраций
  • извлечение текста и сведений из документов на изображениях
  • визуальные рассуждения по диаграммам и сценам
  • создание рассказа с опорой на последовательность изображений

Ограничения

Ответы могут быть краткими и требовать уточнения запроса, а фактическая информация — ошибочной. Модель не предназначена для критически важных решений, оценки людей или генерации изображений.

Для каких профессий подходит10

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Также подходит для

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

Transformers version: >4.46.

Idefics3

Idefics3 is an open multimodal model that accepts arbitrary sequences of image and text inputs and produces text outputs. The model can answer questions about images, describe visual content, create stories grounded on multiple images, or simply behave as a pure language model without visual inputs. It improves upon Idefics1 and Idefics2, significantly enhancing capabilities around OCR, document understanding and visual reasoning.

We release the checkpoints under the Apache 2.0.

Model Summary

Uses

Idefics3-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.

The post-training of Idefics3-8B involves only a supervised fine-tuning stage, without RLHF alignment. As a result, the model may produce short answers or require prompt iterations to fully address the user's request. Adding a prefix to the assistant's response, such as "Let's fix this step by step" has been found to effectively influence the generated output.

To fine-tune Idefics3-8B on a specific task, we provide a fine-tuning tutorial. Other resources for the fine-tuning of Idefics2 (can easily be adapted to Idefics3):

Technical summary

Idefics3 demonstrates a great improvement over Idefics2, especially in document understanding tasks. It serves as a strong foundation for various use-case specific fine-tunings.

ModelMMMU (val)MathVista (test)MMStar (val)DocVQA (test)TextVQA (val)
Idefics2-8B45.252.249.574.073.0
Idefics3-8B46.658.455.987.774.9

Idefics3 introduces several changes compared to Idefics2:

  • We use 169 visual tokens to encode a image of size 364x364. Each image is divided into several sub images of sizes at most 364x364, which are then encoded separately.
  • For the fine-tuning datasets, we have extended The Cauldron and added several datasets, including Docmatix. We will push soon these datasets to the same repo of The Cauldron (TODO).

More details about the training of the model is available in our technical report.

How to Get Started

This section shows snippets of code for generation for Idefics3-8B.

import requests
import torch
from PIL import Image
from io import BytesIO

from transformers import AutoProcessor, AutoModelForVision2Seq
from transformers.image_utils import load_image

DEVICE = "cuda:0"

# Note that passing the image urls (instead of the actual pil images) to the processor is also possible
image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")

processor = AutoProcessor.from_pretrained("HuggingFaceM4/Idefics3-8B-Llama3")
model = AutoModelForVision2Seq.from_pretrained(
    "HuggingFaceM4/Idefics3-8B-Llama3", torch_dtype=torch.bfloat16
).to(DEVICE)

# Create inputs
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "What do we see in this image?"},
        ]
    },
    {
        "role": "assistant",
        "content": [
            {"type": "text", "text": "In this image, we can see the city of New York, and more specifically the Statue of Liberty."},
        ]
    },
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "And how about this image?"},
        ]
    },       
]
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
inputs = processor(text=prompt, images=[image1, image2], return_tensors="pt")
inputs = {k: v.to(DEVICE) for k, v in inputs.items()}


# Generate
generated_ids = model.generate(**inputs, max_new_tokens=500)
generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)

print(generated_texts)

Text generation inference

TODO.

Model optimizations

If your GPU allows, we first recommend loading (and running inference) in half precision (torch.float16 or torch.bfloat16).

model = AutoModelForVision2Seq.from_pretrained(
    "HuggingFaceM4/Idefics3-8B-Llama3",
+    torch_dtype=torch.bfloat16,    
).to(DEVICE)

Vision encoder efficiency

You can choose the default resolution the images will be rescaled to by adding size= {"longest_edge": N*364} when initializing the processor (AutoProcessor.from_pretrained), with N your desired value. N=4 works best in practice (this is the default value), but for very large images, it could be interesting to pass N=5. This will have an impact on the number of visual tokens passed to the language model. If you are GPU-memory-constrained, you can decrease N, and choose for example N=3 or N=2, especially for low resolution images.

Using Flash-attention 2 to speed up generation

First, make sure to install flash-attn. Refer to the original repository of Flash Attention for the package installation. Simply change the snippet above with:

model = AutoModelForVision2Seq.from_pretrained(
    "HuggingFaceM4/Idefics3-8B-Llama3",
+    torch_dtype=torch.bfloat16,    
+    _attn_implementation="flash_attention_2",
).to(DEVICE)

Misuse and Out-of-scope use

Using the model in high-stakes settings is out of scope for this model. The model is not designed for critical decisions nor uses with any material consequences on an individual's livelihood or wellbeing. The model outputs content that appears factual but may not be correct. Out-of-scope uses include:

  • Usage for evaluating or scoring individuals, such as for employment, education, or credit
  • Applying the model for critical automatic decisions, generating factual content, creating reliable summaries, or generating predictions that must be correct

Intentionally using the model for harm, violating human rights, or other kinds of malicious activities, is a misuse of this model. This includes:

  • Spam generation
  • Disinformation and influence operations
  • Disparagement and defamation
  • Harassment and abuse
  • Deception
  • Unconsented impersonation and imitation
  • Unconsented surveillance

License

The model is built on top of two pre-trained models: google/siglip-so400m-patch14-384 and meta-llama/Meta-Llama-3.1-8B-Instruct. We release the Idefics3 checkpoints under the Apache 2.0 license.

Citation

BibTeX:

@misc{laurençon2024building,
      title={Building and better understanding vision-language models: insights and future directions.}, 
      author={Hugo Laurençon and Andrés Marafioti and Victor Sanh and Léo Tronchon},
      year={2024},
      eprint={2408.12637},
      archivePrefix={arXiv},
      primaryClass={cs.CV}
}

Acknowledgements

We thank @andito and @amyeroberts for helping on the integration in Transformers.

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers

Можно запустить

Подбираем GPU…

Класс архитектуры
Idefics3ForConditionalGeneration
Ревизия весов
fddb4ff

0 моделей