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






			def __init__(self     :  List[Any]			,SCREAMING_SNAKE_CASE_     :  str			,SCREAMING_SNAKE_CASE_     :  List[str]=13			,SCREAMING_SNAKE_CASE_     :  str=7			,SCREAMING_SNAKE_CASE_     :  Dict=False			,SCREAMING_SNAKE_CASE_     :  Optional[int]=True			,SCREAMING_SNAKE_CASE_     :  Dict=True			,SCREAMING_SNAKE_CASE_     :  int=True			,SCREAMING_SNAKE_CASE_     :  Union[str, Any]=99			,SCREAMING_SNAKE_CASE_     :  Union[str, Any]=32			,SCREAMING_SNAKE_CASE_     :  List[str]=5			,SCREAMING_SNAKE_CASE_     :  List[Any]=4			,SCREAMING_SNAKE_CASE_     :  List[str]=37			,SCREAMING_SNAKE_CASE_     :  List[str]="gelu"			,SCREAMING_SNAKE_CASE_     :  Any=0.1			,SCREAMING_SNAKE_CASE_     :  Union[str, Any]=0.1			,SCREAMING_SNAKE_CASE_     :  List[str]=512			,SCREAMING_SNAKE_CASE_     :  Any=16			,SCREAMING_SNAKE_CASE_     :  List[str]=2			,SCREAMING_SNAKE_CASE_     :  List[Any]=0.02			,SCREAMING_SNAKE_CASE_     :  int=3			,SCREAMING_SNAKE_CASE_     :  Union[str, Any]=4			,SCREAMING_SNAKE_CASE_     :  List[Any]=None			,SCREAMING_SNAKE_CASE_     :  str=0			,)					->  int:





				"""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 				UpperCAmelCase       (self     :  Optional[Any] )					->  Union[str, Any]:





				"""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 				UpperCAmelCase       (self     :  Optional[int] )					->  Optional[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 				UpperCAmelCase       (self     :  Optional[Any]			,SCREAMING_SNAKE_CASE_     :  Union[str, Any]			,SCREAMING_SNAKE_CASE_     :  Optional[int]			,SCREAMING_SNAKE_CASE_     :  Any			,SCREAMING_SNAKE_CASE_     :  int			,SCREAMING_SNAKE_CASE_     :  List[Any]			,SCREAMING_SNAKE_CASE_     :  List[str]			,SCREAMING_SNAKE_CASE_     :  List[str] )					->  int:





				"""simple docstring"""


				lowerCAmelCase				       =     DPRContextEncoder(config=SCREAMING_SNAKE_CASE_ )
				model.to(SCREAMING_SNAKE_CASE_ )
				model.eval()
				lowerCAmelCase				       =     model(SCREAMING_SNAKE_CASE_			,attention_mask=SCREAMING_SNAKE_CASE_			,token_type_ids=SCREAMING_SNAKE_CASE_ )
				lowerCAmelCase				       =     model(SCREAMING_SNAKE_CASE_			,token_type_ids=SCREAMING_SNAKE_CASE_ )
				lowerCAmelCase				       =     model(SCREAMING_SNAKE_CASE_ )
				self.parent.assertEqual(result.pooler_output.shape			,(self.batch_size, self.projection_dim or self.hidden_size) )






			def 				UpperCAmelCase       (self     :  Union[str, Any]			,SCREAMING_SNAKE_CASE_     :  List[str]			,SCREAMING_SNAKE_CASE_     :  int			,SCREAMING_SNAKE_CASE_     :  Optional[int]			,SCREAMING_SNAKE_CASE_     :  Optional[int]			,SCREAMING_SNAKE_CASE_     :  int			,SCREAMING_SNAKE_CASE_     :  int			,SCREAMING_SNAKE_CASE_     :  Tuple )					->  Tuple:





				"""simple docstring"""


				lowerCAmelCase				       =     DPRQuestionEncoder(config=SCREAMING_SNAKE_CASE_ )
				model.to(SCREAMING_SNAKE_CASE_ )
				model.eval()
				lowerCAmelCase				       =     model(SCREAMING_SNAKE_CASE_			,attention_mask=SCREAMING_SNAKE_CASE_			,token_type_ids=SCREAMING_SNAKE_CASE_ )
				lowerCAmelCase				       =     model(SCREAMING_SNAKE_CASE_			,token_type_ids=SCREAMING_SNAKE_CASE_ )
				lowerCAmelCase				       =     model(SCREAMING_SNAKE_CASE_ )
				self.parent.assertEqual(result.pooler_output.shape			,(self.batch_size, self.projection_dim or self.hidden_size) )






			def 				UpperCAmelCase       (self     :  Union[str, Any]			,SCREAMING_SNAKE_CASE_     :  Dict			,SCREAMING_SNAKE_CASE_     :  Tuple			,SCREAMING_SNAKE_CASE_     :  Optional[int]			,SCREAMING_SNAKE_CASE_     :  Dict			,SCREAMING_SNAKE_CASE_     :  int			,SCREAMING_SNAKE_CASE_     :  int			,SCREAMING_SNAKE_CASE_     :  Optional[int] )					->  Dict:





				"""simple docstring"""


				lowerCAmelCase				       =     DPRReader(config=SCREAMING_SNAKE_CASE_ )
				model.to(SCREAMING_SNAKE_CASE_ )
				model.eval()
				lowerCAmelCase				       =     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 				UpperCAmelCase       (self     :  Tuple )					->  Optional[int]:





				"""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  lowercase				(   lowercase__      ,lowercase__      ,unittest.TestCase		):
			lowercase			     =    (
			    (
			        DPRContextEncoder,
			        DPRQuestionEncoder,
			        DPRReader,
			    )
			    if is_torch_available()
			    else ()
			)
			lowercase			     =    {'''feature-extraction''': DPRQuestionEncoder} if is_torch_available() else {}

			lowercase			     =    False
			lowercase			     =    False  # why?
			lowercase			     =    False
			lowercase			     =    False






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





				"""simple docstring"""


				lowerCAmelCase				       =     DPRModelTester(self )
				lowerCAmelCase				       =     ConfigTester(self			,config_class=SCREAMING_SNAKE_CASE_			,hidden_size=37 )






			def 				UpperCAmelCase       (self     :  Union[str, Any] )					->  Optional[Any]:





				"""simple docstring"""


				self.config_tester.run_common_tests()






			def 				UpperCAmelCase       (self     :  Tuple )					->  Optional[int]:





				"""simple docstring"""


				lowerCAmelCase				       =     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_context_encoder(*SCREAMING_SNAKE_CASE_ )






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





				"""simple docstring"""


				lowerCAmelCase				       =     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_question_encoder(*SCREAMING_SNAKE_CASE_ )






			def 				UpperCAmelCase       (self     :  Optional[int] )					->  Optional[int]:





				"""simple docstring"""


				lowerCAmelCase				       =     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_reader(*SCREAMING_SNAKE_CASE_ )






			def 				UpperCAmelCase       (self     :  List[str] )					->  Any:





				"""simple docstring"""


				lowerCAmelCase				       =     self.model_tester.prepare_config_and_inputs()[0]

				lowerCAmelCase				       =     DPRQuestionEncoder(config=SCREAMING_SNAKE_CASE_ )
				model.to(SCREAMING_SNAKE_CASE_ )
				model.eval()

				with tempfile.TemporaryDirectory() as tmp_dirname:
					model.save_pretrained(SCREAMING_SNAKE_CASE_ )
					lowerCAmelCase				       =     DPRQuestionEncoder.from_pretrained(SCREAMING_SNAKE_CASE_			,projection_dim=512 )

				self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )






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





				"""simple docstring"""


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

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

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

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





@require_torch
class  lowercase				(   unittest.TestCase		):






			@slow
			def 				UpperCAmelCase       (self     :  Optional[int] )					->  Any:





				"""simple docstring"""


				lowerCAmelCase				       =     DPRQuestionEncoder.from_pretrained('''facebook/dpr-question_encoder-single-nq-base'''			,return_dict=SCREAMING_SNAKE_CASE_ )
				model.to(SCREAMING_SNAKE_CASE_ )

				lowerCAmelCase				       =     torch.tensor(
				    [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]]			,dtype=torch.long			,device=SCREAMING_SNAKE_CASE_ )  # [CLS] hello, is my dog cute? [SEP]
				lowerCAmelCase				       =     model(SCREAMING_SNAKE_CASE_ )[0]  # embedding shape = (1, 768)
				# compare the actual values for a slice.
				lowerCAmelCase				       =     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=SCREAMING_SNAKE_CASE_			,)
				self.assertTrue(torch.allclose(output[:, :10]			,SCREAMING_SNAKE_CASE_			,atol=1e-4 ) )






			@slow
			def 				UpperCAmelCase       (self     :  Optional[int] )					->  Union[str, Any]:





				"""simple docstring"""


				lowerCAmelCase				       =     DPRReaderTokenizer.from_pretrained('''facebook/dpr-reader-single-nq-base''' )
				lowerCAmelCase				       =     DPRReader.from_pretrained('''facebook/dpr-reader-single-nq-base''' )
				model.to(SCREAMING_SNAKE_CASE_ )

				lowerCAmelCase				       =     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_ )

				lowerCAmelCase				       =     model(**SCREAMING_SNAKE_CASE_ )

				# compare the actual values for a slice.
				lowerCAmelCase				       =     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=SCREAMING_SNAKE_CASE_			,)

				lowerCAmelCase				       =     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=SCREAMING_SNAKE_CASE_			,)
				self.assertTrue(torch.allclose(outputs.start_logits[:, :10]			,SCREAMING_SNAKE_CASE_			,atol=1e-4 ) )
				self.assertTrue(torch.allclose(outputs.end_logits[:, :10]			,SCREAMING_SNAKE_CASE_			,atol=1e-4 ) )




"""simple docstring"""






from __future__ import annotations

from typing import Generic, TypeVar

UpperCAmelCase          =							TypeVar("""T""")



class  lowercase				(   lowercase__		):
			pass





class  lowercase				(   lowercase__		):
			pass





class  lowercase				(   Generic[T]		):






			def __init__(self     :  Any			,SCREAMING_SNAKE_CASE_     :  int = 10 )					->  Any:





				"""simple docstring"""


				lowerCAmelCase				       =     []
				lowerCAmelCase				       =     limit






			def __bool__(self     :  List[Any] )					->  bool:





				"""simple docstring"""


				return bool(self.stack )






			def __str__(self     :  Any )					->  str:





				"""simple docstring"""


				return str(self.stack )






			def 				UpperCAmelCase       (self     :  Optional[Any]			,SCREAMING_SNAKE_CASE_     :  T )					->  None:





				"""simple docstring"""


				if len(self.stack ) >= self.limit:
					raise StackOverflowError
				self.stack.append(SCREAMING_SNAKE_CASE_ )






			def 				UpperCAmelCase       (self     :  Tuple )					->  T:





				"""simple docstring"""


				if not self.stack:
					raise StackUnderflowError
				return self.stack.pop()






			def 				UpperCAmelCase       (self     :  int )					->  T:





				"""simple docstring"""


				if not self.stack:
					raise StackUnderflowError
				return self.stack[-1]






			def 				UpperCAmelCase       (self     :  Any )					->  bool:





				"""simple docstring"""


				return not bool(self.stack )






			def 				UpperCAmelCase       (self     :  Optional[Any] )					->  bool:





				"""simple docstring"""


				return self.size() == self.limit






			def 				UpperCAmelCase       (self     :  Tuple )					->  int:





				"""simple docstring"""


				return len(self.stack )






			def __contains__(self     :  List[str]			,SCREAMING_SNAKE_CASE_     :  T )					->  bool:





				"""simple docstring"""


				return item in self.stack





def __magic_name__  (							)				->	None:

	'''simple docstring'''




	lowerCAmelCase				       =     Stack(10 )
	assert bool(_lowerCamelCase ) is False
	assert stack.is_empty() is True
	assert stack.is_full() is False
	assert str(_lowerCamelCase ) == "[]"

	try:
		lowerCAmelCase				       =     stack.pop()
		raise AssertionError  # This should not happen
	except StackUnderflowError:
		assert True  # This should happen

	try:
		lowerCAmelCase				       =     stack.peek()
		raise AssertionError  # This should not happen
	except StackUnderflowError:
		assert True  # This should happen

	for i in range(10 ):
		assert stack.size() == i
		stack.push(_lowerCamelCase )

	assert bool(_lowerCamelCase )
	assert not stack.is_empty()
	assert stack.is_full()
	assert str(_lowerCamelCase ) == str(list(range(10 ) ) )
	assert stack.pop() == 9
	assert stack.peek() == 8

	stack.push(100 )
	assert str(_lowerCamelCase ) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100] )

	try:
		stack.push(200 )
		raise AssertionError  # This should not happen
	except StackOverflowError:
		assert True  # This should happen

	assert not stack.is_empty()
	assert stack.size() == 10

	assert 5 in stack
	assert 55 not in stack


if __name__ == "__main__":
					test_stack()


