Transformers documentation

TrOCR

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.2).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2021-09-21 在 HF papers 上发布,并于 2021-10-13 贡献给 Hugging Face Transformers。

TrOCR

TrOCR 是一款用于图像理解和文本生成的文本识别模型。它无需为图像处理或字符生成分别使用独立的模型。TrOCR 是一个简单的端到端系统,利用 transformer 同时处理视觉理解和文本生成。

您可以在 Microsoft 组织下找到所有原始的 TrOCR 检查点。

drawing TrOCR architecture. Taken from the original paper.

该模型由 nielsr 贡献。

点击右侧边栏中的 TrOCR 模型,以查看将 TrOCR 应用于不同图像和文本任务的更多示例。

以下示例演示了如何使用 AutoModel 类执行光学字符识别(OCR)。

AutoModel
import requests
from PIL import Image

from transformers import TrOCRProcessor, VisionEncoderDecoderModel


processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten", device_map="auto")

# load image from the IAM dataset
url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg"
image = Image.open(requests.get(url, stream=True).raw).convert("RGB")

pixel_values = processor(image, return_tensors="pt").to(model.device).pixel_values
generated_ids = model.generate(pixel_values)

generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
print(generated_text)

量化

量化通过以较低精度表示权重来降低大模型的内存负担。有关更多可用的量化后端,请参阅 量化 概述。

以下示例使用 bitsandbytes 将权重量化为 8 位。

# pip install bitsandbytes accelerate
from transformers import TrOCRProcessor, VisionEncoderDecoderModel, BitsandBytesConfig
import requests
from PIL import Image

# Set up the quantization configuration
quantization_config = BitsandBytesConfig(load_in_8bit=True)

# Use a large checkpoint for a more noticeable impact
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-large-handwritten")
model = VisionEncoderDecoderModel.from_pretrained(
    "microsoft/trocr-large-handwritten",
    quantization_config=quantization_config
 device_map="auto")

# load image from the IAM dataset
url = "[https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg](https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg)"
image = Image.open(requests.get(url, stream=True).raw).convert("RGB")

pixel_values = processor(image, return_tensors="pt").to(model.device).pixel_values
generated_ids = model.generate(pixel_values)

generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
print(generated_text)

备注

资源

TrOCRConfig

class transformers.TrOCRConfig

< >

( 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 = Nonevocab_size: int = 50265d_model: int = 1024decoder_layers: int = 12decoder_attention_heads: int = 16decoder_ffn_dim: int = 4096activation_function: str = 'gelu'max_position_embeddings: int = 512dropout: float | int = 0.1attention_dropout: float | int = 0.0activation_dropout: float | int = 0.0decoder_start_token_id: int = 2init_std: float = 0.02decoder_layerdrop: float | int = 0.0use_cache: bool = Truescale_embedding: bool = Falseuse_learned_position_embeddings: bool = Truelayernorm_embedding: bool = Truepad_token_id: int | None = 1bos_token_id: int | None = 0eos_token_id: int | list[int] | None = 2cross_attention_hidden_size: int | None = Noneis_decoder: bool = Falsetie_word_embeddings: bool = True )

参数

  • vocab_size (int, 可选, 默认为 50265) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 的数量。
  • d_model (int,可选,默认为 1024) — 编码器层和池化层的维度大小。
  • decoder_layers (int, 可选,默认为 12) — Transformer 解码器中的隐藏层数量。如果未设置,将使用与 num_layers 相同的值。
  • decoder_attention_heads (int,可选,默认为 16) — Transformer 解码器中每个注意力层的注意力头数量。
  • decoder_ffn_dim (int,可选,默认为 4096) — 解码器中“中间”(通常称为前馈)层的维度。
  • activation_function (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu" 等。
  • max_position_embeddings (int,可选,默认为 512) — 该模型可能使用的最大序列长度。
  • dropout (Union[float, int],可选,默认为 0.1) — 所有 dropout 层的比率。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • activation_dropout (Union[float, int],可选,默认为 0.0) — 全连接层中激活值的 dropout 比率。
  • decoder_start_token_id (int,可选,默认为 2) — 如果编码器-解码器模型使用不同于 bos 的 token 开始解码,则指定该 token 的 id。
  • init_std (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • decoder_layerdrop (Union[float, int],可选,默认为 0.0) — 解码器的 LayerDrop 概率。有关更多详细信息,请参阅 [LayerDrop 论文](参见 https://huggingface.co/papers/1909.11556)。
  • use_cache (bool,可选,默认为 True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当 config.is_decoder=True 或模型为仅解码器生成式模型时相关。
  • scale_embedding (bool,可选,默认为 False) — 是否通过将嵌入除以 sqrt(d_model) 来对嵌入进行缩放。
  • use_learned_position_embeddings (bool,可选,默认为 True) — 是否使用学习得到的位置嵌入。如果未使用,则将采用正弦位置嵌入。
  • layernorm_embedding (bool,可选,默认为 True) — 是否在词嵌入和位置嵌入之后使用 layernorm。
  • pad_token_id (int,可选,默认为 1) — 词表中用于填充的 token id。
  • bos_token_id (int,可选,默认为 0) — 词汇表中用于表示流起始的 Token id。
  • eos_token_id (Union[int, list[int]],可选,默认为 2) — 词汇表中用于表示流结束(end-of-stream)的 token id。
  • cross_attention_hidden_size (int, 可选) — 编码器输出投影到解码器交叉注意力键/值空间的隐藏层大小。当编码器和解码器的隐藏层大小不同时使用。
  • is_decoder (bool,可选,默认为 False) — 指示该模型是否用作解码器。如果为 False,则模型用作编码器。
  • tie_word_embeddings (bool,可选,默认为 True) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。

这是用于存储 TrocrModel 配置的类。它根据指定的参数实例化 Trocr 模型,并定义模型架构。使用默认值实例化配置,将得到与 microsoft/trocr-base-handwritten 类似的配置。

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

示例:

>>> from transformers import TrOCRConfig, TrOCRForCausalLM

>>> # Initializing a TrOCR-base style configuration
>>> configuration = TrOCRConfig()

>>> # Initializing a model (with random weights) from the TrOCR-base style configuration
>>> model = TrOCRForCausalLM(configuration)

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

TrOCRProcessor

class transformers.TrOCRProcessor

< >

( image_processor = Nonetokenizer = None**kwargs )

参数

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

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

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

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] | None = None**kwargs: *<class 'transformers.models.trocr.processing_trocr.TrOCRProcessorKwargs'> ) → ~image_processing_base.BatchFeature

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], 可选) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
  • text (Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置 is_split_into_words=True,以避免与批量输入产生歧义。
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

from_pretrained

< >

( pretrained_model_name_or_path: str | os.PathLikecache_dir: str | os.PathLike | None = Noneforce_download: bool = Falselocal_files_only: bool = Falsetoken: str | bool | None = Nonerevision: str = 'main'**kwargs )

参数

  • pretrained_model_name_or_path (str 或 os.PathLike) — 可以是以下之一:
    • 一个字符串,即托管在 huggingface.co 上某个模型仓库中的预训练 feature_extractor 的 model id。
    • 指向一个目录的路径,该目录包含使用 save_pretrained() 方法保存的特征提取器文件,例如 ./my_model_directory/。
    • 指向已保存的特征提取器 JSON 文件的路径,例如 ./my_model_directory/preprocessor_config.json。
  • **kwargs — 同时传递给 from_pretrained() 和 ~tokenization_utils_base.PreTrainedTokenizer.from_pretrained 的额外关键字参数。

实例化与预训练模型关联的处理器。

此类的该方法只是调用了特征提取器的 from_pretrained()、图像处理器 ImageProcessingMixin 以及分词器的 ~tokenization_utils_base.PreTrainedTokenizer.from_pretrained 方法。有关更多信息,请参阅上述方法的文档字符串。

save_pretrained

< >

( save_directorypush_to_hub: bool = False**kwargs )

参数

  • save_directory (str 或 os.PathLike) — 用于保存特征提取器 JSON 文件和分词器文件的目录(如果该目录不存在,则会自动创建)。
  • push_to_hub (bool,可选,默认为 False) — 是否在保存模型后将其推送到 Hugging Face 模型库。您可以使用 repo_id 指定要推送到的仓库(默认使用您命名空间中 save_directory 的名称)。
  • kwargs (dict[str, Any],可选) — 传递给 push_to_hub() 方法的额外关键字参数。

将此处理器的属性(特征提取器、分词器……)保存到指定目录中,以便使用 from_pretrained() 方法重新加载。

此类的该方法只是调用了 save_pretrained() 和 save_pretrained()。有关更多信息,请参阅上述方法的文档字符串。

batch_decode

< >

( *args**kwargs )

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

decode

< >

( *args**kwargs )

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

TrOCRForCausalLM

class transformers.TrOCRForCausalLM

< >

( config: TrOCRConfig )

参数

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

带有语言建模头的 TrOCR 解码器。可作为 EncoderDecoderModel 的解码器部分使用,并且

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneencoder_hidden_states: typing.Optional[torch.Tensor] = Noneencoder_attention_mask: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → CausalLMOutputWithCrossAttentions or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • encoder_hidden_states (torch.Tensor,形状为 (batch_size, sequence_length, hidden_size),可选) — 编码器最后一层输出的隐藏状态序列。如果模型被配置为解码器,则用于交叉注意力。
  • encoder_attention_mask (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 用于避免对编码器输入中填充标记索引执行注意力的掩码。如果模型被配置为解码器,则此掩码用于交叉注意力。掩码值选自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。
  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

CausalLMOutputWithCrossAttentions 或 tuple(torch.Tensor)

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

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

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

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。

  • 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 之后的权重,用于在自注意力头中计算加权平均值。

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

    注意力 softmax 之后的交叉注意力权重,用于在交叉注意力头中计算加权平均值。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

示例:

>>> from transformers import (
...     TrOCRConfig,
...     TrOCRProcessor,
...     TrOCRForCausalLM,
...     ViTConfig,
...     ViTModel,
...     VisionEncoderDecoderModel,
... )
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image

>>> # TrOCR is a decoder model and should be used within a VisionEncoderDecoderModel
>>> # init vision2text model with random weights
>>> encoder = ViTModel(ViTConfig())
>>> decoder = TrOCRForCausalLM(TrOCRConfig())
>>> model = VisionEncoderDecoderModel(encoder=encoder, decoder=decoder)

>>> # If you want to start from the pretrained model, load the checkpoint with `VisionEncoderDecoderModel`
>>> processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
>>> model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")

>>> # load image from the IAM dataset
>>> url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read())).convert("RGB")
>>> pixel_values = processor(image, return_tensors="pt").pixel_values
>>> text = "industry, ' Mr. Brown commented icily. ' Let us have a"

>>> # training
>>> model.config.decoder_start_token_id = processor.tokenizer.eos_token_id
>>> model.config.pad_token_id = processor.tokenizer.pad_token_id
>>> model.config.vocab_size = model.config.decoder.vocab_size

>>> labels = processor.tokenizer(text, return_tensors="pt").input_ids
>>> outputs = model(pixel_values, labels=labels)
>>> loss = outputs.loss
>>> round(loss.item(), 2)
5.30

>>> # inference
>>> generated_ids = model.generate(pixel_values)
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> generated_text
'industry, " Mr. Brown commented icily. " Let us have a'
Update on GitHub