Transformers documentation

Donut

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

and get access to the augmented documentation experience

to get started

该模型于 2021-11-30 在 HF papers 上发表,并于 2022-08-12 贡献给 Hugging Face Transformers。

Donut

Donut(Document Understanding Transformer)是一种无需光学字符识别(OCR)引擎的视觉文档理解模型。与先使用 OCR 提取文本再进行处理的传统方法不同,Donut 采用基于 Transformer 的端到端架构,直接分析文档图像。这消除了与 OCR 相关的低效环节,使其更加准确,并能更好地适应多种语言和格式。

Donut 包含视觉编码器(Swin)和文本解码器(BART)。Swin 将文档图像转换为嵌入,BART 则将其处理为有意义的文本序列。

您可以在 Naver Clova Information Extraction 组织下找到所有原始的 Donut 检查点。

点击右侧边栏中的 Donut 模型,以查看更多将 Donut 应用于不同语言和视觉任务的示例。

以下示例演示了如何使用 Donut 结合 Pipeline 和 AutoModel 执行文档理解任务。

Pipeline
AutoModel
# pip install datasets
from transformers import pipeline


pipeline = pipeline(
    task="document-question-answering",
    model="naver-clova-ix/donut-base-finetuned-docvqa",
    device=0,
)
dataset = load_dataset("hf-internal-testing/example-documents", split="test")
image = dataset[0]["image"]

pipeline(image=image, question="What time is the coffee break?")

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

以下示例使用 torchao 仅将权重量化为 int4。

# pip install datasets torchao
from datasets import load_dataset

from transformers import AutoModelForImageTextToText, AutoProcessor, TorchAoConfig


quantization_config = TorchAoConfig("int4_weight_only", group_size=128)
processor = AutoProcessor.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa")
model = AutoModelForImageTextToText.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa", quantization_config=quantization_config, device_map="auto")

dataset = load_dataset("hf-internal-testing/example-documents", split="test")
image = dataset[0]["image"]
question = "What time is the coffee break?"
task_prompt = f"<s_docvqa><s_question>{question}</s_question><s_answer>"
inputs = processor(image, task_prompt, return_tensors="pt").to(model.device)

outputs = model.generate(
    input_ids=inputs.input_ids,
    pixel_values=inputs.pixel_values,
    max_length=512
)
answer = processor.decode(outputs[0], skip_special_tokens=True)
print(answer)

备注

  • 如下所示,使用 Donut 进行文档图像分类。

    import re
    from transformers import DonutProcessor, VisionEncoderDecoderModel
        from datasets import load_dataset
    import torch
    
    processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base-finetuned-rvlcdip")
    model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base-finetuned-rvlcdip", device_map="auto")
    
    model.to(model.device)  # doctest: +IGNORE_RESULT
    
    # load document image
    dataset = load_dataset("hf-internal-testing/example-documents", split="test")
    image = dataset[1]["image"]
    
    # prepare decoder inputs
    task_prompt = "<s_rvlcdip>"
    decoder_input_ids = processor.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt").to(model.device).input_ids
    
    pixel_values = processor(image, return_tensors="pt").to(model.device).pixel_values
    
    outputs = model.generate(
        pixel_values.to(model.device),
        decoder_input_ids=decoder_input_ids.to(model.device),
        max_length=model.decoder.config.max_position_embeddings,
        pad_token_id=processor.tokenizer.pad_token_id,
        eos_token_id=processor.tokenizer.eos_token_id,
        use_cache=True,
        bad_words_ids=[[processor.tokenizer.unk_token_id]],
        return_dict_in_generate=True,
    )
    
    sequence = processor.batch_decode(outputs.sequences)[0]
    sequence = sequence.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "")
    sequence = re.sub(r"<.*?>", "", sequence, count=1).strip()  # remove first task start token
    print(processor.token2json(sequence))
    {'class': 'advertisement'}
  • 如下所示,使用 Donut 进行文档解析。

    import re
        from datasets import load_dataset
    from transformers import DonutProcessor, VisionEncoderDecoderModel
    import torch
    
    processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base-finetuned-cord-v2")
    model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base-finetuned-cord-v2", device_map="auto")
    
    model.to(model.device)  # doctest: +IGNORE_RESULT
    
    # load document image
    dataset = load_dataset("hf-internal-testing/example-documents", split="test")
    image = dataset[2]["image"]
    
    # prepare decoder inputs
    task_prompt = "<s_cord-v2>"
    decoder_input_ids = processor.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt").to(model.device).input_ids
    
    pixel_values = processor(image, return_tensors="pt").to(model.device).pixel_values
    
    outputs = model.generate(
        pixel_values.to(model.device),
        decoder_input_ids=decoder_input_ids.to(model.device),
        max_length=model.decoder.config.max_position_embeddings,
        pad_token_id=processor.tokenizer.pad_token_id,
        eos_token_id=processor.tokenizer.eos_token_id,
        use_cache=True,
        bad_words_ids=[[processor.tokenizer.unk_token_id]],
        return_dict_in_generate=True,
    )
    
    sequence = processor.batch_decode(outputs.sequences)[0]
    sequence = sequence.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "")
    sequence = re.sub(r"<.*?>", "", sequence, count=1).strip()  # remove first task start token
    print(processor.token2json(sequence))
    {'menu': {'nm': 'CINNAMON SUGAR', 'unitprice': '17,000', 'cnt': '1 x', 'price': '17,000'}, 'sub_total': {'subtotal_price': '17,000'}, 'total': 
    {'total_price': '17,000', 'cashprice': '20,000', 'changeprice': '3,000'}}

DonutSwinConfig

class transformers.DonutSwinConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneimage_size: int | list[int] | tuple[int, int] = 224patch_size: int | list[int] | tuple[int, int] = 4num_channels: int = 3embed_dim: int = 96depths: list[int] | tuple[int, ...] = (2, 2, 6, 2)num_heads: list[int] | tuple[int, ...] = (3, 6, 12, 24)window_size: int = 7mlp_ratio: float = 4.0qkv_bias: bool = Truehidden_dropout_prob: float | int = 0.0attention_probs_dropout_prob: float | int = 0.0drop_path_rate: float | int = 0.1hidden_act: str = 'gelu'use_absolute_embeddings: bool = Falseinitializer_range: float = 0.02layer_norm_eps: float = 1e-05 )

参数

  • image_size (Union[int, list[int], tuple[int, int]],可选,默认为 224) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 4) — 每个 patch 的大小(分辨率)。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • embed_dim (int,可选,默认为 96) — 嵌入和隐藏状态的维度。
  • depths (Union[list[int], tuple[int, ...]],可选,默认为 (2, 2, 6, 2)) — Transformer 中每一层的深度。
  • num_heads (Union[list[int], tuple[int, ...]],可选,默认为 (3, 6, 12, 24)) — Transformer 解码器中每个注意力层的注意力头数量。
  • window_size (int,可选,默认为 7) — 窗口大小。
  • mlp_ratio (float,可选,默认为 4.0) — MLP 隐藏层维度与嵌入维度的比值。
  • qkv_bias (bool,可选,默认为 True) — 是否向查询、键和值添加偏置。
  • hidden_dropout_prob (Union[float, int],可选,默认为 0.0) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • drop_path_rate (Union[float, int],可选,默认为 0.1) — 用于 patch 融合的 drop path 比率。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • use_absolute_embeddings (bool,可选,默认为 False) — 是否使用绝对位置嵌入。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float,可选,默认为 1e-05) — 层归一化层所使用的 epsilon 值。

这是用于存储 Donut SwinModel 配置的类。它根据指定的参数实例化 Donut Swin 模型,并定义模型架构。使用默认值实例化配置,将得到与 naver-clova-ix/donut-base 类似的配置。

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

示例:

>>> from transformers import DonutSwinConfig, DonutSwinModel

>>> # Initializing a Donut naver-clova-ix/donut-base style configuration
>>> configuration = DonutSwinConfig()

>>> # Randomly initializing a model from the naver-clova-ix/donut-base style configuration
>>> model = DonutSwinModel(configuration)

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

DonutImageProcessor

class transformers.DonutImageProcessor

< >

( **kwargs: *<class 'transformers.models.donut.image_processing_donut.DonutImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None],kwargs,默认为 {'height' -- 2560, 'width': 1920}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.5, 0.5, 0.5]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.5, 0.5, 0.5]) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool,kwargs,可选,默认为 True) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • do_thumbnail (bool,kwargs,可选,默认为 self.do_thumbnail) — 是否使用 thumbnail 方法调整图像大小。
  • do_align_long_axis (bool, kwargs, 可选,默认为 self.do_align_long_axis) — 是否通过旋转 90 度,将图像的长轴与 size 的长轴对齐。

构建一个 image_processor_class 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.donut.image_processing_donut.DonutImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
  • default_to_square (bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时生效。
  • do_rescale (bool,kwargs,可选) — 是否对图像进行重新缩放。
  • rescale_factor (float, kwargs, 可选) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • do_thumbnail (bool,kwargs,可选,默认为 self.do_thumbnail) — 是否使用 thumbnail 方法调整图像大小。
  • do_align_long_axis (bool, kwargs, 可选,默认为 self.do_align_long_axis) — 是否通过旋转 90 度,将图像的长轴与 size 的长轴对齐。

返回值

~image_processing_base.BatchFeature

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

DonutImageProcessorPil

class transformers.DonutImageProcessorPil

< >

( **kwargs: *<class 'transformers.models.donut.image_processing_pil_donut.DonutImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None],kwargs,默认为 {'height' -- 2560, 'width': 1920}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.5, 0.5, 0.5]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.5, 0.5, 0.5]) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool,kwargs,可选,默认为 True) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • do_thumbnail (bool,kwargs,可选,默认为 self.do_thumbnail) — 是否使用 thumbnail 方法调整图像大小。
  • do_align_long_axis (bool, kwargs, 可选,默认为 self.do_align_long_axis) — 是否通过旋转 90 度,将图像的长轴与 size 的长轴对齐。

构建一个 image_processor_class 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.donut.image_processing_pil_donut.DonutImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
  • default_to_square (bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时生效。
  • do_rescale (bool,kwargs,可选) — 是否对图像进行重新缩放。
  • rescale_factor (float, kwargs, 可选) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • do_thumbnail (bool,kwargs,可选,默认为 self.do_thumbnail) — 是否使用 thumbnail 方法调整图像大小。
  • do_align_long_axis (bool, kwargs, 可选,默认为 self.do_align_long_axis) — 是否通过旋转 90 度,将图像的长轴与 size 的长轴对齐。

返回值

~image_processing_base.BatchFeature

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

DonutProcessor

class transformers.DonutProcessor

< >

( image_processor = Nonetokenizer = None**kwargs )

参数

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

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

DonutProcessor 提供了 image_processor_class 和 tokenizer_class 的所有功能。有关更多信息,请参阅 ~image_processor_class 和 ~tokenizer_class。

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] | None = None**kwargs: *<class 'transformers.models.donut.processing_donut.DonutProcessorKwargs'> )

参数

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

from_pretrained

< >

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

参数

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

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

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

save_pretrained

< >

( save_directorypush_to_hub: bool = False**kwargs )

参数

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

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

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

batch_decode

< >

( *args**kwargs )

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

decode

< >

( *args**kwargs )

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

DonutSwinModel

class transformers.DonutSwinModel

< >

( config: DonutSwinConfigadd_pooling_layer = Trueuse_mask_token = False )

参数

  • config (DonutSwinConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
  • add_pooling_layer (bool,可选,默认为 True) — 是否添加池化层
  • use_mask_token (bool,可选,默认为 False) — 是否使用掩码标记进行掩码图像建模。

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

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

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

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Nonebool_masked_pos: typing.Optional[torch.BoolTensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Noneinterpolate_pos_encoding: bool = Falsereturn_dict: bool | None = None**kwargs ) → DonutSwinModelOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 DonutImageProcessor 获取像素值。有关详细信息,请参阅 DonutImageProcessor.call()(processor_class 使用 DonutImageProcessor 处理图像)。
  • bool_masked_pos(形状为 (batch_size, num_patches) 的 torch.BoolTensor)— 布尔掩码位置。指示哪些 patch 被掩码(1),哪些未被掩码(0)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

DonutSwinModelOutput 或 tuple(torch.Tensor)

DonutSwinModelOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(DonutSwinConfig)和输入而定的各种元素。

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

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

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

  • pooler_output(形状为 (batch_size, hidden_size) 的 torch.Tensor,可选,在传入 add_pooling_layer=True 时返回) — 最后一层隐藏状态的均值池化。

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

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

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

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

  • reshaped_hidden_states (tuple(torch.Tensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(包含嵌入层输出以及每个阶段的输出各一个),形状为 (batch_size, hidden_size, height, width)。

    模型在每一层输出处的隐藏状态,以及重塑为包含空间维度的初始嵌入输出。

DonutSwinForImageClassification

class transformers.DonutSwinForImageClassification

< >

( config: DonutSwinConfig )

参数

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

DonutSwin 模型,顶部带有图像分类头(在 [CLS] token 的最终隐藏状态之上添加一个线性层),例如用于 ImageNet。

请注意,通过在模型的前向传播中将 interpolate_pos_encoding 设置为 True,可以对 DonutSwin 进行微调,使其能够处理比训练时更高分辨率的图像。这会将预训练的位置嵌入插值到更高分辨率。

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

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

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Noneinterpolate_pos_encoding: bool = Falsereturn_dict: bool | None = None**kwargs ) → DonutSwinImageClassifierOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 DonutImageProcessor 获取像素值。有关详细信息,请参阅 DonutImageProcessor.call()(processor_class 使用 DonutImageProcessor 处理图像)。
  • labels(形状为 (batch_size,) 的 torch.LongTensor,可选)— 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失);如果 config.num_labels > 1,则计算分类损失(交叉熵)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

DonutSwinImageClassifierOutput 或 tuple(torch.Tensor)

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

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

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

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

  • logits(形状为 (batch_size, config.num_labels) 的 torch.Tensor)— 分类(或当 config.num_labels==1 时为回归)得分(SoftMax 之前)。

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

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

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

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

  • reshaped_hidden_states (tuple(torch.Tensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(包含嵌入层输出以及每个阶段的输出各一个),形状为 (batch_size, hidden_size, height, width)。

    模型在每一层输出处的隐藏状态,以及重塑为包含空间维度的初始嵌入输出。

示例:

>>> from transformers import AutoImageProcessor, DonutSwinForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("naver-clova-ix/donut-base")
>>> model = DonutSwinForImageClassification.from_pretrained("naver-clova-ix/donut-base")

>>> inputs = image_processor(image, return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
...
Update on GitHub