/ Модель

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

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

Florence-2-large

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

Florence-2-large — модель Microsoft для описания изображений, обнаружения объектов, локализации, сегментации и OCR по текстовым промптам.

367 тыс.скачиваний за 30 дней1 875лайковвеса обновлены4 авг 2025

Бенчмарки

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Microsoft Florence-2-large — универсальная модель компьютерного зрения и языка с архитектурой Florence-2 и последовательной схемой преобразования входа в выход. В этой карточке размещена продолженная версия предварительно обученной Florence-2-large: в README указано, что для продолжения обучения использовано 0,1 млрд примеров и контекст увеличен до 4 тыс. токенов; авторы предупреждают, что модель могла быть обучена недостаточно хорошо. Размер исходной Florence-2-large указан как 0,77 млрд параметров.

Модель принимает изображение и текстовую задачу в виде промпта. Она предназначена для создания подписей к изображениям, обнаружения объектов, локализации областей по тексту, предложений регионов, сегментации и распознавания текста на изображениях, в том числе с привязкой OCR-результатов к областям. Florence-2 обучалась на датасете FLD-5B с 5,4 млрд аннотаций для 126 млн изображений; README приводит результаты оценки для описания изображений и обнаружения объектов, но отдельно отмечает возможное ухудшение качества именно этой продолженно обученной версии.

Репозиторий содержит реализацию для Transformers, веса представлены в PyTorch и Safetensors. Лицензия — MIT. Описание не задаёт конкретный набор естественных языков; качество OCR и визуальных предсказаний может зависеть от изображения и задачи.

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

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

Ограничения

В README отмечено, что продолженное обучение использовало лишь 0,1 млрд примеров, поэтому качество этой версии может быть недостаточным. Языковой охват отдельно не описан.

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

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

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

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

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

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

Открыть на Hugging Face

Florence-2: Advancing a Unified Representation for a Variety of Vision Tasks

Model Summary

This is a continued pretrained version of Florence-2-large model with 4k context length, only 0.1B samples are used for continue pretraining, thus it might not be trained well. In addition, OCR task has been updated with line separator ('\n'). COCO OD AP 39.8

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=4096,
    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)

Output confidence score with Object Detection


def run_example_with_score(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,
      return_dict_in_generate=True,
      output_scores=True,
    )
    generated_text = processor.batch_decode(generated_ids.sequences, skip_special_tokens=False)[0]

    prediction, scores, beam_indices = generated_ids.sequences, generated_ids.scores, generated_ids.beam_indices
    transition_beam_scores = model.compute_transition_scores(
        sequences=prediction,
        scores=scores,
        beam_indices=beam_indices,
    )

    parsed_answer = processor.post_process_generation(sequence=generated_ids.sequences[0], 
        transition_beam_score=transition_beam_scores[0],
        task=task_prompt, image_size=(image.width, image.height)
    )

    print(parsed_answer)

prompt = "<OD>"
run_example_with_score(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
Ревизия весов
21a599d

0 моделей