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(数据高效图像 Transformer)是更高效训练的图像分类 Transformer,与原始 ViT 模型相比,需要更少的数据和更少的计算资源。
该论文的摘要如下:
最近,纯粹基于注意力的神经网络被证明可以解决图像理解任务,例如图像分类。然而,这些视觉 Transformer 使用昂贵的基础设施预训练数亿张图像,从而限制了它们的采用。在这项工作中,我们仅通过在 Imagenet 上训练来生成具有竞争力的无卷积 Transformer。我们在不到 3 天的时间内在单台计算机上训练它们。我们的参考视觉 Transformer(86M 参数)在 ImageNet 上实现了 83.1% 的 top-1 准确率(单裁剪评估),且没有外部数据。更重要的是,我们引入了一种特定于 Transformer 的师生策略。它依赖于一个蒸馏令牌,确保学生通过注意力从老师那里学习。我们展示了这种基于令牌的蒸馏的优势,尤其是在使用卷积网络作为教师时。这使我们能够报告在 Imagenet(我们获得了高达 85.2% 的准确率)以及转移到其他任务时与卷积网络相比具有竞争力的结果。我们分享我们的代码和模型。
此模型由 nielsr 贡献。此模型的 TensorFlow 版本由 amyeroberts 添加。
使用技巧
- 与 ViT 相比,DeiT 模型使用所谓的蒸馏令牌,以便有效地从教师(在 DeiT 论文中,这是一个类似 ResNet 的模型)那里学习。蒸馏令牌通过反向传播学习,通过自注意力层与类 ([CLS]) 和补丁令牌交互。
- 微调蒸馏模型有两种方法,要么 (1) 以经典方式,仅将预测头放在类令牌的最终隐藏状态之上,而不使用蒸馏信号,要么 (2) 通过将预测头同时放在类令牌和蒸馏令牌之上。在后一种情况下,[CLS] 预测头使用头部预测和 ground-truth 标签之间的常规交叉熵进行训练,而蒸馏预测头使用硬蒸馏(蒸馏头部预测与教师预测的标签之间的交叉熵)进行训练。在推理时,将两个头部之间的平均预测作为最终预测。(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 包括一个原生的缩放点积注意力 (SDPA) 运算符,作为 torch.nn.functional
的一部分。此函数包含多个实现,可以根据输入和使用的硬件应用。有关更多信息,请参阅 官方文档 或 GPU 推理 页面。
当实现可用时,默认情况下 torch>=2.1.1
使用 SDPA,但您也可以在 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
模型,我们看到了以下推理期间的加速。
批次大小 | 平均推理时间 (ms),eager 模式 | 平均推理时间 (ms),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 由此 示例脚本 和 notebook 支持。
- 另请参阅:图像分类任务指南
除此之外
- DeiTForMaskedImageModeling 由此 示例脚本 支持。
如果您有兴趣提交资源以包含在此处,请随时打开 Pull Request,我们将对其进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。
DeiTConfig
class transformers.DeiTConfig
< source >( 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
, optional, defaults to 3072) — Transformer 编码器中“中间”(即,前馈)层的维度。 - hidden_act (
str
或function
, optional, 默认值为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持"gelu"
,"relu"
,"selu"
和"gelu_new"
。 - hidden_dropout_prob (
float
, optional, 默认值为 0.0) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
float
, optional, 默认值为 0.0) — 注意力概率的 dropout 比率。 - initializer_range (
float
, optional, 默认值为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float
, optional, 默认值为 1e-12) — 层归一化层使用的 epsilon 值。 - image_size (
int
, optional, 默认值为 224) — 每张图片的大小(分辨率)。 - patch_size (
int
, optional, 默认值为 16) — 每个 patch 的大小(分辨率)。 - num_channels (
int
, optional, 默认值为 3) — 输入通道数。 - qkv_bias (
bool
, optional, 默认值为True
) — 是否向 queries, keys 和 values 添加偏置。 - encoder_stride (
int
, optional, 默认值为 16) — 用于 masked image modeling 的解码器头部中,增加空间分辨率的因子。 - pooler_output_size (
int
, optional) — 池化器层的维度。如果为 None,则默认为hidden_size
。 - pooler_act (
str
, optional, 默认值为"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
< source >( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = 3 do_center_crop: bool = True crop_size: typing.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, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None **kwargs )
参数
- do_resize (
bool
, optional, 默认值为True
) — 是否将图像的(高度,宽度)尺寸调整为指定的size
。可以被preprocess
中的do_resize
覆盖。 - size (
Dict[str, int]
optional, 默认值为{"height" -- 256, "width": 256}
):resize
后图像的大小。可以被preprocess
中的size
覆盖。 - resample (
PILImageResampling
过滤器, optional, 默认值为Resampling.BICUBIC
) — 如果调整图像大小,要使用的重采样过滤器。可以被preprocess
中的resample
覆盖。 - do_center_crop (
bool
, optional, 默认值为True
) — 是否对图像进行中心裁剪。如果输入大小在任何边缘都小于crop_size
,则图像将用 0 填充,然后进行中心裁剪。可以被preprocess
中的do_center_crop
覆盖。 - crop_size (
Dict[str, int]
, optional, 默认值为{"height" -- 224, "width": 224}
): 应用中心裁剪时所需的输出大小。可以被preprocess
中的crop_size
覆盖。 - rescale_factor (
int
或float
, optional, 默认值为1/255
) — 如果要重新缩放图像,则使用的缩放因子。可以被preprocess
方法中的rescale_factor
参数覆盖。 - do_rescale (
bool
, optional, 默认值为True
) — 是否按指定的比例rescale_factor
重新缩放图像。可以被preprocess
方法中的do_rescale
参数覆盖。 - do_normalize (
bool
, optional, 默认值为True
) — 是否对图像进行归一化。可以被preprocess
方法中的do_normalize
参数覆盖。 - image_mean (
float
或List[float]
, optional, 默认值为IMAGENET_STANDARD_MEAN
) — 如果要归一化图像,则使用的均值。这是一个浮点数或浮点数列表,其长度为图像中的通道数。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或List[float]
, optional, 默认值为IMAGENET_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: bool = None size: typing.Dict[str, int] = None resample = None do_center_crop: bool = None crop_size: typing.Dict[str, int] = None do_rescale: bool = None rescale_factor: float = None do_normalize: 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: 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
或TensorType
, optional) — 返回的张量类型。 可以是以下之一:None
: 返回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 (
ChannelDimension
或str
, optional, defaults toChannelDimension.FIRST
) — 输出图像的通道维度格式。 可以是以下之一:ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。
- input_data_format (
ChannelDimension
或str
, optional) — 输入图像的通道维度格式。 如果未设置,则通道维度格式将从输入图像中推断。 可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 图像格式为 (height, width)。
预处理单张或批量图像。
DeiTImageProcessorFast
class transformers.DeiTImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )
参数
- do_resize (
bool
, optional, defaults toself.do_resize
) — 是否将图像的(高度,宽度)尺寸调整为指定的size
。 可以被preprocess
方法中的do_resize
参数覆盖。 - size (
dict
, optional, defaults toself.size
) — 调整大小后输出图像的大小。 可以被preprocess
方法中的size
参数覆盖。 - default_to_square (
bool
, optional, defaults toself.default_to_square
) — 如果 size 是整数,是否在调整大小时默认使用正方形图像。 - resample (
PILImageResampling
, optional, defaults toself.resample
) — 如果调整图像大小,则使用的重采样滤波器。 仅当do_resize
设置为True
时才有效。 可以被preprocess
方法中的resample
参数覆盖。 - do_center_crop (
bool
, optional, defaults toself.do_center_crop
) — 是否将图像中心裁剪为指定的crop_size
。 可以被preprocess
方法中的do_center_crop
参数覆盖。 - crop_size (
Dict[str, int]
optional, defaults toself.crop_size
) — 应用center_crop
后输出图像的大小。 可以被preprocess
方法中的crop_size
参数覆盖。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否按指定的比例rescale_factor
重新缩放图像。 可以被preprocess
方法中的do_rescale
参数覆盖。 - rescale_factor (
int
或float
, optional, defaults toself.rescale_factor
) — 如果重新缩放图像,则使用的缩放因子。 仅当do_rescale
设置为True
时才有效。 可以被preprocess
方法中的rescale_factor
参数覆盖。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否标准化图像。 可以被preprocess
方法中的do_normalize
参数覆盖。 可以被preprocess
方法中的do_normalize
参数覆盖。 - image_mean (
float
或List[float]
, optional, defaults toself.image_mean
) — 如果标准化图像,则使用的均值。 这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。 可以被preprocess
方法中的image_mean
参数覆盖。 可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 如果要对图像进行归一化,则使用的标准差。这是一个浮点数或浮点数列表,其长度为图像中的通道数。可以被preprocess
方法中的image_std
参数覆盖。可以被preprocess
方法中的image_std
参数覆盖。 - do_convert_rgb (
bool
, 可选, 默认为self.do_convert_rgb
) — 是否将图像转换为 RGB 格式。 - return_tensors (
str
或TensorType
, 可选, 默认为self.return_tensors
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
ChannelDimension
或str
, 可选, 默认为self.data_format
) — 仅支持ChannelDimension.FIRST
。为与慢速处理器兼容而添加。 - input_data_format (
ChannelDimension
或str
, 可选, 默认为self.input_data_format
) — 输入图像的通道维度格式。如果未设置,则通道维度格式从输入图像推断。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:图像格式为 (height, width)。
- device (
torch.device
, 可选, 默认为self.device
) — 处理图像的设备。如果未设置,则设备从输入图像推断。
构建一个快速的 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']] **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )
参数
- images (
ImageInput
) — 要预处理的图像。 期望是像素值范围为 0 到 255 的单个或一批图像。 如果传入的图像像素值介于 0 和 1 之间,请设置do_rescale=False
。 - do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, 可选, 默认为self.size
) — 描述模型的最大输入维度。 - resample (
PILImageResampling
或InterpolationMode
, 可选, 默认为self.resample
) — 如果调整图像大小,则使用的重采样滤波器。这可以是枚举PILImageResampling
之一。 仅在do_resize
设置为True
时有效。 - do_center_crop (
bool
, 可选, 默认为self.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
Dict[str, int]
, 可选, 默认为self.crop_size
) — 应用center_crop
后输出图像的大小。 - do_rescale (
bool
, 可选, 默认为self.do_rescale
) — 是否对图像进行重新缩放。 - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的缩放因子。 - do_normalize (
bool
, 可选, 默认为self.do_normalize
) — 是否对图像进行归一化。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 用于归一化的图像均值。 仅在do_normalize
设置为True
时有效。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 用于归一化的图像标准差。 仅在do_normalize
设置为True
时有效。 - do_convert_rgb (
bool
, 可选, 默认为self.do_convert_rgb
) — 是否将图像转换为 RGB 格式。 - return_tensors (
str
或TensorType
, 可选, 默认为self.return_tensors
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
ChannelDimension
或str
, 可选, 默认为self.data_format
) — 仅支持ChannelDimension.FIRST
。为与慢速处理器兼容而添加。 - input_data_format (
ChannelDimension
或str
, 可选, 默认为self.input_data_format
) — 输入图像的通道维度格式。如果未设置,则通道维度格式从输入图像推断。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:图像格式为 (height, width)。
- device (
torch.device
, 可选, 默认为self.device
) — 处理图像的设备。如果未设置,则设备从输入图像推断。
预处理单张或批量图像。
DeiTModel
class transformers.DeiTModel
< source >( config: DeiTConfig add_pooling_layer: bool = True use_mask_token: bool = False )
参数
- config (DeiTConfig) — 带有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法来加载模型权重。
裸 DeiT 模型 Transformer 输出原始隐藏状态,顶部没有任何特定的 head。 此模型是 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.FloatTensor
, 形状为(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用 AutoImageProcessor 获得。 详细信息请参阅 DeiTImageProcessor.call()。 - head_mask (
torch.FloatTensor
, 形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定 head 的掩码。 掩码值在[0, 1]
中选择:- 1 表示 head 不被屏蔽,
- 0 表示 head 被屏蔽。
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。 - interpolate_pos_encoding (
bool
, 可选, 默认为False
) — 是否插值预训练的位置编码。 - bool_masked_pos (
torch.BoolTensor
, 形状为(batch_size, num_patches)
, 可选) — 布尔掩码位置。指示哪些 patch 被掩码 (1) 以及哪些未被掩码 (0)。
返回值
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)
) — 序列第一个 token (分类 token) 的最后一层隐藏状态,通过用于辅助预训练任务的层进一步处理后得到。 例如,对于 BERT 系列模型,这将返回通过线性层和 tanh 激活函数处理后的分类 token。 线性层权重在预训练期间从下一句预测(分类)目标中训练得出。 -
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__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应在之后调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, DeiTModel
>>> 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("facebook/deit-base-distilled-patch16-224")
>>> model = DeiTModel.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> 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, 198, 768]
DeiTForMaskedImageModeling
class transformers.DeiTForMaskedImageModeling
< source >( config: DeiTConfig )
参数
- config (DeiTConfig) — 带有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法以加载模型权重。
带有用于掩码图像建模的解码器的 DeiT 模型,如 SimMIM 中提出的。
请注意,我们在 examples directory 中提供了一个脚本,用于在自定义数据上预训练此模型。
此模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch Module,并参阅 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.MaskedImageModelingOutput
或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
, 形状为(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用 AutoImageProcessor 获得。 详细信息请参阅 DeiTImageProcessor.call()。 - head_mask (
torch.FloatTensor
, 形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定 head 的掩码。 掩码值在[0, 1]
中选择:- 1 表示 head 不被屏蔽,
- 0 表示 head 被屏蔽。
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。 - interpolate_pos_encoding (
bool
, 可选, 默认为False
) — 是否插值预训练的位置编码。 - bool_masked_pos (
torch.BoolTensor
, 形状为(batch_size, num_patches)
) — 布尔掩码位置。指示哪些 patch 被掩码 (1) 以及哪些未被掩码 (0)。
返回值
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__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应在之后调用 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
< source >( config: DeiTConfig )
参数
- config (DeiTConfig) — 带有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法以加载模型权重。
带有图像分类 head (最终隐藏状态的 [CLS] token 之上的线性层) 的 DeiT 模型转换器,例如用于 ImageNet。
此模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch Module,并参阅 PyTorch 文档以获取与常规用法和行为相关的所有事项。
forward
< source >( 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.FloatTensor
,形状为(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用 AutoImageProcessor 获取。有关详细信息,请参阅 DeiTImageProcessor.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
。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通元组。 - interpolate_pos_encoding (
bool
,可选,默认为False
) — 是否插值预训练的位置编码。 - labels (
torch.LongTensor
,形状为(batch_size,)
,可选) — 用于计算图像分类/回归损失的标签。索引应为[0, ..., config.num_labels - 1]
。如果config.num_labels == 1
,则计算回归损失(均方损失),如果config.num_labels > 1
,则计算分类损失(交叉熵损失)。
返回值
transformers.modeling_outputs.ImageClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.ImageClassifierOutput 或一个 torch.FloatTensor
元组(如果传递 return_dict=False
或当 config.return_dict=False
时),其中包含各种元素,具体取决于配置 (DeiTConfig) 和输入。
-
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 之后的注意力权重,用于计算自注意力头中的加权平均值。
DeiTForImageClassification 前向传播方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应在之后调用 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
< source >( config: DeiTConfig )
参数
- config (DeiTConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
DeiT 模型 Transformer,顶部带有图像分类头([CLS] 令牌的最终隐藏状态之上的线性层和蒸馏令牌的最终隐藏状态之上的线性层),例如用于 ImageNet。
.. warning:
此模型仅支持推理。尚不支持使用蒸馏(即使用教师模型)进行微调。
此模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch Module,并参阅 PyTorch 文档以获取与常规用法和行为相关的所有事项。
forward
< source >( 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.FloatTensor
,形状为(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用 AutoImageProcessor 获取。有关详细信息,请参阅 DeiTImageProcessor.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
。 - 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 (
torch.FloatTensor
,形状为(batch_size, config.num_labels)
) — 分类头的预测分数(即类令牌的最终隐藏状态之上的线性层)。 - distillation_logits (
torch.FloatTensor
,形状为(batch_size, config.num_labels)
) — 蒸馏头的预测分数(即蒸馏令牌的最终隐藏状态之上的线性层)。 - 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 前向传播方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应在之后调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, DeiTForImageClassificationWithTeacher
>>> 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("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])
tabby, tabby cat
TFDeiTModel
class transformers.TFDeiTModel
< source >( 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 文档以了解所有与通用用法和行为相关的事项。
call
< source >( 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 (形状为
(batch_size, num_channels, height, width)
的tf.Tensor
) — 像素值。像素值可以使用 AutoImageProcessor 获取。 有关详细信息,请参阅 DeiTImageProcessor.call()。 - head_mask (形状为
(num_heads,)
或(num_layers, num_heads)
的tf.Tensor
, 可选) — 用于置零自注意力模块中选定头的掩码。掩码值在[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 (形状为
(batch_size, sequence_length, hidden_size)
的tf.Tensor
) — 模型最后一层的输出处的隐藏状态序列。 -
pooler_output (形状为
(batch_size, hidden_size)
的tf.Tensor
) — 序列的第一个标记(分类标记)的最后一层隐藏状态,由线性层和 Tanh 激活函数进一步处理。 线性层权重从预训练期间的下一个句子预测(分类)目标中训练而来。此输出通常不是输入的语义内容的良好摘要,对于整个输入序列,通常最好使用平均或池化隐藏状态序列。
-
hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 形状为(batch_size, sequence_length, hidden_size)
的tf.Tensor
元组(嵌入输出一个,每层输出一个)。模型在每一层输出以及初始嵌入输出处的隐藏状态。
-
attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的tf.Tensor
元组(每层一个)。注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
TFDeiTModel 前向方法,覆盖 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应在之后调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, TFDeiTModel
>>> 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("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
< source >( config: DeiTConfig )
参数
- config (DeiTConfig) — 带有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
用于掩码图像建模的顶部带有解码器的 DeiT 模型,如 SimMIM 中提出的。 此模型是 TensorFlow keras.layers.Layer。 将其用作常规 TensorFlow 模块,并参阅 TensorFlow 文档以了解与常规用法和行为相关的所有事项。
call
< source >( 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 (形状为
(batch_size, num_channels, height, width)
的tf.Tensor
) — 像素值。像素值可以使用 AutoImageProcessor 获取。 有关详细信息,请参阅 DeiTImageProcessor.call()。 - head_mask (形状为
(num_heads,)
或(num_layers, num_heads)
的tf.Tensor
, 可选) — 用于置零自注意力模块中选定头的掩码。掩码值在[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 (类型为 bool 且形状为
(batch_size, num_patches)
的tf.Tensor
) — 布尔掩码位置。 指示哪些补丁被掩蔽 (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 (形状为
(1,)
的tf.Tensor
, 可选, 当提供bool_masked_pos
时返回) — 重建损失。 - reconstruction (形状为
(batch_size, num_channels, height, width)
的tf.Tensor
) — 重建/完成的图像。 - hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当 config.output_hidden_states=True
): 形状为(batch_size, sequence_length, hidden_size)
的tf.Tensor
元组(对于模型的嵌入输出,如果模型具有嵌入层,则为一个;对于每个阶段的输出,则为一个)。 模型在每个阶段输出处的隐藏状态(也称为特征图)。- attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当 config.output_attentions=True
): 形状为(batch_size, num_heads, patch_size, sequence_length)
的tf.Tensor
元组(每层一个)。 注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
TFDeiTForMaskedImageModeling 前向方法,覆盖 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应在之后调用 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
< source >( config: DeiTConfig )
参数
- config (DeiTConfig) — 带有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
带有图像分类 head (最终隐藏状态的 [CLS] token 之上的线性层) 的 DeiT 模型转换器,例如用于 ImageNet。
此模型是 TensorFlow keras.layers.Layer。 将其用作常规 TensorFlow 模块,并参阅 TensorFlow 文档以了解与常规用法和行为相关的所有事项。
call
< source >( 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 (形状为
(batch_size, num_channels, height, width)
的tf.Tensor
) — 像素值。像素值可以使用 AutoImageProcessor 获取。 有关详细信息,请参阅 DeiTImageProcessor.call()。 - head_mask (
tf.Tensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) — 用于置零自注意力模块中选定头的掩码。 掩码值在[0, 1]
中选择:- 1 表示头 不被掩蔽,
- 0 表示头 被掩蔽。
- output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的hidden_states
。 - interpolate_pos_encoding (
bool
, optional, defaults toFalse
) — 是否对预训练的位置编码进行插值。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是纯元组。 - labels (
tf.Tensor
of shape(batch_size,)
, optional) — 用于计算图像分类/回归损失的标签。 索引应在[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 (
tf.Tensor
of shape(1,)
, optional, returned whenlabels
is provided) — 分类损失(如果 config.num_labels==1,则为回归损失)。 -
logits (
tf.Tensor
of shape(batch_size, config.num_labels)
) — 分类(或回归,如果 config.num_labels==1)得分(在 SoftMax 之前)。 -
hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) —tf.Tensor
的元组(如果模型具有嵌入层,则为嵌入的输出,+ 每个阶段的输出一个),形状为(batch_size, sequence_length, hidden_size)
。 模型在每个阶段输出的隐藏状态(也称为特征图)。 -
attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) —tf.Tensor
的元组(每层一个),形状为(batch_size, num_heads, patch_size, sequence_length)
。注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
TFDeiTForImageClassification
的前向传播方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应在之后调用 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
< source >( config: DeiTConfig )
参数
- config (DeiTConfig) — 带有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法以加载模型权重。
DeiT 模型 Transformer,顶部带有图像分类头([CLS] 令牌的最终隐藏状态之上的线性层和蒸馏令牌的最终隐藏状态之上的线性层),例如用于 ImageNet。
.. warning:
此模型仅支持推理。尚不支持使用蒸馏(即使用教师模型)进行微调。
此模型是 TensorFlow keras.layers.Layer。 将其用作常规 TensorFlow 模块,并参阅 TensorFlow 文档以了解与常规用法和行为相关的所有事项。
call
< source >( 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
of shape(batch_size, num_channels, height, width)
) — 像素值。 像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参见 DeiTImageProcessor.call()。 - head_mask (
tf.Tensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) — 用于置零自注意力模块中选定头的掩码。 掩码值在[0, 1]
中选择:- 1 表示头 不被掩蔽,
- 0 表示头 被掩蔽。
- output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的hidden_states
。 - interpolate_pos_encoding (
bool
, optional, defaults toFalse
) — 是否对预训练的位置编码进行插值。 - return_dict (
bool
, optional) — 是否返回 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
of shape(batch_size, config.num_labels)
) — 预测分数,为 cls_logits 和 distillation logits 的平均值。 - cls_logits (
tf.Tensor
of shape(batch_size, config.num_labels)
) — 分类头的预测分数(即,类 token 的最终隐藏状态之上的线性层)。 - distillation_logits (
tf.Tensor
of shape(batch_size, config.num_labels)
) — 蒸馏头的预测分数(即,蒸馏 token 的最终隐藏状态之上的线性层)。 - hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) —tf.Tensor
的元组(嵌入输出一个 + 每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。 模型在每层输出的隐藏状态,加上初始嵌入输出。 - attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) —tf.Tensor
的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。 注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
TFDeiTForImageClassificationWithTeacher
的前向传播方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应在之后调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, TFDeiTForImageClassificationWithTeacher
>>> 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("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