Transformers 文档

视觉变换器 (ViT)

视觉变换器 (ViT)

概述

Vision Transformer (ViT) 模型是由 Alexey Dosovitskiy、Lucas Beyer、Alexander Kolesnikov、Dirk Weissenborn、Xiaohua Zhai、Thomas Unterthiner、Mostafa Dehghani、Matthias Minderer、Georg Heigold、Sylvain Gelly、Jakob Uszkoreit 和 Neil Houlsby 在 An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale 中提出的。这是第一篇成功在 ImageNet 上训练 Transformer 编码器的论文,与常见的卷积架构相比,取得了非常好的结果。

论文的摘要如下:

尽管Transformer架构已成为自然语言处理任务的事实标准,但其在计算机视觉中的应用仍然有限。在视觉领域,注意力机制要么与卷积网络结合使用,要么用于替换卷积网络的某些组件,同时保持其整体结构不变。我们表明,这种对卷积网络的依赖是不必要的,直接应用于图像块序列的纯Transformer在图像分类任务中可以表现得非常好。当在大规模数据上进行预训练并转移到多个中型或小型图像识别基准(如ImageNet、CIFAR-100、VTAB等)时,Vision Transformer(ViT)与最先进的卷积网络相比,取得了优异的结果,同时训练所需的计算资源显著减少。

drawing ViT architecture. Taken from the original paper.

继最初的Vision Transformer之后,一些后续工作已经完成:

  • DeiT(数据高效的图像变换器)由Facebook AI开发。DeiT模型是经过蒸馏的视觉变换器。 DeiT的作者还发布了更高效训练的ViT模型,您可以直接将其插入ViTModelViTForImageClassification。有4种变体可用(有3种不同尺寸):facebook/deit-tiny-patch16-224facebook/deit-small-patch16-224facebook/deit-base-patch16-224facebook/deit-base-patch16-384。请注意,应该使用 DeiTImageProcessor来为模型准备图像。

  • BEiT(图像变换器的BERT预训练)由微软研究院提出。BEiT模型通过一种受BERT(掩码图像建模)启发的自监督方法,并基于VQ-VAE,超越了使用监督预训练的视觉变换器。

  • DINO(一种用于自监督训练视觉Transformer的方法)由Facebook AI开发。使用DINO方法训练的视觉Transformer展示出卷积模型所不具备的非常有趣的特性。它们能够在没有经过专门训练的情况下进行对象分割。DINO的检查点可以在hub上找到。

  • MAE (Masked Autoencoders) 由 Facebook AI 提出。通过预训练 Vision Transformers 来重建大部分(75%)被遮蔽的补丁的像素值(使用非对称编码器-解码器架构),作者展示了这种简单的方法在微调后优于监督预训练。

该模型由nielsr贡献。原始代码(用JAX编写)可以在这里找到。

请注意,我们从Ross Wightman的timm库中转换了权重, 他已经将权重从JAX转换为PyTorch。功劳归功于他!

使用提示

  • 为了将图像输入到Transformer编码器中,每张图像被分割成一系列固定大小的不重叠的补丁,然后进行线性嵌入。添加一个[CLS]标记作为整个图像的表示,可以用于分类。作者还添加了绝对位置嵌入,并将生成的向量序列输入到标准的Transformer编码器中。
  • 由于Vision Transformer期望每张图像具有相同的大小(分辨率),可以使用 ViTImageProcessor来调整(或重新缩放)和归一化图像以供模型使用。
  • 在预训练或微调过程中使用的补丁分辨率和图像分辨率都反映在每个检查点的名称中。例如,google/vit-base-patch16-224指的是一个基础大小的架构,补丁分辨率为16x16,微调分辨率为224x224。所有检查点都可以在hub上找到。
  • 可用的检查点要么是(1)仅在ImageNet-21k(包含1400万张图像和21k个类别的集合)上预训练,要么是(2)也在ImageNet(也称为ILSVRC 2012,包含130万张图像和1000个类别的集合)上进行了微调。
  • Vision Transformer 使用 224x224 的分辨率进行了预训练。在微调过程中,使用比预训练更高的分辨率通常是有益的 (Touvron et al., 2019), (Kolesnikov et al., 2020)。为了在更高分辨率下进行微调,作者根据预训练位置嵌入在原始图像中的位置进行了二维插值。
  • 最佳结果是通过有监督的预训练获得的,这在NLP中并非如此。作者还进行了一项实验,使用自监督的预训练目标,即掩码补丁预测(受掩码语言建模的启发)。通过这种方法,较小的ViT-B/16模型在ImageNet上达到了79.9%的准确率,相比从头训练显著提高了2%,但仍比有监督的预训练低4%。

使用缩放点积注意力 (SDPA)

PyTorch 包含一个原生的缩放点积注意力(SDPA)操作符,作为 torch.nn.functional 的一部分。这个函数 包含了几种实现,可以根据输入和使用的硬件进行应用。更多信息请参阅 官方文档GPU 推理 页面。

默认情况下,当有可用实现时,SDPA 用于 torch>=2.1.1,但你也可以在 from_pretrained() 中设置 attn_implementation="sdpa" 来明确请求使用 SDPA。

from transformers import ViTForImageClassification
model = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224", attn_implementation="sdpa", torch_dtype=torch.float16)
...

为了获得最佳加速效果,我们建议以半精度加载模型(例如 torch.float16torch.bfloat16)。

在本地基准测试(A100-40GB,PyTorch 2.3.0,操作系统 Ubuntu 22.04)中,使用float32google/vit-base-patch16-224模型,我们在推理过程中看到了以下加速效果。

批量大小 平均推理时间(毫秒),eager模式 平均推理时间(毫秒),sdpa模型 加速比,Sdpa / Eager(倍)
1 7 6 1.17
2 8 6 1.33
4 8 6 1.33
8 8 6 1.33

资源

关于推理以及在自定义数据上微调ViT的演示笔记本可以在这里找到。 以下是官方Hugging Face和社区(由🌎表示)资源的列表,以帮助您开始使用ViT。如果您有兴趣提交资源以包含在此处,请随时打开一个Pull Request,我们将进行审核!资源最好展示一些新的内容,而不是重复现有的资源。

ViTForImageClassification 支持以下内容:

Image Classification

⚗️ 优化

  • 一篇关于如何使用Optimum通过量化加速视觉Transformer(ViT)的博客文章

⚡️ 推理

🚀 部署

ViTConfig

transformers.ViTConfig

< >

( hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu' hidden_dropout_prob = 0.0 attention_probs_dropout_prob = 0.0 initializer_range = 0.02 layer_norm_eps = 1e-12 image_size = 224 patch_size = 16 num_channels = 3 qkv_bias = True encoder_stride = 16 **kwargs )

参数

  • hidden_size (int, optional, 默认为 768) — 编码器层和池化层的维度。
  • num_hidden_layers (int, optional, 默认为 12) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, optional, defaults to 12) — Transformer编码器中每个注意力层的注意力头数。
  • intermediate_size (int, optional, 默认为 3072) — Transformer 编码器中“中间”(即前馈)层的维度。
  • hidden_act (strfunction, 可选, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu""relu""selu""gelu_new"
  • hidden_dropout_prob (float, optional, 默认为 0.0) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (float, optional, 默认为 0.0) — 注意力概率的丢弃比例。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • layer_norm_eps (float, optional, defaults to 1e-12) — 层归一化层使用的epsilon值。
  • image_size (int, optional, 默认为 224) — 每张图像的尺寸(分辨率)。
  • patch_size (int, optional, defaults to 16) — 每个补丁的大小(分辨率)。
  • num_channels (int, optional, 默认为 3) — 输入通道的数量。
  • qkv_bias (bool, optional, defaults to True) — 是否在查询、键和值中添加偏置。
  • encoder_stride (int, optional, defaults to 16) — 在解码器头部用于掩码图像建模的空间分辨率增加因子。

这是用于存储ViTModel配置的配置类。它用于根据指定的参数实例化一个ViT模型,定义模型架构。使用默认值实例化配置将产生与google/vit-base-patch16-224架构类似的配置。

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

示例:

>>> from transformers import ViTConfig, ViTModel

>>> # Initializing a ViT vit-base-patch16-224 style configuration
>>> configuration = ViTConfig()

>>> # Initializing a model (with random weights) from the vit-base-patch16-224 style configuration
>>> model = ViTModel(configuration)

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

ViT特征提取器

transformers.ViTFeatureExtractor

< >

( *args **kwargs )

__call__

< >

( images **kwargs )

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

ViTImageProcessor

transformers.ViTImageProcessor

< >

( do_resize: bool = True size: typing.Optional[typing.Dict[str, int]] = None resample: Resampling = do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_convert_rgb: typing.Optional[bool] = None **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将图像的(高度,宽度)尺寸调整为指定的 (size["height"], size["width"])。可以在 preprocess 方法中通过 do_resize 参数覆盖此设置。
  • size (dict, 可选, 默认为 {"height" -- 224, "width": 224}): 调整大小后输出图像的尺寸。可以在 preprocess 方法中通过 size 参数覆盖此设置。
  • resample (PILImageResampling, 可选, 默认为 Resampling.BILINEAR) — 如果调整图像大小,使用的重采样过滤器。可以在 preprocess 方法中的 resample 参数中覆盖此设置。
  • do_rescale (bool, 可选, 默认为 True) — 是否通过指定的比例 rescale_factor 重新缩放图像。可以在 preprocess 方法中通过 do_rescale 参数覆盖此设置。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 如果重新缩放图像,则使用的缩放因子。可以在 preprocess 方法中通过 rescale_factor 参数覆盖此值。
  • do_normalize (bool, 可选, 默认为 True) — 是否对图像进行归一化。可以在 preprocess 方法中通过 do_normalize 参数进行覆盖。
  • image_mean (floatList[float], 可选, 默认为 IMAGENET_STANDARD_MEAN) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以通过 preprocess 方法中的 image_mean 参数进行覆盖。
  • image_std (floatList[float], 可选, 默认为 IMAGENET_STANDARD_STD) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以通过 preprocess 方法中的 image_std 参数进行覆盖。
  • do_convert_rgb (bool, optional) — 是否将图像转换为RGB.

构建一个ViT图像处理器。

预处理

< >

( 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: typing.Optional[bool] = None size: typing.Dict[str, int] = None resample: Resampling = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None do_convert_rgb: typing.Optional[bool] = None )

参数

  • 图像 (ImageInput) — 要预处理的图像。期望输入单个或批量的图像,像素值范围在0到255之间。如果传入的图像像素值在0到1之间,请设置 do_rescale=False.
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小.
  • size (Dict[str, int], 可选, 默认为 self.size) — 指定调整大小后输出图像大小的字典,格式为 {"height": h, "width": w}.
  • resample (PILImageResampling 过滤器, 可选, 默认为 self.resample) — PILImageResampling 过滤器用于调整图像大小,例如 PILImageResampling.BILINEAR。仅在 do_resize 设置为 True 时有效。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否将图像值缩放到 [0 - 1] 之间。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 如果 do_rescale 设置为 True,则用于重新缩放图像的重新缩放因子。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否对图像进行归一化处理。
  • image_mean (floatList[float], 可选, 默认为 self.image_mean) — 如果 do_normalize 设置为 True,则使用的图像均值。
  • image_std (floatList[float], 可选, 默认为 self.image_std) — 如果 do_normalize 设置为 True,则使用的图像标准差。
  • return_tensors (strTensorType, 可选) — 返回的张量类型。可以是以下之一:
    • 未设置:返回一个 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf':返回一个类型为 tf.Tensor 的批次。
    • TensorType.PYTORCH'pt':返回一个类型为 torch.Tensor 的批次。
    • TensorType.NUMPY'np':返回一个类型为 np.ndarray 的批次。
    • TensorType.JAX'jax':返回一个类型为 jax.numpy.ndarray 的批次。
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • 未设置:使用输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。
  • do_convert_rgb (bool, optional, defaults to self.do_convert_rgb) — 是否将图像转换为RGB.

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

ViTImageProcessorFast

transformers.ViTImageProcessorFast

< >

( do_resize: bool = True size: typing.Optional[typing.Dict[str, int]] = None resample: Resampling = do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_convert_rgb: typing.Optional[bool] = None **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将图像的(高度,宽度)尺寸调整为指定的 (size["height"], size["width"])。可以在 preprocess 方法中通过 do_resize 参数覆盖此设置。
  • size (dict, 可选, 默认为 {"height" -- 224, "width": 224}): 调整大小后输出图像的尺寸。可以在 preprocess 方法中通过 size 参数覆盖此设置。
  • resample (PILImageResampling, 可选, 默认为 Resampling.BILINEAR) — 如果调整图像大小,使用的重采样过滤器。可以在 preprocess 方法中通过 resample 参数覆盖。
  • do_rescale (bool, 可选, 默认为 True) — 是否通过指定的比例 rescale_factor 来重新缩放图像。可以在 preprocess 方法中通过 do_rescale 参数进行覆盖。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 如果重新缩放图像,则使用的缩放因子。可以在 preprocess 方法中通过 rescale_factor 参数覆盖此值。
  • do_normalize (bool, 可选, 默认为 True) — 是否对图像进行归一化。可以在 preprocess 方法中通过 do_normalize 参数进行覆盖。
  • image_mean (floatList[float], 可选, 默认为 IMAGENET_STANDARD_MEAN) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以通过 preprocess 方法中的 image_mean 参数进行覆盖。
  • image_std (floatList[float], 可选, 默认为 IMAGENET_STANDARD_STD) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以通过 preprocess 方法中的 image_std 参数进行覆盖。
  • do_convert_rgb (bool, optional) — 是否将图像转换为RGB.

构建一个ViT图像处理器。

预处理

< >

( 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: typing.Optional[bool] = None size: typing.Dict[str, int] = None resample: Resampling = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = 'pt' data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None do_convert_rgb: typing.Optional[bool] = None **kwargs )

参数

  • 图像 (ImageInput) — 要预处理的图像。期望输入单个或批量的图像,像素值范围在0到255之间。如果传入的图像像素值在0到1之间,请设置 do_rescale=False.
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小.
  • size (Dict[str, int], 可选, 默认为 self.size) — 指定调整大小后输出图像大小的字典,格式为 {"height": h, "width": w}.
  • resample (PILImageResampling filter, 可选, 默认为 self.resample) — PILImageResampling 过滤器,用于调整图像大小,例如 PILImageResampling.BILINEAR。仅在 do_resize 设置为 True 时有效。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否将图像值缩放到 [0 - 1] 之间。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 如果do_rescale设置为True,则用于重新缩放图像的重新缩放因子。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否对图像进行归一化处理。
  • image_mean (floatList[float], 可选, 默认为 self.image_mean) — 如果 do_normalize 设置为 True,则使用的图像均值。
  • image_std (floatList[float], 可选, 默认为 self.image_std) — 如果 do_normalize 设置为 True,则使用的图像标准差。
  • return_tensors (str or TensorType, optional) — 返回的张量类型。仅支持“pt”
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。当前支持以下格式:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。

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

do_convert_rgb (bool, 可选): 是否将图像转换为RGB。

Pytorch
Hide Pytorch content

ViTModel

transformers.ViTModel

< >

( config: ViTConfig add_pooling_layer: bool = True use_mask_token: bool = False )

参数

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

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

前进

< >

( pixel_values: typing.Optional[torch.Tensor] = None bool_masked_pos: typing.Optional[torch.BoolTensor] = None head_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None interpolate_pos_encoding: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见ViTImageProcessor.call()
  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • interpolate_pos_encoding (bool, optional) — 是否插值预训练的位置编码.
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • bool_masked_pos (torch.BoolTensor of shape (batch_size, num_patches), optional) — 布尔掩码位置。指示哪些补丁被掩码(1)和哪些没有被掩码(0)。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

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

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

  • pooler_output (torch.FloatTensor 形状为 (batch_size, hidden_size)) — 序列的第一个标记(分类标记)在经过用于辅助预训练任务的层进一步处理后的最后一层隐藏状态。例如,对于BERT系列模型,这返回经过线性层和tanh激活函数处理后的分类标记。线性层的权重是在预训练期间通过下一个句子预测(分类)目标进行训练的。

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

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

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

示例:

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

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

>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
>>> model = ViTModel.from_pretrained("google/vit-base-patch16-224-in21k")

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

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

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 197, 768]

ViTForMaskedImageModeling

transformers.ViTForMaskedImageModeling

< >

( config: ViTConfig )

参数

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

ViT模型,顶部带有解码器,用于掩码图像建模,如SimMIM中提出的。

请注意,我们在示例目录中提供了一个脚本来在自定义数据上预训练此模型。

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

前进

< >

( pixel_values: typing.Optional[torch.Tensor] = None bool_masked_pos: typing.Optional[torch.BoolTensor] = None head_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None interpolate_pos_encoding: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.MaskedImageModelingOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见ViTImageProcessor.call()
  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • interpolate_pos_encoding (bool, optional) — 是否插值预训练的位置编码.
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • bool_masked_pos (torch.BoolTensor of shape (batch_size, num_patches)) — 布尔掩码位置。指示哪些补丁被掩码(1)和哪些没有被掩码(0)。

返回

transformers.modeling_outputs.MaskedImageModelingOutputtuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor 形状为 (1,), 可选, 当提供 bool_masked_pos 时返回) — 重建损失。
  • reconstruction (torch.FloatTensor 形状为 (batch_size, num_channels, height, width)) — 重建/完成的图像。
  • 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, patch_size, sequence_length)。注意力权重在注意力 softmax 之后,用于计算自注意力头中的加权平均值。

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

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

示例:

>>> from transformers import AutoImageProcessor, ViTForMaskedImageModeling
>>> import torch
>>> from PIL import Image
>>> import requests

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
>>> model = ViTForMaskedImageModeling.from_pretrained("google/vit-base-patch16-224-in21k")

>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
>>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
>>> # create random boolean mask of shape (batch_size, num_patches)
>>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()

>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
>>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
>>> list(reconstructed_pixel_values.shape)
[1, 3, 224, 224]

ViTForImageClassification

transformers.ViTForImageClassification

< >

( config: ViTConfig )

参数

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

ViT模型转换器,顶部带有图像分类头(在[CLS]标记的最终隐藏状态之上的线性层),例如用于ImageNet。

请注意,通过在模型的前向传播中将interpolate_pos_encoding设置为True,可以在比训练时更高分辨率的图像上微调ViT。这将把预训练的位置嵌入插值到更高的分辨率。

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

前进

< >

( pixel_values: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None interpolate_pos_encoding: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.ImageClassifierOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见ViTImageProcessor.call()
  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • interpolate_pos_encoding (bool, optional) — 是否插值预训练的位置编码.
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • labels (torch.LongTensor 形状为 (batch_size,), 可选) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失),如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回

transformers.modeling_outputs.ImageClassifierOutputtuple(torch.FloatTensor)

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

  • 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, patch_size, sequence_length)

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

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

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

示例:

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

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

>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
>>> model = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224")

>>> 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])
Egyptian cat
TensorFlow
Hide TensorFlow content

TFViTModel

transformers.TFViTModel

< >

( config: ViTConfig *inputs add_pooling_layer = True **kwargs )

参数

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

裸的ViT模型变压器输出原始隐藏状态,没有任何特定的头部。

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

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

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

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

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

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

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

调用

< >

( pixel_values: TFModelInputType | None = None head_mask: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None interpolate_pos_encoding: Optional[bool] = None return_dict: Optional[bool] = None training: bool = False ) transformers.modeling_tf_outputs.TFBaseModelOutputWithPoolingtuple(tf.Tensor)

参数

  • pixel_values (np.ndarray, tf.Tensor, List[tf.Tensor] `Dict[str, tf.Tensor] or Dict[str, np.ndarray] and each example must have the shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见ViTImageProcessor.call()
  • head_mask (np.ndarraytf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。
  • interpolate_pos_encoding (bool, optional) — 是否插值预训练的位置编码.
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True.
  • 训练 (bool, 可选, 默认为 `False“) — 是否在训练模式下使用模型(一些模块如dropout模块在训练和评估之间有不同的行为)。

返回

transformers.modeling_tf_outputs.TFBaseModelOutputWithPoolingtuple(tf.Tensor)

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

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

  • pooler_output (tf.Tensor 形状为 (batch_size, hidden_size)) — 序列的第一个标记(分类标记)的最后一层隐藏状态,经过线性层和 Tanh 激活函数进一步处理。线性层的权重是在预训练期间通过下一个句子预测(分类)目标训练的。

    这个输出通常不是输入语义内容的一个好的总结,通常最好对整个输入序列的隐藏状态序列进行平均或池化。

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

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

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

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

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

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

示例:

>>> from transformers import AutoImageProcessor, TFViTModel
>>> from datasets import load_dataset

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

>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
>>> model = TFViTModel.from_pretrained("google/vit-base-patch16-224-in21k")

>>> inputs = image_processor(image, return_tensors="tf")
>>> outputs = model(**inputs)

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 197, 768]

TFViTForImageClassification

transformers.TFViTForImageClassification

< >

( config: ViTConfig *inputs **kwargs )

参数

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

ViT模型转换器,顶部带有图像分类头(在[CLS]标记的最终隐藏状态之上的线性层),例如用于ImageNet。

请注意,通过在模型的前向传播中将interpolate_pos_encoding设置为True,可以在比训练时更高分辨率的图像上微调ViT。这将把预训练的位置嵌入插值到更高的分辨率。

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

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

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

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

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

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

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

调用

< >

( pixel_values: TFModelInputType | None = None head_mask: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None interpolate_pos_encoding: Optional[bool] = None return_dict: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None training: Optional[bool] = False ) transformers.modeling_tf_outputs.TFSequenceClassifierOutputtuple(tf.Tensor)

参数

  • pixel_values (np.ndarray, tf.Tensor, List[tf.Tensor] `Dict[str, tf.Tensor] or Dict[str, np.ndarray] and each example must have the shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见ViTImageProcessor.call()
  • head_mask (np.ndarraytf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states。此参数只能在急切模式下使用,在图形模式下将使用配置中的值。
  • interpolate_pos_encoding (bool, optional) — 是否插值预训练的位置编码.
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True.
  • 训练 (bool, 可选, 默认为 `False“) — 是否在训练模式下使用模型(一些模块如dropout模块在训练和评估时具有不同的行为)。
  • labels (tf.Tensornp.ndarray 形状为 (batch_size,), 可选) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失),如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回

transformers.modeling_tf_outputs.TFSequenceClassifierOutputtuple(tf.Tensor)

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

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

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

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

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

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

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

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

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

示例:

>>> from transformers import AutoImageProcessor, TFViTForImageClassification
>>> import tensorflow as tf
>>> from datasets import load_dataset

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

>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
>>> model = TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224")

>>> inputs = image_processor(image, return_tensors="tf")
>>> logits = model(**inputs).logits

>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = int(tf.math.argmax(logits, axis=-1))
>>> print(model.config.id2label[predicted_label])
Egyptian cat
JAX
Hide JAX content

FlaxVitModel

transformers.FlaxViTModel

< >

( config: ViTConfig input_shape = 无 seed: int = 0 dtype: dtype = _do_init: bool = 真 **kwargs )

参数

  • config (ViTConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs).

    这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的dtype执行。

    请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。

    如果您希望更改模型参数的dtype,请参阅to_fp16()to_bf16().

裸的ViT模型变压器输出原始隐藏状态,没有任何特定的头部。

该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。

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

最后,该模型支持JAX的固有特性,例如:

__call__

< >

( pixel_values params: 字典 = 无 dropout_rng: <函数 PRNGKey 在 0x7f50727b7640> = 无 train: 布尔值 = 假 output_attentions: 可选[布尔值] = 无 output_hidden_states: 可选[布尔值] = 无 return_dict: 可选[布尔值] = 无 ) transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPoolingtuple(torch.FloatTensor)

返回

transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPoolingtuple(torch.FloatTensor)

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

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

  • pooler_output (jnp.ndarray 形状为 (batch_size, hidden_size)) — 序列的第一个标记(分类标记)的最后一层隐藏状态,经过线性层和 Tanh 激活函数进一步处理。线性层的权重是在预训练期间通过下一个句子预测(分类)目标进行训练的。

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

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

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

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

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

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

示例:

>>> from transformers import AutoImageProcessor, FlaxViTModel
>>> from PIL import Image
>>> import requests

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
>>> model = FlaxViTModel.from_pretrained("google/vit-base-patch16-224-in21k")

>>> inputs = image_processor(images=image, return_tensors="np")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state

FlaxViTForImageClassification

transformers.FlaxViTForImageClassification

< >

( config: ViTConfig input_shape = 无 seed: int = 0 dtype: dtype = _do_init: bool = 真 **kwargs )

参数

  • config (ViTConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs).

    这可以用于在GPU或TPU上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的dtype执行。

    请注意,这仅指定了计算的数据类型,并不影响模型参数的数据类型。

    如果您希望更改模型参数的dtype,请参阅to_fp16()to_bf16().

ViT模型转换器,顶部带有图像分类头(在[CLS]标记的最终隐藏状态之上的线性层),例如用于ImageNet。

该模型继承自FlaxPreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载、保存和从PyTorch模型转换权重)。

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

最后,该模型支持JAX的固有特性,例如:

__call__

< >

( pixel_values params: 字典 = 无 dropout_rng: <函数 PRNGKey 位于 0x7f50727b7640> = 无 train: 布尔值 = 假 output_attentions: 可选[布尔值] = 无 output_hidden_states: 可选[布尔值] = 无 return_dict: 可选[布尔值] = 无 ) transformers.modeling_flax_outputs.FlaxSequenceClassifierOutputtuple(torch.FloatTensor)

返回

transformers.modeling_flax_outputs.FlaxSequenceClassifierOutputtuple(torch.FloatTensor)

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

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

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

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

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

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

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

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

示例:

>>> from transformers import AutoImageProcessor, FlaxViTForImageClassification
>>> from PIL import Image
>>> import jax
>>> import requests

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
>>> model = FlaxViTForImageClassification.from_pretrained("google/vit-base-patch16-224")

>>> inputs = image_processor(images=image, return_tensors="np")
>>> outputs = model(**inputs)
>>> logits = outputs.logits

>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_class_idx = jax.numpy.argmax(logits, axis=-1)
>>> print("Predicted class:", model.config.id2label[predicted_class_idx.item()])
< > Update on GitHub