





import math
import unittest

from transformers import BioGptConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          BioGptForCausalLM,
          BioGptForSequenceClassification,
          BioGptForTokenClassification,
          BioGptModel,
          BioGptTokenizer,
      )
      from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST





class 					A_					:







       """simple docstring"""





       def __init__(     self						:						str    ,__A						:						Union[str, Any]    ,__A						:						Any=13    ,__A						:						Union[str, Any]=7    ,__A						:						List[Any]=True    ,__A						:						int=True    ,__A						:						Optional[Any]=False    ,__A						:						Union[str, Any]=True    ,__A						:						Union[str, Any]=99    ,__A						:						Any=32    ,__A						:						Tuple=5    ,__A						:						Tuple=4    ,__A						:						Union[str, Any]=37    ,__A						:						str="gelu"    ,__A						:						Optional[int]=0.1    ,__A						:						Dict=0.1    ,__A						:						Any=512    ,__A						:						Optional[Any]=16    ,__A						:						Any=2    ,__A						:						List[str]=0.02    ,__A						:						Dict=3    ,__A						:						Any=4    ,__A						:						int=None    ,)    ->       Dict:
         _lowercase						    =			parent
         _lowercase						    =			batch_size
         _lowercase						    =			seq_length
         _lowercase						    =			is_training
         _lowercase						    =			use_input_mask
         _lowercase						    =			use_token_type_ids
         _lowercase						    =			use_labels
         _lowercase						    =			vocab_size
         _lowercase						    =			hidden_size
         _lowercase						    =			num_hidden_layers
         _lowercase						    =			num_attention_heads
         _lowercase						    =			intermediate_size
         _lowercase						    =			hidden_act
         _lowercase						    =			hidden_dropout_prob
         _lowercase						    =			attention_probs_dropout_prob
         _lowercase						    =			max_position_embeddings
         _lowercase						    =			type_vocab_size
         _lowercase						    =			type_sequence_label_size
         _lowercase						    =			initializer_range
         _lowercase						    =			num_labels
         _lowercase						    =			num_choices
         _lowercase						    =			scope







       def  __UpperCAmelCase			(     self						:						List[Any]	)    ->       str:
         _lowercase						    =			ids_tensor([self.batch_size, self.seq_length]    ,self.vocab_size	)

         _lowercase						    =			None
         if self.use_input_mask:
           _lowercase						    =			random_attention_mask([self.batch_size, self.seq_length]	)

         _lowercase						    =			None
         if self.use_token_type_ids:
           _lowercase						    =			ids_tensor([self.batch_size, self.seq_length]    ,self.type_vocab_size	)

         _lowercase						    =			None
         _lowercase						    =			None
         _lowercase						    =			None
         if self.use_labels:
           _lowercase						    =			ids_tensor([self.batch_size]    ,self.type_sequence_label_size	)
           _lowercase						    =			ids_tensor([self.batch_size, self.seq_length]    ,self.num_labels	)
           _lowercase						    =			ids_tensor([self.batch_size]    ,self.num_choices	)

         _lowercase						    =			self.get_config()

         return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels







       def  __UpperCAmelCase			(     self						:						Union[str, Any]	)    ->       List[Any]:
         return BioGptConfig(
             vocab_size=self.vocab_size    ,hidden_size=self.hidden_size    ,num_hidden_layers=self.num_hidden_layers    ,num_attention_heads=self.num_attention_heads    ,intermediate_size=self.intermediate_size    ,hidden_act=self.hidden_act    ,hidden_dropout_prob=self.hidden_dropout_prob    ,attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,max_position_embeddings=self.max_position_embeddings    ,type_vocab_size=self.type_vocab_size    ,is_decoder=__A    ,initializer_range=self.initializer_range    ,)







       def  __UpperCAmelCase			(     self						:						Optional[Any]    ,__A						:						List[Any]    ,__A						:						Optional[int]    ,__A						:						Optional[Any]    ,__A						:						str    ,__A						:						int    ,__A						:						int    ,__A						:						Optional[Any]	)    ->       int:
         _lowercase						    =			BioGptModel(config=__A	)
         model.to(__A	)
         model.eval()
         _lowercase						    =			model(__A    ,attention_mask=__A	)
         _lowercase						    =			model(__A	)
         self.parent.assertEqual(result.last_hidden_state.shape    ,(self.batch_size, self.seq_length, self.hidden_size)	)







       def  __UpperCAmelCase			(     self						:						List[str]    ,__A						:						Optional[Any]    ,__A						:						Dict    ,__A						:						Dict    ,__A						:						Union[str, Any]    ,__A						:						str    ,__A						:						Any    ,__A						:						str    ,__A						:						List[Any]    ,__A						:						List[Any]    ,)    ->       Tuple:
         _lowercase						    =			BioGptForCausalLM(config=__A	)
         model.to(__A	)
         model.eval()
         _lowercase						    =			model(__A    ,attention_mask=__A    ,token_type_ids=__A    ,labels=__A	)
         self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.seq_length, self.vocab_size)	)







       def  __UpperCAmelCase			(     self						:						Optional[int]    ,__A						:						str    ,__A						:						int    ,__A						:						int    ,__A						:						int    ,__A						:						List[Any]    ,*__A						:						Union[str, Any]	)    ->       Tuple:
         _lowercase						    =			BioGptModel(config=__A	)
         model.to(__A	)
         model.eval()

         # create attention mask
         _lowercase						    =			torch.ones(input_ids.shape    ,dtype=torch.long    ,device=__A	)
         _lowercase						    =			self.seq_length // 2
         _lowercase						    =			0

         # first forward pass
         _lowercase    ,		_lowercase						    =			model(__A    ,attention_mask=__A	).to_tuple()

         # create hypothetical next token and extent to next_input_ids
         _lowercase						    =			ids_tensor((self.batch_size, 1)    ,config.vocab_size	)

         # change a random masked slice from input_ids
         _lowercase						    =			ids_tensor((1,)    ,__A	).item() + 1
         _lowercase						    =			ids_tensor((self.batch_size, 1)    ,config.vocab_size	).squeeze(-1	)
         _lowercase						    =			random_other_next_tokens

         # append to next input_ids and attn_mask
         _lowercase						    =			torch.cat([input_ids, next_tokens]    ,dim=-1	)
         _lowercase						    =			torch.cat(
             [attn_mask, torch.ones((attn_mask.shape[0], 1)    ,dtype=torch.long    ,device=__A	)]    ,dim=1    ,)

         # get two different outputs
         _lowercase						    =			model(__A    ,attention_mask=__A	)['last_hidden_state']
         _lowercase						    =			model(__A    ,past_key_values=__A    ,attention_mask=__A	)['last_hidden_state']

         # select random slice
         _lowercase						    =			ids_tensor((1,)    ,output_from_past.shape[-1]	).item()
         _lowercase						    =			output_from_no_past[:, -1, random_slice_idx].detach()
         _lowercase						    =			output_from_past[:, 0, random_slice_idx].detach()

         # test that outputs are equal for slice
         self.parent.assertTrue(torch.allclose(__A    ,__A    ,atol=1e-3	)	)







       def  __UpperCAmelCase			(     self						:						Tuple    ,__A						:						List[str]    ,__A						:						Any    ,__A						:						List[Any]    ,__A						:						Dict    ,__A						:						Optional[int]    ,*__A						:						List[Any]	)    ->       List[str]:
         _lowercase						    =			BioGptModel(config=__A	).to(__A	).eval()

         _lowercase						    =			torch.ones(input_ids.shape    ,dtype=torch.long    ,device=__A	)

         # first forward pass
         _lowercase						    =			model(__A    ,attention_mask=__A    ,use_cache=__A	)

         _lowercase    ,		_lowercase						    =			outputs.to_tuple()

         # create hypothetical multiple next token and extent to next_input_ids
         _lowercase						    =			ids_tensor((self.batch_size, 3)    ,config.vocab_size	)
         _lowercase						    =			ids_tensor((self.batch_size, 3)    ,2	)

         # append to next input_ids and
         _lowercase						    =			torch.cat([input_ids, next_tokens]    ,dim=-1	)
         _lowercase						    =			torch.cat([attention_mask, next_attn_mask]    ,dim=-1	)

         _lowercase						    =			model(__A    ,attention_mask=__A	)['last_hidden_state']
         _lowercase						    =			model(__A    ,attention_mask=__A    ,past_key_values=__A	)[
             'last_hidden_state'
         ]

         # select random slice
         _lowercase						    =			ids_tensor((1,)    ,output_from_past.shape[-1]	).item()
         _lowercase						    =			output_from_no_past[:, -3:, random_slice_idx].detach()
         _lowercase						    =			output_from_past[:, :, random_slice_idx].detach()

         self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]	)

         # test that outputs are equal for slice
         self.parent.assertTrue(torch.allclose(__A    ,__A    ,atol=1e-3	)	)







       def  __UpperCAmelCase			(     self						:						Any    ,__A						:						List[str]    ,__A						:						int    ,__A						:						List[str]    ,__A						:						List[str]    ,__A						:						List[Any]    ,*__A						:						Any    ,__A						:						Union[str, Any]=False	)    ->       Any:
         _lowercase						    =			BioGptForCausalLM(__A	)
         model.to(__A	)
         if gradient_checkpointing:
           model.gradient_checkpointing_enable()

         _lowercase						    =			model(__A    ,labels=__A	)
         self.parent.assertEqual(result.loss.shape    ,()	)
         self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.seq_length, self.vocab_size)	)
         result.loss.backward()







       def  __UpperCAmelCase			(     self						:						Tuple    ,__A						:						str    ,*__A						:						Tuple	)    ->       List[str]:
         _lowercase						    =			BioGptModel(__A	)
         _lowercase						    =			model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers	)
         for key in model.state_dict().keys():
           if "c_proj" in key and "weight" in key:
             self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]	) - model_std	)    ,0.001	)
             self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]	) - 0.0	)    ,0.01	)







       def  __UpperCAmelCase			(     self						:						List[Any]    ,__A						:						Union[str, Any]    ,__A						:						Optional[Any]    ,__A						:						Any    ,__A						:						Union[str, Any]    ,__A						:						Dict    ,*__A						:						Any	)    ->       int:
         _lowercase						    =			self.num_labels
         _lowercase						    =			BioGptForTokenClassification(__A	)
         model.to(__A	)
         model.eval()
         _lowercase						    =			model(__A    ,attention_mask=__A    ,token_type_ids=__A	)
         self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.seq_length, self.num_labels)	)







       def  __UpperCAmelCase			(     self						:						Any	)    ->       Optional[int]:
         _lowercase						    =			self.prepare_config_and_inputs()
         (
             (
             _lowercase
         )    ,		(
             _lowercase
         )    ,		(
             _lowercase
         )    ,		(
             _lowercase
         )    ,		(
             _lowercase
         )    ,		(
             _lowercase
         )    ,		(
             _lowercase
         )    ,		
         )						    =			config_and_inputs
         _lowercase						    =			{'input_ids': input_ids, 'attention_mask': input_mask}
         return config, inputs_dict





@require_torch
class 					A_					(   UpperCAmelCase       ,						UpperCAmelCase       ,						UpperCAmelCase       ,						unittest.TestCase						):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_   :			Tuple  			=	(
           (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification)
           if is_torch_available()
           else ()
       )
       SCREAMING_SNAKE_CASE_   :			Union[str, Any]  			=	(BioGptForCausalLM,) if is_torch_available() else ()
       SCREAMING_SNAKE_CASE_   :			List[Any]  			=	(
           {
               '''feature-extraction''': BioGptModel,
               '''text-classification''': BioGptForSequenceClassification,
               '''text-generation''': BioGptForCausalLM,
               '''token-classification''': BioGptForTokenClassification,
               '''zero-shot''': BioGptForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       SCREAMING_SNAKE_CASE_   :			Optional[Any]  			=	False







       def  __UpperCAmelCase			(     self						:						Optional[Any]	)    ->       Any:
         _lowercase						    =			BioGptModelTester(self	)
         _lowercase						    =			ConfigTester(self    ,config_class=__A    ,hidden_size=37	)







       def  __UpperCAmelCase			(     self						:						str	)    ->       Any:
         self.config_tester.run_common_tests()







       def  __UpperCAmelCase			(     self						:						str	)    ->       str:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__A	)







       def  __UpperCAmelCase			(     self						:						List[str]	)    ->       Optional[int]:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         for type in ["absolute", "relative_key", "relative_key_query"]:
           _lowercase						    =			type
           self.model_tester.create_and_check_model(*__A	)







       def  __UpperCAmelCase			(     self						:						List[Any]	)    ->       List[str]:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_biogpt_model_attention_mask_past(*__A	)







       def  __UpperCAmelCase			(     self						:						Any	)    ->       List[Any]:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_forward_and_backwards(*__A    ,gradient_checkpointing=__A	)







       def  __UpperCAmelCase			(     self						:						Any	)    ->       Tuple:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_biogpt_model_past_large_inputs(*__A	)







       def  __UpperCAmelCase			(     self						:						Optional[int]	)    ->       List[str]:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_biogpt_weight_initialization(*__A	)







       def  __UpperCAmelCase			(     self						:						Optional[int]	)    ->       Union[str, Any]:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_biogpt_for_token_classification(*__A	)







       @slow
       def  __UpperCAmelCase			(     self						:						Any	)    ->       Optional[int]:
         _lowercase						    =			BioGptForCausalLM.from_pretrained('microsoft/biogpt'	)
         model.to(__A	)
         _lowercase						    =			BioGptTokenizer.from_pretrained('microsoft/biogpt'	)

         _lowercase						    =			'left'

         # Define PAD Token = EOS Token = 50256
         _lowercase						    =			tokenizer.eos_token
         _lowercase						    =			model.config.eos_token_id

         # use different length sentences to test batching
         _lowercase						    =			[
             'Hello, my dog is a little',
             'Today, I',
         ]

         _lowercase						    =			tokenizer(__A    ,return_tensors='pt'    ,padding=__A	)
         _lowercase						    =			inputs['input_ids'].to(__A	)

         _lowercase						    =			model.generate(
             input_ids=__A    ,attention_mask=inputs['attention_mask'].to(__A	)    ,)

         _lowercase						    =			tokenizer(sentences[0]    ,return_tensors='pt'	).input_ids.to(__A	)
         _lowercase						    =			model.generate(input_ids=__A	)

         _lowercase						    =			inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item()
         _lowercase						    =			tokenizer(sentences[1]    ,return_tensors='pt'	).input_ids.to(__A	)
         _lowercase						    =			model.generate(input_ids=__A    ,max_length=model.config.max_length - num_paddings	)

         _lowercase						    =			tokenizer.batch_decode(__A    ,skip_special_tokens=__A	)
         _lowercase						    =			tokenizer.decode(output_non_padded[0]    ,skip_special_tokens=__A	)
         _lowercase						    =			tokenizer.decode(output_padded[0]    ,skip_special_tokens=__A	)

         _lowercase						    =			[
             'Hello, my dog is a little bit bigger than a little bit.',
             'Today, I have a good idea of how to use the information',
         ]
         self.assertListEqual(__A    ,__A	)
         self.assertListEqual(__A    ,[non_padded_sentence, padded_sentence]	)







       @slow
       def  __UpperCAmelCase			(     self						:						Optional[Any]	)    ->       Optional[Any]:
         for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _lowercase						    =			BioGptModel.from_pretrained(__A	)
           self.assertIsNotNone(__A	)







       def  __UpperCAmelCase			(     self						:						int	)    ->       int:
         _lowercase    ,		_lowercase						    =			self.model_tester.prepare_config_and_inputs_for_common()
         _lowercase						    =			3
         _lowercase						    =			input_dict['input_ids']
         _lowercase						    =			input_ids.ne(1	).to(__A	)
         _lowercase						    =			ids_tensor([self.model_tester.batch_size]    ,self.model_tester.type_sequence_label_size	)
         _lowercase						    =			BioGptForSequenceClassification(__A	)
         model.to(__A	)
         model.eval()
         _lowercase						    =			model(__A    ,attention_mask=__A    ,labels=__A	)
         self.assertEqual(result.logits.shape    ,(self.model_tester.batch_size, self.model_tester.num_labels)	)







       def  __UpperCAmelCase			(     self						:						Optional[int]	)    ->       int:
         _lowercase    ,		_lowercase						    =			self.model_tester.prepare_config_and_inputs_for_common()
         _lowercase						    =			3
         _lowercase						    =			'multi_label_classification'
         _lowercase						    =			input_dict['input_ids']
         _lowercase						    =			input_ids.ne(1	).to(__A	)
         _lowercase						    =			ids_tensor(
             [self.model_tester.batch_size, config.num_labels]    ,self.model_tester.type_sequence_label_size	).to(torch.float	)
         _lowercase						    =			BioGptForSequenceClassification(__A	)
         model.to(__A	)
         model.eval()
         _lowercase						    =			model(__A    ,attention_mask=__A    ,labels=__A	)
         self.assertEqual(result.logits.shape    ,(self.model_tester.batch_size, self.model_tester.num_labels)	)





@require_torch
class 					A_					(   unittest.TestCase						):







       """simple docstring"""





       @slow
       def  __UpperCAmelCase			(     self						:						Union[str, Any]	)    ->       Optional[Any]:
         _lowercase						    =			BioGptForCausalLM.from_pretrained('microsoft/biogpt'	)
         _lowercase						    =			torch.tensor([[2, 4805, 9, 656, 21]]	)
         _lowercase						    =			model(__A	)[0]

         _lowercase						    =			4_2384

         _lowercase						    =			torch.Size((1, 5, vocab_size)	)
         self.assertEqual(output.shape    ,__A	)

         _lowercase						    =			torch.tensor(
             [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]]	)

         self.assertTrue(torch.allclose(output[:, :3, :3]    ,__A    ,atol=1e-4	)	)







       @slow
       def  __UpperCAmelCase			(     self						:						Union[str, Any]	)    ->       List[str]:
         _lowercase						    =			BioGptTokenizer.from_pretrained('microsoft/biogpt'	)
         _lowercase						    =			BioGptForCausalLM.from_pretrained('microsoft/biogpt'	)
         model.to(__A	)

         torch.manual_seed(0	)
         _lowercase						    =			tokenizer('COVID-19 is'    ,return_tensors='pt'	).to(__A	)
         _lowercase						    =			model.generate(
             **__A    ,min_length=100    ,max_length=1024    ,num_beams=5    ,early_stopping=__A    ,)
         _lowercase						    =			tokenizer.decode(output_ids[0]    ,skip_special_tokens=__A	)

         _lowercase						    =			(
             'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the'
             ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and'
             ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),'
             ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and'
             ' more than 800,000 deaths.'
         )
         self.assertEqual(__A    ,__A	)







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''']