Transformers 文档

高效前身

高效前身

该模型目前处于维护模式,我们不接受任何更改其代码的新PR。 如果您在运行此模型时遇到任何问题,请重新安装支持此模型的最后一个版本:v4.40.2。 您可以通过运行以下命令来执行此操作:pip install -U transformers==4.40.2

概述

EfficientFormer模型由Yanyu Li, Geng Yuan, Yang Wen, Eric Hu, Georgios Evangelidis, Sergey Tulyakov, Yanzhi Wang, Jian Ren在EfficientFormer: Vision Transformers at MobileNet Speed中提出。EfficientFormer提出了一种维度一致性的纯Transformer模型,可以在移动设备上运行,用于图像分类、目标检测和语义分割等密集预测任务。

论文的摘要如下:

视觉变换器(ViT)在计算机视觉任务中显示出快速进展,在各种基准测试中取得了令人瞩目的结果。然而,由于大量的参数和模型设计,例如注意力机制,基于ViT的模型通常比轻量级卷积网络慢几倍。因此,将ViT部署到实时应用中尤其具有挑战性,特别是在资源受限的硬件上,如移动设备。最近的努力试图通过网络架构搜索或与MobileNet块的混合设计来降低ViT的计算复杂性,但推理速度仍然不尽如人意。这引出了一个重要问题:变换器能否在获得高性能的同时像MobileNet一样快速运行?为了回答这个问题,我们首先重新审视了基于ViT的模型中使用的网络架构和操作符,并识别出低效的设计。然后,我们引入了一种维度一致的纯变换器(不含MobileNet块)作为设计范式。最后,我们进行了延迟驱动的精简,得到了一系列最终模型,称为EfficientFormer。大量实验表明,EfficientFormer在移动设备上的性能和速度方面具有优越性。我们最快的模型EfficientFormer-L1在ImageNet-1K上达到了79.2%的top-1准确率,在iPhone 12(使用CoreML编译)上仅需1.6毫秒的推理延迟,{与MobileNetV2×1.4(1.6毫秒,74.7% top-1)一样快},而我们最大的模型EfficientFormer-L7在仅7.0毫秒的延迟下获得了83.3%的准确率。我们的工作证明,经过适当设计的变换器可以在保持高性能的同时在移动设备上达到极低的延迟。

该模型由novice03Bearnardd贡献。 原始代码可以在这里找到。该模型的TensorFlow版本由D-Roberts添加。

文档资源

EfficientFormerConfig

transformers.EfficientFormerConfig

< >

( depths: typing.List[int] = [3, 2, 6, 4] hidden_sizes: typing.List[int] = [48, 96, 224, 448] downsamples: typing.List[bool] = [True, True, True, True] dim: int = 448 key_dim: int = 32 attention_ratio: int = 4 resolution: int = 7 num_hidden_layers: int = 5 num_attention_heads: int = 8 mlp_expansion_ratio: int = 4 hidden_dropout_prob: float = 0.0 patch_size: int = 16 num_channels: int = 3 pool_size: int = 3 downsample_patch_size: int = 3 downsample_stride: int = 2 downsample_pad: int = 1 drop_path_rate: float = 0.0 num_meta3d_blocks: int = 1 distillation: bool = True use_layer_scale: bool = True layer_scale_init_value: float = 1e-05 hidden_act: str = 'gelu' initializer_range: float = 0.02 layer_norm_eps: float = 1e-12 image_size: int = 224 batch_norm_eps: float = 1e-05 **kwargs )

参数

  • depths (List(int), optional, 默认为 [3, 2, 6, 4]) — 每个阶段的深度。
  • hidden_sizes (List(int), 可选, 默认为 [48, 96, 224, 448]) — 每个阶段的维度.
  • downsamples (List(bool), 可选, 默认为 [True, True, True, True]) — 是否在两个阶段之间对输入进行下采样。
  • dim (int, 可选, 默认为 448) — Meta3D 层中的通道数
  • key_dim (int, optional, 默认为 32) — meta3D 块中键的大小.
  • attention_ratio (int, optional, 默认为 4) — MSHA 块中查询和值的维度与键的维度的比率
  • 分辨率 (int, 可选, 默认为 7) — 每个补丁的大小
  • num_hidden_layers (int, optional, 默认为 5) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, optional, defaults to 8) — 3D MetaBlock中每个注意力层的注意力头数。
  • mlp_expansion_ratio (int, optional, defaults to 4) — MLP的隐藏维度大小与其输入维度大小的比率。
  • hidden_dropout_prob (float, optional, 默认为 0.1) — 嵌入层和编码器中所有全连接层的 dropout 概率。
  • patch_size (int, optional, defaults to 16) — 每个补丁的大小(分辨率)。
  • num_channels (int, optional, defaults to 3) — 输入通道的数量。
  • pool_size (int, optional, defaults to 3) — 池化层的核大小。
  • downsample_patch_size (int, optional, defaults to 3) — 下采样层中补丁的大小。
  • downsample_stride (int, optional, defaults to 2) — 下采样层中卷积核的步长。
  • downsample_pad (int, optional, defaults to 1) — 下采样层中的填充。
  • drop_path_rate (int, optional, defaults to 0) — 在DropPath中增加丢弃概率的速率。
  • num_meta3d_blocks (int, 可选, 默认为 1) — 最后阶段中3D MetaBlocks的数量。
  • 蒸馏 (bool, 可选, 默认为 True) — 是否添加蒸馏头.
  • use_layer_scale (bool, 可选, 默认为 True) — 是否缩放来自token mixers的输出。
  • layer_scale_init_value (float, optional, defaults to 1e-5) — 用于缩放来自token mixers输出的因子。
  • hidden_act (strfunction, 可选, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu""relu""selu""gelu_new"
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • layer_norm_eps (float, optional, defaults to 1e-12) — 层归一化层使用的epsilon值。
  • image_size (int, 可选, 默认为 224) — 每张图片的大小(分辨率)。

这是用于存储EfficientFormerModel配置的配置类。它用于根据指定的参数实例化一个EfficientFormer模型,定义模型架构。使用默认值实例化配置将产生与EfficientFormer snap-research/efficientformer-l1架构类似的配置。

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

示例:

>>> from transformers import EfficientFormerConfig, EfficientFormerModel

>>> # Initializing a EfficientFormer efficientformer-l1 style configuration
>>> configuration = EfficientFormerConfig()

>>> # Initializing a EfficientFormerModel (with random weights) from the efficientformer-l3 style configuration
>>> model = EfficientFormerModel(configuration)

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

EfficientFormerImageProcessor

transformers.EfficientFormerImageProcessor

< >

( do_resize: bool = True size: typing.Optional[typing.Dict[str, int]] = None resample: Resampling = do_center_crop: bool = True do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 crop_size: typing.Dict[str, int] = None 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, defaults to True) — 是否将图像的(高度,宽度)尺寸调整为指定的(size["height"], size["width"])。可以在preprocess方法中通过do_resize参数覆盖此设置。
  • size (dict, 可选, 默认为 {"height" -- 224, "width": 224}): 调整大小后输出图像的尺寸。可以在 preprocess 方法中通过 size 参数覆盖此设置。
  • resample (PILImageResampling, 可选, 默认为 PILImageResampling.BILINEAR) — 如果调整图像大小,则使用的重采样过滤器。可以在 preprocess 方法中通过 resample 参数覆盖。
  • do_center_crop (bool, 可选, 默认为 True) — 是否将图像中心裁剪到指定的 crop_size。可以在 preprocess 方法中被 do_center_crop 覆盖。
  • crop_size (Dict[str, int] optional, 默认为 224) — 应用 center_crop 后输出图像的大小。可以在 preprocess 方法中通过 crop_size 覆盖此设置。
  • do_rescale (bool, 可选, 默认为 True) — 是否通过指定的比例 rescale_factor 重新缩放图像。可以在 preprocess 方法中通过 do_rescale 参数覆盖此设置。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 如果重新缩放图像,则使用的缩放因子。可以在 preprocess 方法中通过 rescale_factor 参数覆盖此值。
  • do_normalize — 是否对图像进行归一化。可以在 preprocess 方法中通过 do_normalize 参数进行覆盖。
  • image_mean (floatList[float], 可选, 默认为 IMAGENET_STANDARD_MEAN) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以通过 preprocess 方法中的 image_mean 参数进行覆盖。
  • image_std (floatList[float], 可选, 默认为 IMAGENET_STANDARD_STD) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以在 preprocess 方法中通过 image_std 参数进行覆盖。

构建一个EfficientFormer图像处理器。

预处理

< >

( 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_center_crop: bool = None crop_size: 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, 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 **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_center_crop (bool, optional, defaults to self.do_center_crop) — 是否对图像进行中心裁剪。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否将图像值缩放到 [0 - 1] 之间。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 如果do_rescale设置为True,则用于重新缩放图像的重新缩放因子。
  • crop_size (Dict[str, int], 可选, 默认为 self.crop_size) — 中心裁剪的大小。仅在 do_center_crop 设置为 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)。

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

Pytorch
Hide Pytorch content

EfficientFormerModel

transformers.EfficientFormerModel

< >

( config: EfficientFormerConfig )

参数

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

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

前进

< >

( pixel_values: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: 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)) — 像素值。像素值可以使用ViTImageProcessor获取。详情请参见 ViTImageProcessor.preprocess().
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

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

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

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

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

示例:

>>> from transformers import AutoImageProcessor, EfficientFormerModel
>>> 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("snap-research/efficientformer-l1-300")
>>> model = EfficientFormerModel.from_pretrained("snap-research/efficientformer-l1-300")

>>> 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, 49, 448]

EfficientFormerForImageClassification

transformers.EfficientFormerForImageClassification

< >

( config: EfficientFormerConfig )

参数

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

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

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

前进

< >

( pixel_values: 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 ) transformers.modeling_outputs.ImageClassifierOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用ViTImageProcessor获取。详情请参见 ViTImageProcessor.preprocess().
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • labels (torch.LongTensor of shape (batch_size,), optional) — 用于计算图像分类/回归损失的标签。索引应在 [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 时),包含各种 元素,具体取决于配置(EfficientFormerConfig)和输入。

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

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

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

示例:

>>> from transformers import AutoImageProcessor, EfficientFormerForImageClassification
>>> 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("snap-research/efficientformer-l1-300")
>>> model = EfficientFormerForImageClassification.from_pretrained("snap-research/efficientformer-l1-300")

>>> 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

EfficientFormerForImageClassificationWithTeacher

transformers.EfficientFormerForImageClassificationWithTeacher

< >

( config: EfficientFormerConfig )

参数

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

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

该模型仅支持推理。目前不支持通过蒸馏(即使用教师模型)进行微调。

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

前进

< >

( pixel_values: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.deprecated.efficientformer.modeling_efficientformer.EfficientFormerForImageClassificationWithTeacherOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用ViTImageProcessor获取。详情请参见 ViTImageProcessor.preprocess().
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.models.deprecated.efficientformer.modeling_efficientformer.EfficientFormerForImageClassificationWithTeacherOutputtuple(torch.FloatTensor)

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

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

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

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

示例:

>>> from transformers import AutoImageProcessor, EfficientFormerForImageClassificationWithTeacher
>>> 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("snap-research/efficientformer-l1-300")
>>> model = EfficientFormerForImageClassificationWithTeacher.from_pretrained("snap-research/efficientformer-l1-300")

>>> 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

TFEfficientFormerModel

transformers.TFEfficientFormerModel

< >

( config: EfficientFormerConfig **kwargs )

参数

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

裸的EfficientFormer模型转换器输出原始隐藏状态,没有任何特定的头部。 这个模型是一个TensorFlow keras.layers.Layer。将其用作常规的 TensorFlow模块,并参考TensorFlow文档以获取与一般使用和行为相关的所有事项。

调用

< >

( pixel_values: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None training: bool = False ) transformers.modeling_tf_outputs.TFBaseModelOutputWithPoolingtuple(tf.Tensor)

参数

  • pixel_values ((tf.Tensor 形状为 (batch_size, num_channels, height, width)) — 像素值。像素值可以使用 AutoImageProcessor 获取。详情请参见 EfficientFormerImageProcessor.call().
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.modeling_tf_outputs.TFBaseModelOutputWithPoolingtuple(tf.Tensor)

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

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

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

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

示例:

>>> from transformers import AutoImageProcessor, TFEfficientFormerModel
>>> 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("snap-research/efficientformer-l1-300")
>>> model = TFEfficientFormerModel.from_pretrained("snap-research/efficientformer-l1-300")

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

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 49, 448]

TFEfficientFormerForImageClassification

transformers.TFEfficientFormerForImageClassification

< >

( config: EfficientFormerConfig )

参数

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

EfficientFormer 模型转换器,顶部带有图像分类头,用于池化的最后隐藏状态,例如用于 ImageNet。

该模型是一个 TensorFlow keras.layers.Layer。将其作为常规的 TensorFlow 模块使用,并参考 TensorFlow 文档以获取与一般使用和行为相关的所有信息。

调用

< >

( pixel_values: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None labels: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None training: bool = False ) transformers.modeling_tf_outputs.TFImageClassifierOutputtuple(tf.Tensor)

参数

  • pixel_values ((tf.Tensor of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见 EfficientFormerImageProcessor.call().
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • 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.TFImageClassifierOutputtuple(tf.Tensor)

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

  • loss (tf.Tensor 形状为 (1,), 可选, 当提供 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 后的注意力权重,用于计算自注意力头中的加权平均值。

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

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

示例:

>>> from transformers import AutoImageProcessor, TFEfficientFormerForImageClassification
>>> 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("snap-research/efficientformer-l1-300")
>>> model = TFEfficientFormerForImageClassification.from_pretrained("snap-research/efficientformer-l1-300")

>>> 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])
LABEL_281

TFEfficientFormerForImageClassificationWithTeacher

transformers.TFEfficientFormerForImageClassificationWithTeacher

< >

( config: EfficientFormerConfig )

参数

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

EfficientFormer 模型转换器,顶部带有图像分类头(在最终隐藏状态顶部的线性层和在蒸馏令牌的最终隐藏状态顶部的线性层),例如用于 ImageNet。

.. 警告:: 此模型仅支持推理。目前不支持通过蒸馏(即使用教师模型)进行微调。

该模型是一个 TensorFlow keras.layers.Layer。将其作为常规的 TensorFlow 模块使用,并参考 TensorFlow 文档以获取与一般使用和行为相关的所有信息。

调用

< >

( pixel_values: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None training: bool = False ) transformers.models.deprecated.efficientformer.modeling_tf_efficientformer.TFEfficientFormerForImageClassificationWithTeacherOutputtuple(tf.Tensor)

参数

  • pixel_values ((tf.Tensor 形状为 (batch_size, num_channels, height, width)) — 像素值。像素值可以使用 AutoImageProcessor 获取。详情请参见 EfficientFormerImageProcessor.call().
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.models.deprecated.efficientformer.modeling_tf_efficientformer.TFEfficientFormerForImageClassificationWithTeacherOutputtuple(tf.Tensor)

一个 transformers.models.deprecated.efficientformer.modeling_tf_efficientformer.TFEfficientFormerForImageClassificationWithTeacherOutput 或一个 tf.Tensor 元组(如果 return_dict=False 被传递或当 config.return_dict=False 时)包含各种元素,具体取决于 配置 (EfficientFormerConfig) 和输入。

TFEfficientFormerForImageClassificationWithTeacher 的 forward 方法,重写了 __call__ 特殊方法。

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

  • 输出 类型为 EfficientFormerForImageClassificationWithTeacher。 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=Trueconfig.output_hidden_states=True 时返回) — tf.Tensor 的元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)。模型在每层输出处的隐藏状态加上初始嵌入输出。 attentions (tuple(tf.Tensor), 可选, 当传递 output_attentions=Trueconfig.output_attentions=True 时返回) — tf.Tensor 的元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

示例:

>>> from transformers import AutoImageProcessor, TFEfficientFormerForImageClassificationWithTeacher
>>> 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("snap-research/efficientformer-l1-300")
>>> model = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained("snap-research/efficientformer-l1-300")

>>> 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])
LABEL_281
< > Update on GitHub