Transformers 文档
DeiT
并获得增强的文档体验
开始使用
DeiT
概述
DeiT 模型由 Hugo Touvron、Matthieu Cord、Matthijs Douze、Francisco Massa、Alexandre Sablayrolles 和 Hervé Jégou 在论文 Training data-efficient image transformers & distillation through attention 中提出。Vision Transformer (ViT) 模型在 Dosovitskiy 等人,2020 的论文中提出,表明使用 Transformer 编码器(类似 BERT)可以匹敌甚至超越现有的卷积神经网络。然而,该论文中介绍的 ViT 模型需要使用外部数据在昂贵的基础设施上训练数周。DeiT (data-efficient image transformers) 是为图像分类任务而设计的、训练效率更高的 Transformer 模型,相比原始 ViT 模型,它需要的数据和计算资源都少得多。
论文摘要如下:
最近,纯粹基于注意力机制的神经网络被证明可以解决图像理解任务,如图像分类。然而,这些视觉 Transformer 模型需要使用数亿张图片在昂贵的基础设施上进行预训练,从而限制了它们的普及。在这项工作中,我们仅在 ImageNet 上训练,就产生了一个具有竞争力的无卷积 Transformer 模型。我们在单台计算机上用不到 3 天的时间就完成了训练。我们的参考视觉 Transformer 模型(8600 万参数)在 ImageNet 上(单次裁剪评估)实现了 83.1% 的 top-1 准确率,且未使用任何外部数据。更重要的是,我们引入了一种专为 Transformer 设计的师生策略。它依赖一个蒸馏标记(distillation token),确保学生通过注意力机制向老师学习。我们展示了这种基于标记的蒸馏方法的优势,特别是在使用卷积网络作为老师时。这使得我们在 ImageNet(准确率高达 85.2%)以及迁移到其他任务时,都取得了与卷积网络相媲美的结果。我们分享了我们的代码和模型。
此模型由 nielsr 贡献。此模型的 TensorFlow 版本由 amyeroberts 添加。
使用技巧
- 与 ViT 相比,DeiT 模型使用一个所谓的蒸馏标记(distillation token),以便有效地从一个老师模型(在 DeiT 论文中,这是一个类似 ResNet 的模型)学习。蒸馏标记通过反向传播进行学习,它通过自注意力层与类别标记 ([CLS]) 和图像块标记(patch tokens)进行交互。
- 微调蒸馏模型有两种方式:(1) 传统方式,仅在类别标记的最终隐藏状态之上放置一个预测头,而不使用蒸馏信号;或者 (2) 同时在类别标记和蒸馏标记之上都放置一个预测头。在第二种情况下,[CLS] 预测头通过常规的交叉熵损失进行训练,即预测头的预测与真实标签之间的损失;而蒸馏预测头则通过硬蒸馏进行训练(蒸馏头预测与老师模型预测的标签之间的交叉熵)。在推理时,最终预测结果是两个头的预测的平均值。(2) 也被称为“带蒸馏的微调”,因为这依赖于一个已经在下游数据集上微调过的老师模型。在模型方面,(1) 对应 DeiTForImageClassification,而 (2) 对应 DeiTForImageClassificationWithTeacher。
- 请注意,作者也尝试了针对 (2) 的软蒸馏方法(在这种情况下,蒸馏预测头通过 KL 散度来匹配老师模型的 softmax 输出),但硬蒸馏取得了最好的结果。
- 所有发布的检查点都仅在 ImageNet-1k 上进行预训练和微调,没有使用任何外部数据。这与原始的 ViT 模型形成对比,后者使用了像 JFT-300M 数据集/ImageNet-21k 这样的外部数据进行预训练。
- DeiT 的作者还发布了训练效率更高的 ViT 模型,您可以直接将其用于 ViTModel 或 ViTForImageClassification。通过使用数据增强、优化和正则化等技术,模拟了在更大的数据集上进行训练的效果(尽管仅使用 ImageNet-1k 进行预训练)。共有 4 种变体(3 种不同大小):facebook/deit-tiny-patch16-224、facebook/deit-small-patch16-224、facebook/deit-base-patch16-224 和 facebook/deit-base-patch16-384。请注意,您应该使用 DeiTImageProcessor 来为模型准备图像。
使用缩放点积注意力 (SDPA)
PyTorch 在 torch.nn.functional
中包含了原生的缩放点积注意力(SDPA)算子。该函数包含多种实现,可根据输入和使用的硬件进行应用。更多信息请参阅官方文档或GPU 推理页面。
当实现可用时,SDPA 默认用于 `torch>=2.1.1`,但你也可以在 `from_pretrained()` 中设置 `attn_implementation="sdpa"` 来明确请求使用 SDPA。
from transformers import DeiTForImageClassification
model = DeiTForImageClassification.from_pretrained("facebook/deit-base-distilled-patch16-224", attn_implementation="sdpa", torch_dtype=torch.float16)
...
为了获得最佳加速效果,我们建议以半精度(例如 `torch.float16` 或 `torch.bfloat16`)加载模型。
在本地基准测试(A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04)中,使用 float32
和 facebook/deit-base-distilled-patch16-224
模型,我们在推理过程中观察到了以下速度提升。
批次大小 | 平均推理时间(毫秒),eager 模式 | 平均推理时间(毫秒),sdpa 模型 | 加速,Sdpa / Eager (x) |
---|---|---|---|
1 | 8 | 6 | 1.33 |
2 | 9 | 6 | 1.5 |
4 | 9 | 6 | 1.5 |
8 | 8 | 6 | 1.33 |
资源
一份官方 Hugging Face 和社区(由 🌎 标识)资源的列表,帮助您开始使用 DeiT。
- DeiTForImageClassification 受此示例脚本和笔记本支持。
- 另请参阅:图像分类任务指南
除此之外
如果您有兴趣在此处提交资源,请随时开启 Pull Request,我们将对其进行审查!该资源最好能展示一些新内容,而不是重复现有资源。
DeiTConfig
class transformers.DeiTConfig
< 源文件 >( 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 pooler_output_size = None pooler_act = 'tanh' **kwargs )
参数
- hidden_size (
int
, 可选, 默认为 768) — 编码器层和池化层的维度。 - num_hidden_layers (
int
, 可选, 默认为 12) — Transformer 编码器中的隐藏层数量。 - num_attention_heads (
int
, 可选, 默认为 12) — Transformer 编码器中每个注意力层的注意力头数量。 - intermediate_size (
int
, 可选, 默认为 3072) — Transformer 编码器中“中间”(即前馈)层的维度。 - hidden_act (
str
或function
, 可选, 默认为"gelu"
) — 编码器和池化层中的非线性激活函数(函数或字符串)。如果为字符串,则支持"gelu"
、"relu"
、"selu"
和"gelu_new"
。 - hidden_dropout_prob (
float
, 可选, 默认为 0.0) — 嵌入、编码器和池化层中所有全连接层的丢弃概率。 - attention_probs_dropout_prob (
float
, 可选, 默认为 0.0) — 注意力概率的丢弃率。 - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float
, 可选, 默认为 1e-12) — 层归一化层使用的 epsilon 值。 - image_size (
int
, 可选, 默认为 224) — 每张图像的大小(分辨率)。 - patch_size (
int
, 可选, 默认为 16) — 每个图像块的大小(分辨率)。 - num_channels (
int
, 可选, 默认为 3) — 输入通道的数量。 - qkv_bias (
bool
, 可选, 默认为True
) — 是否为查询、键和值添加偏置。 - encoder_stride (
int
, 可选, 默认为 16) — 在解码器头中用于掩码图像建模时,增加空间分辨率的因子。 - pooler_output_size (
int
, 可选) — 池化层的维度。如果为 None,则默认为hidden_size
。 - pooler_act (
str
, 可选, 默认为"tanh"
) — 池化层要使用的激活函数。对于 Flax 和 Pytorch,支持 ACT2FN 的键;对于 Tensorflow,支持 https://tensorflowcn.cn/api_docs/python/tf/keras/activations 中的元素。
这是用于存储 DeiTModel 配置的配置类。它用于根据指定的参数实例化一个 DeiT 模型,定义模型架构。使用默认值实例化配置将产生与 DeiT facebook/deit-base-distilled-patch16-224 架构类似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。更多信息请参阅 PretrainedConfig 的文档。
示例
>>> from transformers import DeiTConfig, DeiTModel
>>> # Initializing a DeiT deit-base-distilled-patch16-224 style configuration
>>> configuration = DeiTConfig()
>>> # Initializing a model (with random weights) from the deit-base-distilled-patch16-224 style configuration
>>> model = DeiTModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
DeiTFeatureExtractor
预处理单张或批量图像。
DeiTImageProcessor
class transformers.DeiTImageProcessor
< 源文件 >( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = 3 do_center_crop: bool = True crop_size: typing.Optional[dict[str, int]] = None rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_rescale: bool = True do_normalize: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None **kwargs )
参数
- do_resize (
bool
, 可选, 默认为True
) — 是否将图像的(高、宽)维度调整为指定的size
。可在preprocess
中通过do_resize
覆盖。 - size (
dict[str, int]
可选, 默认为{"height" -- 256, "width": 256}
):resize
后的图像尺寸。可在preprocess
中通过size
覆盖。 - resample (
PILImageResampling
过滤器, 可选, 默认为Resampling.BICUBIC
) — 调整图像大小时使用的重采样过滤器。可在preprocess
中通过resample
覆盖。 - do_center_crop (
bool
, 可选, 默认为True
) — 是否对图像进行中心裁剪。如果输入的尺寸在任何一边小于crop_size
,图像会先用 0 填充,然后再进行中心裁剪。可在preprocess
中通过do_center_crop
覆盖。 - crop_size (
dict[str, int]
, 可选, 默认为{"height" -- 224, "width": 224}
): 应用中心裁剪时期望的输出尺寸。可在preprocess
中通过crop_size
覆盖。 - rescale_factor (
int
或float
, 可选, 默认为1/255
) — 如果重缩放图像,则使用此缩放因子。可在preprocess
方法中通过rescale_factor
参数覆盖。 - do_rescale (
bool
, 可选, 默认为True
) — 是否按指定的缩放因子rescale_factor
对图像进行重缩放。可在preprocess
方法中通过do_rescale
参数覆盖。 - do_normalize (
bool
, 可选, 默认为True
) — 是否对图像进行归一化。可在preprocess
方法中通过do_normalize
参数覆盖。 - image_mean (
float
orlist[float]
, optional, defaults toIMAGENET_STANDARD_MEAN
) — 用于图像归一化的均值。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以通过preprocess
方法中的image_mean
参数覆盖此值。 - image_std (
float
orlist[float]
, optional, defaults toIMAGENET_STANDARD_STD
) — 用于图像归一化的标准差。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以通过preprocess
方法中的image_std
参数覆盖此值。
构建一个 DeiT 图像处理器。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample = None do_center_crop: typing.Optional[bool] = None crop_size: typing.Optional[dict[str, int]] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )
参数
- images (
ImageInput
) — 要预处理的图像。需要单个或一批图像,像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False
。 - do_resize (
bool
, optional, defaults toself.do_resize
) — 是否调整图像大小。 - size (
dict[str, int]
, optional, defaults toself.size
) —resize
后的图像大小。 - resample (
PILImageResampling
, optional, defaults toself.resample
) — 用于调整图像大小的 PILImageResampling 过滤器,仅当do_resize
设置为True
时有效。 - do_center_crop (
bool
, optional, defaults toself.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
dict[str, int]
, optional, defaults toself.crop_size
) — 中心裁剪后的图像大小。如果图像的一条边小于crop_size
,将用零进行填充,然后进行裁剪。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否将图像值重新缩放到 [0 - 1] 之间。 - rescale_factor (
float
, optional, defaults toself.rescale_factor
) — 当do_rescale
设置为True
时,用于重新缩放图像的比例因子。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否对图像进行归一化。 - image_mean (
float
orlist[float]
, optional, defaults toself.image_mean
) — 图像均值。 - image_std (
float
orlist[float]
, optional, defaults toself.image_std
) — 图像标准差。 - return_tensors (
str
orTensorType
, optional) — 返回的张量类型。可以是以下之一:None
: 返回一个np.ndarray
列表。TensorType.TENSORFLOW
or'tf'
: 返回一个tf.Tensor
类型的批次。TensorType.PYTORCH
or'pt'
: 返回一个torch.Tensor
类型的批次。TensorType.NUMPY
or'np'
: 返回一个np.ndarray
类型的批次。TensorType.JAX
or'jax'
: 返回一个jax.numpy.ndarray
类型的批次。
- data_format (
ChannelDimension
orstr
, optional, defaults toChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。
- input_data_format (
ChannelDimension
orstr
, optional) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"
orChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
orChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
orChannelDimension.NONE
: 图像格式为 (height, width)。
预处理一张或一批图像。
DeiTImageProcessorFast
class transformers.DeiTImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )
构建一个快速 Deit 图像处理器。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] *args **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] ) → <class 'transformers.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_resize (
bool
, optional) — 是否调整图像大小。 - size (
dict[str, int]
, optional) — 描述模型输入的最大尺寸。 - default_to_square (
bool
, optional) — 如果 size 是一个整数,是否在调整大小时默认使用方形图像。 - resample (
Union[PILImageResampling, F.InterpolationMode, NoneType]
) — 用于调整图像大小的重采样过滤器。可以是PILImageResampling
枚举之一。仅当do_resize
设置为True
时有效。 - do_center_crop (
bool
, optional) — 是否对图像进行中心裁剪。 - crop_size (
dict[str, int]
, optional) — 应用center_crop
后的输出图像大小。 - do_rescale (
bool
, optional) — 是否重新缩放图像。 - rescale_factor (
Union[int, float, NoneType]
) — 当do_rescale
设置为True
时,用于重新缩放图像的比例因子。 - do_normalize (
bool
, optional) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], NoneType]
) — 用于归一化的图像均值。仅当do_normalize
设置为True
时有效。 - image_std (
Union[float, list[float], NoneType]
) — 用于归一化的图像标准差。仅当do_normalize
设置为True
时有效。 - do_convert_rgb (
bool
, optional) — 是否将图像转换为 RGB。 - return_tensors (
Union[str, ~utils.generic.TensorType, NoneType]
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
~image_utils.ChannelDimension
, optional) — 仅支持ChannelDimension.FIRST
。为与慢速处理器兼容而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension, NoneType]
) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"
orChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
orChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
orChannelDimension.NONE
: 图像格式为 (height, width)。
- device (
torch.device
, optional) — 处理图像的设备。如果未设置,则从输入图像中推断设备。 - disable_grouping (
bool
, optional) — 是否禁用按大小对图像进行分组,以便单独处理而不是分批处理。如果为 None,则当图像在 CPU 上时设置为 True,否则为 False。此选择基于经验观察,详见: https://github.com/huggingface/transformers/pull/38157
返回
<class 'transformers.image_processing_base.BatchFeature'>
- data (
dict
) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。 - tensor_type (
Union[None, str, TensorType]
, 可选) — 您可以在此处提供一个`tensor_type`,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。
DeiTModel
class transformers.DeiTModel
< source >( config: DeiTConfig add_pooling_layer: bool = True use_mask_token: bool = False )
参数
- config (DeiTConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。请查阅 from_pretrained() 方法来加载模型权重。
- add_pooling_layer (
bool
, optional, defaults toTrue
) — 是否添加池化层。 - use_mask_token (
bool
, optional, defaults toFalse
) — 是否为掩码图像建模使用掩码标记。
一个基础的 Deit 模型,输出原始的隐藏状态,没有任何特定的头部。
该模型继承自 PreTrainedModel。请查阅超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
该模型也是 PyTorch 的 torch.nn.Module 子类。可以像常规的 PyTorch 模块一样使用它,并参考 PyTorch 文档了解所有与常规用法和行为相关的事项。
forward
< source >( 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 return_dict: typing.Optional[bool] = None interpolate_pos_encoding: bool = False ) → transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.Tensor
of shape(batch_size, num_channels, image_size, image_size)
, optional) — 对应于输入图像的张量。像素值可以使用{image_processor_class}
获得。有关详细信息,请参阅{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - bool_masked_pos (
torch.BoolTensor
of shape(batch_size, num_patches)
, optional) — 布尔类型的掩码位置。指示哪些图像块被掩盖(1),哪些没有被掩盖(0)。 - head_mask (
torch.Tensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) — 用于使自注意力模块的选定头部无效的掩码。掩码值在[0, 1]
中选择:- 1 表示头部未被掩盖,
- 0 表示头部被掩盖。
- output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。 - interpolate_pos_encoding (
bool
, 默认为False
) — 是否对预训练的位置编码进行插值。
返回
transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutputWithPooling 或一个 torch.FloatTensor
的元组 (如果传递了 return_dict=False
或 config.return_dict=False
),它包含根据配置 (DeiTConfig) 和输入而定的各种元素。
-
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 后的注意力权重,用于计算自注意力头中的加权平均值。
DeiTModel 的 forward 方法,重写了 __call__
特殊方法。
尽管前向传播的流程需要在此函数内定义,但之后应调用 Module
实例而不是此函数,因为前者会处理前处理和后处理步骤,而后者会静默地忽略它们。
DeiTForMaskedImageModeling
class transformers.DeiTForMaskedImageModeling
< 源码 >( config: DeiTConfig )
参数
- config (DeiTConfig) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
DeiT 模型,顶部带有一个解码器用于掩码图像建模,如 SimMIM 中所提出的。
请注意,我们在 examples directory 中提供了一个脚本,用于在自定义数据上预训练此模型。
该模型继承自 PreTrainedModel。请查阅超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
该模型也是 PyTorch 的 torch.nn.Module 子类。可以像常规的 PyTorch 模块一样使用它,并参考 PyTorch 文档了解所有与常规用法和行为相关的事项。
forward
< 源码 >( 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 return_dict: typing.Optional[bool] = None interpolate_pos_encoding: bool = False ) → transformers.modeling_outputs.MaskedImageModelingOutput
or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.Tensor
,形状为(batch_size, num_channels, image_size, image_size)
, 可选) — 对应于输入图像的张量。像素值可以使用{image_processor_class}
获取。有关详细信息,请参阅{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - bool_masked_pos (
torch.BoolTensor
,形状为(batch_size, num_patches)
) — 布尔掩码位置。指示哪些图像块被掩码 (1),哪些没有 (0)。 - head_mask (
torch.Tensor
,形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于使自注意力模块的选定头无效的掩码。掩码值在[0, 1]
中选择:- 1 表示头未被掩码,
- 0 表示头被掩码。
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是普通的元组。 - interpolate_pos_encoding (
bool
, 默认为False
) — 是否对预训练的位置编码进行插值。
返回
transformers.modeling_outputs.MaskedImageModelingOutput
或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.MaskedImageModelingOutput
或一个 torch.FloatTensor
的元组 (如果传递了 return_dict=False
或 config.return_dict=False
),它包含根据配置 (DeiTConfig) 和输入而定的各种元素。
- 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 后的注意力权重,用于在自注意力头中计算加权平均。
DeiTForMaskedImageModeling 的 forward 方法,重写了 __call__
特殊方法。
尽管前向传播的流程需要在此函数内定义,但之后应调用 Module
实例而不是此函数,因为前者会处理前处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, DeiTForMaskedImageModeling
>>> 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("facebook/deit-base-distilled-patch16-224")
>>> model = DeiTForMaskedImageModeling.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> 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]
DeiTForImageClassification
class transformers.DeiTForImageClassification
< 源码 >( config: DeiTConfig )
参数
- config (DeiTConfig) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
DeiT Transformer 模型,顶部带有一个图像分类头 (在 [CLS] 标记的最终隐藏状态上加一个线性层),例如用于 ImageNet。
该模型继承自 PreTrainedModel。请查阅超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
该模型也是 PyTorch 的 torch.nn.Module 子类。可以像常规的 PyTorch 模块一样使用它,并参考 PyTorch 文档了解所有与常规用法和行为相关的事项。
forward
< 源码 >( 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 return_dict: typing.Optional[bool] = None interpolate_pos_encoding: bool = False ) → transformers.modeling_outputs.ImageClassifierOutput 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.Tensor
,形状为(batch_size, num_channels, image_size, image_size)
, 可选) — 对应于输入图像的张量。像素值可以使用{image_processor_class}
获取。有关详细信息,请参阅{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - head_mask (
torch.Tensor
,形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于使自注意力模块的选定头无效的掩码。掩码值在[0, 1]
中选择:- 1 表示头未被掩码,
- 0 表示头被掩码。
- labels (
torch.LongTensor
,形状为(batch_size,)
, 可选) — 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
范围内。如果config.num_labels == 1
,则计算回归损失 (均方损失),如果config.num_labels > 1
,则计算分类损失 (交叉熵)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是普通的元组。 - interpolate_pos_encoding (
bool
, 默认为False
) — 是否对预训练的位置编码进行插值。
返回
transformers.modeling_outputs.ImageClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.ImageClassifierOutput 或一个 torch.FloatTensor
的元组 (如果传递了 return_dict=False
或 config.return_dict=False
),它包含根据配置 (DeiTConfig) 和输入而定的各种元素。
-
loss (形状为
(1,)
的torch.FloatTensor
,可选,当提供labels
时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。 -
logits (形状为
(batch_size, config.num_labels)
的torch.FloatTensor
) — 分类(如果 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 后的注意力权重,用于计算自注意力头中的加权平均值。
DeiTForImageClassification 的 forward 方法,重写了 __call__
特殊方法。
尽管前向传播的流程需要在此函数内定义,但之后应调用 Module
实例而不是此函数,因为前者会处理前处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, DeiTForImageClassification
>>> import torch
>>> from PIL import Image
>>> import requests
>>> torch.manual_seed(3)
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> # note: we are loading a DeiTForImageClassificationWithTeacher from the hub here,
>>> # so the head will be randomly initialized, hence the predictions will be random
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> model = DeiTForImageClassification.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_class_idx = logits.argmax(-1).item()
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
Predicted class: Polaroid camera, Polaroid Land camera
DeiTForImageClassificationWithTeacher
class transformers.DeiTForImageClassificationWithTeacher
< 源码 >( config: DeiTConfig )
参数
- config (DeiTConfig) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
DeiT Transformer 模型,顶部带有图像分类头 (一个在线性层上方的 [CLS] 标记的最终隐藏状态,另一个在线性层上方的蒸馏标记的最终隐藏状态),例如用于 ImageNet。
.. 警告:
此模型仅支持推理。尚不支持使用蒸馏(即带教师模型)进行微调。
该模型继承自 PreTrainedModel。请查阅超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
该模型也是 PyTorch 的 torch.nn.Module 子类。可以像常规的 PyTorch 模块一样使用它,并参考 PyTorch 文档了解所有与常规用法和行为相关的事项。
forward
< 源码 >( pixel_values: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None interpolate_pos_encoding: bool = False ) → transformers.models.deit.modeling_deit.DeiTForImageClassificationWithTeacherOutput
或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.Tensor
,形状为(batch_size, num_channels, image_size, image_size)
, 可选) — 对应于输入图像的张量。像素值可以使用{image_processor_class}
获取。有关详细信息,请参阅{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - head_mask (
torch.Tensor
,形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于使自注意力模块的选定头无效的掩码。掩码值在[0, 1]
中选择:- 1 表示头未被掩码,
- 0 表示头被掩码。
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是普通的元组。 - interpolate_pos_encoding (
bool
, 默认为False
) — 是否对预训练的位置编码进行插值。
返回
transformers.models.deit.modeling_deit.DeiTForImageClassificationWithTeacherOutput
或 tuple(torch.FloatTensor)
一个 transformers.models.deit.modeling_deit.DeiTForImageClassificationWithTeacherOutput
或一个 torch.FloatTensor
的元组 (如果传递了 return_dict=False
或 config.return_dict=False
),它包含根据配置 (DeiTConfig) 和输入而定的各种元素。
-
logits (
torch.FloatTensor
,形状为(batch_size, config.num_labels)
) — 作为 cls_logits 和 distillation logits 平均值的预测分数。 -
cls_logits (形状为
(batch_size, config.num_labels)
的torch.FloatTensor
) — 分类头部(即类标记最终隐藏状态顶部线性层)的预测分数。 -
distillation_logits (形状为
(batch_size, config.num_labels)
的torch.FloatTensor
) — 蒸馏头部(即蒸馏标记最终隐藏状态顶部线性层)的预测分数。 -
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 后的注意力权重,用于计算自注意力头中的加权平均值。
DeiTForImageClassificationWithTeacher 的 forward 方法,重写了 __call__
特殊方法。
尽管前向传播的流程需要在此函数内定义,但之后应调用 Module
实例而不是此函数,因为前者会处理前处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, DeiTForImageClassificationWithTeacher
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> model = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-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])
...
TFDeiTModel
class transformers.TFDeiTModel
< 源码 >( config: DeiTConfig add_pooling_layer: bool = True use_mask_token: bool = False **kwargs )
参数
- config (DeiTConfig) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
基础的 DeiT Transformer 模型,输出原始隐藏状态,顶部没有任何特定的头。此模型是一个 TensorFlow keras.layers.Layer。像常规 TensorFlow 模块一样使用它,并参考 TensorFlow 文档了解所有与通用用法和行为相关的事项。
调用
< 源码 >( pixel_values: tf.Tensor | None = None bool_masked_pos: tf.Tensor | None = None head_mask: tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None interpolate_pos_encoding: bool = False training: bool = False ) → transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或 tuple(tf.Tensor)
参数
- pixel_values (
tf.Tensor
,形状为(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用 AutoImageProcessor 获取。有关详细信息,请参阅 DeiTImageProcessor.call()。 - head_mask (
tf.Tensor
,形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于使自注意力模块的选定头无效的掩码。掩码值在[0, 1]
中选择:- 1 表示头未被掩码,
- 0 表示头被掩码。
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
。 - interpolate_pos_encoding (
bool
, 可选, 默认为False
) — 是否对预训练的位置编码进行插值。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是普通的元组。
返回
transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或一个 tf.Tensor
的元组 (如果传递了 return_dict=False
或 config.return_dict=False
),它包含根据配置 (DeiTConfig) 和输入而定的各种元素。
-
last_hidden_state (
tf.Tensor
of shape(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 后的注意力权重,用于计算自注意力头中的加权平均值。
TFDeiTModel 的 forward 方法,重写了 __call__
特殊方法。
尽管前向传播的流程需要在此函数内定义,但之后应调用 Module
实例而不是此函数,因为前者会处理前处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, TFDeiTModel
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> model = TFDeiTModel.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> inputs = image_processor(image, return_tensors="tf")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 198, 768]
TFDeiTForMaskedImageModeling
class transformers.TFDeiTForMaskedImageModeling
< 源码 >( config: DeiTConfig )
参数
- config (DeiTConfig) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
DeiT 模型,顶部带有一个解码器用于掩码图像建模,如 SimMIM 中所提出的。此模型是一个 TensorFlow keras.layers.Layer。像常规 TensorFlow 模块一样使用它,并参考 TensorFlow 文档了解所有与通用用法和行为相关的事项。
调用
< 源代码 >( pixel_values: tf.Tensor | None = None bool_masked_pos: tf.Tensor | None = None head_mask: tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None interpolate_pos_encoding: bool = False training: bool = False ) → transformers.modeling_tf_outputs.TFMaskedImageModelingOutput
或 tuple(tf.Tensor)
参数
- pixel_values (
tf.Tensor
,形状为(batch_size, num_channels, height, width)
) — 像素值。像素值可以通过 AutoImageProcessor 获取。详见 DeiTImageProcessor.call()。 - head_mask (
tf.Tensor
,形状为(num_heads,)
或(num_layers, num_heads)
,可选) — 用于使自注意力模块中选定的头无效的掩码。掩码值选自[0, 1]
:- 1 表示头未被屏蔽,
- 0 表示头被屏蔽。
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 `attentions`。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 `hidden_states`。 - interpolate_pos_encoding (
bool
, 可选, 默认为False
) — 是否对预训练的位置编码进行插值。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。 - bool_masked_pos (
tf.Tensor
,类型为 bool,形状为(batch_size, num_patches)
) — 布尔类型的掩码位置。指示哪些图像块被掩码 (1),哪些没有 (0)。
返回
transformers.modeling_tf_outputs.TFMaskedImageModelingOutput
或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFMaskedImageModelingOutput
或一个 tf.Tensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置(DeiTConfig)和输入。
- loss (
tf.Tensor
,形状为(1,)
,可选,在提供bool_masked_pos
时返回) — 重建损失。 - reconstruction (
tf.Tensor
,形状为(batch_size, num_channels, height, width)
) — 重建/完成的图像。 - 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, patch_size, sequence_length)
。在注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
TFDeiTForMaskedImageModeling 的前向方法,重写了 `__call__` 特殊方法。
尽管前向传播的流程需要在此函数内定义,但之后应调用 Module
实例而不是此函数,因为前者会处理前处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, TFDeiTForMaskedImageModeling
>>> import tensorflow as tf
>>> 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("facebook/deit-base-distilled-patch16-224")
>>> model = TFDeiTForMaskedImageModeling.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
>>> pixel_values = image_processor(images=image, return_tensors="tf").pixel_values
>>> # create random boolean mask of shape (batch_size, num_patches)
>>> bool_masked_pos = tf.cast(tf.random.uniform((1, num_patches), minval=0, maxval=2, dtype=tf.int32), tf.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]
TFDeiTForImageClassification
class transformers.TFDeiTForImageClassification
< 源代码 >( config: DeiTConfig )
参数
- config (DeiTConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
DeiT Transformer 模型,顶部带有一个图像分类头 (在 [CLS] 标记的最终隐藏状态上加一个线性层),例如用于 ImageNet。
这个模型是一个 TensorFlow keras.layers.Layer。像使用常规 TensorFlow 模块一样使用它,并参考 TensorFlow 文档了解所有与常规用法和行为相关的事项。
调用
< 源代码 >( pixel_values: tf.Tensor | None = None head_mask: tf.Tensor | None = None labels: tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None interpolate_pos_encoding: bool = False training: bool = False ) → transformers.modeling_tf_outputs.TFImageClassifierOutput
或 tuple(tf.Tensor)
参数
- pixel_values (
tf.Tensor
,形状为(batch_size, num_channels, height, width)
) — 像素值。像素值可以通过 AutoImageProcessor 获取。详见 DeiTImageProcessor.call()。 - head_mask (
tf.Tensor
,形状为(num_heads,)
或(num_layers, num_heads)
,可选) — 用于使自注意力模块中选定的头无效的掩码。掩码值选自[0, 1]
:- 1 表示头未被屏蔽,
- 0 表示头被屏蔽。
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 `attentions`。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 `hidden_states`。 - interpolate_pos_encoding (
bool
, 可选, 默认为False
) — 是否对预训练的位置编码进行插值。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。 - labels (
tf.Tensor
,形状为(batch_size,)
,可选) — 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
范围内。如果config.num_labels == 1
,则计算回归损失(均方损失),如果config.num_labels > 1
,则计算分类损失(交叉熵)。
返回
transformers.modeling_tf_outputs.TFImageClassifierOutput
或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFImageClassifierOutput
或一个 tf.Tensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置(DeiTConfig)和输入。
-
loss (形状为
(1,)
的tf.Tensor
,可选,当提供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, patch_size, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
TFDeiTForImageClassification 的前向方法,重写了 `__call__` 特殊方法。
尽管前向传播的流程需要在此函数内定义,但之后应调用 Module
实例而不是此函数,因为前者会处理前处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, TFDeiTForImageClassification
>>> import tensorflow as tf
>>> from PIL import Image
>>> import requests
>>> keras.utils.set_random_seed(3)
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> # note: we are loading a TFDeiTForImageClassificationWithTeacher from the hub here,
>>> # so the head will be randomly initialized, hence the predictions will be random
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> model = TFDeiTForImageClassification.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> inputs = image_processor(images=image, return_tensors="tf")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_class_idx = tf.math.argmax(logits, axis=-1)[0]
>>> print("Predicted class:", model.config.id2label[int(predicted_class_idx)])
Predicted class: little blue heron, Egretta caerulea
TFDeiTForImageClassificationWithTeacher
class transformers.TFDeiTForImageClassificationWithTeacher
< 源代码 >( config: DeiTConfig )
参数
- config (DeiTConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
DeiT Transformer 模型,顶部带有图像分类头 (一个在线性层上方的 [CLS] 标记的最终隐藏状态,另一个在线性层上方的蒸馏标记的最终隐藏状态),例如用于 ImageNet。
.. 警告:
此模型仅支持推理。尚不支持使用蒸馏(即带教师模型)进行微调。
这个模型是一个 TensorFlow keras.layers.Layer。像使用常规 TensorFlow 模块一样使用它,并参考 TensorFlow 文档了解所有与常规用法和行为相关的事项。
调用
< 源代码 >( pixel_values: tf.Tensor | None = None head_mask: tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None interpolate_pos_encoding: bool = False training: bool = False ) → transformers.models.deit.modeling_tf_deit.TFDeiTForImageClassificationWithTeacherOutput
或 tuple(tf.Tensor)
参数
- pixel_values (
tf.Tensor
,形状为(batch_size, num_channels, height, width)
) — 像素值。像素值可以通过 AutoImageProcessor 获取。详见 DeiTImageProcessor.call()。 - head_mask (
tf.Tensor
,形状为(num_heads,)
或(num_layers, num_heads)
,可选) — 用于使自注意力模块中选定的头无效的掩码。掩码值选自[0, 1]
:- 1 表示头未被屏蔽,
- 0 表示头被屏蔽。
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 `attentions`。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 `hidden_states`。 - interpolate_pos_encoding (
bool
, 可选, 默认为False
) — 是否对预训练的位置编码进行插值。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
返回
transformers.models.deit.modeling_tf_deit.TFDeiTForImageClassificationWithTeacherOutput
或 tuple(tf.Tensor)
一个 transformers.models.deit.modeling_tf_deit.TFDeiTForImageClassificationWithTeacherOutput
或一个 tf.Tensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置(DeiTConfig)和输入。
- logits (
tf.Tensor
,形状为(batch_size, config.num_labels)
) — 作为 cls_logits 和 distillation logits 平均值的预测分数。 - cls_logits (
tf.Tensor
,形状为(batch_size, config.num_labels)
) — 分类头的预测分数(即类标记最终隐藏状态之上的线性层)。 - distillation_logits (
tf.Tensor
,形状为(batch_size, config.num_labels)
) — 蒸馏头的预测分数(即蒸馏标记最终隐藏状态之上的线性层)。 - 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 之后的注意力权重,用于计算自注意力头中的加权平均值。
TFDeiTForImageClassificationWithTeacher 的前向方法,重写了 `__call__` 特殊方法。
尽管前向传播的流程需要在此函数内定义,但之后应调用 Module
实例而不是此函数,因为前者会处理前处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, TFDeiTForImageClassificationWithTeacher
>>> import tensorflow as tf
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image"))
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> model = TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-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])
tabby, tabby cat