DPR

Overview

Dense Passage Retrieval (DPR) - is a set of tools and models for state-of-the-art open-domain Q&A research. It is based on the following paper:

Vladimir Karpukhin, Barlas Oğuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, Wen-tau Yih, Dense Passage Retrieval for Open-Domain Question Answering.

The abstract from the paper is the following:

Open-domain question answering relies on efficient passage retrieval to select candidate contexts, where traditional sparse vector space models, such as TF-IDF or BM25, are the de facto method. In this work, we show that retrieval can be practically implemented using dense representations alone, where embeddings are learned from a small number of questions and passages by a simple dual-encoder framework. When evaluated on a wide range of open-domain QA datasets, our dense retriever outperforms a strong Lucene-BM25 system largely by 9%-19% absolute in terms of top-20 passage retrieval accuracy, and helps our end-to-end QA system establish new state-of-the-art on multiple open-domain QA benchmarks.

The original code can be found here.

DPRConfig

class transformers.DPRConfig(projection_dim: int = 0, **kwargs)[source]

DPRConfig is the configuration class to store the configuration of a DPRModel.

This is the configuration class to store the configuration of a DPRContextEncoder, DPRQuestionEncoder, or a DPRReader. It is used to instantiate the components of the DPR model.

Parameters

projection_dim (int, optional, defaults to 0) – Dimension of the projection for the context and question encoders. If it is set to zero (default), then no projection is done.

DPRContextEncoderTokenizer

class transformers.DPRContextEncoderTokenizer(vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token='[UNK]', sep_token='[SEP]', pad_token='[PAD]', cls_token='[CLS]', mask_token='[MASK]', tokenize_chinese_chars=True, strip_accents=None, **kwargs)[source]

Constructs a DPRContextEncoderTokenizer.

DPRContextEncoderTokenizer is identical to BertTokenizer and runs end-to-end tokenization: punctuation splitting + wordpiece.

Refer to superclass BertTokenizer for usage examples and documentation concerning parameters.

DPRContextEncoderTokenizerFast

class transformers.DPRContextEncoderTokenizerFast(vocab_file, do_lower_case=True, unk_token='[UNK]', sep_token='[SEP]', pad_token='[PAD]', cls_token='[CLS]', mask_token='[MASK]', clean_text=True, tokenize_chinese_chars=True, strip_accents=None, wordpieces_prefix='##', **kwargs)[source]

Constructs a “Fast” DPRContextEncoderTokenizer (backed by HuggingFace’s tokenizers library).

DPRContextEncoderTokenizerFast is identical to BertTokenizerFast and runs end-to-end tokenization: punctuation splitting + wordpiece.

Refer to superclass BertTokenizerFast for usage examples and documentation concerning parameters.

DPRQuestionEncoderTokenizer

class transformers.DPRQuestionEncoderTokenizer(vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token='[UNK]', sep_token='[SEP]', pad_token='[PAD]', cls_token='[CLS]', mask_token='[MASK]', tokenize_chinese_chars=True, strip_accents=None, **kwargs)[source]

Constructs a DPRQuestionEncoderTokenizer.

DPRQuestionEncoderTokenizer is identical to BertTokenizer and runs end-to-end tokenization: punctuation splitting + wordpiece.

Refer to superclass BertTokenizer for usage examples and documentation concerning parameters.

DPRQuestionEncoderTokenizerFast

class transformers.DPRQuestionEncoderTokenizerFast(vocab_file, do_lower_case=True, unk_token='[UNK]', sep_token='[SEP]', pad_token='[PAD]', cls_token='[CLS]', mask_token='[MASK]', clean_text=True, tokenize_chinese_chars=True, strip_accents=None, wordpieces_prefix='##', **kwargs)[source]

Constructs a “Fast” DPRQuestionEncoderTokenizer (backed by HuggingFace’s tokenizers library).

DPRQuestionEncoderTokenizerFast is identical to BertTokenizerFast and runs end-to-end tokenization: punctuation splitting + wordpiece.

Refer to superclass BertTokenizerFast for usage examples and documentation concerning parameters.

DPRReaderTokenizer

class transformers.DPRReaderTokenizer(vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token='[UNK]', sep_token='[SEP]', pad_token='[PAD]', cls_token='[CLS]', mask_token='[MASK]', tokenize_chinese_chars=True, strip_accents=None, **kwargs)[source]

Constructs a DPRReaderTokenizer.

DPRReaderTokenizer is alsmost identical to BertTokenizer and runs end-to-end tokenization: punctuation splitting + wordpiece.

What is different is that is has three inputs strings: question, titles and texts that are combined to feed into the DPRReader model.

Refer to superclass BertTokenizer for usage examples and documentation concerning parameters.

Return a dictionary with the token ids of the input strings and other information to give to decode_best_spans. It converts the strings of a question and different passages (title + text) in a sequence of ids (integer), using the tokenizer and vocabulary. The resulting input_ids is a matrix of size (n_passages, sequence_length) with the format:

[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>

Inputs:
questions (str, List[str]):

The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like [questions] * n_passages. Otherwise you have to specify as many questions as in titles or texts.

titles (str, List[str]):

The passages titles to be encoded. This can be a string, a list of strings if there are several passages.

texts (str, List[str]):

The passages texts to be encoded. This can be a string, a list of strings if there are several passages.

padding (Union[bool, str], optional, defaults to False):

Activate and control padding. Accepts the following values:

  • True or ‘longest’: pad to the longest sequence in the batch (or no padding if only a single sequence if provided),

  • ‘max_length’: pad to a max length specified in max_length or to the max acceptable input length for the model if no length is provided (max_length=None)

  • False or ‘do_not_pad’ (default): No padding (i.e. can output batch with sequences of uneven lengths)

truncation (Union[bool, str], optional, defaults to False):

Activate and control truncation. Accepts the following values:

  • True or ‘only_first’: truncate to a max length specified in max_length or to the max acceptable input length for the model if no length is provided (max_length=None).

  • False or ‘do_not_truncate’ (default): No truncation (i.e. can output batch with sequences length greater than the model max admissible input size)

max_length (Union[int, None], optional):

Control the length for padding/truncation. Accepts the following values

  • None (default): This will use the predefined model max length if required by one of the truncation/padding parameters. If the model has no specific max input length (e.g. XLNet) truncation/padding to max length is deactivated.

  • any integer value (e.g. 42): Use this specific maximum length value if required by one of the truncation/padding parameters.

return_tensors (str, optional):

Can be set to ‘tf’, ‘pt’ or ‘np’ to return respectively TensorFlow tf.constant, PyTorch torch.Tensor or Numpy :obj: np.ndarray instead of a list of python integers.

return_attention_mask (bool, optional, defaults to none):

Whether to return the attention mask. If left to the default, will return the attention mask according to the specific tokenizer’s default, defined by the return_outputs attribute.

What are attention masks?

Returns

A Dictionary of shape:

{
    input_ids: list[list[int]],
    attention_mask: list[int] if return_attention_mask is True (default)
}

With the fields:

  • input_ids: list of token ids to be fed to a model

  • attention_mask: list of indices specifying which tokens should be attended to by the model

DPRReaderTokenizerFast

class transformers.DPRReaderTokenizerFast(vocab_file, do_lower_case=True, unk_token='[UNK]', sep_token='[SEP]', pad_token='[PAD]', cls_token='[CLS]', mask_token='[MASK]', clean_text=True, tokenize_chinese_chars=True, strip_accents=None, wordpieces_prefix='##', **kwargs)[source]

Constructs a DPRReaderTokenizerFast.

DPRReaderTokenizerFast is almost identical to BertTokenizerFast and runs end-to-end tokenization: punctuation splitting + wordpiece.

What is different is that is has three inputs strings: question, titles and texts that are combined to feed into the DPRReader model.

Refer to superclass BertTokenizer for usage examples and documentation concerning parameters.

Return a dictionary with the token ids of the input strings and other information to give to decode_best_spans. It converts the strings of a question and different passages (title + text) in a sequence of ids (integer), using the tokenizer and vocabulary. The resulting input_ids is a matrix of size (n_passages, sequence_length) with the format:

[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>

Inputs:
questions (str, List[str]):

The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like [questions] * n_passages. Otherwise you have to specify as many questions as in titles or texts.

titles (str, List[str]):

The passages titles to be encoded. This can be a string, a list of strings if there are several passages.

texts (str, List[str]):

The passages texts to be encoded. This can be a string, a list of strings if there are several passages.

padding (Union[bool, str], optional, defaults to False):

Activate and control padding. Accepts the following values:

  • True or ‘longest’: pad to the longest sequence in the batch (or no padding if only a single sequence if provided),

  • ‘max_length’: pad to a max length specified in max_length or to the max acceptable input length for the model if no length is provided (max_length=None)

  • False or ‘do_not_pad’ (default): No padding (i.e. can output batch with sequences of uneven lengths)

truncation (Union[bool, str], optional, defaults to False):

Activate and control truncation. Accepts the following values:

  • True or ‘only_first’: truncate to a max length specified in max_length or to the max acceptable input length for the model if no length is provided (max_length=None).

  • False or ‘do_not_truncate’ (default): No truncation (i.e. can output batch with sequences length greater than the model max admissible input size)

max_length (Union[int, None], optional):

Control the length for padding/truncation. Accepts the following values

  • None (default): This will use the predefined model max length if required by one of the truncation/padding parameters. If the model has no specific max input length (e.g. XLNet) truncation/padding to max length is deactivated.

  • any integer value (e.g. 42): Use this specific maximum length value if required by one of the truncation/padding parameters.

return_tensors (str, optional):

Can be set to ‘tf’, ‘pt’ or ‘np’ to return respectively TensorFlow tf.constant, PyTorch torch.Tensor or Numpy :obj: np.ndarray instead of a list of python integers.

return_attention_mask (bool, optional, defaults to none):

Whether to return the attention mask. If left to the default, will return the attention mask according to the specific tokenizer’s default, defined by the return_outputs attribute.

What are attention masks?

Returns

A Dictionary of shape:

{
    input_ids: list[list[int]],
    attention_mask: list[int] if return_attention_mask is True (default)
}

With the fields:

  • input_ids: list of token ids to be fed to a model

  • attention_mask: list of indices specifying which tokens should be attended to by the model

DPR specific outputs

class transformers.modeling_dpr.DPRContextEncoderOutput(pooler_output: torch.FloatTensor, hidden_states: Optional[Tuple[torch.FloatTensor]] = None, attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]

Class for outputs of DPRQuestionEncoder.

Parameters
  • pooler_output – (:obj:torch.FloatTensor of shape (batch_size, embeddings_size)): The DPR encoder outputs the pooler_output that corresponds to the context representation. Last layer hidden-state of the first token of the sequence (classification token) further processed by a Linear layer. This output is to be used to embed contexts for nearest neighbors queries with questions embeddings.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) –

    Tuple of torch.FloatTensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, 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 when output_attentions=True is passed or when config.output_attentions=True) –

    Tuple of torch.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.

class transformers.modeling_dpr.DPRQuestionEncoderOutput(pooler_output: torch.FloatTensor, hidden_states: Optional[Tuple[torch.FloatTensor]] = None, attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]

Class for outputs of DPRQuestionEncoder.

Parameters
  • pooler_output – (:obj:torch.FloatTensor of shape (batch_size, embeddings_size)): The DPR encoder outputs the pooler_output that corresponds to the question representation. Last layer hidden-state of the first token of the sequence (classification token) further processed by a Linear layer. This output is to be used to embed questions for nearest neighbors queries with context embeddings.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) –

    Tuple of torch.FloatTensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, 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 when output_attentions=True is passed or when config.output_attentions=True) –

    Tuple of torch.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.

class transformers.modeling_dpr.DPRReaderOutput(start_logits: torch.FloatTensor, end_logits: torch.FloatTensor = None, relevance_logits: torch.FloatTensor = None, hidden_states: Optional[Tuple[torch.FloatTensor]] = None, attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]

Class for outputs of DPRQuestionEncoder.

Parameters
  • start_logits – (:obj:torch.FloatTensor of shape (n_passages, sequence_length)): Logits of the start index of the span for each passage.

  • end_logits – (:obj:torch.FloatTensor of shape (n_passages, sequence_length)): Logits of the end index of the span for each passage.

  • relevance_logits – (torch.FloatTensor` of shape (n_passages, )): Outputs of the QA classifier of the DPRReader that corresponds to the scores of each passage to answer the question, compared to all the other passages.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) –

    Tuple of torch.FloatTensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, 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 when output_attentions=True is passed or when config.output_attentions=True) –

    Tuple of torch.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.

DPRContextEncoder

class transformers.DPRContextEncoder(config: transformers.configuration_dpr.DPRConfig)[source]

The bare DPRContextEncoder transformer outputting pooler outputs as context representations.

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.

Parameters

config (DPRConfig) – 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.

forward(input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, output_attentions=None, output_hidden_states=None, return_dict=None) → Union[transformers.modeling_dpr.DPRContextEncoderOutput, Tuple[torch.Tensor, ]][source]

The DPRContextEncoder forward method, overrides the __call__() special method.

Note

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

Parameters
  • input_ids

    (:obj:torch.LongTensor of shape (batch_size, sequence_length)): Indices of input sequence tokens in the vocabulary. To match pre-training, DPR input sequence should be formatted with [CLS] and [SEP] tokens as follows:

    1. For sequence pairs (for a pair title+text for example):

      tokens:         [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]

      token_type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1

    2. For single sequences (for a question for example):

      tokens:         [CLS] the dog is hairy . [SEP]

      token_type_ids:   0   0   0   0  0     0   0

    DPR is a model with absolute position embeddings so it’s usually advised to pad the inputs on the right rather than the left.

    Indices can be obtained using transformers.DPRTokenizer. See transformers.PreTrainedTokenizer.encode() and transformers.PreTrainedTokenizer.convert_tokens_to_ids() for details.

  • attention_mask – (:obj: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 MASKED tokens.

  • token_type_ids – (:obj: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

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) – Optionally, instead of passing input_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

  • output_attentions (bool, optional) – If set to True, the attentions tensors of all attention layers are returned. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) – If set to True, the hidden states tensors of all layers are returned. See hidden_states under returned tensors for more detail.

  • return_dict (bool, optional) – If set to True, the model will return a ModelOutput instead of a plain tuple.

Returns

A DPRContextEncoderOutput (if return_dict=True is passed or when config.return_dict=True) or a tuple of torch.FloatTensor comprising various elements depending on the configuration (DPRConfig) and inputs.

  • pooler_output: (:obj:torch.FloatTensor of shape (batch_size, embeddings_size)) – The DPR encoder outputs the pooler_output that corresponds to the context representation. Last layer hidden-state of the first token of the sequence (classification token) further processed by a Linear layer. This output is to be used to embed contexts for nearest neighbors queries with questions embeddings.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) – Tuple of torch.FloatTensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, 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 when output_attentions=True is passed or when config.output_attentions=True) – Tuple of torch.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.

Examples:

>>> from transformers import DPRContextEncoder, DPRContextEncoderTokenizer
>>> tokenizer = DPRContextEncoderTokenizer.from_pretrained('facebook/dpr-ctx_encoder-single-nq-base')
>>> model = DPRContextEncoder.from_pretrained('facebook/dpr-ctx_encoder-single-nq-base', return_dict=True)
>>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors='pt')["input_ids"]
>>> embeddings = model(input_ids).pooler_output

Return type

DPRContextEncoderOutput or tuple(torch.FloatTensor)

DPRQuestionEncoder

class transformers.DPRQuestionEncoder(config: transformers.configuration_dpr.DPRConfig)[source]

The bare DPRQuestionEncoder transformer outputting pooler outputs as question representations.

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.

Parameters

config (DPRConfig) – 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.

forward(input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, output_attentions=None, output_hidden_states=None, return_dict=None) → Union[transformers.modeling_dpr.DPRQuestionEncoderOutput, Tuple[torch.Tensor, ]][source]

The DPRQuestionEncoder forward method, overrides the __call__() special method.

Note

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

Parameters
  • input_ids

    (:obj:torch.LongTensor of shape (batch_size, sequence_length)): Indices of input sequence tokens in the vocabulary. To match pre-training, DPR input sequence should be formatted with [CLS] and [SEP] tokens as follows:

    1. For sequence pairs (for a pair title+text for example):

      tokens:         [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]

      token_type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1

    2. For single sequences (for a question for example):

      tokens:         [CLS] the dog is hairy . [SEP]

      token_type_ids:   0   0   0   0  0     0   0

    DPR is a model with absolute position embeddings so it’s usually advised to pad the inputs on the right rather than the left.

    Indices can be obtained using transformers.DPRTokenizer. See transformers.PreTrainedTokenizer.encode() and transformers.PreTrainedTokenizer.convert_tokens_to_ids() for details.

  • attention_mask – (:obj: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 MASKED tokens.

  • token_type_ids – (:obj: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

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) – Optionally, instead of passing input_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

  • output_attentions (bool, optional) – If set to True, the attentions tensors of all attention layers are returned. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) – If set to True, the hidden states tensors of all layers are returned. See hidden_states under returned tensors for more detail.

  • return_dict (bool, optional) – If set to True, the model will return a ModelOutput instead of a plain tuple.

Returns

A DPRQuestionEncoderOutput (if return_dict=True is passed or when config.return_dict=True) or a tuple of torch.FloatTensor comprising various elements depending on the configuration (DPRConfig) and inputs.

  • pooler_output: (:obj:torch.FloatTensor of shape (batch_size, embeddings_size)) – The DPR encoder outputs the pooler_output that corresponds to the question representation. Last layer hidden-state of the first token of the sequence (classification token) further processed by a Linear layer. This output is to be used to embed questions for nearest neighbors queries with context embeddings.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) – Tuple of torch.FloatTensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, 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 when output_attentions=True is passed or when config.output_attentions=True) – Tuple of torch.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.

Examples:

>>> from transformers import DPRQuestionEncoder, DPRQuestionEncoderTokenizer
>>> tokenizer = DPRQuestionEncoderTokenizer.from_pretrained('facebook/dpr-question_encoder-single-nq-base')
>>> model = DPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base', return_dict=True)
>>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors='pt')["input_ids"]
>>> embeddings = model(input_ids).pooler_output

Return type

DPRQuestionEncoderOutput or tuple(torch.FloatTensor)

DPRReader

class transformers.DPRReader(config: transformers.configuration_dpr.DPRConfig)[source]

The bare DPRReader transformer outputting span predictions.

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.

Parameters

config (DPRConfig) – 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.

forward(input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, output_attentions: bool = None, output_hidden_states: bool = None, return_dict=None) → Union[transformers.modeling_dpr.DPRReaderOutput, Tuple[torch.Tensor, ]][source]

The DPRReader forward method, overrides the __call__() special method.

Note

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

Parameters
  • input_ids

    (:obj:torch.LongTensor of shape (n_passages, sequence_length)): Indices of input sequence tokens in the vocabulary. It has to be a sequence triplet with 1) the question and 2) the passages titles and 3) the passages texts To match pre-training, DPR input_ids sequence should be formatted with [CLS] and [SEP] with the format:

    [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>

    DPR is a model with absolute position embeddings so it’s usually advised to pad the inputs on the right rather than the left.

    Indices can be obtained using transformers.DPRReaderTokenizer. See transformers.DPRReaderTokenizer for more details

  • attention_mask – (:obj:torch.FloatTensor``, of shape (n_passages, 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 MASKED tokens.

  • inputs_embeds (torch.FloatTensor of shape (n_passages, sequence_length, hidden_size), optional) – Optionally, instead of passing input_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

  • output_attentions (bool, optional) – If set to True, the attentions tensors of all attention layers are returned. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) – If set to True, the hidden states tensors of all layers are returned. See hidden_states under returned tensors for more detail.

  • return_dict (bool, optional) – If set to True, the model will return a ModelOutput instead of a plain tuple.

Returns

A DPRReaderOutput (if return_dict=True is passed or when config.return_dict=True) or a tuple of torch.FloatTensor comprising various elements depending on the configuration (DPRConfig) and inputs.

  • start_logits: (:obj:torch.FloatTensor of shape (n_passages, sequence_length)) – Logits of the start index of the span for each passage.

  • end_logits: (:obj:torch.FloatTensor of shape (n_passages, sequence_length)) – Logits of the end index of the span for each passage.

  • relevance_logits: (torch.FloatTensor` of shape (n_passages, )) – Outputs of the QA classifier of the DPRReader that corresponds to the scores of each passage to answer the question, compared to all the other passages.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) – Tuple of torch.FloatTensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, 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 when output_attentions=True is passed or when config.output_attentions=True) – Tuple of torch.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.

Examples:

>>> from transformers import DPRReader, DPRReaderTokenizer
>>> tokenizer = DPRReaderTokenizer.from_pretrained('facebook/dpr-reader-single-nq-base')
>>> model = DPRReader.from_pretrained('facebook/dpr-reader-single-nq-base', return_dict=True)
>>> encoded_inputs = tokenizer(
...         questions=["What is love ?"],
...         titles=["Haddaway"],
...         texts=["'What Is Love' is a song recorded by the artist Haddaway"],
...         return_tensors='pt'
...     )
>>> outputs = model(**encoded_inputs)
>>> start_logits = outputs.stat_logits
>>> end_logits = outputs.end_logits
>>> relevance_logits = outputs.relevance_logits

Return type

DPRReaderOutput or tuple(torch.FloatTensor)