ProphetNet (original) (raw)

PyTorch

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.

Usage tips

Resources

ProphetNetConfig

class transformers.ProphetNetConfig

< source >

( activation_dropout: typing.Optional[float] = 0.1 activation_function: typing.Union[str, typing.Callable, NoneType] = 'gelu' vocab_size: typing.Optional[int] = 30522 hidden_size: typing.Optional[int] = 1024 encoder_ffn_dim: typing.Optional[int] = 4096 num_encoder_layers: typing.Optional[int] = 12 num_encoder_attention_heads: typing.Optional[int] = 16 decoder_ffn_dim: typing.Optional[int] = 4096 num_decoder_layers: typing.Optional[int] = 12 num_decoder_attention_heads: typing.Optional[int] = 16 attention_dropout: typing.Optional[float] = 0.1 dropout: typing.Optional[float] = 0.1 max_position_embeddings: typing.Optional[int] = 512 init_std: typing.Optional[float] = 0.02 is_encoder_decoder: typing.Optional[bool] = True add_cross_attention: typing.Optional[bool] = True decoder_start_token_id: typing.Optional[int] = 0 ngram: typing.Optional[int] = 2 num_buckets: typing.Optional[int] = 32 relative_max_distance: typing.Optional[int] = 128 disable_ngram_loss: typing.Optional[bool] = False eps: typing.Optional[float] = 0.0 use_cache: typing.Optional[bool] = True pad_token_id: typing.Optional[int] = 0 bos_token_id: typing.Optional[int] = 1 eos_token_id: typing.Optional[int] = 2 **kwargs )

Parameters

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. Instantiating a configuration with the defaults will yield a similar configuration to that of the ProphetNetmicrosoft/prophetnet-large-uncased architecture.

Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.

ProphetNetTokenizer

class transformers.ProphetNetTokenizer

< source >

( vocab_file: str do_lower_case: typing.Optional[bool] = True do_basic_tokenize: typing.Optional[bool] = True never_split: typing.Optional[typing.Iterable] = None unk_token: typing.Optional[str] = '[UNK]' sep_token: typing.Optional[str] = '[SEP]' x_sep_token: typing.Optional[str] = '[X_SEP]' pad_token: typing.Optional[str] = '[PAD]' mask_token: typing.Optional[str] = '[MASK]' tokenize_chinese_chars: typing.Optional[bool] = True strip_accents: typing.Optional[bool] = None clean_up_tokenization_spaces: bool = True **kwargs )

Parameters

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.

build_inputs_with_special_tokens

< source >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]

Parameters

List of input IDs with the appropriate special tokens.

Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A BERT sequence has the following format:

convert_tokens_to_string

< source >

( tokens: str )

Converts a sequence of tokens (string) in a single string.

create_token_type_ids_from_sequences

< source >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]

Parameters

List of token type IDs according to the given sequence(s).

Create a mask from the two sequences passed to be used in a sequence-pair classification task. A 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 is None, this method only returns the first portion of the mask (0s).

get_special_tokens_mask

< source >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None already_has_special_tokens: typing.Optional[bool] = False ) → List[int]

Parameters

A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.

Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer prepare_for_model method.

ProphetNet specific outputs

class transformers.models.prophetnet.modeling_prophetnet.ProphetNetSeq2SeqLMOutput

< source >

( loss: typing.Optional[torch.FloatTensor] = None logits: typing.Optional[torch.FloatTensor] = None logits_ngram: typing.Optional[torch.FloatTensor] = None past_key_values: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_ngram_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_ngram_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None cross_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None encoder_last_hidden_state: typing.Optional[torch.FloatTensor] = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None encoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

Parameters

Base class for sequence-to-sequence language models outputs.

class transformers.models.prophetnet.modeling_prophetnet.ProphetNetSeq2SeqModelOutput

< source >

( last_hidden_state: FloatTensor last_hidden_state_ngram: typing.Optional[torch.FloatTensor] = None past_key_values: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_ngram_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_ngram_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None cross_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None encoder_last_hidden_state: typing.Optional[torch.FloatTensor] = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None encoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

Parameters

Base class for model encoder’s outputs that also contains : pre-computed hidden states that can speed up sequential decoding.

class transformers.models.prophetnet.modeling_prophetnet.ProphetNetDecoderModelOutput

< source >

( last_hidden_state: FloatTensor last_hidden_state_ngram: typing.Optional[torch.FloatTensor] = None past_key_values: typing.Optional[typing.Tuple[torch.FloatTensor]] = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None hidden_states_ngram: typing.Optional[typing.Tuple[torch.FloatTensor]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None ngram_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None cross_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

Parameters

Base class for model’s outputs that may also contain a past key/values (to speed up sequential decoding).

class transformers.models.prophetnet.modeling_prophetnet.ProphetNetDecoderLMOutput

< source >

( loss: typing.Optional[torch.FloatTensor] = None logits: typing.Optional[torch.FloatTensor] = None logits_ngram: typing.Optional[torch.FloatTensor] = None past_key_values: typing.Optional[typing.Tuple[torch.FloatTensor]] = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None hidden_states_ngram: typing.Optional[typing.Tuple[torch.FloatTensor]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None ngram_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None cross_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

Parameters

Base class for model’s outputs that may also contain a past key/values (to speed up sequential decoding).

ProphetNetModel

class transformers.ProphetNetModel

< source >

( config: ProphetNetConfig )

Parameters

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

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.

forward

< source >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None decoder_input_ids: typing.Optional[torch.Tensor] = None decoder_attention_mask: typing.Optional[torch.BoolTensor] = None head_mask: typing.Optional[torch.Tensor] = None decoder_head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[typing.Tuple] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = None inputs_embeds: typing.Optional[torch.Tensor] = None decoder_inputs_embeds: typing.Optional[torch.Tensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.prophetnet.modeling_prophetnet.ProphetNetSeq2SeqModelOutput or tuple(torch.FloatTensor)

Parameters

A transformers.models.prophetnet.modeling_prophetnet.ProphetNetSeq2SeqModelOutput or a tuple oftorch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (ProphetNetConfig) and inputs.

The ProphetNetModel forward method, overrides the __call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call the Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

from transformers import AutoTokenizer, ProphetNetModel

tokenizer = AutoTokenizer.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
decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids
outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)

last_hidden_states = outputs.last_hidden_state
last_hidden_states_ngram = outputs.last_hidden_state_ngram

ProphetNetEncoder

class transformers.ProphetNetEncoder

< source >

( config: ProphetNetConfig word_embeddings: Embedding = None )

Parameters

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

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.

forward

< source >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutput or tuple(torch.FloatTensor)

Parameters

A transformers.modeling_outputs.BaseModelOutput or a tuple oftorch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (ProphetNetConfig) and inputs.

The ProphetNetEncoder forward method, overrides the __call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call the Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

from transformers import AutoTokenizer, ProphetNetEncoder import torch

tokenizer = AutoTokenizer.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

ProphetNetDecoder

class transformers.ProphetNetDecoder

< source >

( config: ProphetNetConfig word_embeddings: typing.Optional[torch.nn.modules.sparse.Embedding] = None )

Parameters

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

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.

forward

< source >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None encoder_hidden_states: typing.Optional[torch.Tensor] = None encoder_attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = None inputs_embeds: typing.Optional[torch.Tensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.prophetnet.modeling_prophetnet.ProphetNetDecoderModelOutput or tuple(torch.FloatTensor)

Parameters

A transformers.models.prophetnet.modeling_prophetnet.ProphetNetDecoderModelOutput or a tuple oftorch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (ProphetNetConfig) and inputs.

The ProphetNetDecoder forward method, overrides the __call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call the Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

from transformers import AutoTokenizer, ProphetNetDecoder import torch

tokenizer = AutoTokenizer.from_pretrained("microsoft/prophetnet-large-uncased") model = ProphetNetDecoder.from_pretrained("microsoft/prophetnet-large-uncased", add_cross_attention=False) inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") outputs = model(**inputs)

last_hidden_states = outputs.last_hidden_state

ProphetNetForConditionalGeneration

class transformers.ProphetNetForConditionalGeneration

< source >

( config: ProphetNetConfig )

Parameters

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

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.

forward

< source >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None decoder_input_ids: typing.Optional[torch.Tensor] = None decoder_attention_mask: typing.Optional[torch.BoolTensor] = None head_mask: typing.Optional[torch.Tensor] = None decoder_head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[torch.Tensor] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = None inputs_embeds: typing.Optional[torch.Tensor] = None decoder_inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.prophetnet.modeling_prophetnet.ProphetNetSeq2SeqLMOutput or tuple(torch.FloatTensor)

Parameters

A transformers.models.prophetnet.modeling_prophetnet.ProphetNetSeq2SeqLMOutput or a tuple oftorch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (ProphetNetConfig) and inputs.

The ProphetNetForConditionalGeneration forward method, overrides the __call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call the Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

from transformers import AutoTokenizer, ProphetNetForConditionalGeneration

tokenizer = AutoTokenizer.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
decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids
outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)

logits_next_token = outputs.logits
logits_ngram_next_tokens = outputs.logits_ngram

ProphetNetForCausalLM

class transformers.ProphetNetForCausalLM

< source >

( config: ProphetNetConfig )

Parameters

The standalone decoder part of the ProphetNetModel with a lm head on top. The model can be used for causal

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.

forward

< source >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None encoder_hidden_states: typing.Optional[torch.Tensor] = None encoder_attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.prophetnet.modeling_prophetnet.ProphetNetDecoderLMOutput or tuple(torch.FloatTensor)

Parameters

A transformers.models.prophetnet.modeling_prophetnet.ProphetNetDecoderLMOutput or a tuple oftorch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (ProphetNetConfig) and inputs.

The ProphetNetForCausalLM forward method, overrides the __call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call the Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

from transformers import AutoTokenizer, ProphetNetForCausalLM import torch

tokenizer = AutoTokenizer.from_pretrained("microsoft/prophetnet-large-uncased") model = ProphetNetForCausalLM.from_pretrained("microsoft/prophetnet-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

from transformers import BertTokenizer, EncoderDecoderModel, AutoTokenizer import torch

tokenizer_enc = BertTokenizer.from_pretrained("google-bert/bert-large-uncased") tokenizer_dec = AutoTokenizer.from_pretrained("microsoft/prophetnet-large-uncased") model = EncoderDecoderModel.from_encoder_decoder_pretrained( ... "google-bert/bert-large-uncased", "microsoft/prophetnet-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

< > Update on GitHub