Transformers 文档

EfficientFormer

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

EfficientFormer

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

概述

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

该论文的摘要如下:

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

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

文档资源

EfficientFormerConfig

class transformers.EfficientFormerConfig

< >

( depths: List = [3, 2, 6, 4] hidden_sizes: List = [48, 96, 224, 448] downsamples: List = [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), 可选, 默认值为 [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, 可选, 默认值为 32) — meta3D 块中键的大小。
  • attention_ratio (int, 可选, 默认值为 4) — MSHA 块中查询和值的维度与键的维度之比
  • resolution (int, 可选, 默认值为 7) — 每个补丁的大小
  • num_hidden_layers (int, 可选, 默认值为 5) — Transformer 编码器中隐藏层的数量。
  • num_attention_heads (int, 可选, 默认值为 8) — 3D MetaBlock 中每个注意力层的注意力头数。
  • mlp_expansion_ratio (int, 可选, 默认为 4) — MLP 隐藏层维度大小与其输入维度的比率。
  • hidden_dropout_prob (float, 可选, 默认为 0.1) — 嵌入层和编码器中所有全连接层的 dropout 概率。
  • patch_size (int, 可选, 默认为 16) — 每个图像块(patch)的大小(分辨率)。
  • num_channels (int, 可选, 默认为 3) — 输入通道的数量。
  • pool_size (int, 可选, 默认为 3) — 池化层(pooling layers)的卷积核大小。
  • downsample_patch_size (int, 可选, 默认为 3) — 下采样层中图像块(patch)的大小。
  • downsample_stride (int, 可选, 默认为 2) — 下采样层中卷积核的步幅。
  • downsample_pad (int, 可选, 默认为 1) — 下采样层中的填充(padding)。
  • drop_path_rate (int, 可选, 默认为 0) — DropPath 中 dropout 概率的增加速率。
  • num_meta3d_blocks (int, 可选, 默认为 1) — 最后一个阶段中 3D MetaBlock 的数量。
  • distillation (bool, 可选, 默认为 True) — 是否添加蒸馏头。
  • use_layer_scale (bool, 可选, 默认为 True) — 是否缩放 token mixer 的输出。
  • layer_scale_init_value (float, 可选, 默认为 1e-5) — 缩放 token mixer 输出的因子。
  • hidden_act (strfunction, 可选, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持 "gelu", "relu", "selu""gelu_new"
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, 可选, 默认为 1e-12) — layer normalization 层使用的 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

class transformers.EfficientFormerImageProcessor

< >

( do_resize: bool = True size: Optional = None resample: Resampling = <Resampling.BICUBIC: 3> do_center_crop: bool = True do_rescale: bool = True rescale_factor: Union = 0.00392156862745098 crop_size: Dict = None do_normalize: bool = True image_mean: Union = None image_std: Union = None **kwargs )

参数

  • do_resize (bool, 可选, 默认为 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] 可选, 默认为 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 图像处理器。

preprocess

< >

( images: Union do_resize: Optional = None size: Dict = None resample: Resampling = None do_center_crop: bool = None crop_size: int = None do_rescale: Optional = None rescale_factor: Optional = None do_normalize: Optional = None image_mean: Union = None image_std: Union = None return_tensors: Union = None data_format: Union = <ChannelDimension.FIRST: 'channels_first'> input_data_format: Union = None **kwargs )

参数

  • images (ImageInput) — 要预处理的图像。 接受像素值范围为 0 到 255 的单张或批量图像。如果传入的图像像素值介于 0 和 1 之间,请设置 do_rescale=False
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像大小。
  • size (Dict[str, int], 可选, 默认为 self.size) — 字典格式为 {"height": h, "width": w},指定调整大小后输出图像的大小。
  • resample (PILImageResampling 过滤器, 可选, 默认为 self.resample) — 如果调整图像大小,则使用的 PILImageResampling 过滤器,例如 PILImageResampling.BILINEAR。 仅当 do_resize 设置为 True 时才有效。
  • do_center_crop (bool, 可选, 默认为 self.do_center_crop) — 是否对图像进行中心裁剪。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否将图像值重新缩放到 [0 - 1] 之间。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 如果 do_rescale 设置为 True,则用于重新缩放图像的缩放因子。
  • crop_size (Dict[str, int], 可选, 默认为 self.crop_size) — 中心裁剪的大小。 仅当 do_center_crop 设置为 True 时才有效。
  • do_normalize (bool, 可选, 默认为 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, 可选) — 要返回的张量类型。 可以是以下之一:
    • Unset: 返回 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)。
    • Unset: 使用输入图像的通道维度格式。
  • 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
隐藏 Pytorch 内容

EfficientFormerModel

class transformers.EfficientFormerModel

< >

( config: EfficientFormerConfig )

参数

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

裸 EfficientFormer 模型 Transformer,输出原始隐藏状态,顶部没有任何特定的 head。 此模型是 PyTorch nn.Module 子类。 可将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( pixel_values: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (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)) — 序列的第一个 token(分类 token)的最后一层隐藏状态,在通过用于辅助预训练任务的层进一步处理之后。 例如,对于 BERT 系列模型,这会返回分类 token,该 token 在通过线性层和 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 的 forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 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

class transformers.EfficientFormerForImageClassification

< >

( config: EfficientFormerConfig )

参数

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

带有图像分类头的 EfficientFormer 模型 transformer(分类 token 的最终隐藏状态之上的线性层),例如用于 ImageNet。

此模型是 PyTorch nn.Module 子类。 将其用作常规 PyTorch Module,并参考 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( pixel_values: 可选 = None labels: 可选 = None output_attentions: 可选 = None output_hidden_states: 可选 = None return_dict: 可选 = None ) transformers.modeling_outputs.ImageClassifierOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (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,形状为 (batch_size,), 可选) — 用于计算图像分类/回归损失的标签。 索引应在 [0, ..., config.num_labels - 1] 中。 如果 config.num_labels == 1,则计算回归损失(均方误差损失);如果 config.num_labels > 1,则计算分类损失(交叉熵损失)。

返回:

transformers.modeling_outputs.ImageClassifierOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.ImageClassifierOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置 (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 的 forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 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

class transformers.EfficientFormerForImageClassificationWithTeacher

< >

( config: EfficientFormerConfig )

参数

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

带有图像分类头的 EfficientFormer 模型 transformer(分类 token 的最终隐藏状态之上的线性层以及蒸馏 token 的最终隐藏状态之上的线性层),例如用于 ImageNet。

此模型仅支持推理。 尚不支持使用蒸馏(即使用教师模型)进行微调。

此模型是 PyTorch nn.Module 子类。 将其用作常规 PyTorch Module,并参考 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( pixel_values: 可选 = None output_attentions: 可选 = None output_hidden_states: 可选 = None return_dict: 可选 = None ) transformers.models.deprecated.efficientformer.modeling_efficientformer.EfficientFormerForImageClassificationWithTeacherOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 像素值。像素值可以使用 ViTImageProcessor 获得。 详情请参阅 ViTImageProcessor.preprocess()
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。 更多详情请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。 更多详情请参阅返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 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 (形状为 (batch_size, config.num_labels)torch.FloatTensor) — 作为 cls_logits 和 distillation logits 平均值的预测分数。
  • cls_logits (形状为 (batch_size, config.num_labels)torch.FloatTensor) — 分类头的预测分数 (即,类 token 的最终隐藏状态之上的线性层)。
  • distillation_logits (形状为 (batch_size, config.num_labels)torch.FloatTensor) — 蒸馏头的预测分数 (即,蒸馏 token 的最终隐藏状态之上的线性层)。
  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组 (embedding 的输出一个,每一层的输出一个),形状为 (batch_size, sequence_length, hidden_size)。模型在每一层输出的隐藏状态以及初始 embedding 输出。
  • attentions (tuple(torch.FloatTensor), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 元组 (每一层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。

EfficientFormerForImageClassificationWithTeacher 的前向传播方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 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
隐藏 TensorFlow 内容

TFEfficientFormerModel

class transformers.TFEfficientFormerModel

< >

( config: EfficientFormerConfig **kwargs )

参数

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

裸 EfficientFormer 模型 Transformer,输出原始隐藏状态,顶部没有任何特定的 head。此模型是一个 TensorFlow keras.layers.Layer。将其用作常规 TensorFlow 模块,并查阅 TensorFlow 文档以了解与常规用法和行为相关的所有事项。

call

< >

( pixel_values: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None training: bool = False ) transformers.modeling_tf_outputs.TFBaseModelOutputWithPoolingtuple(tf.Tensor)

参数

  • pixel_values ((形状为 (batch_size, num_channels, height, width)tf.Tensor) — 像素值。像素值可以使用 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 (形状为 (batch_size, sequence_length, hidden_size)tf.Tensor) — 模型最后一层的输出处的隐藏状态序列。

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

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

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

    模型在每一层输出的隐藏状态以及初始 embedding 输出。

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

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

TFEfficientFormerModel 的前向传播方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 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

class transformers.TFEfficientFormerForImageClassification

< >

( config: EfficientFormerConfig )

参数

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

EfficientFormer 模型 Transformer,在池化的最后隐藏状态之上带有一个图像分类 head,例如用于 ImageNet。

此模型是一个 TensorFlow keras.layers.Layer。将其用作常规 TensorFlow 模块,并查阅 TensorFlow 文档以了解与常规用法和行为相关的所有事项。

call

< >

( pixel_values: Optional = None labels: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None training: bool = False ) transformers.modeling_tf_outputs.TFImageClassifierOutputtuple(tf.Tensor)

参数

  • pixel_values ((形状为 (batch_size, num_channels, height, width)tf.Tensor) — 像素值。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 EfficientFormerImageProcessor.call()
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是一个普通的元组。
  • labels (形状为 (batch_size,)tf.Tensor, 可选) — 用于计算图像分类/回归损失的标签。索引应在 [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 (形状为 (1,)tf.Tensor, 可选, 当提供 labels 时返回) — 分类 (或回归,如果 config.num_labels==1) 损失。

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

  • hidden_states (tuple(tf.Tensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — tf.Tensor 元组 (embedding 的输出一个,如果模型有 embedding 层,+ 每一阶段的输出一个),形状为 (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__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 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

class transformers.TFEfficientFormerForImageClassificationWithTeacher

< >

( config: EfficientFormerConfig )

参数

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

带有图像分类头的 EfficientFormer 模型 Transformer(图像分类头是最终隐藏状态之上的线性层和蒸馏 token 的最终隐藏状态之上的线性层),例如用于 ImageNet。

.. warning:: 此模型仅支持推理。尚不支持使用蒸馏(即使用教师模型)进行微调。

此模型是一个 TensorFlow keras.layers.Layer。将其用作常规 TensorFlow 模块,并查阅 TensorFlow 文档以了解与常规用法和行为相关的所有事项。

call

< >

( pixel_values: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = 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__ 特殊方法。

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

  • EfficientFormerForImageClassificationWithTeacher输出类型。 logits (tf.Tensor,形状为 (batch_size, config.num_labels)) — 作为 cls_logits 和 蒸馏 logits 平均值的预测分数。 cls_logits (tf.Tensor,形状为 (batch_size, config.num_labels)) — 分类头的预测分数(即类 token 的最终隐藏状态之上的线性层)。 distillation_logits (tf.Tensor,形状为 (batch_size, config.num_labels)) — 蒸馏头的预测分数(即蒸馏 token 的最终隐藏状态之上的线性层)。 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 之后的注意力权重,用于计算自注意力头中的加权平均值。

示例

>>> 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
< > GitHub 上更新