Transformers documentation

ViTMAE

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

このモデルは2021年11月11日にHF papersで公開され、2022年1月18日にHugging Face Transformersに貢献されました。

FlashAttention SDPA

ViTMAE

ViTMAE は、画像の大部分(約 75%)をマスクして事前学習を行う自己教師ありビジョンモデルです。エンコーダーは表示されている画像パッチを処理し、デコーダーはエンコードされたパッチとマスクトークンから欠損ピクセルを再構成します。事前学習後、エンコーダーは画像分類や物体検出などの下流タスクに再利用でき、教師あり学習で訓練されたモデルを上回る性能を発揮することがよくあります。

drawing

すべてのオリジナルのViTMAEチェックポイントは、AI at Meta組織の下で確認できます。

ViTMAEをビジョンタスクに適用する方法のより多くの例については、右側のサイドバーにあるViTMAEモデルをクリックしてください。

以下の例では、ViTMAEForPreTraining クラスを使用して欠損ピクセルを再構成する方法を示しています。

AutoModel
import requests
import torch
from PIL import Image

from transformers import ViTImageProcessor, ViTMAEForPreTraining


url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
image = Image.open(requests.get(url, stream=True).raw)

processor = ViTImageProcessor.from_pretrained("facebook/vit-mae-base")
inputs = processor(image, return_tensors="pt").to(model.device)
inputs = {k: v.to(model.device) for k, v in inputs.items()}

model = ViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base", attn_implementation="sdpa", device_map="auto")
with torch.no_grad():
    outputs = model(**inputs)

reconstruction = outputs.logits

注記

  • ViTMAEは通常、2段階で利用されます。まずViTMAEForPreTrainingによる自己教師あり事前学習を行い、その後、デコーダーを破棄してエンコーダーをファインチューニングします。ファインチューニング後、重みはViTForImageClassificationなどのモデルに適用できます。
  • 入力の準備にはViTImageProcessorを使用します。

リソース

ViTMAEConfig

class transformers.ViTMAEConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12intermediate_size: int = 3072hidden_act: str = 'gelu'hidden_dropout_prob: float | int = 0.0attention_probs_dropout_prob: float | int = 0.0initializer_range: float = 0.02layer_norm_eps: float = 1e-12image_size: int | list[int] | tuple[int, int] = 224patch_size: int | list[int] | tuple[int, int] = 16num_channels: int = 3qkv_bias: bool = Truedecoder_num_attention_heads: int = 16decoder_hidden_size: int = 512decoder_num_hidden_layers: int = 8decoder_intermediate_size: int = 2048mask_ratio: float = 0.75norm_pix_loss: bool = False )

パラメータ

  • hidden_size (int、任意、デフォルトは 768) — 隠れ表現の次元数。
  • num_hidden_layers (int、任意、デフォルトは 12) — Transformer デコーダーの隠れ層の数。
  • num_attention_heads (int、任意、デフォルトは12) — Transformerデコーダーの各アテンション層におけるアテンションヘッドの数。
  • intermediate_size (int、任意、デフォルトは3072) — MLP 表現の次元数。
  • hidden_act (str、任意、デフォルトは gelu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、 "relu"、"silu" など。
  • hidden_dropout_prob (Union[float, int]、任意、デフォルト値は0.0) — embeddings、encoder、pooler 内のすべての全結合層における dropout 確率です。
  • attention_probs_dropout_prob (Union[float, int]、任意、デフォルトは 0.0) — アテンション確率のドロップアウト率です。
  • initializer_range (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。
  • layer_norm_eps (float、任意、デフォルトは 1e-12) — レイヤーノーマル層で使用する epsilon です。
  • image_size (Union[int, list[int], tuple[int, int]]、任意、デフォルトは224) — 各画像のサイズ(解像度)。
  • patch_size (Union[int, list[int], tuple[int, int]]、任意、デフォルトは16) — 各パッチのサイズ(解像度)です。
  • num_channels (int、任意、デフォルトは3) — 入力チャネル数。
  • qkv_bias (bool、省略可、デフォルトは True) — クエリ、キー、バリューにバイアスを追加するかどうか。
  • decoder_num_attention_heads (int、任意、デフォルトは16) — Transformerデコーダーの各アテンション層におけるアテンションヘッドの数。
  • decoder_hidden_size (int、任意、デフォルトは512) — 隠れ表現の次元数。
  • decoder_num_hidden_layers (int、任意、デフォルトは 8) — デコーダーの隠れ層の数。
  • decoder_intermediate_size (int、任意、デフォルトは2048) — MLP 表現の次元数。
  • mask_ratio (float、任意、デフォルト値は 0.75) — 入力シーケンスにおけるマスクされたトークンの割合です。
  • norm_pix_loss (bool、任意、デフォルトはFalse) — 正規化されたピクセルで学習するかどうか(論文の Table 3 を参照)。著者の実験では、正規化されたピクセルを使用することで表現の品質が向上しました。

This is the configuration class to store the configuration of a ViTMAEModel. It is used to instantiate a Vit Mae model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the facebook/vit-mae-base

設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。

例:

>>> from transformers import ViTMAEConfig, ViTMAEModel

>>> # Initializing a ViT MAE vit-mae-base style configuration
>>> configuration = ViTMAEConfig()

>>> # Initializing a model (with random weights) from the vit-mae-base style configuration
>>> model = ViTMAEModel(configuration)

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

ViTMAEModel

class transformers.ViTMAEModel

< >

( config: ViTMAEConfig )

パラメータ

特定のヘッドを付加せず、生のhidden-statesを出力する、素のVit Mae Model。

このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Nonenoise: typing.Optional[torch.Tensor] = Noneinterpolate_pos_encoding: bool | None = Noneattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ViTMAEModelOutput or tuple(torch.FloatTensor)

パラメータ

  • pixel_values (torch.Tensor、形状 (batch_size, num_channels, image_size, image_size)、任意) — 入力画像に対応するテンソルです。ピクセル値は ViTImageProcessor を使用して取得できます。詳細については ViTImageProcessor.call() を参照してください(processor_class は画像の処理に ViTImageProcessor を使用します)。
  • noise (torch.FloatTensor、形状 (batch_size, sequence_length)、任意) — 主にテスト目的で使用され、ランダム性を制御して再現性を維持するために用いられます。
  • interpolate_pos_encoding (bool、省略可、デフォルトは False) — 事前学習済みの位置エンコーディングを補間するかどうか。主に、より高い解像度の画像でモデルを使用する場合に用いられます。
  • attention_mask (torch.Tensor の形状 (batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。 [0, 1]:
    • マスクされていないトークンに対して1
    • マスクされたトークンに対しては 0 です。

    アテンションマスクとは?

戻り値

ViTMAEModelOutput または tuple(torch.FloatTensor)

ViTMAEModelOutput、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(ViTMAEConfig)や入力に応じて、さまざまな要素で構成されます。

ViTMAEModelのforwardメソッドは、__call__特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなくModuleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。

  • last_hidden_state (torch.FloatTensor、shape (batch_size, sequence_length, hidden_size)、optional) — モデルの最終層の出力における隠れ状態のシーケンス。

  • mask (torch.FloatTensor、shape (batch_size, sequence_length)) — マスクされるパッチ(1)とされないパッチ(0)を示すテンソル。

  • ids_restore (torch.LongTensor、shape (batch_size, sequence_length)) — シャッフルされたマスク済みパッチの元のインデックスを含むテンソル。

  • hidden_states (tuple[torch.FloatTensor]、optional、output_hidden_states=True が渡された場合または config.output_hidden_states=True の場合に返される) — torch.FloatTensor のタプル(埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ)で、形状は (batch_size, sequence_length, hidden_size) です。

    各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。

  • attentions (tuple[torch.FloatTensor]、optional、output_attentions=True が渡された場合または config.output_attentions=True の場合に返されます) — torch.FloatTensor のタプル(各レイヤーごとに1つ)、形状は (batch_size, num_heads, sequence_length, sequence_length)。

    アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

>>> from transformers import AutoImageProcessor, ViTMAEModel
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> image_processor = AutoImageProcessor.from_pretrained("facebook/vit-mae-base")
>>> model = ViTMAEModel.from_pretrained("facebook/vit-mae-base")

>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state

ViTMAEForPreTraining

クラス transformers.ViTMAEForPreTraining

< >

( config: ViTMAEConfig )

パラメータ

  • config (ViTMAEConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。

自己教師あり事前学習のためにデコーダーを上部に配置したViTMAEモデルのtransformer。

このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Nonenoise: typing.Optional[torch.Tensor] = Noneinterpolate_pos_encoding: bool | None = Noneattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ViTMAEForPreTrainingOutput or tuple(torch.FloatTensor)

パラメータ

  • pixel_values (torch.Tensor、形状 (batch_size, num_channels, image_size, image_size)、任意) — 入力画像に対応するテンソルです。ピクセル値は ViTImageProcessor を使用して取得できます。詳細については ViTImageProcessor.call() を参照してください(processor_class は画像の処理に ViTImageProcessor を使用します)。
  • noise (torch.FloatTensor、形状 (batch_size, sequence_length)、任意) — 主にテスト目的で使用され、ランダム性を制御して再現性を維持するために用いられます。
  • interpolate_pos_encoding (bool、省略可、デフォルトは False) — 事前学習済みの位置エンコーディングを補間するかどうか。主に、より高い解像度の画像でモデルを使用する場合に用いられます。
  • attention_mask (torch.Tensor の形状 (batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。 [0, 1]:
    • マスクされていないトークンに対して1
    • マスクされたトークンに対しては 0 です。

    アテンションマスクとは?

戻り値

ViTMAEForPreTrainingOutput または tuple(torch.FloatTensor)

ViTMAEForPreTrainingOutput、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(ViTMAEConfig)と入力に応じて、さまざまな要素で構成されます。

ViTMAEForPreTrainingのforwardメソッドは、__call__特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなくModuleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。

  • loss (torch.FloatTensor、shape (1,)) — ピクセル再構成損失。

  • logits (torch.FloatTensor、shape (batch_size, sequence_length, patch_size ** 2 * num_channels)) — ピクセル再構成の logits。

  • mask (torch.FloatTensor、shape (batch_size, sequence_length)) — マスクされるパッチ(1)とされないパッチ(0)を示すテンソル。

  • ids_restore (torch.LongTensor、shape (batch_size, sequence_length)) — シャッフルされたマスク済みパッチの元のインデックスを含むテンソル。

  • hidden_states (tuple[torch.FloatTensor]、optional、output_hidden_states=True が渡された場合または config.output_hidden_states=True の場合に返される) — torch.FloatTensor のタプル(埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ)で、形状は (batch_size, sequence_length, hidden_size) です。

    各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。

  • attentions (tuple[torch.FloatTensor]、optional、output_attentions=True が渡された場合または config.output_attentions=True の場合に返されます) — torch.FloatTensor のタプル(各レイヤーごとに1つ)、形状は (batch_size, num_heads, sequence_length, sequence_length)。

    アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

>>> from transformers import AutoImageProcessor, ViTMAEForPreTraining
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read())).convert("RGB")

>>> image_processor = AutoImageProcessor.from_pretrained("facebook/vit-mae-base")
>>> model = ViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base")

>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> loss = outputs.loss
>>> mask = outputs.mask
>>> ids_restore = outputs.ids_restore
Update on GitHub