

'''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   UpperCamelCase__   :


		"""simple docstring"""

		def __init__(			self   ,      snake_case   ,      snake_case=1_3   ,      snake_case=7   ,      snake_case=False   ,      snake_case=True   ,      snake_case=True   ,      snake_case=True   ,      snake_case=9_9   ,      snake_case=3_2   ,      snake_case=5   ,      snake_case=4   ,      snake_case=3_7   ,      snake_case="gelu"   ,      snake_case=0.1   ,      snake_case=0.1   ,      snake_case=5_1_2   ,      snake_case=1_6   ,      snake_case=2   ,      snake_case=0.02   ,      snake_case=3   ,      snake_case=4   ,      snake_case=None   ,      snake_case=0   ,      ):


							'''simple docstring'''

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







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							Dict        =       ids_tensor([self.batch_size, self.seq_length]   ,      self.vocab_size      )

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

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

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

							UpperCAmelCase		:							List[str]        =       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   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

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







		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

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







		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							int        =       DPRReader(config=__SCREAMING_SNAKE_CASE      )
							model.to(__SCREAMING_SNAKE_CASE      )
							model.eval()
							UpperCAmelCase		:							int        =       model(
							    __SCREAMING_SNAKE_CASE   ,      attention_mask=__SCREAMING_SNAKE_CASE   ,      )

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

							UpperCAmelCase		:							List[Any]        =       self.prepare_config_and_inputs()
							(
							    (
							    UpperCAmelCase      
							) ,			(
							    UpperCAmelCase      
							) ,			(
							    UpperCAmelCase      
							) ,			(
							    UpperCAmelCase      
							) ,			(
							    UpperCAmelCase      
							) ,			(
							    UpperCAmelCase      
							) ,			(
							    UpperCAmelCase      
							) ,			      
							)		:							Tuple        =       config_and_inputs
							UpperCAmelCase		:							int        =       {"input_ids": input_ids}
							return config, inputs_dict







@require_torch
class   UpperCamelCase__   (       __lowerCAmelCase							,							__lowerCAmelCase							,							unittest.TestCase       ):


		"""simple docstring"""

		SCREAMING_SNAKE_CASE__  :     Optional[int]       =							(
		    (
		        DPRContextEncoder,
		        DPRQuestionEncoder,
		        DPRReader,
		    )
		    if is_torch_available()
		    else ()
		)
		SCREAMING_SNAKE_CASE__  :     Optional[Any]       =							{'''feature-extraction''': DPRQuestionEncoder} if is_torch_available() else {}

		SCREAMING_SNAKE_CASE__  :     Optional[Any]       =							False
		SCREAMING_SNAKE_CASE__  :     List[str]       =							False  # why?
		SCREAMING_SNAKE_CASE__  :     Optional[Any]       =							False
		SCREAMING_SNAKE_CASE__  :     Dict       =							False







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							Optional[int]        =       DPRModelTester(self      )
							UpperCAmelCase		:							Tuple        =       ConfigTester(self   ,      config_class=__SCREAMING_SNAKE_CASE   ,      hidden_size=3_7      )







		def 				A_	(			self      ):


							'''simple docstring'''

							self.config_tester.run_common_tests()







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							Tuple        =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_context_encoder(*__SCREAMING_SNAKE_CASE      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]        =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_question_encoder(*__SCREAMING_SNAKE_CASE      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							Union[str, Any]        =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_reader(*__SCREAMING_SNAKE_CASE      )







		def 				A_	(			self      ):


							'''simple docstring'''

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

							UpperCAmelCase		:							Dict        =       DPRQuestionEncoder(config=__SCREAMING_SNAKE_CASE      )
							model.to(__SCREAMING_SNAKE_CASE      )
							model.eval()

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

							self.assertIsNotNone(__SCREAMING_SNAKE_CASE      )







		@slow
		def 				A_	(			self      ):


							'''simple docstring'''

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

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

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

							for model_name in DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												UpperCAmelCase		:							Dict        =       DPRReader.from_pretrained(__SCREAMING_SNAKE_CASE      )
												self.assertIsNotNone(__SCREAMING_SNAKE_CASE      )







@require_torch
class   UpperCamelCase__   (       unittest.TestCase       ):


		"""simple docstring"""

		@slow
		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							str        =       DPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base"   ,      return_dict=__SCREAMING_SNAKE_CASE      )
							model.to(__SCREAMING_SNAKE_CASE      )

							UpperCAmelCase		:							List[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=__SCREAMING_SNAKE_CASE      )  # [CLS] hello, is my dog cute? [SEP]
							UpperCAmelCase		:							Tuple        =       model(__SCREAMING_SNAKE_CASE      )[0]  # embedding shape = (1, 768)
							# compare the actual values for a slice.
							UpperCAmelCase		:							List[Any]        =       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=__SCREAMING_SNAKE_CASE   ,      )
							self.assertTrue(torch.allclose(output[:, :1_0]   ,      __SCREAMING_SNAKE_CASE   ,      atol=1e-4      )      )







		@slow
		def 				A_	(			self      ):


							'''simple docstring'''

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

							UpperCAmelCase		:							List[str]        =       tokenizer(
							    questions="What is love ?"   ,      titles="Haddaway"   ,      texts="What Is Love is a song recorded by the artist Haddaway"   ,      padding=__SCREAMING_SNAKE_CASE   ,      return_tensors="pt"   ,      )
							encoded_inputs.to(__SCREAMING_SNAKE_CASE      )

							UpperCAmelCase		:							Union[str, Any]        =       model(**__SCREAMING_SNAKE_CASE      )

							# compare the actual values for a slice.
							UpperCAmelCase		:							int        =       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=__SCREAMING_SNAKE_CASE   ,      )

							UpperCAmelCase		:							Optional[int]        =       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=__SCREAMING_SNAKE_CASE   ,      )
							self.assertTrue(torch.allclose(outputs.start_logits[:, :1_0]   ,      __SCREAMING_SNAKE_CASE   ,      atol=1e-4      )      )
							self.assertTrue(torch.allclose(outputs.end_logits[:, :1_0]   ,      __SCREAMING_SNAKE_CASE   ,      atol=1e-4      )      )



'''simple docstring'''

from ..utils import DummyObject, requires_backends







class   UpperCamelCase__   (       metaclass=lowercase__       ):


		"""simple docstring"""

		SCREAMING_SNAKE_CASE__  :     List[Any]       =							["torch", "transformers", "invisible_watermark"]







		def __init__(			self   ,      *snake_case   ,      **snake_case      ):


							'''simple docstring'''

							requires_backends(self   ,      ["torch", "transformers", "invisible_watermark"]      )







		@classmethod
		def 				A_	(			cls   ,      *snake_case   ,      **snake_case      ):


							'''simple docstring'''

							requires_backends(cls   ,      ["torch", "transformers", "invisible_watermark"]      )







		@classmethod
		def 				A_	(			cls   ,      *snake_case   ,      **snake_case      ):


							'''simple docstring'''

							requires_backends(cls   ,      ["torch", "transformers", "invisible_watermark"]      )







class   UpperCamelCase__   (       metaclass=lowercase__       ):


		"""simple docstring"""

		SCREAMING_SNAKE_CASE__  :     int       =							["torch", "transformers", "invisible_watermark"]







		def __init__(			self   ,      *snake_case   ,      **snake_case      ):


							'''simple docstring'''

							requires_backends(self   ,      ["torch", "transformers", "invisible_watermark"]      )







		@classmethod
		def 				A_	(			cls   ,      *snake_case   ,      **snake_case      ):


							'''simple docstring'''

							requires_backends(cls   ,      ["torch", "transformers", "invisible_watermark"]      )







		@classmethod
		def 				A_	(			cls   ,      *snake_case   ,      **snake_case      ):


							'''simple docstring'''

							requires_backends(cls   ,      ["torch", "transformers", "invisible_watermark"]      )
