/ Модель

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

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

Florence-2-base-ft

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

Дообученная модель Microsoft для описания и анализа изображений, распознавания текста и обнаружения объектов по текстовым запросам.

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

Бенчмарки

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Florence-2-base-ft — модель компьютерного зрения и понимания изображений от Microsoft, представленная в реализации для библиотеки Transformers. Это дообученная версия Florence-2-base с архитектурой последовательность-в-последовательность и примерно 0,23 млрд параметров. Модель использует текстовые запросы, чтобы переключаться между задачами: описанием изображения, обнаружением объектов, выделением областей, привязкой фраз к объектам и распознаванием текста на изображении.

Модель подходит для автоматического описания и анализа изображений, извлечения текста и координат объектов, а также для ответов на визуальные вопросы. В README перечислены оценки на задачах captioning, object detection и визуального вопросно-ответного анализа; модель обучалась на FLD-5B с аннотациями для изображений. Карточка не сообщает поддерживаемые языки текста, поэтому языковую специализацию определить нельзя.

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

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

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

Ограничения

Карточка не указывает языки, на которых модель распознаёт текст или отвечает на вопросы; качество на конкретных изображениях может отличаться от приведённых тестовых оценок.

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

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

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

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

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

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

Открыть на Hugging Face

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

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

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-base-ft", torch_dtype=torch_dtype, trust_remote_code=True).to(device)
processor = AutoProcessor.from_pretrained("microsoft/Florence-2-base-ft", 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,
    do_sample=False,
    num_beams=3
)
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

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-base-ft", torch_dtype=torch_dtype, trust_remote_code=True).to(device)
processor = AutoProcessor.from_pretrained("microsoft/Florence-2-base-ft", 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
Ревизия весов
f6c1a25

0 моделей