




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



       """simple docstring"""
       lowerCAmelCase__								=			parent
       lowerCAmelCase__								=			batch_size
       lowerCAmelCase__								=			seq_length
       lowerCAmelCase__								=			is_training
       lowerCAmelCase__								=			use_input_mask
       lowerCAmelCase__								=			use_token_type_ids
       lowerCAmelCase__								=			use_labels
       lowerCAmelCase__								=			vocab_size
       lowerCAmelCase__								=			hidden_size
       lowerCAmelCase__								=			num_hidden_layers
       lowerCAmelCase__								=			num_attention_heads
       lowerCAmelCase__								=			intermediate_size
       lowerCAmelCase__								=			hidden_act
       lowerCAmelCase__								=			hidden_dropout_prob
       lowerCAmelCase__								=			attention_probs_dropout_prob
       lowerCAmelCase__								=			max_position_embeddings
       lowerCAmelCase__								=			type_vocab_size
       lowerCAmelCase__								=			type_sequence_label_size
       lowerCAmelCase__								=			initializer_range
       lowerCAmelCase__								=			num_labels
       lowerCAmelCase__								=			num_choices
       lowerCAmelCase__								=			scope
       lowerCAmelCase__								=			projection_dim
     def 					A__			(	self  :		Optional[int]	):



       """simple docstring"""
       lowerCAmelCase__								=			ids_tensor([self.batch_size, self.seq_length]					,	self.vocab_size	)

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

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

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

       lowerCAmelCase__								=			self.get_config()

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



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



       """simple docstring"""
       lowerCAmelCase__								=			DPRContextEncoder(config=__lowerCamelCase	)
       model.to(__lowerCamelCase	)
       model.eval()
       lowerCAmelCase__								=			model(__lowerCamelCase					,	attention_mask=__lowerCamelCase					,	token_type_ids=__lowerCamelCase	)
       lowerCAmelCase__								=			model(__lowerCamelCase					,	token_type_ids=__lowerCamelCase	)
       lowerCAmelCase__								=			model(__lowerCamelCase	)
       self.parent.assertEqual(result.pooler_output.shape					,	(self.batch_size, self.projection_dim or self.hidden_size)	)
     def 					A__			(	self  :		Dict					,	__lowerCamelCase  :		List[Any]					,	__lowerCamelCase  :		List[str]					,	__lowerCamelCase  :		Optional[int]					,	__lowerCamelCase  :		Tuple					,	__lowerCamelCase  :		Any					,	__lowerCamelCase  :		Optional[int]					,	__lowerCamelCase  :		Tuple	):



       """simple docstring"""
       lowerCAmelCase__								=			DPRQuestionEncoder(config=__lowerCamelCase	)
       model.to(__lowerCamelCase	)
       model.eval()
       lowerCAmelCase__								=			model(__lowerCamelCase					,	attention_mask=__lowerCamelCase					,	token_type_ids=__lowerCamelCase	)
       lowerCAmelCase__								=			model(__lowerCamelCase					,	token_type_ids=__lowerCamelCase	)
       lowerCAmelCase__								=			model(__lowerCamelCase	)
       self.parent.assertEqual(result.pooler_output.shape					,	(self.batch_size, self.projection_dim or self.hidden_size)	)
     def 					A__			(	self  :		Optional[int]					,	__lowerCamelCase  :		List[str]					,	__lowerCamelCase  :		List[Any]					,	__lowerCamelCase  :		Union[str, Any]					,	__lowerCamelCase  :		Optional[int]					,	__lowerCamelCase  :		Optional[Any]					,	__lowerCamelCase  :		int					,	__lowerCamelCase  :		Optional[int]	):



       """simple docstring"""
       lowerCAmelCase__								=			DPRReader(config=__lowerCamelCase	)
       model.to(__lowerCamelCase	)
       model.eval()
       lowerCAmelCase__								=			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  :		Union[str, Any]	):



       """simple docstring"""
       lowerCAmelCase__								=			self.prepare_config_and_inputs()
       (
           (
           lowerCAmelCase__
       )							,			(
           lowerCAmelCase__
       )							,			(
           lowerCAmelCase__
       )							,			(
           lowerCAmelCase__
       )							,			(
           lowerCAmelCase__
       )							,			(
           lowerCAmelCase__
       )							,			(
           lowerCAmelCase__
       )							,			
       )								=			config_and_inputs
       lowerCAmelCase__								=			{'''input_ids''': input_ids}
       return config, inputs_dict





@require_torch
class 						SCREAMING_SNAKE_CASE__		(_a						,				_a						,				unittest.TestCase ):
     lowercase_   :			Tuple   =   (
         (
             DPRContextEncoder,
             DPRQuestionEncoder,
             DPRReader,
         )
         if is_torch_available()
         else ()
     )
     lowercase_   :			str   =   {"feature-extraction": DPRQuestionEncoder} if is_torch_available() else {}

     lowercase_   :			Tuple   =   False
     lowercase_   :			str   =   False  # why?
     lowercase_   :			Optional[Any]   =   False
     lowercase_   :			Optional[Any]   =   False
     def 					A__			(	self  :		int	):



       """simple docstring"""
       lowerCAmelCase__								=			DPRModelTester(self	)
       lowerCAmelCase__								=			ConfigTester(self					,	config_class=__lowerCamelCase					,	hidden_size=37	)
     def 					A__			(	self  :		Optional[int]	):



       """simple docstring"""
       self.config_tester.run_common_tests()
     def 					A__			(	self  :		Optional[Any]	):



       """simple docstring"""
       lowerCAmelCase__								=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_context_encoder(*__lowerCamelCase	)
     def 					A__			(	self  :		Union[str, Any]	):



       """simple docstring"""
       lowerCAmelCase__								=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_question_encoder(*__lowerCamelCase	)
     def 					A__			(	self  :		Union[str, Any]	):



       """simple docstring"""
       lowerCAmelCase__								=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_reader(*__lowerCamelCase	)
     def 					A__			(	self  :		Union[str, Any]	):



       """simple docstring"""
       lowerCAmelCase__								=			self.model_tester.prepare_config_and_inputs()[0]

       lowerCAmelCase__								=			DPRQuestionEncoder(config=__lowerCamelCase	)
       model.to(__lowerCamelCase	)
       model.eval()

       with tempfile.TemporaryDirectory() as tmp_dirname:
         model.save_pretrained(__lowerCamelCase	)
         lowerCAmelCase__								=			DPRQuestionEncoder.from_pretrained(__lowerCamelCase					,	projection_dim=5_12	)

       self.assertIsNotNone(__lowerCamelCase	)



     @slow
     def 					A__			(	self  :		str	):



       """simple docstring"""
       for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         lowerCAmelCase__								=			DPRContextEncoder.from_pretrained(__lowerCamelCase	)
         self.assertIsNotNone(__lowerCamelCase	)

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

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

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





@require_torch
class 						SCREAMING_SNAKE_CASE__		(unittest.TestCase ):
     @slow
     def 					A__			(	self  :		List[Any]	):



       """simple docstring"""
       lowerCAmelCase__								=			DPRQuestionEncoder.from_pretrained('''facebook/dpr-question_encoder-single-nq-base'''					,	return_dict=__lowerCamelCase	)
       model.to(__lowerCamelCase	)

       lowerCAmelCase__								=			torch.tensor(
           [[1_01, 75_92, 10_10, 20_03, 20_26, 38_99, 1_01_40, 10_29, 1_02]]					,	dtype=torch.long					,	device=__lowerCamelCase	)  # [CLS] hello, is my dog cute? [SEP]
       lowerCAmelCase__								=			model(__lowerCamelCase	)[0]  # embedding shape = (1, 768)
       # compare the actual values for a slice.
       lowerCAmelCase__								=			torch.tensor(
           [
               [
                   0.0323_6253,
                   0.1275_3335,
                   0.1681_8509,
                   0.0027_9786,
                   0.389_6933,
                   0.2426_4945,
                   0.217_8971,
                   -0.0233_5227,
                   -0.0848_1959,
                   -0.1432_4117,
               ]
           ]					,	dtype=torch.float					,	device=__lowerCamelCase					,	)
       self.assertTrue(torch.allclose(output[:, :10]					,	__lowerCamelCase					,	atol=1e-4	)	)



     @slow
     def 					A__			(	self  :		str	):



       """simple docstring"""
       lowerCAmelCase__								=			DPRReaderTokenizer.from_pretrained('''facebook/dpr-reader-single-nq-base'''	)
       lowerCAmelCase__								=			DPRReader.from_pretrained('''facebook/dpr-reader-single-nq-base'''	)
       model.to(__lowerCamelCase	)

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

       lowerCAmelCase__								=			model(**__lowerCamelCase	)

       # compare the actual values for a slice.
       lowerCAmelCase__								=			torch.tensor(
           [[-10.3005, -10.7765, -11.4872, -11.6841, -11.9312, -10.3002, -9.8544, -11.7378, -12.0821, -10.2975]]					,	dtype=torch.float					,	device=__lowerCamelCase					,	)

       lowerCAmelCase__								=			torch.tensor(
           [[-11.0684, -11.7041, -11.5397, -10.3465, -10.8791, -6.8443, -11.9959, -11.0364, -10.0096, -6.8405]]					,	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	)	)







__magic_name__     :     dict[str, float]  							=					{
    "kilogram": 1,
    "gram": pow(10, 3),
    "milligram": pow(10, 6),
    "metric-ton": pow(10, -3),
    "long-ton": 0.0009842073,
    "short-ton": 0.0011023122,
    "pound": 2.2046244202,
    "stone": 0.1574731728,
    "ounce": 35.273990723,
    "carrat": 50_00,
    "atomic-mass-unit": 6.022_136_652E26,
}

__magic_name__     :     dict[str, float]  							=					{
    "kilogram": 1,
    "gram": pow(10, -3),
    "milligram": pow(10, -6),
    "metric-ton": pow(10, 3),
    "long-ton": 1016.04608,
    "short-ton": 907.184,
    "pound": 0.453592,
    "stone": 6.35029,
    "ounce": 0.0283495,
    "carrat": 0.0002,
    "atomic-mass-unit": 1.660_540_199E-27,
}
def 		a_       (   __lowerCAmelCase      ,   __lowerCAmelCase      ,   __lowerCAmelCase							):
  if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART:
    lowerCAmelCase__								=			(
        F"""Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n"""
        F"""Supported values are: {', '.join(__lowerCAmelCase							)}"""
    )
    raise ValueError(__lowerCAmelCase							)
  return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_type]


if __name__ == "__main__":
      import doctest

      doctest.testmod()

