Transformers documentation

PP-FormulaNet

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

and get access to the augmented documentation experience

to get started

该模型于 2026-04-30 贡献至 Hugging Face Transformers。

PP-FormulaNet

概述

PP-FormulaNet-L 和 PP-FormulaNet_plus-L 是一系列专为表格结构识别设计的轻量级模型,专注于准确识别文档和自然场景中的表格结构。有关 SLANet 系列模型的更多详细信息,请参阅官方文档。

用法

单输入推理

以下示例演示了如何使用 AutoModel 通过 PP-FormulaNet_plus-L 检测文本。

AutoModel
from io import BytesIO

from huggingface_hub.utils import httpx
from PIL import Image
from transformers import AutoProcessor, AutoModelForImageTextToText

model_path = "PaddlePaddle/PP-FormulaNet_plus-L_safetensors" # or "PaddlePaddle/PP-FormulaNet-L_safetensors"
model = AutoModelForImageTextToText.from_pretrained(model_path, device_map="auto")
processor = AutoProcessor.from_pretrained(model_path)

image_url = "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/paddle_general_formula_rec_001.png"
image = Image.open(BytesIO(httpx.get(image_url).content)).convert("RGB")
inputs = processor(images=image, return_tensors="pt").to(model.device)
outputs = model(**inputs)
result = processor.post_process(outputs)
print(result)

PPFormulaNetConfig

class transformers.PPFormulaNetConfig

< >

( 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 = 0id2label: 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 = Noneis_encoder_decoder: bool = Truetext_config: dict | transformers.models.pp_formulanet.configuration_pp_formulanet.PPFormulaNetTextConfig | None = Nonevision_config: dict | transformers.models.pp_formulanet.configuration_pp_formulanet.PPFormulaNetVisionConfig | None = None )

参数

  • is_encoder_decoder (bool,可选,默认为 True) — 指示该模型是否用作编码器/解码器。
  • text_config (Union[dict, ~models.pp_formulanet.configuration_pp_formulanet.PPFormulaNetTextConfig], 可选) — 文本骨干网络的配置对象或字典。
  • vision_config (Union[dict, ~models.pp_formulanet.configuration_pp_formulanet.PPFormulaNetVisionConfig], 可选) — 视觉骨干网络的配置对象或字典。

这是用于存储 Pp FormulanetModel 配置的类。它根据指定的参数实例化 Pp Formulanet 模型,并定义模型架构。使用默认值实例化配置,将得到与 PaddlePaddle/PP-FormulaNet_plus-L_safetensors 类似的配置。

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

PPFormulaNetForConditionalGeneration

class transformers.PPFormulaNetForConditionalGeneration

< >

( config: PPFormulaNetConfig )

参数

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

用于基于其他模态(例如图像-文本到文本生成)进行 token 生成的 Pp Formulanet 模型。

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

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

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Noneinput_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.LongTensor] = Noneencoder_outputs: list[torch.Tensor] | None = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonedecoder_inputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Seq2SeqLMOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 PPFormulaNetImageProcessor 获取像素值。有关详细信息,请参阅 PPFormulaNetImageProcessor.call()(PPFormulaNetProcessor 使用 PPFormulaNetImageProcessor 处理图像)。
  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

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

    什么是输入 ID?

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

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor 形状为 (batch_size, target_sequence_length), ,可选) — 解码器输入序列中各 token 在词汇表中的索引。可通过 AutoTokenizer 获取索引。详情请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。什么是解码器输入 ID?

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

    什么是解码器输入 ID?

  • decoder_attention_mask(形状为 (batch_size, target_sequence_length) 的 torch.LongTensor,可选) — 用于避免对特定 token 索引执行注意力的掩码。默认情况下,会使用因果掩码,以确保模型只能查看之前的输入来预测未来。
  • encoder_outputs (list[torch.Tensor],可选) — 元组由 (last_hidden_state,可选:hidden_states,可选:attentions) last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size),可选),是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力。
  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

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

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

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

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • decoder_inputs_embeds (torch.Tensor 形状为 (batch_size, target_sequence_length, hidden_size), ,可选) — 可选地,除了传递 decoder_input_ids ,还可以选择直接传递嵌入表示。如果使用了 past_key_values ,则只需输入最后一个 decoder_inputs_embeds (参见 past_key_values). 。这在希望比模型内部的嵌入查找矩阵更精细地控制如何将 decoder_input_ids 索引转换为对应向量时非常有用。

    如果 decoder_input_ids 和 decoder_inputs_embeds 均未设置,decoder_inputs_embeds 将取 inputs_embeds 的值。

  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • logits_to_keep (Union[int, torch.Tensor], 可选,默认为 0) — 如果为 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为 torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。

返回值

Seq2SeqLMOutput 或 tuple(torch.Tensor)

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

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

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

  • loss(形状为 (1,) 的 torch.Tensor,可选,在提供 labels 时返回)— 语言建模损失。

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

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

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

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

    解码器在每一层输出处的隐藏状态,以及初始嵌入输出。

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

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

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

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

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

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

    编码器在每一层输出处的隐藏状态,以及初始嵌入输出。

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

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

示例:

>>> from io import BytesIO

>>> from huggingface_hub.utils import httpx
>>> from PIL import Image
>>> from transformers import AutoProcessor, PPFormulaNetForConditionalGeneration

>>> model_path = "PaddlePaddle/PP-FormulaNet_plus-L_safetensors" # or "PaddlePaddle/PP-FormulaNet-L_safetensors"
>>> model = PPFormulaNetForConditionalGeneration.from_pretrained(model_path, device_map="auto")
>>> processor = AutoProcessor.from_pretrained(model_path)

>>> image_url = "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/paddle_general_formula_rec_001.png"
>>> image = Image.open(BytesIO(httpx.get(image_url).content)).convert("RGB")
>>> inputs = processor(images=image, return_tensors="pt").to(model.device)
>>> outputs = model(**inputs)
>>> result = processor.post_process(outputs)
>>> print(result)
['\\zeta_{0}(\\nu)=-\\frac{\\nu\\varrho^{-2\\nu}}{\\pi}\\int_{\\mu}^{\\infty}d\\omega\\int_{C_{+}}d z\\frac{2z^{2}}{(z^{2}+\\omega^{2})^{\\nu+1}}\\breve{\\Psi}(\\omega;z)e^{i\\epsilon z}\\quad,']

PPFormulaNetTextModel

class transformers.PPFormulaNetTextModel

< >

( config: PPFormulaNetConfig )

参数

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

裸 Pp Formulanet Text Model,输出原始隐藏状态,顶部未添加任何特定头。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneencoder_hidden_states: typing.Optional[torch.Tensor] = Noneencoder_attention_mask: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> )

参数

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

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

    什么是输入 ID?

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

    什么是注意力掩码?

  • encoder_hidden_states (torch.Tensor,形状为 (batch_size, encoder_sequence_length, hidden_size),可选) — 编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力机制。
  • encoder_attention_mask (torch.LongTensor 形状为 (batch_size, encoder_sequence_length), 可选) — 用于避免对 encoder input_ids 中填充 token 的索引执行交叉注意力的掩码。掩码值在 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

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

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

    如果使用了 past_key_values,用户可以选择仅输入最后一个 decoder_input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, 1),而不是输入所有形状为 (batch_size, sequence_length) 的 decoder_input_ids。

  • inputs_embeds (torch.Tensor,形状为 (batch_size, sequence_length, hidden_size),可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。 如果您希望对 input_ids 索引如何转换为对应的向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。

PPFormulaNetVisionModel

class transformers.PPFormulaNetVisionModel

< >

( config: PPFormulaNetVisionConfig )

PPFormulaNetModel

class transformers.PPFormulaNetModel

< >

( config: PPFormulaNetConfig )

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Noneinput_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.LongTensor] = Nonedecoder_inputs_embeds: typing.Optional[torch.Tensor] = Noneencoder_outputs: list[torch.Tensor] | None = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs ) → Seq2SeqModelOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 PPFormulaNetImageProcessor 获取像素值。有关详细信息,请参阅 PPFormulaNetImageProcessor.call()(PPFormulaNetProcessor 使用 PPFormulaNetImageProcessor 处理图像)。
  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

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

    什么是输入 ID?

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

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor 形状为 (batch_size, target_sequence_length), ,可选) — 解码器输入序列中各 token 在词汇表中的索引。可通过 AutoTokenizer 获取索引。详情请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。什么是解码器输入 ID?

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

    什么是解码器输入 ID?

  • decoder_attention_mask(形状为 (batch_size, target_sequence_length) 的 torch.LongTensor,可选) — 用于避免对特定 token 索引执行注意力的掩码。默认情况下,会使用因果掩码,以确保模型只能查看之前的输入来预测未来。
  • decoder_inputs_embeds (torch.Tensor 形状为 (batch_size, target_sequence_length, hidden_size), ,可选) — 可选地,除了传递 decoder_input_ids ,还可以选择直接传递嵌入表示。如果使用了 past_key_values ,则只需输入最后一个 decoder_inputs_embeds (参见 past_key_values). 。这在希望比模型内部的嵌入查找矩阵更精细地控制如何将 decoder_input_ids 索引转换为对应向量时非常有用。

    如果 decoder_input_ids 和 decoder_inputs_embeds 均未设置,decoder_inputs_embeds 将取 inputs_embeds 的值。

  • encoder_outputs (list[torch.Tensor],可选) — 元组由 (last_hidden_state,可选:hidden_states,可选:attentions) last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size),可选),是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力。
  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

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

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

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

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。

返回值

Seq2SeqModelOutput 或 tuple(torch.Tensor)

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

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

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

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

    如果使用了 past_key_values,则仅输出形状为 (batch_size, 1, hidden_size) 的序列的最后一个隐藏状态。

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

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

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

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

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

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

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

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

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

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

    编码器每层输出处的隐藏状态,以及可选的初始嵌入输出。

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

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

PPFormulaNetTextConfig

class transformers.PPFormulaNetTextConfig

< >

( 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 = 0id2label: 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 = Noneis_encoder_decoder: bool = Truevocab_size: int = 50000max_position_embeddings: int = 2560encoder_layers: int = 12encoder_attention_heads: int = 16decoder_layers: int = 8decoder_ffn_dim: int = 2048decoder_attention_heads: int = 16decoder_layerdrop: float | int = 0.0use_cache: bool = Trueactivation_function: str = 'gelu'd_model: int = 512dropout: float | int = 0.1attention_dropout: float | int = 0.0activation_dropout: float | int = 0.0init_std: float = 0.02scale_embedding: bool = Truepad_token_id: int | None = 1bos_token_id: int | None = 0eos_token_id: int | list[int] | None = 2decoder_start_token_id: int | None = 2forced_eos_token_id: int | list[int] | None = 2tie_word_embeddings: bool = False )

参数

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

这是用于存储 Pp FormulanetModel 配置的类。它根据指定的参数实例化 Pp Formulanet 模型,并定义模型架构。使用默认值实例化配置,将得到与 PaddlePaddle/PP-FormulaNet_plus-L_safetensors 类似的配置。

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

示例:

>>> from transformers import PPFormulaNetTextConfig, PPFormulaNetTextModel

>>> # Initializing a PP_FORMULANET facebook/pp_formulanet-large-cc25 style configuration
>>> configuration = PPFormulaNetTextConfig()

>>> # Initializing a model (with random weights) from the facebook/pp_formulanet-large-cc25 style configuration
>>> model = PPFormulaNetTextModel(configuration)

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

PPFormulaNetVisionConfig

class transformers.PPFormulaNetVisionConfig

< >

( 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 = Nonehidden_size: int = 768output_channels: int = 256num_hidden_layers: int = 12num_attention_heads: int = 12num_channels: int = 3image_size: int = 512patch_size: int | list[int] | tuple[int, int] = 16hidden_act: str = 'gelu'layer_norm_eps: float = 1e-06attention_dropout: float | int = 0.0initializer_range: float = 1e-10qkv_bias: bool = Trueuse_abs_pos: bool = Trueuse_rel_pos: bool = Truewindow_size: int = 14global_attn_indexes: list[int] | tuple[int, ...] = (2, 5, 8, 11)mlp_dim: int = 3072post_conv_in_channels: int = 256post_conv_out_channels: int = 1024post_conv_mid_channels: int = 512decoder_hidden_size: int = 512 )

参数

  • hidden_size (int,可选,默认为 768) — 隐藏表示的维度。
  • output_channels (int, 可选,默认为 256) — Patch Encoder 中输出通道的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 12) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • image_size (int,可选,默认为 512) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 16) — 每个 patch 的大小(分辨率)。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • layer_norm_eps (float,可选,默认为 1e-06) — 层归一化层所使用的 epsilon 值。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float,可选,默认为 1e-10) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • qkv_bias (bool,可选,默认为 True) — 是否向查询、键和值添加偏置。
  • use_abs_pos (bool,可选,默认为 True) — 是否使用绝对位置嵌入。
  • use_rel_pos (bool,可选,默认为 True) — 是否在使用自注意力层时使用相对位置偏置。
  • window_size (int,可选,默认为 14) — 相对位置的窗口大小。
  • global_attn_indexes (list[int],可选,默认为 [2, 5, 8, 11]) — 全局注意力层的索引。
  • mlp_dim (int,可选,默认值为 3072) — Transformer 编码器中 MLP 层的维度。
  • post_conv_in_channels (int,可选,默认为 256) — 编码器后卷积层的输入通道数。
  • post_conv_out_channels (int,可选,默认为 1024) — 编码器后卷积层的输出通道数。
  • post_conv_mid_channels (int,可选,默认为 512) — 编码器后卷积层的中间通道数。
  • decoder_hidden_size (int, 可选,默认为 512) — 编码器特征所投影到的解码器的隐藏层大小。

这是用于存储 Pp FormulanetModel 配置的类。它根据指定的参数实例化 Pp Formulanet 模型,并定义模型架构。使用默认值实例化配置,将得到与 PaddlePaddle/PP-FormulaNet_plus-L_safetensors 类似的配置。

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

PPFormulaNetImageProcessor

class transformers.PPFormulaNetImageProcessor

< >

( **kwargs: *<class 'transformers.models.pp_formulanet.image_processing_pp_formulanet.PPFormulaNetImageProcessorKwargs'> )

参数

  • 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' -- 768, 'width': 768}): 描述输入到模型的最大尺寸。
  • 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.7931, 0.7931, 0.7931]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.1738, 0.1738, 0.1738]) — 用于归一化的图像标准差。仅当 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_crop_margin (bool,kwargs,可选,默认为 self.do_crop_margin) — 是否裁剪图像边缘。
  • do_thumbnail (bool,kwargs,可选,默认为 self.do_thumbnail) — 是否使用 thumbnail 方法调整图像大小。
  • do_align_long_axis (bool, kwargs, 可选,默认为 self.do_align_long_axis) — 是否通过旋转 90 度,将图像的长轴与 size 的长轴对齐。

构建一个 PPFormulaNetImageProcessor 图像处理器。

align_long_axis

< >

( image: torch.Tensorsize: SizeDict ) → torch.Tensor

参数

  • image (torch.Tensor) — 要执行对齐操作的图像。
  • size (SizeDict) — 用于对齐长轴的尺寸。

返回值

torch.Tensor

对齐后的图像。

将图像的长轴对齐到指定尺寸的最长轴。

crop_margin

< >

( image: torch.Tensorgray_threshold: int = 200 )

参数

  • image (torch.Tensor) — 要裁剪的图像。
  • gray_threshold (int,可选,默认为 200) — 低于此值的像素被视为灰色。

裁剪图像的边距。灰色像素被视为边距(即值低于阈值的像素)。

pad_images

< >

( image: torch.Tensorsize: SizeDict )

参数

  • image (torch.tensor) — 要填充的图像。
  • size (SizeDict) — 用于填充图像的目标尺寸。

在顶部、底部、左侧和右侧将一批图像填充到指定大小。

预处理

< >

( 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.pp_formulanet.image_processing_pp_formulanet.PPFormulaNetImageProcessorKwargs'> ) → ~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_crop_margin (bool,kwargs,可选,默认为 self.do_crop_margin) — 是否裁剪图像边缘。
  • 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 张量中的整数列表进行转换。

python_bounding_rect

< >

( coordinates )

这是 cv2 中 BoundingRect 函数的重新实现,功能与之等效。

python_find_non_zero

< >

( image: torch.Tensor )

这是 findNonZero 函数的重新实现,其功能与 cv2 中的等效函数相同。

调整大小

< >

( image: torch.Tensorsize: SizeDictresample: PILImageResampling | tvF.InterpolationMode | int | None = Noneantialias: bool = True**kwargs ) → torch.Tensor

参数

  • image (torch.Tensor) — 要调整大小的图像。
  • size (SizeDict) — 输出图像的尺寸。
  • resample (PILImageResampling | tvF.InterpolationMode | int, 可选) — 调整图像大小时使用的重采样滤波器。

返回值

torch.Tensor

调整大小后的图像。

将图像调整为 (size.height, size.width)。

缩略图

< >

( image: torch.Tensorsize: SizeDict )

参数

  • image (torch.tensor) — 要调整大小的图像。
  • size (SizeDict) — 用于调整图像大小的尺寸。

调整图像大小以生成缩略图。图像会被调整大小,使得其任何维度都不大于指定尺寸中对应的维度。

PPFormulaNetProcessor

class transformers.PPFormulaNetProcessor

< >

( image_processortokenizer )

参数

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

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

PPFormulaNetProcessor 提供了 PPFormulaNetImageProcessor 和 NougatTokenizer 的所有功能。有关更多信息,请参阅 ~PPFormulaNetImageProcessor 和 ~NougatTokenizer。

normalize

< >

( text: str )

通过删除多余的空格来规范化字符串。

post_process

< >

( generated_outputsskip_special_tokens = True**kwargs ) → list[str]

参数

  • generated_outputs(torch.Tensor 或 np.ndarray)— 模型 generate 函数的输出。预期输出是一个形状为 (batch_size, sequence_length) 或 (sequence_length,) 的张量。
  • skip_special_tokens(bool,可选,默认为 True)— 是否从输出中移除特殊标记。该参数会传递给分词器的 batch_decode 方法。
  • **kwargs — 传递给分词器 batch_decode method 的额外参数。

返回值

list[str]

解码后的文本。

对模型的输出进行后处理以解码文本。

post_process_generation

< >

( text: str ) → str

参数

  • text (str) — 要后处理的字符串。

返回值

str

经过后处理的字符串。

通过修复文本并对其进行规范化处理,对字符串进行后处理。

Update on GitHub