






"""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    :





    def __init__(				self      :   List[Any]							,						A      :   Tuple							,						A      :   List[Any]=1_3							,						A      :   Optional[Any]=7							,						A      :   Optional[int]=False							,						A      :   Optional[int]=True							,						A      :   Tuple=True							,						A      :   Optional[Any]=True							,						A      :   int=9_9							,						A      :   int=3_2							,						A      :   Dict=5							,						A      :   Any=4							,						A      :   Union[str, Any]=3_7							,						A      :   Optional[int]="gelu"							,						A      :   int=0.1							,						A      :   Union[str, Any]=0.1							,						A      :   Tuple=5_1_2							,						A      :   Tuple=1_6							,						A      :   Union[str, Any]=2							,						A      :   int=0.02							,						A      :   Any=3							,						A      :   List[Any]=4							,						A      :   List[str]=None							,						A      :   Dict=0							,						):


      '''simple docstring'''




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





    def 							lowerCamelCase__ (				self      :   List[str]     ):


      '''simple docstring'''




      a	:     Union[str, Any]							=  ids_tensor([self.batch_size, self.seq_length]							,						self.vocab_size     )

      a	:     List[Any]							=  None
      if self.use_input_mask:
        a	:     Any							=  random_attention_mask([self.batch_size, self.seq_length]     )

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

      a	:     Tuple							=  None
      a	:     Optional[int]							=  None
      a	:     str							=  None
      if self.use_labels:
        a	:     Dict							=  ids_tensor([self.batch_size]							,						self.type_sequence_label_size     )
        a	:     List[Any]							=  ids_tensor([self.batch_size, self.seq_length]							,						self.num_labels     )
        a	:     Union[str, Any]							=  ids_tensor([self.batch_size]							,						self.num_choices     )

      a	:     Optional[Any]							=  self.get_config()

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





    def 							lowerCamelCase__ (				self      :   Any     ):


      '''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 							lowerCamelCase__ (				self      :   List[Any]							,						A      :   List[str]							,						A      :   Dict							,						A      :   Optional[int]							,						A      :   Any							,						A      :   int							,						A      :   Tuple							,						A      :   int     ):


      '''simple docstring'''




      a	:     Dict							=  DPRContextEncoder(config=A     )
      model.to(A     )
      model.eval()
      a	:     List[str]							=  model(A							,						attention_mask=A							,						token_type_ids=A     )
      a	:     Optional[Any]							=  model(A							,						token_type_ids=A     )
      a	:     Union[str, Any]							=  model(A     )
      self.parent.assertEqual(result.pooler_output.shape							,						(self.batch_size, self.projection_dim or self.hidden_size)     )





    def 							lowerCamelCase__ (				self      :   Any							,						A      :   Dict							,						A      :   int							,						A      :   Dict							,						A      :   List[str]							,						A      :   List[str]							,						A      :   Dict							,						A      :   Optional[int]     ):


      '''simple docstring'''




      a	:     Optional[Any]							=  DPRQuestionEncoder(config=A     )
      model.to(A     )
      model.eval()
      a	:     List[str]							=  model(A							,						attention_mask=A							,						token_type_ids=A     )
      a	:     int							=  model(A							,						token_type_ids=A     )
      a	:     str							=  model(A     )
      self.parent.assertEqual(result.pooler_output.shape							,						(self.batch_size, self.projection_dim or self.hidden_size)     )





    def 							lowerCamelCase__ (				self      :   int							,						A      :   int							,						A      :   str							,						A      :   str							,						A      :   List[Any]							,						A      :   Optional[Any]							,						A      :   List[Any]							,						A      :   Tuple     ):


      '''simple docstring'''




      a	:     List[str]							=  DPRReader(config=A     )
      model.to(A     )
      model.eval()
      a	:     List[str]							=  model(
          A							,						attention_mask=A							,						)

      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 							lowerCamelCase__ (				self      :   List[str]     ):


      '''simple docstring'''




      a	:     Dict							=  self.prepare_config_and_inputs()
      (
          (
          a
      ),	(
          a
      ),	(
          a
      ),	(
          a
      ),	(
          a
      ),	(
          a
      ),	(
          a
      ),	
      )	:     int							=  config_and_inputs
      a	:     Optional[int]							=  {'input_ids': input_ids}
      return config, inputs_dict






@require_torch
class 		snake_case    (    UpperCAmelCase  ,					UpperCAmelCase  ,					unittest.TestCase			):
    __magic_name__       	=	(
        (
            DPRContextEncoder,
            DPRQuestionEncoder,
            DPRReader,
        )
        if is_torch_available()
        else ()
    )
    __magic_name__       	=	{'''feature-extraction''': DPRQuestionEncoder} if is_torch_available() else {}

    __magic_name__       	=	False
    __magic_name__       	=	False  # why?
    __magic_name__       	=	False
    __magic_name__       	=	False





    def 							lowerCamelCase__ (				self      :   Tuple     ):


      '''simple docstring'''




      a	:     Optional[Any]							=  DPRModelTester(self     )
      a	:     List[str]							=  ConfigTester(self							,						config_class=A							,						hidden_size=3_7     )





    def 							lowerCamelCase__ (				self      :   Optional[int]     ):


      '''simple docstring'''




      self.config_tester.run_common_tests()





    def 							lowerCamelCase__ (				self      :   Union[str, Any]     ):


      '''simple docstring'''




      a	:     Dict							=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_context_encoder(*A     )





    def 							lowerCamelCase__ (				self      :   Union[str, Any]     ):


      '''simple docstring'''




      a	:     List[str]							=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_question_encoder(*A     )





    def 							lowerCamelCase__ (				self      :   str     ):


      '''simple docstring'''




      a	:     List[Any]							=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_reader(*A     )





    def 							lowerCamelCase__ (				self      :   Optional[int]     ):


      '''simple docstring'''




      a	:     List[Any]							=  self.model_tester.prepare_config_and_inputs()[0]

      a	:     List[str]							=  DPRQuestionEncoder(config=A     )
      model.to(A     )
      model.eval()

      with tempfile.TemporaryDirectory() as tmp_dirname:
        model.save_pretrained(A     )
        a	:     int							=  DPRQuestionEncoder.from_pretrained(A							,						projection_dim=5_1_2     )

      self.assertIsNotNone(A     )





    @slow
    def 							lowerCamelCase__ (				self      :   Dict     ):


      '''simple docstring'''




      for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a	:     Dict							=  DPRContextEncoder.from_pretrained(A     )
        self.assertIsNotNone(A     )

      for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a	:     List[str]							=  DPRContextEncoder.from_pretrained(A     )
        self.assertIsNotNone(A     )

      for model_name in DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a	:     Dict							=  DPRQuestionEncoder.from_pretrained(A     )
        self.assertIsNotNone(A     )

      for model_name in DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a	:     str							=  DPRReader.from_pretrained(A     )
        self.assertIsNotNone(A     )






@require_torch
class 		snake_case    (    unittest.TestCase			):





    @slow
    def 							lowerCamelCase__ (				self      :   List[str]     ):


      '''simple docstring'''




      a	:     Optional[Any]							=  DPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base'							,						return_dict=A     )
      model.to(A     )

      a	:     Any							=  torch.tensor(
          [[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_0_3, 2_0_2_6, 3_8_9_9, 1_0_1_4_0, 1_0_2_9, 1_0_2]]							,						dtype=torch.long							,						device=A     )  # [CLS] hello, is my dog cute? [SEP]
      a	:     str							=  model(A     )[0]  # embedding shape = (1, 768)
      # compare the actual values for a slice.
      a	:     int							=  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=A							,						)
      self.assertTrue(torch.allclose(output[:, :1_0]							,						A							,						atol=1E-4     )     )





    @slow
    def 							lowerCamelCase__ (				self      :   Any     ):


      '''simple docstring'''




      a	:     Union[str, Any]							=  DPRReaderTokenizer.from_pretrained('facebook/dpr-reader-single-nq-base'     )
      a	:     int							=  DPRReader.from_pretrained('facebook/dpr-reader-single-nq-base'     )
      model.to(A     )

      a	:     Union[str, Any]							=  tokenizer(
          questions='What is love ?'							,						titles='Haddaway'							,						texts='What Is Love is a song recorded by the artist Haddaway'							,						padding=A							,						return_tensors='pt'							,						)
      encoded_inputs.to(A     )

      a	:     Optional[Any]							=  model(**A     )

      # compare the actual values for a slice.
      a	:     Union[str, Any]							=  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=A							,						)

      a	:     List[str]							=  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=A							,						)
      self.assertTrue(torch.allclose(outputs.start_logits[:, :1_0]							,						A							,						atol=1E-4     )     )
      self.assertTrue(torch.allclose(outputs.end_logits[:, :1_0]							,						A							,						atol=1E-4     )     )












"""simple docstring"""


from __future__ import annotations




def      snake_case    (A_ :list[int | float]      ,     A_ :int      ,     A_ :int ):







  '''simple docstring'''

  if len(A_ ) == 0:
    raise ValueError('find_min() arg is an empty sequence' )
  if (
      left >= len(A_ )
      or left < -len(A_ )
      or right >= len(A_ )
      or right < -len(A_ )
  ):
    raise IndexError('list index out of range' )
  if left == right:
    return nums[left]
  a	:     Optional[Any]							=  (left + right) >> 1  # the middle
  a	:     List[str]							=  find_min(A_      ,     A_      ,     A_ )  # find min in range[left, mid]
  a	:     Union[str, Any]							=  find_min(A_      ,     mid + 1      ,     A_ )  # find min in range[mid + 1, right]

  return left_min if left_min <= right_min else right_min


if __name__ == "__main__":
   import doctest

   doctest.testmod(verbose=True)




