Transformers documentation

MGP-STR

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2022-09-08 在 HF papers 上发布,并于 2023-03-13 贡献给 Hugging Face Transformers。

MGP-STR

概述

MGP-STR 模型由 Peng Wang、Cheng Da 和 Cong Yao 在 Multi-Granularity Prediction for Scene Text Recognition 中提出。MGP-STR 是一个概念上简单但强大的视觉场景文本识别(STR)模型,其构建于Vision Transformer (ViT)之上。为了整合语言知识,提出了多粒度预测(MGP)策略,以隐式方式将语言模态的信息注入模型中。

该论文的摘要如下:

场景文本识别(STR)多年来一直是计算机视觉领域的活跃研究课题。为应对这一具有挑战性的问题,众多创新方法相继被提出,而将语言知识融入 STR 模型近期已成为一个显著趋势。在本工作中,我们首先从 Vision Transformer(ViT)的最新进展中汲取灵感,构建了一个概念上简洁但功能强大的视觉 STR 模型。该模型基于 ViT 构建,在场景文本识别任务上超越了此前的最先进模型,包括纯视觉模型和语言增强方法。为了整合语言知识,我们进一步提出了一种多粒度预测(Multi-Granularity Prediction)策略,以隐式方式将语言模态的信息注入模型。具体而言,除了传统的字符级表示外,我们将 NLP 中广泛使用的子词表示(BPE 和 WordPiece)引入输出空间,同时不采用独立的语言模型(LM)。所得算法(称为 MGP-STR)能够将 STR 的性能边界推向更高水平。具体地,它在标准基准测试上达到了 93.35% 的平均识别准确率。

drawing MGP-STR architecture. Taken from the original paper.

MGP-STR 在两个合成数据集 MJSynth(MJ)和 SynthText(ST)上进行训练,未在其他数据集上进行微调。它在六个标准的拉丁文场景文本基准测试中取得了最先进的结果,其中包括 3 个常规文本数据集(IC13、SVT、IIIT)和 3 个非常规文本数据集(IC15、SVTP、CUTE)。 该模型由 yuekun 贡献。原始代码可在此处找到。

推理示例

MgpstrModel 接受图像作为输入,并生成三种类型的预测,它们代表不同粒度下的文本信息。 这三种预测会被融合,以给出最终的预测结果。

ViTImageProcessor 类负责预处理输入图像,MgpstrTokenizer 则将生成的字符 token 解码为目标字符串。MgpstrProcessor 将 ViTImageProcessor 和 MgpstrTokenizer 封装为单一实例,以同时提取输入特征并解码预测的 token id。

  • 逐步光学字符识别(OCR)
import requests
from PIL import Image

from transformers import MgpstrForSceneTextRecognition, MgpstrProcessor


processor = MgpstrProcessor.from_pretrained('alibaba-damo/mgp-str-base')
model = MgpstrForSceneTextRecognition.from_pretrained('alibaba-damo/mgp-str-base', device_map="auto")

# load a synthetic scene-text image
url = "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/mgp_str_ticket.png"
image = Image.open(requests.get(url, stream=True).raw).convert("RGB")

pixel_values = processor(images=image, return_tensors="pt").to(model.device).pixel_values
outputs = model(pixel_values)

generated_text = processor.batch_decode(outputs.logits)['generated_text']

MgpstrConfig

类 transformers.MgpstrConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneimage_size: list[int] | tuple[int, ...] = (32, 128)patch_size: int | list[int] | tuple[int, int] = 4num_channels: int = 3max_token_length: int = 27num_character_labels: int = 38num_bpe_labels: int = 50257num_wordpiece_labels: int = 30522hidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12mlp_ratio: float | int = 4.0qkv_bias: bool = Truedistilled: bool = Falselayer_norm_eps: float = 1e-05drop_rate: float | int = 0.0attn_drop_rate: float | int = 0.0drop_path_rate: float | int = 0.0output_a3_attentions: bool = Falseinitializer_range: float = 0.02 )

参数

  • image_size (Union[list[int], tuple[int, ...]],可选,默认为 (32, 128)) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 4) — 每个 patch 的大小(分辨率)。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • max_token_length (int,可选,默认为 27) — 输出 token 的最大数量。
  • num_character_labels (int,可选,默认为 38) — 角色头(character head)的类别数量。
  • num_bpe_labels (int,可选,默认为 50257) — bpe 头的类别数。
  • num_wordpiece_labels (int,可选,默认为 30522) — wordpiece 头的类别数。
  • hidden_size (int,可选,默认为 768) — 隐藏表示的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 12) — Transformer 解码器中每个注意力层的注意力头数量。
  • mlp_ratio (Union[float, int],可选,默认为 4.0) — MLP 隐藏层维度与嵌入维度的比值。
  • qkv_bias (bool,可选,默认为 True) — 是否向查询、键和值添加偏置。
  • distilled (bool,可选,默认为 False) — 模型包含 DeiT 模型中的蒸馏 token 和 head。
  • layer_norm_eps (float,可选,默认为 1e-05) — 层归一化层所使用的 epsilon 值。
  • drop_rate (float,可选,默认值为 0.0) — 嵌入层和编码器中所有全连接层的 dropout 概率。
  • attn_drop_rate (float,可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • drop_path_rate (Union[float, int],可选,默认为 0.0) — 用于 patch fusion 的 drop path 比率。
  • output_a3_attentions (bool,可选,默认为 False) — 是否让模型返回 A^3 模块的注意力。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

这是用于存储 Mgp StrModel 配置的类。它根据指定的参数实例化 Mgp Str 模型,并定义模型架构。使用默认值实例化配置将得到与 alibaba-damo/mgp-str-base 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import MgpstrConfig, MgpstrForSceneTextRecognition

>>> # Initializing a Mgpstr mgp-str-base style configuration
>>> configuration = MgpstrConfig()

>>> # Initializing a model (with random weights) from the mgp-str-base style configuration
>>> model = MgpstrForSceneTextRecognition(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

MgpstrTokenizer

class transformers.MgpstrTokenizer

< >

( vocab_fileunk_token = '[GO]'bos_token = '[GO]'eos_token = '[s]'pad_token = '[GO]'**kwargs )

参数

  • vocab_file (str) — 词汇表文件的路径。
  • unk_token (str,可选,默认为 "[GO]") — 未知标记。不在词汇表中的标记无法转换为 ID,因此会被设置为该标记。
  • bos_token (str,可选,默认为 "[GO]") — 序列开始标记。
  • eos_token (str,可选,默认为 "[s]") — 序列结束标记。
  • pad_token (str 或 tokenizers.AddedToken,可选,默认为 "[GO]") — 一种特殊标记,用于将标记数组调整为相同大小以便进行批处理。随后,注意力机制或损失计算会忽略该标记。

构建 MGP-STR 字符分词器。

该分词器继承自 PreTrainedTokenizer,其中包含了大部分主要方法。用户应参考该父类以获取有关这些方法的更多信息。

save_vocabulary

< >

( save_directory: strfilename_prefix: str | None = None )

MgpstrProcessor

class transformers.MgpstrProcessor

< >

( image_processor = Nonetokenizer = None**kwargs )

参数

  • image_processor(ViTImageProcessor)— 图像处理器是必需的输入。
  • tokenizer (MgpstrTokenizer) — 分词器是必需的输入。

构建一个 MgpstrProcessor,它将图像处理器和分词器封装为单个处理器。

MgpstrProcessor 提供了 ViTImageProcessor 和 MgpstrTokenizer 的所有功能。有关更多信息,请参阅 ~ViTImageProcessor 和 ~MgpstrTokenizer。

__call__

< >

( text = Noneimages = None**kwargs )

参数

  • text (`) -- The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If you pass a pretokenized input, set is_split_into_words=True` to avoid ambiguity with batched inputs.
  • images (`) -- Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set do_rescale=False`.
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。

batch_decode

< >

( sequences ) → dict[str, any]

参数

  • sequences (torch.Tensor) — 标记化输入 ID 的列表。

返回值

dict[str, any]

解码结果所有输出的字典。 generated_text (list[str]): 融合 char、bpe 和 wp 后的最终结果。 scores (list[float]): 融合 char、bpe 和 wp 后的最终分数。 char_preds (list[str]): 字符解码句子列表。 bpe_preds (list[str]): bpe 解码句子列表。 wp_preds (list[str]): wp 解码句子列表。

通过调用 decode,将 token id 的列表的列表转换为字符串列表。

此方法会将其所有参数转发给 PreTrainedTokenizer 的 batch_decode()。有关更多信息,请参阅该方法的文档字符串。

MgpstrModel

class transformers.MgpstrModel

< >

( config: MgpstrConfig )

参数

  • config (MgpstrConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

未添加任何特定头部的裸 Mgp Str 模型,直接输出原始隐藏状态。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: Tensoroutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → BaseModelOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 ViTImageProcessor 获取像素值。有关详细信息,请参阅 ViTImageProcessor.call()(MgpstrProcessor 使用 ViTImageProcessor 处理图像)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

BaseModelOutput 或 tuple(torch.Tensor)

一个 BaseModelOutput 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MgpstrConfig)和输入。

MgpstrModel 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

MgpstrForSceneTextRecognition

class transformers.MgpstrForSceneTextRecognition

< >

( config: MgpstrConfig )

参数

  • config (MgpstrConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

MGP-STR 模型,在 Transformer 顶部设有三个分类头(三个 A^3 模块以及位于 Transformer 编码器输出之上的三个线性层),用于场景文本识别(STR)。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: Tensoroutput_attentions: bool | None = Noneoutput_a3_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → MgpstrModelOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 ViTImageProcessor 获取像素值。有关详细信息,请参阅 ViTImageProcessor.call()(MgpstrProcessor 使用 ViTImageProcessor 处理图像)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions。
  • output_a3_attentions (bool, 可选) — 是否返回 a3 模块的注意力张量。有关更多详细信息,请参阅返回张量中的 a3_attentions。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

MgpstrModelOutput 或 tuple(torch.Tensor)

MgpstrModelOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(MgpstrConfig)和输入。

MgpstrForSceneTextRecognition 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • logits (tuple(torch.Tensor),形状为 (batch_size, config.num_character_labels)) — torch.Tensor 的元组(包含一个字符输出,形状为 (batch_size, config.max_token_length, config.num_character_labels);一个 bpe 输出,形状为 (batch_size, config.max_token_length, config.num_bpe_labels);以及一个 wordpiece 输出,形状为 (batch_size, config.max_token_length, config.num_wordpiece_labels))。

    字符、bpe 和 wordpiece 的分类得分(SoftMax 之前)。

  • hidden_states (tuple[torch.Tensor],可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

  • a3_attentions (tuple(torch.Tensor), optional, returned when output_a3_attentions=True is passed or when config.output_a3_attentions=True) — Tuple of torch.Tensor (one for the attention of character, + one for the attention of bpe, + one for the attention of wordpiece) of shape(batch_size, config.max_token_length, sequence_length)`.

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> from transformers import (
...     MgpstrProcessor,
...     MgpstrForSceneTextRecognition,
... )
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image

>>> # load a synthetic scene-text image
>>> url = "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/mgp_str_ticket.png"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read())).convert("RGB")

>>> processor = MgpstrProcessor.from_pretrained("alibaba-damo/mgp-str-base")
>>> pixel_values = processor(images=image, return_tensors="pt").pixel_values

>>> model = MgpstrForSceneTextRecognition.from_pretrained("alibaba-damo/mgp-str-base")

>>> # inference
>>> outputs = model(pixel_values)
>>> out_strs = processor.batch_decode(outputs.logits)
>>> out_strs["generated_text"]
'["ticket"]'
Update on GitHub