Transformers documentation
エンコーダーデコーダーモデル
このモデルは2017年6月12日にHF papersで公開され、2020年11月16日にHugging Face Transformersに貢献されました。
エンコーダーデコーダーモデル
EncoderDecoderModel は、事前学習済みオートエンコーダーと事前学習済み自己回帰モデルを用いて、シーケンスツーシーケンスモデルを初期化します。事前学習済みエンコーダーによるテキスト要約では、BertModel をエンコーダーおよびデコーダーとして使用しており、シーケンス生成タスクにおいてその有効性が示されています。
このモデルは thomwolf によって提供されました。
Encoder Decoder モデルの右側サイドバーをクリックすると、Encoder Decoder をさまざまな言語タスクに適用する方法の追加例を確認できます。
以下の例では、Pipeline、AutoModel、およびコマンドラインからテキストを生成する方法を示しています。
from transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("patrickvonplaten/bert2bert-cnn_dailymail-fp16")
model = AutoModelForCausalLM.from_pretrained("patrickvonplaten/bert2bert-cnn_dailymail-fp16", device_map="auto",attn_implementation="sdpa")
text = "Plants create energy through a process known as photosynthesis. This involves capturing sunlight and converting carbon dioxide and water into glucose and oxygen."
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True).to(model.device)
summary = model.generate(**inputs, max_length=60, num_beams=4, early_stopping=True)
print(tokenizer.decode(summary[0], skip_special_tokens=True))注記
- EncoderDecoderModel は、事前学習済みの任意のエンコーダーとデコーダーを使用して初期化できます。ただし、デコーダーのアーキテクチャによっては、クロスアテンション層がランダムに初期化される場合があります。
これらのモデルは、このブログ記事で説明されているように、下流のファインチューニングが必要です。エンコーダーとデコーダーのチェックポイントを組み合わせるには、from_encoder_decoder_pretrained()を使用してください。
from transformers import BertTokenizer, EncoderDecoderModel
tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
model = EncoderDecoderModel.from_encoder_decoder_pretrained(
"google-bert/bert-base-uncased",
"google-bert/bert-base-uncased"
)- Encoder Decoderモデルは、BARTやT5など、他のencoder-decoderモデルと同様にファインチューニングできます。損失を計算するには、
input_idsとlabelsの2つの入力のみが必要です。より詳細な学習の例については、このノートブックを参照してください。
from transformers import BertTokenizer, EncoderDecoderModel
tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
model = EncoderDecoderModel.from_encoder_decoder_pretrained("google-bert/bert-base-uncased", "google-bert/bert-base-uncased")
model.config.decoder_start_token_id = tokenizer.cls_token_id
model.config.pad_token_id = tokenizer.pad_token_id
input_ids = tokenizer(
"The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side.During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest man-made structure in the world, a title it held for 41 years until the Chrysler Building in New York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the Chrysler Building by 5.2 metres (17 ft).Excluding transmitters, the Eiffel Tower is the second tallest free-standing structure in France after the Millau Viaduct.",
return_tensors="pt",
).input_ids
labels = tokenizer(
"the eiffel tower surpassed the washington monument to become the tallest structure in the world. it was the first structure to reach a height of 300 metres in paris in 1930. it is now taller than the chrysler building by 5. 2 metres ( 17 ft ) and is the second tallest free - standing structure in paris.",
return_tensors="pt",
).input_ids
# the forward function automatically creates the correct decoder_input_ids
loss = model(input_ids=input_ids, labels=labels).loss- EncoderDecoderModel は、以下に示すように、エンコーダーとデコーダーの設定からランダムに初期化できます。
from transformers import BertConfig, EncoderDecoderConfig, EncoderDecoderModel
config_encoder = BertConfig()
config_decoder = BertConfig()
config = EncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder)
model = EncoderDecoderModel(config=config)- Encoder Decoder Modelは、以下に示すように翻訳にも使用できます。
from transformers import AutoTokenizer, EncoderDecoderModel
# Load a pre-trained translation model
model_name = "google/bert2bert_L-24_wmt_en_de"
tokenizer = AutoTokenizer.from_pretrained(model_name, pad_token="<pad>", eos_token="</s>", bos_token="<s>")
model = EncoderDecoderModel.from_pretrained(model_name, device_map="auto")
# Input sentence to translate
input_text = "Plants create energy through a process known as"
# Encode the input text
inputs = tokenizer(input_text, return_tensors="pt", add_special_tokens=False).to(model.device).input_ids
# Generate the translated output
outputs = model.generate(inputs)[0]
# Decode the output tokens to get the translated sentence
translated_text = tokenizer.decode(outputs, skip_special_tokens=True)
print("Translated text:", translated_text)EncoderDecoderConfig
class transformers.EncoderDecoderConfig
< source >( 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 | None = Trueencoder: transformers.configuration_utils.PreTrainedConfig | dict | None = Nonedecoder: transformers.configuration_utils.PreTrainedConfig | dict | None = Nonepad_token_id: int | None = Nonedecoder_start_token_id: int | None = None )
パラメータ
- is_encoder_decoder (
bool、任意、デフォルトはTrue) — モデルがエンコーダー/デコーダーとして使用されるかどうかを示します。 - encoder (
Union[~configuration_utils.PreTrainedConfig, dict]、任意) — エンコーダーのバックボーンの設定オブジェクトまたは辞書です。 - decoder (
Union[~configuration_utils.PreTrainedConfig, dict]、省略可) — デコーダーのバックボーンの設定オブジェクトまたは辞書。 - pad_token_id (
int, 任意) — 語彙内でパディングに使用されるトークン ID。 - decoder_start_token_id (
int、任意) — エンコーダー・デコーダーモデルがbosとは異なるトークンでデコーディングを開始する場合、そのトークンのIDです。
これは、Encoder Decoderモデルの設定を保存するための設定クラスです。指定された引数に基づいて Encoder Decoderモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、 と同様の設定が得られます。
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
例:
>>> from transformers import BertConfig, EncoderDecoderConfig, EncoderDecoderModel
>>> # Initializing a BERT google-bert/bert-base-uncased style configuration
>>> config_encoder = BertConfig()
>>> config_decoder = BertConfig()
>>> config = EncoderDecoderConfig(encoder=config_encoder, decoder=config_decoder)
>>> # Initializing a Bert2Bert model (with random weights) from the google-bert/bert-base-uncased style configurations
>>> model = EncoderDecoderModel(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 = EncoderDecoderConfig.from_pretrained("my-model")
>>> model = EncoderDecoderModel.from_pretrained("my-model", config=encoder_decoder_config)from_encoder_decoder_configs
< source >( encoder_config: PreTrainedConfigdecoder_config: PreTrainedConfig**kwargs ) → EncoderDecoderConfig
設定オブジェクトのインスタンス
事前学習済みエンコーダーモデルの設定とデコーダーモデルの設定から、EncoderDecoderConfig(または派生クラス)をインスタンス化します。
EncoderDecoderModel
class transformers.EncoderDecoderModel
< source >( 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を出力する素のEncoder Decoder Model。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: 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 = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonedecoder_inputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = None**kwargs ) → Seq2SeqLMOutput or tuple(torch.FloatTensor)
パラメータ
- input_ids (
torch.LongTensorの形状(batch_size, sequence_length), 、省略可) — 語彙における入力シーケンスのトークンインデックスです。デフォルトではパディングは無視されます。インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。
- attention_mask (
torch.FloatTensorの形状(batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。[0, 1]:- マスクされていないトークンに対して1
- マスクされたトークンに対しては 0 です。
- 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()を参照してください。
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))のみを入力することになります。 - inputs_embeds (
torch.FloatTensor、形状(batch_size, sequence_length, hidden_size)、任意) —input_idsを渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込みルックアップ行列よりも、input_idsのインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。 - 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を参照)。
戻り値
Seq2SeqLMOutput または tuple(torch.FloatTensor)
torch.FloatTensor のタプル、または Seq2SeqLMOutput(return_dict=False が渡された場合、または config.return_dict=False の場合)。設定(EncoderDecoderConfig)や入力に応じて、さまざまな要素で構成されます。
EncoderDecoderModelの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 EncoderDecoderModel, BertTokenizer
>>> import torch
>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> model = EncoderDecoderModel.from_encoder_decoder_pretrained(
... "google-bert/bert-base-uncased", "google-bert/bert-base-uncased"
... ) # initialize Bert2Bert from pre-trained checkpoints
>>> # training
>>> model.config.decoder_start_token_id = tokenizer.cls_token_id
>>> model.config.pad_token_id = tokenizer.pad_token_id
>>> model.config.vocab_size = model.config.decoder.vocab_size
>>> input_ids = tokenizer("This is a really long text", return_tensors="pt").input_ids
>>> labels = tokenizer("This is the corresponding summary", return_tensors="pt").input_ids
>>> outputs = model(input_ids=input_ids, labels=labels)
>>> loss, logits = outputs.loss, outputs.logits
>>> # save and load from pretrained
>>> model.save_pretrained("bert2bert")
>>> model = EncoderDecoderModel.from_pretrained("bert2bert")
>>> # generation
>>> generated = model.generate(input_ids)from_encoder_decoder_pretrained
< source >( 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 を示す文字列。
- 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 EncoderDecoderModel
>>> # initialize a bert2bert from two pretrained BERT models. Note that the cross-attention layers will be randomly initialized
>>> model = EncoderDecoderModel.from_encoder_decoder_pretrained("google-bert/bert-base-uncased", "google-bert/bert-base-uncased")
>>> # saving model after fine-tuning
>>> model.save_pretrained("./bert2bert")
>>> # load fine-tuned model
>>> model = EncoderDecoderModel.from_pretrained("./bert2bert")