Transformers 文件

編碼器-解碼器模型

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

編碼器-解碼器模型

PyTorch TensorFlow Flax SDPA

概述

EncoderDecoderModel可用於初始化一個序列到序列模型,其中編碼器可以是任何預訓練的自編碼模型,解碼器可以是任何預訓練的自迴歸模型。

使用預訓練檢查點初始化序列到序列模型在序列生成任務中的有效性已在 Sascha Rothe、Shashi Narayan、Aliaksei Severyn 的論文《利用預訓練檢查點進行序列生成任務》中得到證明。

在訓練/微調這樣一個EncoderDecoderModel後,它可以像任何其他模型一樣儲存/載入(更多資訊請參見示例)。

這種架構的一個應用是利用兩個預訓練的BertModel作為摘要模型的編碼器和解碼器,正如在 Yang Liu 和 Mirella Lapata 的論文《使用預訓練編碼器進行文字摘要》中所示。

從模型配置中隨機初始化 EncoderDecoderModel

EncoderDecoderModel可以從一個編碼器和一個解碼器配置中隨機初始化。在以下示例中,我們展示瞭如何使用預設的BertModel配置作為編碼器,以及預設的 BertForCausalLM 配置作為解碼器。

>>> 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)

從預訓練的編碼器和預訓練的解碼器初始化 EncoderDecoderModel

EncoderDecoderModel可以從一個預訓練的編碼器檢查點和一個預訓練的解碼器檢查點進行初始化。請注意,任何預訓練的自編碼模型(例如BERT)都可以作為編碼器,而預訓練的自編碼模型(例如BERT)、預訓練的因果語言模型(例如GPT2),以及序列到序列模型的預訓練解碼器部分(例如BART的解碼器)都可以用作解碼器。根據您選擇的解碼器架構,交叉注意力層可能會被隨機初始化。從預訓練的編碼器和解碼器檢查點初始化EncoderDecoderModel需要模型在下游任務上進行微調,正如“Warm-starting-encoder-decoder”博文中所展示的。為此,EncoderDecoderModel 類提供了一個 EncoderDecoderModel.from_encoder_decoder_pretrained() 方法。

>>> from transformers import EncoderDecoderModel, BertTokenizer

>>> 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")

載入現有的 EncoderDecoderModel 檢查點並執行推理。

要載入 `EncoderDecoderModel` 類的微調檢查點,EncoderDecoderModel 提供了 `from_pretrained(...)` 方法,就像 Transformers 中的任何其他模型架構一樣。

要執行推理,可以使用 `generate` 方法,該方法允許自迴歸生成文字。此方法支援各種解碼形式,例如貪婪解碼、束搜尋和多項式取樣。

>>> from transformers import AutoTokenizer, EncoderDecoderModel

>>> # load a fine-tuned seq2seq model and corresponding tokenizer
>>> model = EncoderDecoderModel.from_pretrained("patrickvonplaten/bert2bert_cnn_daily_mail")
>>> tokenizer = AutoTokenizer.from_pretrained("patrickvonplaten/bert2bert_cnn_daily_mail")

>>> # let's perform inference on a long piece of text
>>> ARTICLE_TO_SUMMARIZE = (
...     "PG&E stated it scheduled the blackouts in response to forecasts for high winds "
...     "amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were "
...     "scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow."
... )
>>> input_ids = tokenizer(ARTICLE_TO_SUMMARIZE, return_tensors="pt").input_ids

>>> # autoregressively generate summary (uses greedy decoding by default)
>>> generated_ids = model.generate(input_ids)
>>> generated_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> print(generated_text)
nearly 800 thousand customers were affected by the shutoffs. the aim is to reduce the risk of wildfires. nearly 800, 000 customers were expected to be affected by high winds amid dry conditions. pg & e said it scheduled the blackouts to last through at least midday tomorrow.

將PyTorch檢查點載入到TFEncoderDecoderModel中。

TFEncoderDecoderModel.from_pretrained() 目前不支援從 PyTorch 檢查點初始化模型。將 `from_pt=True` 傳遞給此方法會引發異常。如果某個特定的編碼器-解碼器模型只有 PyTorch 檢查點,一個變通方法是

>>> # a workaround to load from pytorch checkpoint
>>> from transformers import EncoderDecoderModel, TFEncoderDecoderModel

>>> _model = EncoderDecoderModel.from_pretrained("patrickvonplaten/bert2bert-cnn_dailymail-fp16")

>>> _model.encoder.save_pretrained("./encoder")
>>> _model.decoder.save_pretrained("./decoder")

>>> model = TFEncoderDecoderModel.from_encoder_decoder_pretrained(
...     "./encoder", "./decoder", encoder_from_pt=True, decoder_from_pt=True
... )
>>> # This is only for copying some specific attributes of this particular model.
>>> model.config = _model.config

訓練

一旦模型被建立,它可以像BART、T5或任何其他編碼器-解碼器模型一樣進行微調。如您所見,模型只需要兩個輸入即可計算損失:`input_ids`(編碼輸入序列的`input_ids`)和`labels`(編碼目標序列的`input_ids`)。

>>> 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

詳細的訓練 colab

該模型由thomwolf貢獻。該模型的TensorFlow和Flax版本由ydshieh貢獻。

EncoderDecoderConfig

class transformers.EncoderDecoderConfig

< >

( **kwargs )

引數

  • kwargs (可選) — 關鍵字引數的字典。特別是:

    • encoder (PretrainedConfig, 可選) — 定義編碼器配置的配置物件例項。
    • decoder (PretrainedConfig, 可選) — 定義解碼器配置的配置物件例項。

EncoderDecoderConfig 是用於儲存 EncoderDecoderModel 配置的配置類。它根據指定的引數例項化一個編碼器-解碼器模型,定義了編碼器和解碼器的配置。

配置物件繼承自 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.from_encoder_decoder_configs(config_encoder, 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

< >

( encoder_config: PretrainedConfig decoder_config: PretrainedConfig **kwargs ) EncoderDecoderConfig

返回

EncoderDecoderConfig

一個配置物件的例項

從預訓練的編碼器模型配置和解碼器模型配置例項化一個 EncoderDecoderConfig(或其派生類)。

Pytorch
隱藏 Pytorch 內容

EncoderDecoderModel

class transformers.EncoderDecoderModel

< >

( config: typing.Optional[transformers.configuration_utils.PretrainedConfig] = None encoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None decoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None )

引數

  • config (PretrainedConfig, 可選) — 包含模型所有引數的模型配置類。使用配置檔案進行初始化不會載入與模型相關的權重,只會載入配置。請查閱 from_pretrained() 方法來載入模型權重。
  • encoder (PreTrainedModel, 可選) — 要使用的編碼器模型。
  • decoder (PreTrainedModel, 可選) — 要使用的解碼器模型。

基礎的編碼器-解碼器模型,輸出原始的隱藏狀態,頂部沒有任何特定的頭。

此模型繼承自 PreTrainedModel。請查閱超類文件,瞭解該庫為其所有模型實現的通用方法(如下載或儲存、調整輸入嵌入大小、修剪頭等)。

此模型也是 PyTorch 的 torch.nn.Module 子類。可以像常規的 PyTorch Module 一樣使用它,並參考 PyTorch 文件瞭解所有與通用用法和行為相關的事項。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.BoolTensor] = None encoder_outputs: typing.Optional[tuple[torch.FloatTensor]] = None past_key_values: typing.Optional[tuple[tuple[torch.FloatTensor]]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None **kwargs ) transformers.modeling_outputs.Seq2SeqLMOutputtuple(torch.FloatTensor)

引數

  • input_ids (torch.LongTensor,形狀為 (batch_size, sequence_length)可選) — 詞彙表中輸入序列標記的索引。預設情況下,填充將被忽略。

    可以使用 AutoTokenizer 獲取索引。有關詳細資訊,請參見 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什麼是輸入ID?

  • 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)。

    在訓練時,模型會自動透過將 labels 右移,將-100替換為 pad_token_id,並在前面加上 decoder_start_token_id 來建立 decoder_input_ids

  • decoder_attention_mask (torch.BoolTensor,形狀為 (batch_size, target_sequence_length)可選) — 預設行為:生成一個忽略 `decoder_input_ids` 中填充標記的張量。預設情況下也會使用因果掩碼。
  • encoder_outputs (tuple[torch.FloatTensor], 可選) — 元組包含 (`last_hidden_state`, *可選*: `hidden_states`, *可選*: `attentions`) `last_hidden_state` 的形狀為 `(batch_size, sequence_length, hidden_size)`,*可選*) 是編碼器最後一層輸出的隱藏狀態序列。用於解碼器的交叉注意力機制。
  • past_key_values (tuple[tuple[torch.FloatTensor]], 可選) — 預先計算的隱藏狀態(自注意力和交叉注意力塊中的鍵和值),可用於加速序列解碼。這通常包含模型在解碼的先前階段返回的 past_key_values,此時 use_cache=Trueconfig.use_cache=True

    支援兩種格式:

    • Cache 例項,請參閱我們的 kv 快取指南
    • 長度為 config.n_layerstuple(torch.FloatTensor) 元組,其中每個元組包含 2 個形狀為 (batch_size, num_heads, sequence_length, embed_size_per_head) 的張量。這也稱為傳統快取格式。

    模型將輸出與輸入相同的快取格式。如果沒有傳遞 past_key_values,將返回傳統快取格式。

    如果使用 past_key_values,使用者可以選擇只輸入最後一個 input_ids(那些沒有為其提供過去鍵值狀態的 `input_ids`),形狀為 (batch_size, 1),而不是所有形狀為 (batch_size, sequence_length)input_ids

  • inputs_embeds (torch.FloatTensor,形狀為 (batch_size, sequence_length, hidden_size)可選) — 可選地,你可以選擇直接傳遞嵌入表示而不是 input_ids。如果你想比模型內部的嵌入查詢矩陣更好地控制如何將 input_ids 索引轉換為相關向量,這會很有用。
  • decoder_inputs_embeds (torch.FloatTensor,形狀為 (batch_size, target_sequence_length, hidden_size)可選) — 可選地,你可以選擇直接傳遞嵌入表示而不是 decoder_input_ids。如果你想比模型內部的嵌入查詢矩陣更好地控制如何將 decoder_input_ids 索引轉換為相關向量,這會很有用。
  • labels (torch.LongTensor,形狀為 (batch_size, sequence_length)可選) — 用於計算解碼器掩碼語言建模損失的標籤。索引應在 [-100, 0, ..., config.vocab_size] 範圍內(參見 input_ids 的文件字串)。索引設定為 -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
  • return_dict (bool, 可選) — 是否返回一個 ModelOutput 而不是一個普通的元組。

返回

transformers.modeling_outputs.Seq2SeqLMOutputtuple(torch.FloatTensor)

一個 transformers.modeling_outputs.Seq2SeqLMOutput 或一個 torch.FloatTensor 元組(如果傳遞了 return_dict=False 或當 config.return_dict=False 時),根據配置(EncoderDecoderConfig)和輸入包含各種元素。

  • loss (torch.FloatTensor,形狀為 (1,)可選,當提供 labels 時返回) — 語言建模損失。

  • logits (形狀為 (batch_size, sequence_length, config.vocab_size)torch.FloatTensor) — 語言建模頭部的預測分數(SoftMax 之前的每個詞彙標記的分數)。

  • past_key_values (EncoderDecoderCache, 可選, 當傳遞 use_cache=True 或當 config.use_cache=True 時返回) — 這是一個 EncoderDecoderCache 例項。更多詳情,請參閱我們的 kv 快取指南

    包含預先計算的隱藏狀態(自注意力塊和交叉注意力塊中的鍵和值),可用於(參見 past_key_values 輸入)加速順序解碼。

  • decoder_hidden_states (tuple(torch.FloatTensor), 可選, 當傳遞 output_hidden_states=True 或當 config.output_hidden_states=True 時返回) — torch.FloatTensor 的元組(如果模型有嵌入層,則一個是嵌入層的輸出,另外每個層的輸出各一個),形狀為 (batch_size, sequence_length, hidden_size)

    解碼器在每一層輸出時的隱藏狀態以及初始嵌入輸出。

  • decoder_attentions (tuple(torch.FloatTensor), 可選, 當傳遞 output_attentions=True 或當 config.output_attentions=True 時返回) — torch.FloatTensor 的元組(每層一個),形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    解碼器的注意力權重,在注意力 softmax 之後,用於計算自注意力頭中的加權平均。

  • cross_attentions (tuple(torch.FloatTensor), 可選, 當傳遞 output_attentions=True 或當 config.output_attentions=True 時返回) — torch.FloatTensor 的元組(每層一個),形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    解碼器交叉注意力層的注意力權重,在注意力 softmax 之後,用於計算交叉注意力頭中的加權平均。

  • encoder_last_hidden_state (torch.FloatTensor,形狀為 (batch_size, sequence_length, hidden_size)可選) — 模型編碼器最後一層輸出的隱藏狀態序列。

  • encoder_hidden_states (tuple(torch.FloatTensor), 可選, 當傳遞 output_hidden_states=True 或當 config.output_hidden_states=True 時返回) — torch.FloatTensor 的元組(如果模型有嵌入層,則一個是嵌入層的輸出,另外每個層的輸出各一個),形狀為 (batch_size, sequence_length, hidden_size)

    編碼器在每一層輸出時的隱藏狀態以及初始嵌入輸出。

  • encoder_attentions (tuple(torch.FloatTensor), 可選, 當傳遞 output_attentions=True 或當 config.output_attentions=True 時返回) — torch.FloatTensor 的元組(每層一個),形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    編碼器的注意力權重,在注意力 softmax 之後,用於計算自注意力頭中的加權平均。

EncoderDecoderModel 的前向方法會覆蓋 __call__ 特殊方法。

儘管前向傳播的流程需要在此函式內定義,但之後應該呼叫 Module 例項而不是這個函式,因為前者會處理前後處理步驟,而後者會靜默地忽略它們。

示例

>>> 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

< >

( encoder_pretrained_model_name_or_path: typing.Optional[str] = None decoder_pretrained_model_name_or_path: typing.Optional[str] = None *model_args **kwargs )

引數

  • encoder_pretrained_model_name_or_path (str, 可選) — 初始化編碼器所需的資訊。可以是:

    • 一個字串,即託管在 huggingface.co 上的模型倉庫中的預訓練模型的 模型 id
    • 一個包含使用 save_pretrained() 儲存的模型權重的 目錄 路徑,例如 ./my_model_directory/
    • 一個 tensorflow 索引檢查點檔案 的路徑或 url(例如,./tf_model/model.ckpt.index)。在這種情況下,應將 from_tf 設定為 True,並應提供一個配置物件作為 config 引數。與使用提供的轉換指令碼將 TensorFlow 檢查點轉換為 PyTorch 模型然後載入 PyTorch 模型相比,此載入路徑較慢。
  • decoder_pretrained_model_name_or_path (str, 可選, 預設為 None) — 初始化解碼器所需的資訊。可以是:

    • 一個字串,即託管在 huggingface.co 上的模型倉庫中的預訓練模型的 模型 id
    • 一個包含使用 save_pretrained() 儲存的模型權重的 目錄 路徑,例如 ./my_model_directory/
    • 一個 tensorflow 索引檢查點檔案 的路徑或 url(例如,./tf_model/model.ckpt.index)。在這種情況下,應將 from_tf 設定為 True,並應提供一個配置物件作為 config 引數。與使用提供的轉換指令碼將 TensorFlow 檢查點轉換為 PyTorch 模型然後載入 PyTorch 模型相比,此載入路徑較慢。
  • model_args (剩餘的位置引數, 可選) — 所有剩餘的位置引數都將傳遞給底層模型的 __init__ 方法。
  • kwargs (剩餘的關鍵字引數字典, 可選) — 可用於更新配置物件(載入後)並初始化模型(例如,output_attentions=True)。

    • 要更新編碼器配置,請為每個配置引數使用字首 encoder_
    • 要更新解碼器配置,請為每個配置引數使用字首 decoder_
    • 要更新父模型配置,請不要為每個配置引數使用字首。

    行為取決於是否提供了 config 或自動載入。

從庫的一個或兩個基類例項化一個編碼器和一個解碼器,這些基類來自預訓練的模型檢查點。

模型預設使用 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")
TensorFlow
隱藏 TensorFlow 內容

TFEncoderDecoderModel

class transformers.TFEncoderDecoderModel

< >

( config: Optional[PretrainedConfig] = None encoder: Optional[TFPreTrainedModel] = None decoder: Optional[TFPreTrainedModel] = None )

引數

  • config (EncoderDecoderConfig) — 包含模型所有引數的模型配置類。使用配置檔案初始化不會載入與模型相關的權重,只會載入配置。請檢視 from_pretrained() 方法來載入模型權重。

這個類可以用來初始化一個序列到序列模型,其中編碼器是任何預訓練的自編碼模型,解碼器是任何預訓練的自迴歸模型。編碼器透過 from_pretrained() 函式載入,解碼器透過 from_pretrained() 函式載入。交叉注意力層會自動新增到解碼器中,並應在下游生成任務(如摘要)上進行微調。

Sascha Rothe、Shashi Narayan、Aliaksei Severyn、Michael Matena、Yanqi Zhou、Wei Li、Peter J. Liu 在 Leveraging Pre-trained Checkpoints for Sequence Generation Tasks 一文中展示了使用預訓練檢查點初始化序列到序列模型在序列生成任務中的有效性。

在這樣一個編碼器-解碼器模型經過訓練/微調後,它可以像任何其他模型一樣儲存/載入(更多資訊請參見示例)。

該模型繼承自 TFPreTrainedModel。請查閱超類的文件,瞭解該庫為其所有模型實現的通用方法(如下載或儲存、調整輸入嵌入大小、修剪頭部等)。

該模型也是一個 keras.Model 子類。可以像常規的 TF 2.0 Keras 模型一樣使用它,並參考 TF 2.0 文件瞭解所有與通用用法和行為相關的事項。

當使用 from_pretrained() 類方法為編碼器建立,並使用 from_pretrained() 類方法為解碼器建立時,TFEncoderDecoderModel 將被例項化為一個 Transformer 架構,其中一個庫的基礎模型類作為編碼器,另一個作為解碼器。

呼叫

< >

( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None decoder_input_ids: np.ndarray | tf.Tensor | None = None decoder_attention_mask: np.ndarray | tf.Tensor | None = None encoder_outputs: np.ndarray | tf.Tensor | None = None past_key_values: tuple[tuple[tf.Tensor]] | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None labels: np.ndarray | tf.Tensor | None = None use_cache: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: bool = False **kwargs ) transformers.modeling_tf_outputs.TFSeq2SeqLMOutputtuple(tf.Tensor)

引數

  • input_ids (np.ndarray, tf.Tensor, list[tf.Tensor]dict[str, tf.Tensor]dict[str, np.ndarray],每個示例的形狀必須為 (batch_size, sequence_length)) — 詞彙表中輸入序列標記的索引。

    可以使用 PreTrainedTokenizer 獲取索引。有關詳細資訊,請參閱 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什麼是輸入 ID?

  • attention_mask (np.ndarraytf.Tensor,形狀為 (batch_size, sequence_length)可選) — 用於避免對填充標記索引執行注意力的掩碼。掩碼值在 [0, 1] 中選擇:

    • 1 表示未被掩碼的標記,
    • 0 表示被掩碼的標記。

    什麼是注意力掩碼?

  • decoder_input_ids (np.ndarraytf.Tensor,形狀為 (batch_size, target_sequence_length)可選) — 詞彙表中解碼器輸入序列標記的索引。

    可以使用 PreTrainedTokenizer 獲取索引。有關詳細資訊,請參閱 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什麼是輸入 ID?

    如果使用了 past_key_values,則可以選擇只輸入最後的 decoder_input_ids(參見 past_key_values)。

    為序列到序列訓練提供給解碼器。可以使用 PreTrainedTokenizer 獲取索引。有關詳細資訊,請參閱 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

  • decoder_attention_mask (np.ndarraytf.Tensor,形狀為 (batch_size, target_sequence_length)可選) — 預設行為:生成一個忽略 decoder_input_ids 中填充標記的張量。預設情況下也會使用因果掩碼。
  • encoder_outputs (tuple(tuple(tf.Tensor), 可選) — 此元組必須包含 (last_hidden_state, 可選: hidden_states, 可選: attentions)。last_hidden_state (tf.Tensor,形狀為 (batch_size, sequence_length, hidden_size)) 是編碼器最後一層輸出的隱藏狀態張量。用於解碼器的交叉注意力。
  • past_key_values (長度為 config.n_layerstuple(tuple(tf.Tensor)),其中每個元組有 4 個形狀為 (batch_size, num_heads, sequence_length - 1, embed_size_per_head) 的張量) — 包含注意力塊的預計算鍵和值隱藏狀態。可用於加速解碼。

    如果使用 past_key_values,使用者可以選擇只輸入最後一個 decoder_input_ids(那些沒有為其提供過去鍵值狀態的 `decoder_input_ids`),形狀為 (batch_size, 1),而不是所有形狀為 (batch_size, sequence_length)decoder_input_ids

  • inputs_embeds (np.ndarraytf.Tensor,形狀為 (batch_size, sequence_length, hidden_size)可選) — 可選地,你可以選擇直接傳遞嵌入表示而不是 input_ids。如果你想比模型內部的嵌入查詢矩陣更好地控制如何將 input_ids 索引轉換為相關向量,這會很有用。
  • decoder_inputs_embeds (np.ndarraytf.Tensor,形狀為 (batch_size, target_sequence_length, hidden_size)可選) — 可選地,你可以選擇直接傳遞嵌入表示而不是 decoder_input_ids。如果你想比模型內部的嵌入查詢矩陣更好地控制如何將 decoder_input_ids 索引轉換為相關向量,這會很有用。
  • labels (np.ndarraytf.Tensor,形狀為 (batch_size, sequence_length)可選) — 用於計算解碼器掩碼語言建模損失的標籤。索引應在 [-100, 0, ..., config.vocab_size] 範圍內(參見 input_ids 的文件字串)。索引設定為 -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
  • return_dict (bool, 可選) — 如果設定為 True,模型將返回一個 ~utils.Seq2SeqLMOutput,而不是一個普通的元組。
  • training (bool, 可選, 預設為 False) — 是否在訓練模式下使用模型(某些模組如 dropout 模組在訓練和評估之間有不同的行為)。
  • kwargs (可選) — 剩餘的關鍵字引數字典。關鍵字引數有兩種:

    • 沒有字首的,將作為 **encoder_kwargs 輸入到編碼器的前向函式中。
    • 帶有 decoder_ 字首的,將作為 `**decoder_kwargs` 輸入到解碼器的前向函式中。

返回

transformers.modeling_tf_outputs.TFSeq2SeqLMOutputtuple(tf.Tensor)

一個 transformers.modeling_tf_outputs.TFSeq2SeqLMOutput 或一個 tf.Tensor 元組(如果傳遞了 return_dict=False 或當 config.return_dict=False 時),根據配置(EncoderDecoderConfig)和輸入包含各種元素。

  • loss (形狀為 (n,)tf.Tensor, 可選, 其中 n 是非掩碼標籤的數量,當提供 labels 時返回) — 語言建模損失。

  • logits (tf.Tensor of shape (batch_size, sequence_length, config.vocab_size)) — 語言模型頭部的預測分數(SoftMax 之前每個詞彙標記的分數)。

  • past_key_values (list[tf.Tensor], 可選, 當傳遞 use_cache=True 或當 config.use_cache=True 時返回) — 長度為 config.n_layerstf.Tensor 列表,其中每個張量的形狀為 (2, batch_size, num_heads, sequence_length, embed_size_per_head))。

    包含解碼器注意力塊的預計算隱藏狀態(鍵和值),可用於(參見 past_key_values 輸入)加速順序解碼。

  • decoder_hidden_states (tuple(tf.Tensor), 可選, 當傳遞 output_hidden_states=True 或當 config.output_hidden_states=True 時返回) — tf.Tensor 的元組(一個是嵌入層的輸出 + 每個層的輸出各一個),形狀為 (batch_size, sequence_length, hidden_size)

    解碼器在每一層輸出時的隱藏狀態以及初始嵌入輸出。

  • decoder_attentions (tuple(tf.Tensor), 可選, 當傳遞 output_attentions=True 或當 config.output_attentions=True 時返回) — tf.Tensor 的元組(每層一個),形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    解碼器的注意力權重,在注意力 softmax 之後,用於計算自注意力頭中的加權平均。

  • cross_attentions (tuple(tf.Tensor), 可選, 當傳遞 output_attentions=True 或當 config.output_attentions=True 時返回) — tf.Tensor 的元組(每層一個),形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    解碼器交叉注意力層的注意力權重,在注意力 softmax 之後,用於計算交叉注意力頭中的加權平均。

  • encoder_last_hidden_state (形狀為 (batch_size, sequence_length, hidden_size)tf.Tensor, 可選) — 模型編碼器最後一層輸出的隱藏狀態序列。

  • encoder_hidden_states (tuple(tf.Tensor), 可選, 當傳遞 output_hidden_states=True 或當 config.output_hidden_states=True 時返回) — tf.Tensor 的元組(一個是嵌入層的輸出 + 每個層的輸出各一個),形狀為 (batch_size, sequence_length, hidden_size)

    編碼器在每一層輸出時的隱藏狀態以及初始嵌入輸出。

  • encoder_attentions (tuple(tf.Tensor), 可選, 當傳遞 output_attentions=True 或當 config.output_attentions=True 時返回) — tf.Tensor 的元組(每層一個),形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    編碼器的注意力權重,在注意力 softmax 之後,用於計算自注意力頭中的加權平均。

TFEncoderDecoderModel 的前向方法會覆蓋 __call__ 特殊方法。

儘管前向傳播的流程需要在此函式內定義,但之後應該呼叫 Module 例項而不是這個函式,因為前者會處理前後處理步驟,而後者會靜默地忽略它們。

示例

>>> from transformers import TFEncoderDecoderModel, BertTokenizer

>>> # initialize a bert2gpt2 from a pretrained BERT and GPT2 models. Note that the cross-attention layers will be randomly initialized
>>> model = TFEncoderDecoderModel.from_encoder_decoder_pretrained("google-bert/bert-base-cased", "openai-community/gpt2")

>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased")

>>> # forward
>>> input_ids = tokenizer.encode(
...     "Hello, my dog is cute", add_special_tokens=True, return_tensors="tf"
... )  # Batch size 1
>>> outputs = model(input_ids=input_ids, decoder_input_ids=input_ids)

>>> # training
>>> outputs = model(input_ids=input_ids, decoder_input_ids=input_ids, labels=input_ids)
>>> loss, logits = outputs.loss, outputs.logits

>>> # save and load from pretrained
>>> model.save_pretrained("bert2gpt2")
>>> model = TFEncoderDecoderModel.from_pretrained("bert2gpt2")

>>> # generation
>>> generated = model.generate(input_ids, decoder_start_token_id=model.config.decoder.bos_token_id)

from_encoder_decoder_pretrained

< >

( encoder_pretrained_model_name_or_path: Optional[str] = None decoder_pretrained_model_name_or_path: Optional[str] = None *model_args **kwargs )

引數

  • encoder_pretrained_model_name_or_path (str, 可選) — 初始化編碼器所需的資訊。可以是:

    • 一個字串,即託管在 huggingface.co 上的模型倉庫中的預訓練模型的 模型 id
    • 一個包含使用 save_pretrained() 儲存的模型權重的 目錄 路徑,例如 ./my_model_directory/
    • 一個 pytorch 索引檢查點檔案 的路徑或 url(例如,./pt_model/)。在這種情況下,應將 encoder_from_pt 設定為 True
  • decoder_pretrained_model_name_or_path (str, 可選, 預設為 None) — 初始化解碼器所需的資訊。可以是:

    • 一個字串,即託管在 huggingface.co 上的模型倉庫中的預訓練模型的 模型 id
    • 一個包含使用 save_pretrained() 儲存的模型權重的 目錄 路徑,例如 ./my_model_directory/
    • 一個 pytorch 檢查點檔案 的路徑或 url(例如,./pt_model/)。在這種情況下,應將 decoder_from_pt 設定為 True
  • model_args (剩餘的位置引數, 可選) — 所有剩餘的位置引數都將傳遞給底層模型的 __init__ 方法。
  • kwargs (剩餘的關鍵字引數字典, 可選) — 可用於更新配置物件(載入後)並初始化模型(例如,output_attentions=True)。

    • 要更新編碼器配置,請為每個配置引數使用字首 encoder_
    • 要更新解碼器配置,請為每個配置引數使用字首 decoder_
    • 要更新父模型配置,請不要為每個配置引數使用字首。

    行為取決於是否提供了 config 或自動載入。

從庫的一個或兩個基類例項化一個編碼器和一個解碼器,這些基類來自預訓練的模型檢查點。

示例

>>> from transformers import TFEncoderDecoderModel

>>> # initialize a bert2gpt2 from two pretrained BERT models. Note that the cross-attention layers will be randomly initialized
>>> model = TFEncoderDecoderModel.from_encoder_decoder_pretrained("google-bert/bert-base-uncased", "openai-community/gpt2")
>>> # saving model after fine-tuning
>>> model.save_pretrained("./bert2gpt2")
>>> # load fine-tuned model
>>> model = TFEncoderDecoderModel.from_pretrained("./bert2gpt2")
JAX
隱藏 JAX 內容

FlaxEncoderDecoderModel

class transformers.FlaxEncoderDecoderModel

< >

( config: EncoderDecoderConfig input_shape: typing.Optional[tuple] = None seed: int = 0 dtype: dtype = <class 'jax.numpy.float32'> _do_init: bool = True **kwargs )

引數

  • config (EncoderDecoderConfig) — 包含模型所有引數的模型配置類。使用配置檔案初始化不會載入與模型相關的權重,只會載入配置。請檢視 from_pretrained() 方法來載入模型權重。
  • dtype (jax.numpy.dtype, 可選, 預設為 jax.numpy.float32) — 計算的資料型別。可以是 jax.numpy.float32jax.numpy.float16 (在 GPU 上) 和 jax.numpy.bfloat16 (在 TPU 上) 之一。

    這可用於在 GPU 或 TPU 上啟用混合精度訓練或半精度推理。如果指定,所有計算都將使用給定的 dtype 執行。

    請注意,這僅指定計算的 dtype,不影響模型引數的 dtype。

    如果您希望更改模型引數的 dtype,請參閱 to_fp16()to_bf16()

這個類可以用來初始化一個序列到序列模型,其中編碼器是任何預訓練的自編碼模型,解碼器是任何預訓練的自迴歸模型。編碼器透過 from_pretrained() 函式載入,解碼器透過 from_pretrained() 函式載入。交叉注意力層會自動新增到解碼器中,並應在下游生成任務(如摘要)上進行微調。

Sascha Rothe、Shashi Narayan、Aliaksei Severyn、Michael Matena、Yanqi Zhou、Wei Li、Peter J. Liu 在 Leveraging Pre-trained Checkpoints for Sequence Generation Tasks 一文中展示了使用預訓練檢查點初始化序列到序列模型在序列生成任務中的有效性。

在這樣一個編碼器-解碼器模型經過訓練/微調後,它可以像任何其他模型一樣儲存/載入(更多資訊請參見示例)。

此模型繼承自 FlaxPreTrainedModel。請檢視超類文件以瞭解該庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭等)。

該模型也是 Flax Linen flax.nn.Module 的子類。請將其作為常規 Flax 模組使用,並參考 Flax 文件瞭解所有與通用用法和行為相關的事項。

FlaxEncoderDecoderModel 是一個通用模型類,在使用編碼器的 :meth~transformers.FlaxAutoModel.from_pretrained 類方法和解碼器的 :meth~transformers.FlaxAutoModelForCausalLM.from_pretrained 類方法建立時,它將被例項化為一個 transformer 架構,其中編碼器模組和解碼器模組分別是庫中基礎模型類之一的模組 (flax.nn.Module)。

__call__

< >

( input_ids: Array attention_mask: typing.Optional[jax.Array] = None decoder_input_ids: typing.Optional[jax.Array] = None decoder_attention_mask: typing.Optional[jax.Array] = None position_ids: typing.Optional[jax.Array] = None decoder_position_ids: typing.Optional[jax.Array] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None train: bool = False params: typing.Optional[dict] = None dropout_rng: <function PRNGKey at 0x7effc7ad3a30> = None ) transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutputtuple(torch.FloatTensor)

引數

  • input_ids (jnp.ndarray,形狀為 (batch_size, sequence_length)) — 詞彙表中輸入序列標記的索引。如果您提供填充,預設情況下將被忽略。

    可以使用 PreTrainedTokenizer 獲取索引。有關詳細資訊,請參閱 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什麼是輸入 ID?

  • attention_mask (jnp.ndarray,形狀為 (batch_size, sequence_length), 可選) — 用於避免在填充標記索引上執行注意力的掩碼。掩碼值在 [0, 1] 中選擇:

    • 1 表示標記未被遮蓋
    • 0 表示標記被遮蓋

    什麼是注意力掩碼?

  • decoder_input_ids (jnp.ndarray,形狀為 (batch_size, target_sequence_length), 可選) — 詞彙表中解碼器輸入序列標記的索引。

    可以使用 PreTrainedTokenizer 獲取索引。有關詳細資訊,請參閱 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什麼是解碼器輸入 ID?

    對於序列到序列訓練,應提供 decoder_input_idsdecoder_input_ids 應該在模型外部建立,方法是將 labels 向右移動,將 -100 替換為 pad_token_id,並在它們前面加上 decoder_start_token_id

  • decoder_attention_mask (jnp.ndarray,形狀為 (batch_size, target_sequence_length), 可選) — 預設行為:生成一個忽略 decoder_input_ids 中填充標記的張量。預設情況下也會使用因果掩碼。
  • position_ids (numpy.ndarray,形狀為 (batch_size, sequence_length), 可選) — 每個輸入序列標記在位置嵌入中的位置索引。在 [0, config.encoder.max_position_embeddings - 1] 範圍內選擇。
  • decoder_position_ids (numpy.ndarray,形狀為 (batch_size, sequence_length), 可選) — 每個解碼器輸入序列標記在位置嵌入中的位置索引。在 [0, config.decoder.max_position_embeddings - 1] 範圍內選擇。
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • return_dict (bool, 可選) — 如果設定為 True,模型將返回一個 ~utils.FlaxSeq2SeqLMOutput 而不是一個普通的元組。

返回

transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutputtuple(torch.FloatTensor)

一個 transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput 或一個 torch.FloatTensor 的元組(如果傳遞了 return_dict=False 或當 config.return_dict=False),包含根據配置(EncoderDecoderConfig)和輸入的不同元素。

  • logits (形狀為 (batch_size, sequence_length, config.vocab_size)jnp.ndarray) — 語言建模頭的預測分數(SoftMax 之前每個詞彙 token 的分數)。

  • past_key_values (tuple(tuple(jnp.ndarray)), 可選, 在傳遞 use_cache=Trueconfig.use_cache=True 時返回) — 長度為 config.n_layerstuple(tuple(jnp.ndarray)) 元組,每個元組包含 2 個形狀為 (batch_size, num_heads, sequence_length, embed_size_per_head) 的張量和 2 個額外的形狀為 (batch_size, num_heads, encoder_sequence_length, embed_size_per_head) 的張量。

    包含預先計算的隱藏狀態(自注意力塊和交叉注意力塊中的鍵和值),可用於(參見 past_key_values 輸入)加速順序解碼。

  • decoder_hidden_states (tuple(jnp.ndarray), 可選, 在傳遞 output_hidden_states=Trueconfig.output_hidden_states=True 時返回) — jnp.ndarray 的元組(一個用於嵌入層的輸出,一個用於每層的輸出),形狀為 (batch_size, sequence_length, hidden_size)

    解碼器在每一層輸出時的隱藏狀態以及初始嵌入輸出。

  • decoder_attentions (tuple(jnp.ndarray), 可選, 在傳遞 output_attentions=Trueconfig.output_attentions=True 時返回) — jnp.ndarray 的元組(每層一個),形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    解碼器的注意力權重,在注意力 softmax 之後,用於計算自注意力頭中的加權平均。

  • cross_attentions (tuple(jnp.ndarray), 可選, 在傳遞 output_attentions=Trueconfig.output_attentions=True 時返回) — jnp.ndarray 的元組(每層一個),形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    解碼器交叉注意力層的注意力權重,在注意力 softmax 之後,用於計算交叉注意力頭中的加權平均。

  • encoder_last_hidden_state (形狀為 (batch_size, sequence_length, hidden_size)jnp.ndarray可選) — 模型編碼器最後一層輸出的隱藏狀態序列。

  • encoder_hidden_states (tuple(jnp.ndarray), 可選, 在傳遞 output_hidden_states=Trueconfig.output_hidden_states=True 時返回) — jnp.ndarray 的元組(一個用於嵌入層的輸出,一個用於每層的輸出),形狀為 (batch_size, sequence_length, hidden_size)

    編碼器在每一層輸出時的隱藏狀態以及初始嵌入輸出。

  • encoder_attentions (tuple(jnp.ndarray), 可選, 在傳遞 output_attentions=Trueconfig.output_attentions=True 時返回) — jnp.ndarray 的元組(每層一個),形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    編碼器的注意力權重,在注意力 softmax 之後,用於計算自注意力頭中的加權平均。

FlaxEncoderDecoderModel 的前向方法重寫了 __call__ 特殊方法。

儘管前向傳播的流程需要在此函式內定義,但之後應該呼叫 Module 例項而不是這個函式,因為前者會處理前後處理步驟,而後者會靜默地忽略它們。

示例

>>> from transformers import FlaxEncoderDecoderModel, BertTokenizer, GPT2Tokenizer

>>> # load a fine-tuned bert2gpt2 model
>>> model = FlaxEncoderDecoderModel.from_pretrained("patrickvonplaten/bert2gpt2-cnn_dailymail-fp16")
>>> # load input & output tokenizer
>>> tokenizer_input = BertTokenizer.from_pretrained("google-bert/bert-base-cased")
>>> tokenizer_output = GPT2Tokenizer.from_pretrained("openai-community/gpt2")

>>> article = '''Sigma Alpha Epsilon is under fire for a video showing party-bound fraternity members
>>> singing a racist chant. SAE's national chapter suspended the students,
>>> but University of Oklahoma President David Boren took it a step further,
>>> saying the university's affiliation with the fraternity is permanently done.'''

>>> input_ids = tokenizer_input(article, add_special_tokens=True, return_tensors="np").input_ids

>>> # use GPT2's eos_token as the pad as well as eos token
>>> model.config.eos_token_id = model.config.decoder.eos_token_id
>>> model.config.pad_token_id = model.config.eos_token_id

>>> sequences = model.generate(input_ids, num_beams=4, max_length=12).sequences

>>> summary = tokenizer_output.batch_decode(sequences, skip_special_tokens=True)[0]
>>> assert summary == "SAS Alpha Epsilon suspended Sigma Alpha Epsilon members"

from_encoder_decoder_pretrained

< >

( encoder_pretrained_model_name_or_path: typing.Union[str, os.PathLike, NoneType] = None decoder_pretrained_model_name_or_path: typing.Union[str, os.PathLike, NoneType] = None *model_args **kwargs )

引數

  • encoder_pretrained_model_name_or_path (Union[str, os.PathLike], 可選) — 初始化編碼器所需的資訊。可以是:

    • 一個字串,即託管在 huggingface.co 上的模型倉庫中的預訓練模型的 model id
    • 一個包含使用 save_pretrained() 儲存的模型權重的目錄的路徑,例如 ./my_model_directory/
  • decoder_pretrained_model_name_or_path (Union[str, os.PathLike], 可選, 預設為 None) — 初始化解碼器所需的資訊。可以是:

    • 一個字串,即託管在 huggingface.co 上的模型倉庫中的預訓練模型的 model id
    • 一個包含使用 save_pretrained() 儲存的模型權重的目錄的路徑,例如 ./my_model_directory/
  • model_args (剩餘的位置引數, 可選) — 所有剩餘的位置引數都將傳遞給底層模型的 __init__ 方法。
  • kwargs (剩餘的關鍵字引數字典, 可選) — 可用於更新配置物件(載入後)並初始化模型(例如,output_attentions=True)。

    • 要更新編碼器配置,請為每個配置引數使用字首 encoder_
    • 要更新解碼器配置,請為每個配置引數使用字首 decoder_
    • 要更新父模型配置,請不要為每個配置引數使用字首。

    行為根據是否提供 config 或自動載入而有所不同。

從庫的一個或兩個基類例項化一個編碼器和一個解碼器,這些基類來自預訓練的模型檢查點。

示例

>>> from transformers import FlaxEncoderDecoderModel

>>> # initialize a bert2gpt2 from pretrained BERT and GPT2 models. Note that the cross-attention layers will be randomly initialized
>>> model = FlaxEncoderDecoderModel.from_encoder_decoder_pretrained("google-bert/bert-base-cased", "openai-community/gpt2")
>>> # saving model after fine-tuning
>>> model.save_pretrained("./bert2gpt2")
>>> # load fine-tuned model
>>> model = FlaxEncoderDecoderModel.from_pretrained("./bert2gpt2")
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.