





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






						'''simple docstring'''







						UpperCAmelCase_		    =  parent
						UpperCAmelCase_		    =  batch_size
						UpperCAmelCase_		    =  seq_length
						UpperCAmelCase_		    =  is_training
						UpperCAmelCase_		    =  use_input_mask
						UpperCAmelCase_		    =  use_token_type_ids
						UpperCAmelCase_		    =  use_labels
						UpperCAmelCase_		    =  vocab_size
						UpperCAmelCase_		    =  hidden_size
						UpperCAmelCase_		    =  num_hidden_layers
						UpperCAmelCase_		    =  num_attention_heads
						UpperCAmelCase_		    =  intermediate_size
						UpperCAmelCase_		    =  hidden_act
						UpperCAmelCase_		    =  hidden_dropout_prob
						UpperCAmelCase_		    =  attention_probs_dropout_prob
						UpperCAmelCase_		    =  max_position_embeddings
						UpperCAmelCase_		    =  type_vocab_size
						UpperCAmelCase_		    =  type_sequence_label_size
						UpperCAmelCase_		    =  initializer_range
						UpperCAmelCase_		    =  num_labels
						UpperCAmelCase_		    =  num_choices
						UpperCAmelCase_		    =  scope
						UpperCAmelCase_		    =  projection_dim





					def 							SCREAMING_SNAKE_CASE				(    self     :	List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_		    =  ids_tensor([self.batch_size, self.seq_length]			,       self.vocab_size		)

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

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

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

						UpperCAmelCase_		    =  self.get_config()

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





					def 							SCREAMING_SNAKE_CASE				(    self     :	List[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 							SCREAMING_SNAKE_CASE				(    self     :	Tuple			,       __lowercase     :	str			,       __lowercase     :	Any			,       __lowercase     :	int			,       __lowercase     :	Optional[Any]			,       __lowercase     :	int			,       __lowercase     :	Dict			,       __lowercase     :	Tuple		):






						'''simple docstring'''







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





					def 							SCREAMING_SNAKE_CASE				(    self     :	List[str]			,       __lowercase     :	Tuple			,       __lowercase     :	Tuple			,       __lowercase     :	Dict			,       __lowercase     :	str			,       __lowercase     :	Tuple			,       __lowercase     :	Optional[Any]			,       __lowercase     :	int		):






						'''simple docstring'''







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





					def 							SCREAMING_SNAKE_CASE				(    self     :	Union[str, Any]			,       __lowercase     :	Dict			,       __lowercase     :	List[str]			,       __lowercase     :	Union[str, Any]			,       __lowercase     :	Optional[int]			,       __lowercase     :	str			,       __lowercase     :	int			,       __lowercase     :	str		):






						'''simple docstring'''







						UpperCAmelCase_		    =  DPRReader(config=__lowercase		)
						model.to(__lowercase		)
						model.eval()
						UpperCAmelCase_		    =  model(
						    __lowercase			,       attention_mask=__lowercase			,       )

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






						'''simple docstring'''







						UpperCAmelCase_		    =  self.prepare_config_and_inputs()
						(
						    (
						    UpperCAmelCase_
						)    ,						(
						    UpperCAmelCase_
						)    ,						(
						    UpperCAmelCase_
						)    ,						(
						    UpperCAmelCase_
						)    ,						(
						    UpperCAmelCase_
						)    ,						(
						    UpperCAmelCase_
						)    ,						(
						    UpperCAmelCase_
						)    ,						
						)		    =  config_and_inputs
						UpperCAmelCase_		    =  {"""input_ids""": input_ids}
						return config, inputs_dict







@require_torch
class 	_UpperCamelCase	(							A_    ,							A_    ,							unittest.TestCase	):







					'''simple docstring'''

					lowerCamelCase  :  Any           =							(
					    (
					        DPRContextEncoder,
					        DPRQuestionEncoder,
					        DPRReader,
					    )
					    if is_torch_available()
					    else ()
					)
					lowerCamelCase  :  Tuple           =							{'feature-extraction': DPRQuestionEncoder} if is_torch_available() else {}

					lowerCamelCase  :  Union[str, Any]           =							False
					lowerCamelCase  :  Optional[int]           =							False  # why?
					lowerCamelCase  :  List[Any]           =							False
					lowerCamelCase  :  Optional[int]           =							False





					def 							SCREAMING_SNAKE_CASE				(    self     :	str		):






						'''simple docstring'''







						UpperCAmelCase_		    =  DPRModelTester(self		)
						UpperCAmelCase_		    =  ConfigTester(self			,       config_class=__lowercase			,       hidden_size=37		)





					def 							SCREAMING_SNAKE_CASE				(    self     :	List[Any]		):






						'''simple docstring'''







						self.config_tester.run_common_tests()





					def 							SCREAMING_SNAKE_CASE				(    self     :	List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_		    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_context_encoder(*__lowercase		)





					def 							SCREAMING_SNAKE_CASE				(    self     :	Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_		    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_question_encoder(*__lowercase		)





					def 							SCREAMING_SNAKE_CASE				(    self     :	Optional[int]		):






						'''simple docstring'''







						UpperCAmelCase_		    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_reader(*__lowercase		)





					def 							SCREAMING_SNAKE_CASE				(    self     :	List[str]		):






						'''simple docstring'''







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

						UpperCAmelCase_		    =  DPRQuestionEncoder(config=__lowercase		)
						model.to(__lowercase		)
						model.eval()

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

						self.assertIsNotNone(__lowercase		)





					@slow
					def 							SCREAMING_SNAKE_CASE				(    self     :	int		):






						'''simple docstring'''







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

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

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

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







@require_torch
class 	_UpperCamelCase	(							unittest.TestCase	):







					'''simple docstring'''

					@slow
					def 							SCREAMING_SNAKE_CASE				(    self     :	Optional[int]		):






						'''simple docstring'''







						UpperCAmelCase_		    =  DPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base"""			,       return_dict=__lowercase		)
						model.to(__lowercase		)

						UpperCAmelCase_		    =  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=__lowercase		)  # [CLS] hello, is my dog cute? [SEP]
						UpperCAmelCase_		    =  model(__lowercase		)[0]  # embedding shape = (1, 768)
						# compare the actual values for a slice.
						UpperCAmelCase_		    =  torch.tensor(
						    [
						        [
						            0.03236253,
						            0.12753335,
						            0.16818509,
						            0.00279786,
						            0.3896933,
						            0.24264945,
						            0.2178971,
						            -0.02335227,
						            -0.08481959,
						            -0.14324117,
						        ]
						    ]			,       dtype=torch.float			,       device=__lowercase			,       )
						self.assertTrue(torch.allclose(output[:, :10]			,       __lowercase			,       atol=1e-4		)		)





					@slow
					def 							SCREAMING_SNAKE_CASE				(    self     :	Tuple		):






						'''simple docstring'''







						UpperCAmelCase_		    =  DPRReaderTokenizer.from_pretrained("""facebook/dpr-reader-single-nq-base"""		)
						UpperCAmelCase_		    =  DPRReader.from_pretrained("""facebook/dpr-reader-single-nq-base"""		)
						model.to(__lowercase		)

						UpperCAmelCase_		    =  tokenizer(
						    questions="""What is love ?"""			,       titles="""Haddaway"""			,       texts="""What Is Love is a song recorded by the artist Haddaway"""			,       padding=__lowercase			,       return_tensors="""pt"""			,       )
						encoded_inputs.to(__lowercase		)

						UpperCAmelCase_		    =  model(**__lowercase		)

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

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









import doctest

import projectq
from projectq.ops import H, Measure




def  A_(      A ):
	UpperCAmelCase_		    =  quantum_engine.allocate_qubit()
	H | qubit
	Measure | qubit
	return int(A )


if __name__ == "__main__":
				doctest.testmod()

				# initialises a new quantum backend
				UpperCamelCase__ :			Dict       	=			projectq.MainEngine()

				# Generate a list of 10 random numbers
				UpperCamelCase__ :			Dict       	=			[get_random_number(quantum_engine) for _ in range(10)]

				# Flushes the quantum engine from memory
				quantum_engine.flush()

				print("""Random numbers""", random_numbers_list)


