ProphetNetΒΆ
DISCLAIMER: If you see something strange, file a Github Issue and assign @patrickvonplaten
OverviewΒΆ
The ProphetNet model was proposed in ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training, by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang, Ming Zhou on 13 Jan, 2020.
ProphetNet is an encoder-decoder model and can predict n-future tokens for βngramβ language modeling instead of just the next token.
The abstract from the paper is the following:
In this paper, we present a new sequence-to-sequence pretraining model called ProphetNet, which introduces a novel self-supervised objective named future n-gram prediction and the proposed n-stream self-attention mechanism. Instead of the optimization of one-step ahead prediction in traditional sequence-to-sequence model, the ProphetNet is optimized by n-step ahead prediction which predicts the next n tokens simultaneously based on previous context tokens at each time step. The future n-gram prediction explicitly encourages the model to plan for the future tokens and prevent overfitting on strong local correlations. We pre-train ProphetNet using a base scale dataset (16GB) and a large scale dataset (160GB) respectively. Then we conduct experiments on CNN/DailyMail, Gigaword, and SQuAD 1.1 benchmarks for abstractive summarization and question generation tasks. Experimental results show that ProphetNet achieves new state-of-the-art results on all these datasets compared to the models using the same scale pretraining corpus.
The Authorsβ code can be found here.
ProphetNetConfigΒΆ
-
class
transformers.
ProphetNetConfig
(activation_dropout=0.1, activation_function='gelu', vocab_size=30522, hidden_size=1024, encoder_ffn_dim=4096, num_encoder_layers=12, num_encoder_attention_heads=16, decoder_ffn_dim=4096, num_decoder_layers=12, num_decoder_attention_heads=16, attention_dropout=0.1, dropout=0.1, max_position_embeddings=512, init_std=0.02, is_encoder_decoder=True, add_cross_attention=True, decoder_start_token_id=0, ngram=2, num_buckets=32, relative_max_distance=128, disable_ngram_loss=False, eps=0.0, use_cache=True, pad_token_id=0, bos_token_id=1, eos_token_id=2, **kwargs)[source]ΒΆ This is the configuration class to store the configuration of a
ProphetNetModel
. It is used to instantiate a ProphetNet 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
activation_dropout (
float
, optional, defaults to 0.1) β The dropout ratio for activations inside the fully connected layer.activation_function (
str
orfunction
, optional, defaults to"gelu"
) β The non-linear activation function (function or string) in the encoder and pooler. If string,"gelu"
,"relu"
,"silu"
and"gelu_new"
are supported.vocab_size (
int
, optional, defaults to 30522) β Vocabulary size of the ProphetNET model. Defines the number of different tokens that can be represented by theinputs_ids
passed when callingProphetNetModel
.hidden_size (
int
, optional, defaults to 1024) β Dimensionality of the layers and the pooler layer.encoder_ffn_dim (
int
, optional, defaults to 4096) β Dimensionality of the βintermediateβ (often named feed-forward) layer in decoder.num_encoder_layers (
int
, optional, defaults to 12) β Number of encoder layers.num_encoder_attention_heads (
int
, optional, defaults to 16) β Number of attention heads for each attention layer in the Transformer encoder.decoder_ffn_dim (
int
, optional, defaults to 4096) β Dimensionality of theintermediate
(often named feed-forward) layer in decoder.num_decoder_layers (
int
, optional, defaults to 12) β Number of decoder layers.num_decoder_attention_heads (
int
, optional, defaults to 16) β Number of attention heads for each attention layer in the Transformer decoder.attention_dropout (
float
, optional, defaults to 0.1) β The dropout ratio for the attention probabilities.dropout (
float
, optional, defaults to 0.1) β The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.max_position_embeddings (
int
, optional, defaults to 512) β 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.add_cross_attention (
bool
, optional, defaults toTrue
) β Whether cross-attention layers should be added to the model.is_encoder_decoder (
bool
, optional, defaults toTrue
) β Whether this is an encoder/decoder model.pad_token_id (
int
, optional, defaults to 1) β Padding token id.bos_token_id (
int
, optional, defaults to 0) β Beginning of stream token id.eos_token_id (
int
, optional, defaults to 2) β End of stream token id.ngram (
int
, optional, defaults to 2) β Number of future tokens to predict. Set to 1 to be same as traditional Language model to predict next first token.num_buckets (
int
, optional, defaults to 32) β The number of buckets to use for each attention layer. This is for relative position calculation. See the T5 paper for more details.relative_max_distance (
int
, optional, defaults to 128) β Relative distances greater than this number will be put into the last same bucket. This is for relative position calculation. See the T5 paper for more details.disable_ngram_loss (
bool
, optional, defaults toFalse
) β Whether be trained predicting only the next first token.eps (
float
, optional, defaults to 0.0) β Controls theepsilon
parameter value for label smoothing in the loss calculation. If set to 0, no label smoothing is performed.use_cache (
bool
, optional, defaults toTrue
) β Whether or not the model should return the last key/values attentions (not used by all models).
ProphetNetTokenizerΒΆ
-
class
transformers.
ProphetNetTokenizer
(vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token='[UNK]', sep_token='[SEP]', x_sep_token='[X_SEP]', pad_token='[PAD]', mask_token='[MASK]', tokenize_chinese_chars=True, strip_accents=None, **kwargs)[source]ΒΆ Construct a ProphetNetTokenizer. Based on WordPiece.
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
vocab_file (
str
) β File containing the vocabulary.do_lower_case (
bool
, optional, defaults toTrue
) β Whether or not to lowercase the input when tokenizing.do_basic_tokenize (
bool
, optional, defaults toTrue
) β Whether or not to do basic tokenization before WordPiece.never_split (
Iterable
, optional) β Collection of tokens which will never be split during tokenization. Only has an effect whendo_basic_tokenize=True
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.sep_token (
str
, optional, defaults to"[SEP]"
) β 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.x_sep_token (
str
, optional, defaults to"[X_SEP]"
) β Special second separator token, which can be generated byProphetNetForConditionalGeneration
. It is used to separate bullet-point like sentences in summarization, e.g..pad_token (
str
, optional, defaults to"[PAD]"
) β The token used for padding, for example when batching sequences of different lengths.cls_token (
str
, optional, defaults to"[CLS]"
) β The classifier token which is used when doing sequence classification (classification of the whole sequence instead of per-token classification). It is the first token of the sequence when built with special tokens.mask_token (
str
, optional, defaults to"[MASK]"
) β The token used for masking values. This is the token used when training this model with masked language modeling. This is the token which the model will try to predict.tokenize_chinese_chars (
bool
, optional, defaults toTrue
) βWhether or not to tokenize Chinese characters.
This should likely be deactivated for Japanese (see this issue).
strip_accents β (
bool
, optional): Whether or not to strip all accents. If this option is not specified, then it will be determined by the value forlowercase
(as in the original BERT).
-
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 BERT sequence has the following format:
single sequence:
[CLS] X [SEP]
pair of sequences:
[CLS] A [SEP] B [SEP]
- 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]
-
convert_tokens_to_string
(tokens)[source]ΒΆ Converts a sequence of tokens (string) in a single string.
-
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 ProphetNet 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]
-
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]
-
get_vocab
()[source]ΒΆ Returns the vocabulary as a dictionary of token to index.
tokenizer.get_vocab()[token]
is equivalent totokenizer.convert_tokens_to_ids(token)
whentoken
is in the vocab.- Returns
The vocabulary.
- Return type
Dict[str, int]
-
prepare_seq2seq_batch
(src_texts: List[str], tgt_texts: Optional[List[str]] = None, max_length: Optional[int] = None, max_target_length: Optional[int] = None, padding: str = 'longest', return_tensors: str = None, truncation: bool = True, **kwargs) → transformers.tokenization_utils_base.BatchEncoding[source]ΒΆ Prepare model inputs for translation. For best performance, translate one sentence at a time.
- Parameters
src_texts (
List[str]
) β List of documents to summarize or source language texts.tgt_texts (
list
, optional) β List of summaries or target language texts.max_length (
int
, optional) β Controls the maximum length for encoder inputs (documents to summarize or source language texts) If left unset or set toNone
, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated.max_target_length (
int
, optional) β Controls the maximum length of decoder inputs (target language texts or summaries) If left unset or set toNone
, this will use the max_length value.padding (
bool
,str
orPaddingStrategy
, optional, defaults toFalse
) βActivates and controls padding. Accepts the following values:
True
or'longest'
: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).'max_length'
: Pad to a maximum length specified with the argumentmax_length
or to the maximum acceptable input length for the model if that argument is not provided.False
or'do_not_pad'
(default): No padding (i.e., can output a batch with sequences of different lengths).
return_tensors (
str
orTensorType
, optional) βIf set, will return tensors instead of list of python integers. Acceptable values are:
'tf'
: Return TensorFlowtf.constant
objects.'pt'
: Return PyTorchtorch.Tensor
objects.'np'
: Return Numpynp.ndarray
objects.
truncation (
bool
,str
orTruncationStrategy
, optional, defaults toTrue
) βActivates and controls truncation. Accepts the following values:
True
or'longest_first'
: Truncate to a maximum length specified with the argumentmax_length
or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.'only_first'
: Truncate to a maximum length specified with the argumentmax_length
or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.'only_second'
: Truncate to a maximum length specified with the argumentmax_length
or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.False
or'do_not_truncate'
(default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
**kwargs β Additional keyword arguments passed along to
self.__call__
.
- Returns
A
BatchEncoding
with the following fields:input_ids β List of token ids to be fed to the encoder.
attention_mask β List of indices specifying which tokens should be attended to by the model.
labels β List of token ids for tgt_texts.
The full set of keys
[input_ids, attention_mask, labels]
, will only be returned if tgt_texts is passed. Otherwise, input_ids, attention_mask will be the only keys.- Return type
-
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)
-
property
vocab_size
ΒΆ Size of the base vocabulary (without the added tokens).
- Type
int
ProphetNet specific outputsΒΆ
-
class
transformers.models.prophetnet.modeling_prophetnet.
ProphetNetSeq2SeqLMOutput
(loss: Optional[torch.FloatTensor] = None, logits: torch.FloatTensor = None, logits_ngram: Optional[torch.FloatTensor] = None, past_key_values: Optional[Tuple[torch.FloatTensor]] = None, decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, decoder_ngram_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None, decoder_ngram_attentions: Optional[Tuple[torch.FloatTensor]] = None, cross_attentions: Optional[Tuple[torch.FloatTensor]] = None, encoder_last_hidden_state: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ Base class for sequence-to-sequence language models outputs.
- Parameters
loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) β Language modeling loss.logits (
torch.FloatTensor
of shape(batch_size, decoder_sequence_length, config.vocab_size)
) β Prediction scores of the main stream language modeling head (scores for each vocabulary token before SoftMax).logits_ngram (
torch.FloatTensor
of shape(batch_size, ngram * decoder_sequence_length, config.vocab_size)
) β Prediction scores of the predict stream language modeling head (scores for each vocabulary token before SoftMax).past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) βList of
torch.FloatTensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_attn_heads, decoder_sequence_length, embed_size_per_head)
).Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder 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 of
torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, decoder_sequence_length, hidden_size)
.Hidden-states of main stream of the decoder at the output of each layer plus the initial embedding outputs.
decoder_ngram_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) βTuple of
torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, ngram * decoder_sequence_length, hidden_size)
.Hidden-states of the predict stream 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 of
torch.FloatTensor
(one for each layer) of shape(batch_size, num_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
decoder_ngram_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) βTuple of
torch.FloatTensor
(one for each layer) of shape(batch_size, num_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the predict stream 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 of
torch.FloatTensor
(one for each layer) of shape(batch_size, num_attn_heads, encoder_sequence_length, decoder_sequence_length)
.Attentions weights of the cross-attention layer of the decoder, after the attention softmax, used to compute the weighted average in the
encoder_last_hidden_state (
torch.FloatTensor
of shape(batch_size, encoder_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 of
torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, encoder_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_attn_heads, encoder_sequence_length, encoder_sequence_length)
. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
-
class
transformers.models.prophetnet.modeling_prophetnet.
ProphetNetSeq2SeqModelOutput
(last_hidden_state: torch.FloatTensor, last_hidden_state_ngram: Optional[torch.FloatTensor] = None, past_key_values: Optional[Tuple[torch.FloatTensor]] = None, decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, decoder_ngram_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None, decoder_ngram_attentions: Optional[Tuple[torch.FloatTensor]] = None, cross_attentions: Optional[Tuple[torch.FloatTensor]] = None, encoder_last_hidden_state: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ Base class for model encoderβs outputs that also contains : pre-computed hidden states that can speed up sequential decoding.
- Parameters
last_hidden_state (
torch.FloatTensor
of shape(batch_size, decoder_sequence_length, hidden_size)
) βSequence of main stream 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.last_hidden_state_ngram (
torch.FloatTensor
of shape(batch_size,ngram * decoder_sequence_length, config.vocab_size)
) β Sequence of predict stream hidden-states at the output of the last layer of the decoder of the model.past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) βList of
torch.FloatTensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_attn_heads, decoder_sequence_length, embed_size_per_head)
).Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder 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 of
torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, decoder_sequence_length, hidden_size)
.Hidden-states of main stream of the decoder at the output of each layer plus the initial embedding outputs.
decoder_ngram_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) βTuple of
torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, ngram * decoder_sequence_length, hidden_size)
.Hidden-states of the predict stream 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 of
torch.FloatTensor
(one for each layer) of shape(batch_size, num_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
decoder_ngram_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) βTuple of
torch.FloatTensor
(one for each layer) of shape(batch_size, num_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the predict stream of the decoder, after the attention softmax, used to compute the weighted average in the
cross_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) βTuple of
torch.FloatTensor
(one for each layer) of shape(batch_size, num_attn_heads, encoder_sequence_length, decoder_sequence_length)
.Attentions weights of the cross-attention layer of the decoder, after the attention softmax, used to compute the weighted average in the
encoder_last_hidden_state (
torch.FloatTensor
of shape(batch_size, encoder_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 of
torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, encoder_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 of
torch.FloatTensor
(one for each layer) of shape(batch_size, num_attn_heads, encoder_sequence_length, encoder_sequence_length)
.Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
-
class
transformers.models.prophetnet.modeling_prophetnet.
ProphetNetDecoderModelOutput
(last_hidden_state: torch.FloatTensor, last_hidden_state_ngram: Optional[torch.FloatTensor] = None, past_key_values: Optional[Tuple[torch.FloatTensor]] = None, hidden_states: Optional[Tuple[torch.FloatTensor]] = None, hidden_states_ngram: Optional[Tuple[torch.FloatTensor]] = None, attentions: Optional[Tuple[torch.FloatTensor]] = None, ngram_attentions: Optional[Tuple[torch.FloatTensor]] = None, cross_attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ Base class for modelβs outputs that may also contain a past key/values (to speed up sequential decoding).
- Parameters
last_hidden_state (
torch.FloatTensor
of shape(batch_size, decoder_sequence_length, hidden_size)
) βSequence of main stream 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.last_hidden_state_ngram (
torch.FloatTensor
of shape(batch_size, ngram * decoder_sequence_length, config.vocab_size)
) β Sequence of predict stream hidden-states at the output of the last layer of the decoder of the model.past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) βList of
torch.FloatTensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_attn_heads, decoder_sequence_length, embed_size_per_head)
).Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be used (see
past_key_values
input) to speed up sequential decoding.hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) βTuple of
torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, decoder_sequence_length, hidden_size)
.Hidden-states of main stream of the decoder at the output of each layer plus the initial embedding outputs.
ngram_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) βTuple of
torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, ngram * decoder_sequence_length, hidden_size)
.Hidden-states of the predict stream of the decoder at the output of each layer plus the initial embedding outputs.
attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) βTuple of
torch.FloatTensor
(one for each layer) of shape(batch_size, num_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
ngram_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) βTuple of
torch.FloatTensor
(one for each layer) of shape(batch_size, num_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the predict stream of the decoder, after the attention softmax, used to compute the weighted average in the
cross_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) βTuple of
torch.FloatTensor
(one for each layer) of shape(batch_size, num_attn_heads, encoder_sequence_length, decoder_sequence_length)
.Attentions weights of the cross-attention layer of the decoder, after the attention softmax, used to compute the weighted average in the
-
class
transformers.models.prophetnet.modeling_prophetnet.
ProphetNetDecoderLMOutput
(loss: Optional[torch.FloatTensor] = None, logits: torch.FloatTensor = None, logits_ngram: Optional[torch.FloatTensor] = None, past_key_values: Optional[Tuple[torch.FloatTensor]] = None, hidden_states: Optional[Tuple[torch.FloatTensor]] = None, hidden_states_ngram: Optional[Tuple[torch.FloatTensor]] = None, attentions: Optional[Tuple[torch.FloatTensor]] = None, ngram_attentions: Optional[Tuple[torch.FloatTensor]] = None, cross_attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ Base class for modelβs outputs that may also contain a past key/values (to speed up sequential decoding).
- Parameters
loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) β Language modeling loss.logits (
torch.FloatTensor
of shape(batch_size, decoder_sequence_length, config.vocab_size)
) β Prediction scores of the main stream language modeling head (scores for each vocabulary token before SoftMax).logits_ngram (
torch.FloatTensor
of shape(batch_size, ngram * decoder_sequence_length, config.vocab_size)
) β Prediction scores of the predict stream language modeling head (scores for each vocabulary token before SoftMax).past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) βList of
torch.FloatTensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_attn_heads, decoder_sequence_length, embed_size_per_head)
).Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be used (see
past_key_values
input) to speed up sequential decoding.hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) βTuple of
torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, decoder_sequence_length, hidden_size)
.Hidden-states of main stream of the decoder at the output of each layer plus the initial embedding outputs.
ngram_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) βTuple of
torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, ngram * decoder_sequence_length, hidden_size)
.Hidden-states of the predict stream of the decoder at the output of each layer plus the initial embedding outputs.
attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) βTuple of
torch.FloatTensor
(one for each layer) of shape(batch_size, num_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
ngram_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) βTuple of
torch.FloatTensor
(one for each layer) of shape(batch_size, num_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the predict stream of the decoder, after the attention softmax, used to compute the weighted average in the
cross_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) βTuple of
torch.FloatTensor
(one for each layer) of shape(batch_size, num_attn_heads, encoder_sequence_length, decoder_sequence_length)
.Attentions weights of the cross-attention layer of the decoder, after the attention softmax, used to compute the weighted average in the
ProphetNetModelΒΆ
-
class
transformers.
ProphetNetModel
(config)[source]ΒΆ The bare ProphetNet 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.)Original ProphetNet code can be found at <https://github.com/microsoft/ProphetNet> . Checkpoints were converted from original Fairseq checkpoints. For more information on the checkpoint conversion, please take a look at the file
convert_prophetnet_original_pytorch_checkpoint_to_pytorch.py
.This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matters related to general usage and behavior.
- Parameters
config (
ProphetNetConfig
) β 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=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, encoder_outputs: Optional[Tuple] = None, past_key_values=None, inputs_embeds=None, decoder_inputs_embeds=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
ProphetNetModel
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. Padding will be ignored by default should you provide it.
Indices can be obtained using
ProphetNetTokenizer
. 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 theinput_ids
to the right, following the paper.decoder_attention_mask (
torch.BoolTensor
of shape(batch_size, tgt_seq_len)
, optional) βDefault behavior: generate a tensor that ignores pad tokens in
decoder_input_ids
. Causal mask will also be used by default.If you want to change padding behavior, you should read
modeling_bart._prepare_decoder_inputs()
and modify to your needs. See diagram 1 in the paper for more information on the default strategy.encoder_outputs (
tuple(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)
, 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 (
tuple(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.
If
past_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) β 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
ProphetNetSeq2SeqModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (ProphenetConfig
) and inputs.last_hidden_state (
torch.FloatTensor
of shape(batch_size, decoder_sequence_length, hidden_size)
) β Sequence of main stream 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.last_hidden_state_ngram (
torch.FloatTensor
of shape(batch_size,ngram * decoder_sequence_length, config.vocab_size)
) β Sequence of predict stream hidden-states at the output of the last layer of the decoder of the model.past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) β List oftorch.FloatTensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_attn_heads, decoder_sequence_length, embed_size_per_head)
).Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder 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, decoder_sequence_length, hidden_size)
.Hidden-states of main stream of the decoder at the output of each layer plus the initial embedding outputs.
decoder_ngram_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, ngram * decoder_sequence_length, hidden_size)
.Hidden-states of the predict stream 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_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
decoder_ngram_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_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the predict stream of the decoder, after the attention softmax, used to compute the weighted average in the
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_attn_heads, encoder_sequence_length, decoder_sequence_length)
.Attentions weights of the cross-attention layer of the decoder, after the attention softmax, used to compute the weighted average in the
encoder_last_hidden_state (
torch.FloatTensor
of shape(batch_size, encoder_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, encoder_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_attn_heads, encoder_sequence_length, encoder_sequence_length)
.Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
Example:
>>> from transformers import ProphetNetTokenizer, ProphetNetModel >>> tokenizer = ProphetNetTokenizer.from_pretrained('microsoft/prophetnet-large-uncased') >>> model = ProphetNetModel.from_pretrained('microsoft/prophetnet-large-uncased') >>> input_ids = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt").input_ids # Batch size 1 >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1 >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids) >>> last_hidden_states = outputs.last_hidden_state # main stream hidden states >>> last_hidden_states_ngram = outputs.last_hidden_state_ngram # predict hidden states
- Return type
ProphetNetSeq2SeqModelOutput
ortuple(torch.FloatTensor)
ProphetNetEncoderΒΆ
-
class
transformers.
ProphetNetEncoder
(config: transformers.models.prophetnet.configuration_prophetnet.ProphetNetConfig, word_embeddings: torch.nn.modules.sparse.Embedding = None)[source]ΒΆ The standalone encoder part of the ProphetNetModel. 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.)Original ProphetNet code can be found at <https://github.com/microsoft/ProphetNet> . Checkpoints were converted from original Fairseq checkpoints. For more information on the checkpoint conversion, please take a look at the file
convert_prophetnet_original_pytorch_checkpoint_to_pytorch.py
.This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matters related to general usage and behavior.
- Parameters
config (
ProphetNetConfig
) β 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.
- word_embeddings (
torch.nn.Embeddings
of shape(config.vocab_size, config.hidden_size)
, optional): The word embedding parameters. This can be used to initialize
ProphetNetEncoder
with pre-defined word embeddings instead of randomely initialized word embeddings.
-
forward
(input_ids=None, attention_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
ProphetNetEncoder
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. Padding will be ignored by default should you provide it.
Indices can be obtained using
ProphetNetTokenizer
. 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.
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
BaseModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (ProphenetConfig
) 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 model.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 model at the output of each layer plus the initial embedding outputs.
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 after the attention softmax, used to compute the weighted average in the self-attention heads.
Example:
>>> from transformers import ProphetNetTokenizer, ProphetNetEncoder >>> import torch >>> tokenizer = ProphetNetTokenizer.from_pretrained('microsoft/prophetnet-large-uncased') >>> model = ProphetNetEncoder.from_pretrained('patrickvonplaten/prophetnet-large-uncased-standalone') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_states = outputs.last_hidden_state
- Return type
BaseModelOutput
ortuple(torch.FloatTensor)
ProphetNetDecoderΒΆ
-
class
transformers.
ProphetNetDecoder
(config: transformers.models.prophetnet.configuration_prophetnet.ProphetNetConfig, word_embeddings: torch.nn.modules.sparse.Embedding = None)[source]ΒΆ The standalone decoder part of the ProphetNetModel. 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.)Original ProphetNet code can be found at <https://github.com/microsoft/ProphetNet> . Checkpoints were converted from original Fairseq checkpoints. For more information on the checkpoint conversion, please take a look at the file
convert_prophetnet_original_pytorch_checkpoint_to_pytorch.py
.This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matters related to general usage and behavior.
- Parameters
config (
ProphetNetConfig
) β 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.
- word_embeddings (
torch.nn.Embeddings
of shape(config.vocab_size, config.hidden_size)
, optional): The word embedding parameters. This can be used to initialize
ProphetNetEncoder
with pre-defined word embeddings instead of randomely initialized word embeddings.
-
forward
(input_ids=None, attention_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, inputs_embeds=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
ProphetNetDecoder
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. Padding will be ignored by default should you provide it.
Indices can be obtained using
ProphetNetTokenizer
. 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.
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.encoder_hidden_states (
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. Used in the cross-attention if the model is configured as a decoder.encoder_attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) β Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in[0, 1]
:past_key_values (
tuple(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.
If
past_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) βIf set to
True
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
).1 for tokens that are not masked,
0 for tokens that are masked.
- Returns
A
ProphetNetDecoderModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (ProphenetConfig
) and inputs.last_hidden_state (
torch.FloatTensor
of shape(batch_size, decoder_sequence_length, hidden_size)
) β Sequence of main stream 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.last_hidden_state_ngram (
torch.FloatTensor
of shape(batch_size, ngram * decoder_sequence_length, config.vocab_size)
) β Sequence of predict stream hidden-states at the output of the last layer of the decoder of the model.past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) β List oftorch.FloatTensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_attn_heads, decoder_sequence_length, embed_size_per_head)
).Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be used (see
past_key_values
input) to speed up sequential decoding.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, decoder_sequence_length, hidden_size)
.Hidden-states of main stream of the decoder at the output of each layer plus the initial embedding outputs.
ngram_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, ngram * decoder_sequence_length, hidden_size)
.Hidden-states of the predict stream of the decoder at the output of each layer plus the initial embedding outputs.
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_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
ngram_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_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the predict stream of the decoder, after the attention softmax, used to compute the weighted average in the
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_attn_heads, encoder_sequence_length, decoder_sequence_length)
.Attentions weights of the cross-attention layer of the decoder, after the attention softmax, used to compute the weighted average in the
Example:
>>> from transformers import ProphetNetTokenizer, ProphetNetDecoder >>> import torch >>> tokenizer = ProphetNetTokenizer.from_pretrained('microsoft/prophetnet-large-uncased') >>> model = ProphetNetDecoder.from_pretrained('patrickvonplaten/prophetnet-large-uncased-standalone', add_cross_attention=False) >>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder." >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_states = outputs.last_hidden_state
- Return type
ProphetNetDecoderModelOutput
ortuple(torch.FloatTensor)
ProphetNetForConditionalGenerationΒΆ
-
class
transformers.
ProphetNetForConditionalGeneration
(config: transformers.models.prophetnet.configuration_prophetnet.ProphetNetConfig)[source]ΒΆ The ProphetNet Model with a language modeling head. Can be used for sequence generation tasks. 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.)Original ProphetNet code can be found at <https://github.com/microsoft/ProphetNet> . Checkpoints were converted from original Fairseq checkpoints. For more information on the checkpoint conversion, please take a look at the file
convert_prophetnet_original_pytorch_checkpoint_to_pytorch.py
.This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matters related to general usage and behavior.
- Parameters
config (
ProphetNetConfig
) β 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=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, encoder_outputs=None, past_key_values=None, inputs_embeds=None, decoder_inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
ProphetNetForConditionalGeneration
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. Padding will be ignored by default should you provide it.
Indices can be obtained using
ProphetNetTokenizer
. 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 theinput_ids
to the right, following the paper.decoder_attention_mask (
torch.BoolTensor
of shape(batch_size, tgt_seq_len)
, optional) βDefault behavior: generate a tensor that ignores pad tokens in
decoder_input_ids
. Causal mask will also be used by default.If you want to change padding behavior, you should read
modeling_bart._prepare_decoder_inputs()
and modify to your needs. See diagram 1 in the paper for more information on the default strategy.encoder_outputs (
tuple(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)
, 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 (
tuple(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.
If
past_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) β 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,)
, optional) β Labels for computing the sequence classification/regression loss. Indices should be in[-100, 0, ..., config.vocab_size - 1]
. All labels set to-100
are ignored (masked), the loss is only computed for labels in[0, ..., config.vocab_size]
- Returns
A
ProphetNetSeq2SeqLMOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (ProphenetConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) β Language modeling loss.logits (
torch.FloatTensor
of shape(batch_size, decoder_sequence_length, config.vocab_size)
) β Prediction scores of the main stream language modeling head (scores for each vocabulary token before SoftMax).logits_ngram (
torch.FloatTensor
of shape(batch_size, ngram * decoder_sequence_length, config.vocab_size)
) β Prediction scores of the predict stream language modeling head (scores for each vocabulary token before SoftMax).past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) β List oftorch.FloatTensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_attn_heads, decoder_sequence_length, embed_size_per_head)
).Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder 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, decoder_sequence_length, hidden_size)
.Hidden-states of main stream of the decoder at the output of each layer plus the initial embedding outputs.
decoder_ngram_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, ngram * decoder_sequence_length, hidden_size)
.Hidden-states of the predict stream 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_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
decoder_ngram_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_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the predict stream 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_attn_heads, encoder_sequence_length, decoder_sequence_length)
.Attentions weights of the cross-attention layer of the decoder, after the attention softmax, used to compute the weighted average in the
encoder_last_hidden_state (
torch.FloatTensor
of shape(batch_size, encoder_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, encoder_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_attn_heads, encoder_sequence_length, encoder_sequence_length)
. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
Example:
>>> from transformers import ProphetNetTokenizer, ProphetNetForConditionalGeneration >>> tokenizer = ProphetNetTokenizer.from_pretrained('microsoft/prophetnet-large-uncased') >>> model = ProphetNetForConditionalGeneration.from_pretrained('microsoft/prophetnet-large-uncased') >>> input_ids = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt").input_ids # Batch size 1 >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1 >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids) >>> logits_next_token = outputs.logits # logits to predict next token as usual >>> logits_ngram_next_tokens = outputs.logits_ngram # logits to predict 2nd, 3rd, ... next tokens
- Return type
ProphetNetSeq2SeqLMOutput
ortuple(torch.FloatTensor)
ProphetNetForCausalLMΒΆ
-
class
transformers.
ProphetNetForCausalLM
(config)[source]ΒΆ The standalone decoder part of the ProphetNetModel with a lm head on top. The model can be used for causal language modeling. 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.)Original ProphetNet code can be found at <https://github.com/microsoft/ProphetNet> . Checkpoints were converted from original Fairseq checkpoints. For more information on the checkpoint conversion, please take a look at the file
convert_prophetnet_original_pytorch_checkpoint_to_pytorch.py
.This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matters related to general usage and behavior.
- Parameters
config (
ProphetNetConfig
) β 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=None, attention_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
ProphetNetForCausalLM
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. Padding will be ignored by default should you provide it.
Indices can be obtained using
ProphetNetTokenizer
. 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.
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.encoder_hidden_states (
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. Used in the cross-attention if the model is configured as a decoder.encoder_attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) β Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in[0, 1]
:past_key_values (
tuple(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.
If
past_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) βIf set to
True
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
).1 for tokens that are not masked,
0 for tokens that are masked.
labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) β Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in[-100, 0, ..., config.vocab_size]
(seeinput_ids
docstring) Tokens with indices set to-100
are ignored (masked), the loss is only computed for the tokens with labels n[0, ..., config.vocab_size]
- Returns
A
ProphetNetDecoderLMOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (ProphenetConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) β Language modeling loss.logits (
torch.FloatTensor
of shape(batch_size, decoder_sequence_length, config.vocab_size)
) β Prediction scores of the main stream language modeling head (scores for each vocabulary token before SoftMax).logits_ngram (
torch.FloatTensor
of shape(batch_size, ngram * decoder_sequence_length, config.vocab_size)
) β Prediction scores of the predict stream language modeling head (scores for each vocabulary token before SoftMax).past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) β List oftorch.FloatTensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_attn_heads, decoder_sequence_length, embed_size_per_head)
).Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be used (see
past_key_values
input) to speed up sequential decoding.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, decoder_sequence_length, hidden_size)
.Hidden-states of main stream of the decoder at the output of each layer plus the initial embedding outputs.
ngram_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, ngram * decoder_sequence_length, hidden_size)
.Hidden-states of the predict stream of the decoder at the output of each layer plus the initial embedding outputs.
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_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
ngram_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_attn_heads, decoder_sequence_length, decoder_sequence_length)
.Attentions weights of the predict stream of the decoder, after the attention softmax, used to compute the weighted average in the
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_attn_heads, encoder_sequence_length, decoder_sequence_length)
.Attentions weights of the cross-attention layer of the decoder, after the attention softmax, used to compute the weighted average in the
Example:
>>> from transformers import ProphetNetTokenizer, ProphetNetForCausalLM >>> import torch >>> tokenizer = ProphetNetTokenizer.from_pretrained('microsoft/prophetnet-large-uncased') >>> model = ProphetNetForCausalLM.from_pretrained('patrickvonplaten/prophetnet-decoder-clm-large-uncased') >>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder." >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> logits = outputs.logits >>> # Model can also be used with EncoderDecoder framework >>> from transformers import BertTokenizer, EncoderDecoderModel, ProphetNetTokenizer >>> import torch >>> tokenizer_enc = BertTokenizer.from_pretrained('bert-large-uncased') >>> tokenizer_dec = ProphetNetTokenizer.from_pretrained('microsoft/prophetnet-large-uncased') >>> model = EncoderDecoderModel.from_encoder_decoder_pretrained("bert-large-uncased", "patrickvonplaten/prophetnet-decoder-clm-large-uncased") >>> ARTICLE = ( ... "the us state department said wednesday it had received no " ... "formal word from bolivia that it was expelling the us ambassador there " ... "but said the charges made against him are `` baseless ." ... ) >>> input_ids = tokenizer_enc(ARTICLE, return_tensors="pt").input_ids >>> labels = tokenizer_dec("us rejects charges against its ambassador in bolivia", return_tensors="pt").input_ids >>> outputs = model(input_ids=input_ids, decoder_input_ids=labels[:, :-1], labels=labels[:, 1:]) >>> loss = outputs.loss
- Return type
ProphetNetDecoderLMOutput
ortuple(torch.FloatTensor)