/ Модель

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

Лицензия
Apache 2.0
Архитектура
pix2struct · dense
Опубликована
13 мар 2023

pix2struct-textcaps-large

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

Крупная модель Pix2Struct от Google, которая генерирует текстовые описания изображений и предназначена для задач визуального понимания.

152скачиваний за 30 дней14лайковвеса обновлены19 мая 2023

Бенчмарки

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

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

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

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

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

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

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

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

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

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

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

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

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

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

google/pix2struct-textcaps-large — крупная модель семейства Pix2Struct от Google для создания текстовых описаний изображений. Это архитектура «визуальный энкодер — текстовый декодер», обученная на парах изображение–текст; предварительное обучение включало преобразование замаскированных снимков веб-страниц в упрощённый HTML. Модель принимает изображение и генерирует текст, в том числе подпись к изображению; семейство также применяют к визуальным вопросам и задачам понимания документов, иллюстраций, интерфейсов и обычных фотографий.

В README указана обучающая длина последовательности 4096; при уменьшении числа патчей для экономии памяти качество может снижаться, особенно при значениях ниже 1024. Репозиторий содержит веса PyTorch. Модель распространяется по лицензии Apache-2.0.

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

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

Ограничения

Снижение длины входа может ухудшить качество, особенно при числе патчей менее 1024. В README также описаны сценарии условной генерации и визуальных вопросов для семейства Pix2Struct, но метаданные этой модели подтверждают только задачу image-to-text.

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

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

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

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

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

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

Открыть на Hugging Face

Model card for Pix2Struct - Finetuned on TextCaps - Large version

model_image

Table of Contents

  1. TL;DR
  2. Using the model
  3. Contribution
  4. Citation

TL;DR

Pix2Struct is an image encoder - text decoder model that is trained on image-text pairs for various tasks, including image captionning and visual question answering. The full list of available models can be found on the Table 1 of the paper:

Table 1 - paper

The abstract of the model states that:

Visually-situated language is ubiquitous—sources range from textbooks with diagrams to web pages with images and tables, to mobile apps with buttons and forms. Perhaps due to this diversity, previous work has typically relied on domainspecific recipes with limited sharing of the underlying data, model architectures, and objectives. We present Pix2Struct, a pretrained image-to-text model for purely visual language understanding, which can be finetuned on tasks containing visually-situated language. Pix2Struct is pretrained by learning to parse masked screenshots of web pages into simplified HTML. The web, with its richness of visual elements cleanly reflected in the HTML structure, provides a large source of pretraining data well suited to the diversity of downstream tasks. Intuitively, this objective subsumes common pretraining signals such as OCR, language modeling, image captioning. In addition to the novel pretraining strategy, we introduce a variable-resolution input representation and a more flexible integration of language and vision inputs, where language prompts such as questions are rendered directly on top of the input image. For the first time, we show that a single pretrained model can achieve state-of-the-art results in six out of nine tasks across four domains: documents, illustrations, user interfaces, and natural images.

Using the model

Converting from T5x to huggingface

You can use the convert_pix2struct_checkpoint_to_pytorch.py script as follows:

python convert_pix2struct_checkpoint_to_pytorch.py --t5x_checkpoint_path PATH_TO_T5X_CHECKPOINTS --pytorch_dump_path PATH_TO_SAVE

if you are converting a large model, run:

python convert_pix2struct_checkpoint_to_pytorch.py --t5x_checkpoint_path PATH_TO_T5X_CHECKPOINTS --pytorch_dump_path PATH_TO_SAVE --use-large

Once saved, you can push your converted model with the following snippet:

from transformers import Pix2StructForConditionalGeneration, Pix2StructProcessor

model = Pix2StructForConditionalGeneration.from_pretrained(PATH_TO_SAVE)
processor = Pix2StructProcessor.from_pretrained(PATH_TO_SAVE)

model.push_to_hub("USERNAME/MODEL_NAME")
processor.push_to_hub("USERNAME/MODEL_NAME")

Running the model

In full precision, on CPU:

You can run the model in full precision on CPU:

import requests
from PIL import Image
from transformers import Pix2StructForConditionalGeneration, Pix2StructProcessor

url = "https://www.ilankelman.org/stopsigns/australia.jpg"
image = Image.open(requests.get(url, stream=True).raw)

model = Pix2StructForConditionalGeneration.from_pretrained("google/pix2struct-textcaps-base")
processor = Pix2StructProcessor.from_pretrained("google/pix2struct-textcaps-base")

# image only
inputs = processor(images=image, return_tensors="pt")

predictions = model.generate(**inputs)
print(processor.decode(predictions[0], skip_special_tokens=True))
>>> A street scene with a sign that says "STOP".

In full precision, on GPU:

You can run the model in full precision on CPU:

import requests
from PIL import Image
from transformers import Pix2StructForConditionalGeneration, Pix2StructProcessor

url = "https://www.ilankelman.org/stopsigns/australia.jpg"
image = Image.open(requests.get(url, stream=True).raw)

model = Pix2StructForConditionalGeneration.from_pretrained("google/pix2struct-textcaps-large").to("cuda")
processor = Pix2StructProcessor.from_pretrained("google/pix2struct-textcaps-large")

# image only
inputs = processor(images=image, return_tensors="pt").to("cuda")

predictions = model.generate(**inputs)
print(processor.decode(predictions[0], skip_special_tokens=True))
>>> A street scene with a sign that says "STOP".

In half precision, on GPU:

You can run the model in full precision on CPU:

import requests
import torch

from PIL import Image
from transformers import Pix2StructForConditionalGeneration, Pix2StructProcessor

url = "https://www.ilankelman.org/stopsigns/australia.jpg"
image = Image.open(requests.get(url, stream=True).raw)

model = Pix2StructForConditionalGeneration.from_pretrained("google/pix2struct-textcaps-large", torch_dtype=torch.bfloat16).to("cuda")
processor = Pix2StructProcessor.from_pretrained("google/pix2struct-textcaps-large")

# image only
inputs = processor(images=image, return_tensors="pt").to("cuda", torch.bfloat16)

predictions = model.generate(**inputs)
print(processor.decode(predictions[0], skip_special_tokens=True))
>>> A street scene with a sign that says "STOP".

Use different sequence length

This model has been trained on a sequence length of 4096. You can try to reduce the sequence length for a more memory efficient inference but you may observe some performance degradation for small sequence length (<1024). Just pass max_patches when calling the processor:

inputs = processor(images=image, return_tensors="pt", max_patches=1024)

Conditional generation

You can also pre-pend some input text to perform conditional generation:

import requests
from PIL import Image
from transformers import Pix2StructForConditionalGeneration, Pix2StructProcessor

url = "https://www.ilankelman.org/stopsigns/australia.jpg"
image = Image.open(requests.get(url, stream=True).raw)
text = "A picture of"

model = Pix2StructForConditionalGeneration.from_pretrained("google/pix2struct-textcaps-large")
processor = Pix2StructProcessor.from_pretrained("google/pix2struct-textcaps-large")

# image only
inputs = processor(images=image, text=text, return_tensors="pt")

predictions = model.generate(**inputs)
print(processor.decode(predictions[0], skip_special_tokens=True))

Contribution

This model was originally contributed by Kenton Lee, Mandar Joshi et al. and added to the Hugging Face ecosystem by Younes Belkada.

Citation

If you want to cite this work, please consider citing the original paper:

@misc{https://doi.org/10.48550/arxiv.2210.03347,
  doi = {10.48550/ARXIV.2210.03347},
  
  url = {https://arxiv.org/abs/2210.03347},
  
  author = {Lee, Kenton and Joshi, Mandar and Turc, Iulia and Hu, Hexiang and Liu, Fangyu and Eisenschlos, Julian and Khandelwal, Urvashi and Shaw, Peter and Chang, Ming-Wei and Toutanova, Kristina},
  
  keywords = {Computation and Language (cs.CL), Computer Vision and Pattern Recognition (cs.CV), FOS: Computer and information sciences, FOS: Computer and information sciences},
  
  title = {Pix2Struct: Screenshot Parsing as Pretraining for Visual Language Understanding},
  
  publisher = {arXiv},
  
  year = {2022},
  
  copyright = {Creative Commons Attribution 4.0 International}
}

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей