



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							:     int			,						lowerCAmelCase							:     List[Any]			,						lowerCAmelCase							:     Optional[Any]=13			,						lowerCAmelCase							:     Any=7			,						lowerCAmelCase							:     str=False			,						lowerCAmelCase							:     Union[str, Any]=True			,						lowerCAmelCase							:     Dict=True			,						lowerCAmelCase							:     str=True			,						lowerCAmelCase							:     List[str]=99			,						lowerCAmelCase							:     Optional[Any]=32			,						lowerCAmelCase							:     Any=5			,						lowerCAmelCase							:     Union[str, Any]=4			,						lowerCAmelCase							:     Optional[Any]=37			,						lowerCAmelCase							:     Optional[Any]="gelu"			,						lowerCAmelCase							:     Union[str, Any]=0.1			,						lowerCAmelCase							:     Optional[Any]=0.1			,						lowerCAmelCase							:     Optional[int]=512			,						lowerCAmelCase							:     Tuple=16			,						lowerCAmelCase							:     Dict=2			,						lowerCAmelCase							:     Optional[int]=0.02			,						lowerCAmelCase							:     Tuple=3			,						lowerCAmelCase							:     Tuple=4			,						lowerCAmelCase							:     List[Any]=None			,						lowerCAmelCase							:     Optional[Any]=0			,						)			->			Dict:

    """simple docstring"""







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

   def        UpperCamelCase_					(   self							:     List[Any])			->			List[Any]:

    """simple docstring"""







    _snake_case      :					int					=   ids_tensor([self.batch_size, self.seq_length]			,						self.vocab_size)

    _snake_case      :					Optional[int]					=   None
    if self.use_input_mask:
     _snake_case      :					Optional[int]					=   random_attention_mask([self.batch_size, self.seq_length])

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

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

    _snake_case      :					str					=   self.get_config()

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

   def        UpperCamelCase_					(   self							:     List[str])			->			Tuple:

    """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        UpperCamelCase_					(   self							:     Optional[int]			,						lowerCAmelCase							:     Optional[Any]			,						lowerCAmelCase							:     List[Any]			,						lowerCAmelCase							:     int			,						lowerCAmelCase							:     Dict			,						lowerCAmelCase							:     Optional[int]			,						lowerCAmelCase							:     List[Any]			,						lowerCAmelCase							:     Any)			->			List[str]:

    """simple docstring"""







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

   def        UpperCamelCase_					(   self							:     Dict			,						lowerCAmelCase							:     List[Any]			,						lowerCAmelCase							:     Union[str, Any]			,						lowerCAmelCase							:     List[Any]			,						lowerCAmelCase							:     Dict			,						lowerCAmelCase							:     str			,						lowerCAmelCase							:     Tuple			,						lowerCAmelCase							:     Optional[Any])			->			Tuple:

    """simple docstring"""







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

   def        UpperCamelCase_					(   self							:     List[str]			,						lowerCAmelCase							:     Tuple			,						lowerCAmelCase							:     Dict			,						lowerCAmelCase							:     List[Any]			,						lowerCAmelCase							:     Optional[Any]			,						lowerCAmelCase							:     str			,						lowerCAmelCase							:     Optional[Any]			,						lowerCAmelCase							:     int)			->			Any:

    """simple docstring"""







    _snake_case      :					Dict					=   DPRReader(config=lowerCAmelCase)
    model.to(lowerCAmelCase)
    model.eval()
    _snake_case      :					Tuple					=   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        UpperCamelCase_					(   self							:     Any)			->			Tuple:

    """simple docstring"""







    _snake_case      :					Dict					=   self.prepare_config_and_inputs()
    (
        (
        _snake_case
    )		,      (
        _snake_case
    )		,      (
        _snake_case
    )		,      (
        _snake_case
    )		,      (
        _snake_case
    )		,      (
        _snake_case
    )		,      (
        _snake_case
    )		,      
    )      :					Tuple					=   config_and_inputs
    _snake_case      :					int					=   {"""input_ids""": input_ids}
    return config, inputs_dict







@require_torch
class 						snake_case  (		SCREAMING_SNAKE_CASE_   ,SCREAMING_SNAKE_CASE_   ,unittest.TestCase					):



   '''simple docstring'''






   snake_case_   :	List[str]       =						(
       (
           DPRContextEncoder,
           DPRQuestionEncoder,
           DPRReader,
       )
       if is_torch_available()
       else ()
   )
   snake_case_   :	Optional[int]       =						{"""feature-extraction""": DPRQuestionEncoder} if is_torch_available() else {}

   snake_case_   :	Dict       =						False
   snake_case_   :	Optional[Any]       =						False  # why?
   snake_case_   :	int       =						False
   snake_case_   :	int       =						False

   def        UpperCamelCase_					(   self							:     Tuple)			->			Dict:

    """simple docstring"""







    _snake_case      :					Any					=   DPRModelTester(self)
    _snake_case      :					Union[str, Any]					=   ConfigTester(self			,						config_class=lowerCAmelCase			,						hidden_size=37)

   def        UpperCamelCase_					(   self							:     List[str])			->			List[str]:

    """simple docstring"""







    self.config_tester.run_common_tests()

   def        UpperCamelCase_					(   self							:     Any)			->			Tuple:

    """simple docstring"""







    _snake_case      :					str					=   self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_context_encoder(*lowerCAmelCase)

   def        UpperCamelCase_					(   self							:     Optional[Any])			->			str:

    """simple docstring"""







    _snake_case      :					List[Any]					=   self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_question_encoder(*lowerCAmelCase)

   def        UpperCamelCase_					(   self							:     Dict)			->			Union[str, Any]:

    """simple docstring"""







    _snake_case      :					List[Any]					=   self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_reader(*lowerCAmelCase)

   def        UpperCamelCase_					(   self							:     List[str])			->			int:

    """simple docstring"""







    _snake_case      :					Dict					=   self.model_tester.prepare_config_and_inputs()[0]

    _snake_case      :					Optional[Any]					=   DPRQuestionEncoder(config=lowerCAmelCase)
    model.to(lowerCAmelCase)
    model.eval()

    with tempfile.TemporaryDirectory() as tmp_dirname:
     model.save_pretrained(lowerCAmelCase)
     _snake_case      :					Optional[int]					=   DPRQuestionEncoder.from_pretrained(lowerCAmelCase			,						projection_dim=512)

    self.assertIsNotNone(lowerCAmelCase)


   @slow
   def        UpperCamelCase_					(   self							:     Tuple)			->			str:

    """simple docstring"""







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

    for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     _snake_case      :					str					=   DPRContextEncoder.from_pretrained(lowerCAmelCase)
     self.assertIsNotNone(lowerCAmelCase)

    for model_name in DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     _snake_case      :					List[str]					=   DPRQuestionEncoder.from_pretrained(lowerCAmelCase)
     self.assertIsNotNone(lowerCAmelCase)

    for model_name in DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     _snake_case      :					Tuple					=   DPRReader.from_pretrained(lowerCAmelCase)
     self.assertIsNotNone(lowerCAmelCase)







@require_torch
class 						snake_case  (		unittest.TestCase					):



   '''simple docstring'''






   @slow
   def        UpperCamelCase_					(   self							:     Tuple)			->			Dict:

    """simple docstring"""







    _snake_case      :					List[str]					=   DPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base"""			,						return_dict=lowerCAmelCase)
    model.to(lowerCAmelCase)

    _snake_case      :					Optional[Any]					=   torch.tensor(
        [[101, 7592, 1010, 2003, 2026, 3899, 1_0140, 1029, 102]]			,						dtype=torch.long			,						device=lowerCAmelCase)  # [CLS] hello, is my dog cute? [SEP]
    _snake_case      :					Optional[Any]					=   model(lowerCAmelCase)[0]  # embedding shape = (1, 768)
    # compare the actual values for a slice.
    _snake_case      :					List[Any]					=   torch.tensor(
        [
            [
                0.03_236_253,
                0.12_753_335,
                0.16_818_509,
                0.00_279_786,
                0.3_896_933,
                0.24_264_945,
                0.2_178_971,
                -0.02_335_227,
                -0.08_481_959,
                -0.14_324_117,
            ]
        ]			,						dtype=torch.float			,						device=lowerCAmelCase			,						)
    self.assertTrue(torch.allclose(output[:, :10]			,						lowerCAmelCase			,						atol=1E-4))


   @slow
   def        UpperCamelCase_					(   self							:     Union[str, Any])			->			List[Any]:

    """simple docstring"""







    _snake_case      :					List[str]					=   DPRReaderTokenizer.from_pretrained("""facebook/dpr-reader-single-nq-base""")
    _snake_case      :					str					=   DPRReader.from_pretrained("""facebook/dpr-reader-single-nq-base""")
    model.to(lowerCAmelCase)

    _snake_case      :					Dict					=   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)

    _snake_case      :					Union[str, Any]					=   model(**lowerCAmelCase)

    # compare the actual values for a slice.
    _snake_case      :					int					=   torch.tensor(
        [[-10.3_005, -10.7_765, -11.4_872, -11.6_841, -11.9_312, -10.3_002, -9.8_544, -11.7_378, -12.0_821, -10.2_975]]			,						dtype=torch.float			,						device=lowerCAmelCase			,						)

    _snake_case      :					Union[str, Any]					=   torch.tensor(
        [[-11.0_684, -11.7_041, -11.5_397, -10.3_465, -10.8_791, -6.8_443, -11.9_959, -11.0_364, -10.0_096, -6.8_405]]			,						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))





def  lowercase    (				SCREAMING_SNAKE_CASE__    :		float			,    SCREAMING_SNAKE_CASE__    :		float			)					->       float:
 _snake_case      :					str					=   float()
 try:
  _snake_case      :					str					=   mass * acceleration
 except Exception:
  return -0.0
 return force


if __name__ == "__main__":
  import doctest

  # run doctest
  doctest.testmod()

  # demo
  a__      =		12.5
  a__      =		10
  a__      =		newtons_second_law_of_motion(mass, acceleration)
  print("""The force is """, force, """N""")
