FSMT¶
DISCLAIMER: If you see something strange, file a Github Issue and assign @stas00.
Overview¶
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.
The original code can be found here <https://github.com/pytorch/fairseq/tree/master/examples/wmt19>__.
Implementation Notes¶
FSMT uses source and target vocabulary pairs that aren’t combined into one. It doesn’t share embeddings tokens either. Its tokenizer is very similar to
XLMTokenizer
and the main model is derived fromBartModel
.
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)[source]¶ 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.Configuration objects inherit from
PretrainedConfig
and can be used to control the model outputs. Read the documentation fromPretrainedConfig
for more information.- Parameters
langs (
List[str]
) – A list with source language and target_language (e.g., [‘en’, ‘ru’]).src_vocab_size (
int
) – Vocabulary size of the encoder. Defines the number of different tokens that can be represented by theinputs_ids
passed to the forward method in the encoder.tgt_vocab_size (
int
) – Vocabulary size of the decoder. Defines the number of different tokens that can be represented by theinputs_ids
passed to the forward method in the decoder.d_model (
int
, optional, defaults to 1024) – Dimensionality of the layers and the pooler layer.encoder_layers (
int
, optional, defaults to 12) – Number of encoder layers.decoder_layers (
int
, optional, defaults to 12) – Number of decoder layers.encoder_attention_heads (
int
, optional, defaults to 16) – Number of attention heads for each attention layer in the Transformer encoder.decoder_attention_heads (
int
, optional, defaults to 16) – Number of attention heads for each attention layer in the Transformer decoder.decoder_ffn_dim (
int
, optional, defaults to 4096) – Dimensionality of the “intermediate” (often named feed-forward) layer in decoder.encoder_ffn_dim (
int
, optional, defaults to 4096) – Dimensionality of the “intermediate” (often named feed-forward) layer in decoder.activation_function (
str
orCallable
, 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.dropout (
float
, optional, defaults to 0.1) – The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.attention_dropout (
float
, optional, defaults to 0.0) – The dropout ratio for the attention probabilities.activation_dropout (
float
, optional, defaults to 0.0) – The dropout ratio for activations inside the fully connected layer.max_position_embeddings (
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).init_std (
float
, optional, defaults to 0.02) – The standard deviation of the truncated_normal_initializer for initializing all weight matrices.scale_embedding (
bool
, optional, defaults toTrue
) – Scale embeddings by diving by sqrt(d_model).bos_token_id (
int
, optional, defaults to 0) – Beginning of stream token id.pad_token_id (
int
, optional, defaults to 1) – Padding token id.eos_token_id (
int
, optional, defaults to 2) – End of stream token 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 thegenerate
method of the model. 1 means no beam search.length_penalty (
float
, optional, defaults to 1) – Exponential penalty to the length that will be used by default in thegenerate
method of the model.early_stopping (
bool
, optional, defaults toFalse
) – Flag that will be used by default in thegenerate
method of the model. Whether to stop the beam search when at leastnum_beams
sentences 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_length
is reached. Usually set toeos_token_id
.Examples:: –
>>> from transformers import FSMTConfig, FSMTModel
>>> config = FSMTConfig.from_pretrained('facebook/wmt19-en-ru') >>> model = FSMTModel(config)
FSMTTokenizer¶
-
class
transformers.
FSMTTokenizer
(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)[source]¶ Construct an FAIRSEQ Transformer tokenizer. Based on Byte-Pair Encoding. The tokenization process is the following:
Moses preprocessing and tokenization.
Normalizing all inputs text.
The arguments
special_tokens
and the functionset_special_tokens
, can be used to add additional symbols (like “__classify__”) to a vocabulary.The argument
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.- Parameters
langs (
List[str]
) – A list of two languages to translate from and to, for instance["en", "ru"]
.src_vocab_file (
str
) – File containing the vocabulary for the source language.tgt_vocab_file (
st
) – File containing the vocabulary for the target language.merges_file (
str
) – 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.
Note
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.
-
build_inputs_with_special_tokens
(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None) → List[int][source]¶ 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:
single sequence:
<s> X </s>
pair of sequences:
<s> A </s> B </s>
- Parameters
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.
- Returns
List of input IDs with the appropriate special tokens.
- Return type
List[int]
-
create_token_type_ids_from_sequences
(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None) → List[int][source]¶ 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
isNone
, this method only returns the first portion of the mask (0s).- Parameters
token_ids_0 (
List[int]
) – List of IDs.token_ids_1 (
List[int]
, optional) – Optional second list of IDs for sequence pairs.
- Returns
List of token type IDs according to the given sequence(s).
- Return type
List[int]
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:
-
get_special_tokens_mask
(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False) → List[int][source]¶ 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.- Parameters
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.
- Returns
A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
- Return type
List[int]
-
save_vocabulary
(save_directory: str, filename_prefix: Optional[str] = None) → Tuple[str][source]¶ Save only the vocabulary of the tokenizer (vocabulary + added tokens).
This method won’t save the configuration and special token mappings of the tokenizer. Use
_save_pretrained()
to save the whole state of the tokenizer.- Parameters
save_directory (
str
) – The directory in which to save the vocabulary.filename_prefix (
str
, optional) – An optional prefix to add to the named of the saved files.
- Returns
Paths to the files saved.
- Return type
Tuple(str)
FSMTModel¶
-
class
transformers.
FSMTModel
(config: transformers.models.fsmt.configuration_fsmt.FSMTConfig)[source]¶ 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.
- Parameters
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 thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, encoder_outputs: Optional[Tuple] = None, past_key_values=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]¶ The
FSMTModel
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) –Indices of input sequence tokens in the vocabulary.
IIndices can be obtained using
FSTMTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.Tensor
of 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.LongTensor
of shape(batch_size, target_sequence_length)
, optional) – Provide for translation and summarization training. By default, the model will create this tensor by shifting the input_ids right, following the paper.decoder_attention_mask (
torch.BoolTensor
of 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. If you want to change padding behavior, you should readmodeling_fstm._prepare_fstm_decoder_inputs()
and modify. See diagram 1 in the paper for more info on the default strategyhead_mask (
torch.Tensor
of shape(num_layers, num_heads)
, optional) –Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in
[0, 1]
:1 indicates the head is not masked,
0 indicates the heas is masked.
decoder_head_mask (
torch.Tensor
of shape(num_layers, num_heads)
, optional) –Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in
[0, 1]
:1 indicates the head is not masked,
0 indicates the head is masked.
encoder_outputs (
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.past_key_values (
Tuple(torch.FloatTensor)
of lengthconfig.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. Ifpast_key_values
are used, the user can optionally input only the lastdecoder_input_ids
(those that don’t have their past key value states given to this model) of shape(batch_size, 1)
instead of alldecoder_input_ids
of shape(batch_size, sequence_length)
.use_cache (
bool
, optional, defaults toTrue
) – If set toTrue
,past_key_values
key 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. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) – Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) – Whether or not to return aModelOutput
instead of a plain tuple.
- Returns
A
Seq2SeqModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
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 whenuse_cache=True
is passed or whenconfig.use_cache=True
) – Tuple oftuple(torch.FloatTensor)
of lengthconfig.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftorch.FloatTensor
(one for the output of the embeddings + 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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftorch.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftorch.FloatTensor
(one for the output of the embeddings + 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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftorch.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.
- Return type
Seq2SeqModelOutput
ortuple(torch.FloatTensor)
Example:
>>> from transformers import FSMTTokenizer, FSMTModel >>> import torch >>> tokenizer = FSMTTokenizer.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
FSMTForConditionalGeneration¶
-
class
transformers.
FSMTForConditionalGeneration
(config: transformers.models.fsmt.configuration_fsmt.FSMTConfig)[source]¶ 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.
- Parameters
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 thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, encoder_outputs=None, past_key_values=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]¶ The
FSMTForConditionalGeneration
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) –Indices of input sequence tokens in the vocabulary.
IIndices can be obtained using
FSTMTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.Tensor
of 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.LongTensor
of shape(batch_size, target_sequence_length)
, optional) – Provide for translation and summarization training. By default, the model will create this tensor by shifting the input_ids right, following the paper.decoder_attention_mask (
torch.BoolTensor
of 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. If you want to change padding behavior, you should readmodeling_fstm._prepare_fstm_decoder_inputs()
and modify. See diagram 1 in the paper for more info on the default strategyhead_mask (
torch.Tensor
of shape(num_layers, num_heads)
, optional) –Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in
[0, 1]
:1 indicates the head is not masked,
0 indicates the heas is masked.
decoder_head_mask (
torch.Tensor
of shape(num_layers, num_heads)
, optional) –Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in
[0, 1]
:1 indicates the head is not masked,
0 indicates the head is masked.
encoder_outputs (
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.past_key_values (
Tuple(torch.FloatTensor)
of lengthconfig.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. Ifpast_key_values
are used, the user can optionally input only the lastdecoder_input_ids
(those that don’t have their past key value states given to this model) of shape(batch_size, 1)
instead of alldecoder_input_ids
of shape(batch_size, sequence_length)
.use_cache (
bool
, optional, defaults toTrue
) – If set toTrue
,past_key_values
key 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. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) – Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) – Whether or not to return aModelOutput
instead of a plain tuple.labels (
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 (seeinput_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
A
Seq2SeqLMOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (FSMTConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
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 whenuse_cache=True
is passed or whenconfig.use_cache=True
) – Tuple oftuple(torch.FloatTensor)
of lengthconfig.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftorch.FloatTensor
(one for the output of the embeddings + 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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftorch.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftorch.FloatTensor
(one for the output of the embeddings + 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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftorch.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.
- Return type
Seq2SeqLMOutput
ortuple(torch.FloatTensor)
Translation example:
from transformers import FSMTTokenizer, FSMTForConditionalGeneration mname = "facebook/wmt19-ru-en" model = FSMTForConditionalGeneration.from_pretrained(mname) tokenizer = FSMTTokenizer.from_pretrained(mname) src_text = "Машинное обучение - это здорово, не так ли?" input_ids = tokenizer.encode(src_text, return_tensors='pt') outputs = model.generate(input_ids, num_beams=5, num_return_sequences=3) for i, output in enumerate(outputs): decoded = tokenizer.decode(output, skip_special_tokens=True) print(f"{i}: {decoded}) # 1: Machine learning is great, isn't it? ...