REALM

## [](#overview)Overview

The REALM model was proposed in [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) 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](https://huggingface.co/qqaatw). The original code can be found [here](https://github.com/google-research/language/tree/master/language/realm).

## [](#transformers.RealmConfig)RealmConfig

### class transformers.RealmConfig

[](#transformers.RealmConfig)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/configuration_realm.py#L44)

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

This is the configuration class to store the configuration of

1.  [RealmEmbedder](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.RealmEmbedder)
2.  [RealmScorer](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.RealmScorer)
3.  [RealmKnowledgeAugEncoder](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.RealmKnowledgeAugEncoder)
4.  [RealmRetriever](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.RealmRetriever)
5.  [RealmReader](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.RealmReader)
6.  [RealmForOpenQA](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.RealmForOpenQA)

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](https://huggingface.co/google/realm-cc-news-pretrained-embedder) architecture.

Configuration objects inherit from [PretrainedConfig](/docs/transformers/v4.30.0/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the documentation from [PretrainedConfig](/docs/transformers/v4.30.0/en/main_classes/configuration#transformers.PretrainedConfig) for more information.

Example:

```
>>> from transformers import RealmConfig, RealmEmbedder

>>> 
>>> configuration = RealmConfig()

>>> 
>>> model = RealmEmbedder(configuration)

>>> 
>>> configuration = model.config```

## [](#transformers.RealmTokenizer)RealmTokenizer

### class transformers.RealmTokenizer

[](#transformers.RealmTokenizer)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/tokenization_realm.py#L95)

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

Construct a REALM tokenizer.

[RealmTokenizer](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.RealmTokenizer) is identical to [BertTokenizer](/docs/transformers/v4.30.0/en/model_doc/bert#transformers.BertTokenizer) and runs end-to-end tokenization: punctuation splitting and wordpiece.

This tokenizer inherits from [PreTrainedTokenizer](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.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

[](#transformers.RealmTokenizer.build_inputs_with_special_tokens)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/tokenization_realm.py#L301)

( token\_ids\_0: typing.List\[int\]token\_ids\_1: typing.Optional\[typing.List\[int\]\] = None ) → `List[int]`

Parameters

-   [](#transformers.RealmTokenizer.build_inputs_with_special_tokens.token_ids_0)**token\_ids\_0** (`List[int]`) — List of IDs to which the special tokens will be added.
-   [](#transformers.RealmTokenizer.build_inputs_with_special_tokens.token_ids_1)**token\_ids\_1** (`List[int]`, _optional_) — Optional second list of IDs for sequence pairs.

List of [input IDs](../glossary#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

[](#transformers.RealmTokenizer.get_special_tokens_mask)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/tokenization_realm.py#L326)

( token\_ids\_0: typing.List\[int\]token\_ids\_1: typing.Optional\[typing.List\[int\]\] = Nonealready\_has\_special\_tokens: bool = False ) → `List[int]`

Parameters

-   [](#transformers.RealmTokenizer.get_special_tokens_mask.token_ids_0)**token\_ids\_0** (`List[int]`) — List of IDs.
-   [](#transformers.RealmTokenizer.get_special_tokens_mask.token_ids_1)**token\_ids\_1** (`List[int]`, _optional_) — Optional second list of IDs for sequence pairs.
-   [](#transformers.RealmTokenizer.get_special_tokens_mask.already_has_special_tokens)**already\_has\_special\_tokens** (`bool`, _optional_, defaults to `False`) — Whether or not the token list is already formatted with special tokens for the model.

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

[](#transformers.RealmTokenizer.create_token_type_ids_from_sequences)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/tokenization_realm.py#L354)

( token\_ids\_0: typing.List\[int\]token\_ids\_1: typing.Optional\[typing.List\[int\]\] = None ) → `List[int]`

Parameters

-   [](#transformers.RealmTokenizer.create_token_type_ids_from_sequences.token_ids_0)**token\_ids\_0** (`List[int]`) — List of IDs.
-   [](#transformers.RealmTokenizer.create_token_type_ids_from_sequences.token_ids_1)**token\_ids\_1** (`List[int]`, _optional_) — Optional second list of IDs for sequence pairs.

List of [token type IDs](../glossary#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:

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

#### save\_vocabulary

[](#transformers.RealmTokenizer.save_vocabulary)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/tokenization_realm.py#L383)

( save\_directory: strfilename\_prefix: typing.Optional\[str\] = None )

#### batch\_encode\_candidates

[](#transformers.RealmTokenizer.batch_encode_candidates)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/tokenization_realm.py#L228)

( text\*\*kwargs ) → [BatchEncoding](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.BatchEncoding)

Parameters

-   [](#transformers.RealmTokenizer.batch_encode_candidates.text)**text** (`List[List[str]]`) — The batch of sequences to be encoded. Each sequence must be in this format: (batch\_size, num\_candidates, text).
-   [](#transformers.RealmTokenizer.batch_encode_candidates.text_pair)**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.

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:

1.  Handle additional num\_candidate axis. (batch\_size, num\_candidates, text)
2.  Always pad the sequences to _max\_length_.
3.  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:

```
>>> from transformers import RealmTokenizer

>>> 
>>> text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]]

>>> tokenizer = RealmTokenizer.from_pretrained("google/realm-cc-news-pretrained-encoder")
>>> tokenized_text = tokenizer.batch_encode_candidates(text, max_length=10, return_tensors="pt")```

## [](#transformers.RealmTokenizerFast)RealmTokenizerFast

### class transformers.RealmTokenizerFast

[](#transformers.RealmTokenizerFast)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/tokenization_realm_fast.py#L102)

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

Construct a “fast” REALM tokenizer (backed by HuggingFace’s _tokenizers_ library). Based on WordPiece.

[RealmTokenizerFast](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.RealmTokenizerFast) is identical to [BertTokenizerFast](/docs/transformers/v4.30.0/en/model_doc/bert#transformers.BertTokenizerFast) and runs end-to-end tokenization: punctuation splitting and wordpiece.

This tokenizer inherits from [PreTrainedTokenizerFast](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.PreTrainedTokenizerFast) which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

#### batch\_encode\_candidates

[](#transformers.RealmTokenizerFast.batch_encode_candidates)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/tokenization_realm_fast.py#L193)

( text\*\*kwargs ) → [BatchEncoding](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.BatchEncoding)

Parameters

-   [](#transformers.RealmTokenizerFast.batch_encode_candidates.text)**text** (`List[List[str]]`) — The batch of sequences to be encoded. Each sequence must be in this format: (batch\_size, num\_candidates, text).
-   [](#transformers.RealmTokenizerFast.batch_encode_candidates.text_pair)**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.

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:

1.  Handle additional num\_candidate axis. (batch\_size, num\_candidates, text)
2.  Always pad the sequences to _max\_length_.
3.  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:

```
>>> from transformers import RealmTokenizerFast

>>> 
>>> text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]]

>>> tokenizer = RealmTokenizerFast.from_pretrained("google/realm-cc-news-pretrained-encoder")
>>> tokenized_text = tokenizer.batch_encode_candidates(text, max_length=10, return_tensors="pt")```

## [](#transformers.RealmRetriever)RealmRetriever

### class transformers.RealmRetriever

[](#transformers.RealmRetriever)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/retrieval_realm.py#L72)

( block\_recordstokenizer )

Parameters

-   [](#transformers.RealmRetriever.block_records)**block\_records** (`np.ndarray`) — A numpy array which cantains evidence texts.
-   [](#transformers.RealmRetriever.tokenizer)**tokenizer** ([RealmTokenizer](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.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

[](#transformers.RealmRetriever.block_has_answer)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/retrieval_realm.py#L129)

( concat\_inputsanswer\_ids )

check if retrieved\_blocks has answers.

## [](#transformers.RealmEmbedder)RealmEmbedder

### class transformers.RealmEmbedder

[](#transformers.RealmEmbedder)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/modeling_realm.py#L1149)

( config )

Parameters

-   [](#transformers.RealmEmbedder.config)**config** ([RealmConfig](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.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()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.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](https://pytorch.org/docs/stable/nn.html#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

[](#transformers.RealmEmbedder.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/modeling_realm.py#L1165)

( 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)`

The [RealmEmbedder](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.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:

```
>>> from transformers import AutoTokenizer, RealmEmbedder
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("google/realm-cc-news-pretrained-embedder")
>>> model = RealmEmbedder.from_pretrained("google/realm-cc-news-pretrained-embedder")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)

>>> projected_score = outputs.projected_score```

## [](#transformers.RealmScorer)RealmScorer

### class transformers.RealmScorer

[](#transformers.RealmScorer)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/modeling_realm.py#L1231)

( configquery\_embedder = None )

Parameters

-   [](#transformers.RealmScorer.config)**config** ([RealmConfig](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.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()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.
-   [](#transformers.RealmScorer.query_embedder)**query\_embedder** ([RealmEmbedder](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.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](https://pytorch.org/docs/stable/nn.html#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

[](#transformers.RealmScorer.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/modeling_realm.py#L1247)

( 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)`

The [RealmScorer](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.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:

```
>>> import torch
>>> from transformers import AutoTokenizer, RealmScorer

>>> tokenizer = AutoTokenizer.from_pretrained("google/realm-cc-news-pretrained-scorer")
>>> model = RealmScorer.from_pretrained("google/realm-cc-news-pretrained-scorer", num_candidates=2)

>>> 
>>> input_texts = ["How are you?", "What is the item in the picture?"]
>>> candidates_texts = [["Hello world!", "Nice to meet you!"], ["A cute cat.", "An adorable dog."]]

>>> inputs = tokenizer(input_texts, return_tensors="pt")
>>> candidates_inputs = tokenizer.batch_encode_candidates(candidates_texts, max_length=10, return_tensors="pt")

>>> outputs = model(
...     **inputs,
...     candidate_input_ids=candidates_inputs.input_ids,
...     candidate_attention_mask=candidates_inputs.attention_mask,
...     candidate_token_type_ids=candidates_inputs.token_type_ids,
... )
>>> relevance_score = outputs.relevance_score```

## [](#transformers.RealmKnowledgeAugEncoder)RealmKnowledgeAugEncoder

### class transformers.RealmKnowledgeAugEncoder

[](#transformers.RealmKnowledgeAugEncoder)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/modeling_realm.py#L1379)

( config )

Parameters

-   [](#transformers.RealmKnowledgeAugEncoder.config)**config** ([RealmConfig](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.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()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.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](https://pytorch.org/docs/stable/nn.html#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

[](#transformers.RealmKnowledgeAugEncoder.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/modeling_realm.py#L1400)

( 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](/docs/transformers/v4.30.0/en/main_classes/output#transformers.modeling_outputs.MaskedLMOutput) or `tuple(torch.FloatTensor)`

The [RealmKnowledgeAugEncoder](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.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:

```
>>> import torch
>>> from transformers import AutoTokenizer, RealmKnowledgeAugEncoder

>>> tokenizer = AutoTokenizer.from_pretrained("google/realm-cc-news-pretrained-encoder")
>>> model = RealmKnowledgeAugEncoder.from_pretrained(
...     "google/realm-cc-news-pretrained-encoder", num_candidates=2
... )

>>> 
>>> text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]]

>>> inputs = tokenizer.batch_encode_candidates(text, max_length=10, return_tensors="pt")
>>> outputs = model(**inputs)
>>> logits = outputs.logits```

## [](#transformers.RealmReader)RealmReader

### class transformers.RealmReader

[](#transformers.RealmReader)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/modeling_realm.py#L1529)

( config )

Parameters

-   [](#transformers.RealmReader.config)**config** ([RealmConfig](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.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()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The reader of REALM. This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#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

[](#transformers.RealmReader.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/modeling_realm.py#L1542)

( 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)`

The [RealmReader](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.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.

## [](#transformers.RealmForOpenQA)RealmForOpenQA

### class transformers.RealmForOpenQA

[](#transformers.RealmForOpenQA)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/modeling_realm.py#L1735)

( configretriever = None )

Parameters

-   [](#transformers.RealmForOpenQA.config)**config** ([RealmConfig](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.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()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.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](https://pytorch.org/docs/stable/nn.html#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

[](#transformers.RealmForOpenQA.block_embedding_to)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/modeling_realm.py#L1758)

( device )

Parameters

-   [](#transformers.RealmForOpenQA.block_embedding_to.device)**device** (`str` or `torch.device`) — The device to which `self.block_emb` will be sent.

Send `self.block_emb` to a specific device.

#### forward

[](#transformers.RealmForOpenQA.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/realm/modeling_realm.py#L1768)

( 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)`

The [RealmForOpenQA](/docs/transformers/v4.30.0/en/model_doc/realm#transformers.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:

```
>>> import torch
>>> from transformers import RealmForOpenQA, RealmRetriever, AutoTokenizer

>>> retriever = RealmRetriever.from_pretrained("google/realm-orqa-nq-openqa")
>>> tokenizer = AutoTokenizer.from_pretrained("google/realm-orqa-nq-openqa")
>>> model = RealmForOpenQA.from_pretrained("google/realm-orqa-nq-openqa", retriever=retriever)

>>> question = "Who is the pioneer in modern computer science?"
>>> question_ids = tokenizer([question], return_tensors="pt")
>>> answer_ids = tokenizer(
...     ["alan mathison turing"],
...     add_special_tokens=False,
...     return_token_type_ids=False,
...     return_attention_mask=False,
... ).input_ids

>>> reader_output, predicted_answer_ids = model(**question_ids, answer_ids=answer_ids, return_dict=False)
>>> predicted_answer = tokenizer.decode(predicted_answer_ids)
>>> loss = reader_output.loss```