Transformers 文件
EfficientFormer
並獲得增強的文件體驗
開始使用
EfficientFormer
此模型僅處於維護模式,我們不接受任何更改其程式碼的新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:MobileNet速度的視覺Transformer中提出。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上(使用CoreML編譯)僅有1.6毫秒的推理延遲,其執行速度與MobileNetV2×1.4(1.6毫秒,74.7%的top-1)一樣快,我們最大的模型EfficientFormer-L7在僅7.0毫秒的延遲下獲得了83.3%的準確率。我們的工作證明,設計合理的Transformer可以在移動裝置上實現極低的延遲,同時保持高效能。
該模型由novice03和Bearnardd貢獻。原始程式碼可以在這裡找到。此模型的TensorFlow版本由D-Roberts新增。
文件資源
EfficientFormerConfig
類 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) — 每個補丁的大小(解析度)。 - num_channels (
int
, 可選, 預設為 3) — 輸入通道數。 - pool_size (
int
, 可選, 預設為 3) — 池化層的核心大小。 - downsample_patch_size (
int
, 可選, 預設為 3) — 下采樣層中補丁的大小。 - downsample_stride (
int
, 可選, 預設為 2) — 下采樣層中卷積核的步長。 - downsample_pad (
int
, 可選, 預設為 1) — 下采樣層中的填充。 - 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 (
str
或function
, 可選, 預設為"gelu"
) — 編碼器和池化器中的非線性啟用函式(函式或字串)。如果為字串,則支援"gelu"
、"relu"
、"selu"
和"gelu_new"
。 - initializer_range (
float
, 可選, 預設為 0.02) — 用於初始化所有權重矩陣的截斷正態初始化器的標準差。 - layer_norm_eps (
float
, 可選, 預設為 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
EfficientFormer影像處理器
類 transformers.EfficientFormerImageProcessor
< 源 >( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BICUBIC: 3> do_center_crop: bool = True do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 crop_size: typing.Optional[dict[str, int]] = None do_normalize: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None **kwargs )
引數
- do_resize (
bool
, 可選, 預設為True
) — 是否將影像的(高度,寬度)尺寸調整為指定的(size["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 (
int
或float
, 可選, 預設為1/255
) — 如果縮放影像,使用的縮放因子。可以透過preprocess
方法中的rescale_factor
引數覆蓋。 - do_normalize — 是否對影像進行歸一化。可以透過
preprocess
方法中的do_normalize
引數覆蓋。 - image_mean (
float
或list[float]
, 可選, 預設為IMAGENET_STANDARD_MEAN
) — 如果對影像進行歸一化,使用的均值。這是一個浮點數或浮點數列表,其長度與影像中的通道數相同。可以透過preprocess
方法中的image_mean
引數覆蓋。 - image_std (
float
或list[float]
, 可選, 預設為IMAGENET_STANDARD_STD
) — 如果對影像進行歸一化,使用的標準差。這是一個浮點數或浮點數列表,其長度與影像中的通道數相同。可以透過preprocess
方法中的image_std
引數覆蓋。
構建EfficientFormer影像處理器。
預處理
< 源 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample: Resampling = None do_center_crop: typing.Optional[bool] = None crop_size: typing.Optional[int] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = 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 (
float
或list[float]
, 可選, 預設為self.image_mean
) — 如果do_normalize
設定為True
,則使用的影像均值。 - image_std (
float
或list[float]
, 可選, 預設為self.image_std
) — 如果do_normalize
設定為True
,則使用的影像標準差。 - return_tensors (
str
或TensorType
, 可選) — 返回張量的型別。可以是以下之一:- 未設定:返回
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
, 可選, 預設為ChannelDimension.FIRST
) — 輸出影像的通道維度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:影像格式為 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:影像格式為 (height, width, num_channels)。- 未設定:使用輸入影像的通道維度格式。
- input_data_format (
ChannelDimension
或str
, 可選) — 輸入影像的通道維度格式。如果未設定,則從輸入影像推斷通道維度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:影像格式為 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:影像格式為 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:影像格式為 (height, width)。
預處理一張或一批影像。
EfficientFormer模型
class 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.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
引數
- pixel_values (形狀為
(batch_size, num_channels, height, width)
的torch.FloatTensor
) — 畫素值。畫素值可以透過 ViTImageProcessor 獲取。有關詳細資訊,請參閱 ViTImageProcessor.preprocess()。 - output_attentions (
bool
, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參閱返回張量中的attentions
。 - output_hidden_states (
bool
, 可選) — 是否返回所有層的隱藏狀態。有關詳細資訊,請參閱返回張量中的hidden_states
。 - return_dict (
bool
, 可選) — 是否返回 ModelOutput 而不是純元組。
返回
transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(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 (形狀為
(batch_size, hidden_size)
的torch.FloatTensor
) — 序列中第一個標記(分類標記)的最後一層隱藏狀態,經過用於輔助預訓練任務的層進一步處理後得到。例如,對於 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")
>>> 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 模型變壓器,頂部帶有影像分類頭部(在 [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.ImageClassifierOutput 或 tuple(torch.FloatTensor)
引數
- pixel_values (形狀為
(batch_size, num_channels, height, width)
的torch.FloatTensor
) — 畫素值。畫素值可以透過 ViTImageProcessor 獲取。有關詳細資訊,請參閱 ViTImageProcessor.preprocess()。 - output_attentions (
bool
, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參閱返回張量中的attentions
。 - output_hidden_states (
bool
, 可選) — 是否返回所有層的隱藏狀態。有關詳細資訊,請參閱返回張量中的hidden_states
。 - return_dict (
bool
, 可選) — 是否返回 ModelOutput 而不是純元組。 - labels (形狀為
(batch_size,)
的torch.LongTensor
, 可選) — 用於計算影像分類/迴歸損失的標籤。索引應在[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
),包含根據配置 (EfficientFormerConfig) 和輸入而定的各種元素。
-
loss (形狀為
(1,)
的torch.FloatTensor
,可選,當提供labels
時返回) — 分類損失(如果 config.num_labels==1,則為迴歸損失)。 -
logits (形狀為
(batch_size, config.num_labels)
的torch.FloatTensor
) — 分類(如果 config.num_labels==1,則為迴歸)分數(SoftMax 之前)。 -
hidden_states (
tuple(torch.FloatTensor)
, 可選, 當傳遞output_hidden_states=True
或config.output_hidden_states=True
時返回) —torch.FloatTensor
元組(一個用於嵌入層的輸出,如果模型有嵌入層,加上每個階段的一個輸出),形狀為(batch_size, sequence_length, hidden_size)
。模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。 -
attentions (
tuple(torch.FloatTensor)
, 可選, 當傳遞output_attentions=True
或config.output_attentions=True
時返回) —torch.FloatTensor
元組(每個層一個),形狀為(batch_size, num_heads, patch_size, sequence_length)
。注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。
EfficientFormerForImageClassification 的前向傳播方法,重寫了 __call__
特殊方法。
雖然必須在此函式中定義前向傳播的配方,但之後應呼叫 Module
例項而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則默默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, EfficientFormerForImageClassification
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> 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 模型變壓器,頂部帶有影像分類頭部(在 [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.EfficientFormerForImageClassificationWithTeacherOutput
或 tuple(torch.FloatTensor)
引數
- pixel_values (形狀為
(batch_size, num_channels, height, width)
的torch.FloatTensor
) — 畫素值。畫素值可以透過 ViTImageProcessor 獲取。有關詳細資訊,請參閱 ViTImageProcessor.preprocess()。 - output_attentions (
bool
, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參閱返回張量中的attentions
。 - output_hidden_states (
bool
, 可選) — 是否返回所有層的隱藏狀態。有關詳細資訊,請參閱返回張量中的hidden_states
。 - return_dict (
bool
, 可選) — 是否返回 ModelOutput 而不是純元組。
返回
transformers.models.deprecated.efficientformer.modeling_efficientformer.EfficientFormerForImageClassificationWithTeacherOutput
或 tuple(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 和蒸餾 logits 平均值的預測分數。 - cls_logits (形狀為
(batch_size, config.num_labels)
的torch.FloatTensor
) — 分類頭部(即類標記最終隱藏狀態頂部線性層)的預測分數。 - distillation_logits (形狀為
(batch_size, config.num_labels)
的torch.FloatTensor
) — 蒸餾頭部(即蒸餾標記最終隱藏狀態頂部線性層)的預測分數。 - hidden_states (
tuple(torch.FloatTensor)
, 可選, 當傳遞output_hidden_states=True
或config.output_hidden_states=True
時返回) —torch.FloatTensor
元組(一個用於嵌入層的輸出 + 一個用於每個層輸出),形狀為(batch_size, sequence_length, hidden_size)
。模型在每個層輸出的隱藏狀態,加上初始嵌入輸出。 - attentions (
tuple(torch.FloatTensor)
, 可選, 當傳遞output_attentions=True
或config.output_attentions=True
時返回) —torch.FloatTensor
元組(每個層一個),形狀為(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均。
EfficientFormerForImageClassificationWithTeacher 的前向傳播方法,重寫了 __call__
特殊方法。
雖然必須在此函式中定義前向傳播的配方,但之後應呼叫 Module
例項而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則默默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, EfficientFormerForImageClassificationWithTeacher
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> 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
TFEfficientFormerModel
class 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.TFBaseModelOutputWithPooling 或 tuple(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.TFBaseModelOutputWithPooling 或 tuple(tf.Tensor)
一個 transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或一個 tf.Tensor
元組(如果傳遞了 return_dict=False
或 config.return_dict=False
),包含根據配置 (EfficientFormerConfig) 和輸入而定的各種元素。
-
last_hidden_state (
tf.Tensor
of shape(batch_size, sequence_length, hidden_size)
) — 模型最後一層輸出的隱藏狀態序列。 -
pooler_output (形狀為
(batch_size, hidden_size)
的tf.Tensor
) — 序列中第一個標記(分類標記)的最後一層隱藏狀態,經由線性層和 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")
>>> 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
< source >( config: EfficientFormerConfig )
引數
- config (EfficientFormerConfig) — 模型配置類,包含模型的所有引數。用配置檔案初始化不會載入與模型關聯的權重,只會載入配置。要載入模型權重,請檢視 from_pretrained() 方法。
EfficientFormer 模型轉換器,在池化後的最後一個隱藏狀態之上帶有一個影像分類頭,例如用於 ImageNet。
此模型是一個 TensorFlow keras.layers.Layer。將其用作常規的 TensorFlow 模組,並參考 TensorFlow 文件瞭解所有與通用用法和行為相關的事項。
呼叫
< source >( 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.TFImageClassifierOutput
或 tuple(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.TFImageClassifierOutput
或 tuple(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 (
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"))
>>> 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
< source >( config: EfficientFormerConfig )
引數
- config (EfficientFormerConfig) — 模型配置類,包含模型的所有引數。用配置檔案初始化不會載入與模型關聯的權重,只會載入配置。要載入模型權重,請檢視 from_pretrained() 方法。
EfficientFormer 模型轉換器,在頂部帶有影像分類頭(在最終隱藏狀態之上有一個線性層,在蒸餾標記的最終隱藏狀態之上有一個線性層),例如用於 ImageNet。
.. 警告:: 此模型僅支援推理。尚不支援帶有蒸餾的微調(即帶有教師模型)。
此模型是一個 TensorFlow keras.layers.Layer。將其用作常規的 TensorFlow 模組,並參考 TensorFlow 文件瞭解所有與通用用法和行為相關的事項。
呼叫
< source >( 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.TFEfficientFormerForImageClassificationWithTeacherOutput
或 tuple(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.models.deprecated.efficientformer.modeling_tf_efficientformer.TFEfficientFormerForImageClassificationWithTeacherOutput
或 tuple(tf.Tensor)
一個 transformers.models.deprecated.efficientformer.modeling_tf_efficientformer.TFEfficientFormerForImageClassificationWithTeacherOutput
或一個 tf.Tensor
的元組(如果傳入 return_dict=False
或當 config.return_dict=False
時),根據配置(EfficientFormerConfig)和輸入包含各種元素。
TFEfficientFormerForImageClassificationWithTeacher 的前向傳播方法,覆蓋了 __call__
特殊方法。
雖然必須在此函式中定義前向傳播的配方,但之後應呼叫 Module
例項而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則默默地忽略它們。
- 輸出型別為 EfficientFormerForImageClassificationWithTeacher。 logits (形狀為
(batch_size, config.num_labels)
的tf.Tensor
) — 作為 cls_logits 和蒸餾 logits 平均值的預測分數。 cls_logits (形狀為(batch_size, config.num_labels)
的tf.Tensor
) — 分類頭(即在類標記的最終隱藏狀態之上的線性層)的預測分數。 distillation_logits (形狀為(batch_size, config.num_labels)
的tf.Tensor
) — 蒸餾頭(即在蒸餾標記的最終隱藏狀態之上的線性層)的預測分數。 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"))
>>> 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