REALM
REALM
Overview
The REALM model was proposed in REALM: Retrieval-Augmented Language Model Pre-Training by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang. It’s a retrieval-augmented language model that firstly retrieves documents from a textual knowledge corpus and then utilizes retrieved documents to process question answering tasks.
The abstract from the paper is the following:
Language model pre-training has been shown to capture a surprising amount of world knowledge, crucial for NLP tasks such as question answering. However, this knowledge is stored implicitly in the parameters of a neural network, requiring ever-larger networks to cover more facts. To capture knowledge in a more modular and interpretable way, we augment language model pre-training with a latent knowledge retriever, which allows the model to retrieve and attend over documents from a large corpus such as Wikipedia, used during pre-training, fine-tuning and inference. For the first time, we show how to pre-train such a knowledge retriever in an unsupervised manner, using masked language modeling as the learning signal and backpropagating through a retrieval step that considers millions of documents. We demonstrate the effectiveness of Retrieval-Augmented Language Model pre-training (REALM) by fine-tuning on the challenging task of Open-domain Question Answering (Open-QA). We compare against state-of-the-art models for both explicit and implicit knowledge storage on three popular Open-QA benchmarks, and find that we outperform all previous methods by a significant margin (4-16% absolute accuracy), while also providing qualitative benefits such as interpretability and modularity.
This model was contributed by qqaatw. The original code can be found here.
RealmConfig
class transformers.RealmConfig
( vocab_size = 30522hidden_size = 768retriever_proj_size = 128num_hidden_layers = 12num_attention_heads = 12num_candidates = 8intermediate_size = 3072hidden_act = 'gelu_new'hidden_dropout_prob = 0.1attention_probs_dropout_prob = 0.1max_position_embeddings = 512type_vocab_size = 2initializer_range = 0.02layer_norm_eps = 1e-12span_hidden_size = 256max_span_width = 10reader_layer_norm_eps = 0.001reader_beam_size = 5reader_seq_len = 320num_block_records = 13353718searcher_beam_size = 5000pad_token_id = 1bos_token_id = 0eos_token_id = 2**kwargs )
Parameters
vocab_size (
int
, optional, defaults to 30522) — Vocabulary size of the REALM model. Defines the number of different tokens that can be represented by theinputs_ids
passed when calling RealmEmbedder, RealmScorer, RealmKnowledgeAugEncoder, or RealmReader.hidden_size (
int
, optional, defaults to 768) — Dimension of the encoder layers and the pooler layer.retriever_proj_size (
int
, optional, defaults to 128) — Dimension of the retriever(embedder) projection.num_hidden_layers (
int
, optional, defaults to 12) — Number of hidden layers in the Transformer encoder.num_attention_heads (
int
, optional, defaults to 12) — Number of attention heads for each attention layer in the Transformer encoder.num_candidates (
int
, optional, defaults to 8) — Number of candidates inputted to the RealmScorer or RealmKnowledgeAugEncoder.intermediate_size (
int
, optional, defaults to 3072) — Dimension of the “intermediate” (i.e., feed-forward) layer in the Transformer encoder.hidden_act (
str
orfunction
, optional, defaults to"gelu_new"
) — The non-linear activation function (function or string) in the encoder and pooler. If string,"gelu"
,"relu"
,"selu"
and"gelu_new"
are supported.hidden_dropout_prob (
float
, optional, defaults to 0.1) — The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.attention_probs_dropout_prob (
float
, optional, defaults to 0.1) — The dropout ratio for the attention probabilities.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).type_vocab_size (
int
, optional, defaults to 2) — The vocabulary size of thetoken_type_ids
passed when calling RealmEmbedder, RealmScorer, RealmKnowledgeAugEncoder, or RealmReader.initializer_range (
float
, optional, defaults to 0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices.layer_norm_eps (
float
, optional, defaults to 1e-12) — The epsilon used by the layer normalization layers.span_hidden_size (
int
, optional, defaults to 256) — Dimension of the reader’s spans.max_span_width (
int
, optional, defaults to 10) — Max span width of the reader.reader_layer_norm_eps (
float
, optional, defaults to 1e-3) — The epsilon used by the reader’s layer normalization layers.reader_beam_size (
int
, optional, defaults to 5) — Beam size of the reader.reader_seq_len (
int
, optional, defaults to 288+32) — Maximum sequence length of the reader.num_block_records (
int
, optional, defaults to 13353718) — Number of block records.searcher_beam_size (
int
, optional, defaults to 5000) — Beam size of the searcher. Note that when eval mode is enabled, searcher_beam_size will be the same as reader_beam_size.
This is the configuration class to store the configuration of
It is used to instantiate an REALM 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 REALM google/realm-cc-news-pretrained-embedder architecture.
Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.
Example:
Copied
RealmTokenizer
class transformers.RealmTokenizer
( vocab_filedo_lower_case = Truedo_basic_tokenize = Truenever_split = Noneunk_token = '[UNK]'sep_token = '[SEP]'pad_token = '[PAD]'cls_token = '[CLS]'mask_token = '[MASK]'tokenize_chinese_chars = Truestrip_accents = None**kwargs )
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.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).
Construct a REALM tokenizer.
RealmTokenizer is identical to BertTokenizer and runs end-to-end tokenization: punctuation splitting and 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
( token_ids_0: typing.List[int]token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
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[int]
List of input IDs with the appropriate special tokens.
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A REALM sequence has the following format:
single sequence:
[CLS] X [SEP]
pair of sequences:
[CLS] A [SEP] B [SEP]
get_special_tokens_mask
( token_ids_0: typing.List[int]token_ids_1: typing.Optional[typing.List[int]] = Nonealready_has_special_tokens: bool = False ) → List[int]
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
List[int]
A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer prepare_for_model
method.
create_token_type_ids_from_sequences
( token_ids_0: typing.List[int]token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
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[int]
List of token type IDs according to the given sequence(s).
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A REALM sequence
pair mask has the following format:
Copied
If token_ids_1
is None
, this method only returns the first portion of the mask (0s).
save_vocabulary
( save_directory: strfilename_prefix: typing.Optional[str] = None )
batch_encode_candidates
( text**kwargs ) → BatchEncoding
Parameters
text (
List[List[str]]
) — The batch of sequences to be encoded. Each sequence must be in this format: (batch_size, num_candidates, text).text_pair (
List[List[str]]
, optional) — The batch of sequences to be encoded. Each sequence must be in this format: (batch_size, num_candidates, text). **kwargs — Keyword arguments of the call method.
Returns
Encoded text or text pair.
Encode a batch of text or text pair. This method is similar to regular call method but has the following differences:
Handle additional num_candidate axis. (batch_size, num_candidates, text)
Always pad the sequences to max_length.
Must specify max_length in order to stack packs of candidates into a batch.
single sequence:
[CLS] X [SEP]
pair of sequences:
[CLS] A [SEP] B [SEP]
Example:
Copied
RealmTokenizerFast
class transformers.RealmTokenizerFast
( vocab_file = Nonetokenizer_file = Nonedo_lower_case = Trueunk_token = '[UNK]'sep_token = '[SEP]'pad_token = '[PAD]'cls_token = '[CLS]'mask_token = '[MASK]'tokenize_chinese_chars = Truestrip_accents = None**kwargs )
Parameters
vocab_file (
str
) — File containing the vocabulary.do_lower_case (
bool
, optional, defaults toTrue
) — Whether or not to lowercase the input when tokenizing.unk_token (
str
, optional, defaults to"[UNK]"
) — The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead.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.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.clean_text (
bool
, optional, defaults toTrue
) — Whether or not to clean the text before tokenization by removing any control characters and replacing all whitespaces by the classic one.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).wordpieces_prefix (
str
, optional, defaults to"##"
) — The prefix for subwords.
Construct a “fast” REALM tokenizer (backed by BOINCAI’s tokenizers library). Based on WordPiece.
RealmTokenizerFast is identical to BertTokenizerFast and runs end-to-end tokenization: punctuation splitting and wordpiece.
This tokenizer inherits from PreTrainedTokenizerFast which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.
batch_encode_candidates
( text**kwargs ) → BatchEncoding
Parameters
text (
List[List[str]]
) — The batch of sequences to be encoded. Each sequence must be in this format: (batch_size, num_candidates, text).text_pair (
List[List[str]]
, optional) — The batch of sequences to be encoded. Each sequence must be in this format: (batch_size, num_candidates, text). **kwargs — Keyword arguments of the call method.
Returns
Encoded text or text pair.
Encode a batch of text or text pair. This method is similar to regular call method but has the following differences:
Handle additional num_candidate axis. (batch_size, num_candidates, text)
Always pad the sequences to max_length.
Must specify max_length in order to stack packs of candidates into a batch.
single sequence:
[CLS] X [SEP]
pair of sequences:
[CLS] A [SEP] B [SEP]
Example:
Copied
RealmRetriever
class transformers.RealmRetriever
( block_recordstokenizer )
Parameters
block_records (
np.ndarray
) — A numpy array which cantains evidence texts.tokenizer (RealmTokenizer) — The tokenizer to encode retrieved texts.
The retriever of REALM outputting the retrieved evidence block and whether the block has answers as well as answer positions.”
block_has_answer
( concat_inputsanswer_ids )
check if retrieved_blocks has answers.
RealmEmbedder
class transformers.RealmEmbedder
( config )
Parameters
config (RealmConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The embedder of REALM outputting projected score that will be used to calculate relevance score. 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 matter related to general usage and behavior.
forward
( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.FloatTensor] = Nonetoken_type_ids: typing.Optional[torch.LongTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonehead_mask: typing.Optional[torch.FloatTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → transformers.models.realm.modeling_realm.RealmEmbedderOutput
or tuple(torch.FloatTensor)
Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
attention_mask (
torch.FloatTensor
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.
token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.max_position_embeddings - 1]
.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1 indicates the head is not masked,
0 indicates the head is masked.
inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.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 a ModelOutput instead of a plain tuple.
Returns
transformers.models.realm.modeling_realm.RealmEmbedderOutput
or tuple(torch.FloatTensor)
A transformers.models.realm.modeling_realm.RealmEmbedderOutput
or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (RealmConfig) and inputs.
projected_score (
torch.FloatTensor
of shape(batch_size, config.retriever_proj_size)
) — Projected score.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.
The RealmEmbedder forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Example:
Copied
RealmScorer
class transformers.RealmScorer
( configquery_embedder = None )
Parameters
config (RealmConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
query_embedder (RealmEmbedder) — Embedder for input sequences. If not specified, it will use the same embedder as candidate sequences.
The scorer of REALM outputting relevance scores representing the score of document candidates (before softmax). 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 matter related to general usage and behavior.
forward
( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.FloatTensor] = Nonetoken_type_ids: typing.Optional[torch.LongTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecandidate_input_ids: typing.Optional[torch.LongTensor] = Nonecandidate_attention_mask: typing.Optional[torch.FloatTensor] = Nonecandidate_token_type_ids: typing.Optional[torch.LongTensor] = Nonecandidate_inputs_embeds: typing.Optional[torch.FloatTensor] = Nonehead_mask: typing.Optional[torch.FloatTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → transformers.models.realm.modeling_realm.RealmScorerOutput
or tuple(torch.FloatTensor)
Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
attention_mask (
torch.FloatTensor
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.
token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.max_position_embeddings - 1]
.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1 indicates the head is not masked,
0 indicates the head is masked.
inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.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 a ModelOutput instead of a plain tuple.candidate_input_ids (
torch.LongTensor
of shape(batch_size, num_candidates, sequence_length)
) — Indices of candidate input sequence tokens in the vocabulary.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
candidate_attention_mask (
torch.FloatTensor
of shape(batch_size, num_candidates, 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.
candidate_token_type_ids (
torch.LongTensor
of shape(batch_size, num_candidates, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
candidate_inputs_embeds (
torch.FloatTensor
of shape(batch_size * num_candidates, sequence_length, hidden_size)
, optional) — Optionally, instead of passingcandidate_input_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert candidate_input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
Returns
transformers.models.realm.modeling_realm.RealmScorerOutput
or tuple(torch.FloatTensor)
A transformers.models.realm.modeling_realm.RealmScorerOutput
or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (RealmConfig) and inputs.
relevance_score (
torch.FloatTensor
of shape(batch_size, config.num_candidates)
) — The relevance score of document candidates (before softmax).query_score (
torch.FloatTensor
of shape(batch_size, config.retriever_proj_size)
) — Query score derived from the query embedder.candidate_score (
torch.FloatTensor
of shape(batch_size, config.num_candidates, config.retriever_proj_size)
) — Candidate score derived from the embedder.
The RealmScorer forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Example:
Copied
RealmKnowledgeAugEncoder
class transformers.RealmKnowledgeAugEncoder
( config )
Parameters
config (RealmConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The knowledge-augmented encoder of REALM outputting masked language model logits and marginal log-likelihood loss. 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 matter related to general usage and behavior.
forward
( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.FloatTensor] = Nonetoken_type_ids: typing.Optional[torch.LongTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonehead_mask: typing.Optional[torch.FloatTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonerelevance_score: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Nonemlm_mask: typing.Optional[torch.LongTensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.MaskedLMOutput or tuple(torch.FloatTensor)
Parameters
input_ids (
torch.LongTensor
of shape(batch_size, num_candidates, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
attention_mask (
torch.FloatTensor
of shape(batch_size, num_candidates, 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.
token_type_ids (
torch.LongTensor
of shape(batch_size, num_candidates, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensor
of shape(batch_size, num_candidates, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.max_position_embeddings - 1]
.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1 indicates the head is not masked,
0 indicates the head is masked.
inputs_embeds (
torch.FloatTensor
of shape(batch_size, num_candidates, sequence_length, hidden_size)
, optional) — Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.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 a ModelOutput instead of a plain tuple.relevance_score (
torch.FloatTensor
of shape(batch_size, num_candidates)
, optional) — Relevance score derived from RealmScorer, must be specified if you want to compute the masked language modeling loss.labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Labels for computing the masked language modeling loss. 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 in[0, ..., config.vocab_size]
mlm_mask (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Mask to avoid calculating joint loss on certain positions. If not specified, the loss will not be masked. Mask values selected in[0, 1]
:1 for tokens that are not masked,
0 for tokens that are masked.
Returns
transformers.modeling_outputs.MaskedLMOutput or tuple(torch.FloatTensor)
A transformers.modeling_outputs.MaskedLMOutput or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (RealmConfig) and inputs.
loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) — Masked language modeling (MLM) loss.logits (
torch.FloatTensor
of shape(batch_size, sequence_length, config.vocab_size)
) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).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, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the optional 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.
The RealmKnowledgeAugEncoder forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Example:
Copied
RealmReader
class transformers.RealmReader
( config )
Parameters
config (RealmConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The reader of REALM. 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 matter related to general usage and behavior.
forward
( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.FloatTensor] = Nonetoken_type_ids: typing.Optional[torch.LongTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonehead_mask: typing.Optional[torch.FloatTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonerelevance_score: typing.Optional[torch.FloatTensor] = Noneblock_mask: typing.Optional[torch.BoolTensor] = Nonestart_positions: typing.Optional[torch.LongTensor] = Noneend_positions: typing.Optional[torch.LongTensor] = Nonehas_answers: typing.Optional[torch.BoolTensor] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) → transformers.models.realm.modeling_realm.RealmReaderOutput
or tuple(torch.FloatTensor)
Parameters
input_ids (
torch.LongTensor
of shape(reader_beam_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
attention_mask (
torch.FloatTensor
of shape(reader_beam_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.
token_type_ids (
torch.LongTensor
of shape(reader_beam_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensor
of shape(reader_beam_size, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.max_position_embeddings - 1]
.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1 indicates the head is not masked,
0 indicates the head is masked.
inputs_embeds (
torch.FloatTensor
of shape(reader_beam_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.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 a ModelOutput instead of a plain tuple.relevance_score (
torch.FloatTensor
of shape(searcher_beam_size,)
, optional) — Relevance score, which must be specified if you want to compute the logits and marginal log loss.block_mask (
torch.BoolTensor
of shape(searcher_beam_size, sequence_length)
, optional) — The mask of the evidence block, which must be specified if you want to compute the logits and marginal log loss.start_positions (
torch.LongTensor
of shape(searcher_beam_size,)
, optional) — Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length
). Position outside of the sequence are not taken into account for computing the loss.end_positions (
torch.LongTensor
of shape(searcher_beam_size,)
, optional) — Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length
). Position outside of the sequence are not taken into account for computing the loss.has_answers (
torch.BoolTensor
of shape(searcher_beam_size,)
, optional) — Whether or not the evidence block has answer(s).
Returns
transformers.models.realm.modeling_realm.RealmReaderOutput
or tuple(torch.FloatTensor)
A transformers.models.realm.modeling_realm.RealmReaderOutput
or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (RealmConfig) and inputs.
loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenstart_positions
,end_positions
,has_answers
are provided) — Total loss.retriever_loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenstart_positions
,end_positions
,has_answers
are provided) — Retriever loss.reader_loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenstart_positions
,end_positions
,has_answers
are provided) — Reader loss.retriever_correct (
torch.BoolTensor
of shape(config.searcher_beam_size,)
, optional) — Whether or not an evidence block contains answer.reader_correct (
torch.BoolTensor
of shape(config.reader_beam_size, num_candidates)
, optional) — Whether or not a span candidate contains answer.block_idx (
torch.LongTensor
of shape()
) — The index of the retrieved evidence block in which the predicted answer is most likely.candidate (
torch.LongTensor
of shape()
) — The index of the retrieved span candidates in which the predicted answer is most likely.start_pos (
torch.IntTensor
of shape()
) — Predicted answer starting position in RealmReader’s inputs.end_pos (
torch.IntTensor
of shape()
) — Predicted answer ending position in RealmReader’s inputs.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.
The RealmReader forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
RealmForOpenQA
class transformers.RealmForOpenQA
( configretriever = None )
Parameters
config (RealmConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
RealmForOpenQA
for end-to-end open domain question answering. 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 matter related to general usage and behavior.
block_embedding_to
( device )
Parameters
device (
str
ortorch.device
) — The device to whichself.block_emb
will be sent.
Send self.block_emb
to a specific device.
forward
( input_ids: typing.Optional[torch.LongTensor]attention_mask: typing.Optional[torch.FloatTensor] = Nonetoken_type_ids: typing.Optional[torch.LongTensor] = Noneanswer_ids: typing.Optional[torch.LongTensor] = Nonereturn_dict: typing.Optional[bool] = None ) → transformers.models.realm.modeling_realm.RealmForOpenQAOutput
or tuple(torch.FloatTensor)
Parameters
input_ids (
torch.LongTensor
of shape(1, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
attention_mask (
torch.FloatTensor
of shape(1, 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.
token_type_ids (
torch.LongTensor
of shape(1, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:0 corresponds to a sentence A token,
1 corresponds to a sentence B token (should not be used in this model by design).
answer_ids (
list
of shape(num_answers, answer_length)
, optional) — Answer ids for computing the marginal log-likelihood loss. Indices should be in[-1, 0, ..., config.vocab_size]
(seeinput_ids
docstring) Tokens with indices set to-1
are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]
return_dict (
bool
, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
Returns
transformers.models.realm.modeling_realm.RealmForOpenQAOutput
or tuple(torch.FloatTensor)
A transformers.models.realm.modeling_realm.RealmForOpenQAOutput
or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (RealmConfig) and inputs.
reader_output (
dict
) — Reader output.predicted_answer_ids (
torch.LongTensor
of shape(answer_sequence_length)
) — Predicted answer ids.
The RealmForOpenQA forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Example:
Copied
Last updated