LayoutLMV2
概述
LayoutLMV2模型由Yang Xu、Yiheng Xu、Tengchao Lv、Lei Cui、Furu Wei、Guoxin Wang、Yijuan Lu、Dinei Florencio、Cha Zhang、Wanxiang Che、Min Zhang、Lidong Zhou在LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding中提出。LayoutLMV2改进了LayoutLM,在多个文档图像理解基准测试中取得了最先进的结果:
- 从扫描文档中提取信息:FUNSD数据集(包含199个带注释的表格,共计超过30,000个单词),CORD数据集(包含800张收据用于训练,100张用于验证,100张用于测试),SROIE数据集(包含626张收据用于训练和347张收据用于测试)以及Kleister-NDA数据集(包含来自EDGAR数据库的非披露协议,包括254份文档用于训练,83份文档用于验证,和203份文档用于测试)。
- 文档图像分类:RVL-CDIP 数据集(包含40万张图像,属于16个类别之一)。
- 文档视觉问答:DocVQA 数据集(包含 50,000 个问题,基于 12,000 多张文档图像)。
论文的摘要如下:
文本和布局的预训练在各种视觉丰富的文档理解任务中被证明是有效的,这得益于其有效的模型架构和大规模未标记的扫描/数字生成文档的优势。在本文中,我们通过在多模态框架中预训练文本、布局和图像来介绍LayoutLMv2,其中利用了新的模型架构和预训练任务。具体来说,LayoutLMv2不仅使用了现有的掩码视觉语言建模任务,还在预训练阶段引入了新的文本-图像对齐和文本-图像匹配任务,从而更好地学习跨模态交互。同时,它还将空间感知的自注意力机制集成到Transformer架构中,使模型能够充分理解不同文本块之间的相对位置关系。实验结果表明,LayoutLMv2在多种下游视觉丰富的文档理解任务上优于强基线,并取得了新的最先进结果,包括FUNSD(0.7895 -> 0.8420)、CORD(0.9493 -> 0.9601)、SROIE(0.9524 -> 0.9781)、Kleister-NDA(0.834 -> 0.852)、RVL-CDIP(0.9443 -> 0.9564)和DocVQA(0.7295 -> 0.8672)。预训练的LayoutLMv2模型可在以下网址公开获取:this https URL。
LayoutLMv2 依赖于 detectron2
、torchvision
和 tesseract
。运行以下命令来安装它们:
python -m pip install 'git+https://github.com/facebookresearch/detectron2.git'
python -m pip install torchvision tesseract
(如果您正在为LayoutLMv2开发,请注意,通过doctests还需要安装这些包。)
使用提示
- LayoutLMv1 和 LayoutLMv2 的主要区别在于后者在预训练期间加入了视觉嵌入(而 LayoutLMv1 仅在微调期间添加视觉嵌入)。
- LayoutLMv2 在自注意力层的注意力分数中增加了相对1D注意力偏差和空间2D注意力偏差。详情可以在论文的第5页找到。
- 关于如何在RVL-CDIP、FUNSD、DocVQA、CORD上使用LayoutLMv2模型的演示笔记本可以在这里找到。
- LayoutLMv2 使用 Facebook AI 的 Detectron2 包作为其视觉骨干。请参阅 此链接 获取安装说明。
- 除了
input_ids
,forward()还期望有2个额外的输入,即image
和bbox
。image
输入对应于文本标记出现的原始文档图像。模型期望每个文档图像的大小为224x224。这意味着如果你有一批文档图像,image
应该是一个形状为(batch_size, 3, 224, 224)的张量。这可以是torch.Tensor
或Detectron2.structures.ImageList
。你不需要对通道进行归一化,因为这是由模型完成的。需要注意的是,视觉骨干网络期望的是BGR通道而不是RGB,因为Detectron2中的所有模型都是使用BGR格式预训练的。bbox
输入是输入文本标记的边界框(即2D位置)。这与LayoutLMModel相同。这些可以使用外部OCR引擎(如Google的Tesseract(有一个Python包装器可用))获得。每个边界框应为(x0, y0, x1, y1)格式,其中(x0, y0)对应于边界框左上角的位置,(x1, y1)表示右下角的位置。需要注意的是,首先需要将边界框归一化到0-1000的范围内。要进行归一化,可以使用以下函数:
def normalize_bbox(bbox, width, height):
return [
int(1000 * (bbox[0] / width)),
int(1000 * (bbox[1] / height)),
int(1000 * (bbox[2] / width)),
int(1000 * (bbox[3] / height)),
]
这里,width
和 height
对应于标记出现的原始文档的宽度和高度(在调整图像大小之前)。例如,可以使用 Python 图像库 (PIL) 库来获取这些值,如下所示:
from PIL import Image
image = Image.open(
"name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)."
)
width, height = image.size
然而,这个模型包含了一个全新的LayoutLMv2Processor,它可以用来直接为模型准备数据(包括在后台应用OCR)。更多信息可以在下面的“使用”部分找到。
- 在内部,LayoutLMv2Model 会将
image
输入通过其视觉骨干网络发送,以获得一个较低分辨率的特征图,其形状等于 LayoutLMv2Config 的image_feature_pool_shape
属性。然后,该特征图被展平以获得一系列图像标记。由于特征图的大小默认为7x7,因此可以获得49个图像标记。这些标记随后与文本标记连接,并通过Transformer编码器发送。这意味着,如果您将文本标记填充到最大长度,模型的最后隐藏状态的长度将为512 + 49 = 561。更一般地说,最后隐藏状态的形状将为seq_length
+image_feature_pool_shape[0]
*config.image_feature_pool_shape[1]
。 - 当调用from_pretrained()时,会打印一个警告,其中包含一长串未初始化的参数名称。这不是问题,因为这些参数是批量归一化统计量,在自定义数据集上进行微调时会有值。
- 如果你想在分布式环境中训练模型,请确保在模型上调用
synchronize_batch_norm
,以便正确同步视觉骨干网络的批量归一化层。
此外,还有LayoutXLM,它是LayoutLMv2的多语言版本。更多信息可以在 LayoutXLM的文档页面找到。
资源
以下是官方Hugging Face和社区(由🌎表示)提供的资源列表,帮助您开始使用LayoutLMv2。如果您有兴趣提交资源以包含在此处,请随时打开一个Pull Request,我们将进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。
- 一个关于如何在RVL-CDIP数据集上微调LayoutLMv2进行文本分类的笔记本。
- 另请参阅:Text classification task guide
- 一个关于如何微调LayoutLMv2以在DocVQA数据集上进行问答的笔记本。
- 另请参阅:问答任务指南
- 另请参阅:文档问答任务指南
- 一个关于如何在CORD数据集上微调LayoutLMv2以进行标记分类的笔记本。
- 一个关于如何在FUNSD数据集上微调LayoutLMv2以进行令牌分类的笔记本。
- 另请参阅:Token分类任务指南
用法:LayoutLMv2Processor
为模型准备数据的最简单方法是使用LayoutLMv2Processor,它在内部结合了图像处理器(LayoutLMv2ImageProcessor)和分词器(LayoutLMv2Tokenizer或LayoutLMv2TokenizerFast)。图像处理器处理图像模态,而分词器处理文本模态。处理器将两者结合起来,这对于像LayoutLMv2这样的多模态模型来说是理想的。请注意,如果您只想处理一种模态,您仍然可以单独使用它们。
from transformers import LayoutLMv2ImageProcessor, LayoutLMv2TokenizerFast, LayoutLMv2Processor
image_processor = LayoutLMv2ImageProcessor() # apply_ocr is set to True by default
tokenizer = LayoutLMv2TokenizerFast.from_pretrained("microsoft/layoutlmv2-base-uncased")
processor = LayoutLMv2Processor(image_processor, tokenizer)
简而言之,可以将文档图像(可能还包括其他数据)提供给LayoutLMv2Processor,它将创建模型所需的输入。在内部,处理器首先使用LayoutLMv2ImageProcessor对图像进行OCR处理,以获取单词列表和归一化的边界框,并将图像调整为给定大小以获取image
输入。然后,单词和归一化的边界框被提供给LayoutLMv2Tokenizer或LayoutLMv2TokenizerFast,它们将这些转换为标记级别的input_ids
、attention_mask
、token_type_ids
、bbox
。可选地,可以向处理器提供单词标签,这些标签将被转换为标记级别的labels
。
LayoutLMv2Processor 使用了 PyTesseract,这是一个围绕 Google 的 Tesseract OCR 引擎的 Python 封装。请注意,您仍然可以使用自己选择的 OCR 引擎,并自行提供单词和归一化的框。这需要将 LayoutLMv2ImageProcessor 的 apply_ocr
设置为 False
。
总共有5个用例由处理器支持。下面,我们列出了所有这些用例。请注意,这些用例都适用于批处理和非批处理输入(我们以非批处理输入为例进行说明)。
用例1:文档图像分类(训练、推理)+ 令牌分类(推理),apply_ocr = True
这是最简单的情况,处理器(实际上是图像处理器)将对图像执行OCR以获取单词和归一化的边界框。
from transformers import LayoutLMv2Processor
from PIL import Image
processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased")
image = Image.open(
"name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)."
).convert("RGB")
encoding = processor(
image, return_tensors="pt"
) # you can also add all tokenizer parameters here such as padding, truncation
print(encoding.keys())
# dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'bbox', 'image'])
用例2:文档图像分类(训练、推理)+ 令牌分类(推理),apply_ocr=False
如果用户想要自己进行OCR,可以将图像处理器初始化为apply_ocr
设置为False
。在这种情况下,用户应自行提供单词和相应的(归一化)边界框给处理器。
from transformers import LayoutLMv2Processor
from PIL import Image
processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr")
image = Image.open(
"name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)."
).convert("RGB")
words = ["hello", "world"]
boxes = [[1, 2, 3, 4], [5, 6, 7, 8]] # make sure to normalize your bounding boxes
encoding = processor(image, words, boxes=boxes, return_tensors="pt")
print(encoding.keys())
# dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'bbox', 'image'])
用例3:令牌分类(训练),apply_ocr=False
对于标记分类任务(如FUNSD、CORD、SROIE、Kleister-NDA),还可以提供相应的单词标签以训练模型。处理器随后会将这些标签转换为标记级别的labels
。默认情况下,它只会标记单词的第一个子词,并将剩余的子词标记为-100,这是PyTorch的CrossEntropyLoss的ignore_index
。如果您希望单词的所有子词都被标记,可以将分词器初始化为only_label_first_subword
设置为False
。
from transformers import LayoutLMv2Processor
from PIL import Image
processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr")
image = Image.open(
"name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)."
).convert("RGB")
words = ["hello", "world"]
boxes = [[1, 2, 3, 4], [5, 6, 7, 8]] # make sure to normalize your bounding boxes
word_labels = [1, 2]
encoding = processor(image, words, boxes=boxes, word_labels=word_labels, return_tensors="pt")
print(encoding.keys())
# dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'bbox', 'labels', 'image'])
用例4:视觉问答(推理),apply_ocr=True
对于视觉问答任务(例如DocVQA),您可以向处理器提供一个问题。默认情况下,处理器将对图像应用OCR,并创建[CLS]问题标记[SEP]单词标记[SEP]。
from transformers import LayoutLMv2Processor
from PIL import Image
processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased")
image = Image.open(
"name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)."
).convert("RGB")
question = "What's his name?"
encoding = processor(image, question, return_tensors="pt")
print(encoding.keys())
# dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'bbox', 'image'])
用例5:视觉问答(推理),apply_ocr=False
对于视觉问答任务(例如DocVQA),您可以向处理器提供一个问题。如果您想自己执行OCR,您可以向处理器提供您自己的单词和(归一化的)边界框。
from transformers import LayoutLMv2Processor
from PIL import Image
processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr")
image = Image.open(
"name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)."
).convert("RGB")
question = "What's his name?"
words = ["hello", "world"]
boxes = [[1, 2, 3, 4], [5, 6, 7, 8]] # make sure to normalize your bounding boxes
encoding = processor(image, question, words, boxes=boxes, return_tensors="pt")
print(encoding.keys())
# dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'bbox', 'image'])
LayoutLMv2Config
类 transformers.LayoutLMv2Config
< source >( 词汇大小 = 30522 隐藏大小 = 768 隐藏层数 = 12 注意力头数 = 12 中间大小 = 3072 隐藏激活函数 = 'gelu' 隐藏层丢弃概率 = 0.1 注意力概率丢弃概率 = 0.1 最大位置嵌入 = 512 类型词汇大小 = 2 初始化范围 = 0.02 层归一化epsilon = 1e-12 填充标记ID = 0 最大2D位置嵌入 = 1024 最大相对位置 = 128 相对位置分箱数 = 32 快速QKV = True 最大相对2D位置 = 256 相对2D位置分箱数 = 64 同步批量归一化转换 = True 图像特征池形状 = [7, 7, 256] 坐标大小 = 128 形状大小 = 128 具有相对注意力偏置 = True 具有空间注意力偏置 = True 具有视觉段嵌入 = False Detectron2配置参数 = None **kwargs )
参数
- vocab_size (
int
, 可选, 默认为 30522) — LayoutLMv2 模型的词汇表大小。定义了可以通过调用 LayoutLMv2Model 或TFLayoutLMv2Model
时传递的inputs_ids
表示的不同标记的数量。 - hidden_size (
int
, optional, 默认为 768) — 编码器层和池化层的维度。 - num_hidden_layers (
int
, optional, defaults to 12) — Transformer编码器中的隐藏层数量。 - num_attention_heads (
int
, optional, defaults to 12) — Transformer编码器中每个注意力层的注意力头数量。 - intermediate_size (
int
, optional, 默认为 3072) — Transformer 编码器中“中间”(即前馈)层的维度。 - hidden_act (
str
或function
, 可选, 默认为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持"gelu"
、"relu"
、"selu"
和"gelu_new"
。 - hidden_dropout_prob (
float
, optional, 默认为 0.1) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
float
, optional, 默认为 0.1) — 注意力概率的丢弃比例。 - max_position_embeddings (
int
, optional, 默认为 512) — 此模型可能使用的最大序列长度。通常将其设置为较大的值以防万一(例如,512 或 1024 或 2048)。 - type_vocab_size (
int
, 可选, 默认为 2) — 调用 LayoutLMv2Model 或TFLayoutLMv2Model
时传递的token_type_ids
的词汇大小。 - initializer_range (
float
, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float
, 可选, 默认为 1e-12) — 层归一化层使用的 epsilon 值。 - max_2d_position_embeddings (
int
, 可选, 默认为 1024) — 2D位置嵌入可能使用的最大值。通常将其设置为较大的值以防万一(例如,1024)。 - max_rel_pos (
int
, optional, 默认为 128) — 在自注意力机制中使用的最大相对位置数。 - rel_pos_bins (
int
, optional, 默认为 32) — 用于自注意力机制中的相对位置分箱数量。 - fast_qkv (
bool
, 可选, 默认为True
) — 是否在自注意力层中使用单一矩阵来表示查询、键和值。 - max_rel_2d_pos (
int
, optional, defaults to 256) — 自注意力机制中相对2D位置的最大数量。 - rel_2d_pos_bins (
int
, optional, defaults to 64) — 自注意力机制中2D相对位置的分箱数量。 - image_feature_pool_shape (
List[int]
, optional, 默认为 [7, 7, 256]) — 平均池化特征图的形状。 - coordinate_size (
int
, optional, 默认为 128) — 坐标嵌入的维度。 - shape_size (
int
, optional, defaults to 128) — 宽度和高度嵌入的维度。 - has_relative_attention_bias (
bool
, optional, defaults toTrue
) — 是否在自注意力机制中使用相对注意力偏置。 - has_spatial_attention_bias (
bool
, 可选, 默认为True
) — 是否在自注意力机制中使用空间注意力偏置。 - has_visual_segment_embedding (
bool
, 可选, 默认为False
) — 是否添加视觉段嵌入。 - detectron2_config_args (
dict
, 可选) — 包含Detectron2视觉骨干配置参数的字典。有关默认值的详细信息,请参阅此文件。
这是用于存储LayoutLMv2Model配置的配置类。它用于根据指定的参数实例化一个LayoutLMv2模型,定义模型架构。使用默认值实例化配置将产生与LayoutLMv2 microsoft/layoutlmv2-base-uncased架构类似的配置。
配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。
示例:
>>> from transformers import LayoutLMv2Config, LayoutLMv2Model
>>> # Initializing a LayoutLMv2 microsoft/layoutlmv2-base-uncased style configuration
>>> configuration = LayoutLMv2Config()
>>> # Initializing a model (with random weights) from the microsoft/layoutlmv2-base-uncased style configuration
>>> model = LayoutLMv2Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
LayoutLMv2FeatureExtractor
预处理一张图像或一批图像。
LayoutLMv2ImageProcessor
类 transformers.LayoutLMv2ImageProcessor
< source >( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling =
参数
- do_resize (
bool
, 可选, 默认为True
) — 是否将图像的(高度,宽度)尺寸调整为(size["height"], size["width"])
。可以在preprocess
中被do_resize
覆盖。 - size (
Dict[str, int]
optional, defaults to{"height" -- 224, "width": 224}
): 调整后图像的大小。可以在preprocess
中通过size
覆盖。 - resample (
PILImageResampling
, 可选, 默认为Resampling.BILINEAR
) — 如果调整图像大小,则使用的重采样过滤器。可以在preprocess
方法中通过resample
参数覆盖。 - 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
覆盖。
构建一个LayoutLMv2图像处理器。
预处理
< source >( 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: Resampling = 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 =
参数
- 图片 (
ImageInput
) — 需要预处理的图片. - do_resize (
bool
, optional, defaults toself.do_resize
) — 是否调整图像大小. - size (
Dict[str, int]
, optional, defaults toself.size
) — 调整大小后输出图像的期望尺寸。 - resample (
PILImageResampling
, 可选, 默认为self.resample
) — 如果调整图像大小,则使用的重采样过滤器。这可以是PIL.Image
枚举的重采样过滤器之一。仅在do_resize
设置为True
时有效。 - apply_ocr (
bool
, optional, defaults toself.apply_ocr
) — 是否应用Tesseract OCR引擎来获取单词和归一化的边界框。 - ocr_lang (
str
, 可选, 默认为self.ocr_lang
) — Tesseract OCR 引擎使用的语言,由其 ISO 代码指定。默认情况下,使用英语。 - tesseract_config (
str
, 可选, 默认为self.tesseract_config
) — 任何额外的自定义配置标志,这些标志在调用 Tesseract 时会传递给config
参数。 - return_tensors (
str
或TensorType
, 可选) — 返回的张量类型。可以是以下之一:- 未设置:返回一个
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 (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。
预处理一张图像或一批图像。
LayoutLMv2Tokenizer
class transformers.LayoutLMv2Tokenizer
< source >( vocab_file do_lower_case = True do_basic_tokenize = True never_split = None unk_token = '[UNK]' sep_token = '[SEP]' pad_token = '[PAD]' cls_token = '[CLS]' mask_token = '[MASK]' cls_token_box = [0, 0, 0, 0] sep_token_box = [1000, 1000, 1000, 1000] pad_token_box = [0, 0, 0, 0] pad_token_label = -100 only_label_first_subword = True tokenize_chinese_chars = True strip_accents = None model_max_length: int = 512 additional_special_tokens: typing.Optional[typing.List[str]] = None **kwargs )
构建一个LayoutLMv2分词器。基于WordPiece。LayoutLMv2Tokenizer 可用于将单词、单词级别的边界框和可选的单词标签转换为标记级别的 input_ids
、attention_mask
、token_type_ids
、bbox
和可选的 labels
(用于标记分类)。
此分词器继承自PreTrainedTokenizer,其中包含了大部分主要方法。用户应参考此超类以获取有关这些方法的更多信息。
LayoutLMv2Tokenizer 运行端到端的分词:标点符号分割和词片。它还将单词级别的边界框转换为词片级别的边界框。
__call__
< source >( 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 ) → BatchEncoding
参数
- 文本 (
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 toTrue
) — 是否使用与模型相关的特殊标记对序列进行编码。 - padding (
bool
,str
or PaddingStrategy, optional, defaults toFalse
) — 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 argumentmax_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 toFalse
) — Activates and controls truncation. Accepts the following values:True
or'longest_first'
: Truncate to a maximum length specified with the argumentmax_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 argumentmax_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 argumentmax_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 (
str
或 TensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:'tf'
: 返回 TensorFlowtf.constant
对象。'pt'
: 返回 PyTorchtorch.Tensor
对象。'np'
: 返回 Numpynp.ndarray
对象。
- return_token_type_ids (
bool
, optional) — Whether to return token type IDs. If left to the default, will return the token type IDs according to the specific tokenizer’s default, defined by thereturn_outputs
attribute. - return_attention_mask (
bool
, optional) — Whether to return the attention mask. If left to the default, will return the attention mask according to the specific tokenizer’s default, defined by thereturn_outputs
attribute. - return_overflowing_tokens (
bool
, optional, defaults toFalse
) — 是否返回溢出的令牌序列。如果提供了一对输入ID序列(或一批对)并且使用了truncation_strategy = longest_first
或True
,则会引发错误而不是返回溢出的令牌。 - return_special_tokens_mask (
bool
, optional, defaults toFalse
) — 是否返回特殊令牌掩码信息。 - return_offsets_mapping (
bool
, optional, defaults toFalse
) — Whether or not to return(char_start, char_end)
for each token.这仅在继承自PreTrainedTokenizerFast的快速分词器上可用,如果使用Python的分词器,此方法将引发
NotImplementedError
。 - return_length (
bool
, optional, defaults toFalse
) — 是否返回编码输入的长度。 - verbose (
bool
, optional, defaults toTrue
) — 是否打印更多信息和警告。 - **kwargs — 传递给
self.tokenize()
方法
一个 BatchEncoding 包含以下字段:
-
input_ids — 要输入模型的标记ID列表。
-
bbox — 要输入模型的边界框列表。
-
token_type_ids — 要输入模型的标记类型ID列表(当
return_token_type_ids=True
或 如果 “token_type_ids” 在self.model_input_names
中)。 -
attention_mask — 指定模型应关注哪些标记的索引列表(当
return_attention_mask=True
或如果 “attention_mask” 在self.model_input_names
中)。 -
labels — 要输入模型的标签列表。(当指定了
word_labels
时)。 -
overflowing_tokens — 溢出标记序列列表(当指定了
max_length
并且return_overflowing_tokens=True
时)。 -
num_truncated_tokens — 截断的标记数量(当指定了
max_length
并且return_overflowing_tokens=True
时)。 -
special_tokens_mask — 0和1的列表,1表示添加的特殊标记,0表示 常规序列标记(当
add_special_tokens=True
并且return_special_tokens_mask=True
时)。 -
length — 输入的长度(当
return_length=True
时)。
主要方法,用于将一个或多个序列或一个或多个序列对进行分词,并为模型准备,这些序列带有单词级别的归一化边界框和可选的标签。
LayoutLMv2TokenizerFast
类 transformers.LayoutLMv2TokenizerFast
< source >( vocab_file = None tokenizer_file = None do_lower_case = True unk_token = '[UNK]' sep_token = '[SEP]' pad_token = '[PAD]' cls_token = '[CLS]' mask_token = '[MASK]' cls_token_box = [0, 0, 0, 0] sep_token_box = [1000, 1000, 1000, 1000] pad_token_box = [0, 0, 0, 0] pad_token_label = -100 only_label_first_subword = True tokenize_chinese_chars = True strip_accents = None **kwargs )
参数
- vocab_file (
str
) — 包含词汇表的文件。 - do_lower_case (
bool
, optional, defaults toTrue
) — 是否在分词时将输入转换为小写。 - unk_token (
str
, optional, defaults to"[UNK]"
) — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。 - sep_token (
str
, optional, defaults to"[SEP]"
) — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。 - pad_token (
str
, optional, defaults to"[PAD]"
) — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。 - cls_token (
str
, 可选, 默认为"[CLS]"
) — 用于序列分类的分类器标记(对整个序列进行分类而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。 - mask_token (
str
, optional, defaults to"[MASK]"
) — 用于屏蔽值的标记。这是在训练此模型时使用的标记,用于屏蔽语言建模。这是模型将尝试预测的标记。 - cls_token_box (
List[int]
, optional, defaults to[0, 0, 0, 0]
) — 用于特殊 [CLS] 标记的边界框。 - sep_token_box (
List[int]
, 可选, 默认为[1000, 1000, 1000, 1000]
) — 用于特殊 [SEP] 令牌的边界框。 - pad_token_box (
List[int]
, 可选, 默认为[0, 0, 0, 0]
) — 用于特殊 [PAD] 令牌的边界框。 - pad_token_label (
int
, 可选, 默认为 -100) — 用于填充标签的标签。默认为 -100,这是 PyTorch 的 CrossEntropyLoss 的ignore_index
。 - only_label_first_subword (
bool
, optional, defaults toTrue
) — 是否仅标记第一个子词,在提供单词标签的情况下。 - tokenize_chinese_chars (
bool
, 可选, 默认为True
) — 是否对中文字符进行分词。对于日语,可能需要停用此功能(参见 此问题)。 - strip_accents (
bool
, 可选) — 是否去除所有重音符号。如果未指定此选项,则将由lowercase
的值决定(如原始LayoutLMv2中所示)。
构建一个“快速”的LayoutLMv2分词器(基于HuggingFace的tokenizers库)。基于WordPiece。
这个分词器继承自PreTrainedTokenizerFast,其中包含了大部分主要方法。用户应参考这个超类以获取有关这些方法的更多信息。
__call__
< source >( 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 ) → BatchEncoding
参数
- 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 toTrue
) — 是否使用与模型相关的特殊标记对序列进行编码。 - padding (
bool
,str
or PaddingStrategy, optional, defaults toFalse
) — 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 argumentmax_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 toFalse
) — Activates and controls truncation. Accepts the following values:True
or'longest_first'
: Truncate to a maximum length specified with the argumentmax_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 argumentmax_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 argumentmax_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
, optional, defaults to 0) — 如果与max_length
一起设置为一个数字,当return_overflowing_tokens=True
时返回的溢出标记将包含来自截断序列末尾的一些标记,以提供截断序列和溢出序列之间的一些重叠。此参数的值定义了重叠标记的数量。 - pad_to_multiple_of (
int
, 可选) — 如果设置,将序列填充到提供的值的倍数。这对于在计算能力>= 7.5
(Volta)的NVIDIA硬件上启用Tensor Cores特别有用。 - return_tensors (
str
或 TensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:'tf'
: 返回 TensorFlowtf.constant
对象。'pt'
: 返回 PyTorchtorch.Tensor
对象。'np'
: 返回 Numpynp.ndarray
对象。
- return_token_type_ids (
bool
, optional) — Whether to return token type IDs. If left to the default, will return the token type IDs according to the specific tokenizer’s default, defined by thereturn_outputs
attribute. - return_attention_mask (
bool
, optional) — Whether to return the attention mask. If left to the default, will return the attention mask according to the specific tokenizer’s default, defined by thereturn_outputs
attribute. - return_overflowing_tokens (
bool
, 可选, 默认为False
) — 是否返回溢出的令牌序列。如果提供了一对输入ID序列(或一批对),并且使用了truncation_strategy = longest_first
或True
,则会引发错误,而不是返回溢出的令牌。 - return_special_tokens_mask (
bool
, optional, defaults toFalse
) — 是否返回特殊令牌掩码信息。 - return_offsets_mapping (
bool
, optional, defaults toFalse
) — Whether or not to return(char_start, char_end)
for each token.这仅在继承自PreTrainedTokenizerFast的快速分词器上可用,如果使用Python的分词器,此方法将引发
NotImplementedError
。 - return_length (
bool
, optional, defaults toFalse
) — 是否返回编码输入的长度。 - verbose (
bool
, 可选, 默认为True
) — 是否打印更多信息和警告。 - **kwargs — 传递给
self.tokenize()
方法
一个 BatchEncoding 包含以下字段:
-
input_ids — 要输入模型的标记ID列表。
-
bbox — 要输入模型的边界框列表。
-
token_type_ids — 要输入模型的标记类型ID列表(当
return_token_type_ids=True
或 如果 “token_type_ids” 在self.model_input_names
中时)。 -
attention_mask — 指定模型应关注哪些标记的索引列表(当
return_attention_mask=True
或如果 “attention_mask” 在self.model_input_names
中时)。 -
labels — 要输入模型的标签列表。(当指定了
word_labels
时)。 -
overflowing_tokens — 溢出标记序列列表(当指定了
max_length
并且return_overflowing_tokens=True
时)。 -
num_truncated_tokens — 被截断的标记数量(当指定了
max_length
并且return_overflowing_tokens=True
时)。 -
special_tokens_mask — 0和1的列表,1表示添加的特殊标记,0表示 常规序列标记(当
add_special_tokens=True
并且return_special_tokens_mask=True
时)。 -
length — 输入的长度(当
return_length=True
时)。
主要方法,用于将一个或多个序列或一个或多个序列对进行分词,并为模型准备,这些序列带有单词级别的归一化边界框和可选的标签。
LayoutLMv2Processor
类 transformers.LayoutLMv2Processor
< source >( image_processor = 无 tokenizer = 无 **kwargs )
参数
- image_processor (
LayoutLMv2ImageProcessor
, 可选) — LayoutLMv2ImageProcessor 的一个实例。图像处理器是一个必需的输入。 - tokenizer (
LayoutLMv2Tokenizer
或LayoutLMv2TokenizerFast
, 可选) — LayoutLMv2Tokenizer 或 LayoutLMv2TokenizerFast 的实例。tokenizer 是一个必需的输入。
构建一个LayoutLMv2处理器,它将LayoutLMv2图像处理器和LayoutLMv2分词器组合成一个单一的处理器。
LayoutLMv2Processor 提供了准备模型数据所需的所有功能。
首先使用LayoutLMv2ImageProcessor将文档图像调整为固定大小,并可以选择应用OCR来获取单词和归一化的边界框。然后将这些提供给LayoutLMv2Tokenizer或LayoutLMv2TokenizerFast,它们将单词和边界框转换为标记级别的input_ids
、attention_mask
、token_type_ids
、bbox
。可以选择提供整数word_labels
,这些将被转换为标记级别的labels
,用于标记分类任务(如FUNSD、CORD)。
__call__
< source >( 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] = False 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()。如果LayoutLMv2ImageProcessor初始化时apply_ocr
设置为True
,它会将获得的单词和边界框与附加参数一起传递给call()并返回输出,以及调整大小后的images
。如果LayoutLMv2ImageProcessor初始化时apply_ocr
设置为False
,它会将用户指定的单词(text
/text_pair
)和boxes
与附加参数一起传递给[__call__()](/docs/transformers/v4.47.1/en/model_doc/layoutlmv2#transformers.LayoutLMv2Tokenizer.__call__)并返回输出,以及调整大小后的images
。
请参考上述两个方法的文档字符串以获取更多信息。
LayoutLMv2Model
类 transformers.LayoutLMv2Model
< source >( config )
参数
- config (LayoutLMv2Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
裸的LayoutLMv2模型转换器输出原始隐藏状态,没有任何特定的头部。 该模型是PyTorch torch.nn.Module 的子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有事项。
前进
< source >( input_ids: typing.Optional[torch.LongTensor] = None bbox: typing.Optional[torch.LongTensor] = None image: typing.Optional[torch.FloatTensor] = 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 output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutput 或 tuple(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()。
- bbox (
torch.LongTensor
形状为((batch_size, sequence_length), 4)
, 可选) — 每个输入序列标记的边界框。选择范围在[0, config.max_2d_position_embeddings-1]
。每个边界框应为 (x0, y0, x1, y1) 格式的归一化版本,其中 (x0, y0) 对应于边界框左上角的位置,(x1, y1) 表示右下角的位置。 - image (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
ordetectron.structures.ImageList
whosetensors
is of shape(batch_size, num_channels, height, width)
) — 文档图像的批次。 - 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.
- 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]
. - head_mask (
torch.FloatTensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
返回
transformers.modeling_outputs.BaseModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(LayoutLMv2Config)和输入。
-
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 之后,用于计算自注意力头中的加权平均值。
LayoutLMv2Model 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoProcessor, LayoutLMv2Model, set_seed
>>> from PIL import Image
>>> import torch
>>> from datasets import load_dataset
>>> set_seed(0)
>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
>>> model = LayoutLMv2Model.from_pretrained("microsoft/layoutlmv2-base-uncased")
>>> dataset = load_dataset("hf-internal-testing/fixtures_docvqa", trust_remote_code=True)
>>> image_path = dataset["test"][0]["file"]
>>> image = Image.open(image_path).convert("RGB")
>>> encoding = processor(image, return_tensors="pt")
>>> outputs = model(**encoding)
>>> last_hidden_states = outputs.last_hidden_state
>>> last_hidden_states.shape
torch.Size([1, 342, 768])
LayoutLMv2ForSequenceClassification
类 transformers.LayoutLMv2ForSequenceClassification
< source >( config )
参数
- config (LayoutLMv2Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
LayoutLMv2 模型,顶部带有序列分类头(在 [CLS] 标记的最终隐藏状态、平均池化的初始视觉嵌入和平均池化的最终视觉嵌入的连接之上有一个线性层),例如用于文档图像分类任务,如 RVL-CDIP 数据集。
该模型是一个PyTorch torch.nn.Module 子类。将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.LongTensor] = None bbox: typing.Optional[torch.LongTensor] = None image: typing.Optional[torch.FloatTensor] = 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 ) → transformers.modeling_outputs.SequenceClassifierOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shapebatch_size, sequence_length
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- bbox (
torch.LongTensor
形状为(batch_size, sequence_length, 4)
, 可选) — 每个输入序列标记的边界框。选择范围在[0, config.max_2d_position_embeddings-1]
。每个边界框应为 (x0, y0, x1, y1) 格式的归一化版本,其中 (x0, y0) 对应于边界框左上角的位置,(x1, y1) 表示右下角的位置。 - image (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
ordetectron.structures.ImageList
whosetensors
is of shape(batch_size, num_channels, height, width)
) — 文档图像的批次。 - attention_mask (
torch.FloatTensor
of shapebatch_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 shapebatch_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.
- position_ids (
torch.LongTensor
of shapebatch_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]
. - 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而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算序列分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
范围内。如果config.num_labels == 1
,则计算回归损失(均方损失),如果config.num_labels > 1
,则计算分类损失(交叉熵)。
返回
transformers.modeling_outputs.SequenceClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.SequenceClassifierOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(LayoutLMv2Config)和输入。
-
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 后的注意力权重,用于计算自注意力头中的加权平均值。
LayoutLMv2ForSequenceClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoProcessor, LayoutLMv2ForSequenceClassification, set_seed
>>> from PIL import Image
>>> import torch
>>> from datasets import load_dataset
>>> set_seed(0)
>>> dataset = load_dataset("aharley/rvl_cdip", split="train", streaming=True, trust_remote_code=True)
>>> data = next(iter(dataset))
>>> image = data["image"].convert("RGB")
>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
>>> model = LayoutLMv2ForSequenceClassification.from_pretrained(
... "microsoft/layoutlmv2-base-uncased", num_labels=dataset.info.features["label"].num_classes
... )
>>> encoding = processor(image, return_tensors="pt")
>>> sequence_label = torch.tensor([data["label"]])
>>> outputs = model(**encoding, labels=sequence_label)
>>> loss, logits = outputs.loss, outputs.logits
>>> predicted_idx = logits.argmax(dim=-1).item()
>>> predicted_answer = dataset.info.features["label"].names[4]
>>> predicted_idx, predicted_answer # results are not good without further fine-tuning
(7, 'advertisement')
LayoutLMv2ForTokenClassification
类 transformers.LayoutLMv2ForTokenClassification
< source >( config )
参数
- config (LayoutLMv2Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
LayoutLMv2 模型,顶部带有标记分类头(在隐藏状态的文本部分之上的线性层),例如用于序列标注(信息提取)任务,如 FUNSD, SROIE, CORD 和 Kleister-NDA。
该模型是一个PyTorch torch.nn.Module 子类。将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.LongTensor] = None bbox: typing.Optional[torch.LongTensor] = None image: typing.Optional[torch.FloatTensor] = 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 ) → transformers.modeling_outputs.TokenClassifierOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shapebatch_size, sequence_length
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- bbox (
torch.LongTensor
形状为(batch_size, sequence_length, 4)
, 可选) — 每个输入序列标记的边界框。选择范围在[0, config.max_2d_position_embeddings-1]
。每个边界框应为 (x0, y0, x1, y1) 格式的归一化版本,其中 (x0, y0) 对应于边界框左上角的位置,(x1, y1) 表示右下角的位置。 - image (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
ordetectron.structures.ImageList
whosetensors
is of shape(batch_size, num_channels, height, width)
) — 文档图像的批次。 - attention_mask (
torch.FloatTensor
of shapebatch_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 shapebatch_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.
- position_ids (
torch.LongTensor
of shapebatch_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]
. - 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 而不是一个普通的元组。 - 标签 (
torch.LongTensor
形状为(batch_size, sequence_length)
, 可选) — 用于计算令牌分类损失的标签。索引应在[0, ..., config.num_labels - 1]
范围内。
返回
transformers.modeling_outputs.TokenClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.TokenClassifierOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(LayoutLMv2Config)和输入。
-
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 后的注意力权重,用于计算自注意力头中的加权平均值。
LayoutLMv2ForTokenClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoProcessor, LayoutLMv2ForTokenClassification, set_seed
>>> from PIL import Image
>>> from datasets import load_dataset
>>> set_seed(0)
>>> datasets = load_dataset("nielsr/funsd", split="test", trust_remote_code=True)
>>> labels = datasets.features["ner_tags"].feature.names
>>> id2label = {v: k for v, k in enumerate(labels)}
>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr")
>>> model = LayoutLMv2ForTokenClassification.from_pretrained(
... "microsoft/layoutlmv2-base-uncased", num_labels=len(labels)
... )
>>> data = datasets[0]
>>> image = Image.open(data["image_path"]).convert("RGB")
>>> words = data["words"]
>>> boxes = data["bboxes"] # make sure to normalize your bounding boxes
>>> word_labels = data["ner_tags"]
>>> encoding = processor(
... image,
... words,
... boxes=boxes,
... word_labels=word_labels,
... padding="max_length",
... truncation=True,
... return_tensors="pt",
... )
>>> outputs = model(**encoding)
>>> logits, loss = outputs.logits, outputs.loss
>>> predicted_token_class_ids = logits.argmax(-1)
>>> predicted_tokens_classes = [id2label[t.item()] for t in predicted_token_class_ids[0]]
>>> predicted_tokens_classes[:5] # results are not good without further fine-tuning
['I-HEADER', 'I-HEADER', 'I-QUESTION', 'I-HEADER', 'I-QUESTION']
LayoutLMv2ForQuestionAnswering
类 transformers.LayoutLMv2ForQuestionAnswering
< source >( config has_visual_segment_embedding = True )
参数
- config (LayoutLMv2Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
LayoutLMv2 模型,顶部带有用于抽取式问答任务的跨度分类头,例如
DocVQA(在隐藏状态输出的文本部分顶部有一个线性层,用于计算
span start logits
和 span end logits
)。
该模型是一个PyTorch torch.nn.Module 子类。将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.LongTensor] = None bbox: typing.Optional[torch.LongTensor] = None image: typing.Optional[torch.FloatTensor] = 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 ) → transformers.modeling_outputs.QuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shapebatch_size, sequence_length
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- bbox (
torch.LongTensor
形状为(batch_size, sequence_length, 4)
, 可选) — 每个输入序列标记的边界框。选择范围在[0, config.max_2d_position_embeddings-1]
。每个边界框应为 (x0, y0, x1, y1) 格式的归一化版本,其中 (x0, y0) 对应于边界框左上角的位置,(x1, y1) 表示右下角的位置。 - image (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
ordetectron.structures.ImageList
whosetensors
is of shape(batch_size, num_channels, height, width)
) — 文档图像的批次。 - attention_mask (
torch.FloatTensor
of shapebatch_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 shapebatch_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.
- position_ids (
torch.LongTensor
of shapebatch_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]
. - 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
, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的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.QuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.QuestionAnsweringModelOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(LayoutLMv2Config)和输入。
-
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 后的注意力权重,用于计算自注意力头中的加权平均值。
LayoutLMv2ForQuestionAnswering 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
在下面的示例中,我们给LayoutLMv2模型一张(包含文本的)图像,并向它提出一个问题。它将给出它认为的答案的预测(即从图像中解析出的文本中答案的范围)。
>>> from transformers import AutoProcessor, LayoutLMv2ForQuestionAnswering, set_seed
>>> import torch
>>> from PIL import Image
>>> from datasets import load_dataset
>>> set_seed(0)
>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
>>> model = LayoutLMv2ForQuestionAnswering.from_pretrained("microsoft/layoutlmv2-base-uncased")
>>> dataset = load_dataset("hf-internal-testing/fixtures_docvqa", trust_remote_code=True)
>>> image_path = dataset["test"][0]["file"]
>>> image = Image.open(image_path).convert("RGB")
>>> question = "When is coffee break?"
>>> encoding = processor(image, question, return_tensors="pt")
>>> outputs = model(**encoding)
>>> predicted_start_idx = outputs.start_logits.argmax(-1).item()
>>> predicted_end_idx = outputs.end_logits.argmax(-1).item()
>>> predicted_start_idx, predicted_end_idx
(30, 191)
>>> predicted_answer_tokens = encoding.input_ids.squeeze()[predicted_start_idx : predicted_end_idx + 1]
>>> predicted_answer = processor.tokenizer.decode(predicted_answer_tokens)
>>> predicted_answer # results are not good without further fine-tuning
'44 a. m. to 12 : 25 p. m. 12 : 25 to 12 : 58 p. m. 12 : 58 to 4 : 00 p. m. 2 : 00 to 5 : 00 p. m. coffee break coffee will be served for men and women in the lobby adjacent to exhibit area. please move into exhibit area. ( exhibits open ) trrf general session ( part | ) presiding : lee a. waller trrf vice president “ introductory remarks ” lee a. waller, trrf vice presi - dent individual interviews with trrf public board members and sci - entific advisory council mem - bers conducted by trrf treasurer philip g. kuehn to get answers which the public refrigerated warehousing industry is looking for. plus questions from'
>>> target_start_index = torch.tensor([7])
>>> target_end_index = torch.tensor([14])
>>> outputs = model(**encoding, start_positions=target_start_index, end_positions=target_end_index)
>>> predicted_answer_span_start = outputs.start_logits.argmax(-1).item()
>>> predicted_answer_span_end = outputs.end_logits.argmax(-1).item()
>>> predicted_answer_span_start, predicted_answer_span_end
(30, 191)