Transformers documentation

ModernVBert

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

该模型于 2025-10-01 在 HF papers 上发布,并于 2026-02-23 贡献至 Hugging Face Transformers。

ModernVBert

FlashAttention SDPA

概述

ModernVBert 是一种视觉-语言编码器,它将 ModernBert 与 SigLIP 视觉编码器相结合。它针对视觉文档理解和检索任务进行了优化。

该模型在 ModernVBERT: Towards Smaller Visual Document Retrievers 中提出。

Python
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import AutoModelForMaskedLM, AutoProcessor


processor = AutoProcessor.from_pretrained("./mvb")
model = AutoModelForMaskedLM.from_pretrained("./mvb", device_map="auto")

image = Image.open(hf_hub_download("HuggingFaceTB/SmolVLM", "example_images/rococo.jpg", repo_type="space"))
text = "This [MASK] is on the wall."

# Create input messages
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": text}
        ]
    },
]

# Prepare inputs
prompt = processor.apply_chat_template(messages)
inputs = processor(text=prompt, images=[image], return_tensors="pt").to(model.device)

# Inference
with torch.no_grad():
  outputs = model(**inputs)

# To get predictions for the mask:
masked_index = inputs["input_ids"][0].tolist().index(processor.tokenizer.mask_token_id)
predicted_token_id = outputs.logits[0, masked_index].argmax(axis=-1)
predicted_token = processor.tokenizer.decode(predicted_token_id)
print("Predicted token:", predicted_token)  # Predicted token: painting

ModernVBertConfig

class transformers.ModernVBertConfig

< >

( 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 = Nonetext_config: transformers.configuration_utils.PreTrainedConfig | dict | None = Nonevision_config: transformers.configuration_utils.PreTrainedConfig | dict | None = Noneimage_token_id: int = 50407pixel_shuffle_factor: int = 4initializer_range: float = 0.02initializer_cutoff_factor: float = 2.0classifier_pooling: typing.Literal['cls', 'mean'] = 'cls'classifier_dropout: float | int = 0.0classifier_bias: bool = Falsetie_word_embeddings: bool = False )

参数

  • text_config (Union[~configuration_utils.PreTrainedConfig, dict],可选) — 文本骨干网络的配置对象或字典。
  • vision_config (Union[~configuration_utils.PreTrainedConfig, dict], 可选) — 视觉骨干网络的配置对象或字典。
  • image_token_id (int,可选,默认为 50407) — 用作输入图像占位符的图像 token 索引。
  • pixel_shuffle_factor (int | None,可选,默认为 4) — 视觉头中任何像素重排 / 上采样操作所使用的缩放因子。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • initializer_cutoff_factor (float | None,可选,默认值为 2.0) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的截断因子。
  • classifier_pooling (Literal["cls", "mean"],可选,默认为 "cls") — 用于分类任务的池化策略。
  • classifier_dropout (Union[float, int],可选,默认为 0.0) — 分类器的 dropout 比率。
  • classifier_bias (bool | None,可选,默认为 False) — 是否向分类头添加偏置项
  • tie_word_embeddings (bool,可选,默认为 False) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。

这是用于存储 ModernVBertModel 配置的类。它根据指定的参数实例化 Modernvbert 模型,并定义模型架构。使用默认值实例化配置将得到与 ModernVBERT/modernvbert 类似的配置。

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

示例:

>>> from transformers import ModernVBertConfig

>>> # Initializing configuration
>>> configuration = ModernVBertConfig()

>>> # Initializing a model from the configuration (model class is implemented in
>>> # `modernvbert.modeling_modernvbert`)

>>> from transformers import ModernVBertModel
>>> model = ModernVBertModel(configuration)

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

ModernVBertModel

class transformers.ModernVBertModel

< >

( config: ModernVBertConfig )

参数

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

ModernVBertModel 是一个结合了视觉编码器(SigLIP)和文本编码器(ModernBert)的模型。

ModernVBert 是视觉检索器 ColModernVBert 的基础模型,并在以下论文中提出:ModernVBERT: Towards Smaller Visual Document Retrievers。

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

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

forward

< >

( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_attention_mask: typing.Optional[torch.BoolTensor] = Noneimage_hidden_states: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ModernVBertBaseModelOutput or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

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

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 image_processor_class 获取像素值。有关详细信息,请参阅 image_processor_class.__call__(Idefics3Processor 使用 image_processor_class 处理图像)。
  • pixel_attention_mask(形状为 (batch_size, image_size, image_size) 的 torch.Tensor,可选) — 用于避免对填充像素索引执行注意力机制的掩码。
  • image_hidden_states (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 图像编码器经过模态投影后的隐藏状态。

返回值

ModernVBertBaseModelOutput 或 tuple(torch.Tensor)

ModernVBertBaseModelOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(ModernVBertConfig)和输入。

输入到模型的图像数量可以是任意的。为此,传入模型的 pixel_values 会进行图像填充,其形状为 (batch_size, max_num_images, 3, max_heights, max_widths),其中 max_num_images 是 batch_size 个样本中图像数量的最大值。除了在模型入口处对 pixel_values 进行填充外,不需要额外的填充图像。为了提高效率,我们在 vision_model 的前向传播中只传递真实图像,即丢弃填充图像,因此 pixel_values 的形状为 (image_batch_size, 3, height, width)。例如,当 num_images_per_sample=[1, 3, 1, 2] 且 max_num_images 为 3 时,image_batch_size 为 7。

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

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

  • image_hidden_states (tuple(torch.FloatTensor),可选) — 由 torch.FloatTensor 组成的元组(一个用于图像嵌入的输出,(batch_size, num_images, sequence_length, hidden_size)。 由视觉编码器生成的模型的 image_hidden_states

ModernVBertForMaskedLM

class transformers.ModernVBertForMaskedLM

< >

( config: ModernVBertConfig )

参数

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

带有 language modeling 头的 Modernvbert 模型。”

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

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

forward

< >

( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_attention_mask: typing.Optional[torch.BoolTensor] = Noneimage_hidden_states: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ModernVBertMaskedLMOutput or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

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

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 image_processor_class 获取像素值。有关详细信息,请参阅 image_processor_class.__call__(Idefics3Processor 使用 image_processor_class 处理图像)。
  • pixel_attention_mask(形状为 (batch_size, image_size, image_size) 的 torch.Tensor,可选) — 用于避免对填充像素索引执行注意力机制的掩码。
  • image_hidden_states (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 图像编码器经过模态投影后的隐藏状态。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引应位于 [0, ..., text_config.] 或 model.image_token_id 中。索引设置为 model.image_token_id 的 token 将被忽略(掩码),损失仅针对标签位于 [0, ..., text_config.] 中的 token 进行计算。

返回值

ModernVBertMaskedLMOutput 或 tuple(torch.Tensor)

ModernVBertMaskedLMOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),包含根据配置(ModernVBertConfig)和输入而定的各种元素。

输入到模型的图像数量可以是任意的。为此,传入模型的 pixel_values 会进行图像填充,其形状为 (batch_size, max_num_images, 3, max_heights, max_widths),其中 max_num_images 是 batch_size 个样本中图像数量的最大值。除了在模型入口处对 pixel_values 进行填充外,不需要额外的填充图像。为了提高效率,我们在 vision_model 的前向传播中只传递真实图像,即丢弃填充图像,因此 pixel_values 的形状为 (image_batch_size, 3, height, width)。例如,当 num_images_per_sample=[1, 3, 1, 2] 且 max_num_images 为 3 时,image_batch_size 为 7。

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

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

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

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

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

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

  • image_hidden_states (tuple(torch.FloatTensor),可选) — 由 torch.FloatTensor 组成的元组(一个用于图像嵌入的输出,(batch_size, num_images, sequence_length, hidden_size)。 由视觉编码器生成的模型的 image_hidden_states

示例:

>>> from transformers import AutoTokenizer, ModernVBertForMaskedLM
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("ModernVBERT/modernvbert")
>>> model = ModernVBertForMaskedLM.from_pretrained("ModernVBERT/modernvbert")

>>> inputs = tokenizer("The capital of France is <mask>.", return_tensors="pt")

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

>>> # retrieve index of <mask>
>>> mask_token_index = (inputs.input_ids == tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]

>>> predicted_token_id = logits[0, mask_token_index].argmax(axis=-1)
>>> tokenizer.decode(predicted_token_id)
...

>>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"]
>>> # mask labels of non-<mask> tokens
>>> labels = torch.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)

>>> outputs = model(**inputs, labels=labels)
>>> round(outputs.loss.item(), 2)
...

ModernVBertForSequenceClassification

class transformers.ModernVBertForSequenceClassification

< >

( config: ModernVBertConfig )

参数

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

在顶部添加了一个执行池化的序列分类头的 ModernVBert 模型。

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

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

forward

< >

( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_attention_mask: typing.Optional[torch.BoolTensor] = Noneimage_hidden_states: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → SequenceClassifierOutput or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

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

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 image_processor_class 获取像素值。有关详细信息,请参阅 image_processor_class.__call__(Idefics3Processor 使用 image_processor_class 处理图像)。
  • pixel_attention_mask(形状为 (batch_size, image_size, image_size) 的 torch.Tensor,可选) — 用于避免对填充像素索引执行注意力机制的掩码。
  • image_hidden_states (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 图像编码器经过模态投影后的隐藏状态。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引应位于 [0, ..., text_config.] 或 model.image_token_id 中。索引设置为 model.image_token_id 的 token 将被忽略(掩码),损失仅针对标签位于 [0, ..., text_config.] 中的 token 进行计算。

返回值

SequenceClassifierOutput 或 tuple(torch.Tensor)

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

输入到模型的图像数量可以是任意的。为此,传入模型的 pixel_values 会进行图像填充,其形状为 (batch_size, max_num_images, 3, max_heights, max_widths),其中 max_num_images 是 batch_size 个样本中图像数量的最大值。除了在模型入口处对 pixel_values 进行填充外,不需要额外的填充图像。为了提高效率,我们在 vision_model 的前向传播中只传递真实图像,即丢弃填充图像,因此 pixel_values 的形状为 (image_batch_size, 3, height, width)。例如,当 num_images_per_sample=[1, 3, 1, 2] 且 max_num_images 为 3 时,image_batch_size 为 7。

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

单标签分类示例:

>>> import torch
>>> from transformers import AutoTokenizer, ModernVBertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("ModernVBERT/modernvbert")
>>> model = ModernVBertForSequenceClassification.from_pretrained("ModernVBERT/modernvbert")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")

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

>>> predicted_class_id = logits.argmax().item()
>>> model.config.id2label[predicted_class_id]
...

>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = ModernVBertForSequenceClassification.from_pretrained("ModernVBERT/modernvbert", num_labels=num_labels)

>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...

多标签分类示例:

>>> import torch
>>> from transformers import AutoTokenizer, ModernVBertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("ModernVBERT/modernvbert")
>>> model = ModernVBertForSequenceClassification.from_pretrained("ModernVBERT/modernvbert", problem_type="multi_label_classification")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")

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

>>> predicted_class_ids = torch.arange(0, logits.shape[-1])[torch.sigmoid(logits).squeeze(dim=0) > 0.5]

>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = ModernVBertForSequenceClassification.from_pretrained(
...     "ModernVBERT/modernvbert", num_labels=num_labels, problem_type="multi_label_classification"
... )

>>> labels = torch.sum(
...     torch.nn.functional.one_hot(predicted_class_ids[None, :].clone(), num_classes=num_labels), dim=1
... ).to(torch.float)
>>> loss = model(**inputs, labels=labels).loss

ModernVBertForTokenClassification

class transformers.ModernVBertForTokenClassification

< >

( config: ModernVBertConfig )

参数

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

带有 token 分类头的 ModernVBert 模型,例如用于命名实体识别(NER)任务。

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

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

forward

< >

( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_attention_mask: typing.Optional[torch.BoolTensor] = Noneimage_hidden_states: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → TokenClassifierOutput or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

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

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 image_processor_class 获取像素值。有关详细信息,请参阅 image_processor_class.__call__(Idefics3Processor 使用 image_processor_class 处理图像)。
  • pixel_attention_mask(形状为 (batch_size, image_size, image_size) 的 torch.Tensor,可选) — 用于避免对填充像素索引执行注意力机制的掩码。
  • image_hidden_states (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 图像编码器经过模态投影后的隐藏状态。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引应位于 [0, ..., text_config.] 或 model.image_token_id 中。索引设置为 model.image_token_id 的 token 将被忽略(掩码),损失仅针对标签位于 [0, ..., text_config.] 中的 token 进行计算。

返回值

TokenClassifierOutput 或 tuple(torch.Tensor)

TokenClassifierOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(ModernVBertConfig)和输入。

输入到模型的图像数量可以是任意的。为此,传入模型的 pixel_values 会进行图像填充,其形状为 (batch_size, max_num_images, 3, max_heights, max_widths),其中 max_num_images 是 batch_size 个样本中图像数量的最大值。除了在模型入口处对 pixel_values 进行填充外,不需要额外的填充图像。为了提高效率,我们在 vision_model 的前向传播中只传递真实图像,即丢弃填充图像,因此 pixel_values 的形状为 (image_batch_size, 3, height, width)。例如,当 num_images_per_sample=[1, 3, 1, 2] 且 max_num_images 为 3 时,image_batch_size 为 7。

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

  • logits(形状为 (batch_size, sequence_length, config.num_labels) 的 torch.Tensor)— 分类分数(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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> from transformers import AutoTokenizer, ModernVBertForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("ModernVBERT/modernvbert")
>>> model = ModernVBertForTokenClassification.from_pretrained("ModernVBERT/modernvbert")

>>> inputs = tokenizer(
...     "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="pt"
... )

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

>>> predicted_token_class_ids = logits.argmax(-1)

>>> # Note that tokens are classified rather then input words which means that
>>> # there might be more predicted token classes than words.
>>> # Multiple token classes might account for the same word
>>> predicted_tokens_classes = [model.config.id2label[t.item()] for t in predicted_token_class_ids[0]]
>>> predicted_tokens_classes
...

>>> labels = predicted_token_class_ids
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...
Update on GitHub