Transformers 文档
FSMT
并获得增强的文档体验
开始使用
此模型于 2019-07-15 发布,并于 2020-11-16 添加到 Hugging Face Transformers。
FSMT
概述
FSMT (FairSeq MachineTranslation) 模型在 Facebook FAIR 的 WMT19 新闻翻译任务提交 中引入,作者是 Nathan Ng、Kyra Yee、Alexei Baevski、Myle Ott、Michael Auli、Sergey Edunov。
论文摘要如下:
本文描述了 Facebook FAIR 在 WMT19 共享新闻翻译任务中的提交。我们参与了两个语言对和四个语言方向的比赛:英语 <-> 德语和英语 <-> 俄语。沿用去年的方法,我们的基线系统是使用 Fairseq 序列建模工具包训练的大型基于 BPE 的 Transformer 模型,该模型依赖于采样回译。今年,我们尝试了不同的双语数据过滤方案,并添加了过滤后的回译数据。我们还对模型进行了集成和领域特定数据微调,然后使用噪声通道模型重排序进行解码。在人工评估活动的所有四个方向中,我们的提交均获得第一名。在英德(En->De)方向上,我们的系统显著优于其他系统以及人工翻译。与我们 WMT’18 的提交相比,该系统将 BLEU 分数提高了 4.5 分。
实现说明
- FSMT 使用不合并在一起的源词汇表和目标词汇表。它也不共享嵌入式标记。其分词器与 XLMTokenizer 非常相似,主模型源自 BartModel。
FSMTConfig
class transformers.FSMTConfig
< 来源 >( langs = ['en', 'de'] src_vocab_size = 42024 tgt_vocab_size = 42024 activation_function = 'relu' d_model = 1024 max_length = 200 max_position_embeddings = 1024 encoder_ffn_dim = 4096 encoder_layers = 12 encoder_attention_heads = 16 encoder_layerdrop = 0.0 decoder_ffn_dim = 4096 decoder_layers = 12 decoder_attention_heads = 16 decoder_layerdrop = 0.0 attention_dropout = 0.0 dropout = 0.1 activation_dropout = 0.0 init_std = 0.02 decoder_start_token_id = 2 is_encoder_decoder = True scale_embedding = True tie_word_embeddings = False num_beams = 5 length_penalty = 1.0 early_stopping = False use_cache = True pad_token_id = 1 bos_token_id = 0 eos_token_id = 2 forced_eos_token_id = 2 **common_kwargs )
参数
- langs (
list[str]) — 源语言和目标语言的列表(例如:['en', 'ru'])。 - src_vocab_size (
int) — 编码器的词汇量大小。定义了在编码器 `forward` 方法中传递的 `inputs_ids` 可以表示的不同标记的数量。 - tgt_vocab_size (
int) — 解码器的词汇量大小。定义了在解码器 `forward` 方法中传递的 `inputs_ids` 可以表示的不同标记的数量。 - d_model (
int, 可选, 默认为 1024) — 各层的维度和池化层的维度。 - encoder_layers (
int, 可选, 默认为 12) — 编码器层数。 - decoder_layers (
int, 可选, 默认为 12) — 解码器层数。 - encoder_attention_heads (
int, 可选, 默认为 16) — Transformer 编码器中每个注意力层的注意力头数量。 - decoder_attention_heads (
int, 可选, 默认为 16) — Transformer 解码器中每个注意力层的注意力头数量。 - decoder_ffn_dim (
int, 可选, 默认为 4096) — 解码器中“中间”(通常称为前馈)层的维度。 - encoder_ffn_dim (
int, 可选, 默认为 4096) — 编码器中“中间”(通常称为前馈)层的维度。 - activation_function (
str或Callable, 可选, 默认为"relu") — 编码器和池化层中的非线性激活函数(函数或字符串)。如果为字符串,支持"gelu"、"relu"、"silu"和"gelu_new"。 - dropout (
float, 可选, 默认为 0.1) — 嵌入、编码器和池化层中所有全连接层的 dropout 概率。 - attention_dropout (
float, 可选, 默认为 0.0) — 注意力概率的 dropout 比率。 - activation_dropout (
float, 可选, 默认为 0.0) — 完全连接层内激活的 dropout 比率。 - max_position_embeddings (
int, 可选, 默认为 1024) — 此模型可能使用的最大序列长度。通常将其设置为一个较大的值以防万一(例如,512 或 1024 或 2048)。 - init_std (
float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态分布初始化器的标准差。 - scale_embedding (
bool, 可选, 默认为True) — 通过除以 sqrt(d_model) 来缩放嵌入。 - bos_token_id (
int, 可选, 默认为 0) — 开始流标记 ID。 - pad_token_id (
int, 可选, 默认为 1) — 填充标记 ID。 - eos_token_id (
int, 可选, 默认为 2) — 结束流标记 ID。 - decoder_start_token_id (
int, optional) — This model starts decoding witheos_token_id - encoder_layerdrop (
float, optional, defaults to 0.0) — Google “layerdrop arxiv”, as its not explainable in one line. - decoder_layerdrop (
float, optional, defaults to 0.0) — Google “layerdrop arxiv”, as its not explainable in one line. - is_encoder_decoder (
bool, optional, defaults toTrue) — Whether this is an encoder/decoder model. - tie_word_embeddings (
bool, optional, defaults toFalse) — Whether to tie input and output embeddings. - num_beams (
int, optional, defaults to 5) — Number of beams for beam search that will be used by default in thegeneratemethod of the model. 1 means no beam search. - length_penalty (
float, optional, defaults to 1) — Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative),length_penalty> 0.0 promotes longer sequences, whilelength_penalty< 0.0 encourages shorter sequences. - early_stopping (
bool, optional, defaults toFalse) — Flag that will be used by default in thegeneratemethod of the model. Whether to stop the beam search when at leastnum_beamssentences are finished per batch or not. - use_cache (
bool, optional, defaults toTrue) — Whether or not the model should return the last key/values attentions (not used by all models). - forced_eos_token_id (
int, optional, defaults to 2) — The id of the token to force as the last generated token whenmax_lengthis reached. Usually set toeos_token_id.
这是存储 FSMTModel 配置的类。它用于根据指定的参数实例化一个 FSMT 模型,定义了模型的架构。使用默认值实例化配置将得到一个与 FSMT facebook/wmt19-en-ru 架构类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PreTrainedConfig 的文档。
示例
>>> from transformers import FSMTConfig, FSMTModel
>>> # Initializing a FSMT facebook/wmt19-en-ru style configuration
>>> config = FSMTConfig()
>>> # Initializing a model (with random weights) from the configuration
>>> model = FSMTModel(config)
>>> # Accessing the model configuration
>>> configuration = model.configFSMTTokenizer
class transformers.FSMTTokenizer
< source >( langs = None src_vocab_file = None tgt_vocab_file = None merges_file = None do_lower_case = False unk_token = '<unk>' bos_token = '<s>' sep_token = '</s>' pad_token = '<pad>' **kwargs )
参数
- langs (
List[str], optional) — A list of two languages to translate from and to, for instance["en", "ru"]. - src_vocab_file (
str, optional) — File containing the vocabulary for the source language. - tgt_vocab_file (
st, optional) — File containing the vocabulary for the target language. - merges_file (
str, optional) — File containing the merges. - do_lower_case (
bool, optional, defaults toFalse) — Whether or not to lowercase the input when tokenizing. - unk_token (
str, optional, defaults to"<unk>") — The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. - bos_token (
str, optional, defaults to"<s>") — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.When building a sequence using special tokens, this is not the token that is used for the beginning of sequence. The token used is the
cls_token. - sep_token (
str, optional, defaults to"</s>") — The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for sequence classification or for a text and a question for question answering. It is also used as the last token of a sequence built with special tokens. - pad_token (
str, optional, defaults to"<pad>") — The token used for padding, for example when batching sequences of different lengths.
构建一个 FAIRSEQ Transformer 分词器。基于字节对编码(Byte-Pair Encoding)。分词过程如下
- Moses 预处理和分词。
- 对所有输入文本进行归一化。
- 参数 `special_tokens` 和函数 `set_special_tokens` 可用于向词汇表添加额外的符号(如 “classify”)。
langs参数定义了一对语言。
此分词器继承自 PreTrainedTokenizer,其中包含大部分主要方法。用户应参考此超类以获取有关这些方法的更多信息。
build_inputs_with_special_tokens
< source >( token_ids_0: list token_ids_1: list[int] | None = None already_has_special_tokens: bool = False ) → List[int]
参数
- token_ids_0 (
List[int]) — List of IDs to which the special tokens will be added. - token_ids_1 (
List[int], optional) — Optional second list of IDs for sequence pairs.
返回
List[int]
带有适当特殊标记的输入ID列表。
通过连接和添加特殊标记来构建用于序列分类任务的序列或序列对的输入。FAIRSEQ Transformer 序列格式如下
- 单个序列:
<s> X </s> - 序列对:
<s> A </s> B </s>
get_special_tokens_mask
< source >( token_ids_0: list token_ids_1: list[int] | None = None already_has_special_tokens: bool = False ) → List[int]
参数
- token_ids_0 (
List[int]) — List of IDs. - token_ids_1 (
List[int], optional) — Optional second list of IDs for sequence pairs. - already_has_special_tokens (
bool, optional, defaults toFalse) — Whether or not the token list is already formatted with special tokens for the model.
返回
List[int]
一个范围为 [0, 1] 的整数列表:1 表示特殊标记,0 表示序列标记。
从没有添加特殊标记的标记列表中检索序列ID。此方法在使用分词器prepare_for_model方法添加特殊标记时调用。
create_token_type_ids_from_sequences
< source >( token_ids_0: list token_ids_1: list[int] | None = None ) → list[int]
为用于序列对分类任务的两个序列创建一个掩码。
此方法根据分词器的配置属性动态构建 token 类型 ID
token_type_ids_pattern: 要使用的模式 ("all_zeros" 或 "bert_style")token_type_ids_include_special_tokens: 在长度计算中是否计入特殊标记
示例
# All zeros pattern (default, used by RoBERTa, BART, etc.)
tokenizer.token_type_ids_pattern = "all_zeros"
# Returns: [0, 0, 0, ...] for both sequences
# BERT-style pattern (first sequence gets 0s, second gets 1s)
tokenizer.token_type_ids_pattern = "bert_style"
# Returns: [0, 0, 0, ..., 1, 1, 1, ...] for sequence pairsFSMTModel
class transformers.FSMTModel
< source >( config: FSMTConfig )
参数
- config (FSMTConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The bare Fsmt Model outputting raw hidden-states without any specific head on top.
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: LongTensor attention_mask: torch.Tensor | None = None decoder_input_ids: torch.LongTensor | None = None decoder_attention_mask: torch.BoolTensor | None = None encoder_outputs: tuple[torch.FloatTensor] | None = None past_key_values: transformers.cache_utils.Cache | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None inputs_embeds: torch.FloatTensor | None = None decoder_inputs_embeds: torch.FloatTensor | None = None return_dict: bool | None = None cache_position: torch.Tensor | None = None **kwargs ) → transformers.modeling_outputs.Seq2SeqModelOutput or tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- decoder_input_ids (
torch.LongTensorof shape(batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
FSMT uses the
eos_token_idas the starting token fordecoder_input_idsgeneration. Ifpast_key_valuesis used, optionally only the lastdecoder_input_idshave to be input (seepast_key_values). - decoder_attention_mask (
torch.BoolTensorof shape(batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens indecoder_input_ids. Causal mask will also be used by default. - encoder_outputs (
tuple, optional) — Tuple consists of (last_hidden_state, optional:hidden_states, optional:attentions)last_hidden_stateof shape(batch_size, sequence_length, hidden_size), optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. - past_key_values (
~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - use_cache (
bool, optional) — If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values). - output_attentions (
bool, optional) — Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail. - output_hidden_states (
bool, optional) — Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail. - inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - decoder_inputs_embeds (
torch.FloatTensorof shape(batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passingdecoder_input_idsyou can choose to directly pass an embedded representation. Ifpast_key_valuesis used, optionally only the lastdecoder_inputs_embedshave to be input (seepast_key_values). This is useful if you want more control over how to convertdecoder_input_idsindices into associated vectors than the model’s internal embedding lookup matrix.If
decoder_input_idsanddecoder_inputs_embedsare both unset,decoder_inputs_embedstakes the value ofinputs_embeds. - return_dict (
bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. - cache_position (
torch.Tensorof shape(sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.
返回
transformers.modeling_outputs.Seq2SeqModelOutput 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.Seq2SeqModelOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (FSMTConfig) and inputs.
-
last_hidden_state (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size)) — 模型解码器最后一层输出的隐藏状态序列。如果使用了
past_key_values,则只输出形状为(batch_size, 1, hidden_size)的序列的最后一个隐藏状态。 -
past_key_values (
EncoderDecoderCache, optional, 当传入use_cache=True或当config.use_cache=True时返回) — 这是一个 EncoderDecoderCache 实例。有关更多详细信息,请参阅我们的 kv 缓存指南。包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于(参见
past_key_values输入)加速顺序解码。 -
decoder_hidden_states (
tuple(torch.FloatTensor), optional, 当传入output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor元组(一个用于嵌入的输出,如果模型有嵌入层,+ 一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。解码器在每个层输出的隐藏状态,加上可选的初始嵌入输出。
-
decoder_attentions (
tuple(torch.FloatTensor), optional, 当传入output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均。
-
cross_attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor(one for each layer) of shape(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), optional, 当传入output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor元组(一个用于嵌入的输出,如果模型有嵌入层,+ 一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。编码器在每个层输出的隐藏状态,加上可选的初始嵌入输出。
-
encoder_attentions (
tuple(torch.FloatTensor), optional, 当传入output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均。
The FSMTModel forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
FSMTForConditionalGeneration
class transformers.FSMTForConditionalGeneration
< source >( config: FSMTConfig )
参数
- config (FSMTConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The FSMT Model with a language modeling head. Can be used for summarization.
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None decoder_input_ids: torch.LongTensor | None = None decoder_attention_mask: torch.BoolTensor | None = None encoder_outputs: tuple[torch.FloatTensor] | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.Tensor | None = None decoder_inputs_embeds: torch.Tensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None cache_position: torch.Tensor | None = None **kwargs ) → transformers.modeling_outputs.Seq2SeqLMOutput or tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- decoder_input_ids (
torch.LongTensorof shape(batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
FSMT uses the
eos_token_idas the starting token fordecoder_input_idsgeneration. Ifpast_key_valuesis used, optionally only the lastdecoder_input_idshave to be input (seepast_key_values). - decoder_attention_mask (
torch.BoolTensorof shape(batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens indecoder_input_ids. Causal mask will also be used by default. - encoder_outputs (
tuple, optional) — Tuple consists of (last_hidden_state, optional:hidden_states, optional:attentions)last_hidden_stateof shape(batch_size, sequence_length, hidden_size), optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. - past_key_values (
~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.Tensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - decoder_inputs_embeds (
torch.Tensorof shape(batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passingdecoder_input_idsyou can choose to directly pass an embedded representation. Ifpast_key_valuesis used, optionally only the lastdecoder_inputs_embedshave to be input (seepast_key_values). This is useful if you want more control over how to convertdecoder_input_idsindices into associated vectors than the model’s internal embedding lookup matrix.If
decoder_input_idsanddecoder_inputs_embedsare both unset,decoder_inputs_embedstakes the value ofinputs_embeds. - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size]or -100 (seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]. - use_cache (
bool, optional) — If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values). - output_attentions (
bool, optional) — Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail. - output_hidden_states (
bool, optional) — Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail. - return_dict (
bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. - cache_position (
torch.Tensorof shape(sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.
返回
transformers.modeling_outputs.Seq2SeqLMOutput 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.Seq2SeqLMOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (FSMTConfig) and inputs.
-
loss (
torch.FloatTensor,形状为(1,),可选,当提供labels时返回) — 语言建模损失。 -
logits (形状为
(batch_size, sequence_length, config.vocab_size)的torch.FloatTensor) — 语言建模头部的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
past_key_values (
EncoderDecoderCache, optional, 当传入use_cache=True或当config.use_cache=True时返回) — 这是一个 EncoderDecoderCache 实例。有关更多详细信息,请参阅我们的 kv 缓存指南。包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于(参见
past_key_values输入)加速顺序解码。 -
decoder_hidden_states (
tuple(torch.FloatTensor), optional, 当传入output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor元组(一个用于嵌入的输出,如果模型有嵌入层,+ 一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。解码器在每一层输出时的隐藏状态以及初始嵌入输出。
-
decoder_attentions (
tuple(torch.FloatTensor), optional, 当传入output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均。
-
cross_attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor(one for each layer) of shape(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), optional, 当传入output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor元组(一个用于嵌入的输出,如果模型有嵌入层,+ 一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。编码器在每一层输出时的隐藏状态以及初始嵌入输出。
-
encoder_attentions (
tuple(torch.FloatTensor), optional, 当传入output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均。
The FSMTForConditionalGeneration forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
翻译示例
>>> from transformers import AutoTokenizer, FSMTForConditionalGeneration
>>> mname = "facebook/wmt19-ru-en"
>>> model = FSMTForConditionalGeneration.from_pretrained(mname)
>>> tokenizer = AutoTokenizer.from_pretrained(mname)
>>> src_text = "Машинное обучение - это здорово, не так ли?"
>>> input_ids = tokenizer(src_text, return_tensors="pt").input_ids
>>> outputs = model.generate(input_ids, num_beams=5, num_return_sequences=3)
>>> tokenizer.decode(outputs[0], skip_special_tokens=True)
"Machine learning is great, isn't it?"