Transformers documentation

ビジョンエンコーダーデコーダーモデル

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年9月21日にHF papersで公開され、2021年10月13日にHugging Face Transformersに貢献されました。

ビジョンエンコーダーデコーダーモデル

FlashAttention SDPA

概要

VisionEncoderDecoderModel は、事前学習済みの Transformer ベースのビジョンモデル(例: ViT、BEiT、DeiT、Swin)をエンコーダーとして、事前学習済みの言語モデル(例: RoBERTa、GPT2、BERT、DistilBERT)をデコーダーとして使用して、画像からテキストへの変換モデルを初期化するために使用できます。

事前学習済みチェックポイントを用いた画像からテキストシーケンスへのモデルの初期化の有効性は、Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei による TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models などにおいて示されています。

このような VisionEncoderDecoderModel の学習/ファインチューニングが完了した後、他のモデルと同様に保存/読み込みを行うことができます(詳細は以下の例を参照してください)。

アプリケーションの例として、画像キャプション生成があります。このタスクでは、エンコーダーが画像をエンコードし、その後、自己回帰型言語モデルがキャプションを生成します。別の例としては、文字認識(OCR)があります。VisionEncoderDecoderModel のインスタンスである TrOCR を参照してください。

モデル設定からVisionEncoderDecoderModelをランダムに初期化

VisionEncoderDecoderModel は、エンコーダーとデコーダーの設定からランダムに初期化できます。次の例では、エンコーダーにデフォルトの ViTModel 設定、デコーダーにデフォルトの BertForCausalLM 設定を使用して、これを行う方法を示します。

from transformers import BertConfig, VisionEncoderDecoderConfig, VisionEncoderDecoderModel, ViTConfig


config_encoder = ViTConfig()
config_decoder = BertConfig()

config = VisionEncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder)
model = VisionEncoderDecoderModel(config=config)

事前学習済みエンコーダーと事前学習済みデコーダーからVisionEncoderDecoderModelを初期化

VisionEncoderDecoderModel は、事前学習済みのエンコーダーチェックポイントと事前学習済みのデコーダーチェックポイントから初期化できます。事前学習済みの Transformer ベースのビジョンモデル、例えば Swin はエンコーダーとして使用でき、事前学習済みのオートエンコーディングモデル、例えば BERT、事前学習済みの因果言語モデル、例えば GPT2、およびシーケンスツーシーケンスモデルの事前学習済みのデコーダー部分、例えば BART のデコーダーは、デコーダーとして使用できます。 デコーダーとしてどのアーキテクチャを選択するかによって、クロスアテンション層がランダムに初期化される場合があります。 事前学習済みのエンコーダーとデコーダーチェックポイントから VisionEncoderDecoderModel を初期化するには、Warm-starting-encoder-decoder ブログ記事に示されているように、下流タスクでのファインチューニングが必要です。 これを行うために、VisionEncoderDecoderModel クラスは VisionEncoderDecoderModel.from_encoder_decoder_pretrained() メソッドを提供しています。

from transformers import VisionEncoderDecoderModel


model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained(
    "microsoft/swin-base-patch4-window7-224-in22k", "google-bert/bert-base-uncased"
)

既存のVisionEncoderDecoderModelチェックポイントをロードして推論を実行する

VisionEncoderDecoderModel クラスのファインチューニング済みチェックポイントを読み込むには、Transformers の他のモデルアーキテクチャと同様に、VisionEncoderDecoderModel が from_pretrained(...) メソッドを提供しています。

推論を実行するには、generateメソッドを使用します。このメソッドは、テキストを自己回帰的に生成することを可能にします。このメソッドは、貪欲法、ビームサーチ、多項分布サンプリングなど、さまざまなデコーディング形式をサポートしています。

import requests
from PIL import Image

from transformers import GPT2TokenizerFast, ViTImageProcessor, VisionEncoderDecoderModel

# load a fine-tuned image captioning model and corresponding tokenizer and image processor
model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning", device_map="auto")
tokenizer = GPT2TokenizerFast.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
image_processor = ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")

# let's perform inference on an image
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
pixel_values = image_processor(image, return_tensors="pt").to(model.device).pixel_values

# autoregressively generate caption (uses greedy decoding by default)
generated_ids = model.generate(pixel_values)
generated_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
print(generated_text)
a cat laying on a blanket next to a cat laying on a bed

トレーニング

モデルが作成されると、(画像, テキスト) のペアからなるデータセット上で、BART や T5 など他のエンコーダー・デコーダーモデルと同様にファインチューニングを行うことができます。 ご覧のとおり、損失を計算するには、モデルには 2 つの入力のみが必要です: pixel_values(画像)と labels(エンコードされたターゲットシーケンスの input_ids)です。

from datasets import load_dataset

from transformers import BertTokenizer, VisionEncoderDecoderModel, ViTImageProcessor


image_processor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained(
    "google/vit-base-patch16-224-in21k", "google-bert/bert-base-uncased"
)

model.config.decoder_start_token_id = tokenizer.cls_token_id
model.config.pad_token_id = tokenizer.pad_token_id

dataset = load_dataset("huggingface/cats-image")
image = dataset["test"]["image"][0]
pixel_values = image_processor(image, return_tensors="pt").to(model.device).pixel_values

labels = tokenizer(
    "an image of two cats chilling on a couch",
    return_tensors="pt",
).input_ids

# the forward function automatically creates the correct decoder_input_ids
loss = model(pixel_values=pixel_values, labels=labels).loss

このモデルは nielsr によって提供されました。

VisionEncoderDecoderConfig

class transformers.VisionEncoderDecoderConfig

< >

( 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 = 0id2label: 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 = Noneis_encoder_decoder: bool = Trueencoder: transformers.configuration_utils.PreTrainedConfig | dict | None = Nonedecoder: transformers.configuration_utils.PreTrainedConfig | dict | None = None )

パラメータ

  • is_encoder_decoder (bool、任意、デフォルトはTrue) — モデルがエンコーダー/デコーダーとして使用されるかどうかを示します。
  • encoder (Union[~configuration_utils.PreTrainedConfig, dict]、任意) — エンコーダーのバックボーンの設定オブジェクトまたは辞書です。
  • decoder (Union[~configuration_utils.PreTrainedConfig, dict]、省略可) — デコーダーのバックボーンの設定オブジェクトまたは辞書。

これは、Vision Encoder Decoderモデルの構成を保存するための設定クラスです。指定された引数に基づいてVision Encoder Decoderモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、Noneの構成に類似した設定が得られます。

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

例:

>>> from transformers import BertConfig, ViTConfig, VisionEncoderDecoderConfig, VisionEncoderDecoderModel

>>> # Initializing a ViT & BERT style configuration
>>> config_encoder = ViTConfig()
>>> config_decoder = BertConfig()

>>> config = VisionEncoderDecoderConfig(encoder=config_encoder, decoder=config_decoder)

>>> # Initializing a ViTBert model (with random weights) from a ViT & google-bert/bert-base-uncased style configurations
>>> model = VisionEncoderDecoderModel(config=config)

>>> # Accessing the model configuration
>>> config_encoder = model.config.encoder
>>> config_decoder = model.config.decoder
>>> # set decoder config to causal lm
>>> config_decoder.is_decoder = True
>>> config_decoder.add_cross_attention = True

>>> # Saving the model, including its configuration
>>> model.save_pretrained("my-model")

>>> # loading model and config from pretrained folder
>>> encoder_decoder_config = VisionEncoderDecoderConfig.from_pretrained("my-model")
>>> model = VisionEncoderDecoderModel.from_pretrained("my-model", config=encoder_decoder_config)

from_encoder_decoder_configs

< >

( encoder_config: PreTrainedConfigdecoder_config: PreTrainedConfig**kwargs ) → VisionEncoderDecoderConfig

設定オブジェクトのインスタンス

事前学習済みエンコーダーモデルの設定とデコーダーモデルの設定から、VisionEncoderDecoderConfig(または派生クラス)をインスタンス化します。

VisionEncoderDecoderModel

class transformers.VisionEncoderDecoderModel

< >

( config: transformers.configuration_utils.PreTrainedConfig | None = Noneencoder: transformers.modeling_utils.PreTrainedModel | None = Nonedecoder: transformers.modeling_utils.PreTrainedModel | None = None )

パラメータ

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

特定のヘッドを上に付加せず、生のhidden-statesを出力する、素のVision Encoder Decoder Model。

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

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

forward

< >

( pixel_values: typing.Optional[torch.FloatTensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.BoolTensor] = Noneencoder_outputs: tuple[torch.FloatTensor] | None = Nonepast_key_values: transformers.cache_utils.Cache | None = Nonedecoder_inputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → Seq2SeqLMOutput or tuple(torch.FloatTensor)

パラメータ

  • pixel_values (torch.FloatTensor、形状 (batch_size, num_channels, image_size, image_size)、任意) — 入力画像に対応するテンソルです。ピクセル値は image_processor_class を使用して取得できます。詳細は image_processor_class.__call__ を参照してください(processor_class は画像の処理に image_processor_class を使用します)。
  • decoder_input_ids (torch.LongTensor の形状 (batch_size, target_sequence_length), 、任意) — 語彙におけるデコーダー入力シーケンスのトークンインデックス。インデックスは PreTrainedTokenizer を使用して取得できます。詳細については PreTrainedTokenizer.encode() および PreTrainedTokenizer.call() を参照してください。入力 ID とは? past_key_values を使用する場合、任意で最後の decoder_input_ids のみを入力すれば十分です (past_key_values を参照)。学習時には、モデルがラベルを右にシフトし、-100 を pad_token_id に置き換えて、先頭に decoder_start_token_id を付加することで、decoder_input_ids を自動的に作成します。

    インデックスはPreTrainedTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。

    入力IDとは何ですか?

    past_key_valuesを使用する場合、decoder_input_idsの最後の要素のみを入力すればよい場合があります(past_key_valuesを参照)。

    学習では、decoder_input_ids はモデルによって自動的に作成されます。具体的には、labels を右にシフトし、-100 を pad_token_id に置き換え、先頭に decoder_start_token_id を付加します。

  • decoder_attention_mask (torch.BoolTensor、shape (batch_size, target_sequence_length)、任意) — デフォルトの動作: decoder_input_ids 内の pad トークンを無視するテンソルを生成します。デフォルトでは、causal mask も使用されます。
  • encoder_outputs (tuple[torch.FloatTensor], 任意) — last_hidden_state、任意: hidden_states、任意: attentions のタプルです。 last_hidden_state は形状 (batch_size, sequence_length, hidden_size)、任意)であり、エンコーダーの最終層の出力における隠れ状態のシーケンスです。デコーダーのクロスアテンションで使用されます。
  • past_key_values (~cache_utils.Cache, 省略可) — 逐次デコードを高速化するために使用できる、事前計算された隠れ状態(自己アテンションブロックおよびクロスアテンションブロックのキーとバリュー)。通常、これはデコードの以前の段階でモデルが返した past_key_values であり、 use_cache=True または config.use_cache=True.

    入力として許可されるのは Cache インスタンスのみです。kv cache ガイドを参照してください。 past_key_values が渡されない場合、デフォルトで DynamicCache が初期化されます。

    モデルは、入力として与えられたのと同じキャッシュ形式を出力します。

    past_key_values を使用する場合、すべての input_ids(形状 (batch_size, sequence_length))ではなく、このモデルに過去のキー・バリュー状態が与えられていない未処理の input_ids(形状 (batch_size, unprocessed_length))のみを入力することになります。

  • decoder_inputs_embeds (torch.FloatTensor、shape (batch_size, target_sequence_length, hidden_size)、任意) — decoder_input_ids を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込みルックアップ行列よりも、decoder_input_ids のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。
  • labels (torch.LongTensor、shape (batch_size, sequence_length)、任意) — デコーダーのマスク言語モデリング損失を計算するためのラベル。インデックスは [-100, 0, ..., config.vocab_size] の範囲である必要があります(input_ids の docstring を参照)。インデックスが -100 に設定されたトークンは無視(マスク)され、損失はラベルが [0, ..., config.vocab_size] の範囲にあるトークンに対してのみ計算されます。
  • use_cache (bool、任意) — True に設定すると、past_key_values のキーバリュー状態が返され、デコーディングの高速化に利用できます(past_key_values を参照)。
  • output_attentions (bool, 省略可) — すべてのアテンション層のアテンションテンソルを返すかどうかを指定します。詳細は、返されるテンソルの attentions を参照してください。
  • output_hidden_states (bool, 省略可) — すべての層の hidden states を返すかどうかを指定します。詳細は、返されるテンソルの hidden_states を参照してください。
  • return_dict (bool, 任意) — プレーンなタプルではなく ModelOutput を返すかどうか。

戻り値

Seq2SeqLMOutput または tuple(torch.FloatTensor)

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

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

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

  • loss (torch.FloatTensor、shape (1,)、optional、labels が指定された場合に返されます)— 言語モデリングの損失。

  • logits (torch.FloatTensor、shape (batch_size, sequence_length, config.vocab_size)) — 言語モデリングヘッドの予測スコア(SoftMax 適用前の各語彙トークンのスコア)。

  • past_key_values (EncoderDecoderCache、任意、use_cache=True が渡された場合または config.use_cache=True の場合に返されます) — EncoderDecoderCache のインスタンスです。詳細については、kv cache ガイドを参照してください。

    自己注意ブロックおよび相互注意ブロック内のキーとバリューの事前計算済み隠れ状態(hidden-states)を保持しており、シーケンシャルデコーディングを高速化するために使用できます(past_key_values 入力参照)。

  • decoder_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) です。

    各層の出力および初期埋め込み出力における、デコーダーの隠れ状態。

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

    自己アテンションヘッドにおける加重平均を計算するために使用される、アテンションのsoftmax後のデコーダーのアテンション重み。

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

    クロスアテンション層のアテンション重みは、アテンションのsoftmax適用後に計算され、クロスアテンションヘッドにおける加重平均の計算に使用されます。

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

  • encoder_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) です。

    各層の出力および初期埋め込み出力におけるエンコーダーの隠れ状態。

  • encoder_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 AutoProcessor, VisionEncoderDecoderModel
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image
>>> import torch

>>> processor = AutoProcessor.from_pretrained("microsoft/trocr-base-handwritten")
>>> model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")

>>> # load image from the IAM dataset
>>> url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read())).convert("RGB")

>>> # training
>>> model.config.decoder_start_token_id = processor.tokenizer.eos_token_id
>>> model.config.pad_token_id = processor.tokenizer.pad_token_id
>>> model.config.vocab_size = model.config.decoder.vocab_size

>>> pixel_values = processor(image, return_tensors="pt").pixel_values
>>> text = "hello world"
>>> labels = processor.tokenizer(text, return_tensors="pt").input_ids
>>> outputs = model(pixel_values=pixel_values, labels=labels)
>>> loss = outputs.loss

>>> # inference (generation)
>>> generated_ids = model.generate(pixel_values)
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]

from_encoder_decoder_pretrained

< >

( encoder_pretrained_model_name_or_path: str | None = Nonedecoder_pretrained_model_name_or_path: str | None = None*model_args**kwargs )

パラメータ

  • encoder_pretrained_model_name_or_path (str, 省略可) — 画像エンコーダーを初期化するために必要な情報。次のいずれかです:
    • huggingface.co のモデルリポジトリにホストされている事前学習済みモデルの model id を表す文字列です。例として google/vit-base-patch16-224-in21k があります。
    • save_pretrained() を使用して保存されたモデルの重みを含むディレクトリへのパス。例: ./my_model_directory/
  • decoder_pretrained_model_name_or_path (str, 省略可, デフォルトは None) — テキストデコーダーの初期化に必要な情報。次のいずれかです:
    • huggingface.co のモデルリポジトリにホストされている事前学習済みモデルの model id を示す文字列。
    • save_pretrained() を使用して保存されたモデルの重みを含むディレクトリへのパス。例: ./my_model_directory/
  • model_args (残りの位置引数、任意) — 残りのすべての位置引数は、基盤となるモデルの __init__ メソッドに渡されます。
  • kwargs (残りのキーワード引数の辞書、 省略可能) — 設定オブジェクト(読み込み後)を更新し、モデルを初期化するために使用できます(例: output_attentions=True).
    • エンコーダーの設定を更新するには、各設定パラメータにプレフィックス encoder_ を使用します。
    • デコーダーの設定を更新するには、各設定パラメータにプレフィックス decoder_ を使用します。
    • 親モデルの設定を更新する場合は、各設定パラメータにプレフィックスを使用しないでください。

    configが提供されるか、自動的に読み込まれるかによって、動作が異なります。

事前学習済みモデルのチェックポイントから、ライブラリの1つまたは2つのベースクラスを使用してエンコーダーとデコーダーをインスタンス化します。

モデルはデフォルトでmodel.eval()によって評価モードに設定されています(Dropoutモジュールは無効化されます)。モデルを学習するには、まずmodel.train()でトレーニングモードに戻す必要があります。

例:

>>> from transformers import VisionEncoderDecoderModel

>>> # initialize a vit-bert from a pretrained ViT and a pretrained BERT model. Note that the cross-attention layers will be randomly initialized
>>> model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained(
...     "google/vit-base-patch16-224-in21k", "google-bert/bert-base-uncased"
... )
>>> # saving model after fine-tuning
>>> model.save_pretrained("./vit-bert")
>>> # load fine-tuned model
>>> model = VisionEncoderDecoderModel.from_pretrained("./vit-bert")
Update on GitHub