Transformers 文档

LayoutLMv3

LayoutLMv3

概述

LayoutLMv3模型由Yupan Huang、Tengchao Lv、Lei Cui、Yutong Lu和Furu Wei在LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking中提出。 LayoutLMv3通过使用补丁嵌入(如ViT中所示)而不是利用CNN骨干网络来简化LayoutLMv2,并在三个目标上预训练模型:掩码语言建模(MLM)、掩码图像建模(MIM)和词-补丁对齐(WPA)。

论文的摘要如下:

自监督预训练技术在文档AI领域取得了显著进展。大多数多模态预训练模型使用掩码语言建模目标来学习文本模态的双向表示,但它们在图像模态的预训练目标上有所不同。这种差异增加了多模态表示学习的难度。在本文中,我们提出了LayoutLMv3,通过统一的文本和图像掩码来预训练文档AI的多模态Transformer。此外,LayoutLMv3通过单词-图像块对齐目标进行预训练,通过预测文本单词对应的图像块是否被掩码来学习跨模态对齐。这种简单的统一架构和训练目标使LayoutLMv3成为适用于以文本为中心和以图像为中心的文档AI任务的通用预训练模型。实验结果表明,LayoutLMv3不仅在以文本为中心的任务中(包括表单理解、收据理解和文档视觉问答)取得了最先进的性能,而且在以图像为中心的任务(如文档图像分类和文档布局分析)中也表现出色。

drawing LayoutLMv3 architecture. Taken from the original paper.

该模型由nielsr贡献。该模型的TensorFlow版本由chriskootokeclre添加。原始代码可以在这里找到。

使用提示

  • 在数据处理方面,LayoutLMv3 与其前身 LayoutLMv2 相同,除了以下几点:
    • 图像需要调整大小并以常规 RGB 格式的通道进行归一化。而 LayoutLMv2 在内部对图像进行归一化,并期望通道为 BGR 格式。
    • 文本使用字节对编码(BPE)进行分词,而不是 WordPiece。 由于这些数据预处理的差异,可以使用 LayoutLMv3Processor,它在内部结合了 LayoutLMv3ImageProcessor(用于图像模态)和 LayoutLMv3Tokenizer/LayoutLMv3TokenizerFast(用于文本模态)来为模型准备所有数据。
  • 关于LayoutLMv3Processor的使用,我们参考其前身的使用指南

资源

以下是官方Hugging Face和社区(由🌎表示)提供的资源列表,帮助您开始使用LayoutLMv3。如果您有兴趣提交资源以包含在此处,请随时打开一个Pull Request,我们将进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。

LayoutLMv3 与 LayoutLMv2 几乎相同,因此我们也包含了可以用于 LayoutLMv3 任务的 LayoutLMv2 资源。对于这些笔记本,请注意在为模型准备数据时使用 LayoutLMv2Processor

  • LayoutLMv3的演示笔记本可以在这里找到。
  • 演示脚本可以在这里找到。
Text Classification
Token Classification
Question Answering

文档问答

LayoutLMv3Config

transformers.LayoutLMv3Config

< >

( 词汇表大小 = 50265 隐藏层大小 = 768 隐藏层数量 = 12 注意力头数量 = 12 中间层大小 = 3072 隐藏层激活函数 = 'gelu' 隐藏层丢弃概率 = 0.1 注意力概率丢弃概率 = 0.1 最大位置嵌入 = 512 类型词汇表大小 = 2 初始化范围 = 0.02 层归一化epsilon = 1e-05 填充标记ID = 1 开始标记ID = 0 结束标记ID = 2 最大2D位置嵌入 = 1024 坐标大小 = 128 形状大小 = 128 具有相对注意力偏置 = True 相对位置分箱 = 32 最大相对位置 = 128 相对2D位置分箱 = 64 最大相对2D位置 = 256 具有空间注意力偏置 = True 文本嵌入 = True 视觉嵌入 = True 输入大小 = 224 通道数量 = 3 补丁大小 = 16 分类器丢弃 = None **kwargs )

参数

  • vocab_size (int, 可选, 默认为 50265) — LayoutLMv3 模型的词汇表大小。定义了可以通过调用 LayoutLMv3Model 时传递的 inputs_ids 表示的不同标记的数量。
  • hidden_size (int, optional, 默认为 768) — 编码器层和池化层的维度。
  • num_hidden_layers (int, optional, 默认为 12) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, optional, defaults to 12) — Transformer编码器中每个注意力层的注意力头数。
  • intermediate_size (int, optional, 默认为 3072) — Transformer 编码器中“中间”(即前馈)层的维度。
  • hidden_act (strfunction, 可选, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu""relu""selu""gelu_new"
  • hidden_dropout_prob (float, optional, 默认为 0.1) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (float, optional, defaults to 0.1) — 注意力概率的丢弃比例。
  • max_position_embeddings (int, optional, 默认为 512) — 此模型可能使用的最大序列长度。通常将其设置为较大的值以防万一(例如,512、1024 或 2048)。
  • type_vocab_size (int, 可选, 默认为 2) — 调用 LayoutLMv3Model 时传递的 token_type_ids 的词汇大小.
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • layer_norm_eps (float, optional, defaults to 1e-5) — 层归一化层使用的epsilon值。
  • max_2d_position_embeddings (int, 可选, 默认为 1024) — 2D 位置嵌入可能使用的最大值。通常将其设置为较大的值以防万一(例如,1024)。
  • coordinate_size (int, optional, defaults to 128) — 坐标嵌入的维度。
  • shape_size (int, optional, defaults to 128) — 宽度和高度嵌入的维度。
  • has_relative_attention_bias (bool, optional, defaults to True) — 是否在自注意力机制中使用相对注意力偏置。
  • rel_pos_bins (int, optional, defaults to 32) — 用于自注意力机制中的相对位置分箱的数量。
  • max_rel_pos (int, optional, 默认为 128) — 在自注意力机制中使用的最大相对位置数。
  • max_rel_2d_pos (int, optional, defaults to 256) — 自注意力机制中相对2D位置的最大数量。
  • rel_2d_pos_bins (int, optional, 默认为 64) — 自注意力机制中2D相对位置的分箱数量。
  • has_spatial_attention_bias (bool, optional, defaults to True) — 是否在自注意力机制中使用空间注意力偏置。
  • visual_embed (bool, 可选, 默认为 True) — 是否添加补丁嵌入。
  • input_size (int, 可选, 默认为 224) — 图像的大小(分辨率)。
  • num_channels (int, optional, defaults to 3) — 图像的通道数。
  • patch_size (int, optional, defaults to 16) — 补丁的大小(分辨率)。
  • classifier_dropout (float, optional) — 分类头的丢弃比率。

这是用于存储LayoutLMv3Model配置的配置类。它用于根据指定的参数实例化一个LayoutLMv3模型,定义模型架构。使用默认值实例化配置将产生与LayoutLMv3 microsoft/layoutlmv3-base架构相似的配置。

配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。

示例:

>>> from transformers import LayoutLMv3Config, LayoutLMv3Model

>>> # Initializing a LayoutLMv3 microsoft/layoutlmv3-base style configuration
>>> configuration = LayoutLMv3Config()

>>> # Initializing a model (with random weights) from the microsoft/layoutlmv3-base style configuration
>>> model = LayoutLMv3Model(configuration)

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

LayoutLMv3FeatureExtractor

transformers.LayoutLMv3FeatureExtractor

< >

( *args **kwargs )

__call__

< >

( images **kwargs )

预处理一张图像或一批图像。

LayoutLMv3ImageProcessor

transformers.LayoutLMv3ImageProcessor

< >

( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = do_rescale: bool = True rescale_value: float = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.Iterable[float]] = None image_std: typing.Union[float, typing.Iterable[float]] = None apply_ocr: bool = True ocr_lang: typing.Optional[str] = None tesseract_config: typing.Optional[str] = '' **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将图像的(高度,宽度)尺寸调整为 (size["height"], size["width"])。可以在 preprocess 中被 do_resize 覆盖。
  • size (Dict[str, int] 可选, 默认为 {"height" -- 224, "width": 224}): 调整大小后的图像尺寸。可以在 preprocess 中被 size 覆盖。
  • resample (PILImageResampling, 可选, 默认为 PILImageResampling.BILINEAR) — 如果调整图像大小,则使用的重采样过滤器。可以在 preprocess 中通过 resample 覆盖。
  • do_rescale (bool, 可选, 默认为 True) — 是否通过指定的 rescale_value 重新缩放图像的像素值。可以在 preprocess 中被 do_rescale 覆盖。
  • rescale_factor (float, optional, 默认为 1 / 255) — 图像像素值重新缩放的比例。可以在 preprocess 中通过 rescale_factor 覆盖此值。
  • do_normalize (bool, 可选, 默认为 True) — 是否对图像进行归一化。可以在 preprocess 方法中通过 do_normalize 参数进行覆盖。
  • image_mean (Iterable[float]float, 可选, 默认为 IMAGENET_STANDARD_MEAN) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以通过 preprocess 方法中的 image_mean 参数进行覆盖。
  • image_std (Iterable[float]float, 可选, 默认为 IMAGENET_STANDARD_STD) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以通过 preprocess 方法中的 image_std 参数进行覆盖。
  • apply_ocr (bool, 可选, 默认为 True) — 是否应用Tesseract OCR引擎以获取单词和归一化的边界框。可以在preprocess方法中通过apply_ocr参数进行覆盖。
  • ocr_lang (str, 可选) — Tesseract OCR 引擎使用的语言,由其 ISO 代码指定。默认情况下,使用英语。 可以通过 preprocess 方法中的 ocr_lang 参数进行覆盖。
  • tesseract_config (str, 可选) — 任何额外的自定义配置标志,这些标志在调用Tesseract时会转发到config参数。例如:‘—psm 6’。可以在preprocess方法中的tesseract_config参数中覆盖此设置。

构建一个LayoutLMv3图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] do_resize: bool = None size: typing.Dict[str, int] = None resample = None do_rescale: bool = None rescale_factor: float = None do_normalize: bool = None image_mean: typing.Union[float, typing.Iterable[float]] = None image_std: typing.Union[float, typing.Iterable[float]] = None apply_ocr: bool = None ocr_lang: typing.Optional[str] = None tesseract_config: typing.Optional[str] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: ChannelDimension = input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • 图像 (ImageInput) — 要预处理的图像。期望输入单个或批量的图像,像素值范围在0到255之间。如果传入的图像像素值在0到1之间,请设置 do_rescale=False.
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小。
  • size (Dict[str, int], optional, defaults to self.size) — 应用resize后输出图像的期望大小。
  • resample (int, 可选, 默认为 self.resample) — 如果调整图像大小,则使用的重采样过滤器。这可以是 PILImageResampling 过滤器之一。 仅在 do_resize 设置为 True 时有效。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否将图像像素值缩放到 [0, 1] 之间。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 应用于图像像素值的重新缩放因子。仅在 do_rescale 设置为 True 时有效。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否对图像进行归一化处理。
  • image_mean (floatIterable[float], 可选, 默认为 self.image_mean) — 用于归一化的平均值。仅在 do_normalize 设置为 True 时有效。
  • image_std (floatIterable[float], 可选, 默认为 self.image_std) — 用于归一化的标准差值。仅在 do_normalize 设置为 True 时有效。
  • apply_ocr (bool, optional, defaults to self.apply_ocr) — 是否应用Tesseract OCR引擎以获取单词和归一化的边界框。
  • ocr_lang (str, optional, defaults to self.ocr_lang) — Tesseract OCR引擎使用的语言,由其ISO代码指定。默认情况下,使用英语。
  • tesseract_config (str, 可选, 默认为 self.tesseract_config) — 任何额外的自定义配置标志,这些标志在调用 Tesseract 时会被转发到 config 参数中。
  • return_tensors (strTensorType, 可选) — 返回的张量类型。可以是以下之一:
    • 未设置:返回一个 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf':返回一个类型为 tf.Tensor 的批次。
    • TensorType.PYTORCH'pt':返回一个类型为 torch.Tensor 的批次。
    • TensorType.NUMPY'np':返回一个类型为 np.ndarray 的批次。
    • TensorType.JAX'jax':返回一个类型为 jax.numpy.ndarray 的批次。
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。

预处理一张图像或一批图像。

LayoutLMv3Tokenizer

transformers.LayoutLMv3Tokenizer

< >

( vocab_file merges_file errors = 'replace' bos_token = '' eos_token = '' sep_token = '' cls_token = '' unk_token = '' pad_token = '' mask_token = '' add_prefix_space = True cls_token_box = [0, 0, 0, 0] sep_token_box = [0, 0, 0, 0] pad_token_box = [0, 0, 0, 0] pad_token_label = -100 only_label_first_subword = True **kwargs )

参数

  • vocab_file (str) — 词汇表文件的路径。
  • merges_file (str) — 合并文件的路径。
  • errors (str, 可选, 默认为 "replace") — 解码字节为UTF-8时遵循的范式。更多信息请参见 bytes.decode.
  • bos_token (str, optional, defaults to "<s>") — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

    在使用特殊标记构建序列时,这不是用于序列开头的标记。使用的标记是cls_token

  • eos_token (str, optional, defaults to "</s>") — The end of sequence token.

    在使用特殊标记构建序列时,这不是用于序列结束的标记。 使用的标记是sep_token

  • sep_token (str, 可选, 默认为 "") — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。
  • cls_token (str, 可选, 默认为 "") — 用于序列分类的分类器标记(对整个序列进行分类而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。
  • unk_token (str, optional, defaults to "") — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。
  • pad_token (str, optional, defaults to "") — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。
  • mask_token (str, 可选, 默认为 "") — 用于屏蔽值的标记。这是在训练此模型时用于屏蔽语言建模的标记。这是模型将尝试预测的标记。
  • add_prefix_space (bool, 可选, 默认为 True) — 是否在输入前添加一个初始空格。这允许将前导词视为任何其他词。(RoBERTa 分词器通过前面的空格检测词的开始)。
  • cls_token_box (List[int], optional, defaults to [0, 0, 0, 0]) — 用于特殊 [CLS] 令牌的边界框。
  • sep_token_box (List[int], optional, defaults to [0, 0, 0, 0]) — 用于特殊[SEP]令牌的边界框。
  • pad_token_box (List[int], optional, defaults to [0, 0, 0, 0]) — 用于特殊[PAD]令牌的边界框。
  • pad_token_label (int, 可选, 默认为 -100) — 用于填充标签的标签。默认为 -100,这是 PyTorch 的 CrossEntropyLoss 的 ignore_index.
  • only_label_first_subword (bool, optional, defaults to True) — 是否仅标记第一个子词,在提供单词标签的情况下。

构建一个LayoutLMv3分词器。基于RoBERTatokenizer(字节对编码或BPE)。 LayoutLMv3Tokenizer 可用于将单词、单词级别的边界框和可选的单词标签转换为 token级别的input_idsattention_masktoken_type_idsbbox和可选的labels(用于token分类)。

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

LayoutLMv3Tokenizer 运行端到端的分词:标点符号分割和词片。它还将单词级别的边界框转换为标记级别的边界框。

__call__

< >

( text: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] text_pair: typing.Union[typing.List[str], typing.List[typing.List[str]], NoneType] = None boxes: typing.Union[typing.List[typing.List[int]], typing.List[typing.List[typing.List[int]]]] = None word_labels: typing.Union[typing.List[int], typing.List[typing.List[int]], NoneType] = None add_special_tokens: bool = True padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = False truncation: typing.Union[bool, str, transformers.tokenization_utils_base.TruncationStrategy] = None max_length: typing.Optional[int] = None stride: int = 0 pad_to_multiple_of: typing.Optional[int] = None padding_side: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None return_token_type_ids: typing.Optional[bool] = None return_attention_mask: typing.Optional[bool] = None return_overflowing_tokens: bool = False return_special_tokens_mask: bool = False return_offsets_mapping: bool = False return_length: bool = False verbose: bool = True **kwargs )

参数

  • text (str, List[str], List[List[str]]) — 要编码的序列或序列批次。每个序列可以是一个字符串、一个字符串列表 (单个示例的单词或一批示例的问题)或一个字符串列表的列表(一批 单词)。
  • text_pair (List[str], List[List[str]]) — 要编码的序列或序列批次。每个序列应该是一个字符串列表 (预分词的字符串)。
  • boxes (List[List[int]], List[List[List[int]]]) — 单词级别的边界框。每个边界框应归一化到0-1000的范围内。
  • word_labels (List[int], List[List[int]], optional) — 单词级别的整数标签(用于诸如FUNSD、CORD等标记分类任务)。
  • add_special_tokens (bool, optional, defaults to True) — 是否使用与模型相关的特殊标记对序列进行编码。
  • padding (bool, str or PaddingStrategy, optional, defaults to False) — Activates and controls padding. Accepts the following values:
    • True or 'longest': Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).
    • 'max_length': Pad to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided.
    • False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different lengths).
  • truncation (bool, str or TruncationStrategy, optional, defaults to False) — Activates and controls truncation. Accepts the following values:
    • True or 'longest_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_second': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • False or 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
  • max_length (int, optional) — Controls the maximum length to use by one of the truncation/padding parameters.

    如果未设置或设置为None,则在需要截断/填充参数时,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如XLNet),则截断/填充到最大长度的功能将被停用。

  • stride (int, 可选, 默认为 0) — 如果与 max_length 一起设置为一个数字,当 return_overflowing_tokens=True 时返回的溢出标记将包含来自截断序列末尾的一些标记,以提供截断序列和溢出序列之间的一些重叠。此参数的值定义了重叠标记的数量。
  • pad_to_multiple_of (int, 可选) — 如果设置,将序列填充到提供的值的倍数。这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。
  • add_special_tokens (bool, optional, defaults to True) — 是否使用与模型相关的特殊标记对序列进行编码。
  • padding (bool, str or PaddingStrategy, optional, defaults to False) — Activates and controls padding. Accepts the following values:
    • True or 'longest': Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).
    • 'max_length': Pad to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided.
    • False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different lengths).
  • truncation (bool, str or TruncationStrategy, optional, defaults to False) — Activates and controls truncation. Accepts the following values:
    • True or 'longest_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_second': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • False or 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
  • max_length (int, 可选) — 控制由截断/填充参数之一使用的最大长度。如果未设置或设置为 None,则在需要最大长度的情况下,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如XLNet), 则截断/填充到最大长度的功能将被停用。
  • stride (int, 可选, 默认为 0) — 如果与 max_length 一起设置为一个数字,当 return_overflowing_tokens=True 时返回的溢出标记将包含来自截断序列末尾的一些标记,以提供截断序列和溢出序列之间的一些重叠。此参数的值定义了重叠标记的数量。
  • pad_to_multiple_of (int, 可选) — 如果设置,将序列填充到提供的值的倍数。这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。

主要方法,用于将一个或多个序列或一个或多个序列对进行分词,并为模型准备,这些序列带有单词级别的归一化边界框和可选的标签。

保存词汇表

< >

( 保存目录: str 文件名前缀: typing.Optional[str] = None )

LayoutLMv3TokenizerFast

transformers.LayoutLMv3TokenizerFast

< >

( vocab_file = None merges_file = None tokenizer_file = None errors = 'replace' bos_token = '' eos_token = '' sep_token = '' cls_token = '' unk_token = '' pad_token = '' mask_token = '' add_prefix_space = True trim_offsets = True cls_token_box = [0, 0, 0, 0] sep_token_box = [0, 0, 0, 0] pad_token_box = [0, 0, 0, 0] pad_token_label = -100 only_label_first_subword = True **kwargs )

参数

  • vocab_file (str) — 词汇表文件的路径。
  • merges_file (str) — 合并文件的路径。
  • errors (str, 可选, 默认为 "replace") — 解码字节为UTF-8时遵循的范式。更多信息请参见 bytes.decode.
  • bos_token (str, optional, defaults to "<s>") — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

    在使用特殊标记构建序列时,这不是用于序列开头的标记。使用的标记是cls_token

  • eos_token (str, optional, defaults to "</s>") — The end of sequence token.

    在使用特殊标记构建序列时,这不是用于序列结束的标记。 使用的标记是sep_token

  • sep_token (str, 可选, 默认为 "") — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。
  • cls_token (str, 可选, 默认为 "") — 用于序列分类的分类器标记(对整个序列进行分类而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。
  • unk_token (str, optional, defaults to "") — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。
  • pad_token (str, optional, defaults to "") — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。
  • mask_token (str, optional, defaults to "") — 用于屏蔽值的标记。这是在训练此模型时用于屏蔽语言建模的标记。这是模型将尝试预测的标记。
  • add_prefix_space (bool, 可选, 默认为 False) — 是否在输入前添加一个初始空格。这允许将前导词视为任何其他词。(RoBERTa 分词器通过前面的空格检测词的开始)。
  • trim_offsets (bool, 可选, 默认为 True) — 后处理步骤是否应修剪偏移量以避免包含空格。
  • cls_token_box (List[int], optional, defaults to [0, 0, 0, 0]) — 用于特殊 [CLS] 标记的边界框。
  • sep_token_box (List[int], optional, defaults to [0, 0, 0, 0]) — 用于特殊 [SEP] 令牌的边界框。
  • pad_token_box (List[int], optional, 默认为 [0, 0, 0, 0]) — 用于特殊 [PAD] 令牌的边界框。
  • pad_token_label (int, optional, defaults to -100) — 用于填充标签的标签。默认为-100,这是PyTorch的CrossEntropyLoss的ignore_index
  • only_label_first_subword (bool, optional, defaults to True) — 是否仅标记第一个子词,在提供单词标签的情况下。

构建一个“快速”的LayoutLMv3分词器(基于HuggingFace的tokenizers库)。基于BPE。

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

__call__

< >

( text: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] text_pair: typing.Union[typing.List[str], typing.List[typing.List[str]], NoneType] = None boxes: typing.Union[typing.List[typing.List[int]], typing.List[typing.List[typing.List[int]]]] = None word_labels: typing.Union[typing.List[int], typing.List[typing.List[int]], NoneType] = None add_special_tokens: bool = True padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = False truncation: typing.Union[bool, str, transformers.tokenization_utils_base.TruncationStrategy] = None max_length: typing.Optional[int] = None stride: int = 0 pad_to_multiple_of: typing.Optional[int] = None padding_side: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None return_token_type_ids: typing.Optional[bool] = None return_attention_mask: typing.Optional[bool] = None return_overflowing_tokens: bool = False return_special_tokens_mask: bool = False return_offsets_mapping: bool = False return_length: bool = False verbose: bool = True **kwargs )

参数

  • text (str, List[str], List[List[str]]) — 要编码的序列或序列批次。每个序列可以是一个字符串、一个字符串列表 (单个示例的单词或一批示例的问题)或一个字符串列表的列表(一批 单词)。
  • text_pair (List[str], List[List[str]]) — 要编码的序列或序列批次。每个序列应该是一个字符串列表 (预分词的字符串)。
  • boxes (List[List[int]], List[List[List[int]]]) — 单词级别的边界框。每个边界框应归一化到0-1000的范围内。
  • word_labels (List[int], List[List[int]], optional) — 单词级别的整数标签(用于如FUNSD、CORD等标记分类任务)。
  • add_special_tokens (bool, optional, defaults to True) — 是否使用与模型相关的特殊标记对序列进行编码。
  • padding (bool, str or PaddingStrategy, optional, defaults to False) — Activates and controls padding. Accepts the following values:
    • True or 'longest': Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).
    • 'max_length': Pad to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided.
    • False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different lengths).
  • truncation (bool, str or TruncationStrategy, optional, defaults to False) — Activates and controls truncation. Accepts the following values:
    • True or 'longest_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_second': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • False or 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
  • max_length (int, optional) — Controls the maximum length to use by one of the truncation/padding parameters.

    如果未设置或设置为None,则在需要截断/填充参数时,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如XLNet),则截断/填充到最大长度的功能将被停用。

  • stride (int, 可选, 默认为 0) — 如果设置为一个数字并与 max_length 一起使用,当 return_overflowing_tokens=True 时返回的溢出标记将包含一些来自截断序列末尾的标记,以提供截断序列和溢出序列之间的一些重叠。此参数的值定义了重叠标记的数量。
  • pad_to_multiple_of (int, optional) — 如果设置,将序列填充到提供的值的倍数。这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。
  • add_special_tokens (bool, optional, defaults to True) — 是否使用与模型相关的特殊标记对序列进行编码。
  • padding (bool, str or PaddingStrategy, optional, defaults to False) — Activates and controls padding. Accepts the following values:
    • True or 'longest': Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).
    • 'max_length': Pad to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided.
    • False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different lengths).
  • truncation (bool, str or TruncationStrategy, optional, defaults to False) — Activates and controls truncation. Accepts the following values:
    • True or 'longest_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_second': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • False or 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
  • max_length (int, optional) — 控制由截断/填充参数之一使用的最大长度。如果未设置或设置为 None,则在需要最大长度时,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如XLNet), 则截断/填充到最大长度将被停用。
  • stride (int, 可选, 默认为 0) — 如果设置为一个数字并与 max_length 一起使用,当 return_overflowing_tokens=True 时返回的溢出标记将包含一些来自截断序列末尾的标记, 以提供截断序列和溢出序列之间的一些重叠。此参数的值定义了重叠标记的数量。
  • pad_to_multiple_of (int, 可选) — 如果设置,将序列填充到提供的值的倍数。这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。

主要方法,用于将一个或多个序列或一个或多个序列对进行分词,并为模型准备,这些序列带有单词级别的归一化边界框和可选的标签。

LayoutLMv3Processor

class transformers.LayoutLMv3Processor

< >

( image_processor = 无 tokenizer = 无 **kwargs )

参数

构建一个LayoutLMv3处理器,它将LayoutLMv3图像处理器和LayoutLMv3分词器组合成一个单一的处理器。

LayoutLMv3Processor 提供了准备模型数据所需的所有功能。

首先使用LayoutLMv3ImageProcessor来调整和规范化文档图像,并可选地应用OCR来获取单词和规范化边界框。然后将这些提供给LayoutLMv3TokenizerLayoutLMv3TokenizerFast,它们将单词和边界框转换为标记级别的input_idsattention_masktoken_type_idsbbox。可选地,可以提供整数word_labels,这些将被转换为标记级别的labels,用于标记分类任务(如FUNSD、CORD)。

__call__

< >

( images text: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] = None text_pair: typing.Union[typing.List[str], typing.List[typing.List[str]], NoneType] = None boxes: typing.Union[typing.List[typing.List[int]], typing.List[typing.List[typing.List[int]]]] = None word_labels: typing.Union[typing.List[int], typing.List[typing.List[int]], NoneType] = None add_special_tokens: bool = True padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = False truncation: typing.Union[bool, str, transformers.tokenization_utils_base.TruncationStrategy] = None max_length: typing.Optional[int] = None stride: int = 0 pad_to_multiple_of: typing.Optional[int] = None return_token_type_ids: typing.Optional[bool] = None return_attention_mask: typing.Optional[bool] = None return_overflowing_tokens: bool = False return_special_tokens_mask: bool = False return_offsets_mapping: bool = False return_length: bool = False verbose: bool = True return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None **kwargs )

此方法首先将images参数转发给call()。如果LayoutLMv3ImageProcessor初始化时将apply_ocr设置为True,它会将获得的单词和边界框与附加参数一起传递给call()并返回输出,同时返回调整大小和归一化的pixel_values。如果LayoutLMv3ImageProcessor初始化时将apply_ocr设置为False,它会将用户指定的单词(text/`text_pair)和boxes与附加参数一起传递给call()并返回输出,同时返回调整大小和归一化的pixel_values

请参考上述两个方法的文档字符串以获取更多信息。

Pytorch
Hide Pytorch content

LayoutLMv3Model

transformers.LayoutLMv3Model

< >

( config )

参数

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

裸的LayoutLMv3模型转换器输出原始隐藏状态,没有任何特定的头部。 该模型是PyTorch torch.nn.Module的子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有事项。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None bbox: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None token_type_ids: typing.Optional[torch.LongTensor] = None position_ids: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None pixel_values: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, token_sequence_length)) — Indices of input sequence tokens in the vocabulary.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • bbox (torch.LongTensor of shape (batch_size, token_sequence_length, 4), optional) — Bounding boxes of each input sequence tokens. Selected in the range [0, config.max_2d_position_embeddings-1]. Each bounding box should be a normalized version in (x0, y0, x1, y1) format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1, y1) represents the position of the lower right corner.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1 其中 1 是用于 [CLS] 标记的。有关 patch_sequence_length 的信息,请参见 pixel_values

  • pixel_values (torch.FloatTensor 形状为 (batch_size, num_channels, height, width)) — 文档图像的批次。每张图像被分割成形状为 (num_channels, config.patch_size, config.patch_size) 的补丁,补丁的总数 (=patch_sequence_length) 等于 ((height / config.patch_size) * (width / config.patch_size)).
  • attention_mask (torch.FloatTensor of shape (batch_size, token_sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1 其中 1 是用于 [CLS] 标记的。有关 patch_sequence_length 的信息,请参见 pixel_values

    什么是注意力掩码?

  • token_type_ids (torch.LongTensor of shape (batch_size, token_sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    什么是token type IDs?

  • position_ids (torch.LongTensor of shape (batch_size, token_sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    什么是位置ID?

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, token_sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回的张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(LayoutLMv3Config)和输入。

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

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递了 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为 (batch_size, sequence_length, hidden_size)

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

  • attentions (tuple(torch.FloatTensor), 可选, 当传递了 output_attentions=True 或当 config.output_attentions=True 时返回) — 由 torch.FloatTensor 组成的元组(每一层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

LayoutLMv3Model 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoProcessor, AutoModel
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=False)
>>> model = AutoModel.from_pretrained("microsoft/layoutlmv3-base")

>>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train", trust_remote_code=True)
>>> example = dataset[0]
>>> image = example["image"]
>>> words = example["tokens"]
>>> boxes = example["bboxes"]

>>> encoding = processor(image, words, boxes=boxes, return_tensors="pt")

>>> outputs = model(**encoding)
>>> last_hidden_states = outputs.last_hidden_state

LayoutLMv3ForSequenceClassification

transformers.LayoutLMv3ForSequenceClassification

< >

( config )

参数

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

LayoutLMv3 模型,顶部带有序列分类头(在最终隐藏状态的 [CLS] 标记上有一个线性层),例如用于文档图像分类任务,如 RVL-CDIP 数据集。

该模型是一个PyTorch torch.nn.Module 子类。将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None token_type_ids: typing.Optional[torch.LongTensor] = None position_ids: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None bbox: typing.Optional[torch.LongTensor] = None pixel_values: typing.Optional[torch.LongTensor] = None ) transformers.modeling_outputs.SequenceClassifierOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • bbox (torch.LongTensor 形状为 (batch_size, sequence_length, 4), 可选) — 每个输入序列标记的边界框。选择范围在 [0, config.max_2d_position_embeddings-1]。每个边界框应为 (x0, y0, x1, y1) 格式的归一化版本,其中 (x0, y0) 对应于边界框左上角的位置,(x1, y1) 表示右下角的位置。
  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 文档图像的批次。每张图像被分割成形状为 (num_channels, config.patch_size, config.patch_size) 的补丁,补丁的总数 (=patch_sequence_length) 等于 ((height / config.patch_size) * (width / config.patch_size)).
  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    什么是位置ID?

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.modeling_outputs.SequenceClassifierOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.SequenceClassifierOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(LayoutLMv3Config)和输入。

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 分类(或回归,如果 config.num_labels==1)损失。

  • logits (torch.FloatTensor 形状为 (batch_size, config.num_labels)) — 分类(或回归,如果 config.num_labels==1)得分(在 SoftMax 之前)。

  • hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为 (batch_size, sequence_length, hidden_size)

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

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

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

LayoutLMv3ForSequenceClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoProcessor, AutoModelForSequenceClassification
>>> from datasets import load_dataset
>>> import torch

>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=False)
>>> model = AutoModelForSequenceClassification.from_pretrained("microsoft/layoutlmv3-base")

>>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train", trust_remote_code=True)
>>> example = dataset[0]
>>> image = example["image"]
>>> words = example["tokens"]
>>> boxes = example["bboxes"]

>>> encoding = processor(image, words, boxes=boxes, return_tensors="pt")
>>> sequence_label = torch.tensor([1])

>>> outputs = model(**encoding, labels=sequence_label)
>>> loss = outputs.loss
>>> logits = outputs.logits

LayoutLMv3ForTokenClassification

transformers.LayoutLMv3ForTokenClassification

< >

( config )

参数

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

LayoutLMv3 模型,顶部带有标记分类头(在最终隐藏状态之上的线性层),例如用于序列标注(信息提取)任务,如 FUNSDSROIECORDKleister-NDA

该模型是一个PyTorch torch.nn.Module 子类。将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None bbox: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None token_type_ids: typing.Optional[torch.LongTensor] = None position_ids: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None pixel_values: typing.Optional[torch.LongTensor] = None ) transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • bbox (torch.LongTensor 形状为 (batch_size, sequence_length, 4), 可选) — 每个输入序列标记的边界框。选择范围在 [0, config.max_2d_position_embeddings-1]。每个边界框应为 (x0, y0, x1, y1) 格式的归一化版本,其中 (x0, y0) 对应于边界框左上角的位置,(x1, y1) 表示右下角的位置。
  • pixel_values (torch.FloatTensor 形状为 (batch_size, num_channels, height, width)) — 文档图像的批次。每张图像被分割成形状为 (num_channels, config.patch_size, config.patch_size) 的补丁,补丁的总数 (=patch_sequence_length) 等于 ((height / config.patch_size) * (width / config.patch_size)).
  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    什么是位置ID?

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — 用于计算标记分类损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。

返回

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.TokenClassifierOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,取决于配置(LayoutLMv3Config)和输入。

  • loss (torch.FloatTensor 形状为 (1,), 可选, 当提供 labels 时返回) — 分类损失。

  • logits (torch.FloatTensor 形状为 (batch_size, sequence_length, config.num_labels)) — 分类分数(在 SoftMax 之前)。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为 (batch_size, sequence_length, hidden_size)

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

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

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

LayoutLMv3ForTokenClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoProcessor, AutoModelForTokenClassification
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=False)
>>> model = AutoModelForTokenClassification.from_pretrained("microsoft/layoutlmv3-base", num_labels=7)

>>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train", trust_remote_code=True)
>>> example = dataset[0]
>>> image = example["image"]
>>> words = example["tokens"]
>>> boxes = example["bboxes"]
>>> word_labels = example["ner_tags"]

>>> encoding = processor(image, words, boxes=boxes, word_labels=word_labels, return_tensors="pt")

>>> outputs = model(**encoding)
>>> loss = outputs.loss
>>> logits = outputs.logits

LayoutLMv3ForQuestionAnswering

transformers.LayoutLMv3ForQuestionAnswering

< >

( config )

参数

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

LayoutLMv3 模型,顶部带有用于抽取式问答任务的跨度分类头,例如 DocVQA(在隐藏状态输出的文本部分顶部添加一个线性层,用于计算 span start logitsspan end logits)。

该模型是一个PyTorch torch.nn.Module 子类。将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None token_type_ids: typing.Optional[torch.LongTensor] = None position_ids: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None start_positions: typing.Optional[torch.LongTensor] = None end_positions: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None bbox: typing.Optional[torch.LongTensor] = None pixel_values: typing.Optional[torch.LongTensor] = None ) transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • bbox (torch.LongTensor 形状为 (batch_size, sequence_length, 4), 可选) — 每个输入序列标记的边界框。选择范围在 [0, config.max_2d_position_embeddings-1]。每个边界框应为 (x0, y0, x1, y1) 格式的归一化版本,其中 (x0, y0) 对应于边界框左上角的位置,而 (x1, y1) 表示右下角的位置。
  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 文档图像的批次。每张图像被分割成形状为 (num_channels, config.patch_size, config.patch_size) 的补丁,补丁的总数 (=patch_sequence_length) 等于 ((height / config.patch_size) * (width / config.patch_size)).
  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    什么是位置ID?

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • start_positions (torch.LongTensor of shape (batch_size,), optional) — 用于计算标记分类损失的标记跨度起始位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会被考虑用于计算损失。
  • end_positions (torch.LongTensor of shape (batch_size,), optional) — 用于计算标记分类损失的标记跨度结束位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会用于计算损失。

返回

transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.QuestionAnsweringModelOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(LayoutLMv3Config)和输入。

  • loss (torch.FloatTensor 形状为 (1,), 可选, 当提供 labels 时返回) — 总跨度提取损失是起始和结束位置的交叉熵之和。

  • start_logits (torch.FloatTensor 形状为 (batch_size, sequence_length)) — 跨度起始分数(在 SoftMax 之前)。

  • end_logits (torch.FloatTensor 形状为 (batch_size, sequence_length)) — 跨度结束分数(在 SoftMax 之前)。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为 (batch_size, sequence_length, hidden_size)

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

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

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

LayoutLMv3ForQuestionAnswering 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoProcessor, AutoModelForQuestionAnswering
>>> from datasets import load_dataset
>>> import torch

>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=False)
>>> model = AutoModelForQuestionAnswering.from_pretrained("microsoft/layoutlmv3-base")

>>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train", trust_remote_code=True)
>>> example = dataset[0]
>>> image = example["image"]
>>> question = "what's his name?"
>>> words = example["tokens"]
>>> boxes = example["bboxes"]

>>> encoding = processor(image, question, words, boxes=boxes, return_tensors="pt")
>>> start_positions = torch.tensor([1])
>>> end_positions = torch.tensor([3])

>>> outputs = model(**encoding, start_positions=start_positions, end_positions=end_positions)
>>> loss = outputs.loss
>>> start_scores = outputs.start_logits
>>> end_scores = outputs.end_logits
TensorFlow
Hide TensorFlow content

TFLayoutLMv3Model

transformers.TFLayoutLMv3Model

< >

( config *inputs **kwargs )

参数

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

裸的LayoutLMv3模型转换器输出原始的隐藏状态,没有任何特定的头部。 该模型继承自TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。

TensorFlow 模型和层在 transformers 中接受两种格式作为输入:

  • 将所有输入作为关键字参数(如PyTorch模型),或
  • 将所有输入作为列表、元组或字典放在第一个位置参数中。

支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit() 这样的方法时,事情应该“正常工作”——只需以 model.fit() 支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:

  • 仅包含input_ids的单个张量,没有其他内容:model(input_ids)
  • 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序: model([input_ids, attention_mask])model([input_ids, attention_mask, token_type_ids])
  • 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量: model({"input_ids": input_ids, "token_type_ids": token_type_ids})

请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!

调用

< >

( input_ids: tf.Tensor | None = None bbox: tf.Tensor | None = None attention_mask: tf.Tensor | None = None token_type_ids: tf.Tensor | None = None position_ids: tf.Tensor | None = None head_mask: tf.Tensor | None = None inputs_embeds: tf.Tensor | None = None pixel_values: tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: bool = False ) transformers.modeling_tf_outputs.TFBaseModelOutputtuple(tf.Tensor)

参数

  • input_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • bbox (Numpy array or tf.Tensor of shape (batch_size, sequence_length, 4), optional) — Bounding boxes of each input sequence tokens. Selected in the range [0, config.max_2d_position_embeddings-1]. Each bounding box should be a normalized version in (x0, y0, x1, y1) format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1, y1) represents the position of the lower right corner.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1 其中 1 是用于 [CLS] 标记的。有关 patch_sequence_length 的信息,请参见 pixel_values

  • pixel_values (tf.Tensor 形状为 (batch_size, num_channels, height, width)) — 文档图像的批次。每张图像被分割成形状为 (num_channels, config.patch_size, config.patch_size) 的补丁,补丁的总数 (=patch_sequence_length) 等于 ((height / config.patch_size) * (width / config.patch_size)).
  • attention_mask (tf.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    什么是注意力掩码?

  • token_type_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    什么是token type IDs?

  • position_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    什么是位置ID?

  • head_mask (tf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (tf.Tensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.modeling_tf_outputs.TFBaseModelOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFBaseModelOutput 或一个由 tf.Tensor 组成的元组(如果 传递了 return_dict=False 或当 config.return_dict=False 时),包含根据配置(LayoutLMv3Config)和输入而定的各种元素。

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

  • hidden_states (tuple(tf.FloatTensor), 可选, 当传递了 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 tf.Tensor 组成的元组(一个用于嵌入层的输出,一个用于每一层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(tf.Tensor), 可选, 当传递了 output_attentions=True 或当 config.output_attentions=True 时返回) — 由 tf.Tensor 组成的元组(每一层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

TFLayoutLMv3Model 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoProcessor, TFAutoModel
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=False)
>>> model = TFAutoModel.from_pretrained("microsoft/layoutlmv3-base")

>>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train", trust_remote_code=True)
>>> example = dataset[0]
>>> image = example["image"]
>>> words = example["tokens"]
>>> boxes = example["bboxes"]

>>> encoding = processor(image, words, boxes=boxes, return_tensors="tf")

>>> outputs = model(**encoding)
>>> last_hidden_states = outputs.last_hidden_state

TFLayoutLMv3ForSequenceClassification

transformers.TFLayoutLMv3ForSequenceClassification

< >

( config: LayoutLMv3Config **kwargs )

参数

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

LayoutLMv3 模型,顶部带有序列分类头(在最终隐藏状态的 [CLS] 标记上有一个线性层),例如用于文档图像分类任务,如 RVL-CDIP 数据集。

该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。

TensorFlow 模型和层在 transformers 中接受两种格式作为输入:

  • 将所有输入作为关键字参数(如PyTorch模型),或
  • 将所有输入作为列表、元组或字典放在第一个位置参数中。

支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit() 这样的方法时,事情应该“正常工作”——只需以 model.fit() 支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:

  • 仅包含input_ids的单个张量,没有其他内容:model(input_ids)
  • 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序: model([input_ids, attention_mask])model([input_ids, attention_mask, token_type_ids])
  • 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量: model({"input_ids": input_ids, "token_type_ids": token_type_ids})

请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!

调用

< >

( input_ids: tf.Tensor | None = None attention_mask: tf.Tensor | None = None token_type_ids: tf.Tensor | None = None position_ids: tf.Tensor | None = None head_mask: tf.Tensor | None = None inputs_embeds: tf.Tensor | None = None labels: tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None bbox: tf.Tensor | None = None pixel_values: tf.Tensor | None = None training: Optional[bool] = False ) transformers.modeling_tf_outputs.TFSequenceClassifierOutputtuple(tf.Tensor)

参数

  • input_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • bbox (Numpy array or tf.Tensor of shape (batch_size, sequence_length, 4), optional) — Bounding boxes of each input sequence tokens. Selected in the range [0, config.max_2d_position_embeddings-1]. Each bounding box should be a normalized version in (x0, y0, x1, y1) format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1, y1) represents the position of the lower right corner.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1 其中 1 是用于 [CLS] 标记的。有关 patch_sequence_length 的信息,请参见 pixel_values

  • pixel_values (tf.Tensor 形状为 (batch_size, num_channels, height, width)) — 文档图像的批次。每张图像被分割成形状为 (num_channels, config.patch_size, config.patch_size) 的补丁,补丁的总数 (=patch_sequence_length) 等于 ((height / config.patch_size) * (width / config.patch_size)).
  • attention_mask (tf.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    什么是注意力掩码?

  • token_type_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    什么是token type IDs?

  • position_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    什么是位置ID?

  • head_mask (tf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_tf_outputs.TFSequenceClassifierOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFSequenceClassifierOutput 或一个 tf.Tensor 的元组(如果 return_dict=False 被传递或当 config.return_dict=False 时)包含根据配置(LayoutLMv3Config)和输入的各种元素。

  • loss (tf.Tensor 形状为 (batch_size, ), 可选, 当提供 labels 时返回) — 分类(或回归,如果 config.num_labels==1)损失。

  • logits (tf.Tensor 形状为 (batch_size, config.num_labels)) — 分类(或回归,如果 config.num_labels==1)得分(在 SoftMax 之前)。

  • hidden_states (tuple(tf.Tensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — tf.Tensor 的元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    模型在每层输出处的隐藏状态加上初始嵌入输出。

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

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

TFLayoutLMv3ForSequenceClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoProcessor, TFAutoModelForSequenceClassification
>>> from datasets import load_dataset
>>> import tensorflow as tf

>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=False)
>>> model = TFAutoModelForSequenceClassification.from_pretrained("microsoft/layoutlmv3-base")

>>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train", trust_remote_code=True)
>>> example = dataset[0]
>>> image = example["image"]
>>> words = example["tokens"]
>>> boxes = example["bboxes"]

>>> encoding = processor(image, words, boxes=boxes, return_tensors="tf")
>>> sequence_label = tf.convert_to_tensor([1])

>>> outputs = model(**encoding, labels=sequence_label)
>>> loss = outputs.loss
>>> logits = outputs.logits

TFLayoutLMv3ForTokenClassification

transformers.TFLayoutLMv3ForTokenClassification

< >

( config: LayoutLMv3Config **kwargs )

参数

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

LayoutLMv3 模型,顶部带有标记分类头(在最终隐藏状态之上的线性层),例如用于序列标注(信息提取)任务,如 FUNSDSROIECORDKleister-NDA

该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。

TensorFlow 模型和层在 transformers 中接受两种格式作为输入:

  • 将所有输入作为关键字参数(如PyTorch模型),或
  • 将所有输入作为列表、元组或字典放在第一个位置参数中。

支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit() 这样的方法时,事情应该“正常工作”——只需以 model.fit() 支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:

  • 仅包含input_ids的单个张量,没有其他内容:model(input_ids)
  • 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序: model([input_ids, attention_mask])model([input_ids, attention_mask, token_type_ids])
  • 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量: model({"input_ids": input_ids, "token_type_ids": token_type_ids})

请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!

调用

< >

( input_ids: tf.Tensor | None = None bbox: tf.Tensor | None = None attention_mask: tf.Tensor | None = None token_type_ids: tf.Tensor | None = None position_ids: tf.Tensor | None = None head_mask: tf.Tensor | None = None inputs_embeds: tf.Tensor | None = None labels: tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None pixel_values: tf.Tensor | None = None training: Optional[bool] = False ) transformers.modeling_tf_outputs.TFTokenClassifierOutputtuple(tf.Tensor)

参数

  • input_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • bbox (Numpy array or tf.Tensor of shape (batch_size, sequence_length, 4), optional) — Bounding boxes of each input sequence tokens. Selected in the range [0, config.max_2d_position_embeddings-1]. Each bounding box should be a normalized version in (x0, y0, x1, y1) format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1, y1) represents the position of the lower right corner.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1 其中 1 是用于 [CLS] 标记的。有关 patch_sequence_length 的信息,请参见 pixel_values

  • pixel_values (tf.Tensor 形状为 (batch_size, num_channels, height, width)) — 文档图像的批次。每张图像被分割成形状为 (num_channels, config.patch_size, config.patch_size) 的补丁,补丁的总数 (=patch_sequence_length) 等于 ((height / config.patch_size) * (width / config.patch_size)).
  • attention_mask (tf.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    什么是注意力掩码?

  • token_type_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    什么是token type IDs?

  • position_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    什么是位置ID?

  • head_mask (tf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (tf.Tensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • labels (tf.Tensor of shape (batch_size, sequence_length), optional) — 用于计算标记分类损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。

返回

transformers.modeling_tf_outputs.TFTokenClassifierOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFTokenClassifierOutput 或一个 tf.Tensor 的元组(如果 传递了 return_dict=False 或当 config.return_dict=False 时)包含各种元素,具体取决于 配置(LayoutLMv3Config)和输入。

  • loss (tf.Tensor 形状为 (n,), 可选, 其中 n 是未掩码标签的数量,当提供 labels 时返回) — 分类损失。

  • logits (tf.Tensor 形状为 (batch_size, sequence_length, config.num_labels)) — 分类分数(在 SoftMax 之前)。

  • hidden_states (tuple(tf.Tensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — tf.Tensor 的元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    模型在每层输出处的隐藏状态加上初始嵌入输出。

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

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

TFLayoutLMv3ForTokenClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoProcessor, TFAutoModelForTokenClassification
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=False)
>>> model = TFAutoModelForTokenClassification.from_pretrained("microsoft/layoutlmv3-base", num_labels=7)

>>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train", trust_remote_code=True)
>>> example = dataset[0]
>>> image = example["image"]
>>> words = example["tokens"]
>>> boxes = example["bboxes"]
>>> word_labels = example["ner_tags"]

>>> encoding = processor(image, words, boxes=boxes, word_labels=word_labels, return_tensors="tf")

>>> outputs = model(**encoding)
>>> loss = outputs.loss
>>> logits = outputs.logits

TFLayoutLMv3ForQuestionAnswering

transformers.TFLayoutLMv3ForQuestionAnswering

< >

( config: LayoutLMv3Config **kwargs )

参数

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

LayoutLMv3 模型,顶部带有用于抽取式问答任务的跨度分类头,例如 DocVQA(在隐藏状态输出的文本部分顶部添加一个线性层,用于计算 span start logitsspan end logits)。

该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。

TensorFlow 模型和层在 transformers 中接受两种格式作为输入:

  • 将所有输入作为关键字参数(如PyTorch模型),或
  • 将所有输入作为列表、元组或字典放在第一个位置参数中。

支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit() 这样的方法时,事情应该“正常工作”——只需以 model.fit() 支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:

  • 仅包含input_ids的单个张量,没有其他内容:model(input_ids)
  • 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序: model([input_ids, attention_mask])model([input_ids, attention_mask, token_type_ids])
  • 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量: model({"input_ids": input_ids, "token_type_ids": token_type_ids})

请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!

调用

< >

( input_ids: tf.Tensor | None = None attention_mask: tf.Tensor | None = None token_type_ids: tf.Tensor | None = None position_ids: tf.Tensor | None = None head_mask: tf.Tensor | None = None inputs_embeds: tf.Tensor | None = None start_positions: tf.Tensor | None = None end_positions: tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None bbox: tf.Tensor | None = None pixel_values: tf.Tensor | None = None return_dict: Optional[bool] = None training: bool = False ) transformers.modeling_tf_outputs.TFQuestionAnsweringModelOutputtuple(tf.Tensor)

参数

  • input_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • bbox (Numpy array or tf.Tensor of shape (batch_size, sequence_length, 4), optional) — Bounding boxes of each input sequence tokens. Selected in the range [0, config.max_2d_position_embeddings-1]. Each bounding box should be a normalized version in (x0, y0, x1, y1) format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1, y1) represents the position of the lower right corner.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1 其中 1 是用于 [CLS] 标记的。有关 patch_sequence_length 的信息,请参见 pixel_values

  • pixel_values (tf.Tensor 形状为 (batch_size, num_channels, height, width)) — 文档图像的批次。每张图像被分割成形状为 (num_channels, config.patch_size, config.patch_size) 的补丁,补丁的总数 (=patch_sequence_length) 等于 ((height / config.patch_size) * (width / config.patch_size)).
  • attention_mask (tf.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    什么是注意力掩码?

  • token_type_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    什么是token type IDs?

  • position_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    请注意,sequence_length = token_sequence_length + patch_sequence_length + 1,其中1代表[CLS]标记。有关patch_sequence_length的详细信息,请参见pixel_values

    什么是位置ID?

  • head_mask (tf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • start_positions (tf.Tensor 形状为 (batch_size,), 可选) — 用于计算标记分类损失的标记跨度起始位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会用于计算损失。
  • end_positions (tf.Tensor of shape (batch_size,), optional) — 用于计算标记分类损失的标记跨度结束位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会用于计算损失。

返回

transformers.modeling_tf_outputs.TFQuestionAnsweringModelOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFQuestionAnsweringModelOutput 或一个 tf.Tensor 元组(如果 return_dict=False 被传递或当 config.return_dict=False 时)包含各种元素,具体取决于 配置 (LayoutLMv3Config) 和输入。

  • loss (tf.Tensor 形状为 (batch_size, ), 可选, 当提供 start_positionsend_positions 时返回) — 总跨度提取损失是起始和结束位置的交叉熵之和。

  • start_logits (tf.Tensor 形状为 (batch_size, sequence_length)) — 跨度起始分数(在 SoftMax 之前)。

  • end_logits (tf.Tensor 形状为 (batch_size, sequence_length)) — 跨度结束分数(在 SoftMax 之前)。

  • hidden_states (tuple(tf.Tensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — tf.Tensor 元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    模型在每层输出处的隐藏状态加上初始嵌入输出。

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

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

TFLayoutLMv3ForQuestionAnswering 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoProcessor, TFAutoModelForQuestionAnswering
>>> from datasets import load_dataset
>>> import tensorflow as tf

>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=False)
>>> model = TFAutoModelForQuestionAnswering.from_pretrained("microsoft/layoutlmv3-base")

>>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train", trust_remote_code=True)
>>> example = dataset[0]
>>> image = example["image"]
>>> question = "what's his name?"
>>> words = example["tokens"]
>>> boxes = example["bboxes"]

>>> encoding = processor(image, question, words, boxes=boxes, return_tensors="tf")
>>> start_positions = tf.convert_to_tensor([1])
>>> end_positions = tf.convert_to_tensor([3])

>>> outputs = model(**encoding, start_positions=start_positions, end_positions=end_positions)
>>> loss = outputs.loss
>>> start_scores = outputs.start_logits
>>> end_scores = outputs.end_logits
< > Update on GitHub