FSMT (FairSeq MachineTranslation) models were introduced in Facebook FAIR’s WMT19 News Translation Task Submission by Nathan Ng, Kyra Yee, Alexei Baevski, Myle Ott, Michael Auli, Sergey Edunov.
The abstract of the paper is the following:
This paper describes Facebook FAIR’s submission to the WMT19 shared news translation task. We participate in two language pairs and four language directions, English <-> German and English <-> Russian. Following our submission from last year, our baseline systems are large BPE-based transformer models trained with the Fairseq sequence modeling toolkit which rely on sampled back-translations. This year we experiment with different bitext data filtering schemes, as well as with adding filtered back-translated data. We also ensemble and fine-tune our models on domain-specific data, then decode using noisy channel model reranking. Our submissions are ranked first in all four directions of the human evaluation campaign. On En->De, our system significantly outperforms other systems as well as human translations. This system improves upon our WMT’18 submission by 4.5 BLEU points.
This model was contributed by stas. The original code can be found here.
( 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 )
Parameters
List[str]
) —
A list with source language and target_language (e.g., [‘en’, ‘ru’]). int
) —
Vocabulary size of the encoder. Defines the number of different tokens that can be represented by the
inputs_ids
passed to the forward method in the encoder. int
) —
Vocabulary size of the decoder. Defines the number of different tokens that can be represented by the
inputs_ids
passed to the forward method in the decoder. int
, optional, defaults to 1024) —
Dimensionality of the layers and the pooler layer. int
, optional, defaults to 12) —
Number of encoder layers. int
, optional, defaults to 12) —
Number of decoder layers. int
, optional, defaults to 16) —
Number of attention heads for each attention layer in the Transformer encoder. int
, optional, defaults to 16) —
Number of attention heads for each attention layer in the Transformer decoder. int
, optional, defaults to 4096) —
Dimensionality of the “intermediate” (often named feed-forward) layer in decoder. int
, optional, defaults to 4096) —
Dimensionality of the “intermediate” (often named feed-forward) layer in decoder. str
or Callable
, optional, defaults to "relu"
) —
The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu"
,
"relu"
, "silu"
and "gelu_new"
are supported. float
, optional, defaults to 0.1) —
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. float
, optional, defaults to 0.0) —
The dropout ratio for the attention probabilities. float
, optional, defaults to 0.0) —
The dropout ratio for activations inside the fully connected layer. int
, optional, defaults to 1024) —
The maximum sequence length that this model might ever be used with. Typically set this to something large
just in case (e.g., 512 or 1024 or 2048). float
, optional, defaults to 0.02) —
The standard deviation of the truncated_normal_initializer for initializing all weight matrices. bool
, optional, defaults to True
) —
Scale embeddings by diving by sqrt(d_model). int
, optional, defaults to 0) —
Beginning of stream token id. int
, optional, defaults to 1) —
Padding token id. int
, optional, defaults to 2) —
End of stream token id. int
, optional) —
This model starts decoding with eos_token_id
float
, optional, defaults to 0.0) —
Google “layerdrop arxiv”, as its not explainable in one line. float
, optional, defaults to 0.0) —
Google “layerdrop arxiv”, as its not explainable in one line. bool
, optional, defaults to True
) —
Whether this is an encoder/decoder model. bool
, optional, defaults to False
) —
Whether to tie input and output embeddings. int
, optional, defaults to 5) —
Number of beams for beam search that will be used by default in the generate
method of the model. 1 means
no beam search. 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, while
length_penalty
< 0.0 encourages shorter sequences. bool
, optional, defaults to False
) —
Flag that will be used by default in the generate
method of the model. Whether to stop the beam search
when at least num_beams
sentences are finished per batch or not. bool
, optional, defaults to True
) —
Whether or not the model should return the last key/values attentions (not used by all models). int
, optional, defaults to 2) —
The id of the token to force as the last generated token when max_length
is reached. Usually set to
eos_token_id
. This is the configuration class to store the configuration of a FSMTModel. It is used to instantiate a FSMT model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the FSMT facebook/wmt19-en-ru architecture.
Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.
Examples:
>>> 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.config
( 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 )
Parameters
List[str]
, optional) —
A list of two languages to translate from and to, for instance ["en", "ru"]
. str
, optional) —
File containing the vocabulary for the source language. st
, optional) —
File containing the vocabulary for the target language. str
, optional) —
File containing the merges. bool
, optional, defaults to False
) —
Whether or not to lowercase the input when tokenizing. 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. 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
.
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. str
, optional, defaults to "<pad>"
) —
The token used for padding, for example when batching sequences of different lengths. Construct an FAIRSEQ Transformer tokenizer. Based on Byte-Pair Encoding. The tokenization process is the following:
special_tokens
and the function set_special_tokens
, can be used to add additional symbols (like
”classify”) to a vocabulary.langs
defines a pair of languages.This tokenizer inherits from PreTrainedTokenizer which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.
( token_ids_0: List token_ids_1: Optional = None ) → List[int]
Parameters
List[int]
) —
List of IDs to which the special tokens will be added. List[int]
, optional) —
Optional second list of IDs for sequence pairs. Returns
List[int]
List of input IDs with the appropriate special tokens.
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A FAIRSEQ Transformer sequence has the following format:
<s> X </s>
<s> A </s> B </s>
( token_ids_0: List token_ids_1: Optional = None already_has_special_tokens: bool = False ) → List[int]
Parameters
List[int]
) —
List of IDs. List[int]
, optional) —
Optional second list of IDs for sequence pairs. bool
, optional, defaults to False
) —
Whether or not the token list is already formatted with special tokens for the model. Returns
List[int]
A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer prepare_for_model
method.
( token_ids_0: List token_ids_1: Optional = None ) → List[int]
Parameters
List[int]
) —
List of IDs. List[int]
, optional) —
Optional second list of IDs for sequence pairs. Returns
List[int]
List of token type IDs according to the given sequence(s).
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A FAIRSEQ
Transformer sequence pair mask has the following format:
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence | second sequence |
If token_ids_1
is None
, this method only returns the first portion of the mask (0s).
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An FAIRSEQ_TRANSFORMER sequence pair mask has the following format:
( config: FSMTConfig )
Parameters
The bare FSMT Model outputting raw hidden-states without any specific head on top.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
( input_ids: LongTensor attention_mask: Optional = None decoder_input_ids: Optional = None decoder_attention_mask: Optional = None head_mask: Optional = None decoder_head_mask: Optional = None cross_attn_head_mask: Optional = None encoder_outputs: Optional = None past_key_values: Optional = None use_cache: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None inputs_embeds: Optional = None decoder_inputs_embeds: Optional = None return_dict: Optional = None ) → transformers.modeling_outputs.Seq2SeqModelOutput or tuple(torch.FloatTensor)
Parameters
torch.LongTensor
of shape (batch_size, sequence_length)
) —
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using FSTMTokenizer
. See PreTrainedTokenizer.encode() and
PreTrainedTokenizer.call() for details.
torch.Tensor
of shape (batch_size, sequence_length)
, optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
torch.LongTensor
of 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_id
as the starting token for decoder_input_ids
generation. If past_key_values
is used, optionally only the last decoder_input_ids
have to be input (see past_key_values
).
torch.BoolTensor
of shape (batch_size, target_sequence_length)
, optional) —
Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids
. Causal mask will also
be used by default. torch.Tensor
of shape (encoder_layers, encoder_attention_heads)
, optional) —
Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in [0, 1]
:
torch.Tensor
of shape (decoder_layers, decoder_attention_heads)
, optional) —
Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in [0, 1]
:
torch.Tensor
of shape (decoder_layers, decoder_attention_heads)
, optional) —
Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in [0, 1]
:
Tuple(torch.FloatTensor)
, optional) —
Tuple consists of (last_hidden_state
, optional: hidden_states
, optional: attentions
)
last_hidden_state
of shape (batch_size, sequence_length, hidden_size)
is a sequence of hidden-states at
the output of the last layer of the encoder. Used in the cross-attention of the decoder. Tuple(torch.FloatTensor)
of length config.n_layers
with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)
) —
Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding.
If past_key_values
are used, the user can optionally input only the last decoder_input_ids
(those that
don’t have their past key value states given to this model) of shape (batch_size, 1)
instead of all
decoder_input_ids
of shape (batch_size, sequence_length)
. torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) —
Optionally, instead of passing input_ids
you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert input_ids
indices into associated vectors than the
model’s internal embedding lookup matrix. torch.FloatTensor
of shape (batch_size, target_sequence_length, hidden_size)
, optional) —
Optionally, instead of passing decoder_input_ids
you can choose to directly pass an embedded
representation. If past_key_values
is used, optionally only the last decoder_inputs_embeds
have to be
input (see past_key_values
). This is useful if you want more control over how to convert
decoder_input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.
If decoder_input_ids
and decoder_inputs_embeds
are both unset, decoder_inputs_embeds
takes the value
of inputs_embeds
.
bool
, optional, defaults to True
) —
If set to True
, past_key_values
key value states are returned and can be used to speed up decoding (see
past_key_values
). bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail. bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail. bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. Returns
transformers.modeling_outputs.Seq2SeqModelOutput or 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
of shape (batch_size, sequence_length, hidden_size)
) — Sequence of hidden-states at the output of the last layer of the decoder of the model.
If past_key_values
is used only the last hidden-state of the sequences of shape (batch_size, 1, hidden_size)
is output.
past_key_values (tuple(tuple(torch.FloatTensor))
, optional, returned when use_cache=True
is passed or when config.use_cache=True
) — Tuple of tuple(torch.FloatTensor)
of length config.n_layers
, with each tuple having 2 tensors of shape
(batch_size, num_heads, sequence_length, embed_size_per_head)
) and 2 additional tensors of shape
(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
.
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
blocks) that can be used (see past_key_values
input) to speed up sequential decoding.
decoder_hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
Hidden-states of the decoder at the output of each layer plus the optional initial embedding outputs.
decoder_attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
cross_attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
Attentions weights of the decoder’s cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.
encoder_last_hidden_state (torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) — Sequence of hidden-states at the output of the last layer of the encoder of the model.
encoder_hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
Hidden-states of the encoder at the output of each layer plus the optional initial embedding outputs.
encoder_attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
The FSMTModel forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example:
>>> from transformers import AutoTokenizer, FSMTModel
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/wmt19-ru-en")
>>> model = FSMTModel.from_pretrained("facebook/wmt19-ru-en")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
( config: FSMTConfig )
Parameters
The FSMT Model with a language modeling head. Can be used for summarization.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
( input_ids: LongTensor attention_mask: Optional = None decoder_input_ids: Optional = None decoder_attention_mask: Optional = None head_mask: Optional = None decoder_head_mask: Optional = None cross_attn_head_mask: Optional = None encoder_outputs: Optional = None past_key_values: Optional = None inputs_embeds: Optional = None decoder_inputs_embeds: Optional = None labels: Optional = None use_cache: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) → transformers.modeling_outputs.Seq2SeqLMOutput or tuple(torch.FloatTensor)
Parameters
torch.LongTensor
of shape (batch_size, sequence_length)
) —
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using FSTMTokenizer
. See PreTrainedTokenizer.encode() and
PreTrainedTokenizer.call() for details.
torch.Tensor
of shape (batch_size, sequence_length)
, optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]
:
torch.LongTensor
of 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_id
as the starting token for decoder_input_ids
generation. If past_key_values
is used, optionally only the last decoder_input_ids
have to be input (see past_key_values
).
torch.BoolTensor
of shape (batch_size, target_sequence_length)
, optional) —
Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids
. Causal mask will also
be used by default. torch.Tensor
of shape (encoder_layers, encoder_attention_heads)
, optional) —
Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in [0, 1]
:
torch.Tensor
of shape (decoder_layers, decoder_attention_heads)
, optional) —
Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in [0, 1]
:
torch.Tensor
of shape (decoder_layers, decoder_attention_heads)
, optional) —
Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in [0, 1]
:
Tuple(torch.FloatTensor)
, optional) —
Tuple consists of (last_hidden_state
, optional: hidden_states
, optional: attentions
)
last_hidden_state
of shape (batch_size, sequence_length, hidden_size)
is a sequence of hidden-states at
the output of the last layer of the encoder. Used in the cross-attention of the decoder. Tuple(torch.FloatTensor)
of length config.n_layers
with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)
) —
Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding.
If past_key_values
are used, the user can optionally input only the last decoder_input_ids
(those that
don’t have their past key value states given to this model) of shape (batch_size, 1)
instead of all
decoder_input_ids
of shape (batch_size, sequence_length)
. torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) —
Optionally, instead of passing input_ids
you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert input_ids
indices into associated vectors than the
model’s internal embedding lookup matrix. torch.FloatTensor
of shape (batch_size, target_sequence_length, hidden_size)
, optional) —
Optionally, instead of passing decoder_input_ids
you can choose to directly pass an embedded
representation. If past_key_values
is used, optionally only the last decoder_inputs_embeds
have to be
input (see past_key_values
). This is useful if you want more control over how to convert
decoder_input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.
If decoder_input_ids
and decoder_inputs_embeds
are both unset, decoder_inputs_embeds
takes the value
of inputs_embeds
.
bool
, optional, defaults to True
) —
If set to True
, past_key_values
key value states are returned and can be used to speed up decoding (see
past_key_values
). bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail. bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail. bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. torch.LongTensor
of 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 (see input_ids
docstring). Tokens with indices set to -100
are ignored
(masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size]
. Returns
transformers.modeling_outputs.Seq2SeqLMOutput or 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
of shape (1,)
, optional, returned when labels
is provided) — Language modeling loss.
logits (torch.FloatTensor
of shape (batch_size, sequence_length, config.vocab_size)
) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
past_key_values (tuple(tuple(torch.FloatTensor))
, optional, returned when use_cache=True
is passed or when config.use_cache=True
) — Tuple of tuple(torch.FloatTensor)
of length config.n_layers
, with each tuple having 2 tensors of shape
(batch_size, num_heads, sequence_length, embed_size_per_head)
) and 2 additional tensors of shape
(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
.
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
blocks) that can be used (see past_key_values
input) to speed up sequential decoding.
decoder_hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
decoder_attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
cross_attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
Attentions weights of the decoder’s cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.
encoder_last_hidden_state (torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
, optional) — Sequence of hidden-states at the output of the last layer of the encoder of the model.
encoder_hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
encoder_attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
The FSMTForConditionalGeneration forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Translation example::
>>> 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?"