/ Модель

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

Контекст
1 024 токена
Лицензия
MIT
Архитектура
florence2 · dense
Опубликована
29 авг 2024

Florence-2-large-no-flash-attn

Генерация текстаТекст → текст7 профессий

Модифицированная Florence-2-large для анализа изображений по текстовым промптам, включая описание сцен, обнаружение объектов и OCR.

4 680скачиваний за 30 дней26лайковвеса обновлены29 авг 2024

Бенчмарки

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

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

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

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

    Вместе с другими моделями категории «Текст» — сравнение идёт внутри одной категории.

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

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

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

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

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

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

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

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

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

Это модифицированная версия Florence-2-large от Microsoft, опубликованная multimodalart для работы без зависимости flash-attn: специализированные методы внимания заменены стандартным attention, что может снизить производительность. Модель использует плотную seq2seq-архитектуру Florence-2 и содержит около 0,77 млрд параметров; веса представлены в формате PyTorch и обучены в float16. Лицензия — MIT.

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

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

  • Создание кратких и подробных подписей к изображениям
  • Обнаружение объектов и получение их рамок
  • Поиск на изображении объектов, соответствующих текстовой фразе
  • Распознавание текста на изображениях и получение координат текста
  • Генерация описаний отдельных областей изображения

Ограничения

Замена flash-attn на стандартный attention может снизить производительность. Карточка не сообщает языки, поддерживаемые моделью, и не приводит конкретных ограничений точности для отдельных задач.

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

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

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

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

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

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

Открыть на Hugging Face

Florence-2 (without flash-attn): Advancing a Unified Representation for a Variety of Vision Tasks

⚠️ This is a modified version of Florence 2 that modifies the custom modeling_florence2.py file to remove the need for installing flash-attn package (by hijacking the flash-attn methods and replacing with regular attention). It probably has impact in performance.

Model Summary

This Hub repository contains a HuggingFace's transformers implementation of Florence-2 model from Microsoft.

Florence-2 is an advanced vision foundation model that uses a prompt-based approach to handle a wide range of vision and vision-language tasks. Florence-2 can interpret simple text prompts to perform tasks like captioning, object detection, and segmentation. It leverages our FLD-5B dataset, containing 5.4 billion annotations across 126 million images, to master multi-task learning. The model's sequence-to-sequence architecture enables it to excel in both zero-shot and fine-tuned settings, proving to be a competitive vision foundation model.

Resources and Technical Documentation:

ModelModel sizeModel Description
Florence-2-base[HF]0.23BPretrained model with FLD-5B
Florence-2-large[HF]0.77BPretrained model with FLD-5B
Florence-2-base-ft[HF]0.23BFinetuned model on a colletion of downstream tasks
Florence-2-large-ft[HF]0.77BFinetuned model on a colletion of downstream tasks

How to Get Started with the Model

Use the code below to get started with the model. All models are trained with float16.

import requests

import torch
from PIL import Image
from transformers import AutoProcessor, AutoModelForCausalLM 


device = "cuda:0" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32

model = AutoModelForCausalLM.from_pretrained("microsoft/Florence-2-large", torch_dtype=torch_dtype, trust_remote_code=True).to(device)
processor = AutoProcessor.from_pretrained("microsoft/Florence-2-large", trust_remote_code=True)

prompt = "<OD>"

url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg?download=true"
image = Image.open(requests.get(url, stream=True).raw)

inputs = processor(text=prompt, images=image, return_tensors="pt").to(device, torch_dtype)

generated_ids = model.generate(
    input_ids=inputs["input_ids"],
    pixel_values=inputs["pixel_values"],
    max_new_tokens=1024,
    num_beams=3,
    do_sample=False
)
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]

parsed_answer = processor.post_process_generation(generated_text, task="<OD>", image_size=(image.width, image.height))

print(parsed_answer)

Tasks

This model is capable of performing different tasks through changing the prompts.

First, let's define a function to run a prompt.

import requests

import torch
from PIL import Image
from transformers import AutoProcessor, AutoModelForCausalLM 

device = "cuda:0" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32

model = AutoModelForCausalLM.from_pretrained("microsoft/Florence-2-large", torch_dtype=torch_dtype, trust_remote_code=True).to(device)
processor = AutoProcessor.from_pretrained("microsoft/Florence-2-large", trust_remote_code=True)

url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg?download=true"
image = Image.open(requests.get(url, stream=True).raw)

def run_example(task_prompt, text_input=None):
    if text_input is None:
        prompt = task_prompt
    else:
        prompt = task_prompt + text_input
    inputs = processor(text=prompt, images=image, return_tensors="pt").to(device, torch_dtype)
    generated_ids = model.generate(
      input_ids=inputs["input_ids"],
      pixel_values=inputs["pixel_values"],
      max_new_tokens=1024,
      num_beams=3
    )
    generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]

    parsed_answer = processor.post_process_generation(generated_text, task=task_prompt, image_size=(image.width, image.height))

    print(parsed_answer)

Here are the tasks Florence-2 could perform:

Caption

prompt = "<CAPTION>"
run_example(prompt)

Detailed Caption

prompt = "<DETAILED_CAPTION>"
run_example(prompt)

More Detailed Caption

prompt = "<MORE_DETAILED_CAPTION>"
run_example(prompt)

Caption to Phrase Grounding

caption to phrase grounding task requires additional text input, i.e. caption.

Caption to phrase grounding results format: {'<CAPTION_TO_PHRASE_GROUNDING>': {'bboxes': [[x1, y1, x2, y2], ...], 'labels': ['', '', ...]}}

task_prompt = "<CAPTION_TO_PHRASE_GROUNDING>"
results = run_example(task_prompt, text_input="A green car parked in front of a yellow building.")

Object Detection

OD results format: {'<OD>': {'bboxes': [[x1, y1, x2, y2], ...], 'labels': ['label1', 'label2', ...]} }

prompt = "<OD>"
run_example(prompt)

Dense Region Caption

Dense region caption results format: {'<DENSE_REGION_CAPTION>' : {'bboxes': [[x1, y1, x2, y2], ...], 'labels': ['label1', 'label2', ...]} }

prompt = "<DENSE_REGION_CAPTION>"
run_example(prompt)

Region proposal

Dense region caption results format: {'<REGION_PROPOSAL>': {'bboxes': [[x1, y1, x2, y2], ...], 'labels': ['', '', ...]}}

prompt = "<REGION_PROPOSAL>"
run_example(prompt)

OCR

prompt = "<OCR>"
run_example(prompt)

OCR with Region

OCR with region output format: {'<OCR_WITH_REGION>': {'quad_boxes': [[x1, y1, x2, y2, x3, y3, x4, y4], ...], 'labels': ['text1', ...]}}

prompt = "<OCR_WITH_REGION>"
run_example(prompt)

for More detailed examples, please refer to notebook

Benchmarks

Florence-2 Zero-shot performance

The following table presents the zero-shot performance of generalist vision foundation models on image captioning and object detection evaluation tasks. These models have not been exposed to the training data of the evaluation tasks during their training phase.

Method#paramsCOCO Cap. test CIDErNoCaps val CIDErTextCaps val CIDErCOCO Det. val2017 mAP
Flamingo80B84.3---
Florence-2-base0.23B133.0118.770.134.7
Florence-2-large0.77B135.6120.872.837.5

The following table continues the comparison with performance on other vision-language evaluation tasks.

MethodFlickr30k test R@1Refcoco val AccuracyRefcoco test-A AccuracyRefcoco test-B AccuracyRefcoco+ val AccuracyRefcoco+ test-A AccuracyRefcoco+ test-B AccuracyRefcocog val AccuracyRefcocog test AccuracyRefcoco RES val mIoU
Kosmos-278.752.357.447.345.550.742.260.661.7-
Florence-2-base83.653.958.449.751.556.447.966.365.134.6
Florence-2-large84.456.361.651.453.657.949.968.067.035.8

Florence-2 finetuned performance

We finetune Florence-2 models with a collection of downstream tasks, resulting two generalist models Florence-2-base-ft and Florence-2-large-ft that can conduct a wide range of downstream tasks.

The table below compares the performance of specialist and generalist models on various captioning and Visual Question Answering (VQA) tasks. Specialist models are fine-tuned specifically for each task, whereas generalist models are fine-tuned in a task-agnostic manner across all tasks. The symbol "▲" indicates the usage of external OCR as input.

Method# ParamsCOCO Caption Karpathy test CIDErNoCaps val CIDErTextCaps val CIDErVQAv2 test-dev AccTextVQA test-dev AccVizWiz VQA test-dev Acc
Specialist Models
CoCa2.1B143.6122.4-82.3--
BLIP-27.8B144.5121.6-82.2--
GIT25.1B145.0126.9148.681.767.371.0
Flamingo80B138.1--82.054.165.7
PaLI17B149.1127.0160.0▲84.358.8 / 73.1▲71.6 / 74.4▲
PaLI-X55B149.2126.3147.0 / 163.7▲86.071.4 / 80.8▲70.9 / 74.6▲
Generalist Models
Unified-IO2.9B-100.0-77.9-57.4
Florence-2-base-ft0.23B140.0116.7143.979.763.663.6
Florence-2-large-ft0.77B143.3124.9151.181.773.572.6
Method# ParamsCOCO Det. val2017 mAPFlickr30k test R@1RefCOCO val AccuracyRefCOCO test-A AccuracyRefCOCO test-B AccuracyRefCOCO+ val AccuracyRefCOCO+ test-A AccuracyRefCOCO+ test-B AccuracyRefCOCOg val AccuracyRefCOCOg test AccuracyRefCOCO RES val mIoU
Specialist Models
SeqTR---83.786.581.271.576.364.974.974.2-
PolyFormer---90.492.987.285.089.878.085.885.976.9
UNINEXT0.74B60.6-92.694.391.585.289.679.888.789.4-
Ferret13B--89.592.484.482.888.175.285.886.3-
Generalist Models
UniTAB---88.691.183.881.085.471.684.684.7-
Florence-2-base-ft0.23B41.484.092.694.891.586.891.782.289.882.278.0
Florence-2-large-ft0.77B43.485.293.495.392.088.392.983.691.291.780.5

BibTex and citation info

@article{xiao2023florence,
  title={Florence-2: Advancing a unified representation for a variety of vision tasks},
  author={Xiao, Bin and Wu, Haiping and Xu, Weijian and Dai, Xiyang and Hu, Houdong and Lu, Yumao and Zeng, Michael and Liu, Ce and Yuan, Lu},
  journal={arXiv preprint arXiv:2311.06242},
  year={2023}
}

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
Florence2ForConditionalGeneration
Ревизия весов
8db3793

0 моделей