


import argparse
import csv
import logging
import os
import random

import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from tqdm import tqdm, trange

from transformers import (
    CONFIG_NAME,
    WEIGHTS_NAME,
    AdamW,
    OpenAIGPTDoubleHeadsModel,
    OpenAIGPTTokenizer,
    get_linear_schedule_with_warmup,
)


logging.basicConfig(
    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO
)
lowerCamelCase		   =			logging.getLogger(__name__)




def       a_ (       SCREAMING_SNAKE_CASE__   : Dict						,     SCREAMING_SNAKE_CASE__   : Tuple	):
       '''simple docstring'''





       _lowerCamelCase			:						str            =np.argmax(A_						,     axis=1	)
       return np.sum(outputs == labels	)




def       a_ (       SCREAMING_SNAKE_CASE__   : Union[str, Any]	):
       '''simple docstring'''





       with open(A_						,     encoding='utf_8'	) as f:
              _lowerCamelCase			:						Dict            =csv.reader(A_	)
              _lowerCamelCase			:						Optional[int]            =[]
              next(A_	)  # skip the first line
              for line in tqdm(A_	):
                     output.append((' '.join(line[1:5]	), line[5], line[6], int(line[-1]	) - 1)	)
       return output




def       a_ (       SCREAMING_SNAKE_CASE__   : Tuple						,     SCREAMING_SNAKE_CASE__   : Any						,     SCREAMING_SNAKE_CASE__   : Any						,     SCREAMING_SNAKE_CASE__   : List[Any]						,     SCREAMING_SNAKE_CASE__   : str						,     SCREAMING_SNAKE_CASE__   : Dict	):
       '''simple docstring'''





       _lowerCamelCase			:						str            =[]
       for dataset in encoded_datasets:
              _lowerCamelCase			:						Union[str, Any]            =len(A_	)
              _lowerCamelCase			:						List[Any]            =np.zeros((n_batch, 2, input_len)						,     dtype=np.intaa	)
              _lowerCamelCase			:						List[Any]            =np.zeros((n_batch, 2)						,     dtype=np.intaa	)
              _lowerCamelCase			:						Union[str, Any]            =np.full((n_batch, 2, input_len)						,     fill_value=-100						,     dtype=np.intaa	)
              _lowerCamelCase			:						Optional[int]            =np.zeros((n_batch,)						,     dtype=np.intaa	)
              for (
                  i,
                  (story, conta, conta, mc_label),
              ) in enumerate(A_	):
                     _lowerCamelCase			:						str            =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
                     _lowerCamelCase			:						List[Any]            =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
                     _lowerCamelCase			:						Union[str, Any]            =with_conta
                     _lowerCamelCase			:						Any            =with_conta
                     _lowerCamelCase			:						Any            =len(A_	) - 1
                     _lowerCamelCase			:						List[Any]            =len(A_	) - 1
                     _lowerCamelCase			:						Tuple            =with_conta
                     _lowerCamelCase			:						str            =with_conta
                     _lowerCamelCase			:						List[Any]            =mc_label
              _lowerCamelCase			:						Any            =(input_ids, mc_token_ids, lm_labels, mc_labels)
              tensor_datasets.append(tuple(torch.tensor(A_	) for t in all_inputs	)	)
       return tensor_datasets




def       a_ (       ):
       '''simple docstring'''





       _lowerCamelCase			:						List[str]            =argparse.ArgumentParser()
       parser.add_argument('--model_name'						,     type=A_						,     default='openai-gpt'						,     help='pretrained model name'	)
       parser.add_argument('--do_train'						,     action='store_true'						,     help='Whether to run training.'	)
       parser.add_argument('--do_eval'						,     action='store_true'						,     help='Whether to run eval on the dev set.'	)
       parser.add_argument(
           '--output_dir'						,     default=A_						,     type=A_						,     required=A_						,     help='The output directory where the model predictions and checkpoints will be written.'						,     )
       parser.add_argument('--train_dataset'						,     type=A_						,     default=''	)
       parser.add_argument('--eval_dataset'						,     type=A_						,     default=''	)
       parser.add_argument('--seed'						,     type=A_						,     default=42	)
       parser.add_argument('--num_train_epochs'						,     type=A_						,     default=3	)
       parser.add_argument('--train_batch_size'						,     type=A_						,     default=8	)
       parser.add_argument('--eval_batch_size'						,     type=A_						,     default=16	)
       parser.add_argument('--adam_epsilon'						,     default=1e-8						,     type=A_						,     help='Epsilon for Adam optimizer.'	)
       parser.add_argument('--max_grad_norm'						,     type=A_						,     default=1	)
       parser.add_argument(
           '--max_steps'						,     default=-1						,     type=A_						,     help=(
               'If > 0: set total number of training                         steps to perform. Override num_train_epochs.'
           )						,     )
       parser.add_argument(
           '--gradient_accumulation_steps'						,     type=A_						,     default=1						,     help='Number of updates steps to accumulate before                        performing a backward/update pass.'						,     )
       parser.add_argument('--learning_rate'						,     type=A_						,     default=6.25e-5	)
       parser.add_argument('--warmup_steps'						,     default=0						,     type=A_						,     help='Linear warmup over warmup_steps.'	)
       parser.add_argument('--lr_schedule'						,     type=A_						,     default='warmup_linear'	)
       parser.add_argument('--weight_decay'						,     type=A_						,     default=0.01	)
       parser.add_argument('--lm_coef'						,     type=A_						,     default=0.9	)
       parser.add_argument('--n_valid'						,     type=A_						,     default=374	)

       parser.add_argument('--server_ip'						,     type=A_						,     default=''						,     help='Can be used for distant debugging.'	)
       parser.add_argument('--server_port'						,     type=A_						,     default=''						,     help='Can be used for distant debugging.'	)
       _lowerCamelCase			:						Union[str, Any]            =parser.parse_args()
       print(A_	)

       if args.server_ip and args.server_port:
              # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
              import ptvsd

              print('Waiting for debugger attach'	)
              ptvsd.enable_attach(address=(args.server_ip, args.server_port)						,     redirect_output=A_	)
              ptvsd.wait_for_attach()

       random.seed(args.seed	)
       np.random.seed(args.seed	)
       torch.manual_seed(args.seed	)
       torch.cuda.manual_seed_all(args.seed	)

       _lowerCamelCase			:						Optional[int]            =torch.device('cuda' if torch.cuda.is_available() else 'cpu'	)
       _lowerCamelCase			:						Tuple            =torch.cuda.device_count()
       logger.info('device: {}, n_gpu {}'.format(A_						,     A_	)	)

       if not args.do_train and not args.do_eval:
              raise ValueError('At least one of `do_train` or `do_eval` must be True.'	)

       if not os.path.exists(args.output_dir	):
              os.makedirs(args.output_dir	)

       # Load tokenizer and model
       # This loading functions also add new tokens and embeddings called `special tokens`
       # These new embeddings will be fine-tuned on the RocStories dataset
       _lowerCamelCase			:						List[str]            =['_start_', '_delimiter_', '_classify_']
       _lowerCamelCase			:						Dict            =OpenAIGPTTokenizer.from_pretrained(args.model_name	)
       tokenizer.add_tokens(A_	)
       _lowerCamelCase			:						int            =tokenizer.convert_tokens_to_ids(A_	)
       _lowerCamelCase			:						str            =OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name	)
       model.resize_token_embeddings(len(A_	)	)
       model.to(A_	)

       # Load and encode the datasets
       def tokenize_and_encode(SCREAMING_SNAKE_CASE__   : Optional[int]	):
              if isinstance(A_						,     A_	):
                     return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(A_	)	)
              elif isinstance(A_						,     A_	):
                     return obj
              return [tokenize_and_encode(A_	) for o in obj]

       logger.info('Encoding dataset...'	)
       _lowerCamelCase			:						Tuple            =load_rocstories_dataset(args.train_dataset	)
       _lowerCamelCase			:						Optional[Any]            =load_rocstories_dataset(args.eval_dataset	)
       _lowerCamelCase			:						Optional[int]            =(train_dataset, eval_dataset)
       _lowerCamelCase			:						Tuple            =tokenize_and_encode(A_	)

       # Compute the max input length for the Transformer
       _lowerCamelCase			:						Any            =model.config.n_positions // 2 - 2
       _lowerCamelCase			:						Dict            =max(
           len(story[:max_length]	) + max(len(conta[:max_length]	)						,     len(conta[:max_length]	)	) + 3
           for dataset in encoded_datasets
           for story, conta, conta, _ in dataset	)
       _lowerCamelCase			:						List[str]            =min(A_						,     model.config.n_positions	)  # Max size of input for the pre-trained model

       # Prepare inputs tensors and dataloaders
       _lowerCamelCase			:						int            =pre_process_datasets(A_						,     A_						,     A_						,     *A_	)
       _lowerCamelCase      ,	_lowerCamelCase			:						List[str]            =tensor_datasets[0], tensor_datasets[1]

       _lowerCamelCase			:						List[Any]            =TensorDataset(*A_	)
       _lowerCamelCase			:						Union[str, Any]            =RandomSampler(A_	)
       _lowerCamelCase			:						Tuple            =DataLoader(A_						,     sampler=A_						,     batch_size=args.train_batch_size	)

       _lowerCamelCase			:						int            =TensorDataset(*A_	)
       _lowerCamelCase			:						Union[str, Any]            =SequentialSampler(A_	)
       _lowerCamelCase			:						List[str]            =DataLoader(A_						,     sampler=A_						,     batch_size=args.eval_batch_size	)

       # Prepare optimizer
       if args.do_train:
              if args.max_steps > 0:
                     _lowerCamelCase			:						str            =args.max_steps
                     _lowerCamelCase			:						Any            =args.max_steps // (len(A_	) // args.gradient_accumulation_steps) + 1
              else:
                     _lowerCamelCase			:						Tuple            =len(A_	) // args.gradient_accumulation_steps * args.num_train_epochs

              _lowerCamelCase			:						Tuple            =list(model.named_parameters()	)
              _lowerCamelCase			:						int            =['bias', 'LayerNorm.bias', 'LayerNorm.weight']
              _lowerCamelCase			:						Tuple            =[
                  {
                      'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay	)],
                      'weight_decay': args.weight_decay,
                  },
                  {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay	)], 'weight_decay': 0.0},
              ]
              _lowerCamelCase			:						int            =AdamW(A_						,     lr=args.learning_rate						,     eps=args.adam_epsilon	)
              _lowerCamelCase			:						Optional[Any]            =get_linear_schedule_with_warmup(
                  A_						,     num_warmup_steps=args.warmup_steps						,     num_training_steps=A_	)

       if args.do_train:
              _lowerCamelCase      ,	_lowerCamelCase      ,	_lowerCamelCase			:						List[str]            =0, 0, None
              model.train()
              for _ in trange(int(args.num_train_epochs	)						,     desc='Epoch'	):
                     _lowerCamelCase			:						str            =0
                     _lowerCamelCase			:						Optional[int]            =0
                     _lowerCamelCase			:						Any            =tqdm(A_						,     desc='Training'	)
                     for step, batch in enumerate(A_	):
                            _lowerCamelCase			:						Dict            =tuple(t.to(A_	) for t in batch	)
                            _lowerCamelCase      ,	_lowerCamelCase      ,	_lowerCamelCase      ,	_lowerCamelCase			:						Union[str, Any]            =batch
                            _lowerCamelCase			:						Any            =model(A_						,     mc_token_ids=A_						,     lm_labels=A_						,     mc_labels=A_	)
                            _lowerCamelCase			:						Tuple            =args.lm_coef * losses[0] + losses[1]
                            loss.backward()
                            optimizer.step()
                            scheduler.step()
                            optimizer.zero_grad()
                            tr_loss += loss.item()
                            _lowerCamelCase			:						Optional[Any]            =(
                                loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
                            )
                            nb_tr_steps += 1
                            _lowerCamelCase			:						Union[str, Any]            ='Training loss: {:.2e} lr: {:.2e}'.format(A_						,     scheduler.get_lr()[0]	)

              # Save a trained model
       if args.do_train:
              # Save a trained model, configuration and tokenizer
              _lowerCamelCase			:						Dict            =model.module if hasattr(A_						,     'module'	) else model  # Only save the model itself

              # If we save using the predefined names, we can load using `from_pretrained`
              _lowerCamelCase			:						Optional[Any]            =os.path.join(args.output_dir						,     A_	)
              _lowerCamelCase			:						str            =os.path.join(args.output_dir						,     A_	)

              torch.save(model_to_save.state_dict()						,     A_	)
              model_to_save.config.to_json_file(A_	)
              tokenizer.save_vocabulary(args.output_dir	)

              # Load a trained model and vocabulary that you have fine-tuned
              _lowerCamelCase			:						Union[str, Any]            =OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir	)
              _lowerCamelCase			:						Any            =OpenAIGPTTokenizer.from_pretrained(args.output_dir	)
              model.to(A_	)

       if args.do_eval:
              model.eval()
              _lowerCamelCase      ,	_lowerCamelCase			:						int            =0, 0
              _lowerCamelCase      ,	_lowerCamelCase			:						List[Any]            =0, 0
              for batch in tqdm(A_						,     desc='Evaluating'	):
                     _lowerCamelCase			:						Union[str, Any]            =tuple(t.to(A_	) for t in batch	)
                     _lowerCamelCase      ,	_lowerCamelCase      ,	_lowerCamelCase      ,	_lowerCamelCase			:						Any            =batch
                     with torch.no_grad():
                            _lowerCamelCase      ,	_lowerCamelCase      ,	_lowerCamelCase      ,	_lowerCamelCase			:						Dict            =model(
                                A_						,     mc_token_ids=A_						,     lm_labels=A_						,     mc_labels=A_	)

                     _lowerCamelCase			:						Any            =mc_logits.detach().cpu().numpy()
                     _lowerCamelCase			:						List[Any]            =mc_labels.to('cpu'	).numpy()
                     _lowerCamelCase			:						str            =accuracy(A_						,     A_	)

                     eval_loss += mc_loss.mean().item()
                     eval_accuracy += tmp_eval_accuracy

                     nb_eval_examples += input_ids.size(0	)
                     nb_eval_steps += 1

              _lowerCamelCase			:						Dict            =eval_loss / nb_eval_steps
              _lowerCamelCase			:						Union[str, Any]            =eval_accuracy / nb_eval_examples
              _lowerCamelCase			:						Union[str, Any]            =tr_loss / nb_tr_steps if args.do_train else None
              _lowerCamelCase			:						Union[str, Any]            ={'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss}

              _lowerCamelCase			:						Tuple            =os.path.join(args.output_dir						,     'eval_results.txt'	)
              with open(A_						,     'w'	) as writer:
                     logger.info('***** Eval results *****'	)
                     for key in sorted(result.keys()	):
                            logger.info('  %s = %s'						,     A_						,     str(result[key]	)	)
                            writer.write('%s = %s\n' % (key, str(result[key]	))	)


if __name__ == "__main__":
 main()




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_fast import BertTokenizerFast
from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer


__lowerCAmelCase     :	Optional[Any]       			=  logging.get_logger(__name__)

__lowerCAmelCase     :	List[str]       			=  {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'}

__lowerCAmelCase     :	int       			=  {
    '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'
        ),
    },
}
__lowerCAmelCase     :	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'
        ),
    },
}
__lowerCAmelCase     :	List[Any]       			=  {
    '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'
        ),
    },
}

__lowerCAmelCase     :	Any       			=  {
    'facebook/dpr-ctx_encoder-single-nq-base': 512,
    'facebook/dpr-ctx_encoder-multiset-base': 512,
}
__lowerCAmelCase     :	Optional[int]       			=  {
    'facebook/dpr-question_encoder-single-nq-base': 512,
    'facebook/dpr-question_encoder-multiset-base': 512,
}
__lowerCAmelCase     :	Optional[int]       			=  {
    'facebook/dpr-reader-single-nq-base': 512,
    'facebook/dpr-reader-multiset-base': 512,
}


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




class 			UpperCAmelCase_     (					_A	):


  '''simple docstring'''







  a__       			=						VOCAB_FILES_NAMES
  a__       			=						CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
  a__       			=						CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a__       			=						CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION
  a__       			=						DPRContextEncoderTokenizer







class 			UpperCAmelCase_     (					_A	):


  '''simple docstring'''







  a__       			=						VOCAB_FILES_NAMES
  a__       			=						QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
  a__       			=						QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a__       			=						QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION
  a__       			=						DPRQuestionEncoderTokenizer







__lowerCAmelCase     :	Optional[int]       			=  collections.namedtuple(
    'DPRSpanPrediction', ['span_score', 'relevance_score', 'doc_id', 'start_index', 'end_index', 'text']
)

__lowerCAmelCase     :	Union[str, Any]       			=  collections.namedtuple('DPRReaderOutput', ['start_logits', 'end_logits', 'relevance_logits'])


__lowerCAmelCase     :	str       			=  R'\n    Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n    It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n    using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n    with the format:\n\n    [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n    Args:\n        questions (`str` or `List[str]`):\n            The questions to be encoded. You can specify one question for many passages. In this case, the question\n            will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n            `titles` or `texts`.\n        titles (`str` or `List[str]`):\n            The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n        texts (`str` or `List[str]`):\n            The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n        padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n            Activates and controls padding. Accepts the following values:\n\n            - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n              if provided).\n            - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n              acceptable input length for the model if that argument is not provided.\n            - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different\n              lengths).\n        truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n            Activates and controls truncation. Accepts the following values:\n\n            - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to\n              the maximum acceptable input length for the model if that argument is not provided. This will truncate\n              token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n              of pairs) is provided.\n            - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n              acceptable input length for the model if that argument is not provided. This will only truncate the first\n              sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n            - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n              acceptable input length for the model if that argument is not provided. This will only truncate the\n              second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n            - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths\n              greater than the model maximum admissible input size).\n        max_length (`int`, *optional*):\n                Controls the maximum length to use by one of the truncation/padding parameters.\n\n                If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n                is required by one of the truncation/padding parameters. If the model has no specific maximum input\n                length (like XLNet) truncation/padding to a maximum length will be deactivated.\n        return_tensors (`str` or [`~utils.TensorType`], *optional*):\n                If set, will return tensors instead of list of python integers. Acceptable values are:\n\n                - `\'tf\'`: Return TensorFlow `tf.constant` objects.\n                - `\'pt\'`: Return PyTorch `torch.Tensor` objects.\n                - `\'np\'`: Return Numpy `np.ndarray` objects.\n        return_attention_mask (`bool`, *optional*):\n            Whether or not to return the attention mask. If not set, will return the attention mask according to the\n            specific tokenizer\'s default, defined by the `return_outputs` attribute.\n\n            [What are attention masks?](../glossary#attention-mask)\n\n    Return:\n        `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n        - `input_ids`: List of token ids to be fed to a model.\n        - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n    '




@add_start_docstrings(_A	)
class 			UpperCAmelCase_     :


  '''simple docstring'''







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







    """simple docstring"""






    if titles is None and texts is None:
      return super().__call__(
          UpperCamelCase__     ,				padding=UpperCamelCase__     ,				truncation=UpperCamelCase__     ,				max_length=UpperCamelCase__     ,				return_tensors=UpperCamelCase__     ,				return_attention_mask=UpperCamelCase__     ,				**UpperCamelCase__     ,				)
    elif titles is None or texts is None:
      __magic_name__								=			titles if texts is None else texts
      return super().__call__(
          UpperCamelCase__     ,				UpperCamelCase__     ,				padding=UpperCamelCase__     ,				truncation=UpperCamelCase__     ,				max_length=UpperCamelCase__     ,				return_tensors=UpperCamelCase__     ,				return_attention_mask=UpperCamelCase__     ,				**UpperCamelCase__     ,				)
    __magic_name__								=			titles if not isinstance(UpperCamelCase__     ,				UpperCamelCase__       ) else [titles]
    __magic_name__								=			texts if not isinstance(UpperCamelCase__     ,				UpperCamelCase__       ) else [texts]
    __magic_name__								=			len(UpperCamelCase__       )
    __magic_name__								=			questions if not isinstance(UpperCamelCase__     ,				UpperCamelCase__       ) else [questions] * n_passages
    assert len(UpperCamelCase__       ) == len(
        UpperCamelCase__       ), F'''There should be as many titles than texts but got {len(UpperCamelCase__       )} titles and {len(UpperCamelCase__       )} texts.'''
    __magic_name__								=			super().__call__(UpperCamelCase__     ,				UpperCamelCase__     ,				padding=UpperCamelCase__     ,				truncation=UpperCamelCase__       )["""input_ids"""]
    __magic_name__								=			super().__call__(UpperCamelCase__     ,				add_special_tokens=UpperCamelCase__     ,				padding=UpperCamelCase__     ,				truncation=UpperCamelCase__       )["""input_ids"""]
    __magic_name__								=			{
        """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(UpperCamelCase__     ,				UpperCamelCase__       )
        ]
    }
    if return_attention_mask is not False:
      __magic_name__								=			[]
      for input_ids in encoded_inputs["input_ids"]:
        attention_mask.append([int(input_id != self.pad_token_id       ) for input_id in input_ids]       )
      __magic_name__								=			attention_mask
    return self.pad(UpperCamelCase__     ,				padding=UpperCamelCase__     ,				max_length=UpperCamelCase__     ,				return_tensors=UpperCamelCase__       )
  def 				_lowercase				(					self     :					List[Any]     ,				UpperCamelCase__     :					BatchEncoding     ,				UpperCamelCase__     :					DPRReaderOutput     ,				UpperCamelCase__     :					int = 16     ,				UpperCamelCase__     :					int = 64     ,				UpperCamelCase__     :					int = 4     ,				)     ->      List[DPRSpanPrediction]:







    """simple docstring"""






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

      __magic_name__								=			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=UpperCamelCase__     ,				top_spans=UpperCamelCase__     ,				)
      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=UpperCamelCase__     ,				start_index=UpperCamelCase__     ,				end_index=UpperCamelCase__     ,				text=self.decode(sequence_ids[start_index : end_index + 1]       )     ,				)       )
      if len(UpperCamelCase__       ) >= num_spans:
        break
    return nbest_spans_predictions[:num_spans]





  def 				_lowercase				(					self     :					Optional[int]     ,				UpperCamelCase__     :					List[int]     ,				UpperCamelCase__     :					List[int]     ,				UpperCamelCase__     :					int     ,				UpperCamelCase__     :					int     ,				)     ->      List[DPRSpanPrediction]:







    """simple docstring"""






    __magic_name__								=			[]
    for start_index, start_score in enumerate(UpperCamelCase__       ):
      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)       )
    __magic_name__								=			sorted(UpperCamelCase__     ,				key=lambda UpperCamelCase__       : x[1]     ,				reverse=UpperCamelCase__       )
    __magic_name__								=			[]
    for (start_index, end_index), score in scores:
      assert start_index <= end_index, F'''Wrong span indices: [{start_index}:{end_index}]'''
      __magic_name__								=			end_index - start_index + 1
      assert length <= max_answer_length, 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(UpperCamelCase__       ) == top_spans:
        break
    return chosen_span_intervals







@add_end_docstrings(_A	)
class 			UpperCAmelCase_     (					_A    ,			_A	):


  '''simple docstring'''







  a__       			=						VOCAB_FILES_NAMES
  a__       			=						READER_PRETRAINED_VOCAB_FILES_MAP
  a__       			=						READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a__       			=						READER_PRETRAINED_INIT_CONFIGURATION
  a__       			=						["""input_ids""", """attention_mask"""]
  a__       			=						DPRReaderTokenizer

