"""simple docstring"""







import tempfile
import unittest

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

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 DPRContextEncoder, DPRQuestionEncoder, DPRReader, DPRReaderTokenizer
       from transformers.models.dpr.modeling_dpr import (
           DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
           DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
           DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
       )






class 							__snake_case:


    '''simple docstring'''





    def __init__(  self					,       __lowerCamelCase					,       __lowerCamelCase=13					,       __lowerCamelCase=7					,       __lowerCamelCase=False					,       __lowerCamelCase=True					,       __lowerCamelCase=True					,       __lowerCamelCase=True					,       __lowerCamelCase=99					,       __lowerCamelCase=32					,       __lowerCamelCase=5					,       __lowerCamelCase=4					,       __lowerCamelCase=37					,       __lowerCamelCase="gelu"					,       __lowerCamelCase=0.1					,       __lowerCamelCase=0.1					,       __lowerCamelCase=512					,       __lowerCamelCase=16					,       __lowerCamelCase=2					,       __lowerCamelCase=0.02					,       __lowerCamelCase=3					,       __lowerCamelCase=4					,       __lowerCamelCase=None					,       __lowerCamelCase=0					,       ):




         '''simple docstring'''



         __A					:					Any								=		parent
         __A					:					List[str]								=		batch_size
         __A					:					Optional[int]								=		seq_length
         __A					:					Union[str, Any]								=		is_training
         __A					:					str								=		use_input_mask
         __A					:					Dict								=		use_token_type_ids
         __A					:					Union[str, Any]								=		use_labels
         __A					:					Optional[Any]								=		vocab_size
         __A					:					str								=		hidden_size
         __A					:					Union[str, Any]								=		num_hidden_layers
         __A					:					Tuple								=		num_attention_heads
         __A					:					Optional[int]								=		intermediate_size
         __A					:					Optional[int]								=		hidden_act
         __A					:					List[str]								=		hidden_dropout_prob
         __A					:					Any								=		attention_probs_dropout_prob
         __A					:					int								=		max_position_embeddings
         __A					:					Tuple								=		type_vocab_size
         __A					:					Any								=		type_sequence_label_size
         __A					:					Dict								=		initializer_range
         __A					:					Tuple								=		num_labels
         __A					:					Optional[int]								=		num_choices
         __A					:					Dict								=		scope
         __A					:					List[Any]								=		projection_dim
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					List[Any]								=		ids_tensor([self.batch_size, self.seq_length]					,       self.vocab_size	)

         __A					:					Union[str, Any]								=		None
         if self.use_input_mask:
              __A					:					Union[str, Any]								=		random_attention_mask([self.batch_size, self.seq_length]	)

         __A					:					List[Any]								=		None
         if self.use_token_type_ids:
              __A					:					Union[str, Any]								=		ids_tensor([self.batch_size, self.seq_length]					,       self.type_vocab_size	)

         __A					:					Dict								=		None
         __A					:					int								=		None
         __A					:					List[Any]								=		None
         if self.use_labels:
              __A					:					List[Any]								=		ids_tensor([self.batch_size]					,       self.type_sequence_label_size	)
              __A					:					Dict								=		ids_tensor([self.batch_size, self.seq_length]					,       self.num_labels	)
              __A					:					int								=		ids_tensor([self.batch_size]					,       self.num_choices	)

         __A					:					List[Any]								=		self.get_config()

         return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
    def 						_a							(  self	):




         '''simple docstring'''



         return DPRConfig(
             projection_dim=self.projection_dim					,       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					,       initializer_range=self.initializer_range					,       )
    def 						_a							(  self					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	):




         '''simple docstring'''



         __A					:					List[str]								=		DPRContextEncoder(config=__lowerCamelCase	)
         model.to(__lowerCamelCase	)
         model.eval()
         __A					:					List[Any]								=		model(__lowerCamelCase					,       attention_mask=__lowerCamelCase					,       token_type_ids=__lowerCamelCase	)
         __A					:					Tuple								=		model(__lowerCamelCase					,       token_type_ids=__lowerCamelCase	)
         __A					:					Tuple								=		model(__lowerCamelCase	)
         self.parent.assertEqual(result.pooler_output.shape					,       (self.batch_size, self.projection_dim or self.hidden_size)	)
    def 						_a							(  self					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	):




         '''simple docstring'''



         __A					:					Tuple								=		DPRQuestionEncoder(config=__lowerCamelCase	)
         model.to(__lowerCamelCase	)
         model.eval()
         __A					:					int								=		model(__lowerCamelCase					,       attention_mask=__lowerCamelCase					,       token_type_ids=__lowerCamelCase	)
         __A					:					Any								=		model(__lowerCamelCase					,       token_type_ids=__lowerCamelCase	)
         __A					:					List[str]								=		model(__lowerCamelCase	)
         self.parent.assertEqual(result.pooler_output.shape					,       (self.batch_size, self.projection_dim or self.hidden_size)	)
    def 						_a							(  self					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	):




         '''simple docstring'''



         __A					:					Union[str, Any]								=		DPRReader(config=__lowerCamelCase	)
         model.to(__lowerCamelCase	)
         model.eval()
         __A					:					int								=		model(
             __lowerCamelCase					,       attention_mask=__lowerCamelCase					,       )

         self.parent.assertEqual(result.start_logits.shape					,       (self.batch_size, self.seq_length)	)
         self.parent.assertEqual(result.end_logits.shape					,       (self.batch_size, self.seq_length)	)
         self.parent.assertEqual(result.relevance_logits.shape					,       (self.batch_size,)	)

    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Union[str, Any]								=		self.prepare_config_and_inputs()
         (
             (
             __A
         )						,		(
             __A
         )						,		(
             __A
         )						,		(
             __A
         )						,		(
             __A
         )						,		(
             __A
         )						,		(
             __A
         )						,		
         )					:					Union[str, Any]								=		config_and_inputs
         __A					:					Union[str, Any]								=		{'input_ids': input_ids}
         return config, inputs_dict







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


    '''simple docstring'''





    _UpperCAmelCase       =			(
        (
            DPRContextEncoder,
            DPRQuestionEncoder,
            DPRReader,
        )
        if is_torch_available()
        else ()
    )
    _UpperCAmelCase       =			{"feature-extraction": DPRQuestionEncoder} if is_torch_available() else {}

    _UpperCAmelCase       =			False
    _UpperCAmelCase       =			False  # why?
    _UpperCAmelCase       =			False
    _UpperCAmelCase       =			False
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Optional[Any]								=		DPRModelTester(self	)
         __A					:					List[Any]								=		ConfigTester(self					,       config_class=__lowerCamelCase					,       hidden_size=37	)
    def 						_a							(  self	):




         '''simple docstring'''



         self.config_tester.run_common_tests()
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Optional[int]								=		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_context_encoder(*__lowerCamelCase	)
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					List[Any]								=		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_question_encoder(*__lowerCamelCase	)
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					int								=		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_reader(*__lowerCamelCase	)
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Optional[int]								=		self.model_tester.prepare_config_and_inputs()[0]

         __A					:					List[str]								=		DPRQuestionEncoder(config=__lowerCamelCase	)
         model.to(__lowerCamelCase	)
         model.eval()

         with tempfile.TemporaryDirectory() as tmp_dirname:
              model.save_pretrained(__lowerCamelCase	)
              __A					:					Tuple								=		DPRQuestionEncoder.from_pretrained(__lowerCamelCase					,       projection_dim=512	)

         self.assertIsNotNone(__lowerCamelCase	)

    @slow
    def 						_a							(  self	):




         '''simple docstring'''



         for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __A					:					Optional[Any]								=		DPRContextEncoder.from_pretrained(__lowerCamelCase	)
              self.assertIsNotNone(__lowerCamelCase	)

         for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __A					:					Optional[Any]								=		DPRContextEncoder.from_pretrained(__lowerCamelCase	)
              self.assertIsNotNone(__lowerCamelCase	)

         for model_name in DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __A					:					Tuple								=		DPRQuestionEncoder.from_pretrained(__lowerCamelCase	)
              self.assertIsNotNone(__lowerCamelCase	)

         for model_name in DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __A					:					List[Any]								=		DPRReader.from_pretrained(__lowerCamelCase	)
              self.assertIsNotNone(__lowerCamelCase	)







@require_torch
class 							__snake_case(					unittest.TestCase	):


    '''simple docstring'''





    @slow
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Union[str, Any]								=		DPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base'					,       return_dict=__lowerCamelCase	)
         model.to(__lowerCamelCase	)

         __A					:					Optional[int]								=		torch.tensor(
             [[101, 7592, 1010, 2003, 2026, 3899, 10140, 1029, 102]]					,       dtype=torch.long					,       device=__lowerCamelCase	)  # [CLS] hello, is my dog cute? [SEP]
         __A					:					Union[str, Any]								=		model(__lowerCamelCase	)[0]  # embedding shape = (1, 768)
         # compare the actual values for a slice.
         __A					:					Tuple								=		torch.tensor(
             [
                 [
                     0.03_23_62_53,
                     0.12_75_33_35,
                     0.16_81_85_09,
                     0.00_27_97_86,
                     0.3_89_69_33,
                     0.24_26_49_45,
                     0.2_17_89_71,
                     -0.02_33_52_27,
                     -0.08_48_19_59,
                     -0.14_32_41_17,
                 ]
             ]					,       dtype=torch.float					,       device=__lowerCamelCase					,       )
         self.assertTrue(torch.allclose(output[:, :10]					,       __lowerCamelCase					,       atol=1e-4	)	)

    @slow
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					int								=		DPRReaderTokenizer.from_pretrained('facebook/dpr-reader-single-nq-base'	)
         __A					:					Any								=		DPRReader.from_pretrained('facebook/dpr-reader-single-nq-base'	)
         model.to(__lowerCamelCase	)

         __A					:					int								=		tokenizer(
             questions='What is love ?'					,       titles='Haddaway'					,       texts='What Is Love is a song recorded by the artist Haddaway'					,       padding=__lowerCamelCase					,       return_tensors='pt'					,       )
         encoded_inputs.to(__lowerCamelCase	)

         __A					:					Any								=		model(**__lowerCamelCase	)

         # compare the actual values for a slice.
         __A					:					List[str]								=		torch.tensor(
             [[-10.30_05, -10.77_65, -11.48_72, -11.68_41, -11.93_12, -10.30_02, -9.85_44, -11.73_78, -12.08_21, -10.29_75]]					,       dtype=torch.float					,       device=__lowerCamelCase					,       )

         __A					:					Union[str, Any]								=		torch.tensor(
             [[-11.06_84, -11.70_41, -11.53_97, -10.34_65, -10.87_91, -6.84_43, -11.99_59, -11.03_64, -10.00_96, -6.84_05]]					,       dtype=torch.float					,       device=__lowerCamelCase					,       )
         self.assertTrue(torch.allclose(outputs.start_logits[:, :10]					,       __lowerCamelCase					,       atol=1e-4	)	)
         self.assertTrue(torch.allclose(outputs.end_logits[:, :10]					,       __lowerCamelCase					,       atol=1e-4	)	)




"""simple docstring"""







def 						_lowercase				(  _SCREAMING_SNAKE_CASE				:				list[int]						)    ->     tuple[int, int]:







     '''simple docstring'''


     if len(_SCREAMING_SNAKE_CASE						) == 1:
          return a[0], a[0]
     else:
          # split A into half.
          __A					:					List[str]								=		a[: len(_SCREAMING_SNAKE_CASE						) // 2]
          __A					:					Optional[Any]								=		a[len(_SCREAMING_SNAKE_CASE						) // 2 :]

          # 2 sub problems, 1/2 of original size.
          __A						,		__A					:					int								=		max_difference(_SCREAMING_SNAKE_CASE						)
          __A						,		__A					:					str								=		max_difference(_SCREAMING_SNAKE_CASE						)

          # get min of first and max of second
          # linear time
          __A					:					str								=		min(_SCREAMING_SNAKE_CASE						)
          __A					:					Optional[int]								=		max(_SCREAMING_SNAKE_CASE						)

          # 3 cases, either (small1, big1),
          # (min_first, max_second), (small2, big2)
          # constant comparisons
          if biga - smalla > max_second - min_first and biga - smalla > biga - smalla:
               return smalla, biga
          elif biga - smalla > max_second - min_first:
               return smalla, biga
          else:
               return min_first, max_second


if __name__ == "__main__":
       import doctest

       doctest.testmod()



