






import collections
from typing import List, Optional, Union

from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
from ..bert.tokenization_bert import BertTokenizer


__a:     Tuple   					=					logging.get_logger(__name__)

__a:     Optional[Any]   					=					{'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

__a:     Any   					=					{
    '''vocab_file''': {
        '''facebook/dpr-ctx_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt'''
        ),
        '''facebook/dpr-ctx_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''facebook/dpr-ctx_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json'''
        ),
        '''facebook/dpr-ctx_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json'''
        ),
    },
}
__a:     Any   					=					{
    '''vocab_file''': {
        '''facebook/dpr-question_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt'''
        ),
        '''facebook/dpr-question_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''facebook/dpr-question_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json'''
        ),
        '''facebook/dpr-question_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json'''
        ),
    },
}
__a:     str   					=					{
    '''vocab_file''': {
        '''facebook/dpr-reader-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt'''
        ),
        '''facebook/dpr-reader-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''facebook/dpr-reader-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json'''
        ),
        '''facebook/dpr-reader-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json'''
        ),
    },
}

__a:     Dict   					=					{
    '''facebook/dpr-ctx_encoder-single-nq-base''': 512,
    '''facebook/dpr-ctx_encoder-multiset-base''': 512,
}
__a:     List[str]   					=					{
    '''facebook/dpr-question_encoder-single-nq-base''': 512,
    '''facebook/dpr-question_encoder-multiset-base''': 512,
}
__a:     Dict   					=					{
    '''facebook/dpr-reader-single-nq-base''': 512,
    '''facebook/dpr-reader-multiset-base''': 512,
}


__a:     Optional[int]   					=					{
    '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True},
}
__a:     Tuple   					=					{
    '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True},
}
__a:     Optional[int]   					=					{
    '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True},
}
class 		SCREAMING_SNAKE_CASE__	(  UpperCAmelCase     ):

  '''simple docstring'''







  _lowerCamelCase    =  VOCAB_FILES_NAMES
  _lowerCamelCase    =  CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
  _lowerCamelCase    =  CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  _lowerCamelCase    =  CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION



class 		SCREAMING_SNAKE_CASE__	(  UpperCAmelCase     ):

  '''simple docstring'''







  _lowerCamelCase    =  VOCAB_FILES_NAMES
  _lowerCamelCase    =  QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
  _lowerCamelCase    =  QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  _lowerCamelCase    =  QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION



__a:     List[Any]   					=					collections.namedtuple(
    '''DPRSpanPrediction''', ['''span_score''', '''relevance_score''', '''doc_id''', '''start_index''', '''end_index''', '''text''']
)

__a:     Optional[int]   					=					collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits'''])


__a:     Optional[Any]   					=					R'''
    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 and text) in a sequence of IDs (integers),
    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>
    ```

    Args:
        questions (`str` or `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` or `List[str]`):
            The passages titles to be encoded. This can be a string or a list of strings if there are several passages.
        texts (`str` or `List[str]`):
            The passages texts to be encoded. This can be a string or a list of strings if there are several passages.
        padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
            Activates and controls padding. Accepts the following values:

            - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence
              if provided).
            - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
              acceptable input length for the model if that argument is not provided.
            - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different
              lengths).
        truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
            Activates and controls truncation. Accepts the following values:

            - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to
              the maximum acceptable input length for the model if that argument is not provided. This will truncate
              token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch
              of pairs) is provided.
            - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
              acceptable input length for the model if that argument is not provided. This will only truncate the first
              sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
            - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
              acceptable input length for the model if that argument is not provided. This will only truncate the
              second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
            - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths
              greater than the model maximum admissible input size).
        max_length (`int`, *optional*):
                Controls the maximum length to use by one of the truncation/padding parameters.

                If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
                is required by one of the truncation/padding parameters. If the model has no specific maximum input
                length (like XLNet) truncation/padding to a maximum length will be deactivated.
        return_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors instead of list of python integers. Acceptable values are:

                - `\'tf\'`: Return TensorFlow `tf.constant` objects.
                - `\'pt\'`: Return PyTorch `torch.Tensor` objects.
                - `\'np\'`: Return Numpy `np.ndarray` objects.
        return_attention_mask (`bool`, *optional*):
            Whether or not to return the attention mask. If not set, will return the attention mask according to the
            specific tokenizer\'s default, defined by the `return_outputs` attribute.

            [What are attention masks?](../glossary#attention-mask)

    Returns:
        `Dict[str, List[List[int]]]`: A dictionary with the following keys:

        - `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.
    '''
@add_start_docstrings(UpperCAmelCase     )
class 		SCREAMING_SNAKE_CASE__	:

  '''simple docstring'''







  def __call__(      self		:			int       ,				lowerCamelCase		:			int       ,				lowerCamelCase		:			Optional[str] = None       ,				lowerCamelCase		:			Optional[str] = None       ,				lowerCamelCase		:			Union[bool, str] = False       ,				lowerCamelCase		:			Union[bool, str] = False       ,				lowerCamelCase		:			Optional[int] = None       ,				lowerCamelCase		:			Optional[Union[str, TensorType]] = None       ,				lowerCamelCase		:			Optional[bool] = None       ,				**lowerCamelCase		:			Optional[int]       ,				)						->	BatchEncoding:


         """simple docstring"""
         if titles is None and texts is None:
                return super().__call__(
                    lowerCamelCase       ,				padding=lowerCamelCase       ,				truncation=lowerCamelCase       ,				max_length=lowerCamelCase       ,				return_tensors=lowerCamelCase       ,				return_attention_mask=lowerCamelCase       ,				**lowerCamelCase       ,				)
         elif titles is None or texts is None:
                _UpperCAmelCase							=    titles if texts is None else texts
                return super().__call__(
                    lowerCamelCase       ,				lowerCamelCase       ,				padding=lowerCamelCase       ,				truncation=lowerCamelCase       ,				max_length=lowerCamelCase       ,				return_tensors=lowerCamelCase       ,				return_attention_mask=lowerCamelCase       ,				**lowerCamelCase       ,				)
         _UpperCAmelCase							=    titles if not isinstance(lowerCamelCase       ,				lowerCamelCase							) else [titles]
         _UpperCAmelCase							=    texts if not isinstance(lowerCamelCase       ,				lowerCamelCase							) else [texts]
         _UpperCAmelCase							=    len(lowerCamelCase							)
         _UpperCAmelCase							=    questions if not isinstance(lowerCamelCase       ,				lowerCamelCase							) else [questions] * n_passages
         if len(lowerCamelCase							) != len(lowerCamelCase							):
                raise ValueError(
                    f"""There should be as many titles than texts but got {len(lowerCamelCase							)} titles and {len(lowerCamelCase							)} texts."""							)
         _UpperCAmelCase							=    super().__call__(lowerCamelCase       ,				lowerCamelCase       ,				padding=lowerCamelCase       ,				truncation=lowerCamelCase							)["""input_ids"""]
         _UpperCAmelCase							=    super().__call__(lowerCamelCase       ,				add_special_tokens=lowerCamelCase       ,				padding=lowerCamelCase       ,				truncation=lowerCamelCase							)["""input_ids"""]
         _UpperCAmelCase							=    {
             """input_ids""": [
                 (encoded_question_and_title + encoded_text)[:max_length]
                 if max_length is not None and truncation
                 else encoded_question_and_title + encoded_text
                 for encoded_question_and_title, encoded_text in zip(lowerCamelCase       ,				lowerCamelCase							)
             ]
         }
         if return_attention_mask is not False:
                _UpperCAmelCase							=    []
                for input_ids in encoded_inputs["input_ids"]:
                       attention_mask.append([int(input_id != self.pad_token_id							) for input_id in input_ids]							)
                _UpperCAmelCase							=    attention_mask
         return self.pad(lowerCamelCase       ,				padding=lowerCamelCase       ,				max_length=lowerCamelCase       ,				return_tensors=lowerCamelCase							)


  def  lowerCamelCase       (      self		:			Tuple       ,				lowerCamelCase		:			BatchEncoding       ,				lowerCamelCase		:			DPRReaderOutput       ,				lowerCamelCase		:			int = 16       ,				lowerCamelCase		:			int = 64       ,				lowerCamelCase		:			int = 4       ,				)						->	List[DPRSpanPrediction]:


         """simple docstring"""
         _UpperCAmelCase							=    reader_input["""input_ids"""]
         _UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase							=    reader_output[:3]
         _UpperCAmelCase							=    len(lowerCamelCase							)
         _UpperCAmelCase							=    sorted(range(lowerCamelCase							)       ,				reverse=lowerCamelCase       ,				key=relevance_logits.__getitem__							)
         _UpperCAmelCase							=    []
         for doc_id in sorted_docs:
                _UpperCAmelCase							=    list(input_ids[doc_id]							)
                # assuming question & title information is at the beginning of the sequence
                _UpperCAmelCase							=    sequence_ids.index(self.sep_token_id       ,				2							) + 1  # second sep id
                if sequence_ids[-1] == self.pad_token_id:
                       _UpperCAmelCase							=    sequence_ids.index(self.pad_token_id							)
                else:
                       _UpperCAmelCase							=    len(lowerCamelCase							)

                _UpperCAmelCase							=    self._get_best_spans(
                    start_logits=start_logits[doc_id][passage_offset:sequence_len]       ,				end_logits=end_logits[doc_id][passage_offset:sequence_len]       ,				max_answer_length=lowerCamelCase       ,				top_spans=lowerCamelCase       ,				)
                for start_index, end_index in best_spans:
                       start_index += passage_offset
                       end_index += passage_offset
                       nbest_spans_predictions.append(
                           DPRSpanPrediction(
                               span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index]       ,				relevance_score=relevance_logits[doc_id]       ,				doc_id=lowerCamelCase       ,				start_index=lowerCamelCase       ,				end_index=lowerCamelCase       ,				text=self.decode(sequence_ids[start_index : end_index + 1]							)       ,				)							)
                if len(lowerCamelCase							) >= num_spans:
                       break
         return nbest_spans_predictions[:num_spans]





  def  lowerCamelCase       (      self		:			List[Any]       ,				lowerCamelCase		:			List[int]       ,				lowerCamelCase		:			List[int]       ,				lowerCamelCase		:			int       ,				lowerCamelCase		:			int       ,				)						->	List[DPRSpanPrediction]:


         """simple docstring"""
         _UpperCAmelCase							=    []
         for start_index, start_score in enumerate(lowerCamelCase							):
                for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]							):
                       scores.append(((start_index, start_index + answer_length), start_score + end_score)							)
         _UpperCAmelCase							=    sorted(lowerCamelCase       ,				key=lambda lowerCamelCase							: x[1]       ,				reverse=lowerCamelCase							)
         _UpperCAmelCase							=    []
         for (start_index, end_index), score in scores:
                if start_index > end_index:
                       raise ValueError(f"""Wrong span indices: [{start_index}:{end_index}]"""							)
                _UpperCAmelCase							=    end_index - start_index + 1
                if length > max_answer_length:
                       raise ValueError(f"""Span is too long: {length} > {max_answer_length}"""							)
                if any(
                    start_index <= prev_start_index <= prev_end_index <= end_index
                    or prev_start_index <= start_index <= end_index <= prev_end_index
                    for (prev_start_index, prev_end_index) in chosen_span_intervals							):
                       continue
                chosen_span_intervals.append((start_index, end_index)							)

                if len(lowerCamelCase							) == top_spans:
                       break
         return chosen_span_intervals



@add_end_docstrings(UpperCAmelCase     )
class 		SCREAMING_SNAKE_CASE__	(  UpperCAmelCase					,      UpperCAmelCase     ):

  '''simple docstring'''







  _lowerCamelCase    =  VOCAB_FILES_NAMES
  _lowerCamelCase    =  READER_PRETRAINED_VOCAB_FILES_MAP
  _lowerCamelCase    =  READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  _lowerCamelCase    =  READER_PRETRAINED_INIT_CONFIGURATION
  _lowerCamelCase    =  ['''input_ids''', '''attention_mask''']
'''simple docstring'''

from __future__ import absolute_import, division, print_function, unicode_literals

from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers import RobertaConfig
from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.roberta.modeling_roberta import (
    ROBERTA_INPUTS_DOCSTRING,
    ROBERTA_START_DOCSTRING,
    RobertaEmbeddings,
)

from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy


@add_start_docstrings(
    '''The RoBERTa Model transformer with early exiting (DeeRoBERTa). '''		,lowerCAmelCase		,)
class 					_lowercase						(   lowerCAmelCase ):
      '''simple docstring'''


      UpperCAmelCase_   :   int   				= RobertaConfig
      UpperCAmelCase_   :   Tuple   				= '''roberta'''




      def __init__(					self       ,lowerCamelCase_				)      ->      List[Any]:



         '''simple docstring'''



         super().__init__(lowerCamelCase_				)

         UpperCAmelCase__				:					Optional[Any] 					=	RobertaEmbeddings(lowerCamelCase_				)
         self.init_weights()




@add_start_docstrings(
    '''RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top,
    also takes care of multi-layer training. '''		,lowerCAmelCase		,)
class 					_lowercase						(   lowerCAmelCase ):
      '''simple docstring'''


      UpperCAmelCase_   :   Tuple   				= RobertaConfig
      UpperCAmelCase_   :   Optional[Any]   				= '''roberta'''




      def __init__(					self       ,lowerCamelCase_				)      ->      str:



         '''simple docstring'''



         super().__init__(lowerCamelCase_				)
         UpperCAmelCase__				:					Any 					=	config.num_labels
         UpperCAmelCase__				:					Union[str, Any] 					=	config.num_hidden_layers

         UpperCAmelCase__				:					str 					=	DeeRobertaModel(lowerCamelCase_				)
         UpperCAmelCase__				:					Optional[int] 					=	nn.Dropout(config.hidden_dropout_prob				)
         UpperCAmelCase__				:					Union[str, Any] 					=	nn.Linear(config.hidden_size       ,self.config.num_labels				)




      @add_start_docstrings_to_model_forward(lowerCamelCase_				)
      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_=None       ,lowerCamelCase_=None       ,lowerCamelCase_=None       ,lowerCamelCase_=None       ,lowerCamelCase_=None       ,lowerCamelCase_=None       ,lowerCamelCase_=None       ,lowerCamelCase_=-1       ,lowerCamelCase_=False       ,)      ->      Optional[Any]:



         '''simple docstring'''



         UpperCAmelCase__				:					Tuple 					=	self.num_layers
         try:
            UpperCAmelCase__				:					Union[str, Any] 					=	self.roberta(
                lowerCamelCase_       ,attention_mask=lowerCamelCase_       ,token_type_ids=lowerCamelCase_       ,position_ids=lowerCamelCase_       ,head_mask=lowerCamelCase_       ,inputs_embeds=lowerCamelCase_       ,)

            UpperCAmelCase__				:					List[Any] 					=	outputs[1]

            UpperCAmelCase__				:					Tuple 					=	self.dropout(lowerCamelCase_				)
            UpperCAmelCase__				:					Any 					=	self.classifier(lowerCamelCase_				)
            UpperCAmelCase__				:					Optional[int] 					=	(logits,) + outputs[2:]  # add hidden states and attention if they are here
         except HighwayException as e:
            UpperCAmelCase__				:					int 					=	e.message
            UpperCAmelCase__				:					Optional[int] 					=	e.exit_layer
            UpperCAmelCase__				:					Optional[int] 					=	outputs[0]

         if not self.training:
            UpperCAmelCase__				:					Dict 					=	entropy(lowerCamelCase_				)
            UpperCAmelCase__				:					List[Any] 					=	[]
            UpperCAmelCase__				:					str 					=	[]
         if labels is not None:
            if self.num_labels == 1:
               #  We are doing regression
               UpperCAmelCase__				:					str 					=	MSELoss()
               UpperCAmelCase__				:					Union[str, Any] 					=	loss_fct(logits.view(-1				)       ,labels.view(-1				)				)
            else:
               UpperCAmelCase__				:					Any 					=	CrossEntropyLoss()
               UpperCAmelCase__				:					Optional[Any] 					=	loss_fct(logits.view(-1       ,self.num_labels				)       ,labels.view(-1				)				)

            # work with highway exits
            UpperCAmelCase__				:					List[str] 					=	[]
            for highway_exit in outputs[-1]:
               UpperCAmelCase__				:					Optional[int] 					=	highway_exit[0]
               if not self.training:
                  highway_logits_all.append(lowerCamelCase_				)
                  highway_entropy.append(highway_exit[2]				)
               if self.num_labels == 1:
                  #  We are doing regression
                  UpperCAmelCase__				:					Any 					=	MSELoss()
                  UpperCAmelCase__				:					Optional[Any] 					=	loss_fct(highway_logits.view(-1				)       ,labels.view(-1				)				)
               else:
                  UpperCAmelCase__				:					Any 					=	CrossEntropyLoss()
                  UpperCAmelCase__				:					int 					=	loss_fct(highway_logits.view(-1       ,self.num_labels				)       ,labels.view(-1				)				)
               highway_losses.append(lowerCamelCase_				)

            if train_highway:
               UpperCAmelCase__				:					Dict 					=	(sum(highway_losses[:-1]				),) + outputs
               # exclude the final highway, of course
            else:
               UpperCAmelCase__				:					Dict 					=	(loss,) + outputs
         if not self.training:
            UpperCAmelCase__				:					Tuple 					=	outputs + ((original_entropy, highway_entropy), exit_layer)
            if output_layer >= 0:
               UpperCAmelCase__				:					int 					=	(
                   (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
               )  # use the highway of the last layer

         return outputs  # (loss), logits, (hidden_states), (attentions), entropy




