





"""simple docstring"""






import argparse
import random

import joblib
import numpy as np
import torch
from igf.igf import (
    SecondaryLearner,
    collect_objective_set,
    compute_perplexity,
    generate_datasets,
    load_gpta,
    recopy_gpta,
    set_seed,
    train_secondary_learner,
)
from torch.utils.data import DataLoader, RandomSampler

from transformers import GPTaLMHeadModel

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE=32,SCREAMING_SNAKE_CASE=10,SCREAMING_SNAKE_CASE=100,SCREAMING_SNAKE_CASE=1026,SCREAMING_SNAKE_CASE=True,SCREAMING_SNAKE_CASE="data/tokenized_stories_train_wikitext103.jbl",SCREAMING_SNAKE_CASE="igf_context_pairs.jbl",)		->       Optional[Any]:






       """simple docstring"""




       set_seed(3							)
       # generate train_data and objective_set
       _UpperCAmelCase    ,							_UpperCAmelCase     =     generate_datasets(
           UpperCAmelCase__,UpperCAmelCase__,number=UpperCAmelCase__,min_len=1026,trim=UpperCAmelCase__							)
       # keeps model same across runs
       set_seed(4							)
       # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights
       # can we train on GPU?
       _UpperCAmelCase     =     torch.device('cuda:0' if torch.cuda.is_available() else 'cpu'							)

       # load pretrained model
       _UpperCAmelCase     =     load_gpta('gpt2'							).to(UpperCAmelCase__							)
       print('computing perplexity on objective set'							)
       _UpperCAmelCase     =     compute_perplexity(UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__							).item()
       print('perplexity on objective set:',UpperCAmelCase__							)

       # collect igf pairs and save to file demo.jbl
       collect_objective_set(UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__							)

       # clean up, delete model and data we don't need anymore
       del model, train_data, objective_set
       torch.cuda.empty_cache()

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE=15,SCREAMING_SNAKE_CASE=128,SCREAMING_SNAKE_CASE=100,SCREAMING_SNAKE_CASE="igf_model.pt",)		->       Optional[Any]:






       """simple docstring"""




       set_seed(42							)

       # Load pre-trained model
       _UpperCAmelCase     =     GPTaLMHeadModel.from_pretrained('gpt2'							)

       # Initialize secondary learner to use embedding weights of model
       _UpperCAmelCase     =     SecondaryLearner(UpperCAmelCase__							)

       # Train secondary learner
       _UpperCAmelCase     =     train_secondary_learner(
           UpperCAmelCase__,UpperCAmelCase__,max_epochs=UpperCAmelCase__,batch_size=UpperCAmelCase__,eval_freq=100,igf_model_path=UpperCAmelCase__,)

       del model, secondary_learner_train_data
       torch.cuda.empty_cache()

       return secondary_learner

def       __lowerCamelCase    (       SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE=32,SCREAMING_SNAKE_CASE=1000,SCREAMING_SNAKE_CASE=16,SCREAMING_SNAKE_CASE=1.0,SCREAMING_SNAKE_CASE=recopy_gpta,SCREAMING_SNAKE_CASE=None,SCREAMING_SNAKE_CASE=10,SCREAMING_SNAKE_CASE="gpt2_finetuned.pt",)		->       Union[str, Any]:






       """simple docstring"""




       _UpperCAmelCase     =     torch.device('cuda:0' if torch.cuda.is_available() else 'cpu'							)
       _UpperCAmelCase     =     RandomSampler(UpperCAmelCase__							)
       _UpperCAmelCase     =     DataLoader(UpperCAmelCase__,sampler=UpperCAmelCase__							)

       _UpperCAmelCase     =     max_steps // (len(UpperCAmelCase__							)) + 1
       _UpperCAmelCase     =     0
       _UpperCAmelCase     =     torch.zeros((1, context_len),dtype=torch.long,device=UpperCAmelCase__							)
       _UpperCAmelCase    ,							_UpperCAmelCase    ,							_UpperCAmelCase     =     recopy_model(UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__							)

       model.train()
       if secondary_learner is not None:
              secondary_learner.to(UpperCAmelCase__							)
              secondary_learner.eval()
       _UpperCAmelCase     =     []
       _UpperCAmelCase     =     0

       _UpperCAmelCase     =     []
       _UpperCAmelCase     =     []

       # Compute the performance of the transformer model at the beginning
       _UpperCAmelCase     =     compute_perplexity(UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__							)
       test_perps.append(UpperCAmelCase__							)
       print('Test perplexity, step',UpperCAmelCase__,':',UpperCAmelCase__							)
       for epoch in range(int(UpperCAmelCase__							)							):
              for step, example in enumerate(UpperCAmelCase__							):
                     torch.cuda.empty_cache()
                     _UpperCAmelCase     =     random.randint(0,example.size(2							) - context_len - 1							)
                     _UpperCAmelCase     =     example[0, 0, start : start + context_len]
                     lm_optimizer.zero_grad()
                     _UpperCAmelCase     =     model(UpperCAmelCase__,labels=UpperCAmelCase__							)
                     _UpperCAmelCase     =     True

                     if secondary_learner is not None:
                            _UpperCAmelCase     =     secondary_learner.forward(
                                torch.tensor(UpperCAmelCase__,dtype=torch.long,device=UpperCAmelCase__							).unsqueeze(0							)							)[0].item()
                            observed_qs.append(float(UpperCAmelCase__							)							)

                            # Here we implement the simple non-constant threshold for the predicted IG(X) value
                            # We will decay the selectivity of our secondary learner filter from
                            # 1 standard deviation above average to 1 below average after 10 batches.

                            if global_step == 10:
                                   _UpperCAmelCase     =     -1
                            if predicted_q < threshold:
                                   _UpperCAmelCase     =     False

            # If we passed the filter, add the context to the batch!
                     if do_backprop:
                            contexts.append(np.array(context.cpu()							)							)
                            _UpperCAmelCase     =     outputs[0]
                            lm_loss.backward()
                            examples += 1

                     del outputs

                     # Once the batch is filled with enough contexts, backprop on the batch.
                     if examples == batch_size:
                            torch.cuda.empty_cache()
                            _UpperCAmelCase     =     0
                            # Do LM backprop
                            torch.nn.utils.clip_grad_norm_(model.parameters(),3.0							)
                            lm_optimizer.step()
                            lm_scheduler.step()  # Update learning rate schedule
                            global_step += 1
                            # Compute the performance of the transformer model at this batch
                            if global_step % eval_interval == 0:
                                   _UpperCAmelCase     =     compute_perplexity(UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__							)
                                   test_perps.append(UpperCAmelCase__							)

                                   print('Test perplexity, step',UpperCAmelCase__,':',UpperCAmelCase__							)
            # Break out of the loop after 60 batches
                     if max_steps > 0 and global_step > 60:
                            break
              if max_steps > 0 and global_step > 60:
                     break

    # save finetuned transformer model
       torch.save(model.state_dict(),UpperCAmelCase__							)
       torch.cuda.empty_cache()
       # Do some cleaning up so we can reinitialize for the next run of this function
       del lm_optimizer
       del lm_scheduler
       return model

def       __lowerCamelCase    (       )		->       str:






       """simple docstring"""




       _UpperCAmelCase     =     argparse.ArgumentParser(description='Fine-tune a transformer model with IGF on a language modeling task'							)

       # Required parameters
       parser.add_argument(
           '--data_dir',default=UpperCAmelCase__,type=UpperCAmelCase__,required=UpperCAmelCase__,help='The input data dir. Should contain data files for WikiText.',)
       parser.add_argument(
           '--model_name_or_path',default=UpperCAmelCase__,type=UpperCAmelCase__,required=UpperCAmelCase__,help='Path to pretrained model or model identifier from huggingface.co/models',)
       parser.add_argument(
           '--data_file',type=UpperCAmelCase__,default=UpperCAmelCase__,help=(
               'A jbl file containing tokenized data which can be split as objective dataset, '
               'train_dataset and test_dataset.'
           ),)

       parser.add_argument(
           '--igf_data_file',type=UpperCAmelCase__,default=UpperCAmelCase__,help='A jbl file containing the context and information gain pairs to train secondary learner.',)

       parser.add_argument(
           '--output_dir',default=UpperCAmelCase__,type=UpperCAmelCase__,required=UpperCAmelCase__,help='The output directory where the final fine-tuned model is stored.',)

       parser.add_argument(
           '--tokenizer_name',default=UpperCAmelCase__,type=UpperCAmelCase__,help='Pretrained tokenizer name or path if not the same as model_name',)
       parser.add_argument('--seed',type=UpperCAmelCase__,default=UpperCAmelCase__,help='A seed for reproducible training.'							)

       parser.add_argument(
           '--context_len',default=32,type=UpperCAmelCase__,help=(
               'The maximum total input sequence length after tokenization. Sequences longer '
               'than this will be truncated, sequences shorter will be padded.'
           ),)

       parser.add_argument(
           '--size_objective_set',default=100,type=UpperCAmelCase__,help='number of articles that are long enough to be used as our objective set',)
       parser.add_argument(
           '--eval_freq',default=100,type=UpperCAmelCase__,help='secondary model evaluation is triggered at eval_freq'							)

       parser.add_argument('--max_steps',default=1000,type=UpperCAmelCase__,help='To calculate training epochs'							)

       parser.add_argument(
           '--secondary_learner_batch_size',default=128,type=UpperCAmelCase__,help='batch size of training data for secondary learner',)

       parser.add_argument(
           '--batch_size',default=16,type=UpperCAmelCase__,help='batch size of training data of language model(gpt2) '							)

       parser.add_argument(
           '--eval_interval',default=10,type=UpperCAmelCase__,help=(
               'decay the selectivity of our secondary learner filter from'
               '1 standard deviation above average to 1 below average after 10 batches'
           ),)

       parser.add_argument(
           '--number',default=100,type=UpperCAmelCase__,help='The number of examples split to be used as objective_set/test_data'							)

       parser.add_argument(
           '--min_len',default=1026,type=UpperCAmelCase__,help='The minimum length of the article to be used as objective set'							)

       parser.add_argument(
           '--secondary_learner_max_epochs',default=15,type=UpperCAmelCase__,help='number of epochs to train secondary learner'							)

       parser.add_argument('--trim',default=UpperCAmelCase__,type=UpperCAmelCase__,help='truncate the example if it exceeds context length'							)

       parser.add_argument(
           '--threshold',default=1.0,type=UpperCAmelCase__,help=(
               'The threshold value used by secondary learner to filter the train_data and allow only'
               ' informative data as input to the model'
           ),)

       parser.add_argument('--finetuned_model_name',default='gpt2_finetuned.pt',type=UpperCAmelCase__,help='finetuned_model_name'							)

       parser.add_argument(
           '--recopy_model',default=UpperCAmelCase__,type=UpperCAmelCase__,help='Reset the model to the original pretrained GPT-2 weights after each iteration',)

       # function calls
       # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner
       generate_n_pairs(
           context_len=32,max_steps=10,size_objective_set=100,min_len=1026,trim=UpperCAmelCase__,data_file='data/tokenized_stories_train_wikitext103.jbl',igf_data_file='igf_context_pairs.jbl',)

       # Load train data for secondary learner
       _UpperCAmelCase     =     joblib.load('data/IGF_values.jbl'							)

       # Train secondary learner
       _UpperCAmelCase     =     training_secondary_learner(
           UpperCAmelCase__,secondary_learner_max_epochs=15,secondary_learner_batch_size=128,eval_freq=100,igf_model_path='igf_model.pt',)

       # load pretrained gpt2 model
       _UpperCAmelCase     =     GPTaLMHeadModel.from_pretrained('gpt2'							)
       set_seed(42							)

       # Generate train and test data to train and evaluate gpt2 model
       _UpperCAmelCase    ,							_UpperCAmelCase     =     generate_datasets(
           context_len=32,file='data/tokenized_stories_train_wikitext103.jbl',number=100,min_len=1026,trim=UpperCAmelCase__							)

       # fine-tuning of the gpt2 model using igf (Information Gain Filtration)
       finetune(
           UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__,context_len=32,max_steps=1000,batch_size=16,threshold=1.0,recopy_model=UpperCAmelCase__,secondary_learner=UpperCAmelCase__,eval_interval=10,finetuned_model_name='gpt2_finetuned.pt',)


if __name__ == "__main__":
    main()













"""simple docstring"""






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_			=							logging.get_logger(__name__)

lowerCAmelCase_			=							{'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

lowerCAmelCase_			=							{
    '''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_			=							{
    '''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_			=							{
    '''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_			=							{
    '''facebook/dpr-ctx_encoder-single-nq-base''': 512,
    '''facebook/dpr-ctx_encoder-multiset-base''': 512,
}
lowerCAmelCase_			=							{
    '''facebook/dpr-question_encoder-single-nq-base''': 512,
    '''facebook/dpr-question_encoder-multiset-base''': 512,
}
lowerCAmelCase_			=							{
    '''facebook/dpr-reader-single-nq-base''': 512,
    '''facebook/dpr-reader-multiset-base''': 512,
}


lowerCAmelCase_			=							{
    '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True},
}
lowerCAmelCase_			=							{
    '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True},
}
lowerCAmelCase_			=							{
    '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True},
}



class 	lowerCAmelCase					(      snake_case							):
       lowerCAmelCase__						 =  VOCAB_FILES_NAMES
       lowerCAmelCase__						 =  CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
       lowerCAmelCase__						 =  CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       lowerCAmelCase__						 =  CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION
       lowerCAmelCase__						 =  DPRContextEncoderTokenizer



class 	lowerCAmelCase					(      snake_case							):
       lowerCAmelCase__						 =  VOCAB_FILES_NAMES
       lowerCAmelCase__						 =  QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
       lowerCAmelCase__						 =  QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       lowerCAmelCase__						 =  QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION
       lowerCAmelCase__						 =  DPRQuestionEncoderTokenizer


lowerCAmelCase_			=							collections.namedtuple(
    '''DPRSpanPrediction''', ['''span_score''', '''relevance_score''', '''doc_id''', '''start_index''', '''end_index''', '''text''']
)

lowerCAmelCase_			=							collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits'''])


lowerCAmelCase_			=							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)

    Return:
        `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(snake_case							)
class 	lowerCAmelCase					:






       def __call__(   self    ,  a__    ,  a__ = None    ,  a__ = None    ,  a__ = False    ,  a__ = False    ,  a__ = None    ,  a__ = None    ,  a__ = None    ,  **a__    ,  ):
              if titles is None and texts is None:
                     return super().__call__(
                         a__    ,  padding=a__    ,  truncation=a__    ,  max_length=a__    ,  return_tensors=a__    ,  return_attention_mask=a__    ,  **a__    ,  )
              elif titles is None or texts is None:
                     _UpperCAmelCase     =     titles if texts is None else texts
                     return super().__call__(
                         a__    ,  a__    ,  padding=a__    ,  truncation=a__    ,  max_length=a__    ,  return_tensors=a__    ,  return_attention_mask=a__    ,  **a__    ,  )
              _UpperCAmelCase     =     titles if not isinstance(a__    ,  a__     ) else [titles]
              _UpperCAmelCase     =     texts if not isinstance(a__    ,  a__     ) else [texts]
              _UpperCAmelCase     =     len(a__     )
              _UpperCAmelCase     =     questions if not isinstance(a__    ,  a__     ) else [questions] * n_passages
              assert len(a__     ) == len(
                  a__     ), f"""There should be as many titles than texts but got {len(a__     )} titles and {len(a__     )} texts."""
              _UpperCAmelCase     =     super().__call__(a__    ,  a__    ,  padding=a__    ,  truncation=a__     )['input_ids']
              _UpperCAmelCase     =     super().__call__(a__    ,  add_special_tokens=a__    ,  padding=a__    ,  truncation=a__     )['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(a__    ,  a__     )
                  ]
              }
              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(a__    ,  padding=a__    ,  max_length=a__    ,  return_tensors=a__     )






       def 							__A (   self    ,  a__    ,  a__    ,  a__ = 16    ,  a__ = 64    ,  a__ = 4    ,  ):
              _UpperCAmelCase     =     reader_input['input_ids']
              _UpperCAmelCase    ,							_UpperCAmelCase    ,							_UpperCAmelCase     =     reader_output[:3]
              _UpperCAmelCase     =     len(a__     )
              _UpperCAmelCase     =     sorted(range(a__     )    ,  reverse=a__    ,  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(a__     )

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






       def 							__A (   self    ,  a__    ,  a__    ,  a__    ,  a__    ,  ):
              _UpperCAmelCase     =     []
              for start_index, start_score in enumerate(a__     ):
                     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(a__    ,  key=lambda a__     : x[1]    ,  reverse=a__     )
              _UpperCAmelCase     =     []
              for (start_index, end_index), score in scores:
                     assert start_index <= end_index, f"""Wrong span indices: [{start_index}:{end_index}]"""
                     _UpperCAmelCase     =     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(a__     ) == top_spans:
                            break
              return chosen_span_intervals



@add_end_docstrings(snake_case							)
class 	lowerCAmelCase					(      snake_case			,	snake_case							):
       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"""]
       lowerCAmelCase__						 =  DPRReaderTokenizer






