





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 				_a		:






				def __init__(				self	:					List[Any],				lowerCAmelCase__	:					str,				lowerCAmelCase__	:					int=1_3,				lowerCAmelCase__	:					Tuple=7,				lowerCAmelCase__	:					str=False,				lowerCAmelCase__	:					Any=True,				lowerCAmelCase__	:					str=True,				lowerCAmelCase__	:					int=True,				lowerCAmelCase__	:					List[str]=9_9,				lowerCAmelCase__	:					List[Any]=3_2,				lowerCAmelCase__	:					Optional[Any]=5,				lowerCAmelCase__	:					Optional[Any]=4,				lowerCAmelCase__	:					str=3_7,				lowerCAmelCase__	:					Optional[int]="gelu",				lowerCAmelCase__	:					Union[str, Any]=0.1,				lowerCAmelCase__	:					Union[str, Any]=0.1,				lowerCAmelCase__	:					List[str]=5_1_2,				lowerCAmelCase__	:					Tuple=1_6,				lowerCAmelCase__	:					Optional[Any]=2,				lowerCAmelCase__	:					int=0.02,				lowerCAmelCase__	:					Dict=3,				lowerCAmelCase__	:					Tuple=4,				lowerCAmelCase__	:					str=None,				lowerCAmelCase__	:					Union[str, Any]=0,				)			->   Optional[Any]:




										'''simple docstring'''



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






				def        snake_case			(				self	:					Dict							)			->   List[Any]:




										'''simple docstring'''



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

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

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

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

										_UpperCamelCase    :      Tuple						     =					self.get_config()

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






				def        snake_case			(				self	:					Tuple							)			->   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        snake_case			(				self	:					Tuple,				lowerCAmelCase__	:					Optional[Any],				lowerCAmelCase__	:					Tuple,				lowerCAmelCase__	:					Optional[int],				lowerCAmelCase__	:					Optional[Any],				lowerCAmelCase__	:					Union[str, Any],				lowerCAmelCase__	:					Union[str, Any],				lowerCAmelCase__	:					Optional[int]							)			->   List[str]:




										'''simple docstring'''



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






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




										'''simple docstring'''



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






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




										'''simple docstring'''



										_UpperCamelCase    :      Tuple						     =					DPRReader(config=lowerCamelCase__							)
										model.to(lowerCamelCase__							)
										model.eval()
										_UpperCamelCase    :      int						     =					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        snake_case			(				self	:					Any							)			->   List[str]:




										'''simple docstring'''



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




@require_torch
class 				_a		(   _a			,       _a			,       unittest.TestCase       ):
				UpperCamelCase			=					(
				    (
				        DPRContextEncoder,
				        DPRQuestionEncoder,
				        DPRReader,
				    )
				    if is_torch_available()
				    else ()
				)
				UpperCamelCase			=					{'''feature-extraction''': DPRQuestionEncoder} if is_torch_available() else {}

				UpperCamelCase			=					False
				UpperCamelCase			=					False  # why?
				UpperCamelCase			=					False
				UpperCamelCase			=					False






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




										'''simple docstring'''



										_UpperCamelCase    :      Dict						     =					DPRModelTester(self							)
										_UpperCamelCase    :      List[Any]						     =					ConfigTester(self,				config_class=lowerCamelCase__,				hidden_size=3_7							)






				def        snake_case			(				self	:					int							)			->   Tuple:




										'''simple docstring'''



										self.config_tester.run_common_tests()






				def        snake_case			(				self	:					Tuple							)			->   Tuple:




										'''simple docstring'''



										_UpperCamelCase    :      Tuple						     =					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_context_encoder(*lowerCamelCase__							)






				def        snake_case			(				self	:					Union[str, Any]							)			->   List[Any]:




										'''simple docstring'''



										_UpperCamelCase    :      Any						     =					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_question_encoder(*lowerCamelCase__							)






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




										'''simple docstring'''



										_UpperCamelCase    :      Dict						     =					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_reader(*lowerCamelCase__							)






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




										'''simple docstring'''



										_UpperCamelCase    :      Union[str, Any]						     =					self.model_tester.prepare_config_and_inputs()[0]

										_UpperCamelCase    :      Union[str, Any]						     =					DPRQuestionEncoder(config=lowerCamelCase__							)
										model.to(lowerCamelCase__							)
										model.eval()

										with tempfile.TemporaryDirectory() as tmp_dirname:
																model.save_pretrained(lowerCamelCase__							)
																_UpperCamelCase    :      List[Any]						     =					DPRQuestionEncoder.from_pretrained(lowerCamelCase__,				projection_dim=5_1_2							)

										self.assertIsNotNone(lowerCamelCase__							)






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




										'''simple docstring'''



										for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																_UpperCamelCase    :      Any						     =					DPRContextEncoder.from_pretrained(lowerCamelCase__							)
																self.assertIsNotNone(lowerCamelCase__							)

										for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																_UpperCamelCase    :      Optional[Any]						     =					DPRContextEncoder.from_pretrained(lowerCamelCase__							)
																self.assertIsNotNone(lowerCamelCase__							)

										for model_name in DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																_UpperCamelCase    :      int						     =					DPRQuestionEncoder.from_pretrained(lowerCamelCase__							)
																self.assertIsNotNone(lowerCamelCase__							)

										for model_name in DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																_UpperCamelCase    :      Optional[Any]						     =					DPRReader.from_pretrained(lowerCamelCase__							)
																self.assertIsNotNone(lowerCamelCase__							)




@require_torch
class 				_a		(   unittest.TestCase       ):






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




										'''simple docstring'''



										_UpperCamelCase    :      Any						     =					DPRQuestionEncoder.from_pretrained('''facebook/dpr-question_encoder-single-nq-base''',				return_dict=lowerCamelCase__							)
										model.to(lowerCamelCase__							)

										_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=lowerCamelCase__							)  # [CLS] hello, is my dog cute? [SEP]
										_UpperCamelCase    :      Optional[int]						     =					model(lowerCamelCase__							)[0]  # embedding shape = (1, 768)
										# compare the actual values for a slice.
										_UpperCamelCase    :      Dict						     =					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[:, :1_0],				lowerCamelCase__,				atol=1e-4							)							)






				@slow
				def        snake_case			(				self	:					List[str]							)			->   List[str]:




										'''simple docstring'''



										_UpperCamelCase    :      List[str]						     =					DPRReaderTokenizer.from_pretrained('''facebook/dpr-reader-single-nq-base'''							)
										_UpperCamelCase    :      Dict						     =					DPRReader.from_pretrained('''facebook/dpr-reader-single-nq-base'''							)
										model.to(lowerCamelCase__							)

										_UpperCamelCase    :      str						     =					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__							)

										_UpperCamelCase    :      List[str]						     =					model(**lowerCamelCase__							)

										# compare the actual values for a slice.
										_UpperCamelCase    :      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__,				)

										_UpperCamelCase    :      List[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[:, :1_0],				lowerCamelCase__,				atol=1e-4							)							)
										self.assertTrue(torch.allclose(outputs.end_logits[:, :1_0],				lowerCamelCase__,				atol=1e-4							)							)










"""simple docstring"""




def  a_       (							_lowercase ,		_lowercase ,		_lowercase ,		_lowercase     ):
						return len_board * len_board_column * row + column





def  a_       (							_lowercase ,		_lowercase ,		_lowercase ,		_lowercase ,		_lowercase ,		_lowercase ,		):

						if board[row][column] != word[word_index]:
												return False

						if word_index == len(_lowercase     ) - 1:
												return True

						_UpperCamelCase    :      Union[str, Any]						     =					[(0, 1), (0, -1), (-1, 0), (1, 0)]
						_UpperCamelCase    :      List[str]						     =					len(_lowercase     )
						_UpperCamelCase    :      Optional[Any]						     =					len(board[0]     )
						for direction in traverts_directions:
												_UpperCamelCase    :      Union[str, Any]						     =					row + direction[0]
												_UpperCamelCase    :      List[Any]						     =					column + direction[1]
												if not (0 <= next_i < len_board and 0 <= next_j < len_board_column):
																		continue

												_UpperCamelCase    :      Optional[Any]						     =					get_point_key(_lowercase ,		_lowercase ,		_lowercase ,		_lowercase     )
												if key in visited_points_set:
																		continue

												visited_points_set.add(_lowercase     )
												if exits_word(_lowercase ,		_lowercase ,		_lowercase ,		_lowercase ,		word_index + 1 ,		_lowercase     ):
																		return True

												visited_points_set.remove(_lowercase     )

						return False





def  a_       (							_lowercase ,		_lowercase     ):
						_UpperCamelCase    :      Optional[Any]						     =					(
						    '''The board should be a non empty matrix of single chars strings.'''
						)

						_UpperCamelCase    :      int						     =					len(_lowercase     )
						if not isinstance(_lowercase ,		_lowercase     ) or len(_lowercase     ) == 0:
												raise ValueError(_lowercase     )

						for row in board:
												if not isinstance(_lowercase ,		_lowercase     ) or len(_lowercase     ) == 0:
																		raise ValueError(_lowercase     )

												for item in row:
																		if not isinstance(_lowercase ,		_lowercase     ) or len(_lowercase     ) != 1:
																								raise ValueError(_lowercase     )

    # Validate word
						if not isinstance(_lowercase ,		_lowercase     ) or len(_lowercase     ) == 0:
												raise ValueError(
												    '''The word parameter should be a string of length greater than 0.'''     )

						_UpperCamelCase    :      List[str]						     =					len(board[0]     )
						for i in range(_lowercase     ):
												for j in range(_lowercase     ):
																		if exits_word(
																		    _lowercase ,		_lowercase ,		_lowercase ,		_lowercase ,		0 ,		{get_point_key(_lowercase ,		_lowercase ,		_lowercase ,		_lowercase     )}     ):
																								return True

						return False


if __name__ == "__main__":
						import doctest

						doctest.testmod()



